text:
// Copyright 2015 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

package org.chromium.chrome.browser.tabmodel;

import static org.chromium.base.test.util.Restriction.RESTRICTION_TYPE_LOW_END_DEVICE;
import static org.chromium.base.test.util.Restriction.RESTRICTION_TYPE_NON_LOW_END_DEVICE;

import android.test.suitebuilder.annotation.MediumTest;

import org.chromium.base.ThreadUtils;
import org.chromium.base.test.util.Feature;
import org.chromium.base.test.util.Restriction;
import org.chromium.chrome.browser.tab.ChromeTab;
import org.chromium.chrome.browser.tabmodel.TabModel.TabLaunchType;
import org.chromium.chrome.test.ChromeTabbedActivityTestBase;
import org.chromium.chrome.test.util.ChromeTabUtils;
import org.chromium.chrome.test.util.TestHttpServerClient;
import org.chromium.content_public.browser.LoadUrlParams;

import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;

/**
 * Tests for ChromeTabCreator.
 */
public class ChromeTabCreatorTest extends ChromeTabbedActivityTestBase  {
    private static final String TEST_URL =
            TestHttpServerClient.getUrl("chrome/test/data/android/about.html");

    /**
     * Verify that tabs opened in background on low-end are loaded lazily.
     */
    @Restriction(RESTRICTION_TYPE_LOW_END_DEVICE)
    @MediumTest
    @Feature({"Browser"})
    public void testCreateNewTabInBackgroundLowEnd()
            throws ExecutionException, InterruptedException {
        final ChromeTab fgTab = ChromeTab.fromTab(getActivity().getActivityTab());
        final ChromeTab bgTab = ThreadUtils.runOnUiThreadBlocking(new Callable<ChromeTab>() {
            @Override
            public ChromeTab call() {
                return getActivity().getCurrentTabCreator().createNewTab(
                        new LoadUrlParams(TEST_URL), TabLaunchType.FROM_LONGPRESS_BACKGROUND,
                        fgTab);
            }
        });

        // Verify that the background tab is not loading.
        assertFalse(bgTab.isLoading());

        // Switch tabs and verify that the tab is loaded as it gets foregrounded.
        ChromeTabUtils.waitForTabPageLoaded(bgTab, new Runnable() {
            @Override
            public void run() {
                ThreadUtils.runOnUiThreadBlocking(new Runnable() {
                    @Override
                    public void run() {
                        TabModelUtils.setIndex(getActivity().getCurrentTabModel(), indexOf(bgTab));
                    }
                });
            }
        });
        assertNotNull(bgTab.getView());
    }

    /**
     * Verify that tabs opened in background on regular devices are loaded eagerly.
     */
    @Restriction(RESTRICTION_TYPE_NON_LOW_END_DEVICE)
    @MediumTest
    @Feature({"Browser"})
    public void testCreateNewTabInBackground()
            throws ExecutionException, InterruptedException {
        final ChromeTab fgTab = ChromeTab.fromTab(getActivity().getActivityTab());
        ChromeTab bgTab = ThreadUtils.runOnUiThreadBlocking(new Callable<ChromeTab>() {
            @Override
            public ChromeTab call() {
                return getActivity().getCurrentTabCreator().createNewTab(
                        new LoadUrlParams(TEST_URL), TabLaunchType.FROM_LONGPRESS_BACKGROUND,
                        fgTab);
            }
        });

        // Verify that the background tab is loaded.
        assertNotNull(bgTab.getView());
        ChromeTabUtils.waitForTabPageLoaded(bgTab, TEST_URL);
    }

    /**
     * @return the index of the given tab in the current tab model
     */
    private int indexOf(ChromeTab tab) {
        return getActivity().getCurrentTabModel().indexOf(tab);
    }

    @Override
    public void startMainActivity() throws InterruptedException {
        startMainActivityOnBlankPage();
    }
}

redpajama_set_name: RedPajamaGithub


text:
package com.baidubce.services.billing.model.bill;

import com.baidubce.auth.BceCredentials;
import com.baidubce.model.AbstractBceRequest;

import lombok.Data;

/**
 * request model for query prepay share bill
 */
@Data
public class PrepayShareBillRequest extends AbstractBceRequest {

    /**
     * the month of bill
     */
    private String month;

    /**
     * the type of service
     */
    private String serviceType;

    /**
     * the account id you want to query
     * tips: only the master account of organization group can set the parameter to query the sub account's bill
     */
    private String queryAccountId;

    /**
     * page number
     */
    private Integer pageNo;

    /**
     * page size
     */
    private Integer pageSize;

    /**
     * Configure request credential for the request.
     *
     * @param credentials a valid instance of BceCredentials.
     * @return BindTagsRequest with credentials.
     */
    @Override
    public PrepayShareBillRequest withRequestCredentials(BceCredentials credentials) {
        this.setRequestCredentials(credentials);
        return this;
    }

}


text:
<?php

function test() {
    try {
        throw new \RuntimeException();
    } catch (\RuntimeException $ex) {
    } catch (\LogicException $ex) {
    }

    echo 'foo';
}


text: Warning = ActsAsWarnable::Warning


text:
const mongoose = require('mongoose');

const chatMessageSchema = mongoose.Schema({
  user_id: String,
  text: String,
  timestamp: Number
});

const chatRoomSchema = mongoose.Schema({
  room_id: String,
  messages: []
});

module.exports = {
  ChatMessage: mongoose.model('ChatMessage', chatMessageSchema),
  ChatRoom: mongoose.model('ChatRoom', chatRoomSchema)
};


text:
using System.Data.Entity;
namespace PredicateExtensions.Tests
{
    public class BloggingContext : DbContext
    {
        public DbSet<Blog> Blogs { get; set; }

        public DbSet<Post> Posts { get; set; }
    }
}


text:
package main

import "fmt"
import "math"

type SquareRoot struct {
  number float64
}

func NewSquareRoot(number float64) *SquareRoot {
  return &SquareRoot{number}
}

func (s SquareRoot) Number() float64 {
  return s.number
}

func (s *SquareRoot) SetNumber(number float64) {
  s.number = number
}

func (s SquareRoot) Value() float64 {
  var z float64 = s.number
  var previous float64 = 0
  var iteration int = 0

  for (math.Abs(previous-z)) > 0.000000001 {
    previous = z
    z = z - (z*z-s.number)/(2.0*z)
    iteration += 1
  }
  fmt.Printf("Found result in %d iteration\n", iteration)
  return z
}


text:
#pragma once
#ifndef __H__OCULAR_GRAPHICS_TEXTURE_RESOURCE_LOADER_PNG__H__
#define __H__OCULAR_GRAPHICS_TEXTURE_RESOURCE_LOADER_PNG__H__

#include "TextureResourceLoader.hpp"

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

/**
 * \addtogroup Ocular
 * @{
 */
namespace Ocular
{
    /**
     * \addtogroup Graphics
     * @{
     */
    namespace Graphics
    {
        /**
         * \class TextureResourceLoader_PNG
         */
        class TextureResourceLoader_PNG : public TextureResourceLoader
        {
        public:

            TextureResourceLoader_PNG();
            virtual ~TextureResourceLoader_PNG();

        protected:

            virtual bool readFile(Core::File const& file, std::vector<Core::Color>& pixels, unsigned& width, unsigned& height);

        private:
        };
    }
    /**
     * @} End of Doxygen Groups
     */
}
/**
 * @} End of Doxygen Groups
 */

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

#endif


text:
import { Component, Prop, State } from '@stencil/core';

@Component({
  tag: 'bs-alert'
})
export class BsAlert {

  @State() hidden: boolean = false;

  @Prop() color: string;

  @Prop() dismissable: boolean = false;

  render() {
    let classes = {
      alert: true
    };
    if (this.color) {
      classes['alert-' + this.color] = true;
    }
    if (this.dismissable) {
      classes['alert-dismissible'] = classes['show'] = classes['fade'] = true;
    }
    console.log(classes);

    return (
      !this.hidden &&

        {this.dismissable && <button type="button" class="close" data-dismiss="alert" aria-label="Close">
          ×
        </button>}
        <slot />

    )
  }
}


text:
using System;
using System.Collections.Generic;
using System.Runtime;
using System.Text;
using System.Text.RegularExpressions;
using System.Reflection;
using System.IO;
using System.Linq;
using Cortex.Collections;
using Cortex.LexicalAnalysis;

namespace Cortex.Symbolic
{
  public class GenericFloatingPointNumber : RegexSymbol, IComparable<GenericFloatingPointNumber>
  {
    public const string BASE_FLOATING_POINT_STRING = "((?<=[^0-9a-zA-Z])(\\+|-)?)\\d+\\.\\d+{0}";
    public string Addendum { get; set; }
    public GenericFloatingPointNumber(string name, string type, string addendum)
      : base(string.Format(BASE_FLOATING_POINT_STRING, addendum), name, type)
    {
      Addendum = addendum;
    }
    public GenericFloatingPointNumber(string name, string type)
      : this(name, type, string.Empty)
    {

    }
    public virtual int CompareTo(GenericFloatingPointNumber g)
    {
      return base.CompareTo((RegexSymbol)g);
    }
    public override object Clone()
    {
      return new GenericFloatingPointNumber(Addendum, Name);
    }
  }
}


text:
package com.weiwend.fooldelivery.utils;

public class ActivityResultCode {

	public static String INVALID_SESN="100";   //sesn过期

	public static String ACTION_PSW_MODIFY="com.weiwend.psw.modify";   //密码修改成功广播的action

	public static String ACTION_NICKNAME_MODIFY="com.weiwend.nickname.modify";   //昵称修改成功广播的action

	public static String ACTION_CHECK_VERSION="com.weiwend.check.version";   //版本检测成功广播的action

	//以下均为startActivityForResult函数的requestCode值

	public static int CODE_ADDRESS_SENDER_SELECTOR=0;   //编辑发件人

	public static int CODE_ADDRESS_RECIPIENT_SELECTOR=1;   //编辑收件人

	public static int CODE_ADDRESS_ADD=2;   //添加新地址

	public static int CODE_ADDRESS_SELECTOR=3;   //选择省市区

	public static int CODE_SCAN=4;   //扫一扫

	public static int CODE_SEND_INFO_MODIFY=5;   //修改订单信息

	public static int CODE_LOGIN=6;   //登录

	public static int CODE_IMAGE_REQUEST=7;   //打开本地相册

	public static int CODE_CAMERA_REQUEST=8;   //调用照相机

	public static int CODE_RESULT_REQUEST=9;    //照片裁剪完毕

	public static int CODE_DELIVERY_COMPANY_SELECTOR=10;   //快递公司选择

	//public static int CODE_QUICK_SELECTOR=11;

	public static int CODE_ADDRESS_MODIFY=12;    //修改地址信息

	public static int CODE_PARITY_SELECTOR=13;   //比价后的网点选择

	public static int CODE_DELIVERY_HISTORY_SELECTOR=14;  //查询历史选择

    public static int CODE_PARITY_CITY_SELECTOR=15;   //比价城市选择

	public static int CODE_USER_REGISTER=16;   //用户注册

	public static int CODE_PSW_MODIFY=17;    //登录密码修改

}


text:
<?php

/**
 * Description of EmployeePdpActionCompetenceSelectClusterGroup
 *
 * @author ben.dokter
 */

require_once('modules/interface/interfaceobjects/base/BaseGroupInterfaceObject.class.php');

class EmployeePdpActionCompetenceSelectClusterGroup extends BaseGroupInterfaceObject
{
    const TEMPLATE_FILE = 'employee/pdpAction/employeePdpActionCompetenceSelectClusterGroup.tpl';

    private $clusterName;

    static function create( $displayWidth,
                            $clusterName)
    {
        return new EmployeePdpActionCompetenceSelectClusterGroup(   $displayWidth,
                                                                    $clusterName);
    }

    protected function __construct( $displayWidth,
                                    $clusterName)
    {
        parent::__construct($displayWidth,
                            self::TEMPLATE_FILE);

        $this->clusterName = $clusterName;
    }

    //////////////////////////////////////////////////////////////////////////////////////////////////////////
    function addInterfaceObject(EmployeePdpActionCompetenceSelectView $interfaceObject)
    {
        parent::addInterfaceObject($interfaceObject);
    }

    //////////////////////////////////////////////////////////////////////////////////////////////////////////
    function getClusterName()
    {
        return $this->clusterName;
    }}

?>


text:
<?php
namespace CodeNet\KKClient\Resource;

use CodeNet\KKClient\Resource;

class Service extends Resource
{
    /**
     * @var string
     */
    protected $name;

    /**
     * @return string
     */
    public function getName()
    {
        return $this->name;
    }

    /**
     * @param string $name
     */
    public function setName($name)
    {
        $this->name = $name;
    }
}


text:
package com.android.teacher;

public class WordObject {

    private String KG;
    private String RU;
    private String TR;
    private byte[] img;
    private byte[] snd;
    private int cat;

    public WordObject(String kg, String ru, String tr, byte[] img, byte[] snd, int c_id) {
        this.KG = kg;
        this.RU = ru;
        this.TR = tr;
        this.img = img;
        this.snd = snd;
        this.cat = c_id;
    }

    public String getWord() {return KG;}

/*public void setWord(String kg) {this.KG = kg;}*/

    public String getRU() {return RU;}

/*public void setRU(String ru) {this.RU = ru;}*/

    public String getTR() {return TR;}

/*public void setTR(String tr) {this.TR = tr;}*/

    public byte[] getImg(){return img;}

/*public void setImg(byte[] img){this.img = img;}*/

    public byte[] getSnd(){return snd;}

/*public void setSnd(byte[] snd){this.snd = snd;}*/

    public int getCat() {return cat;}

/*public void setCat(int c_id) {this.cat = c_id;}*/

}


text:
package no.gorman.database;

import no.gorman.please.common.Child;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.lang.reflect.Field;
import java.sql.*;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.*;
import java.util.stream.Collectors;

import static java.util.Arrays.asList;
import static java.util.stream.Collectors.toList;
import static no.gorman.database.ColumnType.PrimaryKey;
import static no.gorman.database.ColumnType.Version;
import static no.gorman.database.DBFunctions.*;
import static org.apache.commons.lang.StringUtils.join;
import static org.apache.commons.lang.StringUtils.trim;

public class DB {

    private static final Logger log = LoggerFactory.getLogger(DB.class);

    private final Connection connection;
    final List<Runnable> onSuccessActions = new ArrayList<>(); //to be run when transaction completes successfully

    public DB(Connection connection) {
        this.connection = connection;
    }

    public <T> List<T> select(Class<T> clazz, Where... whereClause) {
        return select(clazz, new ArrayList<>(), whereClause);
    }

    public <T> List<T> select(Class<T> clazz, OrderBy orderBy, Where... whereClause) {
        return select(clazz, asList(orderBy), whereClause);
    }

    public <T> Optional<T> selectOnlyOne(Class<T> clazz, Where... where) {
        List<T> results = select(clazz, where);
        if (results.isEmpty()) return Optional.empty();
        if (results.size() > 1) throw new IllegalArgumentException("Expected only one value, but got " + results.size() + ". " + Arrays.toString(where));
        return Optional.of(results.get(0));
    }

    private <T> List<T> select(Class<T> clazz, List<OrderBy> orderBy, Where... whereClause) {
        String select = makeSelect(clazz, orderBy, whereClause);

        Set
 tables = getTables(clazz, whereClause);
        Collection<Join> joins = new ArrayList<>();
        if (tables.size() > 1) {
            joins.addAll(findJoins(tables));
            joins.forEach(join -> {
                tables.add(join.primary.getTable());
                tables.add(join.foreign.getTable());});
        }

        String from = " FROM " + join(tables, ", ");
        String where = makeWhere(joins, whereClause);
        String groupBy = makeGroupBy(clazz, orderBy);

        List<String> orderByStrings = orderBy.stream().map(by -> by.getColumn().name() + " " + by.getOrder()).collect(toList());
        String orderByStr = orderBy.isEmpty() ? "" : "ORDER BY " + join(orderByStrings, ",");

        String sql = join(asList(select, from, where, groupBy, orderByStr), " ");
        log.info(sql);
        return runSQL(clazz, sql, createParameterList(whereClause));
    }

    public <T> List<T> runSQL(Class<T> clazz, String sql, List<Object> parameters) {
        try (PreparedStatement stmt = connection.prepareStatement(sql)) {
            addParameters(stmt, parameters);
            try (ResultSet result = stmt.executeQuery()) {
                List<T> list = new ArrayList<>();
                while (result.next()) {
                    T instance = clazz.newInstance();
                    for (Field f : getMappedFields(clazz)) {
                        set(f, instance, getValueFromRS(result, getColumn(f)));
                    }
                    list.add(instance);
                }
                return list;
            }
        } catch (RuntimeException e) {
            log.error(sql);
            throw e;
        } catch (Exception e) {
            log.error(sql);
            throw new RuntimeException(e);
        }
    }

    public <T> List<T> select(DatabaseColumns column, Class<T> clazz, Where... whereClause) {

        if (!column.getFieldClass().isAssignableFrom(clazz)) throw new IllegalArgumentException(column + " is not of type  " + clazz.getSimpleName());
        String select = "SELECT DISTINCT " + column.name();
        Set
 tables = getTables(column.getFieldClass(), whereClause);
        tables.add(column.getTable());
        Collection<Join> joins = new ArrayList<>();
        if (tables.size() > 1) {
            joins.addAll(findJoins(tables));
            joins.forEach(join -> {tables.add(join.primary.getTable());tables.add(join.foreign.getTable());});
        }

        String from = " FROM " + join(tables, ",");
        String where = makeWhere(joins, whereClause);
        String sql = join(asList(trim(select), trim(from), trim(where)), " ").replace("  ", " ");
        log.info(sql);
        try (PreparedStatement stmt = connection.prepareStatement(sql)) {
            addParameters(stmt, createParameterList(whereClause));
            try (ResultSet result = stmt.executeQuery()) {
                List<T> list = new ArrayList<>();
                while (result.next()) {
                    list.add((T)getValueFromRS(result, column));
                }
                return list;
            }
        } catch (RuntimeException e) {
            log.error(sql);
            throw e;
        } catch (Exception e) {
            log.error(sql);
            throw new RuntimeException(e);
        }
    }

    public <T> void update(T updated) {
        update(updated, getMainTable(updated));
    }

    public <T> void update(final T updated, Table table) {
        List<Field> all = DBFunctions.getMappedFields(updated.getClass());

        Optional<Field> versionField = all.stream().filter(f -> getColumn(f).getType() == Version).findFirst();
        versionField.ifPresent(field -> {if (get(field, updated) == null) set(field, updated, 0);});

        List<Field> inMainTable = all.stream()
                .filter(f -> getColumn(f).getTable() == table)
                .filter(f -> getColumn(f).getType() != PrimaryKey)
                .collect(toList());
        List<String> setExpressions = inMainTable.stream()
                .map(f -> getColumn(f).name() + " = ?")
                .collect(Collectors.toList());
        List<Object> params = inMainTable.stream()
                .map(f -> (getColumn(f).getType() == Version) ? (1 + (int) get(f, updated)) : get(f, updated))
                .collect(toList());

        Field pk = all.stream().filter(f -> getColumn(f).getType() == PrimaryKey).findFirst()
                .orElseThrow(() -> new IllegalStateException("Cannot update " + updated.getClass().getName() + " as it has no primary key field"));

        String pkName = getColumn(pk).name();
        String sql = "UPDATE " + table.name() + " SET " + join(setExpressions, ", ") + " WHERE " + pkName + " = " + get(pk, updated);
        if (versionField.isPresent()) {
            String versionName = getColumn(versionField.get()).name();
            sql += " AND " + versionName + " = " + get(versionField.get(), updated);
        }
        log.info(sql);
        try (PreparedStatement stmt = connection.prepareStatement(sql)) {
            addParameters(stmt, params);
            if (stmt.executeUpdate() == 0) {
                String errorMsg = "Could not find row in table " + table + " with " + pkName + " = " + get(pk, updated);
                if (versionField.isPresent()) {
                    errorMsg += " and " + getColumn(versionField.get()) + " = " + get(versionField.get(), updated);
                    throw new ConcurrentModificationException(errorMsg);
                }
                throw new RuntimeException(errorMsg);
            }
            if (versionField.isPresent()) {
                set(versionField.get(), updated, (Integer) (get(versionField.get(), updated)) + 1);
            }
            onSuccessActions.add(() -> BigBrother.informAllAgents(updated));
        } catch (SQLException e) {
            log.error(sql);
            throw new RuntimeException(e);
        }
    }

    public void insert(Object... newOnes) {
        asList(newOnes).forEach(obj -> insert(obj, getMainTable(obj)));
    }

    public <T> Long insert(final T newInstance, Table table) {
        List<Field> all = DBFunctions.getMappedFields(newInstance.getClass());
        List<Field> inMainTable = all.stream()
                .filter(f -> getColumn(f).getTable() == table)
                .filter(f -> getColumn(f).getType() != PrimaryKey)
                .collect(toList());
        List<String> fieldNames = inMainTable.stream().map(f -> getColumn(f).name()).collect(toList());
        List<String> valueMarkers = fieldNames.stream().map(name -> "?").collect(toList());
        List<Object> params = inMainTable.stream()
                .map(f -> get(f, newInstance))
                .collect(toList());

        String sql = "INSERT INTO " + table.name() + "(" + join(fieldNames, ", ") + ") VALUES(" + join(valueMarkers, ", ") + ")";
        log.info(sql);
        try (PreparedStatement stmt = connection.prepareStatement(sql, Statement.RETURN_GENERATED_KEYS)) {
            addParameters(stmt, params);
            stmt.execute();
            ResultSet newIdRS = stmt.getGeneratedKeys();
            newIdRS.next();
            long newId = newIdRS.getLong(1);
            Optional<Field> pk = all.stream().filter(f -> getColumn(f).getType() == PrimaryKey).findFirst();
            if (pk.isPresent()) {
                set(pk.get(), newInstance, newId);
            }
            onSuccessActions.add(() -> BigBrother.informAllAgents(newInstance));
            return newId;
        } catch (Exception e) {
            log.error(sql);
            throw new RuntimeException(e);
        }
    }

    public <T> void delete(Class<T> clazz, Where... where) {
        Table table = getMainTableForClass(clazz);
        Collection<T> deleted = select(clazz, where);
        Optional<DatabaseColumns> pk = DatabaseColumns.getPrimaryKey(table);
        String sql = "DELETE FROM " + table.name() + " " + makeWhere(new ArrayList<Join>(), where);
        log.info(sql);
        try (PreparedStatement stmt = connection.prepareStatement(sql)) {
            addParameters(stmt, createParameterList(where));
            stmt.execute();
            onSuccessActions.add(() -> BigBrother.informAllAgents(deleted.toArray()));
        } catch (Exception e) {
            log.error(sql);
            throw new RuntimeException(e);
        }
    }

    /**
     * Joins a with b via a many-to-many-table-entry.
     * Saves you having to create separate java objects representing each simple many-to-many-join.
     *

     * example:
     *

     * Child c = new Child(1);
     * GrownUp g = new GrownUp(2);
     * DB.link(c,g);
     * will first find a many-to-many-relationship table that links the two tables Child and GrownUp : GrownUpChild.
     * it will then run the following SQL-statement:
     * INSERT INTO GrownUpChild(gcChildId, gcGrownUpId) VALUES(1,2);
     *
     */
    public void link(Object from, Object to) {
        manyToManyOperation(from, to, "INSERT INTO %s (%s, %s) VALUES(?, ?)");
    }

    public void unlink(Object from, Object to) {
        manyToManyOperation(from, to, "DELETE FROM %s WHERE %s = ? AND %s = ?");
    }

    private void manyToManyOperation(Object from, Object to, String sql) {
        Table manyToMany = findManyToManyTable(from, to).orElseThrow(()-> new IllegalArgumentException("No mapping table found between " + from + " and " + to));
        DatabaseColumns fkFrom = DatabaseColumns.getForeignKey(getMainTable(from), manyToMany).orElseThrow(() -> new IllegalArgumentException("no foreign keys found for " + from ));
        DatabaseColumns fkTo = DatabaseColumns.getForeignKey(getMainTable(to), manyToMany).orElseThrow(() -> new IllegalArgumentException("no foreign keys found for " + to ));
        String filledOut = String.format(sql, manyToMany.name(),fkFrom.name(), fkTo.name());
        log.info(filledOut);

        try (PreparedStatement stmt = connection.prepareStatement(filledOut)) {
            Long fromId = (Long) getPrimaryKeyField(from).get(from);
            Long toId = (Long) getPrimaryKeyField(to).get(to);
            stmt.setLong(1, fromId);
            stmt.setLong(2, toId);
            stmt.executeUpdate();
            onSuccessActions.add(() -> BigBrother.inform(new BigBrother.RowIdentifier(fkFrom, fromId), to));
            onSuccessActions.add(() -> BigBrother.inform(new BigBrother.RowIdentifier(fkTo, toId), from));

        } catch (Exception e) {
            log.error(sql);
            throw new RuntimeException(e);
        }
    }

    public static void addParameters(PreparedStatement stmt, List<Object> params) {
        try {
            for (int i = 1; i <= params.size(); i++) {
                Object p = params.get(i-1);
                if (p == null) {
                    stmt.setObject(i, null);
                } else if (p instanceof String) {
                    stmt.setString(i, (String) p);
                } else if (p instanceof Integer) {
                    stmt.setInt(i, (Integer) p);
                } else if (p instanceof Long) {
                    stmt.setLong(i, (Long) p);
                } else if (p instanceof LocalDate) {
                    stmt.setInt(i, Integer.parseInt(((LocalDate) p).format(YYYY_MM_DD)));
                } else if (p.getClass().isEnum()) {
                    stmt.setString(i, ((Enum<?>) p).name());
                } else if (p.getClass() == byte[].class) {
                    stmt.setBytes(i, (byte[])p);
                } else {
                    throw new IllegalArgumentException("No mapping found for " + p);
                }
            }
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    public static Object getValueFromRS(ResultSet rs, DatabaseColumns col) throws IllegalAccessException, SQLException {
        Class<?> clazz = col.getFieldClass();
        String colName = col.name();
        if (clazz == String.class) {
            return rs.getString(colName);
        } else if (INT_TYPES.contains(clazz)) {
            int intValue = rs.getInt(colName);
            return (rs.wasNull() ? null : intValue);
        } else if (LONG_TYPES.contains(clazz)) {
            long longValue = rs.getLong(colName);
            return (rs.wasNull() ? null : longValue);
        } else if (clazz == LocalDate.class) {
            String dateString = String.valueOf(rs.getInt(colName));
            return (rs.wasNull() ? null : LocalDate.parse(dateString, YYYY_MM_DD));
        } else if (clazz == LocalDateTime.class) {
            Timestamp timestamp = rs.getTimestamp(colName);
            return (rs.wasNull() ? null : timestamp.toLocalDateTime());
        }else if (clazz == byte[].class) {
            byte[] array = rs.getBytes(colName);
            return rs.wasNull() ? null : array;
        } else if (clazz.isEnum()) {
            String enumVal = trim(rs.getString(colName));
            if (!rs.wasNull()) {
                try {
                    return Enum.valueOf((Class<? extends Enum>) clazz, enumVal);
                } catch (Exception e) {
                    log.error("Failed to load " + clazz + ": " + e.getMessage());
                }
            }
            return null;
        } else {
            throw new IllegalArgumentException("Damn it, didn't find any type for " + colName + " with type " + clazz);
        }
    }

    public void commitAndReleaseConnection() {
        try {
            if (connection == null) return;
            if (connection.isClosed()) return;
            connection.commit();
            onSuccessActions.forEach(runnable -> runnable.run());
            onSuccessActions.clear();
            connection.close();
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
    }

    public void rollback() {
        try {
            if (connection == null) return;
            if (connection.isClosed()) return;
            connection.rollback();
            onSuccessActions.clear();
            connection.close();
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
    }
}


text:
import { Directive, ElementRef, Renderer, forwardRef } from '@angular/core';
import { NG_VALUE_ACCESSOR } from './control_value_accessor';
export var DEFAULT_VALUE_ACCESSOR = {
    provide: NG_VALUE_ACCESSOR,
    useExisting: forwardRef(function () { return DefaultValueAccessor; }),
    multi: true
};
/**
 * The default accessor for writing a value and listening to changes that is used by the
 * {@link NgModel}, {@link FormControlDirective}, and {@link FormControlName} directives.
 *
 *  ### Example
 *  ```
 *  <input type="text" name="searchQuery" ngModel>
 *  ```
 *
 *  @stable
 */
export var DefaultValueAccessor = (function () {
    function DefaultValueAccessor(_renderer, _elementRef) {
        this._renderer = _renderer;
        this._elementRef = _elementRef;
        this.onChange = function (_) { };
        this.onTouched = function () { };
    }
    DefaultValueAccessor.prototype.writeValue = function (value) {
        var normalizedValue = value == null ? '' : value;
        this._renderer.setElementProperty(this._elementRef.nativeElement, 'value', normalizedValue);
    };
    DefaultValueAccessor.prototype.registerOnChange = function (fn) { this.onChange = fn; };
    DefaultValueAccessor.prototype.registerOnTouched = function (fn) { this.onTouched = fn; };
    DefaultValueAccessor.prototype.setDisabledState = function (isDisabled) {
        this._renderer.setElementProperty(this._elementRef.nativeElement, 'disabled', isDisabled);
    };
    DefaultValueAccessor.decorators = [
        { type: Directive, args: [{
                    selector: 'input:not([type=checkbox])[formControlName],textarea[formControlName],input:not([type=checkbox])[formControl],textarea[formControl],input:not([type=checkbox])[ngModel],textarea[ngModel],[ngDefaultControl]',
                    // TODO: vsavkin replace the above selector with the one below it once
                    // https://github.com/angular/angular/issues/3011 is implemented
                    // selector: '[ngControl],[ngModel],[ngFormControl]',
                    host: { '(input)': 'onChange($event.target.value)', '(blur)': 'onTouched()' },
                    providers: [DEFAULT_VALUE_ACCESSOR]
                },] },
    ];
    /** @nocollapse */
    DefaultValueAccessor.ctorParameters = [
        { type: Renderer, },
        { type: ElementRef, },
    ];
    return DefaultValueAccessor;
}());
//# sourceMappingURL=default_value_accessor.js.map


text:
<?php

namespace App\LanguageFileHandling\InputHandlers;

use \Exception;

class InputHandlerFactory
{
    const SIMPLE_JSON = 1;
    const MANUAL = 2;
    const STEAM_ACHIEVEMENTS = 3;
    const INI = 4;
    const CSV = 5;

    public static $availableHandlers = [
        self::SIMPLE_JSON        => 'Simple JSON',
        self::MANUAL             => 'Manual',
        self::STEAM_ACHIEVEMENTS => 'Steam achievements',
        self::INI                => 'INI file',
        self::CSV                => 'CSV file',
    ];

    public static function getFileHandler($handlerType, $rawData = null)
    {
        switch ($handlerType) {
            case self::SIMPLE_JSON:
                return new SimpleJsonObjectInputHandler($rawData);
            case self::STEAM_ACHIEVEMENTS:
                return new SteamAchievementsInputHandler($rawData);
            case self::INI:
                return new INIInputHandler($rawData);
            case self::CSV:
                return new CSVInputHandler($rawData);
            default:
                throw new Exception('Undefined input handler.');
        }
    }
}


text:
#include <algorithm>

#include "SyslogLogTarget.h"

void SyslogLogTarget::begin(const String &name, const String &server,
                            uint16_t port) {
  syslog.server(server.c_str(), port);
  syslog.deviceHostname(name.c_str());
  syslog.appName("MQTT433gateway");
}

void SyslogLogTarget::flush(const char *buff) { syslog.log(buff); }


text:
package org.apache.geode.internal.util;

import java.util.Collections;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.stream.Collectors;

import org.apache.geode.annotations.Immutable;
import org.apache.geode.distributed.ConfigurationProperties;
import org.apache.geode.distributed.internal.DistributionConfig;

public class ArgumentRedactor {
  public static final String redacted = "********";

  @Immutable
  private static final List<String> tabooToContain =
      Collections.unmodifiableList(ArrayUtils.asList("password"));
  @Immutable
  private static final List<String> tabooForOptionToStartWith =
      Collections.unmodifiableList(ArrayUtils.asList(DistributionConfig.SYS_PROP_NAME,
          DistributionConfig.SSL_SYSTEM_PROPS_NAME,
          ConfigurationProperties.SECURITY_PREFIX));

  private static final Pattern optionWithArgumentPattern = getOptionWithArgumentPattern();

  /**
   * This method returns the {@link java.util.regex.Pattern} given below, used to capture
   * command-line options that accept an argument. For clarity, the regex is given here without
   * the escape characters required by Java's string handling.
   *

   *
   * {@code ((?:^| )(?:--J=)?--?)([^\s=]+)(?=[ =])( *[ =] *)(?! *-)((?:"[^"]*"|\S+))}
   *
   *

   * This pattern consists of one captured boundary,
   * three additional capture groups, and two look-ahead boundaries.
   *
   *

   * The four capture groups are:
   *

   *
[1] The beginning boundary, including at most one leading space,
   * possibly including "--J=", and including the option's leading "-" or "--"

   *
[2] The option, which cannot include spaces

   *
[3] The option / argument separator, consisting of at least one character
   * made of spaces and/or at most one "="

   *
[4] The argument, which terminates at the next space unless it is encapsulated by
   * quotation-marks, in which case it terminates at the next quotation mark.

   *

   *
   * Look-ahead groups avoid falsely identifying two flag options (e.g. `{@code --help --all}`) from
   * interpreting the second flag as the argument to the first option
   * (here, misinterpreting as `{@code --help="--all"}`).
   *

   *
   * Note that at time of writing, the argument (capture group 4) is not consumed by this class's
   * logic, but its capture has proven repeatedly useful during iteration and testing.
   */
  private static Pattern getOptionWithArgumentPattern() {
    String capture_beginningBoundary;
    {
      String spaceOrBeginningAnchor = "(?:^| )";
      String maybeLeadingWithDashDashJEquals = "(?:--J=)?";
      String oneOrTwoDashes = "--?";
      capture_beginningBoundary =
          "(" + spaceOrBeginningAnchor + maybeLeadingWithDashDashJEquals + oneOrTwoDashes + ")";
    }

    String capture_optionNameHasNoSpaces = "([^\\s=]+)";

    String boundary_lookAheadForSpaceOrEquals = "(?=[ =])";

    String capture_optionArgumentSeparator = "( *[ =] *)";

    String boundary_negativeLookAheadToPreventNextOptionAsThisArgument = "(?! *-)";

    String capture_Argument;
    {
      String argumentCanBeAnythingBetweenQuotes = "\"[^\"]*\"";
      String argumentCanHaveNoSpacesWithoutQuotes = "\\S+";
      String argumentCanBeEitherOfTheAbove = "(?:" + argumentCanBeAnythingBetweenQuotes + "|"
          + argumentCanHaveNoSpacesWithoutQuotes + ")";
      capture_Argument = "(" + argumentCanBeEitherOfTheAbove + ")";
    }

    String fullPattern = capture_beginningBoundary + capture_optionNameHasNoSpaces
        + boundary_lookAheadForSpaceOrEquals + capture_optionArgumentSeparator
        + boundary_negativeLookAheadToPreventNextOptionAsThisArgument + capture_Argument;
    return Pattern.compile(fullPattern);
  }

  private ArgumentRedactor() {}

  /**
   * Parse a string to find option/argument pairs and redact the arguments if necessary.

   *
   * The following format is expected:

   * - Each option/argument pair should be separated by spaces.

   * - The option of each pair must be preceded by at least one hyphen '-'.

   * - Arguments may or may not be wrapped in quotation marks.

   * - Options and arguments may be separated by an equals sign '=' or any number of spaces.

   *

   * Examples:

   * "--password=secret"

   * "--user me --password secret"

   * "-Dflag -Dopt=arg"

   * "--classpath=."

   *
   * See {@link #getOptionWithArgumentPattern()} for more information on
   * the regular expression used.
   *
   * @param line The argument input to be parsed
   * @param permitFirstPairWithoutHyphen When true, prepends the line with a "-", which is later
   *        removed. This allows the use on, e.g., "password=secret" rather than "--password=secret"
   *
   * @return A redacted string that has sensitive information obscured.
   */
  public static String redact(String line, boolean permitFirstPairWithoutHyphen) {

    boolean wasPaddedWithHyphen = false;
    if (!line.trim().startsWith("-") && permitFirstPairWithoutHyphen) {
      line = "-" + line.trim();
      wasPaddedWithHyphen = true;
    }

    Matcher matcher = optionWithArgumentPattern.matcher(line);
    while (matcher.find()) {
      String option = matcher.group(2);
      if (!isTaboo(option)) {
        continue;
      }

      String leadingBoundary = matcher.group(1);
      String separator = matcher.group(3);
      String withRedaction = leadingBoundary + option + separator + redacted;
      line = line.replace(matcher.group(), withRedaction);
    }

    if (wasPaddedWithHyphen) {
      line = line.substring(1);
    }
    return line;
  }

  /**
   * Alias for {@code redact(line, true)}. See
   * {@link org.apache.geode.internal.util.ArgumentRedactor#redact(java.lang.String, boolean)}
   */
  public static String redact(String line) {
    return redact(line, true);
  }

  public static String redact(final List<String> args) {
    return redact(String.join(" ", args));
  }

  /**
   * Return the redaction string if the provided option's argument should be redacted.
   * Otherwise, return the provided argument unchanged.
   *
   * @param option A string such as a system property, jvm parameter or command-line option.
   * @param argument A string that is the argument assigned to the option.
   *
   * @return A redacted string if the option indicates it should be redacted, otherwise the
   *         provided argument.
   */
  public static String redactArgumentIfNecessary(String option, String argument) {
    if (isTaboo(option)) {
      return redacted;
    }
    return argument;
  }

  /**
   * Determine whether a option's argument should be redacted.
   *
   * @param option The option in question.
   *
   * @return true if the value should be redacted, otherwise false.
   */
  static boolean isTaboo(String option) {
    if (option == null) {
      return false;
    }
    for (String taboo : tabooForOptionToStartWith) {
      // If a parameter is passed with -Dsecurity-option=argument, the option option is
      // "Dsecurity-option".
      // With respect to taboo words, also check for the addition of the extra D
      if (option.toLowerCase().startsWith(taboo) || option.toLowerCase().startsWith("d" + taboo)) {
        return true;
      }
    }
    for (String taboo : tabooToContain) {
      if (option.toLowerCase().contains(taboo)) {
        return true;
      }
    }
    return false;
  }

  public static List<String> redactEachInList(List<String> argList) {
    return argList.stream().map(ArgumentRedactor::redact).collect(Collectors.toList());
  }
}


text:
VERSION = $(shell cat package.json | sed -n 's/.*"version": "\([^"]*\)",/\1/p')

SHELL = /usr/bin/env bash

default: install
.PHONY: default test install tag remove_tag

version:
	@echo $(VERSION)

install:
	npm install
	$$(npm bin)/jspm install

build_node:
	$$(npm bin)/jspm build lessjs src/bundled_less/less.node.js --node  --minify

build_browser:
	$$(npm bin)/jspm build lessjs/dist/less.js src/bundled_less/less.browser.js  --minify

build_jspm_less_plugin:
	$$(npm bin)/babel  jspm-less-plugin/es6 -d jspm-less-plugin
	$$(npm bin)/jspm build jspm-less-plugin/index.js src/jspm-less-plugin.js

build: build_node build_browser	build_jspm_less_plugin

test:
	$$(npm bin)/mocha

update_version:
ifeq ($(shell expr "${CURRENT_MAJOR}" \> "$(NEXT_MAJOR)"),1)
	$(error "v" parameter is lower than current version ${VERSION})
endif
ifeq ($(shell expr "${CURRENT_MINOR}" \> "$(NEXT_MINOR)"),1)
	$(error "v" parameter is lower than current version ${VERSION})
endif
ifeq ($(shell expr "${CURRENT_HOTFIX}" \> "$(NEXT_HOTFIX)"),1)
	$(error "v" parameter is lower than current version ${VERSION})
endif
ifeq ($(v),)
	$(error v is undefined. Use e.g. make tag v=1.0.0 or make release v=1.0.0)
endif
ifeq (${VERSION},$(v))
	$(error v is already the current version)
endif
	@echo "Current version is " ${VERSION}
	@echo "Next version is " $(v)
	sed -i s/"$(VERSION)"/"$(v)"/g package.json

check_version:
	$(eval SPLIT_VERSION = $(subst ., ,${VERSION}))
	$(eval NEXT_VERSION := $(subst ., ,${v}))
	$(eval CURRENT_MAJOR := $(word 1,$(SPLIT_VERSION)))
	$(eval CURRENT_MINOR := $(word 2,$(SPLIT_VERSION)))
	$(eval CURRENT_HOTFIX := $(word 3,$(SPLIT_VERSION)))
	$(eval NEXT_MAJOR := $(word 1,$(NEXT_VERSION)))
	$(eval NEXT_MINOR := $(word 2,$(NEXT_VERSION)))
	$(eval NEXT_HOTFIX := $(word 3,$(NEXT_VERSION)))

tag_and_push:
		git add --all
		git commit -a -m "Tag v $(v) $(m)"
		git tag v$(v)
		git push
		git push --tags

tag: build release

release: test check_version update_version tag_and_push

remove_tag:
ifeq ($(t),)
	$(error t is undefined, you must config a tag name. e.g. make remove_tag t=v1.0.0)
endif
	git tag -d $(t)
	git push origin :refs/tags$(t)


text:
import "typeface-open-sans"
import "typeface-merriweather"
import "prismjs/themes/prism.css"


text:
<?php
/**
 * Created by PhpStorm.
 * User: frli
 * Date: 15-12-18
 * Time: 下午10:46
 */

namespace Skyling\Flysystem\Qiniu;

use League\Flysystem\Adapter\AbstractAdapter;
use League\Flysystem\Adapter\Polyfill\NotSupportingVisibilityTrait;
use League\Flysystem\Adapter\Polyfill\StreamedReadingTrait;
use League\Flysystem\Adapter\Polyfill\StreamedWritingTrait;
use League\Flysystem\Config;
use Qiniu\Auth;
use Qiniu\Processing\Operation;
use Qiniu\Processing\PersistentFop;
use Qiniu\Storage\BucketManager;
use Qiniu\Storage\UploadManager;

class QiniuAdapter extends AbstractAdapter
{
    use NotSupportingVisibilityTrait, StreamedWritingTrait, StreamedReadingTrait;

    private $accessKey = null;
    private $secretKey = null;
    private $bucket = null;
    private $domain = null;

    private $auth = null;
    private $token = null;
    private $operation = null;
    private $uploadManager = null;
    private $bucketManager = null;

    public function __construct($accessKey, $secretKey, $bucket, $domain)
    {
        $this->accessKey = $accessKey;
        $this->secretKey = $secretKey;
        $this->bucket = $bucket;
        $this->domain = $domain;
        $this->setPathPrefix($this->domain);

        $this->bucketManager = new BucketManager($this->getAuth());
        $this->uploadManager = new UploadManager();
    }

    /**
     * 获取七牛Auth对象
     * @return Auth
     */
    private function getAuth()
    {
        if ($this->auth == null) {
            $this->auth = new Auth($this->accessKey, $this->secretKey);
        }
        return $this->auth;
    }

    /**
     * 获取上传TOKEN
     * @param string $path 文件名称
     * @return string
     */
    private function getToken($path = null)
    {
        if ($this->token == null ) {
            $this->token = $this->setToken($path);
        }
        return $this->token;
    }

    /**
     * 获取BucketManger 对象
     * @return BucketManager
     */
    private function getBucketManager()
    {
        if ($this->bucketManager == null) {
            $this->bucketManager = new BucketManager($this->getAuth());
        }
        return $this->bucketManager;
    }

    /**
     * @return UploadManager
     */
    private function getUploadManager()
    {
        if ($this->uploadManager == null) {
            $this->uploadManager = new UploadManager();
        }
        return $this->uploadManager;
    }

    /**
     * @return Operation
     */
    private function getOperation()
    {
        if ($this->operation == null) {
            $this->operation = new Operation($this->domain);
        }
        return $this->operation;
    }

    private function logQiniuError(Error $error)
    {
        //http://developer.qiniu.com/docs/v6/api/reference/codes.html
        $notLogCode = [612];

        /*if (!in_array($error->code(), $notLogCode)) {
            \Log::error('Qiniu: ' . $error->code() . ' ' . $error->message());
        }*/
    }

    /**
     * 设置token
     * @param null $path
     * @param int $expires
     * @param null $policy
     * @param bool|true $strictPolicy
     * @return string
     */
    public function setToken($path = null, $expires = 3600, $policy = null, $strictPolicy = true)
    {
        $auth = $this->getAuth();
        $this->token = $auth->uploadToken($this->bucket, $path, $expires, $policy, $strictPolicy);
        return $this->token;
    }

    /**
     * 返回处理
     * @param $ret
     * @param $error
     * @param null $key
     * @return bool
     */
    private function returnDeal($ret, $error, $key = null)
    {
        if ($error !== null) {
            $this->logQiniuError($error);
            return false;
        }
        if ($key !== null && isset($ret[$key])) {
            return $ret[$key];
        }
        return $ret;
    }

    public function update($path, $contents, Config $config)
    {
        return $this->write($path, $contents, $config);
    }

    /**
     * 重命名
     * @param string $path
     * @param string $newpath
     * @return bool
     */
    public function rename($path, $newpath)
    {
        $bucketMgr = $this->getBucketManager();
        list($ret, $error) = $bucketMgr->move($this->bucket, $path, $this->bucket, $newpath);

        return $this->returnDeal($ret, $error);
    }

    public function write($path, $contents, Config $config, $isPutFile = false)
    {
        $token = $this->getToken($path);
        $params = $config->get('params', null);
        $mime = $config->get('mime', 'application/octet-stream');
        $checkCrc = $config->get('checkCrc', false);

        $uploadMgr = $this->getUploadManager();
        if ($isPutFile) {
            list($ret, $error) = $uploadMgr->putFile($token, $path, $contents, $params, $mime, $checkCrc);
        } else {
            list($ret, $error) = $uploadMgr->put($token, $path, $contents, $params, $mime, $checkCrc);
        }

        return $this->returnDeal($ret, $error);
    }

    public function copy($path, $newpath)
    {
        $bucketMgr = $this->getBucketManager();

        list($ret, $error) = $bucketMgr->copy($this->bucket, $path, $this->bucket, $newpath);
        return $this->returnDeal($ret, $error);
    }

    public function delete($path)
    {
        $bucketMgr = $this->getBucketManager();

        list($ret, $error) = $bucketMgr->delete($this->bucket, $path);

        $this->returnDeal($ret, $error);

    }

    public function deleteDir($dirname)
    {
        $files = $this->listContents($dirname);
        foreach ($files as $file) {
            $this->delete($file['path']);
        }
        return true;
    }

    public function createDir($dirname, Config $config)
    {
        return ['path' => $dirname];
    }

    public function has($path)
    {
        $meta = $this->getMetadata($path);
        if ($meta) {
            return true;
        }
        return false;
    }

    /**
     * @param string $path
     *
     * @return resource
     */
    public function read($path)
    {
        $location = $this->applyPathPrefix($path);
        return array('contents' => file_get_contents($location));
    }

    public function listContents($directory = '', $recursive = false)
    {
        $bucketMgr = $this->getBucketManager();

        list($items, $marker, $error) = $bucketMgr->listFiles($this->bucket, $directory);
        if ($error !== null) {
            $this->logQiniuError($error);

            return array();
        } else {
            $contents = array();
            foreach ($items as $item) {
                $normalized = ['type' => 'file', 'path' => $item['key'], 'timestamp' => $item['putTime']];

                if ($normalized['type'] === 'file') {
                    $normalized['size'] = $item['fsize'];
                }

                array_push($contents, $normalized);
            }
            return $contents;
        }
    }

    public function getMetadata($path)
    {
        $bucketMgr = $this->getBucketManager();

        list($ret, $error) = $bucketMgr->stat($this->bucket, $path);
        return $this->returnDeal($ret, $error);
    }

    public function getSize($path)
    {
        $stat = $this->getMetadata($path);
        if ($stat) {
            return array('size' => $stat['fsize']);
        }
        return false;
    }

    public function getMimetype($path)
    {
        $stat = $this->getMetadata($path);
        if ($stat) {
            return array('mimetype' => $stat['mimeType']);
        }
        return false;
    }

    public function getTimestamp($path)
    {
        $stat = $this->getMetadata($path);
        if ($stat) {
            return array('timestamp' => $stat['putTime']);
        }
        return false;
    }

    /**
     * 获取私有下载链接
     * @param $path 文件名称
     * @param int $expires 有效时间
     * @return string
     */
    public function privateDownloadUrl($path, $expires = 3600)
    {
        $auth = $this->getAuth();
        $location = $this->applyPathPrefix($path);
        $authUrl = $auth->privateDownloadUrl($location, $expires);

        return $authUrl;
    }

    /**
     * 对资源文件进行异步持久化处理
     * @param string $path 待处理的源文件
     * @param string|array $fops 待处理的pfop操作,多个pfop操作以array的形式传入。
     * @return bool
     */
    public function persistentFop($path = null, $fops = null)
    {
        $auth = $this->getAuth();

        $pfop = new PersistentFop($auth, $this->bucket);
        list($id, $error) = $pfop->execute($path, $fops);
        return $this->returnDeal($id, $error);
    }

    /**
     * 获取持久化文件状态
     * @param $id
     * @return array
     */
    public function persistentStatus($id)
    {
        return PersistentFop::status($id);
    }

    /**
     * 从指定URL抓取资源,并将该资源存储到指定空间中
     * @param $url
     * @param $key
     * @return bool
     */
    public function fetch($url, $key)
    {
        $bucketMgr = $this->getBucketManager();
        list($ret, $error) = $bucketMgr->fetch($url, $this->bucket, $key);
        return $this->returnDeal($ret, $error, 'key');
    }

    /**
     * 获取下载链接
     * @param null $path
     * @return string
     */
    public function downloadUrl($path = null)
    {
        $location = $this->applyPathPrefix($path);
        return $location;
    }

    /**
     * 获取图片信息
     * @param null $path
     * @return bool
     */
    public function imageInfo($path = null)
    {
        $operation = $this->getOperation();
        list($ret, $error) = $operation->execute($path, 'imageInfo');
        return $this->returnDeal($ret, $error);
    }

    /**
     * 获取图片Exif信息
     * @param null $path
     * @return bool
     */
    public function imageExif($path = null)
    {
        $operate = $this->getOperation();
        list($ret, $error) = $operate->execute($path, 'exif');
        return $this->returnDeal($ret, $error);
    }

    /**
     * 获取图片预览地址
     * @param null $path
     * @param null $ops
     * @return string
     */
    public function imagePreviewUrl($path = null, $ops = null)
    {
        $operate = $this->getOperation();
        $url = $operate->buildUrl($path, $ops);
        return $url;
    }
}

/*  End of file QiniuAdapter.php*/


text:
/* jshint quotmark: single */

(function () {
	'use strict';

	questkit.showLocationDescription = function () {
		// TODO: Customisable description order
		// TODO: Darkness
		// TODO: Option to not use "You are in"

		var povParent = questkit.povParent();

		var descprefix = get(povParent, 'descprefix') || questkit.template('YouAreIn');
		msg(descprefix + ' ' + displayName(povParent, true) + '.');

		var objects = questkit.removeSceneryObjects(questkit.getDirectChildren(questkit.getNonTransparentParent(povParent)));
		var youCanSee = questkit.formatList(
			get(povParent, 'objectslistprefix') || questkit.template('SeeListHeader'),
			objects,
			questkit.template('And'),
			true
		);
		if (youCanSee) msg(youCanSee);

		var youCanGo = questkit.formatList(
			get(povParent, 'exitslistprefix') || questkit.template('GoListHeader'),
			questkit.removeSceneryExits(questkit.scopeExits()),
			questkit.template('Or'),
			false
		);
		if (youCanGo) msg(youCanGo);

		var description = get(povParent, 'description');
		if (description) msg(description);
	};

	var displayName = function (object, useDefaultPrefix) {
		var prefix = get(object, 'prefix') || (useDefaultPrefix ? questkit.defaultPrefix(object) : null);
		var suffix = get(object, 'suffix');
		var result = questkit.displayAlias(object);
		if (prefix) result = prefix + ' ' + result;
		if (suffix) result = result + ' ' + suffix;
		return result;
	};

	var formatObjectList = function (preList, parent, preFinal) {
		var list = questkit.removeSceneryObjects(questkit.getDirectChildren(parent));
		return questkit.formatList(preList, list, preFinal, true);
	};

	questkit.formatList = function (preList, list, preFinal, useDefaultPrefix) {
		var result = [];

		list.forEach(function (item, index) {
			if (result.length === 0) result.push(preList, ' ');
			result.push(displayName(item, useDefaultPrefix));

			if (index === list.length - 2) {
				result.push(' ', preFinal, ' ');
			}
			else if (index < list.length - 1) {
				result.push(', ');
			}
			else {
				result.push('.');
			}
		});

		return result.join('');
	};

	questkit.removeSceneryObjects = function (list) {
		var pov = get('pov');
		return list.filter(function (item) {
			return !get(item, 'scenery') && item !== pov;
		});
	};

	questkit.removeSceneryExits = function (list) {
		return list.filter(function (item) {
			return !get(item, 'scenery');
		});
	};

	questkit.go = function (location) {
		var oldLocation = questkit.povParent();
		set(get('pov'), 'parent', location);
		questkit.startLocation(oldLocation);
	};

	questkit.startLocation = function (oldLocation) {
		// TODO: Run "on entering location", "on exiting previous location" scripts etc.
		questkit.showLocationDescription();
	};
})();


text:
package dk.lessismore.nojpa.pool.threadpool;

import dk.lessismore.nojpa.guid.GuidFactory;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import java.util.Iterator;
import java.util.LinkedList;

/**
 * Created by IntelliJ IDEA.
 * User: bart
 * Date: 30-05-2007
 * Time: 21:23:26
 */
public class RuntimeCallbackThreadPool {

    protected final static Log log = LogFactory.getLog(RuntimeCallbackThreadPool.class);

    private final int countOfThreads;
    private boolean runing = true;
    private final LinkedList<CalcWork> workToDo = new LinkedList<CalcWork>();
    private final LinkedList<CallbackWorker> workers;
    private final LinkedList<RuntimeCallbackCalcInterface> unbizyResources;
    private final Class classOfCallbackCalcInterface;

    public RuntimeCallbackThreadPool(int countOfThreads, Class classOfCallbackCalcInterface) throws IllegalAccessException, InstantiationException {
        this.classOfCallbackCalcInterface = classOfCallbackCalcInterface;
        this.countOfThreads = countOfThreads;
        workers = new LinkedList<CallbackWorker>();
        unbizyResources = new LinkedList<RuntimeCallbackCalcInterface>();
        for(int i = 0; i < countOfThreads; i++){
            unbizyResources.add((RuntimeCallbackCalcInterface) classOfCallbackCalcInterface.newInstance());
        }

    }

    public Object doCalc(Object input) throws Exception {
        CalcWork work = new CalcWork(Thread.currentThread());
        work.input = input;
        doCalcWork(work);
        int countOfWait = 0;
        while (!work.getDone()) {
            try {
                synchronized (Thread.currentThread()) {
                    countOfWait++;
                    Thread.currentThread().wait(8 * 1000);
                }
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            if(countOfWait > 3){
                try {
                    synchronized (unbizyResources) {
                        if (!unbizyResources.isEmpty()) {

                            synchronized (workers) {
                                if (workers.size() < countOfThreads) {
                                    CallbackWorker worker = new CallbackWorker();
                                    worker.setName("Callback-Worker");
                                    synchronized (workers) {
                                        workers.addLast(worker);
                                    }
                                    worker.start();
                                }
                            }
                        } else {

                        }
                    }
                } catch (Exception e) {

                }
            }
        }
        if (work.exception != null) {
            throw work.exception;
        } else {
            return work.output;
        }
    }

    private void doCalcWork(CalcWork work) {
        synchronized(workToDo){
            workToDo.addLast(work);
        }
        try{
            boolean isUnbizyResEmpty;
            synchronized(unbizyResources){
                isUnbizyResEmpty = unbizyResources.isEmpty();
            }
            if(isUnbizyResEmpty){
                //log.debug("Reuse thread");
                synchronized(workers){
                    for(Iterator<CallbackWorker> iterator = workers.iterator(); iterator.hasNext(); ){
                        RuntimeCallbackThreadPool.CallbackWorker worker = iterator.next();
                        synchronized(worker){
                            if(worker.getState() == Thread.State.WAITING){
                                worker.notify();
                            }
                        }
                    }
                }
            } else {
                CallbackWorker worker = new CallbackWorker();
                worker.setName("Callback-Worker");
                synchronized(workers){
                    workers.addLast(worker);
                }
                worker.start();
            }

        } catch(Exception e){
            e.printStackTrace();
        }
    }

    public class CallbackWorker extends Thread {
        public CallbackWorker(){
        }

        public void run(){
            int countOfWait = 0;
            while(runing && countOfWait < 10){
                try{
                    RuntimeCallbackCalcInterface calculator = null;
                    synchronized(unbizyResources){
                        if(!unbizyResources.isEmpty()){
                            calculator = unbizyResources.removeFirst();
                        }
                    }
                    if(calculator != null){
                        CalcWork work = null;
                        synchronized(workToDo){
                            if(!workToDo.isEmpty()){
                                work = workToDo.removeFirst();
                            }
                        }
                        if(work != null){
                            countOfWait = 0;
                            try{
                                work.output = calculator.doCalc(work.input);
                            } catch(Exception e){
                                work.exception = e;
                            } finally{
                                synchronized(unbizyResources){
                                    unbizyResources.addLast(calculator);
                                }
                                work.setDone(true);
                                try{
                                    synchronized(work.meToNotify){
                                        work.meToNotify.notify();
                                    }
                                } catch (Exception ne){
                                    ne.printStackTrace();
                                }
                            }
                        } else {
                            synchronized(unbizyResources){
                                unbizyResources.addLast(calculator);
                            }
                            synchronized(this){
                                this.wait(1000);
                                log.debug(Thread.currentThread().getName() + "::countOfWait = " + countOfWait);
                                countOfWait++;
                            }
                        }
                    }
                } catch(Exception e){
                    e.printStackTrace();
                }
            }
            synchronized(workers){
                workers.remove(this);
            }
        }
    }

    protected class CalcWork {
        public Object input = null;
        public Object output = null;
        public Exception exception = null;
        public final Thread meToNotify;
        public String id = GuidFactory.getInstance().makeGuid();
        private boolean done = false;

        public CalcWork(Thread meToNotify){
            this.meToNotify = meToNotify;
        }

        public synchronized boolean getDone() {
            return done;
        }

        public synchronized void setDone(boolean done) {
            this.done = done;
        }
    }

    protected void finalize() throws Throwable {
        super.finalize();
        log.debug("Pool.finalize()");
    }
}


text:
module Shipit
  class UserSerializer < ActiveModel::Serializer
    attributes :id, :name, :email, :login, :avatar_url, :created_at, :updated_at
  end
end


text:
package com.vmware.vim25;

/**
* @author Steve Jin (http://www.doublecloud.org)
* @version 5.1
*/

@SuppressWarnings("all")
public class VmFaultToleranceInvalidFileBacking extends VmFaultToleranceIssue {
  public String backingType;
  public String backingFilename;

  public String getBackingType() {
    return this.backingType;
  }

  public String getBackingFilename() {
    return this.backingFilename;
  }

  public void setBackingType(String backingType) {
    this.backingType=backingType;
  }

  public void setBackingFilename(String backingFilename) {
    this.backingFilename=backingFilename;
  }
}


text:
// -----------------------------------------------------------------------
// Copyright (c) David Kean. All rights reserved.
// -----------------------------------------------------------------------
using System;

namespace AudioSwitcher.ComponentModel
{
    internal interface ILifetime<out T, TMetadata> : ILifetime<T>
    {
        TMetadata Metadata
        {
            get;
        }
    }
}


text:
To use [Discord](https://discord.com/), you need
to [create a Webhook](https://support.discord.com/hc/en-us/articles/228383668-Intro-to-Webhooks), and set following
environment variables on your pipeline:

- `DISCORD_WEBHOOK_ID`
- `DISCORD_WEBHOOK_TOKEN`

After this, you can add following section to your `.goreleaser.yaml` config:

```yaml
# .goreleaser.yaml
announce:
  discord:
    # Whether its enabled or not.
    # Defaults to false.
    enabled: true

    # Message template to use while publishing.
    # Defaults to `{{ .ProjectName }} {{ .Tag }} is out! Check it out at {{ .ReleaseURL }}`
    message_template: 'Awesome project {{.Tag}} is out!'

    # Set author of the embed.
    # Defaults to `GoReleaser`
    author: ''

    # Color code of the embed. You have to use decimal numeral system, not hexadecimal.
    # Defaults to `3888754` - the grey-ish from goreleaser
    color: ''

    # URL to an image to use as the icon for the embed.
    # Defaults to `https://goreleaser.com/static/avatar.png`
    icon_url: ''
```

!!! tip
    Learn more about the [name template engine](/customization/templates/).


text:
'use strict';

var should = require('chai').should(); // eslint-disable-line
var moment = require('moment');

describe('common', function() {
  var common = require('../../../lib/plugins/processor/common');

  it('isTmpFile()', function() {
    common.isTmpFile('foo').should.be.false;
    common.isTmpFile('foo%').should.be.true;
    common.isTmpFile('foo~').should.be.true;
  });

  it('isHiddenFile()', function() {
    common.isHiddenFile('foo').should.be.false;
    common.isHiddenFile('_foo').should.be.true;
    common.isHiddenFile('foo/_bar').should.be.true;
    common.isHiddenFile('.foo').should.be.true;
    common.isHiddenFile('foo/.bar').should.be.true;
  });

  it('ignoreTmpAndHiddenFile()', function() {
    var pattern = common.ignoreTmpAndHiddenFile;

    pattern.match('foo').should.be.true;
    pattern.match('foo%').should.be.false;
    pattern.match('foo~').should.be.false;
    pattern.match('_foo').should.be.false;
    pattern.match('foo/_bar').should.be.false;
    pattern.match('.foo').should.be.false;
    pattern.match('foo/.bar').should.be.false;
  });

  it('toDate()', function() {
    var m = moment();
    var d = new Date();

    should.not.exist(common.toDate());
    common.toDate(m).should.eql(m);
    common.toDate(d).should.eql(d);
    common.toDate(1e8).should.eql(new Date(1e8));
    common.toDate('2014-04-25T01:32:21.196Z').should.eql(new Date('2014-04-25T01:32:21.196Z'));
    common.toDate('Apr 24 2014').should.eql(new Date(2014, 3, 24));
    should.not.exist(common.toDate('foo'));
  });

  it('isMatch() - string', function() {
    // String
    common.isMatch('foo/test.html', 'foo/*.html').should.be.true;
    common.isMatch('foo/test.html', 'bar/*.html').should.be.false;

    // Array
    common.isMatch('foo/test.html', []).should.be.false;
    common.isMatch('foo/test.html', ['foo/*.html']).should.be.true;
    common.isMatch('foo/test.html', ['bar/*.html', 'foo/*.html']).should.be.true;
    common.isMatch('foo/test.html', ['bar/*.html', 'baz/*.html']).should.be.false;

    // Undefined
    common.isMatch('foo/test.html').should.be.false;
  });
});


text:
const express = require('express')
const router = express.Router();

const passport = require('passport');
const passportConfig = require('../config/passport');

/**
 * Controllers (route handlers).
 */
const homeController = require('../controllers/home');
const pricingController = require('../controllers/pricing');
const featuresController = require('../controllers/features');
const aboutController = require('../controllers/about');
const userController = require('../controllers/user');
const contactController = require('../controllers/contact');
const apiController = require('../controllers/api');

/**
 * Primary app routes.
 */
router.get('/', homeController.index);
router.get('/pricing', pricingController.getPricing);
router.get('/features', featuresController.getFeatures);
router.get('/about', aboutController.getAbout);
router.get('/login', userController.getLogin);
router.post('/login', userController.postLogin);
router.get('/logout', userController.logout);
router.get('/forgot', userController.getForgot);
router.post('/forgot', userController.postForgot);
router.get('/reset/:token', userController.getReset);
router.post('/reset/:token', userController.postReset);
router.get('/signup', userController.getSignup);
router.post('/signup', userController.postSignup);
router.get('/contact', contactController.getContact);
router.post('/contact', contactController.postContact);
router.get('/account', passportConfig.isAuthenticated, userController.getAccount);
router.post('/account/profile', passportConfig.isAuthenticated, userController.postUpdateProfile);
router.post('/account/password', passportConfig.isAuthenticated, userController.postUpdatePassword);
router.post('/account/delete', passportConfig.isAuthenticated, userController.postDeleteAccount);
router.get('/account/unlink/:provider', passportConfig.isAuthenticated, userController.getOauthUnlink);

module.exports = router;


text:
import { memo, useEffect, useRef, useState } from 'react'
import { createPortal } from 'react-dom'

const Portal = ({ id, children, zIndex }) => {
  const el = useRef(document.getElementById(id) || document.createElement('div'))
  const [dynamic] = useState(!el.current.parentElement)

  useEffect(() => {
    if (dynamic) {
      el.current.id = id
      zIndex && (el.current.style.zIndex = zIndex)
      document.body.appendChild(el.current)
    }
    return () => {
      if (dynamic && el.current.parentElement) {
        // eslint-disable-next-line react-hooks/exhaustive-deps
        el.current.parentElement.removeChild(el.current)
      }
    }
  }, [dynamic, id, zIndex])
  return createPortal(children, el.current)
}
export default memo(Portal)


text:
package org.apache.hadoop.hive.serde2.objectinspector;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import junit.framework.TestCase;

import org.apache.hadoop.hive.serde2.objectinspector.ObjectInspector.Category;
import org.apache.hadoop.hive.serde2.objectinspector.primitive.PrimitiveObjectInspectorFactory;
import org.apache.hadoop.hive.serde2.thrift.test.Complex;
import org.apache.hadoop.hive.serde2.thrift.test.IntString;

/**
 * TestObjectInspectorUtils.
 *
 */
public class TestObjectInspectorUtils extends TestCase {

  public void testObjectInspectorUtils() throws Throwable {
    try {
      ObjectInspector oi1 = ObjectInspectorFactory
          .getReflectionObjectInspector(Complex.class,
          ObjectInspectorFactory.ObjectInspectorOptions.THRIFT);

      // metadata
      assertEquals(Category.STRUCT, oi1.getCategory());
      // standard ObjectInspector
      StructObjectInspector soi = (StructObjectInspector) ObjectInspectorUtils
          .getStandardObjectInspector(oi1);
      List<? extends StructField> fields = soi.getAllStructFieldRefs();
      assertEquals(10, fields.size());
      assertEquals(fields.get(0), soi.getStructFieldRef("aint"));

      // null
      for (int i = 0; i < fields.size(); i++) {
        assertNull(soi.getStructFieldData(null, fields.get(i)));
      }

      // real object
      Complex cc = new Complex();
      cc.setAint(1);
      cc.setAString("test");
      List<Integer> c2 = Arrays.asList(new Integer[] {1, 2, 3});
      cc.setLint(c2);
      List<String> c3 = Arrays.asList(new String[] {"one", "two"});
      cc.setLString(c3);
      List<IntString> c4 = new ArrayList<IntString>();
      cc.setLintString(c4);
      cc.setMStringString(null);
      // standard object
      Object c = ObjectInspectorUtils.copyToStandardObject(cc, oi1);

      assertEquals(1, soi.getStructFieldData(c, fields.get(0)));
      assertEquals("test", soi.getStructFieldData(c, fields.get(1)));
      assertEquals(c2, soi.getStructFieldData(c, fields.get(2)));
      assertEquals(c3, soi.getStructFieldData(c, fields.get(3)));
      assertEquals(c4, soi.getStructFieldData(c, fields.get(4)));
      assertNull(soi.getStructFieldData(c, fields.get(5)));
      ArrayList<Object> cfields = new ArrayList<Object>();
      for (int i = 0; i < 10; i++) {
        cfields.add(soi.getStructFieldData(c, fields.get(i)));
      }
      assertEquals(cfields, soi.getStructFieldsDataAsList(c));

      // sub fields
      assertEquals(PrimitiveObjectInspectorFactory.javaIntObjectInspector,
          fields.get(0).getFieldObjectInspector());
      assertEquals(PrimitiveObjectInspectorFactory.javaStringObjectInspector,
          fields.get(1).getFieldObjectInspector());
      assertEquals(
          ObjectInspectorFactory
          .getStandardListObjectInspector(PrimitiveObjectInspectorFactory.javaIntObjectInspector),
          fields.get(2).getFieldObjectInspector());
      assertEquals(
          ObjectInspectorFactory
              .getStandardListObjectInspector(PrimitiveObjectInspectorFactory.javaStringObjectInspector),
          fields.get(3).getFieldObjectInspector());
      assertEquals(ObjectInspectorUtils
          .getStandardObjectInspector(ObjectInspectorFactory
          .getStandardListObjectInspector(ObjectInspectorFactory
          .getReflectionObjectInspector(IntString.class,
          ObjectInspectorFactory.ObjectInspectorOptions.THRIFT))),
          fields.get(4).getFieldObjectInspector());
      assertEquals(ObjectInspectorFactory.getStandardMapObjectInspector(
          PrimitiveObjectInspectorFactory.javaStringObjectInspector,
          PrimitiveObjectInspectorFactory.javaStringObjectInspector), fields
          .get(5).getFieldObjectInspector());
    } catch (Throwable e) {
      e.printStackTrace();
      throw e;
    }

  }
}


text:
// Copyright 2019 Open Source Robotics Foundation, Inc.
// Copyright 2016-2018 Proyectos y Sistemas de Mantenimiento SL (eProsima).
//
// 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.

#ifndef RMW_FASTRTPS_SHARED_CPP__QOS_HPP_
#define RMW_FASTRTPS_SHARED_CPP__QOS_HPP_

#include <fastdds/dds/core/policy/QosPolicies.hpp>
#include <fastdds/dds/publisher/qos/DataWriterQos.hpp>
#include <fastdds/dds/subscriber/qos/DataReaderQos.hpp>
#include <fastdds/dds/topic/qos/TopicQos.hpp>

#include "fastrtps/qos/QosPolicies.h"

#include "rmw/rmw.h"

#include "rmw_fastrtps_shared_cpp/visibility_control.h"

RMW_FASTRTPS_SHARED_CPP_PUBLIC
bool
is_valid_qos(const rmw_qos_profile_t & qos_policies);

RMW_FASTRTPS_SHARED_CPP_PUBLIC
bool
get_datareader_qos(
  const rmw_qos_profile_t & qos_policies,
  eprosima::fastdds::dds::DataReaderQos & reader_qos);

RMW_FASTRTPS_SHARED_CPP_PUBLIC
bool
get_datawriter_qos(
  const rmw_qos_profile_t & qos_policies,
  eprosima::fastdds::dds::DataWriterQos & writer_qos);

RMW_FASTRTPS_SHARED_CPP_PUBLIC
bool
get_topic_qos(
  const rmw_qos_profile_t & qos_policies,
  eprosima::fastdds::dds::TopicQos & topic_qos);

RMW_FASTRTPS_SHARED_CPP_PUBLIC
rmw_time_t
dds_duration_to_rmw(const eprosima::fastrtps::Duration_t & duration);

/*
 * Converts the DDS QOS Policy; of type DataWriterQos or DataReaderQos into rmw_qos_profile_t.
 *
 * \param[in] dds_qos of type DataWriterQos or DataReaderQos
 * \param[out] qos the equivalent of the data in dds_qos as a rmw_qos_profile_t
 */
template<typename DDSQoSPolicyT>
void
dds_qos_to_rmw_qos(
  const DDSQoSPolicyT & dds_qos,
  rmw_qos_profile_t * qos)
{
  switch (dds_qos.reliability().kind) {
    case eprosima::fastdds::dds::BEST_EFFORT_RELIABILITY_QOS:
      qos->reliability = RMW_QOS_POLICY_RELIABILITY_BEST_EFFORT;
      break;
    case eprosima::fastdds::dds::RELIABLE_RELIABILITY_QOS:
      qos->reliability = RMW_QOS_POLICY_RELIABILITY_RELIABLE;
      break;
    default:
      qos->reliability = RMW_QOS_POLICY_RELIABILITY_UNKNOWN;
      break;
  }

  switch (dds_qos.durability().kind) {
    case eprosima::fastdds::dds::TRANSIENT_LOCAL_DURABILITY_QOS:
      qos->durability = RMW_QOS_POLICY_DURABILITY_TRANSIENT_LOCAL;
      break;
    case eprosima::fastdds::dds::VOLATILE_DURABILITY_QOS:
      qos->durability = RMW_QOS_POLICY_DURABILITY_VOLATILE;
      break;
    default:
      qos->durability = RMW_QOS_POLICY_DURABILITY_UNKNOWN;
      break;
  }

  qos->deadline = dds_duration_to_rmw(dds_qos.deadline().period);
  qos->lifespan = dds_duration_to_rmw(dds_qos.lifespan().duration);

  switch (dds_qos.liveliness().kind) {
    case eprosima::fastdds::dds::AUTOMATIC_LIVELINESS_QOS:
      qos->liveliness = RMW_QOS_POLICY_LIVELINESS_AUTOMATIC;
      break;
    case eprosima::fastdds::dds::MANUAL_BY_TOPIC_LIVELINESS_QOS:
      qos->liveliness = RMW_QOS_POLICY_LIVELINESS_MANUAL_BY_TOPIC;
      break;
    default:
      qos->liveliness = RMW_QOS_POLICY_LIVELINESS_UNKNOWN;
      break;
  }

  qos->liveliness_lease_duration = dds_duration_to_rmw(dds_qos.liveliness().lease_duration);

  switch (dds_qos.history().kind) {
    case eprosima::fastdds::dds::KEEP_LAST_HISTORY_QOS:
      qos->history = RMW_QOS_POLICY_HISTORY_KEEP_LAST;
      break;
    case eprosima::fastdds::dds::KEEP_ALL_HISTORY_QOS:
      qos->history = RMW_QOS_POLICY_HISTORY_KEEP_ALL;
      break;
    default:
      qos->history = RMW_QOS_POLICY_HISTORY_UNKNOWN;
      break;
  }
  qos->depth = static_cast<size_t>(dds_qos.history().depth);
}

/*
 * Converts the RTPS QOS Policy; of type WriterQos or ReaderQos into rmw_qos_profile_t.
 * Since WriterQos or ReaderQos do not have information about history and depth,
 * these values are not set by this function.
 *
 * \param[in] rtps_qos of type WriterQos or ReaderQos
 * \param[out] qos the equivalent of the data in rtps_qos as a rmw_qos_profile_t
 */
template<typename RTPSQoSPolicyT>
void
rtps_qos_to_rmw_qos(
  const RTPSQoSPolicyT & rtps_qos,
  rmw_qos_profile_t * qos)
{
  switch (rtps_qos.m_reliability.kind) {
    case eprosima::fastrtps::BEST_EFFORT_RELIABILITY_QOS:
      qos->reliability = RMW_QOS_POLICY_RELIABILITY_BEST_EFFORT;
      break;
    case eprosima::fastrtps::RELIABLE_RELIABILITY_QOS:
      qos->reliability = RMW_QOS_POLICY_RELIABILITY_RELIABLE;
      break;
    default:
      qos->reliability = RMW_QOS_POLICY_RELIABILITY_UNKNOWN;
      break;
  }

  switch (rtps_qos.m_durability.kind) {
    case eprosima::fastrtps::TRANSIENT_LOCAL_DURABILITY_QOS:
      qos->durability = RMW_QOS_POLICY_DURABILITY_TRANSIENT_LOCAL;
      break;
    case eprosima::fastrtps::VOLATILE_DURABILITY_QOS:
      qos->durability = RMW_QOS_POLICY_DURABILITY_VOLATILE;
      break;
    default:
      qos->durability = RMW_QOS_POLICY_DURABILITY_UNKNOWN;
      break;
  }

  qos->deadline = dds_duration_to_rmw(rtps_qos.m_deadline.period);
  qos->lifespan = dds_duration_to_rmw(rtps_qos.m_lifespan.duration);

  switch (rtps_qos.m_liveliness.kind) {
    case eprosima::fastrtps::AUTOMATIC_LIVELINESS_QOS:
      qos->liveliness = RMW_QOS_POLICY_LIVELINESS_AUTOMATIC;
      break;
    case eprosima::fastrtps::MANUAL_BY_TOPIC_LIVELINESS_QOS:
      qos->liveliness = RMW_QOS_POLICY_LIVELINESS_MANUAL_BY_TOPIC;
      break;
    default:
      qos->liveliness = RMW_QOS_POLICY_LIVELINESS_UNKNOWN;
      break;
  }
  qos->liveliness_lease_duration = dds_duration_to_rmw(rtps_qos.m_liveliness.lease_duration);
}

extern template RMW_FASTRTPS_SHARED_CPP_PUBLIC
void dds_qos_to_rmw_qos<eprosima::fastdds::dds::DataWriterQos>(
  const eprosima::fastdds::dds::DataWriterQos & dds_qos,
  rmw_qos_profile_t * qos);

extern template RMW_FASTRTPS_SHARED_CPP_PUBLIC
void dds_qos_to_rmw_qos<eprosima::fastdds::dds::DataReaderQos>(
  const eprosima::fastdds::dds::DataReaderQos & dds_qos,
  rmw_qos_profile_t * qos);

template<typename AttributeT>
void
dds_attributes_to_rmw_qos(
  const AttributeT & dds_qos,
  rmw_qos_profile_t * qos);

extern template RMW_FASTRTPS_SHARED_CPP_PUBLIC
void
dds_attributes_to_rmw_qos<eprosima::fastrtps::PublisherAttributes>(
  const eprosima::fastrtps::PublisherAttributes & dds_qos,
  rmw_qos_profile_t * qos);

extern template RMW_FASTRTPS_SHARED_CPP_PUBLIC
void
dds_attributes_to_rmw_qos<eprosima::fastrtps::SubscriberAttributes>(
  const eprosima::fastrtps::SubscriberAttributes & dds_qos,
  rmw_qos_profile_t * qos);

#endif  // RMW_FASTRTPS_SHARED_CPP__QOS_HPP_


text:
describe('Test', function() {
    it('shoul redirect ot sign in page', function() {
        browser.get('http://localhost:3000/#!/');

        element(by.linkText('Sign In')).click();

        var usernameInput = element(by.id('username'));
        expect(usernameInput.isPresent()).toBe(true);
    });
});


text:
<?php
namespace AulaLoPati\BlogBundle\Entity;

use Doctrine\ORM\Mapping as ORM;
use Symfony\Component\Validator\Constraints as Assert;
use Doctrine\Common\Collections\ArrayCollection;
use Vich\UploaderBundle\Mapping\Annotation as Vich;
use AulaLoPati\BlogBundle\Util\Util;
use Symfony\Bridge\Doctrine\Validator\Constraints\UniqueEntity;

/**
 * @ORM\Entity
 * @ORM\HasLifecycleCallbacks
 * @UniqueEntity("titol")
 * @Vich\Uploadable
 */
class Presentacio {

	/**
	 * @ORM\Id
	 * @ORM\Column(type="integer")
	 * @ORM\GeneratedValue
	 */
	protected $id;

	/** @ORM\Column(type="string", length=50, nullable=true) */
	protected $tipus;

	/**
	 * @ORM\Column(type="string", length=255,nullable=true)
	 *
	 */
	protected $titol;

	/**
	 * @ORM\Column(type="text",nullable=true)
	 *
	 */
	protected $slug;

	/**
	 * @ORM\Column(type="text", nullable=true)
	 *
	 */
	protected $resum = null;

	/**
	 * @ORM\Column(type="text")
	 *
	 */
	protected $descripcio;

	/**
	 * @ORM\Column(type="text", nullable=true)
	  */
	protected $links;

	/** @ORM\Column(type="boolean", nullable=true) */
	protected $actiu = FALSE;

	/** @ORM\Column(type="boolean", nullable=true) */
	protected $portada = FALSE;

	/** @ORM\Column(type="boolean", nullable=true) */
	protected $compartir = FALSE;

	/** @ORM\Column(type="date", nullable=true) */
	protected $data_publicacio;

	/** @ORM\Column(type="boolean", nullable=true) */
	protected $data_visible = FALSE;

	/** @ORM\Column(type="date", nullable=true) */
	protected $data_caducitat = null;

	/**
	 * @ORM\Column(type="string", length=255, nullable=true )
	 *
	 */
	protected $data_realitzacio = NULL;

	/**
	 * @ORM\Column(type="string", length=250, nullable=true)
	 *
	 */
	protected $lloc = NULL;

    /**
     * @ORM\Column(type="date",nullable=true)
     *
     */
    protected $updatedAt= NULL;

	/**
	 * @ORM\Column(type="string", length=255, nullable=true )
	 */
	protected $video = NULL;

	/**
	 * @ORM\Column(type="string", length=255, nullable=true )
	 */
	protected $urlVimeo = NULL;

	/**
	 * @ORM\Column(type="string", length=255, nullable=true )
	 */
	protected $urlFlickr = NULL;

	/**
	 * @Assert\File(
	 *     maxSize="1M",
	 *     mimeTypes={"image/png", "image/jpeg", "image/pjpeg"}
	 * )
	 * @Vich\UploadableField(mapping="imatge", fileNameProperty="imagePetitaName")
	 *
	 * @var File $imagePetita
	 */
	protected $imagePetita;

	/**
	 * @ORM\Column(type="string", length=255, name="image_petita_name", nullable=true)
	 *
	 * @var string $imagePetitaName
	 */
	protected $imagePetitaName;

	/**
	 * @Assert\File(
	 *     maxSize="1M",
	 *     mimeTypes={"image/png", "image/jpeg", "image/pjpeg"}
	 * )
	 * @Vich\UploadableField(mapping="imatge", fileNameProperty="imagePetita2Name")
	 *
	 * @var File $imagePetita2
	 */
	protected $imagePetita2;

	/**
	 * @ORM\Column(type="string", length=255, name="image_petita2_name", nullable=true)
	 *
	 * @var string $imagePetita2Name
	 */
	protected $imagePetita2Name;

	/**
	 * @Assert\File(
	 *     maxSize="1M",
	 *     mimeTypes={"image/png", "image/jpeg", "image/pjpeg"}
	 * )
	 * @Vich\UploadableField(mapping="imatge", fileNameProperty="imageGran1Name")
	 *
	 * @var File $imageGran1
	 */
	protected $imageGran1;

	/**
	 * @ORM\Column(type="string", length=255, name="image_gran1_name", nullable=true)
	 *
	 * @var string $imageGran1Name
	 */
	protected $imageGran1Name;

	/**
	 * @ORM\Column(type="string", length=255, nullable=true)
	 *
	 */
	protected $peuImageGran1;
	/////////////////////////////

	/**
	 * @Assert\File(
	 *     maxSize="25M"
	 *
	 * )
	 * @Vich\UploadableField(mapping="pdf", fileNameProperty="document1Name")
	 *
	 * @var File $document1
	 */
	private $document1;

	/**
	 * @ORM\Column(type="string", length=255, name="document1_name", nullable=true)
	 *
	 * @var string $document1Name
	 */
	protected $document1Name;

	/**
	 * @ORM\Column(type="string", length=255, nullable=true)
	 */
	protected $titolDocument1;

	public function getVideo() {
		return $this->video;
	}

	public function setVideo($filename) {
		$this->video=$filename;
	}

    public function getUpdatedAt() {
        return $this->updatedAt;
    }

    public function setUpdatedAt($filename) {
        $this->updatedAt=$filename;
    }
	public function getUrlVimeo() {
		return $this->urlVimeo;
	}

	public function setUrlVimeo($filename) {
		$this->urlVimeo=$filename;
	}

	public function getUrlFlickr() {
		return $this->urlFlickr;
	}

	public function setUrlFlickr($filename) {
		$this->urlFlickr=$filename;
	}

	public function getDocument1() {
		return $this->document1;
	}

	public function setDocument1($filename) {
		$this->document1=$filename;
	}

	public function getDocument1Name() {
		return $this->document1Name;
	}

	public function setDocument1Name($file) {
		$this->document1Name=$file;
	}

	public function getTitolDocument1() {
		return $this->titolDocument1;
	}

	public function setTitolDocument1($file) {
		$this->titolDocument1=$file;
	}

	////////////////////////////////

	public function getLinks() {
		return $this->links;
	}

	public function setLinks($file) {
		$this->links=$file;
	}

	/**
	 * @Assert\File(
	 *     maxSize="25M"
	 * )
	 * @Vich\UploadableField(mapping="pdf", fileNameProperty="document2Name")
	 *
	 * @var File $document2
	 */
	private $document2;

	/**
	 * @ORM\Column(type="string", length=255, name="document2_name", nullable=true)
	 *
	 * @var string $document2Name
	 */
	protected $document2Name;

	/**
	 * @ORM\Column(type="string", length=255, nullable=true)
	 */
	protected $titolDocument2;

	public function getDocument2() {
		return $this->document2;
	}

	public function setDocument2($filename) {
		$this->document2=$filename;
	}

	public function getDocument2Name() {
		return $this->document2Name;
	}

	public function setDocument2Name($file) {
		$this->document2Name=$file;
	}

	public function getTitolDocument2() {
		return $this->titolDocument2;
	}

	public function setTitolDocument2($file) {
		$this->titolDocument2=$file;
	}

	/////////////////////

	public function getPeuImageGran1() {
		return $this->peuImageGran1;
	}

	public function setPeuImageGran1($file) {
		$this->peuImageGran1=$file;

	}

	public function getImageGran1Name() {
		return $this->imageGran1Name;
	}

	public function setImageGran1Name($filename) {
		$this->imageGran1Name=$filename;

	}

	public function getImageGran1() {
		return $this->imageGran1;
	}

	public function setImageGran1($file) {

		$this->imageGran1=$file;

	}

	public function getImagePetitaName() {
		return $this->imagePetitaName;
	}

	public function setImagePetitaName($filename) {
		$this->imagePetitaName=$filename;
	}

	public function getImagePetita() {
		return $this->imagePetita;
	}

	public function setImagePetita($file) {
		$this->imagePetita=$file;
	}

	public function getImagePetita2() {
		return $this->imagePetita2;
	}

	public function setImagePetita2($file) {
		$this->imagePetita2=$file;
	}

	public function getImagePetita2Name() {
		return $this->imagePetita2Name;
	}

	public function setImagePetita2Name($filename) {
		$this->imagePetita2Name=$filename;
	}
	public function __construct() {
		$this->ponencies = new \Doctrine\Common\Collections\ArrayCollection();
	}

	/**
	 * Set translations
	 * @param ArrayCollection $translations
	 * @return Product
	 */
	public function setTranslations($translations) {
		$this->translations = $translations;
		return $this;
	}

	/**
	 * Get translations
	 * @return ArrayCollection
	 */
	public function getTranslations() {
		return $this->translations;
	}

	/**
	 * Get id
	 * @return integer
	 */
	public function getId() {
		return $this->id;
	}

	/**
	 * Set tipus
	 *
	 * @param string $tipus
	 */
	public function setTipus($tipus) {
		$this->tipus = $tipus;
	}

	/**
	 * Get tipus
	 * @return string
	 */
	public function getTipus() {
		return $this->tipus;
	}

	public function setArxiu($tipus) {
		$this->arxiu = $tipus;
	}

	public function getArxiu() {
		return $this->arxiu;
	}

	/**
	 * Set titol
	 *
	 * @param string $titol
	 */
	public function setTitol($titol) {
		$this->titol = $titol;
		$this->slug=Util::getSlug($this->titol);

	}

	/**
	 * Get titol
	 *
	 * @return string
	 */
	public function getTitol() {
		return $this->titol;
	}

	public function setSlug($titol) {

		$this->slug=$titol;

	}

	/**
	 * Get titol
	 *
	 * @return string
	 */
	public function getSlug() {
		return $this->slug;
	}

	/**
	 * Set resum
	 *
	 * @param text $resum
	 */
	public function setResum($resum) {
		$this->resum = $resum;
	}

	/**
	 * Get resum
	 *
	 * @return text
	 */
	public function getResum() {
		return $this->resum;
	}

	public function __toString() {
		return 'Presentació';
	}

	/**
	 * Set descripcio
	 *
	 * @param text $descripcio
	 */
	public function setDescripcio($descripcio) {
		$this->descripcio = $descripcio;
	}

	/**
	 * Get descripcio
	 *
	 * @return text
	 */
	public function getDescripcio() {
		return $this->descripcio;
	}

	/**
	 * Set actiu
	 *
	 * @param boolean $actiu
	 */
	public function setActiu($actiu) {
		$this->actiu = $actiu;
	}

	/**
	 * Get actiu
	 *
	 * @return boolean
	 */
	public function getActiu() {
		return $this->actiu;
	}

	/**
	 * Set portada
	 *
	 * @param boolean $portada
	 */
	public function setPortada($portada) {
		$this->portada = $portada;
	}

	/**
	 * Get portada
	 *
	 * @return boolean
	 */
	public function getPortada() {
		return $this->portada;
	}

	/**
	 * Set data_publicacio
	 *
	 * @param date $dataPublicacio
	 */
	public function setDataPublicacio($dataPublicacio) {
		$this->data_publicacio = $dataPublicacio;
	}

	/**
	 * Get data_publicacio
	 *
	 * @return date
	 */
	public function getDataPublicacio() {
		return $this->data_publicacio;
	}

	/**
	 * Set data_visible
	 *
	 * @param boolean $dataVisible
	 */
	public function setDataVisible($dataVisible) {
		$this->data_visible = $dataVisible;
	}

	/**
	 * Get data_visible
	 *
	 * @return boolean
	 */
	public function getDataVisible() {
		return $this->data_visible;
	}

	/**
	 * Set data_caducitat
	 *
	 * @param date $dataCaducitat
	 */
	public function setDataCaducitat($dataCaducitat) {
		$this->data_caducitat = $dataCaducitat;
	}

	/**
	 * Get data_caducitat
	 *
	 * @return date
	 */
	public function getDataCaducitat() {
		return $this->data_caducitat;
	}

	/**
	 * Set data_realitzacio
	 *
	 * @param string $dataRealitzacio
	 */
	public function setDataRealitzacio($dataRealitzacio) {
		$this->data_realitzacio = $dataRealitzacio;
	}

	/**
	 * Get data_realitzacio
	 *
	 * @return string
	 */
	public function getDataRealitzacio() {
		return $this->data_realitzacio;
	}

	/**
	 * Set lloc
	 *
	 * @param string $lloc
	 */
	public function setLloc($lloc) {
		$this->lloc = $lloc;
	}

	/**
	 * Get lloc
	 *
	 * @return string
	 */
	public function getLloc() {
		return $this->lloc;
	}

	/**
	 * Set data_caducita
	 *
	 * @param date $dataCaducita
	 */
	public function setDataCaducita($dataCaducita) {
		$this->data_caducita = $dataCaducita;
	}

	/**
	 * Set compartir
	 *
	 * @param boolean $compartir
	 * @return Pagina
	 */
	public function setCompartir($compartir) {
		$this->compartir = $compartir;
		return $this;
	}

	/**
	 * Get compartir
	 *
	 * @return boolean
	 */
	public function getCompartir() {
		return $this->compartir;
	}

	public function setLocale($locale) {
		$this->locale = $locale;

	}

	/**
	 * Get compartir
	 *
	 * @return boolean
	 */
	public function getLocale() {
		return $this->locale;
	}

	public function addPonencies(\AulaLoPati\BlogBundle\Entity\Ponencia $ponencies)
	{
		$this->ponencies[] = $ponencies;
	}

	public function getPonencies()
	{
		return $this->ponencies;
	}
	public function setPonencies($translations)
	{
		$this->ponencies = $translations;
		return $this;
	}
}


text:
// Copyright 2000-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.testIntegration;

import com.intellij.codeInsight.TestFrameworks;
import com.intellij.execution.ExecutionBundle;
import com.intellij.execution.TestStateStorage;
import com.intellij.execution.lineMarker.ExecutorAction;
import com.intellij.execution.lineMarker.RunLineMarkerContributor;
import com.intellij.psi.PsiClass;
import com.intellij.psi.PsiElement;
import com.intellij.psi.PsiIdentifier;
import com.intellij.psi.PsiMethod;
import com.intellij.psi.util.ClassUtil;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;

/**
 * @author Dmitry Avdeev
 */
public class TestRunLineMarkerProvider extends RunLineMarkerContributor {
  @Nullable
  @Override
  public Info getInfo(@NotNull PsiElement e) {
    if (isIdentifier(e)) {
      PsiElement element = e.getParent();
      if (element instanceof PsiClass) {
        TestFramework framework = TestFrameworks.detectFramework((PsiClass)element);
        if (framework != null && framework.isTestClass(element)) {
          String url = "java:suite://" + ClassUtil.getJVMClassName((PsiClass)element);
          TestStateStorage.Record state = TestStateStorage.getInstance(e.getProject()).getState(url);
          return getInfo(state, true);
        }
      }
      if (element instanceof PsiMethod) {
        TestFailedLineManager.TestInfo testInfo = TestFailedLineManager.getInstance(e.getProject()).getTestInfo((PsiMethod)element);
        return testInfo == null ? null : getInfo(testInfo.myRecord, false);
      }
    }
    return null;
  }

  @NotNull
  private static Info getInfo(TestStateStorage.Record state, boolean isClass) {
    return new Info(getTestStateIcon(state, isClass), ExecutorAction.getActions(1), element -> ExecutionBundle.message("run.text"));
  }

  protected boolean isIdentifier(PsiElement e) {
    return e instanceof PsiIdentifier;
  }
}