text:
package org.keycloak.models.sessions.infinispan.initializer;

import org.infinispan.Cache;
import org.infinispan.configuration.cache.CacheMode;
import org.infinispan.configuration.cache.Configuration;
import org.infinispan.configuration.cache.ConfigurationBuilder;
import org.infinispan.configuration.cache.VersioningScheme;
import org.infinispan.configuration.global.GlobalConfigurationBuilder;
import org.infinispan.manager.DefaultCacheManager;
import org.infinispan.manager.EmbeddedCacheManager;
import org.infinispan.transaction.TransactionMode;
import org.infinispan.transaction.lookup.EmbeddedTransactionManagerLookup;
import org.infinispan.util.concurrent.IsolationLevel;
import org.junit.Assert;
import org.junit.Ignore;
import org.junit.Test;
import org.keycloak.connections.infinispan.InfinispanConnectionProvider;

import javax.transaction.NotSupportedException;
import javax.transaction.Status;
import javax.transaction.SystemException;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * Unit tests to make sure our model caching concurrency model will work.
 *
 * @author Bill Burke
 * @version $Revision: 1 $
 */
@Ignore
public class ConcurrencyVersioningTest {

    public static abstract class AbstractThread implements Runnable {
        EmbeddedCacheManager cacheManager;
        boolean success;
        CountDownLatch latch = new CountDownLatch(1);

        public AbstractThread(EmbeddedCacheManager cacheManager) {
            this.cacheManager = cacheManager;
        }

        public boolean isSuccess() {
            return success;
        }

        public CountDownLatch getLatch() {
            return latch;
        }
    }

    public static class RemoveThread extends AbstractThread {
        public RemoveThread(EmbeddedCacheManager cacheManager) {
            super(cacheManager);
        }

        public void run() {
            Cache<String, String> cache = cacheManager.getCache(InfinispanConnectionProvider.REALM_CACHE_NAME);
            try {
                startBatch(cache);
                cache.remove("key");
                //cache.getAdvancedCache().getTransactionManager().commit();
                endBatch(cache);
                success = true;
            } catch (Exception e) {
                success = false;
            }
            latch.countDown();
        }

    }

    public static class UpdateThread extends AbstractThread {
        public UpdateThread(EmbeddedCacheManager cacheManager) {
            super(cacheManager);
        }

        public void run() {
            Cache<String, String> cache = cacheManager.getCache(InfinispanConnectionProvider.REALM_CACHE_NAME);
            try {
                startBatch(cache);
                cache.putForExternalRead("key", "value2");
                //cache.getAdvancedCache().getTransactionManager().commit();
                endBatch(cache);
                success = true;
            } catch (Exception e) {
                success = false;
            }
            latch.countDown();
        }

    }

    /**
     * Tests that if remove executes before put, then put still succeeds.
     *
     * @throws Exception
     */
    @Test
    public void testGetRemovePutOnNonExisting() throws Exception {
        final DefaultCacheManager cacheManager = getVersionedCacheManager();
        ExecutorService executor = Executors.newSingleThreadExecutor();

        RemoveThread removeThread = new RemoveThread(cacheManager);

        Cache<String, String> cache = cacheManager.getCache(InfinispanConnectionProvider.REALM_CACHE_NAME);
        cache.remove("key");
        startBatch(cache);
        cache.get("key");
        executor.execute(removeThread);
        removeThread.getLatch().await();
        cache.putForExternalRead("key", "value1");
        endBatch(cache);
        Assert.assertEquals(cache.get("key"), "value1");
        Assert.assertTrue(removeThread.isSuccess());
    }

    /**
     * Test that if a put of an existing key is removed after the put and before tx commit, it is evicted
     *
     * @throws Exception
     */
    @Test
    public void testGetRemovePutOnExisting() throws Exception {
        final DefaultCacheManager cacheManager = getVersionedCacheManager();
        ExecutorService executor = Executors.newSingleThreadExecutor();

        RemoveThread removeThread = new RemoveThread(cacheManager);

        Cache<String, String> cache = cacheManager.getCache(InfinispanConnectionProvider.REALM_CACHE_NAME);
        cache.put("key", "value0");
        startBatch(cache);
        cache.get("key");
        executor.execute(removeThread);
        removeThread.getLatch().await();
        cache.put("key", "value1");
        try {
            endBatch(cache);
            Assert.fail("Write skew should be detected");
        } catch (Exception e) {

        }
        Assert.assertNull(cache.get("key"));
        Assert.assertTrue(removeThread.isSuccess());
    }

    /**
     * Test that if a put of an existing key is removed after the put and before tx commit, it is evicted
     *
     * @throws Exception
     */
    @Test
    public void testGetRemovePutEternalOnExisting() throws Exception {
        final DefaultCacheManager cacheManager = getVersionedCacheManager();
        ExecutorService executor = Executors.newSingleThreadExecutor();

        RemoveThread removeThread = new RemoveThread(cacheManager);

        Cache<String, String> cache = cacheManager.getCache(InfinispanConnectionProvider.REALM_CACHE_NAME);
        cache.put("key", "value0");
        startBatch(cache);
        cache.get("key");
        executor.execute(removeThread);
        cache.putForExternalRead("key", "value1");
        removeThread.getLatch().await();
        try {
            endBatch(cache);
//            Assert.fail("Write skew should be detected");
        } catch (Exception e) {

        }
        Assert.assertNull(cache.get("key"));
        Assert.assertTrue(removeThread.isSuccess());
    }

    @Test
    public void testPutExternalRemoveOnExisting() throws Exception {
        final DefaultCacheManager cacheManager = getVersionedCacheManager();
        ExecutorService executor = Executors.newSingleThreadExecutor();

        RemoveThread removeThread = new RemoveThread(cacheManager);

        Cache<String, String> cache = cacheManager.getCache(InfinispanConnectionProvider.REALM_CACHE_NAME);
        cache.put("key", "value0");
        startBatch(cache);
        cache.putForExternalRead("key", "value1");
        executor.execute(removeThread);
        removeThread.getLatch().await();
        try {
            endBatch(cache);
//            Assert.fail("Write skew should be detected");
        } catch (Exception e) {

        }
        Assert.assertNull(cache.get("key"));
        Assert.assertTrue(removeThread.isSuccess());
    }

    public static void startBatch(Cache<String, String> cache) {
        try {
            if (cache.getAdvancedCache().getTransactionManager().getStatus() == Status.STATUS_NO_TRANSACTION) {
                System.out.println("begin");
                cache.getAdvancedCache().getTransactionManager().begin();
            }
        } catch (NotSupportedException e) {
            throw new RuntimeException(e);
        } catch (SystemException e) {
            throw new RuntimeException(e);
        }

    }

    public static void endBatch(Cache<String, String> cache) {
        boolean commit = true;
        try {
            if (cache.getAdvancedCache().getTransactionManager().getStatus() == Status.STATUS_ACTIVE) {
                if (commit) {
                    cache.getAdvancedCache().getTransactionManager().commit();

                } else {
                    cache.getAdvancedCache().getTransactionManager().rollback();

                }
            }
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    protected DefaultCacheManager getVersionedCacheManager() {
        GlobalConfigurationBuilder gcb = new GlobalConfigurationBuilder();
        gcb.jmx().domain(InfinispanConnectionProvider.JMX_DOMAIN).enable();
        final DefaultCacheManager cacheManager = new DefaultCacheManager(gcb.build());

        ConfigurationBuilder invalidationConfigBuilder = new ConfigurationBuilder();
        invalidationConfigBuilder
                //.invocationBatching().enable()
                .transaction().transactionMode(TransactionMode.TRANSACTIONAL)
                .transaction().transactionManagerLookup(new EmbeddedTransactionManagerLookup())
                .locking().isolationLevel(IsolationLevel.REPEATABLE_READ);
                // KEYCLOAK-13692 - Per ISPN-7613 Infinispan:
                // * Automatically enables versioning when needed,
                // * writeSkewCheck automatically enabled for OPTIMISTIC and REPEATABLE_READ transactions
                //.writeSkewCheck(true).versioning()
                //.enable().scheme(VersioningScheme.SIMPLE);

        Configuration invalidationCacheConfiguration = invalidationConfigBuilder.build();
        cacheManager.defineConfiguration(InfinispanConnectionProvider.REALM_CACHE_NAME, invalidationCacheConfiguration);

        return cacheManager;
    }
}


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

namespace AwfulNET.WinRT
{
    public class WebBrowserTask
    {
        public Uri Uri { get; set; }
        public void Show()
        {
            var exec = Launcher.LaunchUriAsync(this.Uri);
        }
    }
}

redpajama_set_name: RedPajamaGithub


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using Mn.NewsCms.Common;

namespace Mn.NewsCms.Web.Models
{
    public class PhotoToday
    {
        public List<FeedItem> Items { get; set; }
    }
}


text:
<?php
// This file is part of Moodle - http://moodle.org/
//
// Moodle is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// Moodle is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with Moodle.  If not, see <http://www.gnu.org/licenses/>.

defined('MOODLE_INTERNAL') || die();

require_once(__DIR__ . '/../interactive/behaviour.php');

/**
 * Question behaviour for interactive mode with count-back scoring.
 *
 * As an example, suppose we have a matching question with 4 parts, and 3 tries
 * (penalty 1/3), and the question is worth 12 marks (so, 3 marks for each part).
 * Suppose also that:
 *  - on the first try, the student gets the first two parts right, and the
 *    other two wrong.
 *  - on the second try, they are sure they got the first part right, so keep
 *    their answer the same, but they change their answer to the second part.
 *    They also get the answer to the thrid part right on this try, but still
 *    get the 4th part wrong.
 *  - On the final try, they get the first 3 parts right, but the 4th part still
 *    wrong.
 * We want to grade them as follows.
 *  - For the first part, they were right first time, and did not change their
 *    answer, so we credit that part as right first time: 3/3
 *  - For the second part, although they were right first time, they then changed
 *    their mind, an only finally got it right on the third try, so 1/3.
 *  - For the third part, they got it right on the second try, and then did not
 *    change their answer, so 2/3.
 *  - For the last part, they were wrong at the last try, so 0/3.
 * So, total mark is 6/12. (Really, a fraction of 0.5.)
 *
 * Of course, the details of the grading are acutally up to the particular
 * question type. The point is that the final grade can take into account all
 * of the tries the student made.
 *
 * @copyright  2009 The Open University
 * @license    http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
 */
class qbehaviour_interactivecountback extends qbehaviour_interactive {

    public function is_compatible_question(question_definition $question) {
        return $question instanceof question_automatically_gradable_with_countback;
    }

    protected function adjust_fraction($fraction, question_attempt_pending_step $pendingstep) {
        $totaltries = $this->qa->get_step(0)->get_behaviour_var('_triesleft');

        $responses = array();
        $lastsave = array();
        foreach ($this->qa->get_step_iterator() as $step) {
            if ($step->has_behaviour_var('submit') &&
                    $step->get_state() != question_state::$invalid) {
                $responses[] = $step->get_qt_data();
                $lastsave = array();
            } else {
                $lastsave = $step->get_qt_data();
            }
        }
        $lastresponse = $pendingstep->get_qt_data();
        if (!empty($lastresponse)) {
            $responses[] = $lastresponse;
        } else if (!empty($lastsave)) {
            $responses[] = $lastsave;
        }

        return $this->question->compute_final_grade($responses, $totaltries);
    }
}


text:
package org.kuali.kpme.tklm.time.service.mobile;

import java.io.Serializable;
import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.kuali.kpme.tklm.api.time.service.mobile.ClockEntryInfoContract;

public class ClockEntryInfo implements Serializable, ClockEntryInfoContract {

	private static final long serialVersionUID = 7132787403000141501L;

	private Timestamp currentTime;

	private Map<String, String> assignKeyToAssignmentDescriptions = new HashMap<String,String>();
	private String lastClockLogDescription;
	private List<String> clockActions = new ArrayList<String>();

	public Map<String, String> getAssignKeyToAssignmentDescriptions() {
		return assignKeyToAssignmentDescriptions;
	}
	public void setAssignKeyToAssignmentDescriptions(
			Map<String, String> assignKeyToAssignmentDescriptions) {
		this.assignKeyToAssignmentDescriptions = assignKeyToAssignmentDescriptions;
	}
	public String getLastClockLogDescription() {
		return lastClockLogDescription;
	}
	public void setLastClockLogDescription(String lastClockLogDescription) {
		this.lastClockLogDescription = lastClockLogDescription;
	}
	public List<String> getClockActions() {
		return clockActions;
	}
	public void setClockActions(List<String> clockActions) {
		this.clockActions = clockActions;
	}
	public Timestamp getCurrentTime() {
		return currentTime;
	}
	public void setCurrentTime(Timestamp currentTime) {
		this.currentTime = currentTime;
	}
}


text:
/**
 * Provides requestAnimationFrame in a cross browser way.
 * http://paulirish.com/
 */
if (!window.requestAnimationFrame) {

    window.requestAnimationFrame = ( function() {

          return  window.requestAnimationFrame       ||
                  window.webkitRequestAnimationFrame ||
                  window.mozRequestAnimationFrame    ||
                  window.oRequestAnimationFrame      ||
                  window.msRequestAnimationFrame     ||
                  function( callback ){
                    window.setTimeout(callback, 1000 / 60);
                  };
        })();
}

var ColorUtils = (function() {

    function randomRange(min, max) {
        return ((Math.random() * (max - min)) + min);
    }
    function hexToR(h) {
        return parseInt((cutHex(h)).substring(0,2),16);
    }
    function hexToG(h) {
        return parseInt((cutHex(h)).substring(2,4),16);
    }
    function hexToB(h) {
        return parseInt((cutHex(h)).substring(4,6),16);
    }
    function cutHex(h) {
        return (h.charAt(0)=="#") ? h.substring(1,7):h;
    }

    return {
        randomRange: randomRange,
        hexToR: hexToR,
        hexToG: hexToG,
        hexToB: hexToB,
        cutHex: cutHex
    };

}());

var ConnectedPoints = (function(){

    var backColor = '#FAFAFA';
    var lineColor = '#0000FF';
    var canvas;
    var c;
    var particleArray = [];

    function init(){
        canvas = document.getElementById("canvas");
        context = canvas.getContext("2d");
        context.canvas.width  = window.innerWidth;
        context.canvas.height = window.innerHeight;
    }

    function onWindowResize() {
        canvas = document.getElementById('canvas');
        canvas.width = window.innerWidth;
        canvas.height = window.innerHeight;
    }

    function onWindowClick() {
        document.getElementById('advise').style.display = 'none';
        particleArray.push(Particle.get());
        console.log(particleArray.length);
    }

    function draw(){

        context.clearRect(0,0,window.innerWidth,window.innerHeight);
        context.fillStyle = backColor;
        context.fillRect(0,0,window.innerWidth,window.innerHeight);

        for(var i=0; i<particleArray.length;i++){

            var particle = particleArray[i];

            context.beginPath();
            context.fillStyle = "rgba("+ColorUtils.hexToR(particle.color)+", "+ColorUtils.hexToG(particle.color)+", "+ColorUtils.hexToB(particle.color)+", "+particle.opacity+")";

            var radius = particle.size/2;
            context.arc(particle.x, particle.y, radius, 0, 2 * Math.PI, false);
            context.fill();
            context.closePath();

            particle.x = particle.x + particle.xSpeed;
            particle.y = particle.y + particle.ySpeed;

            for(var j=0; j<particleArray.length;j++){
                if(j!=i){
                    var particleFriend = particleArray[j];
                    context.lineWidth = 1;
                    context.beginPath();
                    context.moveTo(particle.x,particle.y);
                    context.lineTo(particleFriend.x ,particleFriend.y);
                    context.strokeStyle = lineColor;
                    context.stroke();
                }
            }

            if(particle.x > window.innerWidth+particle.size ||
                particle.y > window.innerHeight+particle.size ||
                particle.x < 0 ||
                particle.y < 0
            ){
                particleArray.splice(i,1);
            }
        }
    }

    return {
        init: init,
        draw: draw,
        onWindowResize: onWindowResize,
        onWindowClick: onWindowClick
    }

}());

var Particle = (function(){

    var velocity = 1;
    var opacity = 0.25;
    var size = 8;
    var color = "#0000FF";

    function get(){
        var particle = {};
        particle.x = ColorUtils.randomRange(0,window.innerWidth);
        particle.y = ColorUtils.randomRange(0,window.innerHeight);
        particle.xSpeed = ColorUtils.randomRange( (-1) * velocity , velocity);
        particle.ySpeed = ColorUtils.randomRange( (-1) * velocity , velocity);
        particle.color = color;
        particle.opacity = opacity;
        particle.size  = size;
        return particle;
    }

    return {
        get: get
    }

}());

var points;

window.onload = function() {
    ConnectedPoints.init();
    animate();
};

window.addEventListener('resize', ConnectedPoints.onWindowResize, false );
window.addEventListener('click', ConnectedPoints.onWindowClick, false );

function animate(){
    requestAnimationFrame(animate);
    ConnectedPoints.draw();
}


text:
import {Component, EventEmitter, Input, OnInit, Output} from '@angular/core';
import {TranslationFile} from '../model/translation-file';
import {TranslationFileView} from '../model/translation-file-view';

/**
 * Component to show the current status of a loaded translation file.
 * It shows the size, number of translations, wether it is changed etc.
 */
@Component({
  selector: 'app-translation-file-status',
  templateUrl: './translation-file-status.component.html',
  styleUrls: ['./translation-file-status.component.css']
})
export class TranslationFileStatusComponent implements OnInit {

  @Input() translationFile: TranslationFile;
  @Input() translationFileView: TranslationFileView;
  @Input() shortInfo = false;

  @Output() saved: EventEmitter<TranslationFile> = new EventEmitter();

  constructor() { }

  ngOnInit() {
  }

  /**
   * percentage translated rounded to 0 digits.
   * @return percentage number
   */
  public percentageTranslated(): string {
    if (this.translationFile) {
      const result: number = this.translationFile.percentageTranslated();
      return result.toFixed(0);
    } else {
      return '0';
    }
  }

  /**
   * Save the changed file.
   */
  public save() {
    if (this.translationFile) {
      this.saved.emit(this.translationFile);
    }
  }
}


text:
namespace parser {

#define RULE_RHS_SYMBOL_TAG(rule, i) (SymbolTable::GetSymbol((rule).GetRHS((i))).GetTag())
#define RULE_LHS_SYMBOL_TAG(rule)    (SymbolTable::GetSymbol((rule).GetLHS()).GetTag())

std::string Item::ToString() const {
  const Rule &rule = GetRule();
  std::string ret = RULE_LHS_SYMBOL_TAG(rule) + " -> ";

  for (size_t i = 0; i < offset; ++i) {
    ret += RULE_RHS_SYMBOL_TAG(rule, i) + " ";
  }
  ret += "•" + RULE_RHS_SYMBOL_TAG(rule, offset);
  for (size_t i = offset + 1; i < rule.GetRHSSize(); ++i) {
    ret += " " + RULE_RHS_SYMBOL_TAG(rule, i);
  }
  return ret;
}

#undef RULE_RHS_SYMBOL_TAG
#undef RULE_LHS_SYMBOL_TAG

std::size_t Item::HashValue() const {
  std::size_t seed = 0;
  boost::hash_combine(seed, rule_id);
  boost::hash_combine(seed, offset);
  return seed;
}

} // namespace parser


text:
package net.ripe.db.whois.common.ip;

/**
 * An interval with a lower-bound and upper-bound. Both bounds are considered to
 * be inclusive.
 *

 * Implementations of this interface must be immutable and must correctly
 * override {@link Object#equals(Object)} and {@link Object#hashCode()} based on
 * the bounds.
 *
 * @param <K> the interval type
 */
public interface Interval<K extends Interval<K>> {

    /**
     * Tests if this interval contains that. Note that if two
     * intervals are equal, they also contain each other (and vice
     * versa). An interval always contains itself.
     *
     * @param that the interval to test for containment
     * @return true if this contains that interval
     */
    boolean contains(K that);

    /**
     * Tests if these two intervals intersect. Two intervals intersect if there
     * exists a point which is contained within both intervals. An interval
     * always intersects itself.
     *
     * @param that the other interval to test for intersection
     * @return true if this interval intersects that
     *         interval
     */
    boolean intersects(K that);

    /**
     * Copies this interval into a new interval that has both its lower and
     * upper-bound set to the original's lower-bound. This is used to be able to
     * compare an interval's lower-bound with another interval's upper-bound.
     *

     *

     *   Interval a = ...
     *   Interval b = ...
     *   if (a.singletonIntervalAtLowerBound().compareUpperBoundTo(b) < 0) ...
     *

     *
     * @return a new interval that has both its lower- and upper-bound set to
     *         this interval's lower-bound
     */
    K singletonIntervalAtLowerBound();

    /**
     * Compare two intervals based on their upper-bounds. This is used by the
     * {@link NestedIntervalMap} implementation to quickly find two potentially
     * intersecting intervals by ordering intervals on the upper-bound and
     * searching based on the lower-bound.
     *
     * @param that the interval to compare the upper-bound with
     * @return <0 if this upper-bound is less than that upper-bound,
 =0 if
     *         this upper-bound equals that upper-bound,
 >0 if this
     *         upper-bound is greater than that upper-bound
     */
    int compareUpperBound(K that);
}


text:
package com.huawei.esdk.fusioncompute.local.impl.resources.net;

import java.util.List;

import org.apache.log4j.Logger;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.huawei.esdk.fusioncompute.local.impl.SDKClient;
import com.huawei.esdk.fusioncompute.local.impl.bean.net.QueryDVSwitchsResp;
import com.huawei.esdk.fusioncompute.local.impl.constant.ESDKURL;
import com.huawei.esdk.fusioncompute.local.impl.constant.NativeConstant;
import com.huawei.esdk.fusioncompute.local.impl.utils.ClientProvider;
import com.huawei.esdk.fusioncompute.local.impl.utils.EsdkVRMException;
import com.huawei.esdk.fusioncompute.local.impl.utils.URLUtils;
import com.huawei.esdk.fusioncompute.local.model.ClientProviderBean;
import com.huawei.esdk.fusioncompute.local.model.FCSDKResponse;
import com.huawei.esdk.fusioncompute.local.model.net.DvSwitchBasicInfo;
import com.huawei.esdk.fusioncompute.local.resources.net.DVSwitchResource;

public class DVSwitchResourceImpl implements DVSwitchResource
{
    private static final Logger LOGGER = Logger.getLogger(DVSwitchResourceImpl.class);

    private static DVSwitchResourceImpl instance = null;

    private Gson gson = new GsonBuilder().serializeNulls().create();

    private SDKClient sdkRestClient;

    private ClientProviderBean bean;

    private ESDKURL esdkUrl = new ESDKURL();

    public static synchronized DVSwitchResourceImpl getInstance(ClientProviderBean bean)
    {
        if (null == instance)
        {
            instance = new DVSwitchResourceImpl();
        }
        instance.init(bean);
        return instance;
    }

    private DVSwitchResourceImpl()
    {

    }

    private void init(ClientProviderBean bean)
    {
        this.bean = bean;
        sdkRestClient = (SDKClient)ClientProvider.getClient(bean);
    }

    @Override
    public FCSDKResponse<List<DvSwitchBasicInfo>> queryDVSwitchs(String siteUri, String location, String name)
    {
        LOGGER.info("queryDVSwitchs() begin");
        FCSDKResponse<List<DvSwitchBasicInfo>> resp = null;

        try
        {
            String json =
                sdkRestClient.get(URLUtils.makeUrl(bean, esdkUrl.getDVSwitchResourceQueryDVSwitchs(), new String[] {siteUri,location,name}));

            QueryDVSwitchsResp result = gson.fromJson(json, QueryDVSwitchsResp.class);
            resp = new FCSDKResponse<List<DvSwitchBasicInfo>>();
            if (null != result)
            {
                resp.setResult(result.getDvSwitchs());
            }
        }
        catch (EsdkVRMException e)
        {
            LOGGER.error("queryDVSwitchs EsdkVRMException", e);
            resp = new FCSDKResponse<List<DvSwitchBasicInfo>>();
            resp.setErrorCode(e.getErrInfo().getErrorCode());
            resp.setErrorDes(e.getErrInfo().getErrorDes());
        }
        catch (Exception e)
        {
            LOGGER.error("queryDVSwitchs Exception", e);
            resp = new FCSDKResponse<List<DvSwitchBasicInfo>>();
            resp.setErrorCode(NativeConstant.NATIVE_EXCEPTION);
            resp.setErrorDes(NativeConstant.NATIVE_EXCEPTION_DES);
        }

        LOGGER.info("sdk resp: " + gson.toJson(resp));
        LOGGER.info("queryDVSwitchs() end");
        return resp;
    }
}


text:
import { sync as globSync } from 'glob'
import { join } from 'path'
import { readFileSync } from 'fs'
import { po } from 'gettext-parser'

const newNameMatcher = regex => filename => filename.match(regex)[1]

export const defaultNameMatcherPatternString = '.*-(.*)\\.po$'
export const defaultPattern = '**/*.po'

export default ({
  messagesPattern = defaultPattern,
  cwd = process.cwd(),
  langMatcherPattern = defaultNameMatcherPatternString,
  langMatcher = newNameMatcher(langMatcherPattern),
  ignore,
}) => {
  const translations = globSync(messagesPattern, { cwd, ignore }).map(filename => {
    const { translations: contexts } = po.parse(readFileSync(join(cwd, filename)), 'utf-8')
    const mergedTranslations = Object.keys(contexts).filter(id => id !== '').reduce(
      (acc, id) => ({
        ...acc,
        [id]: Object.keys(contexts[id]).reduce((msgstr, nextContextObject, _, array) => {
          if (id !== '' && array.length > 1) {
            throw new Error(`More than one message was found for the context ${id}`)
          }
          if (contexts[id][nextContextObject].msgstr.length > 1) {
            /* eslint-disable no-console */
            console.warn(`Plural definitions were found for the context ${id}.
              Plurals are ignored!`)
            /* eslint-enable no-console */
          }
          return contexts[id][nextContextObject].msgstr[0]
        }, ''),
      }),
      {}
    )
    return {
      [langMatcher(filename)]: mergedTranslations,
    }
  })
  return translations.reduce(
    (acc, nextFile) => ({
      ...acc,
      ...nextFile,
    }),
    {}
  )
}


text:
import {Platform} from 'react-native';
import {callNative} from '../NativeNfcManager';
import {handleNativeException} from '../NfcError';

const NdefStatus = {
  NotSupported: 1,
  ReadWrite: 2,
  ReadOnly: 3,
};

class NdefHandler {
  async writeNdefMessage(bytes) {
    return handleNativeException(callNative('writeNdefMessage', [bytes]));
  }

  async getNdefMessage() {
    return handleNativeException(callNative('getNdefMessage'));
  }

  async makeReadOnly() {
    return handleNativeException(callNative('makeReadOnly'));
  }

  async getNdefStatus() {
    if (Platform.OS === 'ios') {
      return handleNativeException(callNative('queryNDEFStatus'));
    } else {
      try {
        const result = await handleNativeException(callNative('getNdefStatus'));
        return {
          status: result.isWritable
            ? NdefStatus.ReadWrite
            : NdefStatus.ReadOnly,
          capacity: result.maxSize,
        };
      } catch (ex) {
        return {
          status: NdefStatus.NotSupported,
          capacity: 0,
        };
      }
    }
  }

  async getCachedNdefMessageAndroid() {
    return handleNativeException(callNative('getCachedNdefMessage'));
  }
}

export {NdefHandler, NdefStatus};


text:
import rospy
import roslaunch
import sys
import time
import os
import wall_avoid
import jackal_move
from sensor_msgs.msg import Joy

class joy_control(object):

    def __init__(self):

        rate = rospy.Rate(5)
        rospy.Subscriber("/bluetooth_teleop/joy", Joy, self.joy_callback)

        self.ready = False
        self.trigger = False
        self.explore_mode = 0
        explore_process = None
        rosbag_process = None
        timer_start = 0
        rospy.loginfo("In start")

        while not rospy.is_shutdown():
            if (self.trigger == True):

                if self.ready == True:

                    package ='rosbag'
                    executable ='record'

                    node = roslaunch.core.Node(package, executable, args="-O "+str(os.path.dirname(os.path.realpath(__file__)))[:-7]+"rosbag/rosbag /tf /scan")

                    launch = roslaunch.scriptapi.ROSLaunch()
                    launch.start()

                    rosbag_process = launch.launch(node)

                    if self.explore_mode == 0:
                        # run = wall_avoid.WallAvoid(runtime)
                        package = 'building_mapper'
                        executable = 'wall_avoid.py'
                    else:
                        # run = jackal_move.discrete_movement(runtime)
                        package = 'building_mapper'
                        executable = 'jackal_move.py'
                    node = roslaunch.core.Node(package, executable)
                    launch = roslaunch.scriptapi.ROSLaunch()
                    launch.start()
                    explore_process = launch.launch(node)
                else:
                    rospy.loginfo("Stopping rosbag record")
                    rosbag_process.stop()
                    explore_process.stop()
                self.trigger = False
            #rate.sleep()

    def joy_callback(self, data):

        x, circ, sq, tri, L1, R1, share, options, p4, L3, R3, DL, DR, DU, DD = data.buttons
        llr, lud, L2, rlr, rud, R2 = data.axes

        # Start exploration
        if (x == 1) and (L2 < 0.9) and (R2 < 0.9) and (self.ready == False):
            rospy.loginfo("Controller code received, commencing exploration protocol...")
            self.trigger = True
            self.ready = True
        # Stop exploration
        if (tri == 1) and (L2 < 0.9) and (R2 < 0.9) and (self.ready == True):
            rospy.loginfo("Controller code received, terminating exploration protocol...")
            self.trigger = True
            self.ready = False
        # Switch to wall_avoid
        if (sq == 1) and (L2 < 0.9) and (R2 < 0.9) and (self.explore_mode == 1):
            rospy.loginfo("Switching to continuous  algorithm...")
            self.explore_mode = 0
        # Switching to jackal_move
        if (circ == 1) and (L2 < 0.9) and (R2 < 0.9) and (self.explore_mode == 0):
            rospy.loginfo("Switching to discrete algorithm...")
            self.explore_mode = 1
        # rospy.sleep(1)

if __name__ == "__main__":

    try:
        rospy.init_node("joy_start", anonymous=False)
        run = joy_control()  #read in joystick input
    except rospy.ROSInterruptException:
        rospy.loginfo("joy_start node terminated.")


text:
'''
Populates the environment variables or a keyring from a json file
and authenticates via Jason Web Token
'''

import json
import os

from boxsdk import JWTAuth, Client

SETTINGS_PATH = './.box'
SETTINGS_FILE = 'app_settings.json'
TOKEN_FILE = 'access_token.txt'

def read_settings(path):
    '''
    Put the exported settings into a dictionary
    '''
    with open(path, 'r', encoding='utf-8') as sfile:
        settings = json.load(sfile)
    return settings

def get_token(token_path):
    '''
    Read a token from a file if it exists
    '''
    if os.path.exists(token_path):
        with open(token_path, 'r') as token_file:
            token = token_file.read()
    return token

def store_token(access_token, _):
    '''
    Store the token in file
    '''
    with open(os.path.join(SETTINGS_PATH, TOKEN_FILE), 'w') as token_file:
        token_file.writelines(access_token)

def main(json_file):
    '''
    Authorize the application and print the user name and email
    '''
    settings = read_settings(json_file)
    auth = JWTAuth(
        client_id=settings['boxAppSettings']['clientID'],
        client_secret=settings['boxAppSettings']['clientSecret'],
        enterprise_id=settings['enterpriseID'],
        jwt_key_id=settings['boxAppSettings']['appAuth']['publicKeyID'],
        rsa_private_key_data=settings['boxAppSettings']['appAuth']
        ['privateKey'],
        rsa_private_key_passphrase=settings['boxAppSettings']['appAuth']
        ['passphrase'],
        store_tokens=store_token,
        access_token=get_token(os.path.join(SETTINGS_PATH, TOKEN_FILE)))
    client = Client(auth)
    current_user = client.user(user_id='me').get()
    print('Successfully authenticated user: {} with email: {}'.format(
        current_user.name, current_user.login))

if __name__ == '__main__':
    main(os.path.join(SETTINGS_PATH, SETTINGS_FILE))


text:
package cn.com.easy.deploy.utils;

import org.springframework.context.ApplicationContext;

/**
 * The Interface SpringContext.
 *
 * @author
 */
public interface SpringContext {

	/**
	 * Gets the spring context.
	 *
	 * @return the spring context
	 */
	public ApplicationContext getSpringContext();
}


text:
namespace avatar
{

	class ImageSystem;

	class VideoStreamClientApp : public VideoStreamNetworkApp
	{

		Q_OBJECT

	public:

		VideoStreamClientApp(QHostAddress const & serverAddress);

	protected:

		virtual void initializeApp() override;

	private:

		QHostAddress m_serverAddress;
		std::array<std::unique_ptr<ImageSystem>, ovrEye_Count> m_imageSystems;

	};

}


text:
using System.Collections.Generic;

namespace OpenDMS.IO
{
    public sealed class FileSystem : Singleton<FileSystem>
    {
		#region Fields (1)

        // Cannot use Dictionary because we can have multiple access to a single file
        private List<FileStream> _handles = null;

		#endregion Fields

		#region Constructors (1)

        public FileSystem()
        {
            _handles = new List<FileStream>();
        }

		#endregion Constructors

		#region Properties (1)

        public int BufferSize { get; private set; }

		#endregion Properties

		#region Methods (4)

		// Public Methods (4)

        public void CloseHandle(FileStream fs)
        {
            if (!_isInitialized)
                throw new NotInitializedException("Must call Initialize.");

            lock (_handles)
            {
                if (!_handles.Contains(fs))
                    throw new HandleExistsException("The handle does not exist.");

                // We force close and dispose, we will not tolerate unmanaged IO
                fs.Close();
                fs.Dispose();

                // Drop it from handles - btw we can say remove knowing it will hit the correct resource
                // because it is located using the HashCode, which will have customized to always test itself for
                // uniqueness within handles.
                _handles.Remove(fs);

                if (Logger.FileSystem != null)
                    Logger.FileSystem.Debug("Handle released for " + fs.GetLogString());
            }
        }

        public bool HandleExists(FileStream fs)
        {
            if (!_isInitialized)
                throw new NotInitializedException("Must call Initialize.");

            lock (_handles)
            {
                return _handles.Contains(fs);
            }
        }

        public void Initialize(int bufferSize)
        {
            BufferSize = bufferSize;
            _isInitialized = true;
        }

        public void RegisterHandle(FileStream fs)
        {
            if (!_isInitialized)
                throw new NotInitializedException("Must call Initialize.");

            List<FileStream>.Enumerator en;

            lock (_handles)
            {
                en = _handles.GetEnumerator();

                while (en.MoveNext())
                {
                    if (fs.File.ToString() == en.Current.File.ToString())
                    {
                        if ((en.Current.Share & (System.IO.FileShare)fs.Access) != (System.IO.FileShare)fs.Access)
                        {
                            if (Logger.FileSystem != null)
                                Logger.FileSystem.Error("The resource is already open and the requested access conflicts with the existing share.\r\n" + en.Current.GetLogString());
                            throw new AccessException("Resource in use.");
                        }
                    }
                }

                if (_handles.Contains(fs))
                    throw new HandleExistsException("A handle already exists.");

                _handles.Add(fs);

                if (Logger.FileSystem != null)
                    Logger.FileSystem.Debug("Handle registered for " + fs.GetLogString());
            }
        }

		#endregion Methods
    }
}


text:
namespace ConnectionManager
{
    public class GameSocketManagerStatics
    {
        public static readonly int BUFFER_SIZE = 8192;
        public static readonly int MAX_PACKET_SIZE = BUFFER_SIZE - 4;
    }
}


text:
namespace org {
  namespace apache {
    namespace lucene {
      namespace store {
        class DataInput;
      }
    }
  }
}
namespace java {
  namespace lang {
    class String;
    class Class;
  }
}
template<class T> class JArray;

namespace org {
  namespace apache {
    namespace lucene {
      namespace index {

        class IndexFormatTooNewException : public ::org::apache::lucene::index::CorruptIndexException {
        public:
          enum {
            mid_init$_b8e753a2,
            mid_init$_9c112331,
            max_mid
          };

          static ::java::lang::Class *class$;
          static jmethodID *mids$;
          static bool live$;
          static jclass initializeClass(bool);

          explicit IndexFormatTooNewException(jobject obj) : ::org::apache::lucene::index::CorruptIndexException(obj) {
            if (obj != NULL)
              env->getClass(initializeClass);
          }
          IndexFormatTooNewException(const IndexFormatTooNewException& obj) : ::org::apache::lucene::index::CorruptIndexException(obj) {}

          IndexFormatTooNewException(const ::java::lang::String &, jint, jint, jint);
          IndexFormatTooNewException(const ::org::apache::lucene::store::DataInput &, jint, jint, jint);
        };
      }
    }
  }
}

#include <Python.h>

namespace org {
  namespace apache {
    namespace lucene {
      namespace index {
        extern PyTypeObject PY_TYPE(IndexFormatTooNewException);

        class t_IndexFormatTooNewException {
        public:
          PyObject_HEAD
          IndexFormatTooNewException object;
          static PyObject *wrap_Object(const IndexFormatTooNewException&);
          static PyObject *wrap_jobject(const jobject&);
          static void install(PyObject *module);
          static void initialize(PyObject *module);
        };
      }
    }
  }
}

#endif


text:
<?php

namespace CoreBundle\Controller;

use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\HttpFoundation\Request;
use CoreBundle\Entity\Link;
use CoreBundle\Form\LinkType;
use Symfony\Component\Routing\Annotation\Route;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\ParamConverter;
use CoreBundle\Entity\Notification;
use CoreBundle\Enum\NotificationTypeEnum;
use UserBundle\Entity\User;

class LinkController extends Controller
{
    public function indexAction()
    {
        $repository = $this
        ->getDoctrine()
        ->getManager()
        ->getRepository('CoreBundle:Link');

        $listLink = $repository->findByUser($this->getUser());

        return $this->render('CoreBundle:Link:index.html.twig', array('listLink' => $listLink));
    }

    public function addAction(Request $request)
    {
        $link = new Link();
        $form   = $this->createForm(LinkType::class, $link, array('user'=>$this->getUser()));

        if ($request->isMethod('POST') && $form->handleRequest($request)->isValid()) {
            $em = $this->getDoctrine()->getManager();
            $em->persist($link);
            $em->flush();

            $request->getSession()->getFlashBag()->add('success', $this->get('translator')->trans('link.add_success'));

            return $this->redirectToRoute('core_links', array());
        };

        return $this->render('CoreBundle:Link:add_update.html.twig', array(
            'form' => $form->createView(),
            'submitButtonLabel' => 'form.submit.add'
        ));
    }

    public function updateAction(Request $request, $id){
        $repository = $this
        ->getDoctrine()
        ->getManager()
        ->getRepository('CoreBundle:Link');

        $link = $repository->findByIdWithUser($id);

        $form   = $this->createForm(LinkType::class, $link, array('user'=>$this->getUser()));

        if ($request->isMethod('POST') && $form->handleRequest($request)->isValid()) {
            $em = $this->getDoctrine()->getManager();
            $em->flush();

            $request->getSession()->getFlashBag()->add('success', $this->get('translator')->trans('link.update_success'));

            return $this->redirectToRoute('core_links');
        };

        return $this->render('CoreBundle:Link:add_update.html.twig', array(
            'form' => $form->createView(),
            'submitButtonLabel' => 'form.submit.update'
        ));
    }

    public function deleteAction(Request $request, $id){
        $repository = $this
        ->getDoctrine()
        ->getManager()
        ->getRepository('CoreBundle:Link');

        $link = $repository->findOneById($id);

        $em = $this->getDoctrine()->getManager();
        $em->remove($link);
        $em->flush();

        $request->getSession()->getFlashBag()->add('success', $this->get('translator')->trans('link.delete_success'));

        return $this->redirectToRoute('core_links');
    }

    public function copyAction(Request $request, Link $link, $category = null){

        $em = $this->getDoctrine()->getManager();

        $new_link = clone $link;

        if(null === $category){ //On copie juste un lien

            $new_link->setCategory();

            $form   = $this->createForm(LinkType::class, $new_link, array('user'=>$this->getUser()));

            if ($request->isMethod('POST') && $form->handleRequest($request)->isValid()) {
                $em = $this->getDoctrine()->getManager();
                $em->persist($new_link);
                $em->flush();

                $request->getSession()->getFlashBag()->add('success', $this->get('translator')->trans('link.copy_success'));

                return $this->redirectToRoute('core_links');
            };

            return $this->render('CoreBundle:Link:add_update.html.twig', array(
                'form' => $form->createView(),
                'submitButtonLabel' => 'form.submit.add'
            ));
        }
        else{ //On copie une catégorie entière

            $new_link->setCategory($category);

            $em->persist($new_link);
            $em->flush();

            $request->getSession()->getFlashBag()->add('success', $this->get('translator')->trans('link.copy_success'));

            return $this->redirectToRoute('core_homepage');
        }
    }

    /**
     * @Route()()   ("/share/link/{id_link}/user/{id_user}")
     * @ParamConverter("link", options={"id" = "id_link"})
     * @ParamConverter("user", options={"id" = "id_user"})
     */
    public function shareAction(Request $request, Link $link, User $user){
        $notification = new Notification();
        $notification->setCreationDate(new \DateTime());
        $notification->setTypemessage(NotificationTypeEnum::TYPE_SHARE);
        $notification->setEntity($link->getId());
        $notification->setUserReceiver($user);
        $notification->setUserSender($this->getUser());
        $classname = explode('\\', Link::class);
        $classname = array_pop($classname);
        $notification->setEntitytype($classname);

        $em = $this->getDoctrine()->getManager();
        $em->persist($notification);
        $em->flush();

        $request->getSession()->getFlashBag()->add('success', $this->get('translator')->trans('link.share_success'));

        return $this->redirectToRoute('core_homepage');
    }
}


text:
(function () {
  "use strict";

  angular
    .module('mnServices', [])
    .directive('mnServices', mnServicesDirective);

  function mnServicesDirective(mnPools) {
    var mnServices = {
      restrict: 'A',
      scope: {
        config: '=mnServices'
      },
      templateUrl: 'app-classic/components/directives/mn_services/mn_services.html',
      controller: controller
    };

    return mnServices;

    function controller($scope) {
      mnPools.get().then(function (pool) {
        $scope.isEnterprise = pool.isEnterprise;
        $scope.onChange = function (value, model) {
          if (!pool.isEnterprise) {
            $scope.config.services.model[model] = value;
          }
        };
      });
    }
  }
})();


text:
set -euo pipefail
IFS=$'\t\n'

cd /home/fkalter/scripts/sabnzbd

for filename in "$@"; do
    ./cleanup_combined.sh "$filename"
done


text:
ACCEPTED

#### According to
The Catalogue of Life, 3rd January 2011

#### Published in
Fl. Ind. occid. 1:594. 1797

#### Original name
null

### Remarks
null


text:
package perf;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.ObjectWriter;
import com.fasterxml.jackson.databind.SerializationFeature;

abstract class ObjectWriterTestBase<T1,T2>
{
    protected int hash;

    protected abstract int targetSizeMegs();

    protected void test(ObjectMapper mapper,
            String desc1, T1 inputValue1, Class<? extends T1> inputClass1,
            String desc2, T2 inputValue2, Class<? extends T2> inputClass2)
        throws Exception
    {
        final int REPS;
        {
            final byte[] input1 = mapper.writeValueAsBytes(inputValue1);
            final byte[] input2 = mapper.writeValueAsBytes(inputValue2);

            // Let's try to guestimate suitable size, N megs of output
            REPS = (int) ((double) (targetSizeMegs() * 1000 * 1000) / (double) input1.length);
            System.out.printf("Read %d bytes to bind (%d as array); will do %d repetitions\n",
                    input1.length, input2.length, REPS);
        }

        final ObjectWriter writer0 = mapper.writer().with(SerializationFeature.EAGER_SERIALIZER_FETCH);
        final ObjectWriter writer1 = writer0.forType(inputClass1);
        final ObjectWriter writer2 = writer0.forType(inputClass2);

        int i = 0;
        int roundsDone = 0;
        final int TYPES = 2;

        // Skip first 5 seconds
        long startMeasure = System.currentTimeMillis() + 5000L;
        System.out.print("Warming up");

        final double[] timesMsec = new double[TYPES];

        while (true) {
            final int round = (i % TYPES);
            final boolean lf = (++i % TYPES) == 0;

            String msg;

            ObjectWriter writer;
            Object value;
            switch (round) {
            case 0:
                msg = desc1;
                writer = writer1;
                value = inputValue1;
                break;
            case 1:
                msg = desc2;
                writer = writer2;
                value = inputValue2;
                break;
            default:
                throw new Error();
            }

            double msecs = testSer(REPS, value, writer);

            // skip first N seconds to let results stabilize
            if (startMeasure > 0L) {
                if ((round != 0) || (System.currentTimeMillis() < startMeasure)) {
                    System.out.print(".");
                    continue;
                }
                startMeasure = 0L;
                System.out.println();
                System.out.println("Starting measurements...");
                Thread.sleep(250L);
                System.out.println();
            }

            timesMsec[round] += msecs;

            if ((i % 17) == 0) {
                System.out.println("[GC]");
                Thread.sleep(100L);
                System.gc();
                Thread.sleep(100L);
            }

            System.out.printf("Test '%s' [hash: 0x%s] -> %.1f msecs\n", msg, hash, msecs);
            Thread.sleep(50L);
            if (!lf) {
                continue;
            }

            if ((++roundsDone % 3) == 0) {
                double den = (double) roundsDone;
                System.out.printf("Averages after %d rounds (%s/%s): %.1f / %.1f msecs\n",
                        roundsDone, desc1, desc2,
                        timesMsec[0] / den, timesMsec[1] / den);
            }
            System.out.println();
        }
    }

    protected double testSer(int REPS, Object value, ObjectWriter writer) throws Exception
    {
        final NopOutputStream out = new NopOutputStream();
        long start = System.nanoTime();
        while (--REPS >= 0) {
            writer.writeValue(out, value);
        }
        hash = out.size();
        long nanos = System.nanoTime() - start;
        out.close();
        return _msecsFromNanos(nanos);
    }

    protected final double _msecsFromNanos(long nanos) {
        return (nanos / 1000000.0);
    }
}


text:
package vcard

import (
	"strconv"
	"strings"
	"time"
)

// MIME type and file extension for VCard, defined in RFC 6350 section 10.1.
const (
	MIMEType  = "text/vcard"
	Extension = "vcf"
)

const timestampLayout = "20060102T150405Z"

// Card property parameters.
const (
	ParamLanguage      = "LANGUAGE"
	ParamValue         = "VALUE"
	ParamPreferred     = "PREF"
	ParamAltID         = "ALTID"
	ParamPID           = "PID"
	ParamType          = "TYPE"
	ParamMediaType     = "MEDIATYPE"
	ParamCalendarScale = "CALSCALE"
	ParamSortAs        = "SORT-AS"
	ParamGeolocation   = "GEO"
	ParamTimezone      = "TZ"
)

// Card properties.
const (
	// General Properties
	FieldSource = "SOURCE"
	FieldKind   = "KIND"
	FieldXML    = "XML"

	// Identification Properties
	FieldFormattedName = "FN"
	FieldName          = "N"
	FieldNickname      = "NICKNAME"
	FieldPhoto         = "PHOTO"
	FieldBirthday      = "BDAY"
	FieldAnniversary   = "ANNIVERSARY"
	FieldGender        = "GENDER"

	// Delivery Addressing Properties
	FieldAddress = "ADR"

	// Communications Properties
	FieldTelephone = "TEL"
	FieldEmail     = "EMAIL"
	FieldIMPP      = "IMPP" // Instant Messaging and Presence Protocol
	FieldLanguage  = "LANG"

	// Geographical Properties
	FieldTimezone    = "TZ"
	FieldGeolocation = "GEO"

	// Organizational Properties
	FieldTitle        = "TITLE"
	FieldRole         = "ROLE"
	FieldLogo         = "LOGO"
	FieldOrganization = "ORG"
	FieldMember       = "MEMBER"
	FieldRelated      = "RELATED"

	// Explanatory Properties
	FieldCategories   = "CATEGORIES"
	FieldNote         = "NOTE"
	FieldProductID    = "PRODID"
	FieldRevision     = "REV"
	FieldSound        = "SOUND"
	FieldUID          = "UID"
	FieldClientPIDMap = "CLIENTPIDMAP"
	FieldURL          = "URL"
	FieldVersion      = "VERSION"

	// Security Properties
	FieldKey = "KEY"

	// Calendar Properties
	FieldFreeOrBusyURL      = "FBURL"
	FieldCalendarAddressURI = "CALADRURI"
	FieldCalendarURI        = "CALURI"
)

func maybeGet(l []string, i int) string {
	if i < len(l) {
		return l[i]
	}
	return ""
}

// A Card is an address book entry.
type Card map[string][]*Field

// Get returns the first field of the card for the given property. If there is
// no such field, it returns nil.
func (c Card) Get(k string) *Field {
	fields := c[k]
	if len(fields) == 0 {
		return nil
	}
	return fields[0]
}

// Add adds the k, f pair to the list of fields. It appends to any existing
// fields.
func (c Card) Add(k string, f *Field) {
	c[k] = append(c[k], f)
}

// Set sets the key k to the single field f. It replaces any existing field.
func (c Card) Set(k string, f *Field) {
	c[k] = []*Field{f}
}

// Preferred returns the preferred field of the card for the given property.
func (c Card) Preferred(k string) *Field {
	fields := c[k]
	if len(fields) == 0 {
		return nil
	}

	field := fields[0]
	min := 100
	for _, f := range fields {
		n := 100
		if pref := f.Params.Get(ParamPreferred); pref != "" {
			n, _ = strconv.Atoi(pref)
		} else if f.Params.HasType("pref") {
			// Apple Contacts adds "pref" to the TYPE param
			n = 1
		}

		if n < min {
			min = n
			field = f
		}
	}
	return field
}

// Value returns the first field value of the card for the given property. If
// there is no such field, it returns an empty string.
func (c Card) Value(k string) string {
	f := c.Get(k)
	if f == nil {
		return ""
	}
	return f.Value
}

// AddValue adds the k, v pair to the list of field values. It appends to any
// existing values.
func (c Card) AddValue(k, v string) {
	c.Add(k, &Field{Value: v})
}

// SetValue sets the field k to the single value v. It replaces any existing
// value.
func (c Card) SetValue(k, v string) {
	c.Set(k, &Field{Value: v})
}

// PreferredValue returns the preferred field value of the card.
func (c Card) PreferredValue(k string) string {
	f := c.Preferred(k)
	if f == nil {
		return ""
	}
	return f.Value
}

// Values returns a list of values for a given property.
func (c Card) Values(k string) []string {
	fields := c[k]
	if fields == nil {
		return nil
	}

	values := make([]string, len(fields))
	for i, f := range fields {
		values[i] = f.Value
	}
	return values
}

// Kind returns the kind of the object represented by this card. If it isn't
// specified, it returns the default: KindIndividual.
func (c Card) Kind() Kind {
	kind := strings.ToLower(c.Value(FieldKind))
	if kind == "" {
		return KindIndividual
	}
	return Kind(kind)
}

// SetKind sets the kind of the object represented by this card.
func (c Card) SetKind(kind Kind) {
	c.SetValue(FieldKind, string(kind))
}

// FormattedNames returns formatted names of the card. The length of the result
// is always greater or equal to 1.
func (c Card) FormattedNames() []*Field {
	fns := c[FieldFormattedName]
	if len(fns) == 0 {
		return []*Field{{Value: ""}}
	}
	return fns
}

// Names returns names of the card.
func (c Card) Names() []*Name {
	ns := c[FieldName]
	if ns == nil {
		return nil
	}

	names := make([]*Name, len(ns))
	for i, n := range ns {
		names[i] = newName(n)
	}
	return names
}

// Name returns the preferred name of the card. If it isn't specified, it
// returns nil.
func (c Card) Name() *Name {
	n := c.Preferred(FieldName)
	if n == nil {
		return nil
	}
	return newName(n)
}

// AddName adds the specified name to the list of names.
func (c Card) AddName(name *Name) {
	c.Add(FieldName, name.field())
}

// SetName replaces the list of names with the single specified name.
func (c Card) SetName(name *Name) {
	c.Set(FieldName, name.field())
}

// Gender returns this card's gender.
func (c Card) Gender() (sex Sex, identity string) {
	v := c.Value(FieldGender)
	parts := strings.SplitN(v, ";", 2)
	return Sex(strings.ToUpper(parts[0])), maybeGet(parts, 1)
}

// SetGender sets this card's gender.
func (c Card) SetGender(sex Sex, identity string) {
	v := string(sex)
	if identity != "" {
		v += ";" + identity
	}
	c.SetValue(FieldGender, v)
}

// Addresses returns addresses of the card.
func (c Card) Addresses() []*Address {
	adrs := c[FieldAddress]
	if adrs == nil {
		return nil
	}

	addresses := make([]*Address, len(adrs))
	for i, adr := range adrs {
		addresses[i] = newAddress(adr)
	}
	return addresses
}

// Address returns the preferred address of the card. If it isn't specified, it
// returns nil.
func (c Card) Address() *Address {
	adr := c.Preferred(FieldAddress)
	if adr == nil {
		return nil
	}
	return newAddress(adr)
}

// AddAddress adds an address to the list of addresses.
func (c Card) AddAddress(address *Address) {
	c.Add(FieldAddress, address.field())
}

// SetAddress replaces the list of addresses with the single specified address.
func (c Card) SetAddress(address *Address) {
	c.Set(FieldAddress, address.field())
}

// Categories returns category information about the card, also known as "tags".
func (c Card) Categories() []string {
	return strings.Split(c.PreferredValue(FieldCategories), ",")
}

// SetCategories sets category information about the card.
func (c Card) SetCategories(categories []string) {
	c.SetValue(FieldCategories, strings.Join(categories, ","))
}

// Revision returns revision information about the current card.
func (c Card) Revision() (time.Time, error) {
	rev := c.Value(FieldRevision)
	if rev == "" {
		return time.Time{}, nil
	}
	return time.Parse(timestampLayout, rev)
}

// SetRevision sets revision information about the current card.
func (c Card) SetRevision(t time.Time) {
	c.SetValue(FieldRevision, t.Format(timestampLayout))
}

// A field contains a value and some parameters.
type Field struct {
	Value  string
	Params Params
	Group  string
}

// Params is a set of field parameters.
type Params map[string][]string

// Get returns the first value with the key k. It returns an empty string if
// there is no such value.
func (p Params) Get(k string) string {
	values := p[k]
	if len(values) == 0 {
		return ""
	}
	return values[0]
}

// Add adds the k, v pair to the list of parameters. It appends to any existing
// values.
func (p Params) Add(k, v string) {
	p[k] = append(p[k], v)
}

// Set sets the parameter k to the single value v. It replaces any existing
// value.
func (p Params) Set(k, v string) {
	p[k] = []string{v}
}

// Types returns the field types.
func (p Params) Types() []string {
	types := p[ParamType]
	list := make([]string, len(types))
	for i, t := range types {
		list[i] = strings.ToLower(t)
	}
	return list
}

// HasType returns true if and only if the field have the provided type.
func (p Params) HasType(t string) bool {
	for _, tt := range p[ParamType] {
		if strings.EqualFold(t, tt) {
			return true
		}
	}
	return false
}

// Kind is an object's kind.
type Kind string

// Values for FieldKind.
const (
	KindIndividual   Kind = "individual"
	KindGroup        Kind = "group"
	KindOrganization Kind = "org"
	KindLocation     Kind = "location"
)

// Values for ParamType.
const (
	// Generic
	TypeHome = "home"
	TypeWork = "work"

	// For FieldTelephone
	TypeText      = "text"
	TypeVoice     = "voice" // Default
	TypeFax       = "fax"
	TypeCell      = "cell"
	TypeVideo     = "video"
	TypePager     = "pager"
	TypeTextPhone = "textphone"

	// For FieldRelated
	TypeContact      = "contact"
	TypeAcquaintance = "acquaintance"
	TypeFriend       = "friend"
	TypeMet          = "met"
	TypeCoWorker     = "co-worker"
	TypeColleague    = "colleague"
	TypeCoResident   = "co-resident"
	TypeNeighbor     = "neighbor"
	TypeChild        = "child"
	TypeParent       = "parent"
	TypeSibling      = "sibling"
	TypeSpouse       = "spouse"
	TypeKin          = "kin"
	TypeMuse         = "muse"
	TypeCrush        = "crush"
	TypeDate         = "date"
	TypeSweetheart   = "sweetheart"
	TypeMe           = "me"
	TypeAgent        = "agent"
	TypeEmergency    = "emergency"
)

// Name contains an object's name components.
type Name struct {
	*Field

	FamilyName      string
	GivenName       string
	AdditionalName  string
	HonorificPrefix string
	HonorificSuffix string
}

func newName(field *Field) *Name {
	components := strings.Split(field.Value, ";")
	return &Name{
		field,
		maybeGet(components, 0),
		maybeGet(components, 1),
		maybeGet(components, 2),
		maybeGet(components, 3),
		maybeGet(components, 4),
	}
}

func (n *Name) field() *Field {
	if n.Field == nil {
		n.Field = new(Field)
	}
	n.Field.Value = strings.Join([]string{
		n.FamilyName,
		n.GivenName,
		n.AdditionalName,
		n.HonorificPrefix,
		n.HonorificSuffix,
	}, ";")
	return n.Field
}

// Sex is an object's biological sex.
type Sex string

const (
	SexUnspecified Sex = ""
	SexFemale      Sex = "F"
	SexMale        Sex = "M"
	SexOther       Sex = "O"
	SexNone        Sex = "N"
	SexUnknown     Sex = "U"
)

// An Address is a delivery address.
type Address struct {
	*Field

	PostOfficeBox   string
	ExtendedAddress string // e.g., apartment or suite number
	StreetAddress   string
	Locality        string // e.g., city
	Region          string // e.g., state or province
	PostalCode      string
	Country         string
}

func newAddress(field *Field) *Address {
	components := strings.Split(field.Value, ";")
	return &Address{
		field,
		maybeGet(components, 0),
		maybeGet(components, 1),
		maybeGet(components, 2),
		maybeGet(components, 3),
		maybeGet(components, 4),
		maybeGet(components, 5),
		maybeGet(components, 6),
	}
}

func (a *Address) field() *Field {
	if a.Field == nil {
		a.Field = new(Field)
	}
	a.Field.Value = strings.Join([]string{
		a.PostOfficeBox,
		a.ExtendedAddress,
		a.StreetAddress,
		a.Locality,
		a.Region,
		a.PostalCode,
		a.Country,
	}, ";")
	return a.Field
}


text:
The *GoodData Java SDK* encapsulates the REST API of the **GoodData Platform**.
The first version was implemented during the [All Data Hackathon](http://hackathon.gooddata.com) April 10 - 11 2014.
It is free and open-source software provided "as-is" under the [BSD License](LICENSE.txt) as an official project by [GoodData Corporation](http://www.gooddata.com).

## Usage

The *GoodData Java SDK* is available in Maven Central Repository, to use it from Maven add to `pom.xml`:

```xml
<dependency>
    <groupId>com.gooddata</groupId>
    <artifactId>gooddata-java</artifactId>
    <version>2.4.0</version>
</dependency>
```
See [releases page](https://github.com/gooddata/gooddata-java/releases) for information about versions and notable changes,
the [Upgrading Guide](https://github.com/gooddata/gooddata-java/wiki/Upgrading-GoodData-Java-SDK) will navigate you
through changes between major versions.

See [Javadocs](http://javadoc.io/doc/com.gooddata/gooddata-java)
or [Wiki](https://github.com/gooddata/gooddata-java/wiki) for
[Code Examples](https://github.com/gooddata/gooddata-java/wiki/Code-Examples)
and [Extensibility How-To](https://github.com/gooddata/gooddata-java/wiki/Extending).

### Dependencies

The *GoodData Java SDK* uses:
* the [GoodData HTTP client](https://github.com/gooddata/gooddata-http-client) version 0.9.3 or later
* the *Apache HTTP Client* version 4.3 or later (for white-labeled domains at least version 4.3.2 is required)
* the *Spring Framework* version 4.3.*
* the *Jackson JSON Processor* version 2.8.*
* the *Java Development Kit (JDK)* version 8 or later

## Development

Build the library with `mvn package`, see the
[Testing](https://github.com/gooddata/gooddata-java/wiki/Testing) page for different testing methods.

## Contribute

Found a bug? Please create an [issue](https://github.com/gooddata/gooddata-java/issues). Missing functionality?
[Contribute your code](CONTRIBUTING.md).


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

import com.facebook.presto.execution.QueryManagerConfig;
import com.facebook.presto.spi.resourceGroups.ResourceGroup;
import com.facebook.presto.spi.resourceGroups.ResourceGroupConfigurationManager;
import com.facebook.presto.spi.resourceGroups.ResourceGroupConfigurationManagerContext;
import com.facebook.presto.spi.resourceGroups.ResourceGroupConfigurationManagerFactory;
import com.facebook.presto.spi.resourceGroups.ResourceGroupId;
import com.facebook.presto.spi.resourceGroups.ResourceGroupSelector;
import com.facebook.presto.spi.resourceGroups.SelectionContext;
import com.google.common.collect.ImmutableList;

import javax.inject.Inject;

import java.util.List;
import java.util.Map;
import java.util.Optional;

import static com.google.common.base.Preconditions.checkArgument;

public class LegacyResourceGroupConfigurationManagerFactory
        implements ResourceGroupConfigurationManagerFactory
{
    public static final String LEGACY_RESOURCE_GROUP_MANAGER = "legacy";
    private static final ResourceGroupId GLOBAL = new ResourceGroupId("global");

    private final int maxRunning;
    private final int maxQueued;

    @Inject
    public LegacyResourceGroupConfigurationManagerFactory(QueryManagerConfig config)
    {
        maxRunning = config.getMaxConcurrentQueries();
        maxQueued = config.getMaxQueuedQueries();
    }

    @Override
    public String getName()
    {
        return LEGACY_RESOURCE_GROUP_MANAGER;
    }

    @Override
    public ResourceGroupConfigurationManager create(Map<String, String> config, ResourceGroupConfigurationManagerContext context)
    {
        return new LegacyResourceGroupConfigurationManager();
    }

    public class LegacyResourceGroupConfigurationManager
            implements ResourceGroupConfigurationManager
    {
        @Override
        public void configure(ResourceGroup group, SelectionContext context)
        {
            checkArgument(group.getId().equals(GLOBAL), "Unexpected resource group: %s", group.getId());
            group.setMaxQueuedQueries(maxQueued);
            group.setMaxRunningQueries(maxRunning);
        }

        @Override
        public List<ResourceGroupSelector> getSelectors()
        {
            return ImmutableList.of(context -> Optional.of(GLOBAL));
        }
    }
}


text:
using Fiddler;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Windows;
using System.Windows.Controls;

namespace Gizeta.KanColleModifier.KCV
{
    /// <summary>
    /// ModifierView.xaml 的交互逻辑
    /// </summary>
    public partial class ModifierView : UserControl
    {
        private static bool modifierOn = false;
        private static bool hasInitialize = false;
        private static Dictionary<string, string> data = new Dictionary<string, string>();

        public ModifierView()
        {
            InitializeComponent();
            readModifierData();
            showList();
            setModifier();
            toggle(modifierOn);
        }

        public static void Initialize()
        {
            if(File.Exists("modifier.enable"))
            {
                modifierOn = true;
                readModifierData();
                setModifier();
            }
        }

        private static void setModifier()
        {
            if (!hasInitialize)
            {
                hasInitialize = true;
                FiddlerApplication.BeforeRequest += FiddlerApplication_BeforeRequest;
                FiddlerApplication.BeforeResponse += FiddlerApplication_BeforeResponse;
            }
        }

        private static void FiddlerApplication_BeforeResponse(Session oSession)
        {
            if (modifierOn && oSession.fullUrl.IndexOf("/kcs/resources/swf/ships/") >= 0)
            {
                var tmp1 = oSession.fullUrl.Split('/');
                var tmp2 = tmp1.Last().Split('.');
                if (tmp2.Length >= 1)
                {
                    if (data.ContainsKey(tmp2[0]))
                    {
                        oSession.utilDecodeResponse();
                        oSession.ResponseBody = File.ReadAllBytes(data[tmp2[0]]);
                        oSession.oResponse.headers.HTTPResponseCode = 200;
                        oSession.oResponse.headers.HTTPResponseStatus = "200 OK";
                    }
                }
            }
        }

        private static void FiddlerApplication_BeforeRequest(Session oSession)
        {
            if (modifierOn && oSession.fullUrl.IndexOf("/kcs/resources/swf/ships/") >= 0)
            {
                var tmp1 = oSession.fullUrl.Split('/');
                var tmp2 = tmp1.Last().Split('.');
                if (tmp2.Length >= 1)
                {
                    if (data.ContainsKey(tmp2[0]))
                    {
                        oSession.bBufferResponse = true;
                    }
                }
            }
        }

        private static void readModifierData()
        {
            if(File.Exists("魔改.txt"))
            {
                data.Clear();
                var file = File.Open("魔改.txt", FileMode.Open);
                using (var stream = new StreamReader(file))
                {
                    while (!stream.EndOfStream)
                    {
                        var str = stream.ReadLine();
                        var st = str.LastIndexOf('\\') + 1;
                        var ed = str.LastIndexOf(".hack.swf");
                        if (st > 0 && ed > 0)
                        {
                            if (File.Exists(str))
                            {
                                data.Add(str.Substring(st, ed - st), str);
                            }
                        }
                    }
                }
                file.Close();
            }
            else
            {
                modifierOn = false;
            }
        }

        private void showList()
        {
            Modifier_List.Text = "魔改文件:";
            foreach (var d in data)
            {
                Modifier_List.Text += "\r\n" + d.Value;
            }
        }

        private void Modifier_Switch_Click(object sender, RoutedEventArgs e)
        {
            toggle(Modifier_Switch.Content.ToString() == "开启魔改");
        }

        private void Modifier_UpdateList_Click(object sender, RoutedEventArgs e)
        {
            readModifierData();
            showList();
        }

        private void toggle(bool on)
        {
            if(on)
            {
                modifierOn = true;
                Modifier_Switch.Content = "关闭魔改";
                if(!File.Exists("modifier.enable"))
                {
                    File.Create("modifier.enable").Close();
                }
            }
            else
            {
                modifierOn = false;
                Modifier_Switch.Content = "开启魔改";
                if (File.Exists("modifier.enable"))
                {
                    File.Delete("modifier.enable");
                }
            }
        }
    }
}


text:
jquery-stickyscroll
===================

Tiny jQuery plugin (~0.3kb minified) to pin an element to the top of the screen when the user scrolls past it.

####Requirements
This approach requires that the element have a width set. For all the usecases I have come across so far this has been easy to accommodate. Future versions may negate this need.

####Options
At the moment there is only one option, `verticalPadding`, this is the distance in pixels from the top of the screen that the sticky element will stay.


text:
namespace RoutesSystem.Model.SQLiteModels
{
    public class DriverInfo
    {
        public long Id { get; set; }

        public string StartTown { get; set; }

        public string EndTown { get; set; }

        public string DriverFirstName { get; set; }

        public string DriverLastName { get; set; }

        public decimal DriverSalary { get; set; }

        public decimal RouteDistance { get; set; }
    }
}


text:
package analytics

import (
	"bytes"
	"context"
	"fmt"
	"net/http"
	"net/url"
	"strconv"
)

const (
	defaultEndpoint  = "https://www.google-analytics.com/"
	defaultBatchSize = 20 // The maximum number supported by batch endpoint.
)

// Hit represents a single analytics event (called a 'hit').
type Hit map[string]string

// Event generates a new event typed hit.  The label may be empty and the
// value may be nil but category and action are required.
func Event(category, action, label string, value *int64) Hit {
	hit := Hit{
		"t":  "event",
		"ec": category,
		"ea": action,
	}
	if label != "" {
		hit["el"] = label
	}
	if value != nil {
		hit["ev"] = strconv.FormatInt(*value, 10)
	}
	return hit
}

// Client defines a type for communicating with Google Analytics.  To create a
// properly initialized Client instance, use NewClient.
type Client struct {
	propertyID string
	clientID   string
	endpoint   string
	batchSize  int
}

// NewClient returns a Client sends hits to analytics using the provided IDs.
func NewClient(propertyID, clientID string) *Client {
	return &Client{propertyID, clientID, defaultEndpoint, defaultBatchSize}
}

// Send attempts to upload the provided hits to the analytics server.
func (client *Client) Send(hits []Hit) error {
	if len(hits) > 0 {
		if err := client.upload(hits); err != nil {
			return fmt.Errorf("uploading hits: %v", err)
		}
	}
	return nil
}

func (c *Client) upload(hits []Hit) error {
	for i := 0; i < len(hits); i += c.batchSize {
		start, end := i, i+c.batchSize
		if end > len(hits) {
			end = len(hits)
		}

		var body bytes.Buffer
		for _, hit := range hits[start:end] {
			payload := url.Values{
				"v":   []string{"1"},
				"tid": []string{c.propertyID},
				"cid": []string{c.clientID},
			}
			for key, value := range hit {
				payload.Add(key, value)
			}
			body.WriteString(payload.Encode())
			body.WriteByte('\n')
		}

		request, err := http.NewRequest("POST", c.endpoint+"/batch", &body)
		if err != nil {
			return fmt.Errorf("creating request: %v", err)
		}
		response, err := http.DefaultClient.Do(request)
		if err != nil {
			return fmt.Errorf("sending request: %v", err)
		}
		if response.StatusCode != 200 {
			return fmt.Errorf("unexpected response status: %v", response.Status)
		}
	}
	return nil
}

type contextKey int

var (
	hitsKey = contextKey(1)
)

// TrackingHandler returns a new http.Handler which wraps the provided
// handler.  The wrapper prepares the incoming request's context for use with
// the TrackerFromContext function.  When the underlying handler completes,
// the track function is invoked with any hits accumulated during the request.
func TrackingHandler(handler http.Handler, track func([]Hit)) http.Handler {
	return http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) {
		var hits []Hit
		ctx := context.WithValue(req.Context(), hitsKey, &hits)
		handler.ServeHTTP(w, req.WithContext(ctx))
		track(hits)
	})
}

// TrackerFromContext is intended to be used with contexts that are generated
// by handlers returned from the TrackingHandler function.  It returns a
// function that buffers hits to be delivered to the track function provided
// in the original call to the TrackingHandler function.
func TrackerFromContext(ctx context.Context) func(Hit) {
	if hits, ok := ctx.Value(hitsKey).(*[]Hit); ok {
		return func(hit Hit) { *hits = append(*hits, hit) }
	}
	return func(Hit) {}
}


text:
It exists in each direction of CW/CCW and means the error between goal position and present position.
The range of the value is 0~255, and the unit is the same as Goal Position.(Address 30,31)
The greater the value, the more difference occurs.


text:
'use strict';
const expect = require('chai').expect;
const assert = require('assert');
const acl = require('../../');

describe('Express acl export', function() {
  context('Check if they exist', function() {
    it('All method should be defined', function(done) {
      assert(acl, true);
      assert(acl.config, true);
      assert(acl.authorize, true);
      assert(acl.authorize.unless, true);
      done();
    });
  });

  context('Check for the type', function() {
    it('All properties should be functions', function(done) {
      expect(acl).to.be.an('object');
      expect(acl.config).to.be.a('function');
      expect(acl.authorize).to.be.a('function');
      expect(acl.authorize.unless).to.be.a('function');
      done();
    });
  });
});


text:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical" >

    <io.vov.vitamio.widget.CenterLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:orientation="vertical" >

        <io.vov.vitamio.widget.VideoView
            android:id="@+id/buffer"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:layout_centerHorizontal="true"
            android:layout_centerVertical="true" />
    </io.vov.vitamio.widget.CenterLayout>

    <LinearLayout
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerInParent="true"
        android:orientation="horizontal" >

        <ProgressBar
            android:id="@+id/probar"
            style="?android:attr/progressBarStyleLarge"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content" />

        <TextView
            android:id="@+id/download_rate"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_gravity="center"
            android:text="" />

        <TextView
            android:id="@+id/load_rate"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_gravity="center"
            android:text="" />
    </LinearLayout>

</RelativeLayout>


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

import 'chrome://resources/cr_elements/cr_button/cr_button.js';
import '//resources/polymer/v3_0/paper-spinner/paper-spinner-lite.js';

import {CrIconButtonElement} from 'chrome://resources/cr_elements/cr_icon_button/cr_icon_button.js';
import {I18nMixin} from 'chrome://resources/cr_elements/i18n_mixin.js';
import {afterNextRender, PolymerElement} from 'chrome://resources/polymer/v3_0/polymer/polymer_bundled.min.js';

import {LensErrorType, LensFormElement, LensSubmitType} from './lens_form.js';
import {getTemplate} from './lens_upload_dialog.html.js';
import {WindowProxy} from './window_proxy.js';

enum DialogState {
  // Dialog is currently hidden from the user.
  HIDDEN,
  // Dialog is open and awaiting user input.
  NORMAL,
  // User is dragging a file over the UI.
  DRAGGING,
  // User dropped a file and a request to Lens is started.
  LOADING,
  // User selected a file that resulted in an error.
  ERROR,
  // User is offline.
  OFFLINE,
}

enum LensErrorMessage {
  // No error.
  NONE,
  // User provided an invalid file format.
  FILE_TYPE,
  // User provided a file that is too large to handle.
  FILE_SIZE,
  // User provided multiple files.
  MULTIPLE_FILES,
  // User provided URL with improper scheme.
  SCHEME,
  // User provided invalid URL.
  CONFORMANCE,
  // User provided multiple URLs.
  MULTIPLE_URLS,
}

const EventKeys = {
  ENTER: 'Enter',
  ESCAPE: 'Escape',
  SPACE: ' ',
  TAB: 'Tab',
};

export interface LensUploadDialogElement {
  $: {
    dialog: HTMLDivElement,
    lensForm: LensFormElement,
    dragDropArea: HTMLDivElement,
    closeButton: CrIconButtonElement,
  };
}

/**
 * List of possible upload dialog actions. This enum must match with the
 * numbering for NewTabPageLensUploadDialogActions in histogram/enums.xml. These
 * values are persisted to logs. Entries should not be renumbered, removed or
 * reused.
 */
export enum LensUploadDialogAction {
  URL_SUBMITTED = 0,
  FILE_SUBMITTED = 1,
  IMAGE_DROPPED = 2,
  DIALOG_OPENED = 3,
  DIALOG_CLOSED = 4,
  ERROR_SHOWN = 5,
}

/**
 * List of possible upload dialog errors. This enum must match with the
 * numbering for NewTabPageLensUploadDialogErrors in histogram/enums.xml. These
 * values are persisted to logs. Entries should not be renumbered, removed or
 * reused.
 */
export enum LensUploadDialogError {
  FILE_SIZE = 0,
  FILE_TYPE = 1,
  MULTIPLE_FILES = 2,
  MULTIPLE_URLS = 3,
  LENGTH_TOO_GREAT = 4,
  INVALID_SCHEME = 5,
  INVALID_URL = 6,
  NETWORK_ERROR = 7,
}

export function recordLensUploadDialogAction(action: LensUploadDialogAction) {
  chrome.metricsPrivate.recordEnumerationValue(
      'NewTabPage.Lens.UploadDialog.DialogAction', action,
      Object.keys(LensUploadDialogAction).length);
}

export function recordLensUploadDialogError(action: LensUploadDialogError) {
  chrome.metricsPrivate.recordEnumerationValue(
      'NewTabPage.Lens.UploadDialog.DialogError', action,
      Object.keys(LensUploadDialogError).length);
}

const LensUploadDialogElementBase = I18nMixin(PolymerElement);

// Modal that lets the user upload images for search on Lens.
export class LensUploadDialogElement extends LensUploadDialogElementBase {
  static get is() {
    return 'ntp-lens-upload-dialog';
  }

  static get template() {
    return getTemplate();
  }

  static get properties() {
    return {
      dialogState_: {
        type: DialogState,
      },
      lensErrorMessage_: {
        type: LensErrorMessage,
      },
      isHidden_: {
        type: Boolean,
        computed: `computeIsHidden_(dialogState_)`,
      },
      isNormalOrError_: {
        type: Boolean,
        computed: `computeIsNormalOrError_(dialogState_)`,
        reflectToAttribute: true,
      },
      isDragging_: {
        type: Boolean,
        computed: `computeIsDragging_(dialogState_)`,
        reflectToAttribute: true,
      },
      isLoading_: {
        type: Boolean,
        computed: `computeIsLoading_(dialogState_)`,
        reflectToAttribute: true,
      },
      isError_: {
        type: Boolean,
        computed: `computeIsError_(dialogState_)`,
        reflectToAttribute: true,
      },
      isOffline_: {
        type: Boolean,
        computed: `computeIsOffline_(dialogState_)`,
        reflectToAttribute: true,
      },
      uploadUrl_: {
        type: String,
      },
    };
  }

  private dialogState_ = DialogState.HIDDEN;
  private lensErrorMessage_ = LensErrorMessage.NONE;
  private outsideHandlerAttached_ = false;
  private uploadUrl_: string = '';
  private dragCount: number = 0;

  private computeIsHidden_(dialogState: DialogState): boolean {
    return dialogState === DialogState.HIDDEN;
  }

  private computeIsNormalOrError_(dialogState: DialogState): boolean {
    return dialogState === DialogState.NORMAL ||
        dialogState === DialogState.ERROR;
  }

  private computeIsDragging_(dialogState: DialogState): boolean {
    return dialogState === DialogState.DRAGGING;
  }

  private computeIsLoading_(dialogState: DialogState): boolean {
    return dialogState === DialogState.LOADING;
  }

  private computeIsError_(dialogState: DialogState): boolean {
    return dialogState === DialogState.ERROR;
  }

  private computeIsOffline_(dialogState: DialogState): boolean {
    return dialogState === DialogState.OFFLINE;
  }

  override connectedCallback() {
    super.connectedCallback();
  }

  override disconnectedCallback() {
    super.disconnectedCallback();
    this.detachOutsideHandler_();
  }

  openDialog() {
    this.setOnlineState_();
    // Click handler needs to be attached outside of the initial event handler,
    // otherwise the click of the icon which initially opened the dialog would
    // also be registered in the outside click handler, causing the dialog to
    // immediately close after opening.
    afterNextRender(this, () => {
      this.attachOutsideHandler_();
      if (this.computeIsOffline_(this.dialogState_)) {
        this.shadowRoot!.getElementById('offlineRetryButton')?.focus();
      } else {
        this.shadowRoot!.getElementById('uploadText')?.focus();
      }
    });
    recordLensUploadDialogAction(LensUploadDialogAction.DIALOG_OPENED);
  }

  closeDialog() {
    this.dialogState_ = DialogState.HIDDEN;
    this.detachOutsideHandler_();
    this.dispatchEvent(new Event('close-lens-search'));
    recordLensUploadDialogAction(LensUploadDialogAction.DIALOG_CLOSED);
  }

  private getErrorString_(lensErrorMessage: LensErrorMessage) {
    switch (lensErrorMessage) {
      case LensErrorMessage.FILE_TYPE:
        return this.i18n('lensSearchUploadDialogErrorFileType');
      case LensErrorMessage.FILE_SIZE:
        return this.i18n('lensSearchUploadDialogErrorFileSize');
      case LensErrorMessage.MULTIPLE_FILES:
        return this.i18n('lensSearchUploadDialogErrorMultipleFiles');
      case LensErrorMessage.SCHEME:
        return this.i18n('lensSearchUploadDialogValidationErrorScheme');
      case LensErrorMessage.CONFORMANCE:
        return this.i18n('lensSearchUploadDialogValidationErrorConformance');
      case LensErrorMessage.MULTIPLE_URLS:
        return this.i18n('lensSearchUploadDialogErrorMultipleUrls');
      default:
        return '';
    }
  }

  /**
   * Checks to see if the user is online or offline and sets the dialog state
   * accordingly.
   */
  private setOnlineState_() {
    this.dialogState_ = WindowProxy.getInstance().onLine ? DialogState.NORMAL :
                                                           DialogState.OFFLINE;
  }

  private outsideClickHandler_ = (event: MouseEvent) => {
    const outsideDialog = !event.composedPath().includes(this.$.dialog);
    if (outsideDialog) {
      this.closeDialog();
    }
  };

  private outsideKeyHandler_ = (event: KeyboardEvent) => {
    if (event.key === EventKeys.ESCAPE) {
      this.closeDialog();
    }
  };

  private attachOutsideHandler_() {
    if (!this.outsideHandlerAttached_) {
      document.addEventListener('click', this.outsideClickHandler_);
      document.addEventListener('keydown', this.outsideKeyHandler_);
      this.outsideHandlerAttached_ = true;
    }
  }

  private detachOutsideHandler_() {
    if (this.outsideHandlerAttached_) {
      document.removeEventListener('click', this.outsideClickHandler_);
      document.removeEventListener('keydown', this.outsideKeyHandler_);
      this.outsideHandlerAttached_ = false;
    }
  }

  private onCloseButtonKeydown_ = (event: KeyboardEvent) => {
    if (event.key === EventKeys.TAB &&
        (this.computeIsDragging_(this.dialogState_) ||
         this.computeIsLoading_(this.dialogState_))) {
      event.preventDefault();
      // In the dragging and loading states, the close button is the only
      // tabbable element in the dialog, so focus should stay on it.
    } else if (event.key === EventKeys.TAB && event.shiftKey) {
      event.preventDefault();
      if (this.computeIsNormalOrError_(this.dialogState_)) {
        this.shadowRoot!.getElementById('inputSubmit')?.focus();
      } else if (this.computeIsOffline_(this.dialogState_)) {
        this.shadowRoot!.getElementById('offlineRetryButton')?.focus();
      }
    }
  };

  private onOfflineRetryButtonKeydown_ = (event: KeyboardEvent) => {
    if (event.key === EventKeys.TAB && !event.shiftKey) {
      event.preventDefault();
      this.$.closeButton.focus();
    }
  };

  private onCloseButtonClick_() {
    this.closeDialog();
  }

  private onOfflineRetryButtonClick_() {
    this.setOnlineState_();
  }

  private onUploadFileKeyDown_(event: KeyboardEvent) {
    if (event.key === EventKeys.ENTER || event.key === EventKeys.SPACE) {
      this.$.lensForm.openSystemFilePicker();
    }
  }

  private onUploadFileClick_() {
    this.$.lensForm.openSystemFilePicker();
  }

  private handleFormLoading_(event: CustomEvent<LensSubmitType>) {
    this.dialogState_ = DialogState.LOADING;
    switch (event.detail) {
      case LensSubmitType.FILE:
        recordLensUploadDialogAction(LensUploadDialogAction.FILE_SUBMITTED);
        break;
      case LensSubmitType.URL:
        recordLensUploadDialogAction(LensUploadDialogAction.URL_SUBMITTED);
        break;
    }
  }

  private handleFormError_(event: CustomEvent<LensErrorType>) {
    switch (event.detail) {
      case LensErrorType.MULTIPLE_FILES:
        this.dialogState_ = DialogState.ERROR;
        this.lensErrorMessage_ = LensErrorMessage.MULTIPLE_FILES;
        recordLensUploadDialogAction(LensUploadDialogAction.ERROR_SHOWN);
        recordLensUploadDialogError(LensUploadDialogError.MULTIPLE_FILES);
        break;
      case LensErrorType.NO_FILE:
        this.dialogState_ = DialogState.NORMAL;
        this.lensErrorMessage_ = LensErrorMessage.NONE;
        break;
      case LensErrorType.FILE_TYPE:
        this.dialogState_ = DialogState.ERROR;
        this.lensErrorMessage_ = LensErrorMessage.FILE_TYPE;
        recordLensUploadDialogAction(LensUploadDialogAction.ERROR_SHOWN);
        recordLensUploadDialogError(LensUploadDialogError.FILE_TYPE);
        break;
      case LensErrorType.FILE_SIZE:
        this.dialogState_ = DialogState.ERROR;
        this.lensErrorMessage_ = LensErrorMessage.FILE_SIZE;
        recordLensUploadDialogAction(LensUploadDialogAction.ERROR_SHOWN);
        recordLensUploadDialogError(LensUploadDialogError.FILE_SIZE);
        break;
      case LensErrorType.INVALID_SCHEME:
        this.dialogState_ = DialogState.ERROR;
        this.lensErrorMessage_ = LensErrorMessage.SCHEME;
        recordLensUploadDialogAction(LensUploadDialogAction.ERROR_SHOWN);
        recordLensUploadDialogError(LensUploadDialogError.INVALID_SCHEME);
        break;
      case LensErrorType.INVALID_URL:
        this.dialogState_ = DialogState.ERROR;
        this.lensErrorMessage_ = LensErrorMessage.CONFORMANCE;
        recordLensUploadDialogAction(LensUploadDialogAction.ERROR_SHOWN);
        recordLensUploadDialogError(LensUploadDialogError.INVALID_URL);
        break;
      case LensErrorType.LENGTH_TOO_GREAT:
        this.dialogState_ = DialogState.ERROR;
        this.lensErrorMessage_ = LensErrorMessage.CONFORMANCE;
        recordLensUploadDialogAction(LensUploadDialogAction.ERROR_SHOWN);
        recordLensUploadDialogError(LensUploadDialogError.LENGTH_TOO_GREAT);
        break;
      default:
        this.dialogState_ = DialogState.NORMAL;
        this.lensErrorMessage_ = LensErrorMessage.NONE;
    }
  }

  private onUrlKeyDown_(event: KeyboardEvent) {
    if (event.key === EventKeys.ENTER) {
      event.preventDefault();
      this.onSubmitUrl_();
    }
  }

  private onInputSubmitKeyDown_(event: KeyboardEvent) {
    if (event.key === EventKeys.ENTER || event.key === EventKeys.SPACE) {
      this.onSubmitUrl_();
    } else if (event.key === EventKeys.TAB && !event.shiftKey) {
      event.preventDefault();
      this.$.closeButton.focus();
    }
  }

  private onSubmitUrl_() {
    const url = this.uploadUrl_.trim();
    if (url.length > 0) {
      this.$.lensForm.submitUrl(url);
    }
  }

  private onDragEnter_(e: DragEvent) {
    e.preventDefault();
    this.dragCount += 1;

    if (this.dragCount === 1) {
      this.dialogState_ = DialogState.DRAGGING;
    }
  }

  private onDragOver_(e: DragEvent) {
    e.preventDefault();
  }

  private onDragLeave_(e: DragEvent) {
    e.preventDefault();
    this.dragCount -= 1;

    if (this.dragCount === 0) {
      this.dialogState_ = DialogState.NORMAL;
    }
  }

  private onDrop_(e: DragEvent) {
    e.preventDefault();
    this.dragCount = 0;

    if (e.dataTransfer) {
      this.$.lensForm.submitFileList(e.dataTransfer.files);
      recordLensUploadDialogAction(LensUploadDialogAction.IMAGE_DROPPED);
    }
  }
}
declare global {
  interface HTMLElementTagNameMap {
    'ntp-lens-upload-dialog': LensUploadDialogElement;
  }
}

customElements.define(LensUploadDialogElement.is, LensUploadDialogElement);


text:
namespace _12.Test_Numbers
{
    using System;
    using System.Collections.Generic;
    using System.Linq;

    public class TestNumbers
    {
        public static void Main()
        {
            var n = int.Parse(Console.ReadLine());
            var m = int.Parse(Console.ReadLine());
            var maxSum = int.Parse(Console.ReadLine());
            var outputSum = 0;
            var combinationsCount = 0;

            for (int i = n; i >= 1; i--)
            {
                for (int j = 1; j <= m; j++)
                {

                    if(outputSum >= maxSum)
                    {
                        break;
                    }
                    outputSum += (3 * (i * j));
                    combinationsCount++;
                }
            }
            Console.WriteLine($"{combinationsCount} combinations");
            if (outputSum >= maxSum)
            {
                Console.WriteLine($"Sum: {outputSum} >= {maxSum}");
            }
            else
            {
                Console.WriteLine($"Sum: {outputSum}");
            }
        }
    }
}


text:
"use strict";
let should = require('chai').should();
let Opcode = require('../lib/opcode');

describe('Opcode', function() {

  it('should create a new Opcode', function() {
    let opcode = new Opcode(5);
  });

  it('should have 119 opcodes', function() {
    let i = 0;
    for (let key in Opcode) {
      if (key.indexOf('OP_') !== -1)
        i++;
    }
    i.should.equal(119);
  });

  it('should convert to a string with this handy syntax', function() {
    Opcode(0).toString().should.equal('OP_0');
    Opcode(96).toString().should.equal('OP_16');
    Opcode(97).toString().should.equal('OP_NOP');
  });

  it('should convert to a number with this handy syntax', function() {
    Opcode('OP_0').toNumber().should.equal(0);
    Opcode('OP_16').toNumber().should.equal(96);
    Opcode('OP_NOP').toNumber().should.equal(97);
  });

  describe('#fromNumber', function() {

    it('should work for 0', function() {
      Opcode().fromNumber(0).num.should.equal(0);
    });

  });

  describe('#toNumber', function() {

    it('should work for 0', function() {
      Opcode().fromNumber(0).toNumber().should.equal(0);
    });

  });

  describe('#fromString', function() {

    it('should work for OP_0', function() {
      Opcode().fromString('OP_0').num.should.equal(0);
    });

  });

  describe('#toString', function() {

    it('should work for OP_0', function() {
      Opcode().fromString('OP_0').toString().should.equal('OP_0');
    });

  });

  describe('@str', function() {

    it('should exist and have op 185', function() {
      should.exist(Opcode.str);
      Opcode.str[185].should.equal('OP_NOP10');
    });

  });

});


text:
:orphan:

Changelog
=========

This directory contains "news fragments" which are short files that contain a
small **ReST**-formatted text that will be added to the next what's new page.

Make sure to use full sentences with correct case and punctuation, and please
try to use Sphinx intersphinx using backticks. The fragment should have a
header line and an underline using ``------``

Each file should be named like ``<PULL REQUEST>.<TYPE>.rst``, where
``<PULL REQUEST>`` is a pull request number, and ``<TYPE>`` is one of:

* ``new_function``: New user facing functions.
* ``deprecation``: Changes existing code to emit a DeprecationWarning.
* ``future``: Changes existing code to emit a FutureWarning.
* ``expired``: Removal of a deprecated part of the API.
* ``compatibility``: A change which requires users to change code and is not
  backwards compatible. (Not to be used for removal of deprecated features.)
* ``c_api``: Changes in the Numpy C-API exported functions
* ``new_feature``: New user facing features like ``kwargs``.
* ``improvement``: Performance and edge-case changes
* ``change``: Other changes
* ``highlight``: Adds a highlight bullet point to use as a possibly highlight
  of the release.

Most categories should be formatted as paragraphs with a heading.
So for example: ``123.new_feature.rst`` would have the content::

    ``my_new_feature`` option for `my_favorite_function`
    ----------------------------------------------------
    The ``my_new_feature`` option is now available for `my_favorite_function`.
    To use it, write ``np.my_favorite_function(..., my_new_feature=True)``.

``highlight`` is usually formatted as bulled points making the fragment
``* This is a highlight``.

Note the use of single-backticks to get an internal link (assuming
``my_favorite_function`` is exported from the ``numpy`` namespace),
and double-backticks for code.

If you are unsure what pull request type to use, don't hesitate to ask in your
PR.

You can install ``towncrier`` and run ``towncrier --draft --version 1.18``
if you want to get a preview of how your change will look in the final release
notes.

.. note::

    This README was adapted from the pytest changelog readme under the terms of
    the MIT licence.


text:
typedef struct ConsoleContextMenu ConsoleContextMenu;
struct ConsoleContextMenu {
        int32_t unknown[0];
};


text:
This is a reference project to demonstrate how to use [SBT](http://www.scala-sbt.org) to setup a Scala project

To compile and run the project, execute the command `sbt run` from the root directory of the project.

## License

See [LICENSE](https://github.com/paramk/scala-sbt-helloworld/blob/master/LICENSE).