text:
package com.amazonaws.services.servicecatalog.model.transform;

import java.util.List;
import javax.annotation.Generated;

import com.amazonaws.SdkClientException;
import com.amazonaws.services.servicecatalog.model.*;

import com.amazonaws.protocol.*;
import com.amazonaws.annotation.SdkInternalApi;

/**
 * ProvisionedProductPlanDetailsMarshaller
 */
@Generated("com.amazonaws:aws-java-sdk-code-generator")
@SdkInternalApi
public class ProvisionedProductPlanDetailsMarshaller {

    private static final MarshallingInfo<java.util.Date> CREATEDTIME_BINDING = MarshallingInfo.builder(MarshallingType.DATE)
            .marshallLocation(MarshallLocation.PAYLOAD).marshallLocationName("CreatedTime").timestampFormat("unixTimestamp").build();
    private static final MarshallingInfo<String> PATHID_BINDING = MarshallingInfo.builder(MarshallingType.STRING).marshallLocation(MarshallLocation.PAYLOAD)
            .marshallLocationName("PathId").build();
    private static final MarshallingInfo<String> PRODUCTID_BINDING = MarshallingInfo.builder(MarshallingType.STRING).marshallLocation(MarshallLocation.PAYLOAD)
            .marshallLocationName("ProductId").build();
    private static final MarshallingInfo<String> PLANNAME_BINDING = MarshallingInfo.builder(MarshallingType.STRING).marshallLocation(MarshallLocation.PAYLOAD)
            .marshallLocationName("PlanName").build();
    private static final MarshallingInfo<String> PLANID_BINDING = MarshallingInfo.builder(MarshallingType.STRING).marshallLocation(MarshallLocation.PAYLOAD)
            .marshallLocationName("PlanId").build();
    private static final MarshallingInfo<String> PROVISIONPRODUCTID_BINDING = MarshallingInfo.builder(MarshallingType.STRING)
            .marshallLocation(MarshallLocation.PAYLOAD).marshallLocationName("ProvisionProductId").build();
    private static final MarshallingInfo<String> PROVISIONPRODUCTNAME_BINDING = MarshallingInfo.builder(MarshallingType.STRING)
            .marshallLocation(MarshallLocation.PAYLOAD).marshallLocationName("ProvisionProductName").build();
    private static final MarshallingInfo<String> PLANTYPE_BINDING = MarshallingInfo.builder(MarshallingType.STRING).marshallLocation(MarshallLocation.PAYLOAD)
            .marshallLocationName("PlanType").build();
    private static final MarshallingInfo<String> PROVISIONINGARTIFACTID_BINDING = MarshallingInfo.builder(MarshallingType.STRING)
            .marshallLocation(MarshallLocation.PAYLOAD).marshallLocationName("ProvisioningArtifactId").build();
    private static final MarshallingInfo<String> STATUS_BINDING = MarshallingInfo.builder(MarshallingType.STRING).marshallLocation(MarshallLocation.PAYLOAD)
            .marshallLocationName("Status").build();
    private static final MarshallingInfo<java.util.Date> UPDATEDTIME_BINDING = MarshallingInfo.builder(MarshallingType.DATE)
            .marshallLocation(MarshallLocation.PAYLOAD).marshallLocationName("UpdatedTime").timestampFormat("unixTimestamp").build();
    private static final MarshallingInfo<List> NOTIFICATIONARNS_BINDING = MarshallingInfo.builder(MarshallingType.LIST)
            .marshallLocation(MarshallLocation.PAYLOAD).marshallLocationName("NotificationArns").build();
    private static final MarshallingInfo<List> PROVISIONINGPARAMETERS_BINDING = MarshallingInfo.builder(MarshallingType.LIST)
            .marshallLocation(MarshallLocation.PAYLOAD).marshallLocationName("ProvisioningParameters").build();
    private static final MarshallingInfo<List> TAGS_BINDING = MarshallingInfo.builder(MarshallingType.LIST).marshallLocation(MarshallLocation.PAYLOAD)
            .marshallLocationName("Tags").build();
    private static final MarshallingInfo<String> STATUSMESSAGE_BINDING = MarshallingInfo.builder(MarshallingType.STRING)
            .marshallLocation(MarshallLocation.PAYLOAD).marshallLocationName("StatusMessage").build();

    private static final ProvisionedProductPlanDetailsMarshaller instance = new ProvisionedProductPlanDetailsMarshaller();

    public static ProvisionedProductPlanDetailsMarshaller getInstance() {
        return instance;
    }

    /**
     * Marshall the given parameter object.
     */
    public void marshall(ProvisionedProductPlanDetails provisionedProductPlanDetails, ProtocolMarshaller protocolMarshaller) {

        if (provisionedProductPlanDetails == null) {
            throw new SdkClientException("Invalid argument passed to marshall(...)");
        }

        try {
            protocolMarshaller.marshall(provisionedProductPlanDetails.getCreatedTime(), CREATEDTIME_BINDING);
            protocolMarshaller.marshall(provisionedProductPlanDetails.getPathId(), PATHID_BINDING);
            protocolMarshaller.marshall(provisionedProductPlanDetails.getProductId(), PRODUCTID_BINDING);
            protocolMarshaller.marshall(provisionedProductPlanDetails.getPlanName(), PLANNAME_BINDING);
            protocolMarshaller.marshall(provisionedProductPlanDetails.getPlanId(), PLANID_BINDING);
            protocolMarshaller.marshall(provisionedProductPlanDetails.getProvisionProductId(), PROVISIONPRODUCTID_BINDING);
            protocolMarshaller.marshall(provisionedProductPlanDetails.getProvisionProductName(), PROVISIONPRODUCTNAME_BINDING);
            protocolMarshaller.marshall(provisionedProductPlanDetails.getPlanType(), PLANTYPE_BINDING);
            protocolMarshaller.marshall(provisionedProductPlanDetails.getProvisioningArtifactId(), PROVISIONINGARTIFACTID_BINDING);
            protocolMarshaller.marshall(provisionedProductPlanDetails.getStatus(), STATUS_BINDING);
            protocolMarshaller.marshall(provisionedProductPlanDetails.getUpdatedTime(), UPDATEDTIME_BINDING);
            protocolMarshaller.marshall(provisionedProductPlanDetails.getNotificationArns(), NOTIFICATIONARNS_BINDING);
            protocolMarshaller.marshall(provisionedProductPlanDetails.getProvisioningParameters(), PROVISIONINGPARAMETERS_BINDING);
            protocolMarshaller.marshall(provisionedProductPlanDetails.getTags(), TAGS_BINDING);
            protocolMarshaller.marshall(provisionedProductPlanDetails.getStatusMessage(), STATUSMESSAGE_BINDING);
        } catch (Exception e) {
            throw new SdkClientException("Unable to marshall request to JSON: " + e.getMessage(), e);
        }
    }

}


text:
package com.lzx.demo.fragment;

import android.support.v7.widget.RecyclerView;
import android.view.MenuItem;
import android.view.MotionEvent;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;

import com.github.jdsjlzx.recyclerview.LRecyclerViewAdapter;
import com.lzx.demo.ItemDecoration.StickyHeaderDecoration;
import com.lzx.demo.R;
import com.lzx.demo.adapter.StickyTestAdapter;

public class StickyHeaderFragment extends BaseDecorationFragment implements RecyclerView.OnItemTouchListener{

    private StickyHeaderDecoration decor;

    @Override
    protected void setAdapterAndDecor(RecyclerView list) {
        final StickyTestAdapter adapter = new StickyTestAdapter(this.getActivity());
        decor = new StickyHeaderDecoration(adapter);
        setHasOptionsMenu(true);

        mLRecyclerViewAdapter = new LRecyclerViewAdapter(adapter);
        list.setAdapter(mLRecyclerViewAdapter);

        list.addItemDecoration(decor, 1);
        list.addOnItemTouchListener(this);

    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        if (item.getItemId() == R.id.action_clear_cache) {
            decor.clearHeaderCache();
            return true;
        }

        return super.onOptionsItemSelected(item);
    }

    @Override
    public boolean onInterceptTouchEvent(RecyclerView rv, MotionEvent e) {
        // really bad click detection just for demonstration purposes
        // it will not allow the list to scroll if the swipe motion starts
        // on top of a header
        View v = rv.findChildViewUnder(e.getX(), e.getY());
        return v == null;
//        return rv.findChildViewUnder(e.getX(), e.getY()) != null;
    }

    @Override
    public void onTouchEvent(RecyclerView rv, MotionEvent e) {
        // only use the "UP" motion event, discard all others
        if (e.getAction() != MotionEvent.ACTION_UP) {
            return;
        }

        // find the header that was clicked
        View view = decor.findHeaderViewUnder(e.getX(), e.getY());

        if (view instanceof TextView) {
            Toast.makeText(this.getActivity(), ((TextView) view).getText() + " clicked", Toast.LENGTH_SHORT).show();
        }
    }

    @Override
    public void onRequestDisallowInterceptTouchEvent(boolean disallowIntercept) {
        // do nothing
    }

}

redpajama_set_name: RedPajamaGithub


text:
using System;
using System.Threading.Tasks;
using Memoriser.App.Commands;
using Moq;

namespace Memoriser.UnitTests.API
{
    public class MockCommandHandler<TCommand> where TCommand : ICommand
    {
        private readonly Mock<IAsyncCommandHandler<TCommand>> _mock;
        private bool _setupCalled;

        public MockCommandHandler<TCommand> ReturnsForAll()
        {
            _mock.Setup(x => x.HandleAsync(It.IsAny<TCommand>())).Returns(Task.FromResult(0));
            _setupCalled = true;
            return this;
        }
        public IAsyncCommandHandler<TCommand> Handler
        {
            get
            {
                if (!_setupCalled)
                {
                    throw new InvalidOperationException("Tried to get handler before being setup.");
                }
                return _mock.Object;
            }
        }

        public MockCommandHandler()
        {
            _mock = new Mock<IAsyncCommandHandler<TCommand>>();
        }
    }
}


text:
<?php

namespace SMW\Tests\Query\ProfileAnnotator;

use SMW\Tests\Utils\UtilityFactory;

use SMW\Query\ProfileAnnotator\DurationProfileAnnotator;
use SMW\Query\ProfileAnnotator\NullProfileAnnotator;
use SMW\Subobject;
use SMW\DIWikiPage;

/**
 * @covers \SMW\Query\ProfileAnnotator\DurationProfileAnnotator
 * @group semantic-mediawiki
 *
 * @license GNU GPL v2+
 * @since 1.9
 *
 * @author mwjames
 */
class DurationProfileAnnotatorTest extends \PHPUnit_Framework_TestCase {

	private $semanticDataValidator;

	protected function setUp() {
		parent::setUp();

		$this->semanticDataValidator = UtilityFactory::getInstance()->newValidatorFactory()->newSemanticDataValidator();
	}

	public function testCanConstruct() {

		$profileAnnotator = $this->getMockBuilder( '\SMW\Query\ProfileAnnotator\ProfileAnnotator' )
			->disableOriginalConstructor()
			->getMock();

		$this->assertInstanceOf(
			'\SMW\Query\ProfileAnnotator\DurationProfileAnnotator',
			new DurationProfileAnnotator( $profileAnnotator, 0.42 )
		);
	}

	/**
	 * @dataProvider durationDataProvider
	 */
	public function testCreateProfile( $duration, $expected ) {

		$profiler = new NullProfileAnnotator(
			new Subobject( DIWikiPage::newFromText( __METHOD__ )->getTitle() ),
			'foo'
		);

		$instance = new DurationProfileAnnotator( $profiler, $duration );
		$instance->addAnnotation();

		$this->semanticDataValidator->assertThatPropertiesAreSet(
			$expected,
			$instance->getContainer()->getSemanticData()
		);
	}

	public function durationDataProvider() {

		$provider = array();

		$provider[] = array( 0, array(
			'propertyCount' => 0
		) );

		$provider[] = array( 0.9001, array(
			'propertyCount'  => 1,
			'propertyKeys'   => array( '_ASKDU' ),
			'propertyValues' => array( 0.9001 )
		) );

		return $provider;
	}

}


text:
LinkService
===========

A simple web service for reduction options written on Node.JS & Redis

Installation :

1. Download files from git repository
2. sudo npm i
3. Done!


text:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="@color/gray"
    android:orientation="vertical"
    android:paddingTop="10dp">

    <com.android.library.widget.JTextView
        android:id="@+id/tvTitle"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:background="@color/white"
        android:ellipsize="end"
        android:paddingBottom="13dp"
        android:paddingLeft="20dp"
        android:paddingRight="20dp"
        android:paddingTop="13dp"
        android:singleLine="true"
        android:textColor="@color/black_trans54"
        android:textSize="14dp" />

    <com.joy.app.view.LinearListView
        android:id="@+id/linearLv"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:background="@color/white"
        android:focusable="false"
        android:listSelector="@android:color/transparent"
        android:orientation="vertical"
        android:scrollingCache="false" />

</LinearLayout>


text:
DOCKER_IMAGE := docker.io/kanboard/kanboard
DOCKER_TAG := master
VERSION := $(shell git rev-parse --short HEAD)

.PHONY: archive test-sqlite test-mysql test-postgres sql \
	docker-image docker-images docker-run docker-sh

archive:
	@ echo "Build archive: version=$(VERSION)"
	@ git archive --format=zip --prefix=kanboard/ $(VERSION) -o kanboard-$(VERSION).zip

test-sqlite:
	@ ./vendor/bin/phpunit -c tests/units.sqlite.xml

test-mysql:
	@ ./vendor/bin/phpunit -c tests/units.mysql.xml

test-postgres:
	@ ./vendor/bin/phpunit -c tests/units.postgres.xml

sql:
	@ pg_dump --schema-only --no-owner --no-privileges --quote-all-identifiers -n public --file app/Schema/Sql/postgres.sql kanboard
	@ pg_dump -d kanboard --column-inserts --data-only --table settings >> app/Schema/Sql/postgres.sql
	@ pg_dump -d kanboard --column-inserts --data-only --table links >> app/Schema/Sql/postgres.sql

	@ mysqldump -uroot --quote-names --no-create-db --skip-comments --no-data --single-transaction kanboard | sed 's/ AUTO_INCREMENT=[0-9]*//g' > app/Schema/Sql/mysql.sql
	@ mysqldump -uroot --quote-names --no-create-info --skip-comments --no-set-names kanboard settings >> app/Schema/Sql/mysql.sql
	@ mysqldump -uroot --quote-names --no-create-info --skip-comments --no-set-names kanboard links >> app/Schema/Sql/mysql.sql

	@ let password_hash=`php -r "echo password_hash('admin', PASSWORD_DEFAULT);"` ;\
	echo "INSERT INTO users (username, password, role) VALUES ('admin', '$$password_hash', 'app-admin');" >> app/Schema/Sql/mysql.sql ;\
	echo "INSERT INTO public.users (username, password, role) VALUES ('admin', '$$password_hash', 'app-admin');" >> app/Schema/Sql/postgres.sql

	@ let mysql_version=`echo 'select version from schema_version;' | mysql -N -uroot kanboard` ;\
	echo "INSERT INTO schema_version VALUES ('$$mysql_version');" >> app/Schema/Sql/mysql.sql

	@ let pg_version=`psql -U postgres -A -c 'copy(select version from schema_version) to stdout;' kanboard` ;\
	echo "INSERT INTO public.schema_version VALUES ('$$pg_version');" >> app/Schema/Sql/postgres.sql

	@ grep -v "SET idle_in_transaction_session_timeout = 0;" app/Schema/Sql/postgres.sql > temp && mv temp app/Schema/Sql/postgres.sql

docker-image:
	@ docker build --build-arg VERSION=master.$(VERSION) -t $(DOCKER_IMAGE):$(DOCKER_TAG) .

docker-images:
	docker buildx build \
		--platform linux/amd64,linux/arm64,linux/arm/v7,linux/arm/v6 \
		--file Dockerfile \
		--build-arg VERSION=master.$(VERSION) \
		--tag $(DOCKER_IMAGE):$(VERSION) \
		.

docker-run:
	@ docker run --rm --name=kanboard -p 80:80 -p 443:443 $(DOCKER_IMAGE):$(DOCKER_TAG)

docker-sh:
	@ docker exec -ti kanboard bash


text:
use super::FnCtxt;
use crate::astconv::AstConv;

use rustc_ast::util::parser::ExprPrecedence;
use rustc_span::{self, MultiSpan, Span};

use rustc_errors::{Applicability, DiagnosticBuilder};
use rustc_hir as hir;
use rustc_hir::def::{CtorOf, DefKind};
use rustc_hir::lang_items::LangItem;
use rustc_hir::{Expr, ExprKind, ItemKind, Node, Path, QPath, Stmt, StmtKind, TyKind};
use rustc_infer::infer;
use rustc_middle::lint::in_external_macro;
use rustc_middle::ty::{self, Binder, Ty};
use rustc_span::symbol::{kw, sym};

use rustc_middle::ty::subst::GenericArgKind;
use std::iter;

impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
    pub(in super::super) fn suggest_semicolon_at_end(
        &self,
        span: Span,
        err: &mut DiagnosticBuilder<'_>,
    ) {
        err.span_suggestion_short(
            span.shrink_to_hi(),
            "consider using a semicolon here",
            ";".to_string(),
            Applicability::MachineApplicable,
        );
    }

    /// On implicit return expressions with mismatched types, provides the following suggestions:
    ///
    /// - Points out the method's return type as the reason for the expected type.
    /// - Possible missing semicolon.
    /// - Possible missing return type if the return type is the default, and not `fn main()`.
    pub fn suggest_mismatched_types_on_tail(
        &self,
        err: &mut DiagnosticBuilder<'_>,
        expr: &'tcx hir::Expr<'tcx>,
        expected: Ty<'tcx>,
        found: Ty<'tcx>,
        blk_id: hir::HirId,
    ) -> bool {
        let expr = expr.peel_drop_temps();
        // If the expression is from an external macro, then do not suggest
        // adding a semicolon, because there's nowhere to put it.
        // See issue #81943.
        if expr.can_have_side_effects() && !in_external_macro(self.tcx.sess, expr.span) {
            self.suggest_missing_semicolon(err, expr, expected);
        }
        let mut pointing_at_return_type = false;
        if let Some((fn_decl, can_suggest)) = self.get_fn_decl(blk_id) {
            let fn_id = self.tcx.hir().get_return_block(blk_id).unwrap();
            pointing_at_return_type = self.suggest_missing_return_type(
                err,
                &fn_decl,
                expected,
                found,
                can_suggest,
                fn_id,
            );
            self.suggest_missing_break_or_return_expr(
                err, expr, &fn_decl, expected, found, blk_id, fn_id,
            );
        }
        pointing_at_return_type
    }

    /// When encountering an fn-like ctor that needs to unify with a value, check whether calling
    /// the ctor would successfully solve the type mismatch and if so, suggest it:
    /// ```
    /// fn foo(x: usize) -> usize { x }
    /// let x: usize = foo;  // suggest calling the `foo` function: `foo(42)`
    /// ```
    fn suggest_fn_call(
        &self,
        err: &mut DiagnosticBuilder<'_>,
        expr: &hir::Expr<'_>,
        expected: Ty<'tcx>,
        found: Ty<'tcx>,
    ) -> bool {
        let hir = self.tcx.hir();
        let (def_id, sig) = match *found.kind() {
            ty::FnDef(def_id, _) => (def_id, found.fn_sig(self.tcx)),
            ty::Closure(def_id, substs) => (def_id, substs.as_closure().sig()),
            _ => return false,
        };

        let sig = self.replace_bound_vars_with_fresh_vars(expr.span, infer::FnCall, sig).0;
        let sig = self.normalize_associated_types_in(expr.span, sig);
        if self.can_coerce(sig.output(), expected) {
            let (mut sugg_call, applicability) = if sig.inputs().is_empty() {
                (String::new(), Applicability::MachineApplicable)
            } else {
                ("...".to_string(), Applicability::HasPlaceholders)
            };
            let mut msg = "call this function";
            match hir.get_if_local(def_id) {
                Some(
                    Node::Item(hir::Item { kind: ItemKind::Fn(.., body_id), .. })
                    | Node::ImplItem(hir::ImplItem {
                        kind: hir::ImplItemKind::Fn(_, body_id), ..
                    })
                    | Node::TraitItem(hir::TraitItem {
                        kind: hir::TraitItemKind::Fn(.., hir::TraitFn::Provided(body_id)),
                        ..
                    }),
                ) => {
                    let body = hir.body(*body_id);
                    sugg_call = body
                        .params
                        .iter()
                        .map(|param| match &param.pat.kind {
                            hir::PatKind::Binding(_, _, ident, None)
                                if ident.name != kw::SelfLower =>
                            {
                                ident.to_string()
                            }
                            _ => "_".to_string(),
                        })
                        .collect::<Vec<_>>()
                        .join(", ");
                }
                Some(Node::Expr(hir::Expr {
                    kind: ExprKind::Closure(_, _, body_id, _, _),
                    span: full_closure_span,
                    ..
                })) => {
                    if *full_closure_span == expr.span {
                        return false;
                    }
                    msg = "call this closure";
                    let body = hir.body(*body_id);
                    sugg_call = body
                        .params
                        .iter()
                        .map(|param| match &param.pat.kind {
                            hir::PatKind::Binding(_, _, ident, None)
                                if ident.name != kw::SelfLower =>
                            {
                                ident.to_string()
                            }
                            _ => "_".to_string(),
                        })
                        .collect::<Vec<_>>()
                        .join(", ");
                }
                Some(Node::Ctor(hir::VariantData::Tuple(fields, _))) => {
                    sugg_call = fields.iter().map(|_| "_").collect::<Vec<_>>().join(", ");
                    match def_id.as_local().map(|def_id| hir.def_kind(def_id)) {
                        Some(DefKind::Ctor(hir::def::CtorOf::Variant, _)) => {
                            msg = "instantiate this tuple variant";
                        }
                        Some(DefKind::Ctor(CtorOf::Struct, _)) => {
                            msg = "instantiate this tuple struct";
                        }
                        _ => {}
                    }
                }
                Some(Node::ForeignItem(hir::ForeignItem {
                    kind: hir::ForeignItemKind::Fn(_, idents, _),
                    ..
                })) => {
                    sugg_call = idents
                        .iter()
                        .map(|ident| {
                            if ident.name != kw::SelfLower {
                                ident.to_string()
                            } else {
                                "_".to_string()
                            }
                        })
                        .collect::<Vec<_>>()
                        .join(", ")
                }
                Some(Node::TraitItem(hir::TraitItem {
                    kind: hir::TraitItemKind::Fn(.., hir::TraitFn::Required(idents)),
                    ..
                })) => {
                    sugg_call = idents
                        .iter()
                        .map(|ident| {
                            if ident.name != kw::SelfLower {
                                ident.to_string()
                            } else {
                                "_".to_string()
                            }
                        })
                        .collect::<Vec<_>>()
                        .join(", ")
                }
                _ => {}
            }
            err.span_suggestion_verbose(
                expr.span.shrink_to_hi(),
                &format!("use parentheses to {}", msg),
                format!("({})", sugg_call),
                applicability,
            );
            return true;
        }
        false
    }

    pub fn suggest_deref_ref_or_into(
        &self,
        err: &mut DiagnosticBuilder<'_>,
        expr: &hir::Expr<'_>,
        expected: Ty<'tcx>,
        found: Ty<'tcx>,
        expected_ty_expr: Option<&'tcx hir::Expr<'tcx>>,
    ) {
        let expr = expr.peel_blocks();
        if let Some((sp, msg, suggestion, applicability, verbose)) =
            self.check_ref(expr, found, expected)
        {
            if verbose {
                err.span_suggestion_verbose(sp, msg, suggestion, applicability);
            } else {
                err.span_suggestion(sp, msg, suggestion, applicability);
            }
        } else if let (ty::FnDef(def_id, ..), true) =
            (&found.kind(), self.suggest_fn_call(err, expr, expected, found))
        {
            if let Some(sp) = self.tcx.hir().span_if_local(*def_id) {
                let sp = self.sess().source_map().guess_head_span(sp);
                err.span_label(sp, &format!("{} defined here", found));
            }
        } else if !self.check_for_cast(err, expr, found, expected, expected_ty_expr) {
            let is_struct_pat_shorthand_field =
                self.is_hir_id_from_struct_pattern_shorthand_field(expr.hir_id, expr.span);
            let methods = self.get_conversion_methods(expr.span, expected, found, expr.hir_id);
            if !methods.is_empty() {
                if let Ok(expr_text) = self.sess().source_map().span_to_snippet(expr.span) {
                    let mut suggestions = iter::zip(iter::repeat(&expr_text), &methods)
                        .filter_map(|(receiver, method)| {
                            let method_call = format!(".{}()", method.ident);
                            if receiver.ends_with(&method_call) {
                                None // do not suggest code that is already there (#53348)
                            } else {
                                let method_call_list = [".to_vec()", ".to_string()"];
                                let mut sugg = if receiver.ends_with(".clone()")
                                    && method_call_list.contains(&method_call.as_str())
                                {
                                    let max_len = receiver.rfind('.').unwrap();
                                    vec![(
                                        expr.span,
                                        format!("{}{}", &receiver[..max_len], method_call),
                                    )]
                                } else {
                                    if expr.precedence().order()
                                        < ExprPrecedence::MethodCall.order()
                                    {
                                        vec![
                                            (expr.span.shrink_to_lo(), "(".to_string()),
                                            (expr.span.shrink_to_hi(), format!("){}", method_call)),
                                        ]
                                    } else {
                                        vec![(expr.span.shrink_to_hi(), method_call)]
                                    }
                                };
                                if is_struct_pat_shorthand_field {
                                    sugg.insert(
                                        0,
                                        (expr.span.shrink_to_lo(), format!("{}: ", receiver)),
                                    );
                                }
                                Some(sugg)
                            }
                        })
                        .peekable();
                    if suggestions.peek().is_some() {
                        err.multipart_suggestions(
                            "try using a conversion method",
                            suggestions,
                            Applicability::MaybeIncorrect,
                        );
                    }
                }
            } else if found.to_string().starts_with("Option<")
                && expected.to_string() == "Option<&str>"
            {
                if let ty::Adt(_def, subst) = found.kind() {
                    if subst.len() != 0 {
                        if let GenericArgKind::Type(ty) = subst[0].unpack() {
                            let peeled = ty.peel_refs().to_string();
                            if peeled == "String" {
                                let ref_cnt = ty.to_string().len() - peeled.len();
                                let result = format!(".map(|x| &*{}x)", "*".repeat(ref_cnt));
                                err.span_suggestion_verbose(
                                    expr.span.shrink_to_hi(),
                                    "try converting the passed type into a `&str`",
                                    result,
                                    Applicability::MaybeIncorrect,
                                );
                            }
                        }
                    }
                }
            }
        }
    }

    /// When encountering the expected boxed value allocated in the stack, suggest allocating it
    /// in the heap by calling `Box::new()`.
    pub(in super::super) fn suggest_boxing_when_appropriate(
        &self,
        err: &mut DiagnosticBuilder<'_>,
        expr: &hir::Expr<'_>,
        expected: Ty<'tcx>,
        found: Ty<'tcx>,
    ) {
        if self.tcx.hir().is_inside_const_context(expr.hir_id) {
            // Do not suggest `Box::new` in const context.
            return;
        }
        if !expected.is_box() || found.is_box() {
            return;
        }
        let boxed_found = self.tcx.mk_box(found);
        if self.can_coerce(boxed_found, expected) {
            err.multipart_suggestion(
                "store this in the heap by calling `Box::new`",
                vec![
                    (expr.span.shrink_to_lo(), "Box::new(".to_string()),
                    (expr.span.shrink_to_hi(), ")".to_string()),
                ],
                Applicability::MachineApplicable,
            );
            err.note(
                "for more on the distinction between the stack and the heap, read \
                 https://doc.rust-lang.org/book/ch15-01-box.html, \
                 https://doc.rust-lang.org/rust-by-example/std/box.html, and \
                 https://doc.rust-lang.org/std/boxed/index.html",
            );
        }
    }

    /// When encountering a closure that captures variables, where a FnPtr is expected,
    /// suggest a non-capturing closure
    pub(in super::super) fn suggest_no_capture_closure(
        &self,
        err: &mut DiagnosticBuilder<'_>,
        expected: Ty<'tcx>,
        found: Ty<'tcx>,
    ) {
        if let (ty::FnPtr(_), ty::Closure(def_id, _)) = (expected.kind(), found.kind()) {
            if let Some(upvars) = self.tcx.upvars_mentioned(*def_id) {
                // Report upto four upvars being captured to reduce the amount error messages
                // reported back to the user.
                let spans_and_labels = upvars
                    .iter()
                    .take(4)
                    .map(|(var_hir_id, upvar)| {
                        let var_name = self.tcx.hir().name(*var_hir_id).to_string();
                        let msg = format!("`{}` captured here", var_name);
                        (upvar.span, msg)
                    })
                    .collect::<Vec<_>>();

                let mut multi_span: MultiSpan =
                    spans_and_labels.iter().map(|(sp, _)| *sp).collect::<Vec<_>>().into();
                for (sp, label) in spans_and_labels {
                    multi_span.push_span_label(sp, label);
                }
                err.span_note(
                    multi_span,
                    "closures can only be coerced to `fn` types if they do not capture any variables"
                );
            }
        }
    }

    /// When encountering an `impl Future` where `BoxFuture` is expected, suggest `Box::pin`.
    #[instrument(skip(self, err))]
    pub(in super::super) fn suggest_calling_boxed_future_when_appropriate(
        &self,
        err: &mut DiagnosticBuilder<'_>,
        expr: &hir::Expr<'_>,
        expected: Ty<'tcx>,
        found: Ty<'tcx>,
    ) -> bool {
        // Handle #68197.

        if self.tcx.hir().is_inside_const_context(expr.hir_id) {
            // Do not suggest `Box::new` in const context.
            return false;
        }
        let pin_did = self.tcx.lang_items().pin_type();
        // This guards the `unwrap` and `mk_box` below.
        if pin_did.is_none() || self.tcx.lang_items().owned_box().is_none() {
            return false;
        }
        let box_found = self.tcx.mk_box(found);
        let pin_box_found = self.tcx.mk_lang_item(box_found, LangItem::Pin).unwrap();
        let pin_found = self.tcx.mk_lang_item(found, LangItem::Pin).unwrap();
        match expected.kind() {
            ty::Adt(def, _) if Some(def.did) == pin_did => {
                if self.can_coerce(pin_box_found, expected) {
                    debug!("can coerce {:?} to {:?}, suggesting Box::pin", pin_box_found, expected);
                    match found.kind() {
                        ty::Adt(def, _) if def.is_box() => {
                            err.help("use `Box::pin`");
                        }
                        _ => {
                            err.multipart_suggestion(
                                "you need to pin and box this expression",
                                vec![
                                    (expr.span.shrink_to_lo(), "Box::pin(".to_string()),
                                    (expr.span.shrink_to_hi(), ")".to_string()),
                                ],
                                Applicability::MaybeIncorrect,
                            );
                        }
                    }
                    true
                } else if self.can_coerce(pin_found, expected) {
                    match found.kind() {
                        ty::Adt(def, _) if def.is_box() => {
                            err.help("use `Box::pin`");
                            true
                        }
                        _ => false,
                    }
                } else {
                    false
                }
            }
            ty::Adt(def, _) if def.is_box() && self.can_coerce(box_found, expected) => {
                // Check if the parent expression is a call to Pin::new.  If it
                // is and we were expecting a Box, ergo Pin<Box<expected>>, we
                // can suggest Box::pin.
                let parent = self.tcx.hir().get_parent_node(expr.hir_id);
                let fn_name = match self.tcx.hir().find(parent) {
                    Some(Node::Expr(Expr { kind: ExprKind::Call(fn_name, _), .. })) => fn_name,
                    _ => return false,
                };
                match fn_name.kind {
                    ExprKind::Path(QPath::TypeRelative(
                        hir::Ty {
                            kind: TyKind::Path(QPath::Resolved(_, Path { res: recv_ty, .. })),
                            ..
                        },
                        method,
                    )) if recv_ty.opt_def_id() == pin_did && method.ident.name == sym::new => {
                        err.span_suggestion(
                            fn_name.span,
                            "use `Box::pin` to pin and box this expression",
                            "Box::pin".to_string(),
                            Applicability::MachineApplicable,
                        );
                        true
                    }
                    _ => false,
                }
            }
            _ => false,
        }
    }

    /// A common error is to forget to add a semicolon at the end of a block, e.g.,
    ///
    /// ```
    /// fn foo() {
    ///     bar_that_returns_u32()
    /// }
    /// ```
    ///
    /// This routine checks if the return expression in a block would make sense on its own as a
    /// statement and the return type has been left as default or has been specified as `()`. If so,
    /// it suggests adding a semicolon.
    fn suggest_missing_semicolon(
        &self,
        err: &mut DiagnosticBuilder<'_>,
        expression: &'tcx hir::Expr<'tcx>,
        expected: Ty<'tcx>,
    ) {
        if expected.is_unit() {
            // `BlockTailExpression` only relevant if the tail expr would be
            // useful on its own.
            match expression.kind {
                ExprKind::Call(..)
                | ExprKind::MethodCall(..)
                | ExprKind::Loop(..)
                | ExprKind::If(..)
                | ExprKind::Match(..)
                | ExprKind::Block(..)
                    if expression.can_have_side_effects() =>
                {
                    err.span_suggestion(
                        expression.span.shrink_to_hi(),
                        "consider using a semicolon here",
                        ";".to_string(),
                        Applicability::MachineApplicable,
                    );
                }
                _ => (),
            }
        }
    }

    /// A possible error is to forget to add a return type that is needed:
    ///
    /// ```
    /// fn foo() {
    ///     bar_that_returns_u32()
    /// }
    /// ```
    ///
    /// This routine checks if the return type is left as default, the method is not part of an
    /// `impl` block and that it isn't the `main` method. If so, it suggests setting the return
    /// type.
    pub(in super::super) fn suggest_missing_return_type(
        &self,
        err: &mut DiagnosticBuilder<'_>,
        fn_decl: &hir::FnDecl<'_>,
        expected: Ty<'tcx>,
        found: Ty<'tcx>,
        can_suggest: bool,
        fn_id: hir::HirId,
    ) -> bool {
        // Only suggest changing the return type for methods that
        // haven't set a return type at all (and aren't `fn main()` or an impl).
        match (&fn_decl.output, found.is_suggestable(), can_suggest, expected.is_unit()) {
            (&hir::FnRetTy::DefaultReturn(span), true, true, true) => {
                err.span_suggestion(
                    span,
                    "try adding a return type",
                    format!("-> {} ", self.resolve_vars_with_obligations(found)),
                    Applicability::MachineApplicable,
                );
                true
            }
            (&hir::FnRetTy::DefaultReturn(span), false, true, true) => {
                err.span_label(span, "possibly return type missing here?");
                true
            }
            (&hir::FnRetTy::DefaultReturn(span), _, false, true) => {
                // `fn main()` must return `()`, do not suggest changing return type
                err.span_label(span, "expected `()` because of default return type");
                true
            }
            // expectation was caused by something else, not the default return
            (&hir::FnRetTy::DefaultReturn(_), _, _, false) => false,
            (&hir::FnRetTy::Return(ref ty), _, _, _) => {
                // Only point to return type if the expected type is the return type, as if they
                // are not, the expectation must have been caused by something else.
                debug!("suggest_missing_return_type: return type {:?} node {:?}", ty, ty.kind);
                let sp = ty.span;
                let ty = <dyn AstConv<'_>>::ast_ty_to_ty(self, ty);
                debug!("suggest_missing_return_type: return type {:?}", ty);
                debug!("suggest_missing_return_type: expected type {:?}", ty);
                let bound_vars = self.tcx.late_bound_vars(fn_id);
                let ty = Binder::bind_with_vars(ty, bound_vars);
                let ty = self.normalize_associated_types_in(sp, ty);
                let ty = self.tcx.erase_late_bound_regions(ty);
                if self.can_coerce(expected, ty) {
                    err.span_label(sp, format!("expected `{}` because of return type", expected));
                    return true;
                }
                false
            }
        }
    }

    pub(in super::super) fn suggest_missing_break_or_return_expr(
        &self,
        err: &mut DiagnosticBuilder<'_>,
        expr: &'tcx hir::Expr<'tcx>,
        fn_decl: &hir::FnDecl<'_>,
        expected: Ty<'tcx>,
        found: Ty<'tcx>,
        id: hir::HirId,
        fn_id: hir::HirId,
    ) {
        if !expected.is_unit() {
            return;
        }
        let found = self.resolve_vars_with_obligations(found);

        let in_loop = self.is_loop(id)
            || self.tcx.hir().parent_iter(id).any(|(parent_id, _)| self.is_loop(parent_id));

        let in_local_statement = self.is_local_statement(id)
            || self
                .tcx
                .hir()
                .parent_iter(id)
                .any(|(parent_id, _)| self.is_local_statement(parent_id));

        if in_loop && in_local_statement {
            err.multipart_suggestion(
                "you might have meant to break the loop with this value",
                vec![
                    (expr.span.shrink_to_lo(), "break ".to_string()),
                    (expr.span.shrink_to_hi(), ";".to_string()),
                ],
                Applicability::MaybeIncorrect,
            );
            return;
        }

        if let hir::FnRetTy::Return(ty) = fn_decl.output {
            let ty = <dyn AstConv<'_>>::ast_ty_to_ty(self, ty);
            let bound_vars = self.tcx.late_bound_vars(fn_id);
            let ty = self.tcx.erase_late_bound_regions(Binder::bind_with_vars(ty, bound_vars));
            let ty = self.normalize_associated_types_in(expr.span, ty);
            if self.can_coerce(found, ty) {
                err.multipart_suggestion(
                    "you might have meant to return this value",
                    vec![
                        (expr.span.shrink_to_lo(), "return ".to_string()),
                        (expr.span.shrink_to_hi(), ";".to_string()),
                    ],
                    Applicability::MaybeIncorrect,
                );
            }
        }
    }

    pub(in super::super) fn suggest_missing_parentheses(
        &self,
        err: &mut DiagnosticBuilder<'_>,
        expr: &hir::Expr<'_>,
    ) {
        let sp = self.tcx.sess.source_map().start_point(expr.span);
        if let Some(sp) = self.tcx.sess.parse_sess.ambiguous_block_expr_parse.borrow().get(&sp) {
            // `{ 42 } &&x` (#61475) or `{ 42 } && if x { 1 } else { 0 }`
            self.tcx.sess.parse_sess.expr_parentheses_needed(err, *sp);
        }
    }

    fn is_loop(&self, id: hir::HirId) -> bool {
        let node = self.tcx.hir().get(id);
        matches!(node, Node::Expr(Expr { kind: ExprKind::Loop(..), .. }))
    }

    fn is_local_statement(&self, id: hir::HirId) -> bool {
        let node = self.tcx.hir().get(id);
        matches!(node, Node::Stmt(Stmt { kind: StmtKind::Local(..), .. }))
    }
}


text:
require 'test_helper'

module Gingerr
  class AppStatsTest < ActiveSupport::TestCase
    setup do
      app = gingerr_apps(:app_elephant)
      @stats = Gingerr::AppStats.new(app)
    end

    test 'shows chart data for recent signals' do
      data = @stats.recent_signals_timeline
      assert_equal :error, data.first[:name]
      assert_equal :success, data.last[:name]
      data.each do |data_record|
        data_record[:data].each do |date, count|
          assert_kind_of Date, date
          assert count >= 0
        end
      end
    end
  end
end


text:
package com.jreaper.common.validation;

import java.util.Collections;
import java.util.Set;

/**
 * Created by zarubin on 17.10.2014.
 */
public class ValidationResult {

    /**
     * Validation result with no errors
     */
    public static final ValidationResult EMPTY = new ValidationResult(Collections.<ValidationError> emptySet());

    private final Set<ValidationError> errors;

    /**
     * Creates {@link ValidationResult} instance setting a set of validation
     * errors, which afterwards can be retrieved using {@link #getErrors()}. For
     * {@link ValidationResult} with no errors use {@link #EMPTY}.
     *
     * @param errors set with validation errors
     */
    public ValidationResult(Set<ValidationError> errors) {
        this.errors = errors;
    }

    /**
     * Creates {@link ValidationResult} instance with one error
     *
     * @param error validation error
     */
    public ValidationResult(ValidationError error) {
        this(Collections.singleton(error));
    }

    /**
     * Should be called only after {@link #validate(Entity)}
     * @return {@code false} if there's no error, {@code true} otherwise
     */
    public boolean hasErrors() {
        return !errors.isEmpty();
    }

    /**
     * Should be called only after {@link #validate(Entity)}. Before calling,
     * make sure that there is a error by invoking {@link #hasErrors()}.
     * @return specified error message or null if there's none
     */
    public Set<ValidationError> getErrors() {
        return errors;
    }
}


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Sockets;
using System.Text;
using System.Threading.Tasks;
using System.Threading;

namespace TCPClientForDotNetFramework
{
    public class TCPClient
    {
        TcpClient client;

        NetworkStream nstream;

        public event Action ConnectionClosed;

        public TCPClient()
        {
            client = new TcpClient(AddressFamily.InterNetwork);
        }

        object nstreamlock = new object();

        /// <summary>
        /// Kết nối tới server. Exception được bắn khi gặp lỗi
        /// </summary>
        /// <param name="host">Tên hoặc IP của host</param>
        /// <param name="port">Port của host</param>
        /// <returns></returns>
        public async Task ConnectAsync(string host, int port)
        {
            Monitor.Enter(nstreamlock);
            try
            {
                client.Close();
                client = new TcpClient();
                await client.ConnectAsync(host, port);
                nstream = client.GetStream();
            }
            catch
            {
                Monitor.Exit(nstreamlock);
                throw;
            }
            Monitor.Exit(nstreamlock);
        }

        public void CloseConnection()
        {
            Monitor.Enter(nstreamlock);
            OnConnectionClosed();
            Monitor.Exit(nstreamlock);
        }

        public Task<bool> SendAsync(byte[] buffers)
        {
            return Task.Run(new Func<bool>(() =>
            {
                // nếu bên ngoài có 2 thread gọi hàm này thì nó sẽ được xử lí đồng bộ
                Monitor.Enter(nstreamlock);
                bool result = Send(buffers);
                Monitor.Exit(nstreamlock);
                return result;
            }));
        }

        private bool Send(byte[] buffers)
        {
            // khai báo một mảng byte có số byte > item 4 ô
            byte[] send = new byte[buffers.Length + 4];

            // đưa độ dài của item về dạng bytes rồi copy vào send
            Buffer.BlockCopy(BitConverter.GetBytes(buffers.Length), 0, send, 0, 4);

            // copy dữ liệu còn lại vào send
            Buffer.BlockCopy(buffers, 0, send, 4, buffers.Length);

            // gửi đồng bộ
            try
            {
                nstream.Write(send, 0, send.Length);
            }
            catch
            {
                OnConnectionClosed();
                return false;
            }
            return true;
        }

        private byte[] Receive()
        {
            int size = sizeof(int);
            byte[] data;

            // đọc request từ buffer
            // đọc 4 byte đầu tiên vào data để biết kích thước gói tin
            data = new byte[size];
            try
            {
                nstream.Read(data, 0, size);
                if (data.Length == 0)
                {
                    OnConnectionClosed();
                    return null;
                }
                size = BitConverter.ToInt32(data, 0);

                data = new byte[size];

                nstream.Read(data, 0, size);
                if (data.Length == 0)
                {
                    OnConnectionClosed();
                    return null;
                }
                return data;
            }
            catch
            {
                OnConnectionClosed();
                return null;
            }
        }

        /// <summary>
        /// Gửi một số gói tin và đợi gói hồi đáp từ server
        /// </summary>
        /// <param name="buffers">gói trả về từ server</param>
        /// <returns></returns>
        public async Task<SendAndReceiveResult> SendAndReceiveAsync(byte[] buffer)
        {
            return await Task.Run(new Func<SendAndReceiveResult>(() =>
            {
                Monitor.Enter(nstreamlock);
                if (!Send(buffer)) // send không thành công
                {
                    return new SendAndReceiveResult(false, ErrorPoint.Sending, null);
                }
                byte[] data = Receive();
                if (data == null) // receive không thành công
                {
                    return new SendAndReceiveResult(false, ErrorPoint.Receiving, null);
                }
                Monitor.Exit(nstreamlock);
                return new SendAndReceiveResult(true, ErrorPoint.Sending, data);
            }));
        }

        private Task<byte[]> ReceiveAsync()
        {
            return Task.Run(new Func<byte[]>(() =>
            {
                Monitor.Enter(nstreamlock);
                int size = sizeof(int);
                byte[] data;

                // đọc request từ buffer
                // đọc 4 byte đầu tiên vào data để biết kích thước gói tin
                data = new byte[size];
                try
                {
                    nstream.Read(data, 0, size);
                    if (data.Length == 0)
                    {
                        OnConnectionClosed();
                        Monitor.Exit(nstreamlock);
                        return null;
                    }
                    size = BitConverter.ToInt32(data, 0);
                    data = new byte[size];
                    nstream.Read(data, 0, size);
                    if (data.Length == 0)
                    {
                        OnConnectionClosed();
                        Monitor.Exit(nstreamlock);
                        return null;
                    }
                    Monitor.Exit(nstreamlock);
                    return data;
                }
                catch
                {
                    OnConnectionClosed();
                    Monitor.Exit(nstreamlock);
                    return null;
                }
            }));
        }

        private void OnConnectionClosed()
        {
            nstream.Close();
            if (ConnectionClosed != null) ConnectionClosed();
        }
    }

    public class SendAndReceiveResult
    {
        public bool IsSuccess { get; private set; }
        public ErrorPoint ErrorPoint { get; private set; }
        public byte[] Data { get; private set; }

        internal SendAndReceiveResult(bool issuccess, ErrorPoint Point, byte[] data)
        {
            IsSuccess = issuccess;
            ErrorPoint = Point;
            Data = data;
        }
    }

    public enum ErrorPoint
    {
        Sending,
        Receiving,
    }
}


text:
title: Input Tag
---
## Input
HTML input tag can be included in HTML document like this:

```html
<input type="text">
```

This creates an area within which a user can easily enter information. This information is then sent to a back end database and stored or used further down within the website or application.

An input with "type='text'" will produce a single line field where any information can be entered. Other common types of inputs include but are not limited to: button, checkbox, color, email and password.

### The most common types used

* `text`: A single-line text field.

* `button`: A button with no default behavior.

* `submit`: A button that submits the form.

* `checkbox`: A check box allowing values to be selected/deselected.

* `date`:  For entering a date (year, month, and day).

* `email`: For editing an e-mail address.

* `file`: Lets the user select a file.

* `hidden`: Not displayed but its value is submitted to the server.

* `number`: For entering a number.

* `password`: A single-line text field whose value is obscured.

* `radio`: A radio button, allowing a single value to be selected out of multiple choices.

* `range`: A control for entering a number.

* `url`: For entering a URL.

Example:
```html
<input type="button">
<input type="checkbox">
<input type="color">
<input type="email">
<input type="password">
```

Inputs come with a lot of predetermined attributes.

Some commonly found attributes include autocomplete, checked and placeholder.

```html
<input type="text" placeholder="This is a placeholder">
```

In the above instance, an area within which input can be entered is rendered, with the placeholder stating "This is a placeholder". Once the input line is clicked and a key is pressed, the placeholder disappears and is replaced by your own input.

```html
<input type="checkbox" checked>
```

In this instance, a checkbox appears and it is checked by default due to the attribute 'checked'.

There are many different types of inputs and associated attributes that can all be found on the link found below.

#### More Information:
https://developer.mozilla.org/en-US/docs/Web/HTML/Element/input

https://www.w3schools.com/tags/tag_input.asp


text:
namespace Microsoft.JScript {

    using System;
    using System.Reflection;
    using System.Reflection.Emit;

    internal sealed class Constant : AST{
      internal FieldAttributes attributes;
      private Completion completion;
      internal CustomAttributeList customAttributes;
      internal JSVariableField field;
      private FieldBuilder valueField;
      private Lookup identifier;
      internal String name;
      internal AST value;

      internal Constant(Context context, Lookup identifier, TypeExpression type, AST value, FieldAttributes attributes, CustomAttributeList customAttributes)
        : base(context){
        this.attributes = attributes | FieldAttributes.InitOnly;
        this.customAttributes = customAttributes;
        this.completion = new Completion();
        this.identifier = identifier;
        this.name = identifier.ToString();
        this.value = value;
        ScriptObject current_scope = (ScriptObject)Globals.ScopeStack.Peek();
        while (current_scope is WithObject) //Can only happen at run time and only if there is an eval
          current_scope = current_scope.GetParent();
        if (current_scope is ClassScope){
          if (this.name == ((ClassScope)current_scope).name){
            identifier.context.HandleError(JSError.CannotUseNameOfClass);
            this.name = this.name + " const";
          }
          if (attributes == 0) attributes = FieldAttributes.Public;
        }else{
          if (attributes != 0)
            this.context.HandleError(JSError.NotInsideClass);
          attributes = FieldAttributes.Public;
        }
        FieldInfo field = ((IActivationObject)current_scope).GetLocalField(this.name);
        if (field != null){
          identifier.context.HandleError(JSError.DuplicateName, true);
          this.name = this.name + " const";
        }
        if (current_scope is ActivationObject)
          this.field = ((ActivationObject)current_scope).AddNewField(this.identifier.ToString(), value, attributes);
        else
          this.field = ((StackFrame)current_scope).AddNewField(this.identifier.ToString(), value, attributes|FieldAttributes.Static);
        this.field.type = type;
        this.field.customAttributes = customAttributes;
        this.field.originalContext = context;
        if (this.field is JSLocalField)
          // emit debug info for the local only if this block of code is in a section that has debug set
          ((JSLocalField)this.field).debugOn = this.identifier.context.document.debugOn;
      }

      internal override Object Evaluate(){
        if (this.value == null)
          this.completion.value = this.field.value;
        else
          this.completion.value = this.value.Evaluate();
        return this.completion;
      }

      internal override AST PartiallyEvaluate(){
        this.field.attributeFlags &= ~FieldAttributes.InitOnly;
        this.identifier.PartiallyEvaluateAsReference();
        if (this.field.type != null)
          this.field.type.PartiallyEvaluate();
        ScriptObject scope = (ScriptObject)Globals.ScopeStack.Peek();
        if (this.value != null){
          this.value = this.value.PartiallyEvaluate();
          this.identifier.SetPartialValue(this.value);
          if (this.value is ConstantWrapper){
            Object val = this.field.value = this.value.Evaluate();
            if (this.field.type != null) this.field.value = Convert.Coerce(val, this.field.type, true);
            if (this.field.IsStatic && (val is Type || val is ClassScope || val is TypedArray ||
                Convert.GetTypeCode(val) != TypeCode.Object)){
              this.field.attributeFlags |= FieldAttributes.Literal;
              goto set_field_type;
            }
          }
          this.field.attributeFlags |= FieldAttributes.InitOnly;
        set_field_type:
          if (this.field.type == null)
            this.field.type = new TypeExpression(new ConstantWrapper(this.value.InferType(null), null));
        }else{
          this.value = new ConstantWrapper(null, this.context);
          this.field.attributeFlags |= FieldAttributes.InitOnly;
        }
        // deal with custom attributes
        if (this.field != null && this.field.customAttributes != null)
          this.field.customAttributes.PartiallyEvaluate();
        return this;
      }

      internal override void TranslateToIL(ILGenerator il, Type rtype){
        if ((this.field.attributeFlags & FieldAttributes.Literal) != 0){
          Object val = this.field.value;
          if (val is Type || val is ClassScope || val is TypedArray){
            this.field.attributeFlags &= ~FieldAttributes.Literal;
            this.identifier.TranslateToILPreSet(il);
            this.identifier.TranslateToILSet(il, new ConstantWrapper(val, null));
            this.field.attributeFlags |= FieldAttributes.Literal;
          }
        }else{
          if (!this.field.IsStatic){
            FieldBuilder fb = this.valueField = this.field.metaData as FieldBuilder;
            if (fb != null)
              this.field.metaData = ((TypeBuilder)fb.DeclaringType).DefineField(this.name+" value", this.field.type.ToType(), FieldAttributes.Private);
          }
          this.field.attributeFlags &= ~FieldAttributes.InitOnly;
          this.identifier.TranslateToILPreSet(il);
          this.identifier.TranslateToILSet(il, this.value);
          this.field.attributeFlags |= FieldAttributes.InitOnly;
        }
      }

      internal void TranslateToILInitOnlyInitializers(ILGenerator il){
        FieldBuilder fb = this.valueField;
        if (fb != null){
          il.Emit(OpCodes.Ldarg_0);
          il.Emit(OpCodes.Dup);
          il.Emit(OpCodes.Ldfld, (FieldBuilder)this.field.metaData);
          il.Emit(OpCodes.Stfld, fb);
          this.valueField = (FieldBuilder)this.field.metaData;
          this.field.metaData = fb;
        }
      }

      internal override void TranslateToILInitializer(ILGenerator il){
        if (this.value != null)
          this.value.TranslateToILInitializer(il);
      }

    }
}


text:
<?php

namespace Mongobox\Bundle\UsersBundle;

use Symfony\Component\HttpKernel\Bundle\Bundle;

class MongoboxUsersBundle extends Bundle
{
    public function getParent()
    {
        return 'FOSUserBundle';
    }
}


text:
``middleman``

That starts a local server and updates automatically.

##Deploying

``rake publish``

That builds out everything and makes it live. Be sure to push your changes using ``git push`` so that everyone else can work off your latest changes.


text:
package com.perforce.p4java.option.server;

import com.perforce.p4java.exception.OptionsException;
import com.perforce.p4java.option.Options;
import com.perforce.p4java.server.IServer;

import java.util.List;

/**
 * This class is used to encapsulate all the information
 * that forms the options part of the 'p4 list' command
 *

 * Usage: list [-l label [-d]] [-C] [-M] files...
 *

 */
public class ListOptions extends Options {

	public static final String OPTIONS_SPECS = "s:l b:d b:C b:M";

	/**
	 * The repo against which the 'p4 list' command is issued
	 */
	private String label;

	/**
	 * Delete flag
	 */
	private boolean delete;

	/**
	 * Limits any depot paths to those that can be mapped through
	 * the client workspace
	 */
	private boolean limitDepotPaths = false;

	/**
	 * Flag that can be used to specify when issuing the list command against a
	 * forwarding replica
	 */
	private boolean listFromReplica = false;

	/**
	 * Default constructor
	 */
	public ListOptions() {

	}

	/**
	 * @param server possibly-null IServer representing the Perforce server the
	 *               options are to be used against. If this parameter is null, it
	 *               is acceptable to throw an OptionsException, but it is also
	 *               possible to ignore it and do the best you can with what you've
	 *               got...
	 * @return list of options strings
	 * @throws OptionsException Options Exception
	 */
	@Override
	public List<String> processOptions(IServer server) throws OptionsException {
		this.optionList = this.processFields(OPTIONS_SPECS, this.label, this.delete,
				this.limitDepotPaths, this.listFromReplica);
		return this.optionList;
	}

	/**
	 * Returns the label attached to the list of files retrived
	 *
	 * @return the label
	 */
	public String getLabel() {
		return label;
	}

	/**
	 * Sets a label to the list of files to be retrieved
	 *
	 * @param label label name
	 */
	public void setLabel(String label) {
		this.label = label;
	}

	/**
	 * Should the content referred to by the label be deleted
	 *
	 * @return delete flag
	 */
	public boolean isDelete() {
		return delete;
	}

	/**
	 * Sets a flag indicating that the files referred to by the label should be deleted or not
	 *
	 * @param delete delete flag
	 */
	public void setDelete(boolean delete) {
		this.delete = delete;
	}

	/**
	 * Indicates whether depot path should be limited to that can be mapped via client workspace
	 *
	 * @return limitDepotPaths flag
	 */
	public boolean isLimitDepotPaths() {
		return limitDepotPaths;
	}

	/**
	 * Sets a flag indicating whether depot path shou;d be limited to that can be mapped via client workspace
	 *
	 * @param limitDepotPaths limitDepotPaths flag
	 */
	public void setLimitClient(boolean limitDepotPaths) {
		this.limitDepotPaths = limitDepotPaths;
	}

	/**
	 * Returns listFromReplica
	 *
	 * @return listFromReplica flag
	 */
	public boolean isListFromReplica() {
		return listFromReplica;
	}

	/**
	 * Sets listFromReplica
	 *
	 * @param listFromReplica listFromReplica flag
	 */
	public void setListFromReplica(boolean listFromReplica) {
		this.listFromReplica = listFromReplica;
	}
}


text:
namespace WebKit {
class WebFrame;
class WebPlugin;
struct WebPluginParams;
}

namespace WebTestRunner {
class WebTestProxyBase;
}

namespace webkit_glue {
class MockWebHyphenator;
}

class MockWebClipboardImpl;
class TestShellWebMimeRegistryImpl;

namespace content {

class ShellRenderProcessObserver;

class ShellContentRendererClient : public ContentRendererClient {
 public:
  static ShellContentRendererClient* Get();

  ShellContentRendererClient();
  virtual ~ShellContentRendererClient();

  void LoadHyphenDictionary(base::PlatformFile dict_file);

  // ContentRendererClient implementation.
  virtual void RenderThreadStarted() OVERRIDE;
  virtual void RenderViewCreated(RenderView* render_view) OVERRIDE;
  virtual bool OverrideCreatePlugin(
      RenderView* render_view,
      WebKit::WebFrame* frame,
      const WebKit::WebPluginParams& params,
      WebKit::WebPlugin** plugin) OVERRIDE;
  virtual WebKit::WebMediaStreamCenter* OverrideCreateWebMediaStreamCenter(
      WebKit::WebMediaStreamCenterClient* client) OVERRIDE;
  virtual WebKit::WebRTCPeerConnectionHandler*
  OverrideCreateWebRTCPeerConnectionHandler(
      WebKit::WebRTCPeerConnectionHandlerClient* client) OVERRIDE;
  virtual WebKit::WebClipboard* OverrideWebClipboard() OVERRIDE;
  virtual WebKit::WebMimeRegistry* OverrideWebMimeRegistry() OVERRIDE;
  virtual WebKit::WebHyphenator* OverrideWebHyphenator() OVERRIDE;
  virtual WebKit::WebThemeEngine* OverrideThemeEngine() OVERRIDE;
  virtual bool AllowBrowserPlugin(
      WebKit::WebPluginContainer* container) const OVERRIDE;

 private:
   void WebTestProxyCreated(RenderView* render_view,
                            WebTestRunner::WebTestProxyBase* proxy);

  scoped_ptr<ShellRenderProcessObserver> shell_observer_;
  scoped_ptr<MockWebClipboardImpl> clipboard_;
  scoped_ptr<TestShellWebMimeRegistryImpl> mime_registry_;
  scoped_ptr<webkit_glue::MockWebHyphenator> hyphenator_;
};

}  // namespace content

#endif  // CONTENT_SHELL_SHELL_CONTENT_RENDERER_CLIENT_H_


text:
package org.apache.camel.web.resources;

import com.sun.jersey.api.client.Client;
import com.sun.jersey.api.client.WebResource;
import com.sun.jersey.api.client.config.ClientConfig;
import com.sun.jersey.api.client.config.DefaultClientConfig;
import org.apache.camel.web.Main;
import org.junit.After;
import org.junit.Assert;
import org.junit.Before;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * @version
 */
public class TestSupport extends Assert {
    private static final transient Logger LOG = LoggerFactory.getLogger(TestSupport.class);

    protected ClientConfig clientConfig;
    protected Client client;
    protected WebResource resource;

    @Before
    public void setUp() throws Exception {

        Main.start();

        clientConfig = new DefaultClientConfig();
        // use the following jaxb context resolver
        //cc.getProviderClasses().add(JAXBContextResolver.class);
        client = Client.create(clientConfig);
        resource = client.resource(Main.getRootUrl());
    }

    @After
    public void tearDown() throws Exception {
        Main.stop();
    }

    protected WebResource resource(String uri) {
        LOG.info("About to test URI: " + uri);
        return resource.path(uri);
    }
    protected void assertHtmlResponse(String response) {
        assertNotNull("No text returned!", response);

        assertResponseContains(response, "<html>");
        assertResponseContains(response, "</html>");
    }

    protected void assertResponseContains(String response, String text) {
        assertTrue("Response should contain " + text + " but was: " + response, response.contains(text));
    }
}


text:
int main(int argc, char* argv[])
{
  if (argc < 3)
  {
    std::cerr << "Usage: " << argv[0] << " dimensions number_of_points [options]" <<
      std::endl;
    return 1;
  }
  long double learning_rate = 0.5;
  long double threshold = 0.0;
  int iterations_threshold = 0;
  int number_of_neurons = 1;
  std::string initial_weights_file;
  for (int i = 3; i < argc; ++i)
  {
    if (strcmp(argv[i], "--learning-rate") == 0 ||
        strcmp(argv[i], "-l") == 0)
    {
      ++i;
      if (i >= argc)
      {
        std::cerr << argv[i] << " requires an argument" << std::endl;
        return 1;
      }
      learning_rate = atof(argv[i]);
      if (!(0.0 < learning_rate && learning_rate <= 1.0))
      {
        std::cerr << "Learning rate must lie in (0, 1]" << std::endl;
        return 1;
      }
    }
    else if (strcmp(argv[i], "--initial-weights") == 0 ||
        strcmp(argv[i], "-w") == 0)
    {
      ++i;
      if (i >= argc)
      {
        std::cerr << argv[i] << " requires an argument" << std::endl;
        return 1;
      }
      initial_weights_file = argv[i];
    }
    else if (strcmp(argv[i], "--error-threshold") == 0 ||
        strcmp(argv[i], "-e") == 0)
    {
      ++i;
      if (i >= argc)
      {
        std::cerr << argv[i] << " requires an argument" << std::endl;
        return 1;
      }
      threshold = atof(argv[i]);
      if (threshold < 0.0)
      {
        std::cerr << "Threshold can't be negative" << std::endl;
        return 1;
      }
    }
    else if (strcmp(argv[i], "--iterations-threshold") == 0 ||
        strcmp(argv[i], "-i") == 0)
    {
      ++i;
      if (i >= argc)
      {
        std::cerr << argv[i] << " requires an argument" << std::endl;
        return 1;
      }
      iterations_threshold = atoi(argv[i]);
      if (iterations_threshold < 0)
      {
        std::cerr << argv[i - 1] << " can't be negative" << std::endl;
        return 1;
      }
    }
    else if (strcmp(argv[i], "--number-of-output-dimensions") == 0 ||
        strcmp(argv[i], "-n") == 0)
    {
      ++i;
      if (i >= argc)
      {
        std::cerr << argv[i] << " requires an argument" << std::endl;
        return 1;
      }
      number_of_neurons = atoi(argv[i]);
      if (number_of_neurons < 1)
      {
        std::cerr << argv[i - 1] << " can't be less than 1" << std::endl;
        return 1;
      }
    }
  }
  size_t dimensions = atoi(argv[1]), number_of_points = atoi(argv[2]);
  Perceptron perceptron(dimensions, number_of_neurons, learning_rate,
      threshold, iterations_threshold);
  if (!initial_weights_file.empty())
  {
    std::vector<Vector<long double>> initial_weights(number_of_neurons,
        Vector<long double>(dimensions + 1));
    if (initial_weights_file == "-")
    {
      for (Vector<long double>& hyperplane : initial_weights)
      {
        std::cin >> hyperplane;
      }
    }
    else
    {
      std::ifstream file(initial_weights_file);
      for (Vector<long double>& hyperplane : initial_weights)
      {
        file >> hyperplane;
      }
    }
    perceptron.set_initial_weights(initial_weights);
  }
  std::vector<Vector<>> points(number_of_points, Vector<>(dimensions));
  std::vector<std::vector<int>> classes(number_of_neurons,
      std::vector<int>(number_of_points));
  std::vector<Vector<int>> point_classes(number_of_points,
      Vector<int>(number_of_neurons));
  for (size_t index = 0; index < number_of_points; ++index)
  {
    std::cin >> points[index];
    for (size_t neuron_index = 0;
        neuron_index < static_cast<size_t>(number_of_neurons);
        ++neuron_index)
    {
      std::cin >> classes[neuron_index][index];
      if (classes[neuron_index][index] != 1)
      {
        classes[neuron_index][index] = -1;
      }
      point_classes[index][neuron_index] = classes[neuron_index][index];
    }
  }
  perceptron.add_data(points.begin(), points.end(), classes.begin());
  perceptron.compute_weights(std::cerr);
  for (const Vector<long double>& weights : perceptron.get_current_weights())
  {
    Vector<long double> normalized = weights;
    normalized.coordinates.pop_back();
    long double length = normalized.length();
    normalized = normalized.normalized();
    std::cout << normalized << ' ' << weights.coordinates.back() / length << std::endl;
  }
  int number_of_errors = 0;
  for (size_t index = 0; index < number_of_points; ++index)
  {
    if (perceptron.get_vector_category(points[index]) != point_classes[index])
    {
      number_of_errors++;
    }
  }
  std::cout << "Number of mistakes: " << number_of_errors << std::endl;
  return 0;
}


text:
namespace Hend
{
    class SearchDialog : public QDialog
    {
        Q_OBJECT
    public:

        using video_feature_t = QMap<QString, QString>;
        explicit SearchDialog( QWidget *parent = nullptr );
        static video_feature_t videoDuration;
        static video_feature_t videoDimension;
        static video_feature_t videoDefinition;
        static video_feature_t videoType;

        QString getQuery() const;
    private:
        QLabel              *m_labelSearchString;
        QLabel              *m_labelSelection;

        QLineEdit           *m_searchString;
        QPushButton         *m_pushButtonOk;
        QPushButton         *m_pushButtonCancel;

        QComboBox           *m_comboVideoType;
        QComboBox           *m_comboVideoDimension;
        QComboBox           *m_comboVideoDefinition;
        QComboBox           *m_comboVideoDuration;
        QSpinBox            *m_videoMaxSize;
        QGridLayout         *m_gLayout;

    private:
        void setupComboBoxes();
        void connectAllButtonActions();
        void configureWindows();
    };
}

#endif // SEARCHDIALOG_HPP


text:
FROM golang:1.12

LABEL maintainer="Shivani Junawane <shivanij@us.ibm.com>"

WORKDIR /data

RUN git clone https://github.com/prometheus/pushgateway.git \
        && cd pushgateway && git checkout v0.7.0 \
        && make all \
        && cp pushgateway /bin/pushgateway \
        && rm -rf pushgateway

EXPOSE 9091
WORKDIR /pushgateway
CMD [ "/bin/pushgateway" ]


text:
<?xml version="1.0" encoding="UTF-8"?>
<!--
  ~ Licensed to the Apache Software Foundation (ASF) under one or more
  ~ contributor license agreements.  See the NOTICE file distributed with
  ~ this work for additional information regarding copyright ownership.
  ~ The ASF licenses this file to You 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.
  -->

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
  <parent>
    <artifactId>foundations</artifactId>
    <groupId>org.apache.servicecomb</groupId>
    <version>1.0.0-m2-SNAPSHOT</version>
  </parent>
  <modelVersion>4.0.0</modelVersion>

  <properties>
  </properties>

  <artifactId>foundation-config</artifactId>
  <name>Java Chassis::Foundations::Config</name>
  <dependencies>
    <dependency>
      <groupId>org.apache.servicecomb</groupId>
      <artifactId>foundation-common</artifactId>
    </dependency>
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-beans</artifactId>
    </dependency>
    <dependency>
      <groupId>com.netflix.archaius</groupId>
      <artifactId>archaius-core</artifactId>
    </dependency>
    <dependency>
      <groupId>commons-configuration</groupId>
      <artifactId>commons-configuration</artifactId>
    </dependency>
    <dependency>
      <groupId>org.yaml</groupId>
      <artifactId>snakeyaml</artifactId>
    </dependency>
    <dependency>
      <groupId>org.slf4j</groupId>
      <artifactId>slf4j-api</artifactId>
    </dependency>

    <dependency>
      <groupId>org.slf4j</groupId>
      <artifactId>slf4j-log4j12</artifactId>
      <scope>test</scope>
    </dependency>
    <dependency>
      <groupId>log4j</groupId>
      <artifactId>log4j</artifactId>
      <scope>test</scope>
    </dependency>
    <dependency>
      <groupId>org.apache.servicecomb</groupId>
      <artifactId>foundation-test-scaffolding</artifactId>
    </dependency>
    <dependency>
      <groupId>org.apache.httpcomponents</groupId>
      <artifactId>httpclient</artifactId>
    </dependency>
    <dependency>
      <groupId>io.netty</groupId>
      <artifactId>netty-codec</artifactId>
    </dependency>
    <dependency>
      <groupId>io.netty</groupId>
      <artifactId>netty-codec-http</artifactId>
    </dependency>
    <dependency>
      <groupId>io.netty</groupId>
      <artifactId>netty-codec-http2</artifactId>
    </dependency>
    <dependency>
      <groupId>io.netty</groupId>
      <artifactId>netty-common</artifactId>
    </dependency>
    <dependency>
      <groupId>io.netty</groupId>
      <artifactId>netty-handler</artifactId>
    </dependency>
    <dependency>
      <groupId>io.netty</groupId>
      <artifactId>netty-buffer</artifactId>
    </dependency>
    <dependency>
      <groupId>io.netty</groupId>
      <artifactId>netty-codec-socks</artifactId>
    </dependency>
    <dependency>
      <groupId>io.netty</groupId>
      <artifactId>netty-handler-proxy</artifactId>
    </dependency>
    <dependency>
      <groupId>io.netty</groupId>
      <artifactId>netty-resolver</artifactId>
    </dependency>
    <dependency>
      <groupId>io.netty</groupId>
      <artifactId>netty-transport</artifactId>
    </dependency>
    <dependency>
      <groupId>com.google.guava</groupId>
      <artifactId>guava</artifactId>
    </dependency>
  </dependencies>
</project>


text:
package org.jivesoftware.smack.websocket.test;

import static org.junit.jupiter.api.Assertions.assertEquals;

import static org.mockito.Mockito.mock;

import java.net.URISyntaxException;

import org.jivesoftware.smack.c2s.internal.ModularXmppClientToServerConnectionInternal;
import org.jivesoftware.smack.websocket.impl.AbstractWebSocket;
import org.jivesoftware.smack.websocket.impl.WebSocketFactoryService;
import org.jivesoftware.smack.websocket.rce.WebSocketRemoteConnectionEndpoint;

public class WebSocketFactoryServiceTestUtil {

    public static void createWebSocketTest(Class<? extends AbstractWebSocket> expected) throws URISyntaxException {
        WebSocketRemoteConnectionEndpoint endpoint = WebSocketRemoteConnectionEndpoint.from("wss://example.org");

        ModularXmppClientToServerConnectionInternal connectionInternal = mock(ModularXmppClientToServerConnectionInternal.class);

        AbstractWebSocket websocket = WebSocketFactoryService.createWebSocket(endpoint, connectionInternal);
        assertEquals(expected, websocket.getClass());
    }

}


text:
import { Component, OnInit } from '@angular/core';

@Component({
  selector: 'app-recipes',
  templateUrl: './recipes.component.html',
  styleUrls: ['./recipes.component.css']
})
export class RecipesComponent implements OnInit {

  constructor() { }

  ngOnInit() {
  }

}


text:
using System;
using UnityEngine;
using UnityEngine.SceneManagement;
using System.Collections.Generic;
using System.Collections;
using System.Linq;

public class DiscordController : MonoBehaviour
{
    // https://github.com/discordapp/discord-rpc/blob/master/examples/button-clicker/Assets/DiscordController.cs

    private const string DefaultStatusString = "default";

    public bool disableInEditor;

    public string applicationId;
    public string optionalSteamId;
    public string details;
    public string largeImageKey;
    public int callbackCalls;
    public UnityEngine.Events.UnityEvent onConnect;
    public UnityEngine.Events.UnityEvent onDisconnect;

    DiscordRpc.RichPresence presence;
    DiscordRpc.EventHandlers handlers;
    bool initialized = false;
    bool ready = false;

    public enum TimeStampType
    {
        Keep,
        Clear,
        CurrentTime
    }

    public void ReadyCallback()
    {
        ++callbackCalls;
        Debug.Log("Discord: ready");
        onConnect.Invoke();
        ready = true;
    }

    public void DisconnectedCallback(int errorCode, string message)
    {
        ++callbackCalls;
        Debug.Log(string.Format("Discord: disconnect {0}: {1}", errorCode, message));
        onDisconnect.Invoke();
    }

    public void ErrorCallback(int errorCode, string message)
    {
        ++callbackCalls;
        Debug.Log(string.Format("Discord: error {0}: {1}", errorCode, message));
    }

    void Update()
    {
        try
        {
            DiscordRpc.RunCallbacks();
        }
        catch (DllNotFoundException e)
        {
            Debug.Log("Discord controller not found! Probably just a non-Windows build idk");
            enabled = false;
        }
    }

    void Start()
    {
        if (initialized)
            return;
#if UNITY_EDITOR
        if (disableInEditor)
        {
            gameObject.SetActive(false);
            return;
        }
#endif
        if (Application.platform != RuntimePlatform.WindowsPlayer)
        {
            gameObject.SetActive(false);
            return;
        }

        Debug.Log("Discord: init");
        callbackCalls = 0;

        handlers = new DiscordRpc.EventHandlers();
        handlers.readyCallback = ReadyCallback;
        handlers.disconnectedCallback += DisconnectedCallback;
        handlers.errorCallback += ErrorCallback;

        try
        {
            DiscordRpc.Initialize(applicationId, ref handlers, true, optionalSteamId);
            initialized = true;
        }
        catch (DllNotFoundException e)
        {
            Debug.Log("Discord controller not found! Probably just a non-Windows build idk");
            enabled = false;
        }
    }

    IEnumerator updatePresenceCoroutine()
    {
        while (!ready)
        {
            yield return new WaitForEndOfFrame();
        }
        DiscordRpc.UpdatePresence(ref presence);
    }

    public void updatePresence(string details = DefaultStatusString, string state = DefaultStatusString, TimeStampType startTimeStamp = TimeStampType.Keep)
    {
        if (!gameObject.activeInHierarchy)
            return;

        if (details.Equals(DefaultStatusString))
            details = presence.details;
        if (state.Equals(DefaultStatusString))
            state = presence.state;

        StopCoroutine(updatePresenceCoroutine());
        presence.details = details;
        presence.state = state;
        presence.largeImageKey = largeImageKey;
        switch(startTimeStamp)
        {
            case (TimeStampType.Keep):
                break;
            case (TimeStampType.CurrentTime):
                presence.startTimestamp = getTimeSinceEpoch();
                break;
            case (TimeStampType.Clear):
                presence.startTimestamp = 0;
                break;
        }
        StartCoroutine(updatePresenceCoroutine());
    }

    private int getTimeSinceEpoch()
    {
        TimeSpan t = DateTime.UtcNow - new DateTime(1970, 1, 1);
        return (int)t.TotalSeconds;
    }
}


text:
using System;
using Newtonsoft.Json.Linq;
using Skybrud.Essentials.Json.Extensions;
using Skybrud.Social.Microsoft.WindowsLive.Models;
using Skybrud.Social.Microsoft.WindowsLive.Scopes;

namespace Skybrud.Social.Microsoft.WindowsLive.Models.Authentication {

    /// <summary>
    /// Class representing the response body of a call to get a refresh token or an access token.
    /// </summary>
    public class WindowsLiveTokenResponseBody : WindowsLiveObject {

        #region Properties

        /// <summary>
        /// Gets the type of the topen.
        /// </summary>
        public string TokenType { get; }

        /// <summary>
        /// Gets an instance of <see cref="TimeSpan"/> for when the access token will expire.
        /// </summary>
        public TimeSpan ExpiresIn { get; }

        /// <summary>
        /// Gets a collection of the scopes the user has granted.
        /// </summary>
        public WindowsLiveScopeCollection Scope { get; }

        /// <summary>
        /// Gets the access token.
        /// </summary>
        public string AccessToken { get; }

        /// <summary>
        /// Gets the authentication token.
        /// </summary>
        public string AuthenticationToken { get; }

        /// <summary>
        /// Gets the refresh token.
        /// </summary>
        public string RefreshToken { get; }

        /// <summary>
        /// Gets whether a authentication token was specified in the response.
        /// </summary>
        public bool HasAuthenticationToken => !String.IsNullOrWhiteSpace(AuthenticationToken);

        /// <summary>
        /// Gets whether a refresh token was specified in the response.
        /// </summary>
        public bool HasRefreshToken => !String.IsNullOrWhiteSpace(RefreshToken);

        #endregion

        #region Constructors

        private WindowsLiveTokenResponseBody(JObject obj) : base(obj) {

            // Convert the "scope" string to a collection of scopes
            Scope = new WindowsLiveScopeCollection();
            foreach (string name in obj.GetString("scope").Split(' ')) {
                WindowsLiveScope scope = WindowsLiveScope.GetScope(name) ?? WindowsLiveScope.RegisterScope(name);
                Scope.Add(scope);
            }

            // Parse the rest of the response body
            TokenType = obj.GetString("token_type");
            ExpiresIn = obj.GetDouble("expires_in", TimeSpan.FromSeconds);
            AccessToken = obj.GetString("access_token");
            AuthenticationToken = obj.GetString("authentication_token");
            RefreshToken = obj.GetString("refresh_token");

        }

        #endregion

        #region Static methods

        /// <summary>
        /// Parses the specified <paramref name="obj"/> into an instance of <see cref="WindowsLiveTokenResponseBody"/>.
        /// </summary>
        /// <param name="obj">The instance of <see cref="JObject"/> to be parsed.</param>
        /// <returns>An instance of <see cref="WindowsLiveTokenResponseBody"/>.</returns>
        public static WindowsLiveTokenResponseBody Parse(JObject obj) {
            return obj == null ? null : new WindowsLiveTokenResponseBody(obj);
        }

        #endregion

    }

}


text:
<?php

/**
 * DOM SVG Switch element class
 *
 * @category    	PAHDI
 * @package     	PAHDI-DOM
 */
class SVGSwitchElement extends SVGElement{}


text:
This document provides installation instructions for all the various tools and technologies used in the [development workflow](/workflow/gulp/index.html) for this template.

---

## Linux

### Required Software

* **Node.js** - required to run npm - [nodejs.org](https://nodejs.org)

	Ubuntu

		# Setup with Ubuntu:
		curl -sL https://deb.nodesource.com/setup | sudo bash -

		# Then install with Ubuntu:
		sudo apt-get install -y nodejs

	Debian

		# Setup with Debian
		apt-get install curl
		curl -sL https://deb.nodesource.com/setup | bash -

		# Then install with Debian
		apt-get install -y nodejs

	Fedora

		# Setup on RHEL, CentOS or Fedora
		curl -sL https://rpm.nodesource.com/setup | bash -

		# Then install:
		yum install -y nodejs

	Additionally, see [Installing Node.js via package managers](https://github.com/joyent/node/wiki/Installing-Node.js-via-package-manager)

* **Git client** - required by bower dependencies - via package managers:

	Debian/Ubuntu

		apt-get install git

	Fedora

		yum install git

	Additionally, see [Installing Git for Linux via package managers](https://www.git-scm.com/download/linux)

* **Subversion client** - required by some bower dependencies only available via svn:

	Fedora/CentOS

		yum install subversion

	Debian

		apt-get install subversion

---

## Mac OS X

### Required Software

* **Node.js** - required to run npm - [nodejs.org](https://nodejs.org)

	Simply download the **Machintosh Installer** directly from the nodejs.org website.

	Or, using Homebrew:

		brew install node

* **Git client** - required by bower dependencies:

	Install via Homebrew:

		brew install git

* **Subversion client** - required by some bower dependencies only available via svn:

	Install via Homebrew:

		brew install subversion

---

## Windows

### Required Software

* **Node.js** - required to run npm - [Download Node.js for Windows](https://nodejs.org)
* **Git client** - required by bower dependencies - [Download SourceTree for Windows](https://www.sourcetreeapp.com)
* **Subversion client** - required by some bower dependencies only available via svn - [Download SlickSvn for Windows](https://sliksvn.com/download/)
* **MinGW** and **MSYS** (replacement for cmd.exe, required by the gulp/grunt tasks provided with the package) - **only if you choose to NOT install SourceTree above, SourceTree already includes a terminal** - [Install MinGW & MSYS](http://www.mingw.org/wiki/Getting_Started)

---

## Installation

After making sure you have installed all the software dependencies for your operating system, open a terminal (for Windows, MSYS terminal or if you've installed SourceTree as we recommended, open up a terminal from within SourceTree) and change the current working directory to the downloaded item:

	cd /path/to/package/root

Install all the dependencies listed in package.json:

	npm install

**Only if you are using Gulp (recommended)**: Install Gulp:

	npm install -g gulp

**Only if you are using Gulp (recommended)**: Install Gulp Workflow dependencies. This will install all the packages listed in `lib/gulp/package.json` into the current working directory:

	node_modules/.bin/npm-install-from --path lib/gulp

**Only if you are using Grunt**: Install Grunt:

	npm install -g grunt-cli

**Only if you are using Grunt**: Install Grunt Workflow dependencies. This will install all the packages listed in `lib/grunt/package.json` into the current working directory:

	node_modules/.bin/npm-install-from --path lib/grunt

Install Bower:

	npm install -g bower

Install Bower dependencies:

	bower install

---

## See also

- [The build process](/workflow/gulp/index.html)
- [Structure](/code/structure/index.html)
- [Manage assets](/code/bower/index.html)
- [Include paths](/code/include-paths/index.html)
- [Loading assets](/reference/layout/index.html#loading-assets)


text:
<?php
namespace PhpOffice\PhpWord\Tests\Shared;

use PhpOffice\PhpWord\PhpWord;
use PhpOffice\PhpWord\Shared\Font;

/**
 * @runTestsInSeparateProcesses
 */
class FontTest extends \PHPUnit_Framework_TestCase
{
    /**
     * Test various conversions
     */
    public function testConversions()
    {
        $phpWord = new PhpWord();

        $original = 1;

        $result = Font::fontSizeToPixels($original);
        $this->assertEquals($original * 16 / 12, $result);

        $result = Font::inchSizeToPixels($original);
        $this->assertEquals($original * 96, $result);

        $result = Font::centimeterSizeToPixels($original);
        $this->assertEquals($original * 37.795275591, $result);

        $result = Font::centimeterSizeToTwips($original);
        $this->assertEquals($original * 565.217, $result);

        $result = Font::inchSizeToTwips($original);
        $this->assertEquals($original * 565.217 * 2.54, $result);

        $result = Font::pixelSizeToTwips($original);
        $this->assertEquals($original * 565.217 / 37.795275591, $result);

        $result = Font::pointSizeToTwips($original);
        $this->assertEquals($original * 20, $result);
    }
}


text:
<?php

namespace Mykees\MediaBundle\Tests\Controller;

use Liip\FunctionalTestBundle\Test\WebTestCase;
use Symfony\Component\HttpFoundation\File\UploadedFile;

class DefaultControllerTest extends WebTestCase
{
    protected $client;
    protected $container;
    protected $manager;
    protected $image;

    public function setUp()
    {
        //Load fixtures
        $fixtures = array(
            'Mvc\BlogBundle\DataFixtures\ORM\LoadPostsData',
        );
        $this->loadFixtures($fixtures);

        $this->client = static::createClient();
        $this->container = $this->client->getContainer();

        parent::setUp();
    }

    public function testPostsList()
    {
        $crawler = $this->client->request('GET', '/');
        $this->assertEquals(200,$this->client->getResponse()->getStatusCode());
        $this->assertEquals(4,$crawler->filter('.posts')->count());
    }
}


text:
package groovy.swing.impl;

import groovy.lang.Closure;

import java.awt.event.ActionEvent;

import javax.swing.AbstractAction;

/**
 * A default action implementation
 *
 * @author James Strachan
 */
public class DefaultAction extends AbstractAction {

    private Closure closure;

    public void actionPerformed(ActionEvent event) {
        if (closure == null) {
            throw new NullPointerException("No closure has been configured for this Action");
        }
        closure.call(event);
    }

    public Closure getClosure() {
        return closure;
    }

    public void setClosure(Closure closure) {
        this.closure = closure;
    }

}