text:
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Scanner;

public class Igra {
	public static void obdelaj(String vhodnaDatoteka, String izhodnaDatoteka){
		File file = new File(vhodnaDatoteka);

		try {
			// read vhodnaDatoteka and parse all the info
			Scanner sc = new Scanner(file);
			int noPlayers = sc.nextInt();
			int noCards = sc.nextInt();

			String[] cardsUgly = sc.next().split(",");
			QueueListLinked allCards = new QueueListLinked();

			for(int i = cardsUgly.length - 1; i >=0; i--){
				Card cardToAdd = new Card(cardsUgly[i]);
				allCards.enqueue(new ListLinkedNode(cardToAdd));
			}

			Player[] allPlayers = new Player[noPlayers];
			for (int i = 0; i < noPlayers; i++){
				allPlayers[i] = new Player();
			}

//			System.out.println("Read file and created an array of Cards and Players");
			sc.close();

			//distribute all cards
			int currPlayerDist = 0;
			for(int i = 0; i < 5*noPlayers; i++){
				allPlayers[currPlayerDist].addCard((Card) allCards.front().element);
				allCards.dequeue();
				if (currPlayerDist < noPlayers-1){
					currPlayerDist++;
				}
				else{
					currPlayerDist = 0;
				}
			}

			play(0, allPlayers, allCards);

//			System.out.println("Finished the game.");

			try{
				PrintWriter p = new PrintWriter(new FileWriter(izhodnaDatoteka));
				for (int i = 0; i < allPlayers.length; i ++){
					p.println(allPlayers[i].wins);
				}
				p.close();
			}
			catch (IOException ex){
				System.err.println("I/O exception");
			}

		}
		catch (FileNotFoundException e){
			System.err.println("ERROR - File not found.");
		}
	}

	public static void play(int playerIndexStart, Player[] allPlayers, QueueListLinked allCards){
		// allMoves contains the round moves
		Card[] allMoves = new Card[allPlayers.length];

		int allMovesCount = 0;

		for (int i = 0; i < allPlayers.length; i++){
			if (i == 0){
				Card firstmove = allPlayers[(i+playerIndexStart) % allPlayers.length].startMove();
				allMoves[allMovesCount] = firstmove;
				allMovesCount++;
			}
			else{
				Card[] tempAllMoves = new Card[i];
				for (int j = 0; j < i; j++){
					tempAllMoves[j] = allMoves[j];
				}
				int ppp = (i+playerIndexStart) % allPlayers.length;
				allMoves[allMovesCount] = allPlayers[ppp].nextMove(tempAllMoves);
				allMovesCount++;
			}
		}

		// firstMove contains the card that won the round while playerWon is the number of the player that won
		Card firstMove = allMoves[0];

		int playerWon = playerIndexStart;

		for (int i = 1; i < allMoves.length; i++){
			if (Card.isHigher(firstMove, allMoves[i])){
				firstMove = allMoves[i];
				playerWon = (i+playerIndexStart) % allPlayers.length;
			}
		}

		allPlayers[playerWon].hasWon();

		// draw again
		int playersDrawnTurn = playerWon;
		for (int i = 0; i < allPlayers.length; i++){
			allPlayers[playersDrawnTurn % allPlayers.length].drawCard(allCards);
			playersDrawnTurn++;
		}

//		System.out.println("A move has been completed.");
		if (allPlayers[0].hasCards()){
			play(playerWon, allPlayers, allCards);
		}
	}

	public static String vrniVpisnoStevilko(){
		return "00000000";
	}

	public static void main(String[] args){
//		obdelaj("testi/I4_1.txt","O4_1_test.txt");
//		obdelaj("testi/I4_2.txt","O4_2_test.txt");
//		obdelaj("testi/I4_3.txt","O4_3_test.txt");
//		obdelaj("testi/I4_4.txt","O4_4_test.txt");
//		obdelaj("testi/I4_5.txt","O4_5_test.txt");
//		obdelaj("testi/I4_6.txt","O4_6_test.txt");
//		obdelaj("testi/I4_7.txt","O4_7_test.txt");
//		obdelaj("testi/I4_8.txt","O4_8_test.txt");
//		obdelaj("testi/I4_9.txt","O4_9_test.txt");
//		obdelaj("testi/I4_10.txt","O4_10_test.txt");

//		System.out.println("Finished successfully!");

	}

}

class Card {
	public int st;
	public char color;

	public Card(String karta){
		this.st = Integer.parseInt(karta.replaceAll("[^0-9,]", ""));
		this.color = karta.replaceAll("[0-9,]", "").charAt(0); // trick to convert String -> char
	}

	public Card(int st, char color){
		this.st = st;
		this.color = color;
	}

	public static Card highestCard(Card[] currentlyPlaying){
		// currentlyPlaying[0] should include the card that we should try to beat

		Card highestCard = currentlyPlaying[0];

		for (int i = 1; i < currentlyPlaying.length; i++){
			if (currentlyPlaying[i] != null){
				if (currentlyPlaying[i].color == highestCard.color &&
					currentlyPlaying[i].st > highestCard.st){
					highestCard = currentlyPlaying[i];
				}
			}
		}

		return highestCard;
	}
	public static boolean isHigher(Card a, Card b){
		if (a.color == b.color){
			return a.st < b.st;
		}
		return false;

	}

}

class Player {
	public int wins;
	public Card[] cards;
	public int currNoCards;

	public Player(){
		this.wins = 0;
		this.cards = new Card[5];
		this.currNoCards = 0;
	}

	public void hasWon(){
		this.wins += 1;
	}

	public void addCard(Card n){
		cards[this.currNoCards] = n;
		this.currNoCards++;
	}

	public boolean canAddCard(){
		return this.currNoCards < 5;
	}

	public boolean hasCards(){
		return this.currNoCards > 0;
	}

	public void removeCard(Card rem){
		for (int i = 0; i < this.currNoCards; i++){
			if (cards[i].st == rem.st && cards[i].color == rem.color){

				for (int j = i+1; j < this.cards.length; j++){
					cards[j-1] = cards[j];
				}

				cards[this.cards.length-1] = null;
				this.currNoCards--;
				break;
			}
		}
	}

	public void drawCard(QueueListLinked q){
		if (!q.empty()){
			this.cards[this.currNoCards] = (Card) q.front().element;
			q.dequeue();
			this.currNoCards++;
		}

	}

	public Card smallestCard(){
		int smallestNo = this.cards[0].st;
		int smallestColor = (int) this.cards[0].color;

		// find the smallest number
		for (int i = 1; i < this.currNoCards; i ++){
			if (this.cards[i].st < smallestNo){
				smallestNo = this.cards[i].st;
				smallestColor = (int) this.cards[i].color;
			}
			else if (this.cards[i].st == smallestNo){
				if (((int)this.cards[i].color) < smallestColor){
					smallestColor = (int) this.cards[i].color;
				}

			}
		}

		Card smallestCard = null;

		// find the smallest color
		for (int i = 0; i < this.currNoCards; i++){
			if (cards[i].st == smallestNo && ((int)cards[i].color) == smallestColor){
				smallestCard = cards[i];
				break;
			}
		}

		return smallestCard;
	}

	public Card startMove(){
		int maxNoCard = 0;
		int maxNoCardCount = 0;

		// find highest number
		for (int i = 0; i < this.currNoCards;i++){
			if (this.cards[i].st > maxNoCard){
				maxNoCard = this.cards[i].st;
				maxNoCardCount = 1;
			}
			else if (this.cards[i].st == maxNoCard){
				maxNoCardCount++;
			}

		}

		// place highest numbers in array
		Card[] highestNum = new Card[maxNoCardCount];
		int highestNumCount = 0;
		int lowestColor = (int) 'Z';

		for (int i = 0; i < this.currNoCards; i++){
			if (this.cards[i].st == maxNoCard){
				highestNum[highestNumCount] = this.cards[i];
				highestNumCount++;

				if (((int) this.cards[i].color) < lowestColor){
					lowestColor = (int) this.cards[i].color;
				}
			}
		}

		// get the highest number with the lowest color
		for (int i = 0; i < highestNum.length; i++){
			if (highestNum[i].color == lowestColor){
				Card firstmove = highestNum[i];
				this.removeCard(firstmove);
				return firstmove;
			}
		}

		System.err.println("Player has returned null when executing startMove()!");
		return null; // this should NEVER be executed!

	}

	public Card nextMove(Card[] currentlyPlaying){
		// situation 1, if we have a card that can win

		Card highestCard = Card.highestCard(currentlyPlaying);

		Card[] possibleWinnerCards = new Card[this.cards.length];
		int possibleWinnerCardsCount = 0;

		for (int i = 0; i < this.currNoCards; i++){
			if (this.cards[i].color == highestCard.color &&
				this.cards[i].st > highestCard.st){
				possibleWinnerCards[possibleWinnerCardsCount] = this.cards[i];
				possibleWinnerCardsCount++;
			}
		}

		if (possibleWinnerCardsCount > 0){
			Card playersMove = Card.highestCard(possibleWinnerCards);

			this.removeCard(playersMove);
			return playersMove;
		}

		// situation 2, we get rid of our lowest card

		Card playersMove = this.smallestCard();
		this.removeCard(playersMove);
		return playersMove;

	}
}

class ListLinkedNode {
	Object element;
	ListLinkedNode next;
	ListLinkedNode prev;

	ListLinkedNode(){
		element = null;
		next = null;
	}

	ListLinkedNode(Object obj){
		element = obj;
		next = null;
	}

	ListLinkedNode(Object obj, ListLinkedNode n){
		element = obj;
		next = n;
	}

}

class QueueListLinked {
	protected ListLinkedNode first, last;
	int listLen;

	public QueueListLinked(){
		makenull();
	}

	public void makenull(){
		first = null;
		last = null;
		listLen = 0;
	}

	public boolean empty(){
		return first == null;
	}

	public ListLinkedNode front(){
		return last;
	}

	public void enqueue(ListLinkedNode n){
		if (last != null){
			this.last.next = n;
			n.prev = this.last;
			this.last = n;
			n.next = null;
		}
		else{
			this.first = n;
			n.prev = null;
			n.next = null;
			this.last = n;
		}
		this.listLen++;
	}

	public void dequeue(){
		this.last = this.last.prev;
		if (this.last != null){
			this.last.next = null;
		}
		else{
			this.first = null;
		}

		this.listLen--;
	}
}


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 org.activiti.designer.export.bpmn20.export;

import javax.xml.stream.XMLStreamWriter;

import org.eclipse.bpmn2.SequenceFlow;
import org.eclipse.emf.ecore.EObject;

/**
 * @author Tijs Rademakers
 */
public class SequenceFlowExport implements ActivitiNamespaceConstants {

  public static void createSequenceFlow(EObject object, XMLStreamWriter xtw) throws Exception {
    SequenceFlow sequenceFlow = (SequenceFlow) object;
    // start SequenceFlow element
    xtw.writeStartElement("sequenceFlow");
    xtw.writeAttribute("id", sequenceFlow.getId());
    if (sequenceFlow.getName() == null) {
      xtw.writeAttribute("name", "");
    } else {
      xtw.writeAttribute("name", sequenceFlow.getName());
    }
    xtw.writeAttribute("sourceRef", sequenceFlow.getSourceRef().getId());
    xtw.writeAttribute("targetRef", sequenceFlow.getTargetRef().getId());

    ExtensionListenerExport.createExtensionListenerXML(sequenceFlow.getExecutionListeners(), true, EXECUTION_LISTENER, xtw);

    if (sequenceFlow.getConditionExpression() != null && sequenceFlow.getConditionExpression().getBody() != null
            && sequenceFlow.getConditionExpression().getBody().length() > 0) {

      String condition = sequenceFlow.getConditionExpression().getBody();
      // start conditionExpression element
      xtw.writeStartElement("conditionExpression");
      xtw.writeAttribute("xsi", XSI_NAMESPACE, "type", "tFormalExpression");
      xtw.writeCData(condition);

      // end conditionExpression element
      xtw.writeEndElement();
    }

    // end SequenceFlow element
    xtw.writeEndElement();
  }
}

redpajama_set_name: RedPajamaGithub


text:
require 'spec_helper'
describe Auth0::Api::V2::Tenants do
  attr_reader :client, :body

  before(:all) do
    @client = Auth0Client.new(v2_creds)
    @body = {
      'error_page' => {
        'html' => '',
        'show_log_link' => false,
        'url' => 'https://mycompany.org/error'
      },
      'friendly_name' => 'My Company',
      'picture_url' => 'https://mycompany.org/logo.png',
      'support_email' => 'support@mycompany.org',
      'support_url' => 'https://mycompany.org/support'
    }

    client.update_tenant_settings(body)
  end

  describe '.get_tenant_settings' do
    it { expect(client.get_tenant_settings).to include(body) }

    let(:tenant_setting_fields) { client.get_tenant_settings(fields: 'picture_url') }
    it { expect(tenant_setting_fields).to_not include('friendly_name' => 'My Company') }
    it { expect(tenant_setting_fields).to include('picture_url' => 'https://mycompany.org/logo.png') }
  end

  describe '.update_tenant_settings' do
    let(:tenant_name) { Faker::Company.name }
    let(:body_tenant) do
      { 'friendly_name' => tenant_name }
    end
    it { expect(client.update_tenant_settings(body_tenant)['friendly_name']).to include(tenant_name) }
  end
end


text:
import { Observable } from '../Observable';
import { ConnectableObservable } from '../observable/ConnectableObservable';
/**
 * @param value
 * @return {ConnectableObservable<T>}
 * @method publishBehavior
 * @owner Observable
 */
export declare function publishBehavior<T>(this: Observable<T>, value: T): ConnectableObservable<T>;


text:
<?php
namespace App\Action;

use Slim\Views\Twig;
use Psr\Log\LoggerInterface;
use Slim\Http\Request;
use Slim\Http\Response;

final class HomeAction
{
    private $view;
    private $logger;
    private $container;

    public function __construct(Twig $view, LoggerInterface $logger, $c)
    {
        $this->container = $c;
        $this->view = $view;
        $this->logger = $logger;
    }

    public function __invoke(Request $request, Response $response, $args)
    {

        $this->view->render($response, 'home.twig', array(
            "root" => WEBROOT
        ));
        // $this->logger->info("Home page action dispatched");

        // $data = $this->container[\App\Model\Requester::class]->selectAll();

        // $data = $this->container[\App\Model\Requester::class]();

        return $response;
    }
}


text:
package org.elasticsearch.index;

import com.google.common.collect.ImmutableMap;
import com.google.common.collect.ImmutableSet;
import com.google.common.collect.UnmodifiableIterator;
import org.apache.lucene.util.IOUtils;
import org.elasticsearch.ElasticsearchException;
import org.elasticsearch.ElasticsearchIllegalStateException;
import org.elasticsearch.cluster.metadata.IndexMetaData;
import org.elasticsearch.common.Nullable;
import org.elasticsearch.common.inject.*;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.env.NodeEnvironment;
import org.elasticsearch.env.ShardLock;
import org.elasticsearch.index.aliases.IndexAliasesService;
import org.elasticsearch.index.analysis.AnalysisService;
import org.elasticsearch.index.cache.IndexCache;
import org.elasticsearch.index.cache.bitset.BitsetFilterCache;
import org.elasticsearch.index.cache.bitset.ShardBitsetFilterCacheModule;
import org.elasticsearch.index.cache.filter.ShardFilterCacheModule;
import org.elasticsearch.index.cache.query.ShardQueryCacheModule;
import org.elasticsearch.index.deletionpolicy.DeletionPolicyModule;
import org.elasticsearch.index.engine.Engine;
import org.elasticsearch.index.engine.EngineModule;
import org.elasticsearch.index.fielddata.IndexFieldDataService;
import org.elasticsearch.index.fielddata.ShardFieldDataModule;
import org.elasticsearch.index.gateway.IndexShardGatewayModule;
import org.elasticsearch.index.gateway.IndexShardGatewayService;
import org.elasticsearch.index.get.ShardGetModule;
import org.elasticsearch.index.indexing.ShardIndexingModule;
import org.elasticsearch.index.mapper.MapperService;
import org.elasticsearch.index.merge.policy.MergePolicyModule;
import org.elasticsearch.index.merge.policy.MergePolicyProvider;
import org.elasticsearch.index.merge.scheduler.MergeSchedulerModule;
import org.elasticsearch.index.merge.scheduler.MergeSchedulerProvider;
import org.elasticsearch.index.percolator.PercolatorQueriesRegistry;
import org.elasticsearch.index.percolator.PercolatorShardModule;
import org.elasticsearch.index.query.IndexQueryParserService;
import org.elasticsearch.index.search.stats.ShardSearchModule;
import org.elasticsearch.index.settings.IndexSettings;
import org.elasticsearch.index.settings.IndexSettingsService;
import org.elasticsearch.index.shard.IndexShard;
import org.elasticsearch.index.shard.IndexShardCreationException;
import org.elasticsearch.index.shard.IndexShardModule;
import org.elasticsearch.index.shard.ShardId;
import org.elasticsearch.index.similarity.SimilarityService;
import org.elasticsearch.index.snapshots.IndexShardSnapshotModule;
import org.elasticsearch.index.store.IndexStore;
import org.elasticsearch.index.store.Store;
import org.elasticsearch.index.store.StoreModule;
import org.elasticsearch.index.suggest.SuggestShardModule;
import org.elasticsearch.index.termvectors.ShardTermVectorsModule;
import org.elasticsearch.index.translog.Translog;
import org.elasticsearch.index.translog.TranslogModule;
import org.elasticsearch.index.translog.TranslogService;
import org.elasticsearch.indices.IndicesLifecycle;
import org.elasticsearch.indices.InternalIndicesLifecycle;
import org.elasticsearch.plugins.PluginsService;
import org.elasticsearch.plugins.ShardsPluginsModule;

import java.io.Closeable;
import java.io.IOException;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicBoolean;

import static com.google.common.collect.Maps.newHashMap;
import static org.elasticsearch.common.collect.MapBuilder.newMapBuilder;

/**
 *
 */
public class IndexService extends AbstractIndexComponent implements IndexComponent, Iterable<IndexShard> {

    private final Injector injector;

    private final Settings indexSettings;

    private final PluginsService pluginsService;

    private final InternalIndicesLifecycle indicesLifecycle;

    private final AnalysisService analysisService;

    private final MapperService mapperService;

    private final IndexQueryParserService queryParserService;

    private final SimilarityService similarityService;

    private final IndexAliasesService aliasesService;

    private final IndexCache indexCache;

    private final IndexFieldDataService indexFieldData;

    private final BitsetFilterCache bitsetFilterCache;

    private final IndexStore indexStore;

    private final IndexSettingsService settingsService;

    private final NodeEnvironment nodeEnv;

    private volatile ImmutableMap<Integer, Injector> shardsInjectors = ImmutableMap.of();

    private volatile ImmutableMap<Integer, IndexShard> shards = ImmutableMap.of();

    private final AtomicBoolean closed = new AtomicBoolean(false);

    @Inject
    public IndexService(Injector injector, Index index, @IndexSettings Settings indexSettings, NodeEnvironment nodeEnv,
                        AnalysisService analysisService, MapperService mapperService, IndexQueryParserService queryParserService,
                        SimilarityService similarityService, IndexAliasesService aliasesService, IndexCache indexCache,
                        IndexStore indexStore, IndexSettingsService settingsService,
                        IndexFieldDataService indexFieldData, BitsetFilterCache bitSetFilterCache) {
        super(index, indexSettings);
        this.injector = injector;
        this.indexSettings = indexSettings;
        this.analysisService = analysisService;
        this.mapperService = mapperService;
        this.queryParserService = queryParserService;
        this.similarityService = similarityService;
        this.aliasesService = aliasesService;
        this.indexCache = indexCache;
        this.indexFieldData = indexFieldData;
        this.indexStore = indexStore;
        this.settingsService = settingsService;
        this.bitsetFilterCache = bitSetFilterCache;

        this.pluginsService = injector.getInstance(PluginsService.class);
        this.indicesLifecycle = (InternalIndicesLifecycle) injector.getInstance(IndicesLifecycle.class);

        // inject workarounds for cyclic dep
        indexCache.filter().setIndexService(this);
        indexFieldData.setIndexService(this);
        bitSetFilterCache.setIndexService(this);
        this.nodeEnv = nodeEnv;
    }

    public int numberOfShards() {
        return shards.size();
    }

    @Override
    public UnmodifiableIterator<IndexShard> iterator() {
        return shards.values().iterator();
    }

    public boolean hasShard(int shardId) {
        return shards.containsKey(shardId);
    }

    /**
     * Return the shard with the provided id, or null if there is no such shard.
     */
    @Nullable
    public IndexShard shard(int shardId) {
        return shards.get(shardId);
    }
    /**
     * Return the shard with the provided id, or throw an exception if it doesn't exist.
     */
    public IndexShard shardSafe(int shardId) throws IndexShardMissingException {
        IndexShard indexShard = shard(shardId);
        if (indexShard == null) {
            throw new IndexShardMissingException(new ShardId(index, shardId));
        }
        return indexShard;
    }

    public ImmutableSet<Integer> shardIds() {
        return shards.keySet();
    }

    public Injector injector() {
        return injector;
    }

    public IndexSettingsService settingsService() {
        return this.settingsService;
    }

    public IndexStore store() {
        return indexStore;
    }

    public IndexCache cache() {
        return indexCache;
    }

    public IndexFieldDataService fieldData() {
        return indexFieldData;
    }

    public BitsetFilterCache bitsetFilterCache() {
        return bitsetFilterCache;
    }

    public AnalysisService analysisService() {
        return this.analysisService;
    }

    public MapperService mapperService() {
        return mapperService;
    }

    public IndexQueryParserService queryParserService() {
        return queryParserService;
    }

    public SimilarityService similarityService() {
        return similarityService;
    }

    public IndexAliasesService aliasesService() {
        return aliasesService;
    }

    public synchronized void close(final String reason) {
        if (closed.compareAndSet(false, true)) {
            final Set<Integer> shardIds = shardIds();
            for (final int shardId : shardIds) {
                try {
                    removeShard(shardId, reason);
                } catch (Throwable t) {
                    logger.warn("failed to close shard", t);
                }
            }
        }
    }

    /**
     * Return the shard injector for the provided id, or null if there is no such shard.
     */
    @Nullable
    public Injector shardInjector(int shardId) throws ElasticsearchException {
        return shardsInjectors.get(shardId);
    }

    /**
     * Return the shard injector for the provided id, or throw an exception if there is no such shard.
     */
    public Injector shardInjectorSafe(int shardId) throws IndexShardMissingException {
        Injector shardInjector = shardInjector(shardId);
        if (shardInjector == null) {
            throw new IndexShardMissingException(new ShardId(index, shardId));
        }
        return shardInjector;
    }

    public String indexUUID() {
        return indexSettings.get(IndexMetaData.SETTING_UUID, IndexMetaData.INDEX_UUID_NA_VALUE);
    }

    public synchronized IndexShard createShard(int sShardId) throws ElasticsearchException {
        /*
         * TODO: we execute this in parallel but it's a synced method. Yet, we might
         * be able to serialize the execution via the cluster state in the future. for now we just
         * keep it synced.
         */
        if (closed.get()) {
            throw new ElasticsearchIllegalStateException("Can't create shard [" + index.name() + "][" + sShardId + "], closed");
        }
        ShardId shardId = new ShardId(index, sShardId);
        ShardLock lock = null;
        boolean success = false;
        try {
            lock = nodeEnv.shardLock(shardId, TimeUnit.SECONDS.toMillis(5));
            if (shardsInjectors.containsKey(shardId.id())) {
                throw new IndexShardAlreadyExistsException(shardId + " already exists");
            }

            indicesLifecycle.beforeIndexShardCreated(shardId);

            logger.debug("creating shard_id {}", shardId);

            ModulesBuilder modules = new ModulesBuilder();
            modules.add(new ShardsPluginsModule(indexSettings, pluginsService));
            modules.add(new IndexShardModule(shardId));
            modules.add(new ShardIndexingModule());
            modules.add(new ShardSearchModule());
            modules.add(new ShardGetModule());
            modules.add(new StoreModule(indexSettings, injector.getInstance(IndexStore.class), lock));
            modules.add(new DeletionPolicyModule(indexSettings));
            modules.add(new MergePolicyModule(indexSettings));
            modules.add(new MergeSchedulerModule(indexSettings));
            modules.add(new ShardFilterCacheModule());
            modules.add(new ShardQueryCacheModule());
            modules.add(new ShardBitsetFilterCacheModule());
            modules.add(new ShardFieldDataModule());
            modules.add(new TranslogModule(indexSettings));
            modules.add(new EngineModule(indexSettings));
            modules.add(new IndexShardGatewayModule());
            modules.add(new PercolatorShardModule());
            modules.add(new ShardTermVectorsModule());
            modules.add(new IndexShardSnapshotModule());
            modules.add(new SuggestShardModule());

            Injector shardInjector;
            try {
                shardInjector = modules.createChildInjector(injector);
            } catch (CreationException e) {
                throw new IndexShardCreationException(shardId, Injectors.getFirstErrorFailure(e));
            } catch (Throwable e) {
                throw new IndexShardCreationException(shardId, e);
            }

            shardsInjectors = newMapBuilder(shardsInjectors).put(shardId.id(), shardInjector).immutableMap();

            IndexShard indexShard = shardInjector.getInstance(IndexShard.class);
            indicesLifecycle.indexShardStateChanged(indexShard, null, "shard created");
            indicesLifecycle.afterIndexShardCreated(indexShard);

            shards = newMapBuilder(shards).put(shardId.id(), indexShard).immutableMap();
            success = true;
            return indexShard;
        } catch (IOException ex) {
            throw new IndexShardCreationException(shardId, ex);
        } finally {
            if (success == false) {
                IOUtils.closeWhileHandlingException(lock);
            }
        }
    }

    public synchronized void removeShard(int shardId, String reason) throws ElasticsearchException {
        final ShardId sId = new ShardId(index, shardId);
        try {
            final Injector shardInjector;
            final IndexShard indexShard;
            Map<Integer, Injector> tmpShardInjectors = newHashMap(shardsInjectors);
            shardInjector = tmpShardInjectors.remove(shardId);
            if (shardInjector == null) {
                return;
            }

            logger.debug("[{}] closing... (reason: [{}])", shardId, reason);
            shardsInjectors = ImmutableMap.copyOf(tmpShardInjectors);
            Map<Integer, IndexShard> tmpShardsMap = newHashMap(shards);
            indexShard = tmpShardsMap.remove(shardId);
            shards = ImmutableMap.copyOf(tmpShardsMap);
            indicesLifecycle.beforeIndexShardClosed(sId, indexShard);
            for (Class<? extends Closeable> closeable : pluginsService.shardServices()) {
                try {
                    shardInjector.getInstance(closeable).close();
                } catch (Throwable e) {
                    logger.debug("[{}] failed to clean plugin shard service [{}]", e, shardId, closeable);
                }
            }
            try {
                // now we can close the translog service, we need to close it before the we close the shard
                shardInjector.getInstance(TranslogService.class).close();
            } catch (Throwable e) {
                logger.debug("[{}] failed to close translog service", e, shardId);
                // ignore
            }
            // this logic is tricky, we want to close the engine so we rollback the changes done to it
            // and close the shard so no operations are allowed to it
            if (indexShard != null) {
                try {
                    ((IndexShard) indexShard).close(reason);
                } catch (Throwable e) {
                    logger.debug("[{}] failed to close index shard", e, shardId);
                    // ignore
                }
            }
            try {
                shardInjector.getInstance(Engine.class).close();
            } catch (Throwable e) {
                logger.debug("[{}] failed to close engine", e, shardId);
                // ignore
            }
            try {
                shardInjector.getInstance(MergeSchedulerProvider.class).close();
            } catch (Throwable e) {
                logger.debug("[{}] failed to close merge policy scheduler", e, shardId);
                // ignore
            }
            try {
                shardInjector.getInstance(MergePolicyProvider.class).close();
            } catch (Throwable e) {
                logger.debug("[{}] failed to close merge policy provider", e, shardId);
                // ignore
            }
            try {
                shardInjector.getInstance(IndexShardGatewayService.class).close();
            } catch (Throwable e) {
                logger.debug("[{}] failed to close index shard gateway", e, shardId);
                // ignore
            }
            try {
                // now we can close the translog
                shardInjector.getInstance(Translog.class).close();
            } catch (Throwable e) {
                logger.debug("[{}] failed to close translog", e, shardId);
                // ignore
            }
            try {
                // now we can close the translog
                shardInjector.getInstance(PercolatorQueriesRegistry.class).close();
            } catch (Throwable e) {
                logger.debug("[{}] failed to close PercolatorQueriesRegistry", e, shardId);
                // ignore
            }

            // call this before we close the store, so we can release resources for it
            indicesLifecycle.afterIndexShardClosed(sId, indexShard);
            // if we delete or have no gateway or the store is not persistent, clean the store...
            final Store store = shardInjector.getInstance(Store.class);
            // and close it
            try {
                    store.close();
            } catch (Throwable e) {
                logger.warn("[{}] failed to close store on shard deletion", e, shardId);
            }
            Injectors.close(injector);

            logger.debug("[{}] closed (reason: [{}])", shardId, reason);
        } catch (Throwable t) {
            throw t;
        }

    }
}


text:
package org.eclipse.jetty.start;

import static org.hamcrest.Matchers.*;

import java.io.File;

import org.eclipse.jetty.toolchain.test.MavenTestingUtils;
import org.junit.Assert;
import org.junit.Test;

public class JarVersionTest
{
    private void assertJarVersion(String jarname, String expectedVersion)
    {
        File jarfile = MavenTestingUtils.getTestResourceFile(jarname);
        Assert.assertThat("Jar: " + jarname,JarVersion.getVersion(jarfile),containsString(expectedVersion));
    }

    @Test
    public void testNoManifestJar()
    {
        assertJarVersion("bad-libs/no-manifest.jar","(none specified)");
    }

    @Test
    public void testNotAJar()
    {
        assertJarVersion("bad-libs/not-a.jar","(error: ZipException ");
    }

    @Test
    public void testZeroLengthJar()
    {
        assertJarVersion("bad-libs/zero-length.jar","(error: ZipException ");
    }
}


text:
name: Feature request
about: Suggest an idea for this project

---
<!-- Please don't delete this template or we'll close your issue -->
<!-- Please use English language -->
<!-- Before creating an issue please make sure you are using the latest version of Docsify. -->
<!-- Please ask questions on StackOverflow 👉 https://stackoverflow.com/questions/ask?tags=docsify -->

## Feature request

#### What problem does this feature solve?

#### What does the proposed API look like?

#### How should this be implemented in your opinion?

#### Are you willing to work on this yourself?


text:
package cn.adblock.utils;

import android.content.Context;
import android.os.Handler;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;
import cn.adblock.R;

public class ToastUtil {
	public static final int LENGTH_SHORT = android.widget.Toast.LENGTH_SHORT;
	public static final int LENGTH_LONG = android.widget.Toast.LENGTH_LONG;

	private static android.widget.Toast toast;
	private static Handler handler = new Handler();

	private static Runnable run = new Runnable() {
		public void run() {
			toast.cancel();
		}
	};

	public static void cancel(){
		if (null != toast) {
			toast.cancel();
		}
	}

	private static void toast(Context ctx, CharSequence msg, int duration) {
		handler.removeCallbacks(run);
		// handler的duration不能直接对应Toast的常量时长,在此针对Toast的常量相应定义时长
		switch (duration) {
		case LENGTH_SHORT:// Toast.LENGTH_SHORT值为0,对应的持续时间大概为1s
			duration = 1000;
			break;
		case LENGTH_LONG:// Toast.LENGTH_LONG值为1,对应的持续时间大概为3s
			duration = 3000;
			break;
		default:
			break;
		}
		cancel();
		toast = getToast(ctx, msg.toString());
		handler.postDelayed(run, duration);
		toast.show();
	}

	/**
	 * 弹出Toast
	 *
	 * @param ctx
	 *            弹出Toast的上下文
	 * @param msg
	 *            弹出Toast的内容
	 */
	public static void show(Context ctx, CharSequence msg)
			throws NullPointerException {
		if (null == ctx) {
			throw new NullPointerException("The ctx is null!");
		}
		toast(ctx, msg, LENGTH_SHORT);
	}

	/**
	 * 弹出Toast
	 *
	 * @param ctx
	 *            弹出Toast的上下文
	 * @param msg
	 *            弹出Toast的内容
	 * @param duration
	 *            弹出Toast的持续时间
	 */
	public static void show(Context ctx, CharSequence msg, int duration)
			throws NullPointerException {
		if (null == ctx) {
			throw new NullPointerException("The ctx is null!");
		}
		if (0 > duration) {
			duration = LENGTH_SHORT;
		}
		toast(ctx, msg, duration);
	}

	/**
	 * 弹出Toast
	 *
	 * @param ctx
	 *            弹出Toast的上下文
	 * @param msg
	 *            弹出Toast的内容的资源ID
	 * @param duration
	 *            弹出Toast的持续时间
	 */
	public static void show(Context ctx, int resId, int duration)
			throws NullPointerException {
		if (null == ctx) {
			throw new NullPointerException("The ctx is null!");
		}
		if (0 > duration) {
			duration = LENGTH_SHORT;
		}
		toast(ctx, ctx.getResources().getString(resId), duration);
	}

	public static Toast getToast(Context context, String string) {
		LayoutInflater inflater = LayoutInflater.from(context);
		View layout = inflater.inflate(R.layout.view_toast, null);
		TextView text = (TextView) layout.findViewById(R.id.text);
		text.setText(string);
		Toast toast = new Toast(context);
		// 设置Toast显示位置(起点位置,水平向右位移,垂直向下位移)
		// toast.setGravity(Gravity.TOP | Gravity.CENTER, 0, 1150);
		toast.setDuration(Toast.LENGTH_SHORT);
		toast.setView(layout);
		return toast;
	}
}


text:
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using CSC.CSClassroom.Model.Classrooms;

namespace CSC.CSClassroom.Model.Assignments
{
	/// <summary>
	/// A category of exercises.
	/// </summary>
	public class QuestionCategory
	{
		/// <summary>
		/// The unique ID for the category.
		/// </summary>
		[Required]
		public int Id { get; set; }

		/// <summary>
		/// The ID of the classroom that contains this category.
		/// </summary>
		[Required]
		public int ClassroomId { get; set; }

		/// <summary>
		/// The name of the category.
		/// </summary>
		[Required]
		[MaxLength(100)]
		[Display
		(
			Name = "Name",
			Description = "Enter the name of the category."
		)]
		public string Name { get; set; }

		/// <summary>
		/// The classroom that contains this category.
		/// </summary>
		public virtual Classroom Classroom { get; set; }

		/// <summary>
		/// The exercises in this category.
		/// </summary>
		public virtual ICollection<Question> Questions { get; set; }

		/// <summary>
		/// The randomly generated question that this category contains
		/// choices for (if any).
		/// </summary>
		public int? RandomlySelectedQuestionId { get; set; }

		/// <summary>
		/// The randomly generated question that this category contains
		/// choices for (if any).
		/// </summary>
		public RandomlySelectedQuestion RandomlySelectedQuestion { get; set; }
	}
}


text:
package cn.npt.net.tcp.test;

import io.netty.channel.ChannelHandler.Sharable;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;

/**
 * Handler implementation for the echo server.测试用例
 */
@Sharable
public class EchoServerHandler extends ChannelInboundHandlerAdapter {

	private String contentv;
	public EchoServerHandler() {
		this.contentv="default";
	}
    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) {
    	String buf=(String) msg;
    	System.out.println("receive data:"+buf);
        ctx.writeAndFlush(this.contentv);
        this.contentv=buf;
        //ctx.channel().close();
    }

    @Override
    public void channelReadComplete(ChannelHandlerContext ctx) {
        ctx.flush();
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
        // Close the connection when an exception is raised.
        cause.printStackTrace();
        ctx.close();
        System.out.println("========================closed exception");
    }
}


text:
namespace variations {
namespace {

// The minimum time between consecutive variations seed fetches.
constexpr base::TimeDelta kVariationsSeedFetchIntervalMinimum =
    base::Minutes(1);

// Returns the variations seed fetch interval specified through the
// |kVariationsSeedFetchInterval| switch. The value returned is subject to a
// minimum value, |kVariationsSeedFetchIntervalMinimum|. If no overridden value
// is specified, or if it is malformed, an empty optional is returned.
absl::optional<base::TimeDelta> GetOverriddenFetchPeriod() {
  base::CommandLine* command_line = base::CommandLine::ForCurrentProcess();

  const std::string switch_value =
      command_line->GetSwitchValueASCII(switches::kVariationsSeedFetchInterval);

  if (switch_value.empty())
    return absl::nullopt;

  int overridden_period;
  if (!base::StringToInt(switch_value, &overridden_period)) {
    LOG(DFATAL) << "Malformed value for --"
                << switches::kVariationsSeedFetchInterval << ". "
                << "Expected int, got: " << switch_value;
    return absl::nullopt;
  }

  return std::max(base::Minutes(overridden_period),
                  kVariationsSeedFetchIntervalMinimum);
}

}  // namespace

VariationsRequestScheduler::VariationsRequestScheduler(
    const base::RepeatingClosure& task)
    : task_(task) {}

VariationsRequestScheduler::~VariationsRequestScheduler() = default;

void VariationsRequestScheduler::Start() {
  task_.Run();
  timer_.Start(FROM_HERE, GetFetchPeriod(), task_);
}

void VariationsRequestScheduler::Reset() {
  if (timer_.IsRunning())
    timer_.Reset();
  one_shot_timer_.Stop();
}

void VariationsRequestScheduler::ScheduleFetchShortly() {
  // Reset the regular timer to avoid it triggering soon after.
  Reset();
  // The delay before attempting a fetch shortly.
  base::TimeDelta fetch_shortly_delay = base::Minutes(5);

  // If there is a fetch interval specified in the command line, and it is
  // shorter than |fetch_shortly_delay|, use it instead.
  absl::optional<base::TimeDelta> overridden_period =
      GetOverriddenFetchPeriod();
  if (overridden_period.has_value()) {
    fetch_shortly_delay =
        std::min(fetch_shortly_delay, overridden_period.value());
  }

  one_shot_timer_.Start(FROM_HERE, fetch_shortly_delay, task_);
}

void VariationsRequestScheduler::OnAppEnterForeground() {
  NOTREACHED() << "Attempted to OnAppEnterForeground on non-mobile device";
}

base::TimeDelta VariationsRequestScheduler::GetFetchPeriod() const {
  // The fetch interval can be overridden through the command line.
  absl::optional<base::TimeDelta> overridden_period =
      GetOverriddenFetchPeriod();
  if (overridden_period.has_value())
    return overridden_period.value();

  // The fetch interval can be overridden by a variation param.
  std::string period_min_str =
      GetVariationParamValue("VariationsServiceControl", "fetch_period_min");
  size_t period_min;
  if (base::StringToSizeT(period_min_str, &period_min))
    return base::Minutes(period_min);

  // The default fetch interval is every 30 minutes.
  return base::Minutes(30);
}

base::RepeatingClosure VariationsRequestScheduler::task() const {
  return task_;
}

#if !BUILDFLAG(IS_ANDROID) && !BUILDFLAG(IS_IOS)
// static
VariationsRequestScheduler* VariationsRequestScheduler::Create(
    const base::RepeatingClosure& task,
    PrefService* local_state) {
  return new VariationsRequestScheduler(task);
}
#endif  // !BUILDFLAG(IS_ANDROID) && !BUILDFLAG(IS_IOS)

}  // namespace variations


text:
package com.hazelcast.internal.partition.service;

import com.hazelcast.logging.ILogger;
import com.hazelcast.spi.ManagedService;
import com.hazelcast.spi.MigrationAwareService;
import com.hazelcast.spi.NodeEngine;
import com.hazelcast.spi.PartitionMigrationEvent;
import com.hazelcast.spi.ServiceNamespace;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.Properties;

/**
 */
public abstract class TestAbstractMigrationAwareService<N> implements ManagedService, MigrationAwareService {

    protected static final String BACKUP_COUNT_PROP = "backups.count";

    private final List<PartitionMigrationEvent> beforeEvents = new ArrayList<PartitionMigrationEvent>();

    private final List<PartitionMigrationEvent> commitEvents = new ArrayList<PartitionMigrationEvent>();

    private final List<PartitionMigrationEvent> rollbackEvents = new ArrayList<PartitionMigrationEvent>();

    public volatile int backupCount;

    private volatile ILogger logger;

    @Override
    public void init(NodeEngine nodeEngine, Properties properties) {
        backupCount = Integer.parseInt(properties.getProperty(BACKUP_COUNT_PROP, "1"));
        logger = nodeEngine.getLogger(getClass());
    }

    @Override
    public void reset() {
    }

    @Override
    public void shutdown(boolean terminate) {
    }

    @Override
    public final void beforeMigration(PartitionMigrationEvent event) {
        synchronized (beforeEvents) {
            beforeEvents.add(event);
        }
        onBeforeMigration(event);
    }

    protected void onBeforeMigration(PartitionMigrationEvent event) {
    }

    @Override
    public final void commitMigration(PartitionMigrationEvent event) {
        synchronized (commitEvents) {
            commitEvents.add(event);
        }
        onCommitMigration(event);
    }

    protected void onCommitMigration(PartitionMigrationEvent event) {
    }

    @Override
    public void rollbackMigration(PartitionMigrationEvent event) {
        synchronized (rollbackEvents) {
            rollbackEvents.add(event);
        }
        onRollbackMigration(event);
    }

    protected void onRollbackMigration(PartitionMigrationEvent event) {
    }

    public List<PartitionMigrationEvent> getBeforeEvents() {
        synchronized (beforeEvents) {
            return new ArrayList<PartitionMigrationEvent>(beforeEvents);
        }
    }

    public List<PartitionMigrationEvent> getCommitEvents() {
        synchronized (commitEvents) {
            return new ArrayList<PartitionMigrationEvent>(commitEvents);
        }
    }

    public List<PartitionMigrationEvent> getRollbackEvents() {
        synchronized (rollbackEvents) {
            return new ArrayList<PartitionMigrationEvent>(rollbackEvents);
        }
    }

    public void clearEvents() {
        synchronized (beforeEvents) {
            beforeEvents.clear();
        }
        synchronized (commitEvents) {
            commitEvents.clear();
        }
        synchronized (rollbackEvents) {
            rollbackEvents.clear();
        }
    }

    public abstract int size(N name);

    public abstract Integer get(N name, int id);

    public abstract Collection<Integer> keys(N name);

    public abstract boolean contains(N name, int partitionId);

    public abstract String getServiceName();

    public abstract ServiceNamespace getNamespace(N name);
}


text:
'use strict';
/**
 * @ngdoc overview
 * @name costpadApp:routes
 * @description
 * # routes.js
 *
 * Configure routes for use with Angular, and apply authentication security
 * Add new routes to the ROUTES constant or use yo angularfire:route to create them
 *
 * Any controller can be secured so that it will only load if user is logged in by
 * using `whenAuthenticated()` in place of `when()`. This requires the user to
 * be logged in to view this route, and adds the current user into the dependencies
 * which can be injected into the controller. If user is not logged in, the promise is
 * rejected, which is handled below by $routeChangeError
 *
 * Any controller can be forced to wait for authentication to resolve, without necessarily
 * requiring the user to be logged in, by adding a `resolve` block similar to the one below.
 * It would then inject `user` as a dependency. This could also be done in the controller,
 * but abstracting it makes things cleaner (controllers don't need to worry about auth state
 * or timing of displaying its UI components; it can assume it is taken care of when it runs)
 *
 *   resolve: {
 *     user: ['simpleLogin', function(simpleLogin) {
 *       return simpleLogin.getUser();
 *     }]
 *   }
 *
 */
angular.module('costpadApp')

/**
 * Adds a special `whenAuthenticated` method onto $routeProvider. This special method,
 * when called, invokes the authRequired() service (see simpleLogin.js).
 *
 * The promise either resolves to the authenticated user object and makes it available to
 * dependency injection (see AccountCtrl), or rejects the promise if user is not logged in,
 * forcing a redirect to the /login page
 */
  .config(['$routeProvider', 'SECURED_ROUTES', function($routeProvider, SECURED_ROUTES) {
    // credits for this idea: https://groups.google.com/forum/#!msg/angular/dPr9BpIZID0/MgWVluo_Tg8J
    // unfortunately, a decorator cannot be use here because they are not applied until after
    // the .config calls resolve, so they can't be used during route configuration, so we have
    // to hack it directly onto the $routeProvider object
    $routeProvider.whenAuthenticated = function(path, route) {
      route.resolve = route.resolve || {};
      route.resolve.user = ['authRequired', function(authRequired) {
        return authRequired();
      }];
      $routeProvider.when(path, route);
      SECURED_ROUTES[path] = true;
      return $routeProvider;
    };
  }])

  // configure views; the authRequired parameter is used for specifying pages
  // which should only be available while logged in
  .config(['$routeProvider', function($routeProvider) {
    $routeProvider
      .when('/', {
        templateUrl: 'views/main.html',
        controller: 'MainCtrl'
      })

      .when('/login', {
        templateUrl: 'views/login.html',
        controller: 'LoginCtrl'
      })

      .when('/chat', {
        templateUrl: 'views/chat.html',
        controller: 'ChatCtrl'
      })

      .whenAuthenticated('/account', {
        templateUrl: 'views/account.html',
        controller: 'AccountCtrl'
      })

      .when('/chat', {
        templateUrl: 'views/chat.html',
        controller: 'ChatCtrl'
      })
      .otherwise({redirectTo: '/'});
  }])

  /**
   * Apply some route security. Any route's resolve method can reject the promise with
   * { authRequired: true } to force a redirect. This method enforces that and also watches
   * for changes in auth status which might require us to navigate away from a path
   * that we can no longer view.
   */
  .run(['$rootScope', '$location', 'simpleLogin', 'SECURED_ROUTES', 'loginRedirectPath',
    function($rootScope, $location, simpleLogin, SECURED_ROUTES, loginRedirectPath) {
      // watch for login status changes and redirect if appropriate
      simpleLogin.watch(check, $rootScope);

      // some of our routes may reject resolve promises with the special {authRequired: true} error
      // this redirects to the login page whenever that is encountered
      $rootScope.$on('$routeChangeError', function(e, next, prev, err) {
        if( angular.isObject(err) && err.authRequired ) {
          $location.path(loginRedirectPath);
        }
      });

      function check(user) {
        if( !user && authRequired($location.path()) ) {
          $location.path(loginRedirectPath);
        }
      }

      function authRequired(path) {
        return SECURED_ROUTES.hasOwnProperty(path);
      }
    }
  ])

  // used by route security
  .constant('SECURED_ROUTES', {});


text:
<?php

session_start();
include('./Impossible.html');

$host = "localhost";
$user = "root";
$password = "";
$database = "Impossible";

$connection = mysqli_connect($host, $user, $password, $database);
if(mysqli_connect_errno($connection))
	echo "Cannot connect";

if (!$connection) {
    echo "Error: Unable to connect to MySQL." . PHP_EOL;
    echo "Debugging errno: " . mysqli_connect_errno() . PHP_EOL;
    echo "Debugging error: " . mysqli_connect_error() . PHP_EOL;
    exit;
}

$result = mysqli_query($connection, "SELECT * FROM HallOfFame");
if($result == false)
	echo "
failure retrieving data
";

$_SESSION['HallOfFame'] = array();
$i = 0;
while($row = mysqli_fetch_array($result)) {
	$_SESSION['HallOfFame'][$i] = $row;
	$i++;
}

mysqli_close($connection);

?>


text:
<!doctype html>

    <meta charset="UTF-8">
    <title>Cockpit installation</title>
    <link rel="icon" href="../assets/images/favicon.ico" type="image/x-icon">

    <link rel="stylesheet" href="style.css">

Installation failed

                    Failed:

                    <?php echo @$info;?>

                <a href="?<?php echo time();?>" class="uk-button uk-button-large uk-button-primary">Retry installation


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

package org.chromium.chrome.browser.notifications;

import static org.chromium.ui.base.ViewUtils.dpToPx;

import android.content.Context;
import android.content.res.Resources;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.os.Process;
import android.text.format.DateFormat;
import android.util.DisplayMetrics;
import android.view.View;
import android.widget.RemoteViews;

import androidx.annotation.VisibleForTesting;

import org.chromium.base.StrictModeContext;
import org.chromium.components.browser_ui.notifications.NotificationMetadata;
import org.chromium.components.browser_ui.notifications.NotificationWrapper;
import org.chromium.components.browser_ui.notifications.NotificationWrapperBuilder;
import org.chromium.ui.base.LocalizationUtils;

import java.util.Date;

/**
 * Builds a notification using the given inputs. Uses RemoteViews to provide a custom layout.
 */
public class CustomNotificationBuilder extends NotificationBuilderBase {
    /**
     * The maximum width of action icons in dp units.
     */
    private static final int MAX_ACTION_ICON_WIDTH_DP = 32;

    /**
     * The maximum number of lines of body text for the expanded state. Fewer lines are used when
     * the text is scaled up, with a minimum of one line.
     */
    private static final int MAX_BODY_LINES = 7;

    /**
     * The fontScale considered large for the purposes of layout.
     */
    private static final float FONT_SCALE_LARGE = 1.3f;

    /**
     * The maximum amount of padding (in dip units) that is applied around views that must have a
     * flexible amount of padding. If the font size is scaled up the applied padding will be scaled
     * down towards 0.
     */
    private static final int MAX_SCALABLE_PADDING_DP = 3;

    /**
     * The amount of padding at the start of the button, either before an icon or before the text.
     */
    private static final int BUTTON_PADDING_START_DP = 8;

    /**
     * The amount of padding between the icon and text of a button. Used only if there is an icon.
     */
    private static final int BUTTON_ICON_PADDING_DP = 8;

    /**
     * The size of the work profile badge (width and height).
     */
    private static final int WORK_PROFILE_BADGE_SIZE_DP = 16;

    /**
     * Material Grey 600 - to be applied to action button icons in the Material theme.
     */
    private static final int BUTTON_ICON_COLOR_MATERIAL = 0xff757575;

    private final Context mContext;

    public CustomNotificationBuilder(Context context) {
        super(context.getResources());
        mContext = context;
    }

    @Override
    public NotificationWrapper build(NotificationMetadata metadata) {
        // A note about RemoteViews and updating notifications. When a notification is passed to the
        // {@code NotificationManager} with the same tag and id as a previous notification, an
        // in-place update will be performed. In that case, the actions of all new
        // {@link RemoteViews} will be applied to the views of the old notification. This is safe
        // for actions that overwrite old values such as setting the text of a {@code TextView}, but
        // care must be taken for additive actions. Especially in the case of
        // {@link RemoteViews#addView} the result could be to append new views below stale ones. In
        // that case {@link RemoteViews#removeAllViews} must be called before adding new ones.
        RemoteViews compactView =
                new RemoteViews(mContext.getPackageName(), R.layout.web_notification);
        RemoteViews bigView =
                new RemoteViews(mContext.getPackageName(), R.layout.web_notification_big);

        float fontScale = mContext.getResources().getConfiguration().fontScale;
        bigView.setInt(R.id.body, "setMaxLines", calculateMaxBodyLines(fontScale));
        int scaledPadding =
                calculateScaledPadding(fontScale, mContext.getResources().getDisplayMetrics());
        String formattedTime;
        // TODO(crbug.com/577185): Temporarily allowing disk access until more permanent fix is in.
        try (StrictModeContext ignored = StrictModeContext.allowDiskWrites()) {
            formattedTime = DateFormat.getTimeFormat(mContext).format(new Date());
        }

        for (RemoteViews view : new RemoteViews[] {compactView, bigView}) {
            view.setTextViewText(R.id.time, formattedTime);
            view.setTextViewText(R.id.title, mTitle);
            view.setTextViewText(R.id.body, mBody);
            view.setTextViewText(R.id.origin, mOrigin);
            view.setImageViewBitmap(R.id.icon, getNormalizedLargeIcon());
            view.setViewPadding(R.id.title, 0, scaledPadding, 0, 0);
            view.setViewPadding(R.id.body_container, 0, scaledPadding, 0, scaledPadding);
            addWorkProfileBadge(view);

            int smallIconId = R.id.small_icon_overlay;
            view.setViewVisibility(smallIconId, View.VISIBLE);
            if (mSmallIconBitmapForContent != null) {
                view.setImageViewBitmap(smallIconId, mSmallIconBitmapForContent);
            } else {
                view.setImageViewResource(smallIconId, mSmallIconId);
            }
        }
        addActionButtons(bigView);
        configureSettingsButton(bigView);

        NotificationWrapperBuilder builder =
                NotificationWrapperBuilderFactory.createNotificationWrapperBuilder(
                        mChannelId, metadata);
        builder.setTicker(mTickerText);
        builder.setContentIntent(mContentIntent);
        builder.setDeleteIntent(mDeleteIntent);
        builder.setPriorityBeforeO(mPriority);
        builder.setDefaults(mDefaults);
        if (mVibratePattern != null) builder.setVibrate(mVibratePattern);
        builder.setSilent(mSilent);
        builder.setWhen(mTimestamp);
        builder.setShowWhen(true);
        builder.setOnlyAlertOnce(!mRenotify);
        builder.setContent(compactView);

        // Some things are duplicated in the builder to ensure the notification shows correctly on
        // Wear devices and custom lock screens.
        builder.setContentTitle(mTitle);
        builder.setContentText(mBody);
        builder.setSubText(mOrigin);
        builder.setLargeIcon(getNormalizedLargeIcon());
        setStatusBarIcon(builder, mSmallIconId, mSmallIconBitmapForStatusBar);
        for (Action action : mActions) {
            addActionToBuilder(builder, action);
        }
        if (mSettingsAction != null) {
            addActionToBuilder(builder, mSettingsAction);
        }
        setGroupOnBuilder(builder, mOrigin);
        builder.setPublicVersion(createPublicNotification(mContext));

        return builder.buildWithBigContentView(bigView);
    }

    /**
     * If there are actions, shows the button related views, and adds a button for each action.
     */
    private void addActionButtons(RemoteViews bigView) {
        // Remove the existing buttons in case an existing notification is being updated.
        bigView.removeAllViews(R.id.buttons);

        // Always set the visibility of the views associated with the action buttons. The current
        // visibility state is not known as perhaps an existing notification is being updated.
        int visibility = mActions.isEmpty() ? View.GONE : View.VISIBLE;
        bigView.setViewVisibility(R.id.button_divider, visibility);
        bigView.setViewVisibility(R.id.buttons, visibility);

        Resources resources = mContext.getResources();
        DisplayMetrics metrics = resources.getDisplayMetrics();
        for (Action action : mActions) {
            RemoteViews view =
                    new RemoteViews(mContext.getPackageName(), R.layout.web_notification_button);

            // If there is an icon then set it and add some padding.
            if (action.iconBitmap != null || action.iconId != 0) {
                view.setInt(R.id.button_icon, "setColorFilter", BUTTON_ICON_COLOR_MATERIAL);

                int iconWidth = 0;
                if (action.iconBitmap != null) {
                    view.setImageViewBitmap(R.id.button_icon, action.iconBitmap);
                    iconWidth = action.iconBitmap.getWidth();
                } else if (action.iconId != 0) {
                    view.setImageViewResource(R.id.button_icon, action.iconId);
                    BitmapFactory.Options options = new BitmapFactory.Options();
                    options.inJustDecodeBounds = true;
                    BitmapFactory.decodeResource(resources, action.iconId, options);
                    iconWidth = options.outWidth;
                }
                iconWidth = dpToPx(
                        metrics, Math.min(pxToDp(iconWidth, metrics), MAX_ACTION_ICON_WIDTH_DP));

                // Set the padding of the button so the text does not overlap with the icon. Flip
                // between left and right manually as RemoteViews does not expose a method that sets
                // padding in a writing-direction independent way.
                int buttonPadding =
                        dpToPx(metrics, BUTTON_PADDING_START_DP + BUTTON_ICON_PADDING_DP)
                        + iconWidth;
                int buttonPaddingLeft = LocalizationUtils.isLayoutRtl() ? 0 : buttonPadding;
                int buttonPaddingRight = LocalizationUtils.isLayoutRtl() ? buttonPadding : 0;
                view.setViewPadding(R.id.button, buttonPaddingLeft, 0, buttonPaddingRight, 0);
            }

            view.setTextViewText(R.id.button, action.title);
            view.setOnClickPendingIntent(R.id.button, action.intent.getPendingIntent());
            bigView.addView(R.id.buttons, view);
        }
    }

    private void configureSettingsButton(RemoteViews bigView) {
        if (mSettingsAction == null) {
            bigView.setViewVisibility(R.id.origin_settings_icon, View.GONE);
            int rightPadding = dpToPx(mContext, BUTTON_ICON_PADDING_DP);
            int leftPadding = 0;
            bigView.setViewPadding(R.id.origin, leftPadding, 0, rightPadding, 0);
            return;
        }
        bigView.setOnClickPendingIntent(R.id.origin, mSettingsAction.intent.getPendingIntent());
        bigView.setInt(R.id.origin_settings_icon, "setColorFilter", BUTTON_ICON_COLOR_MATERIAL);
    }

    /**
     * Shows the work profile badge if it is needed.
     */
    private void addWorkProfileBadge(RemoteViews view) {
        Resources resources = mContext.getResources();
        DisplayMetrics metrics = resources.getDisplayMetrics();
        int size = dpToPx(metrics, WORK_PROFILE_BADGE_SIZE_DP);
        int[] colors = new int[size * size];

        // Create an immutable bitmap, so that it can not be reused for painting a badge into it.
        Bitmap bitmap = Bitmap.createBitmap(colors, size, size, Bitmap.Config.ARGB_8888);

        Drawable inputDrawable = new BitmapDrawable(resources, bitmap);
        Drawable outputDrawable =
                mContext.getPackageManager().getUserBadgedDrawableForDensity(inputDrawable,
                        Process.myUserHandle(), null /* badgeLocation */, metrics.densityDpi);

        // The input bitmap is immutable, so the output drawable will be a different instance from
        // the input drawable if the work profile badge was applied.
        if (inputDrawable != outputDrawable && outputDrawable instanceof BitmapDrawable) {
            view.setImageViewBitmap(
                    R.id.work_profile_badge, ((BitmapDrawable) outputDrawable).getBitmap());
            view.setViewVisibility(R.id.work_profile_badge, View.VISIBLE);
        }
    }

    /**
     * Scales down the maximum number of displayed lines in the body text if font scaling is greater
     * than 1.0. Never scales up the number of lines, as on some devices the notification text is
     * rendered in dp units (which do not scale) and additional lines could lead to cropping at the
     * bottom of the notification.
     *
     * @param fontScale The current system font scaling factor.
     * @return The number of lines to be displayed.
     */
    @VisibleForTesting
    static int calculateMaxBodyLines(float fontScale) {
        if (fontScale > 1.0f) {
            return (int) Math.round(Math.ceil((1 / fontScale) * MAX_BODY_LINES));
        }
        return MAX_BODY_LINES;
    }

    /**
     * Scales down the maximum amount of flexible padding to use if font scaling is over 1.0. Never
     * scales up the amount of padding, as on some devices the notification text is rendered in dp
     * units (which do not scale) and additional padding could lead to cropping at the bottom of the
     * notification. Never scales the padding below zero.
     *
     * @param fontScale The current system font scaling factor.
     * @param metrics The display metrics for the current context.
     * @return The amount of padding to be used, in pixels.
     */
    @VisibleForTesting
    static int calculateScaledPadding(float fontScale, DisplayMetrics metrics) {
        float paddingScale = 1.0f;
        if (fontScale > 1.0f) {
            fontScale = Math.min(fontScale, FONT_SCALE_LARGE);
            paddingScale = (FONT_SCALE_LARGE - fontScale) / (FONT_SCALE_LARGE - 1.0f);
        }
        return dpToPx(metrics, paddingScale * MAX_SCALABLE_PADDING_DP);
    }

    /**
     * Converts a px value to a dp value.
     */
    private static int pxToDp(float value, DisplayMetrics metrics) {
        return Math.round(value / ((float) metrics.densityDpi / DisplayMetrics.DENSITY_DEFAULT));
    }
}


text:
This is the sample app for `appython` and probably the one you want to use to build your own app.

## Features

* Two different modules, based on Flask blueprints, with different scaling settings.
* The default module includes an [Ionic](http://ionicframework.com) app as frontend.
* The API module has a RESTful API built with Flask-RESTful.
* Authentication is handled by Flask-Login and a default `UserModel` is provided.
* Automatic error management is monitored by [Sentry](https://getsentry.com).
* Includes to sample API endpoints (`meta` and `user`).
* Includes a sample task endpoint.
* Includes a sample daily cron job endpoint.
* A sample script to use the Remote API.
* The deferred API is enabled by default.

Other goodies:

* Module dependencies are managed by `requirements.txt` files and set up in `appengine_config.py`.
* An automated run/build/deploy system in one `Makefile`.
* GitHub's default Python `.gitignore` is included.
* The app is ready to serve static content, securily if needed.
* Web app dependencies are managed by Bower.
* A folder shared among both modules with some App Engine utils.

## Checklists

### Requirements

* Python and Virtualenv.
* Google App Engine SDK for Python.
* Bower.
* Closure.
* SASS.

### Set up checklist

Getting your project off the ground, in 10 easy steps:

1. Add this repository to your project as a submodule: `git submodule add https://github.com/zugaldia/appython.git`.

2. Copy this folder (`appython/samples/standard`) into your own project and rename it to something that makes sense to you. For example: `cp -R appython/samples/standard .; mv standard appengine`.

3. Rename `app/shared/config.py.TEMPLATE` to `app/shared/config.py` and update the `EMAIL_SUPERUSER` (to be able to create the first user), `SECRET_KEY` (you can use `scripts/generate.py` for that), and `SENTRY_DSN` (if you want error management controlled by Sentry). **Note** that `config.py` is, by default, *not* tracked by git (remove the `.gitignore` if you want to track it).

4. Update `Makefile` to set your own `PROJECT_ID`.

5. Update `Makefile` and `vendor/Makefile` to set the relative path to the submodule root (`APPYTHON_ROOT`). For example, in the case above, you'd use `../appython` and `../../appython`, respectively.

6. Add all files to GitHub (it's easier now before adding all vendor dependencies): `git add appengine`

7. Add symlinks to `appython` and the `shared` folder: `make add-symlinks`.

8. Add frontend dependencies: `make add-bower`.

9. Add backend dependencies: `cd vendor; make deps`.

10. Customize `README.md`, edit `app/module_default/static/partials/main.html` and `app/module_default/templates/landing*html` to change the default message.

### Run locally

* Run the default module with `make run-default`, or `make run-default-clean` (for an empty database).

* Run the API module with `make run-api`, or `make run-api-clean` (for an empty database).

Point your browser at `http://localhost:8080` to see a module running
(`http://localhost:8000` for the admin interface).

### Deploy

1. Do `make deploy-default` to deploy the default module (and the information in `cron.yaml`, `index.yaml`, and `queue.yaml`). It should look like this: http://com-zugaldia-appython.appspot.com

2. Do `make deploy-api` to deploy the API module. It should look like this: http://api.com-zugaldia-appython.appspot.com

### First time configuration

In order to create the superuser, visit `/api/v1/user/setup` and write down the generated password and API key.


text:
from absl import logging
import copy
import geopandas as gpd
from geopandas import GeoSeries
import networkx as nx
import os
import osmnx as ox
import pandas as pd
from shapely.geometry.point import Point
from shapely.geometry.polygon import Polygon
from shapely.geometry import LineString
from shapely.geometry.multipolygon import MultiPolygon

import swifter
from typing import Tuple, Sequence, Text, Optional, List, Any

from cabby.geo import util
from cabby.geo.map_processing import edge
from cabby.geo import regions
from cabby.geo import osm

POI_PREFIX = '#'
SHOW_PROGRESS_EVERY = 100
# Addition of distance to POI edges in order to prevent shortcut route through
# the POI node.
ADD_POI_DISTANCE = 5000

# Remove large POI such as Manhattan. Max area in WGS84 - EPSG:4326.
LARGE_AREAS = 0.0001

class Map:

  def __init__(
    self, region: regions.Region, level: int = 18, load_directory: Text = None):
    self.map_name = region.name
    self.s2_graph = None
    self.level = level
    self.polygon_area = region.polygon
    self.num_poi_add = 0

    if load_directory is None:
      logging.info("Preparing map.")
      logging.info("Extracting POI.")
      self.poi, self.streets = self.get_poi()
      self.num_poi = self.poi.shape[0]
      logging.info("Constructing graph.")
      self.nx_graph = ox.graph_from_polygon(
        self.polygon_area, network_type='walk')
      distance = nx.get_edge_attributes(self.nx_graph, 'length')
      nx.set_edge_attributes(self.nx_graph, distance, 'true_length')

      logging.info("Add POI to graph.")
      self.add_poi_to_graph()

      osmid = nx.get_node_attributes(self.nx_graph, 'osmid')
      osmid_str = dict(zip(osmid, map(str, osmid.values())))
      nx.set_node_attributes(self.nx_graph, osmid_str, 'osmid')
      nx.relabel_nodes(self.nx_graph, osmid_str, copy=False)

      self.poi['osmid'] = self.poi['osmid'].astype(str)

    else:
      logging.info("Loading map from directory.")
      self.load_map(load_directory)
      self.num_poi = self.poi.shape[0]

    logging.info("Calculate S2Cell covering.")
    self.calc_s2cells(level)

    self.nodes, self.edges = ox.graph_to_gdfs(self.nx_graph)

    self.process_param()

  def process_param(self):
    '''Helper function for processing the class data objects.'''

    # Drop columns with list type.
    self.edges.drop(self.edges.columns.difference(
      ['osmid', 'true_length', 'length', 'geometry', 'u', 'v', 'key', 'name']),
      1, inplace=True)
    self.edges['osmid'] = self.edges['osmid'].apply(lambda x: str(x))

  def get_poi(self) -> Tuple[GeoSeries, GeoSeries]:
    '''Extract point of interests (POI) for the defined region.
    Returns:
      (1) The POI that are not roads; and (2) the roads POI.
    '''

    tags = osm.INTERESTING_TAGS

    osm_poi = ox.geometries.geometries_from_polygon(self.polygon_area, tags=tags)

    if ('highway' in osm_poi.columns) and ('railway' in osm_poi.columns):
      condition_streets = osm_poi.apply(
        lambda x:  (pd.notnull(x.highway))
                   or (pd.notnull(x.railway))
                   or (isinstance(x.geometry, LineString)), axis=1)
    else:
      condition_streets = osm_poi.apply(
        lambda x:  isinstance(x.geometry, LineString), axis=1)
    osm_poi_no_streets = osm_poi[~condition_streets]
    osm_poi_streets = osm_poi[condition_streets]

    # Remove large POI such as Manhattan.
    osm_without_large_areas = osm_poi_no_streets[
      osm_poi_no_streets.geometry.apply(lambda x: x.area < LARGE_AREAS)]

    # Get centroid for POI.
    centroid_list = osm_without_large_areas['geometry'].apply(
      lambda x: x if isinstance(x, Point) else x.centroid).tolist()

    osm_without_large_areas = osm_without_large_areas.assign(centroid=centroid_list)

    return osm_without_large_areas, osm_poi_streets

  def add_single_poi_to_graph(
      self, single_poi: pd.Series) -> Optional[Sequence[edge.Edge]]:
    '''Add single POI to nx_graph.
    Arguments:
      single_poi: a single POI to be added to graph.
    Returns:
      The new osmid.
    '''

    self.num_poi_add += 1
    if self.num_poi_add%SHOW_PROGRESS_EVERY == 0:
      percentage_gen = round(100*self.num_poi_add/self.num_poi)
      logging.info(
        f"Number of POI add to graph {self.num_poi_add}, " +
        f"that is {percentage_gen}% of the required POI addition.")

    # If the POI is already in the graph, do not add it.
    if single_poi['osmid'] in self.nx_graph:
      return None

    # Project POI on to the closest edge in graph.
    geometry = single_poi['geometry']
    if isinstance(geometry, Point):
      points = [geometry]
    else: # Polygon or LineString
      if isinstance(geometry, Polygon):
        coords = geometry.exterior.coords
      elif isinstance(geometry, LineString):
        coords = geometry.coords
      elif isinstance(geometry, MultiPolygon):
        coords = [poly.exterior.coords[0] for poly in geometry]
      else:
        return None
      n_points = len(coords)

      # Sample maximum 4 points.
      sample_1 = Point(coords[0])
      sample_2 = Point(coords[int(n_points/4)])
      sample_3 = Point(coords[int(n_points/2)])
      sample_4 = Point(coords[int(3*n_points/4)])
      points = [sample_1, sample_2, sample_3, sample_4]
      points = points[0:4]

    poi_osmid = single_poi['osmid']
    centroid_point = single_poi['centroid']

    # POI_PREFIX indicates a POI added to the graph.
    poi_osmid = self.create_poi_id(poi_osmid)

    # If the POI is already in the graph, do not add it.
    if poi_osmid in self.nx_graph:
      return None

    assert poi_osmid not in self.poi['osmid'].tolist(), poi_osmid

    list_edges_connected_ids = []
    edges_to_add = []
    for point in points:
      edges_to_add += self.add_single_point_edge(
        point, list_edges_connected_ids, poi_osmid, centroid_point)

    # Add node POI to graph.
    self.nx_graph.add_node(
      poi_osmid,
      highway="poi",
      osmid=poi_osmid,
      x=centroid_point.x,
      y=centroid_point.y,
      name="poi",
    )

    self.poi.loc[self.poi['osmid'] ==
           single_poi['osmid'], 'osmid'] = poi_osmid

    return edges_to_add

  def create_poi_id(self, poi_osmid: int) -> str:
    '''Create a new OSM id for an added POI to graph.
    Arguments:
      poi_osmid: the POI id to be added to graph.
    Returns:
      The new OSM id of the POI.
    '''
    return POI_PREFIX + str(poi_osmid)

  def create_projected_poi_id(self, poi_osmid: str, list_projected: Sequence) -> str:
    '''Create a new OSM id for an added projected POI to graph.
    Arguments:
      poi_osmid: the POI id to be added to graph.
      list_projected: The list of projected points from the POI.
    Returns:
      The OSM id of the projected POI.
    '''
    assert POI_PREFIX in poi_osmid
    len_list_projected = len(list_projected)
    return str(len_list_projected) + poi_osmid

  def add_single_point_edge(self, point_exterior: Point,
                list_edges_connected_ids: List,
                poi_osmid: str,
                centroid_point: Point) -> Optional[Sequence[edge.Edge]]:
    '''Connect a POI to the closest edge: (1) claculate the projected point to
    the nearest edge; (2) add the projected node to the graph; (3) create an
    edge between the point of the POI and the projcted point (add to the list
    to be returned); (4) create two edges from the closest edge (u-v) and the
    projected point: (a) u-projected point; (b) v-projected point; (5) remove
    closest edge u-v.
    Arguments:
      point_exterior: a point on the exterior of a POI that will be projected
      on to the closest edge.
      list_edges_connected_ids: list of edges ids already connected to the POI.
      If the current edge found is already connected it will avoid connecting
      it again.
      poi_osmid: the POI  id to be connected to the edge.
      centroid_point: the centroid point of the POI that will be connected to
      the edges.
    Returns:
      The edges between the POI and the closest edge found to be added to the
      graph.
    '''

    try:

      near_edge_u, near_edge_v, near_edge_key, line = \
        ox.distance.get_nearest_edge(
          self.nx_graph, util.tuple_from_point(point_exterior), return_geom=True,
          )

    except Exception as e:
      print(e)
      return []

    edge_id = (near_edge_u, near_edge_v, near_edge_key)

    if edge_id in list_edges_connected_ids:  # Edge already connected
      return []

    # Get nearest points - u and v.
    u_node = self.nx_graph.nodes[near_edge_u]
    u_point = Point(u_node['x'], u_node['y'])

    v_node = self.nx_graph.nodes[near_edge_v]
    v_point = Point(v_node['x'], v_node['y'])

    # Add to connected edges.
    list_edges_connected_ids.append(edge_id)

    near_edge = self.nx_graph.edges[edge_id]

    dist_projected = line.project(point_exterior)
    projected_point = line.interpolate(line.project(point_exterior))

    cut_geometry = util.cut(line,dist_projected)

    n_lines = len(cut_geometry)

    line_1 = cut_geometry[0]
    dist_1 = util.get_line_length(line_1)

    if n_lines==2:
      assert projected_point==Point(line_1.coords[-1])
      line_2 = cut_geometry[1]
      dist_2 = util.get_line_length(line_2)

      projected_point_osmid = self.create_projected_poi_id(
        poi_osmid, list_edges_connected_ids)

    else: # Projected point is exactly on the end of the line (U or V).
      dist_u_p = util.get_distance_between_points(u_point, projected_point)
      dist_v_p = util.get_distance_between_points(v_point, projected_point)
      if dist_u_p < dist_v_p:
        projected_point_osmid = near_edge_u
      else:
        projected_point_osmid = near_edge_v

    assert n_lines==1 or projected_point_osmid not in self.poi['osmid'].tolist(), (
      projected_point_osmid)

    if isinstance(near_edge['highway'], list):
      highway = ','.join(near_edge['highway'])
    else:
      highway = near_edge['highway']

    projected_line_centroid = LineString([projected_point,centroid_point])
    projected_line_centroid_dist = util.get_linestring_distance(
      projected_line_centroid)

    edge_to_add = edge.Edge.from_poi(
      u_for_edge=poi_osmid,
      v_for_edge=projected_point_osmid,
      osmid=near_edge['osmid'],
      geometry=projected_line_centroid,
      length = projected_line_centroid_dist + ADD_POI_DISTANCE,
      true_length = projected_line_centroid_dist

    )
    edges_list = [edge_to_add]

    if n_lines==1:
      return edges_list

    self.nx_graph.add_node(
      projected_point_osmid,
      highway=highway,
      osmid=projected_point_osmid,
      x=projected_point.x,
      y=projected_point.y,
      name = 'projected-poi'
    )

    line_1_point_end = Point(line_1.coords[0])
    dist_u_1 = util.get_distance_between_points(u_point, line_1_point_end)
    dist_v_1 = util.get_distance_between_points(v_point, line_1_point_end)

    if dist_u_1 < dist_v_1:
      dist_u = dist_1
      line_u = line_1
      dist_v = dist_2
      line_v = line_2
    else:
      dist_u = dist_2
      line_u = line_2
      dist_v = dist_1
      line_v = line_1

    # Add edges between projected point and u and v, on the street segment.
    street_name = near_edge['name'] if 'name' in near_edge else ""

    if not projected_point_osmid == near_edge_u:
      edge_to_add = edge.Edge.from_projected(
        near_edge_u, projected_point_osmid, dist_u, near_edge['highway'],
        near_edge['osmid'], street_name, line_u)
      self.add_two_ways_edges(edge_to_add)

    if not projected_point_osmid == near_edge_v:
      edge_to_add = edge.Edge.from_projected(
        near_edge_v, projected_point_osmid, dist_v, near_edge['highway'],
        near_edge['osmid'], street_name, line_v)
      self.add_two_ways_edges(edge_to_add)

    # Remove u-v edge.
    self.nx_graph.remove_edge(near_edge_u, near_edge_v)
    self.nx_graph.remove_edge(near_edge_v, near_edge_u)
    return edges_list

  def add_two_ways_edges(self, edge_add: edge.Edge):
    '''Add edges to graph.'''

    assert edge_add.u_for_edge is not None
    assert edge_add.v_for_edge is not None

    self.nx_graph.add_edge(
      u_for_edge=edge_add.u_for_edge,
      v_for_edge=edge_add.v_for_edge,
      length=edge_add.length,
      true_length=edge_add.true_length,
      osmid=edge_add.osmid,
      name=edge_add.name,
      highway=edge_add.highway,
      oneway=edge_add.oneway,
      geometry=edge_add.geometry
    )

    self.nx_graph.add_edge(
      u_for_edge=edge_add.v_for_edge,
      v_for_edge=edge_add.u_for_edge,
      length=edge_add.length,
      true_length=edge_add.true_length,
      osmid=edge_add.osmid,
      name=edge_add.name,
      highway=edge_add.highway,
      oneway=edge_add.oneway,
      geometry=edge_add.geometry
    )

  def add_poi_to_graph(self):
    '''Add all POI to nx_graph(currently contains only the roads).'''
    self.num_poi = self.poi.shape[0]
    logging.info(f"Number of POI to add to graph: {self.num_poi}")
    edges_to_add_list = self.poi.apply(self.add_single_poi_to_graph, axis=1)
    edges_to_add_list = edges_to_add_list.dropna()
    edges_to_add_list.swifter.apply(
      lambda edges_list: [self.add_two_ways_edges(edge) for edge in edges_list])

  def get_s2cellids_for_poi(self, geometry: Any) -> Optional[Sequence[int]]:
    '''get cellids for POI.
    Arguments:
      geometry: The geometry to which a cellids will be retrived.
    Returns:
      The the cellids.
    '''
    ""
    if isinstance(geometry, Point):
      return util.s2cellids_from_point(geometry, self.level)
    else:
      return util.s2cellids_from_polygon(geometry, self.level)

  def calc_s2cells(self, level: int):
    '''Helper funcion for creating S2Graph.'''

    # Get cellids for POI.
    self.poi['s2cellids'] = self.poi['geometry'].apply(
      self.get_s2cellids_for_poi)

    # Filter out entities that we didn't mange to get cellids covering.
    self.poi = self.poi[self.poi['s2cellids'].notnull()]

  def get_valid_path(self, dir_name: Text, name_ending: Text,
             file_ending: Text) -> Optional[Text]:
    '''Creates the file path and checks validity.
    Arguments:
      dir_name: The directory of the path.
      name_ending: the end of the name  of the file
      (_graph or _node or_poi or_streets).
      file_ending: the type of the file.
    Returns:
      The valid path.
    '''

    base_filename = self.map_name.lower() + name_ending

    # Check if directory is valid.
    assert os.path.exists(dir_name), "Current directory is: {0}. The \
  directory {1} doesn't exist.".format(
      os.getcwd(), dir_name)

    # Create path.
    path = os.path.join(dir_name, base_filename + file_ending)

    return path

  def write_map(self, dir_name: Text):
    '''Save POI to disk.'''

    # Write POI.
    pd_poi = copy.deepcopy(self.poi)
    if 's2cellids' in pd_poi.columns:
      pd_poi['cellids'] = pd_poi['s2cellids'].apply(
        lambda x: util.cellids_from_s2cellids(x))
    pd_poi.drop(['s2cellids'], 1, inplace=True)

    path = self.get_valid_path(dir_name, '_poi', '.pkl')
    if not os.path.exists(path):
      pd_poi.to_pickle(path)
    else:
      logging.info(f"path {path} already exist.")

    # Write streets.
    pd_streets = copy.deepcopy(self.streets)

    path = self.get_valid_path(dir_name, '_streets', '.pkl')
    if not os.path.exists(path):
      pd_streets.to_pickle(path)
    else:
      logging.info(f"path {path} already exist.")

    # Write graph.
    base_filename = self.map_name.lower() + "_graph"
    path = os.path.join(dir_name, base_filename + ".gpickle")
    if not os.path.exists(path):
      nx.write_gpickle(self.nx_graph, path)
    else:
      logging.info(f"path {path} already exist.")

  def load_map(self, dir_name: Text):
    '''Load POI from disk.'''

    # Load POI.
    path = self.get_valid_path(dir_name, '_poi', '.pkl')
    self.poi = load_poi(path)

    # Load streets.
    path = self.get_valid_path(dir_name, '_streets', '.pkl')
    self.streets = load_poi(path)

    # Load graph.
    path = self.get_valid_path(dir_name, '_graph', '.gpickle')
    assert os.path.exists(
      path), f"path {path} doesn't exists"
    self.nx_graph = nx.read_gpickle(path)

def load_poi(path: Text):
    '''Load POI from disk.'''
    assert os.path.exists(
      path), f"Path {path} doesn't exist."
    poi_pandas = pd.read_pickle(path)
    if 'cellids' in poi_pandas:
      poi_pandas['s2cellids'] = poi_pandas['cellids'].apply(
        lambda x: util.s2cellids_from_cellids(x))
      poi_pandas.drop(['cellids'], 1, inplace=True)

    return poi_pandas

def convert_string_to_list(string_list: Text) -> Sequence:
  '''Splitting a string into integers and creates a new list of the integers.
  Arguments:
  string_list: A string in the form of a list. E.g "[1,2,3]".
  Returns:
  A list of integers.
  '''
  string_list = string_list.replace("[", "").replace("]", "")
  string_list = string_list.split(",")
  map_object = map(int, string_list)
  return list(map_object)


text:
package com.jcsanchez.hans.model;

import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;

import java.util.Map;

public class LexRequest {

    @SerializedName("currentIntent")
    @Expose
    private CurrentIntent currentIntent;

    @SerializedName("bot")
    @Expose
    private Bot bot;

    @SerializedName("userId")
    @Expose
    private String userId;

    @SerializedName("inputTranscript")
    @Expose
    private String inputTranscript;

    @SerializedName("invocationSource")
    @Expose
    private String invocationSource;

    @SerializedName("outputDialogMode")
    @Expose
    private String outputDialogMode;

    @SerializedName("messageVersion")
    @Expose
    private String messageVersion;

    @SerializedName("sessionAttributes")
    @Expose
    private Map<String, String> sessionAttributes;

    public CurrentIntent getCurrentIntent() {
        return currentIntent;
    }

    public void setCurrentIntent(CurrentIntent currentIntent) {
        this.currentIntent = currentIntent;
    }

    public Bot getBot() {
        return bot;
    }

    public void setBot(Bot bot) {
        this.bot = bot;
    }

    public String getUserId() {
        return userId;
    }

    public void setUserId(String userId) {
        this.userId = userId;
    }

    public String getInputTranscript() {
        return inputTranscript;
    }

    public void setInputTranscript(String inputTranscript) {
        this.inputTranscript = inputTranscript;
    }

    public String getInvocationSource() {
        return invocationSource;
    }

    public void setInvocationSource(String invocationSource) {
        this.invocationSource = invocationSource;
    }

    public String getOutputDialogMode() {
        return outputDialogMode;
    }

    public void setOutputDialogMode(String outputDialogMode) {
        this.outputDialogMode = outputDialogMode;
    }

    public String getMessageVersion() {
        return messageVersion;
    }

    public void setMessageVersion(String messageVersion) {
        this.messageVersion = messageVersion;
    }

    public Map<String, String> getSessionAttributes() {
        return sessionAttributes;
    }

    public void setSessionAttributes(Map<String, String> sessionAttributes) {
        this.sessionAttributes = sessionAttributes;
    }

}


text:
//*********************************************************
//
// Copyright (c) Microsoft. All rights reserved.
// This code is licensed under the MIT License (MIT).
// THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
// ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
// IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
// PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
//
//*********************************************************

//
// ShareFiles.xaml.cpp
// Implementation of the ShareFiles class
//

#include "pch.h"
#include "ShareFiles.xaml.h"
#include <sstream>

using namespace SDKTemplate;

using namespace Platform;
using namespace Windows::Foundation::Collections;
using namespace Windows::UI::Xaml;
using namespace Windows::Storage;
using namespace Windows::Storage::Pickers;
using namespace concurrency;
using namespace Windows::ApplicationModel::DataTransfer;

ShareFiles::ShareFiles()
{
    InitializeComponent();
}

bool ShareFiles::GetShareContent(DataRequest^ request)
{
    bool succeeded = false;

    if (storageItems != nullptr)
    {
        auto requestData = request->Data;
        requestData->Properties->Title = TitleInputBox->Text;

        // The description is optional.
        auto dataPackageDescription = DescriptionInputBox->Text;
        if (dataPackageDescription != nullptr)
        {
            requestData->Properties->Description = dataPackageDescription;
        }
        requestData->SetStorageItems(dynamic_cast<IIterable<IStorageItem^>^>(storageItems));
        succeeded = true;
    }
    else
    {
        request->FailWithDisplayText("Select the files you would like to share and try again.");
    }
    return succeeded;
}

void ShareFiles::SelectFilesButton_Click(Object^ sender, RoutedEventArgs^ e)
{
    auto filePicker = ref new FileOpenPicker();
    filePicker->ViewMode = PickerViewMode::List;
    filePicker->SuggestedStartLocation = PickerLocationId::DocumentsLibrary;
    filePicker->FileTypeFilter->Append("*");

    create_task(filePicker->PickMultipleFilesAsync()).then([this](IVectorView<StorageFile^>^ pickedFiles)
    {
        if (pickedFiles->Size > 0)
        {
            storageItems = pickedFiles;

            // Display the file names in the UI.
            std::wstringstream sstream;
            sstream << L"Picked files: ";
            for (unsigned int i = 0; i < pickedFiles->Size; i++)
            {
                sstream << pickedFiles->GetAt(i)->Name->Data();
                if (i < pickedFiles->Size - 1)
                {
                    sstream << L", ";
                }
            }
            sstream << L".";
            MainPage::Current->NotifyUser(ref new String(sstream.str().c_str()), NotifyType::StatusMessage);

            ShareStep->Visibility = Windows::UI::Xaml::Visibility::Visible;
        }
    });
}


text:
AngularJS with Material

HTML5 & CSS3

# Setup Guide

Nodejs is highly recommended

To Install project dependencies run following command in command line | terminal

npm install

Test in Browser Command

npm start


text:
import re

from supybot.commands import *
import supybot.plugins as plugins
import supybot.ircutils as ircutils
from supybot.i18n import PluginInternationalization, internationalizeDocstring
_ = PluginInternationalization('Praise')

class Praise(plugins.ChannelIdDatabasePlugin):
    """Praise is a plugin for ... well, praising things.  Feel free to add
    your own flavor to it by customizing what praises it gives.  Use "praise
    add <text>" to add new ones, making sure to include "$who" in <text> where
    you want to insert the thing being praised.
    """
    _meRe = re.compile(r'\bme\b', re.I)
    _myRe = re.compile(r'\bmy\b', re.I)
    def _replaceFirstPerson(self, s, nick):
        s = self._meRe.sub(nick, s)
        s = self._myRe.sub('%s\'s' % nick, s)
        return s

    def addValidator(self, irc, text):
        if '$who' not in text:
            irc.error(_('Praises must contain $who.'), Raise=True)

    @internationalizeDocstring
    def praise(self, irc, msg, args, channel, id, text):
        """[<channel>] [<id>] <who|what> [for <reason>]

        Praises <who|what> (for <reason>, if given).  If <id> is given, uses
        that specific praise.  <channel> is only necessary if the message isn't
        sent in the channel itself.
        """
        if ' for ' in text:
            (target, reason) = list(map(str.strip, text.split(' for ', 1)))
        else:
            (target, reason) = (text, '')
        if ircutils.strEqual(target, irc.nick):
            target = 'itself'
        if id is not None:
            try:
                praise = self.db.get(channel, id)
            except KeyError:
                irc.error(format(_('There is no praise with id #%i.'), id))
                return
        else:
            praise = self.db.random(channel)
            if not praise:
                irc.error(format(_('There are no praises in my database ' \
                                 'for %s.'), channel))
                return
        text = self._replaceFirstPerson(praise.text, msg.nick)
        reason = self._replaceFirstPerson(reason, msg.nick)
        target = self._replaceFirstPerson(target, msg.nick)
        text = text.replace('$who', target)
        if reason:
            text += _(' for ') + reason
        if self.registryValue('showIds', channel):
            text += format(' (#%i)', praise.id)
        irc.reply(text, action=True)
    praise = wrap(praise, ['channeldb', optional('id'), 'text'])
Praise = internationalizeDocstring(Praise)

Class = Praise

# vim:set shiftwidth=4 softtabstop=4 expandtab textwidth=79:


text:
Signs arbitrary files in mounted volume with provided GPG key and passphrase,
and stores the signature files in the same directory using the same uid:gid.

## Usage

Place any files you want signed in a dedicated directory, and mount that
directory as volume `/to-sign` in the container. Provide your GPG private key
via the environment variable `GPG_PRIVATE_KEY`, and the passphrase for using
the key as `GPG_PASSPHRASE`. These are both highly sensitive values, so be
sure to use appropriate secret management.

Example:

    $ docker run --rm -it -v $(pwd)/my-signable-files:/to-sign \
          -e GPG_PRIVATE_KEY -e GPG_PASSPHRASE \
          instructure/gpg-signer

If there are no files provided, the script will exit immediately. Any errors
importing the key or signing the provided files will immediately end the run.

Generated signature files will be named `<original-filename>.asc`.