text:
package org.apache.twill.internal.kafka.client;

import com.google.common.cache.CacheBuilder;
import com.google.common.cache.CacheLoader;
import com.google.common.cache.LoadingCache;
import com.google.common.cache.RemovalListener;
import com.google.common.cache.RemovalNotification;
import com.google.common.collect.AbstractIterator;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.Iterables;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.google.common.util.concurrent.Futures;

import kafka.api.FetchRequest;
import kafka.api.FetchRequestBuilder;
import kafka.api.PartitionOffsetRequestInfo;
import kafka.common.ErrorMapping;
import kafka.common.TopicAndPartition;
import kafka.javaapi.FetchResponse;
import kafka.javaapi.OffsetRequest;
import kafka.javaapi.OffsetResponse;
import kafka.javaapi.consumer.SimpleConsumer;
import kafka.javaapi.message.ByteBufferMessageSet;
import kafka.message.MessageAndOffset;

import org.apache.twill.common.Cancellable;
import org.apache.twill.common.Threads;
import org.apache.twill.kafka.client.BrokerInfo;
import org.apache.twill.kafka.client.BrokerService;
import org.apache.twill.kafka.client.FetchedMessage;
import org.apache.twill.kafka.client.KafkaConsumer;
import org.apache.twill.kafka.client.TopicPartition;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.net.ConnectException;
import java.nio.channels.ClosedByInterruptException;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ThreadFactory;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicLong;

/**
 * A {@link KafkaConsumer} implementation using the scala kafka api.
 */
final class SimpleKafkaConsumer implements KafkaConsumer {

  private static final Logger LOG = LoggerFactory.getLogger(SimpleKafkaConsumer.class);
  private static final int FETCH_SIZE = 1024 * 1024;        // Use a default fetch size.
  private static final int SO_TIMEOUT = 5 * 1000;           // 5 seconds.
  private static final int MAX_WAIT = 1000;                 // 1 second.
  private static final long CONSUMER_EXPIRE_MINUTES = 1L;   // close consumer if not used for 1 minute.
  private static final long CONSUMER_FAILURE_RETRY_INTERVAL = 2000L; // Sleep for 2 seconds if failure in consumer.
  private static final long EMPTY_FETCH_WAIT = 500L;        // Sleep for 500 ms if no message is fetched.

  private final BrokerService brokerService;
  private final LoadingCache<BrokerInfo, SimpleConsumer> consumers;
  private final BlockingQueue<Cancellable> consumerCancels;

  SimpleKafkaConsumer(BrokerService brokerService) {
    this.brokerService = brokerService;
    this.consumers = CacheBuilder.newBuilder()
                                 .expireAfterAccess(CONSUMER_EXPIRE_MINUTES, TimeUnit.MINUTES)
                                 .removalListener(createRemovalListener())
                                 .build(createConsumerLoader());
    this.consumerCancels = new LinkedBlockingQueue<Cancellable>();
  }

  @Override
  public Preparer prepare() {
    return new SimplePreparer();
  }

  /**
   * Called to stop all consumers created. This method should only be
   * called by KafkaClientService who own this consumer.
   */
  void stop() {
    LOG.info("Stopping Kafka consumer");
    List<Cancellable> cancels = Lists.newLinkedList();
    consumerCancels.drainTo(cancels);
    for (Cancellable cancel : cancels) {
      cancel.cancel();
    }
    consumers.invalidateAll();
    LOG.info("Kafka Consumer stopped");
  }

  /**
   * Creates a CacheLoader for creating SimpleConsumer.
   */
  private CacheLoader<BrokerInfo, SimpleConsumer> createConsumerLoader() {
    return new CacheLoader<BrokerInfo, SimpleConsumer>() {
      @Override
      public SimpleConsumer load(BrokerInfo key) throws Exception {
        return new SimpleConsumer(key.getHost(), key.getPort(), SO_TIMEOUT, FETCH_SIZE, "simple-kafka-client");
      }
    };
  }

  /**
   * Creates a RemovalListener that will close SimpleConsumer on cache removal.
   */
  private RemovalListener<BrokerInfo, SimpleConsumer> createRemovalListener() {
    return new RemovalListener<BrokerInfo, SimpleConsumer>() {
      @Override
      public void onRemoval(RemovalNotification<BrokerInfo, SimpleConsumer> notification) {
        SimpleConsumer consumer = notification.getValue();
        if (consumer != null) {
          consumer.close();
        }
      }
    };
  }

  /**
   * Retrieves the last offset before the given timestamp for a given topic partition.
   *
   * @return The last offset before the given timestamp or {@code 0} if failed to do so.
   */
  private long getLastOffset(TopicPartition topicPart, long timestamp) {
    BrokerInfo brokerInfo = brokerService.getLeader(topicPart.getTopic(), topicPart.getPartition());
    SimpleConsumer consumer = brokerInfo == null ? null : consumers.getUnchecked(brokerInfo);

    // If no broker, treat it as failure attempt.
    if (consumer == null) {
      LOG.warn("Failed to talk to any broker. Default offset to 0 for {}", topicPart);
      return 0L;
    }

    // Fire offset request
    OffsetRequest request = new OffsetRequest(ImmutableMap.of(
      new TopicAndPartition(topicPart.getTopic(), topicPart.getPartition()),
      new PartitionOffsetRequestInfo(timestamp, 1)
    ), kafka.api.OffsetRequest.CurrentVersion(), consumer.clientId());

    OffsetResponse response = consumer.getOffsetsBefore(request);

    // Retrieve offsets from response
    long[] offsets = response.hasError() ? null : response.offsets(topicPart.getTopic(), topicPart.getPartition());
    if (offsets == null || offsets.length <= 0) {
      short errorCode = response.errorCode(topicPart.getTopic(), topicPart.getPartition());

      // If the topic partition doesn't exists, use offset 0 without logging error.
      if (errorCode != ErrorMapping.UnknownTopicOrPartitionCode()) {
        consumers.refresh(brokerInfo);
        LOG.warn("Failed to fetch offset for {} with timestamp {}. Error: {}. Default offset to 0.",
                 topicPart, timestamp, errorCode);
      }
      return 0L;
    }

    LOG.debug("Offset {} fetched for {} with timestamp {}.", offsets[0], topicPart, timestamp);
    return offsets[0];
  }

  /**
   * A preparer that uses kafak scala api for consuming messages.
   */
  private final class SimplePreparer implements Preparer {

    // Map from TopicPartition to offset
    private final Map<TopicPartition, Long> requests;
    private final ThreadFactory threadFactory;

    private SimplePreparer() {
      this.requests = Maps.newHashMap();
      this.threadFactory = Threads.createDaemonThreadFactory("message-callback-%d");
    }

    @Override
    public Preparer add(String topic, int partition, long offset) {
      requests.put(new TopicPartition(topic, partition), offset);
      return this;
    }

    @Override
    public Preparer addFromBeginning(String topic, int partition) {
      TopicPartition topicPartition = new TopicPartition(topic, partition);
      requests.put(topicPartition, kafka.api.OffsetRequest.EarliestTime());
      return this;
    }

    @Override
    public Preparer addLatest(String topic, int partition) {
      TopicPartition topicPartition = new TopicPartition(topic, partition);
      requests.put(topicPartition, kafka.api.OffsetRequest.LatestTime());
      return this;
    }

    @Override
    public Cancellable consume(MessageCallback callback) {
      final ExecutorService executor = Executors.newSingleThreadExecutor(threadFactory);
      final List<ConsumerThread> pollers = Lists.newArrayList();

      // When cancelling the consumption, first terminates all polling threads and then stop the executor service.
      final AtomicBoolean cancelled = new AtomicBoolean();
      Cancellable cancellable = new Cancellable() {
        @Override
        public void cancel() {
          if (!cancelled.compareAndSet(false, true)) {
            return;
          }
          consumerCancels.remove(this);

          LOG.info("Requesting stop of all consumer threads.");
          for (ConsumerThread consumerThread : pollers) {
            consumerThread.terminate();
          }
          LOG.info("Wait for all consumer threads to stop.");
          for (ConsumerThread consumerThread : pollers) {
            try {
              consumerThread.join();
            } catch (InterruptedException e) {
              LOG.warn("Interrupted exception while waiting for thread to complete.", e);
            }
          }
          LOG.info("All consumer threads stopped.");
          // Use shutdown so that submitted task still has chance to execute, which is important for finished to get
          // called.
          executor.shutdown();
        }
      };

      // Wrap the callback with a single thread executor.
      MessageCallback messageCallback = wrapCallback(callback, executor, cancellable);

      // Starts threads for polling new messages.
      for (Map.Entry<TopicPartition, Long> entry : requests.entrySet()) {
        ConsumerThread consumerThread = new ConsumerThread(entry.getKey(), entry.getValue(), messageCallback);
        consumerThread.setDaemon(true);
        consumerThread.start();
        pollers.add(consumerThread);
      }

      consumerCancels.add(cancellable);
      return cancellable;
    }

    /**
     * Wrap a given MessageCallback by a executor so that calls are executed in the given executor.
     * By running the calls through the executor, it also block and wait for the task being completed so that
     * it can block the poller thread depending on the rate of processing that the callback can handle.
     */
    private MessageCallback wrapCallback(final MessageCallback callback,
                                         final ExecutorService executor, final Cancellable cancellable) {
      final AtomicBoolean stopped = new AtomicBoolean();
      return new MessageCallback() {
        @Override
        public void onReceived(final Iterator<FetchedMessage> messages) {
          if (stopped.get()) {
            return;
          }
          Futures.getUnchecked(executor.submit(new Runnable() {
            @Override
            public void run() {
              if (stopped.get()) {
                return;
              }
              callback.onReceived(messages);
            }
          }));
        }

        @Override
        public void finished() {
          // Make sure finished only get called once.
          if (!stopped.compareAndSet(false, true)) {
            return;
          }
          Futures.getUnchecked(executor.submit(new Runnable() {
            @Override
            public void run() {
              // When finished is called, also cancel the consumption from all polling thread.
              callback.finished();
              cancellable.cancel();
            }
          }));
        }
      };
    }
  }

  /**
   * The thread for polling kafka.
   */
  private final class ConsumerThread extends Thread {

    private final TopicPartition topicPart;
    private final long startOffset;
    private final MessageCallback callback;
    private final BasicFetchedMessage fetchedMessage;
    private volatile boolean running;

    private ConsumerThread(TopicPartition topicPart, long startOffset, MessageCallback callback) {
      super(String.format("Kafka-Consumer-%s-%d", topicPart.getTopic(), topicPart.getPartition()));
      this.topicPart = topicPart;
      this.startOffset = startOffset;
      this.callback = callback;
      this.running = true;
      this.fetchedMessage = new BasicFetchedMessage(topicPart);
    }

    @Override
    public void run() {
      final AtomicLong offset = new AtomicLong(startOffset);

      Map.Entry<BrokerInfo, SimpleConsumer> consumerEntry = null;

      while (running) {
        if (consumerEntry == null && (consumerEntry = getConsumerEntry()) == null) {
          LOG.debug("No leader for topic partition {}.", topicPart);
          try {
            TimeUnit.MILLISECONDS.sleep(CONSUMER_FAILURE_RETRY_INTERVAL);
          } catch (InterruptedException e) {
            // OK to ignore this, as interrupt would be caused by thread termination.
            LOG.trace("Consumer sleep interrupted.", e);
          }
          continue;
        }

        // If offset < 0, meaning it's special offset value that needs to fetch either the earliest or latest offset
        // from kafak server.
        long off = offset.get();
        if (off < 0) {
          offset.set(getLastOffset(topicPart, off));
        }

        SimpleConsumer consumer = consumerEntry.getValue();

        // Fire a fetch message request
        try {
          FetchResponse response = fetchMessages(consumer, offset.get());

          // Failure response, set consumer entry to null and let next round of loop to handle it.
          if (response.hasError()) {
            short errorCode = response.errorCode(topicPart.getTopic(), topicPart.getPartition());
            LOG.info("Failed to fetch message on {}. Error: {}", topicPart, errorCode);
            // If it is out of range error, reset to earliest offset
            if (errorCode == ErrorMapping.OffsetOutOfRangeCode()) {
              offset.set(kafka.api.OffsetRequest.EarliestTime());
            }

            consumers.refresh(consumerEntry.getKey());
            consumerEntry = null;
            continue;
          }

          ByteBufferMessageSet messages = response.messageSet(topicPart.getTopic(), topicPart.getPartition());
          if (sleepIfEmpty(messages)) {
            continue;
          }

          // Call the callback
          invokeCallback(messages, offset);
        } catch (Throwable t) {
          // Only log if it is still running, otherwise, it just the interrupt caused by the stop.
          if (!running) {
            LOG.debug("Unable to fetch messages on {}, kafka consumer service shutdown is in progress.", topicPart);
          } else if (running && (t instanceof ClosedByInterruptException || t instanceof ConnectException)) {
            LOG.debug("Unable to fetch messages on {}, kafka server shutdown is in progress.", topicPart);
          } else {
            LOG.info("Exception when fetching message on {}.", topicPart, t);
          }
          consumers.refresh(consumerEntry.getKey());
          consumerEntry = null;
        }
      }

      // When the thread is done, call the callback finished method.
      try {
        callback.finished();
      } catch (Throwable t) {
        LOG.error("Exception thrown from MessageCallback.finished({})", running, t);
      }
    }

    public void terminate() {
      LOG.info("Terminate requested {}", getName());
      running = false;
      interrupt();
    }

    /**
     * Gets the leader broker and the associated SimpleConsumer for the current topic and partition.
     */
    private Map.Entry<BrokerInfo, SimpleConsumer> getConsumerEntry() {
      BrokerInfo leader = brokerService.getLeader(topicPart.getTopic(), topicPart.getPartition());
      return leader == null ? null : Maps.immutableEntry(leader, consumers.getUnchecked(leader));
    }

    /**
     * Makes a call to kafka to fetch messages.
     */
    private FetchResponse fetchMessages(SimpleConsumer consumer, long offset) {
      FetchRequest request = new FetchRequestBuilder()
        .clientId(consumer.clientId())
        .addFetch(topicPart.getTopic(), topicPart.getPartition(), offset, FETCH_SIZE)
        .maxWait(MAX_WAIT)
        .build();
      return consumer.fetch(request);
    }

    /**
     * Sleeps if the message set is empty.
     * @return {@code true} if it is empty, {@code false} otherwise.
     */
    private boolean sleepIfEmpty(ByteBufferMessageSet messages) {
      if (Iterables.isEmpty(messages)) {
        LOG.trace("No message fetched. Sleep for {} ms before next fetch.", EMPTY_FETCH_WAIT);
        try {
          TimeUnit.MILLISECONDS.sleep(EMPTY_FETCH_WAIT);
        } catch (InterruptedException e) {
          // It's interrupted from stop, ok to ignore.
        }
        return true;
      }
      return false;
    }

    /**
     * Calls the message callback with the given message set.
     */
    private void invokeCallback(ByteBufferMessageSet messages, AtomicLong offset) {
      long savedOffset = offset.get();
      try {
        callback.onReceived(createFetchedMessages(messages, offset));
      } catch (Throwable t) {
        LOG.error("Callback throws exception. Retry from offset {} for {}", startOffset, topicPart, t);
        offset.set(savedOffset);
      }
    }

    /**
     * Creates an Iterator of FetchedMessage based on the given message set. The iterator would also updates
     * the offset while iterating.
     */
    private Iterator<FetchedMessage> createFetchedMessages(ByteBufferMessageSet messageSet, final AtomicLong offset) {
      final Iterator<MessageAndOffset> messages = messageSet.iterator();
      return new AbstractIterator<FetchedMessage>() {
        @Override
        protected FetchedMessage computeNext() {
          while (messages.hasNext()) {
            MessageAndOffset message = messages.next();
            long msgOffset = message.offset();
            if (msgOffset < offset.get()) {
              LOG.trace("Received old offset {}, expecting {} on {}. Message Ignored.",
                        msgOffset, offset.get(), topicPart);
              continue;
            }

            offset.set(message.nextOffset());
            fetchedMessage.setPayload(message.message().payload());
            fetchedMessage.setNextOffset(offset.get());

            return fetchedMessage;
          }
          return endOfData();
        }
      };
    }
  }
}


text:
module Scope
  def self.included(base)
    base.class_eval do
      scope :in_scope, ->(scope) {
        if scope == :current
          where(is_current: true)
        elsif scope == :historic
          where(is_current: false)
        else
          where(nil)
        end
      }
    end
  end
end

redpajama_set_name: RedPajamaGithub


text:
package iptc.newsml.g2.model;

import javax.validation.constraints.NotNull;
import javax.xml.bind.annotation.XmlAttribute;

/**
 * Headline Model Object
 *
 * @see <a
 *      href="http://www.iptc.org/std/NewsML-G2/2.19/specification/XML-Schema-Doc-Power/Headline.html">Headline</a>
 */

public class Headline extends Label1
{
    private static final long serialVersionUID = 1L;

    @NotNull
    private Integer rank;

    private String value;

    public Headline()
    {
    }

    @XmlAttribute()
    public Integer getRank()
    {
        return rank;
    }

    public void setRank(Integer rank)
    {
        this.rank = rank;

    }

    // FIXME blocked by: @XmlValue is not allowed on a class that derives
    // another class.
    // @XmlValue()
    public String getValue()
    {
        return value;
    }

    public void setValue(String value)
    {
        this.value = value;
    }

}


text:
<?php

require_once dirname(__FILE__).'/../bootstrap.php';

class Twig_Tests_Extension_SandboxTest extends PHPUnit_Framework_TestCase
{
    static protected $params, $templates;

    public function setUp()
    {
        self::$params = array(
            'name' => 'Fabien',
            'obj'  => new Object(),
        );

        self::$templates = array(
            '1_basic1' => '{{ obj.foo }}',
            '1_basic2' => '{{ name|upper }}',
            '1_basic3' => '{% if name %}foo{% endif %}',
            '1_basic4' => '{{ obj.bar }}',
            '1_basic'  => '{% if obj.foo %}{{ obj.foo|upper }}{% endif %}',
        );
    }

    public function testSandboxGloballySet()
    {
        $twig = $this->getEnvironment(false, self::$templates);
        $this->assertEquals('FOO', $twig->loadTemplate('1_basic')->render(self::$params), 'Sandbox does nothing if it is disabled globally');

        $twig = $this->getEnvironment(true, self::$templates);
        try {
            $twig->loadTemplate('1_basic1')->render(self::$params);
            $this->fail('Sandbox throws a SecurityError exception if an unallowed method is called');
        } catch (Twig_Sandbox_SecurityError $e) {
        }

        $twig = $this->getEnvironment(true, self::$templates);
        try {
            $twig->loadTemplate('1_basic2')->render(self::$params);
            $this->fail('Sandbox throws a SecurityError exception if an unallowed filter is called');
        } catch (Twig_Sandbox_SecurityError $e) {
        }

        $twig = $this->getEnvironment(true, self::$templates);
        try {
            $twig->loadTemplate('1_basic3')->render(self::$params);
            $this->fail('Sandbox throws a SecurityError exception if an unallowed tag is used in the template');
        } catch (Twig_Sandbox_SecurityError $e) {
        }

        $twig = $this->getEnvironment(true, self::$templates);
        try {
            $twig->loadTemplate('1_basic4')->render(self::$params);
            $this->fail('Sandbox throws a SecurityError exception if an unallowed property is called in the template');
        } catch (Twig_Sandbox_SecurityError $e) {
        }

        $twig = $this->getEnvironment(true, self::$templates, array(), array(), array('Object' => 'foo'));
        $this->assertEquals('foo', $twig->loadTemplate('1_basic1')->render(self::$params), 'Sandbox allow some methods');

        $twig = $this->getEnvironment(true, self::$templates, array(), array('upper'));
        $this->assertEquals('FABIEN', $twig->loadTemplate('1_basic2')->render(self::$params), 'Sandbox allow some filters');

        $twig = $this->getEnvironment(true, self::$templates, array('if'));
        $this->assertEquals('foo', $twig->loadTemplate('1_basic3')->render(self::$params), 'Sandbox allow some tags');

        $twig = $this->getEnvironment(true, self::$templates, array(), array(), array(), array('Object' => 'bar'));
        $this->assertEquals('bar', $twig->loadTemplate('1_basic4')->render(self::$params), 'Sandbox allow some properties');
    }

    public function testSandboxLocallySetForAnInclude()
    {
        self::$templates = array(
            '2_basic'    => '{{ obj.foo }}{% include "2_included" %}{{ obj.foo }}',
            '2_included' => '{% if obj.foo %}{{ obj.foo|upper }}{% endif %}',
        );

        $twig = $this->getEnvironment(false, self::$templates);
        $this->assertEquals('fooFOOfoo', $twig->loadTemplate('2_basic')->render(self::$params), 'Sandbox does nothing if disabled globally and sandboxed not used for the include');

        self::$templates = array(
            '3_basic'    => '{{ obj.foo }}{% include "3_included" sandboxed %}{{ obj.foo }}',
            '3_included' => '{% if obj.foo %}{{ obj.foo|upper }}{% endif %}',
        );

        $twig = $this->getEnvironment(false, self::$templates);
        $twig = $this->getEnvironment(true, self::$templates);
        try {
            $twig->loadTemplate('3_basic')->render(self::$params);
            $this->fail('Sandbox throws a SecurityError exception when the included file is sandboxed');
        } catch (Twig_Sandbox_SecurityError $e) {
        }
    }

    protected function getEnvironment($sandboxed, $templates, $tags = array(), $filters = array(), $methods = array(), $properties = array())
    {
        $loader = new Twig_Loader_Array($templates);
        $twig = new Twig_Environment($loader, array('trim_blocks' => true, 'debug' => true));
        $policy = new Twig_Sandbox_SecurityPolicy($tags, $filters, $methods, $properties);
        $twig->addExtension(new Twig_Extension_Sandbox($policy, $sandboxed));

        return $twig;
    }
}

class Object
{
    public $bar = 'bar';

    public function foo()
    {
        return 'foo';
    }
}


text:
<?PHP

require_once"include/init.php";

if(CommonFunc::isPost())
{
    $oDonation = new modDonations(MySql::Instance());

    $dataset = array();
    if(isset($_POST['export_all_csv']) && $_POST['export_all_csv'] != '')
    {
        $dataset = $oDonation->CSVDataset();
    }
    else if(isset($_POST['export_selected']) && $_POST['export_selected'] != '')
    {
        if(count($_POST['donation_ids']) == 0)
        {
            CommonFunc::SetFlashMessage('error',"Please select at least one record to export.");
            header("Location: donations.php?".$_POST['qstr']."");
        }
        $dataset = $oDonation->CSVDataset($_POST['donation_ids']);
    }
    else if(isset($_POST['export_all_visible']) && $_POST['export_all_visible'] != '')
    {
        if(count($_POST['donation_ids']) == 0)
        {
            CommonFunc::SetFlashMessage('error',"No visible records to export.");
            header("Location: donations.php?".$_POST['qstr']."");
        }

        $dataset = $oDonation->CSVDataset($_POST['visible_donation_ids']);
    }

    $csv = new clsCSV(",","\n");
    $csv->Export($dataset,"donations-".CommonFunc::CurrentDateFileName().".csv");

}
else
{
    echo"Invalid request!";
}
?>


text:
TorBar
======

Menu bar Tor relay server app for OSX.

To do
--------

Network Detection: Detect wifi/network changes and only run tor on networks where user has manually turned on tor. If the user turns off tor on a network, also remember this as a preference for that network.

Autolaunch: have app autolaunch on startup or option to do so?

Bandwidth: add code to grab bandwidth usage info from logs or another means and display in menu bar?


text:
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Windows.Data;
using System.Windows.Input;

namespace GoldenAnvil.Utility.Windows
{
	public sealed class RoutedCommandToCommandBindingConverter : IMultiValueConverter
	{
		public static readonly RoutedCommandToCommandBindingConverter Instance = new RoutedCommandToCommandBindingConverter();

		public object Convert(object[] values, Type targetType, object parameter, CultureInfo culture)
		{
			List<CommandBinding> commandBindings = new List<CommandBinding>();
			for (var index = 0; index < values.Length; index++)
			{
				var routedCommand = values[index] as RoutedCommand;
				index++;
				if (index != values.Length)
				{
					var command = values[index] as ICommand;
					if (routedCommand != null && command != null)
					{
						commandBindings.Add(new CommandBinding(
							routedCommand,
							(sender, args) => command.Execute(args.Parameter),
							(sender, args) => args.CanExecute = command.CanExecute(args.Parameter)));
					}
				}
			}

			return commandBindings;
		}

		public object[] ConvertBack(object value, Type[] targetTypes, object parameter, CultureInfo culture)
		{
			throw new NotImplementedException();
		}
	}
}


text:
    <?php echo $leftview;?>

                Cancelled Orders

                        <a href="<?php echo base_url()?>admin/dashboard">Home

                        <a href="<?php echo base_url()?>admin/order">Order

                            Cancelled orders

                                    No

                                    Date

                                    Accepted Date

                                    Client name

                                    Service man

                            <?php for($i = 0 ; $i < count($cancelled); $i++):?>

                                    <?php echo $i+1;?>
                                    <?php echo $cancelled[$i]['created_at'];?>
                                    <?php echo $cancelled[$i]['updated_at'];?>
                                    <?php echo $cancelled[$i]['client']['0']['user_name'];?>  (<?php echo $cancelled[$i]['client']['0']['user_phone'];?>)
                                    <?php echo $cancelled[$i]['service']['0']['user_name'];?>  (<?php echo $cancelled[$i]['service']['0']['user_phone'];?>)
                                    <a href="<?php echo base_url();?>admin/order/view/<?php echo $cancelled[$i]['id']?>" class="btn btn-small green-jungle"> View position

                            <?php endfor;?>

        2016 © SAHULAT company All rights recancelled.


text:
<?php
/**
 * The template used for displaying posts.
 * @package WordPress
 * @subpackage Kevin Lesht
 */

?>

<article id="post-<?php the_ID(); ?>" class="module" role="article">

<a href="<?php the_permalink() ?>" title="<?php the_title(); ?>"><?php the_title(); ?>

Published <?php the_date(); ?>, by <?php the_author(); ?>

	<?php the_excerpt(); ?>

	<a href="<?php the_permalink() ?>" class="button button--small button--fixed-right">Continue Reading


text:
FROM node:14.16.1-slim

COPY ./ ./

RUN npm install
RUN npm run build

ENV NODE_ENV production
ENV DATABASE_CONFIGURATION_PROFILE postgres
ENV FRAMEWORK fastify

EXPOSE 8080
CMD ["node", "dist/main"]


text:
package domain_intl

//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.
//
// Code generated by Alibaba Cloud SDK Code Generator.
// Changes may cause incorrect behavior and will be lost if the code is regenerated.

// RegistrantProfile is a nested struct in domain_intl response
type RegistrantProfile struct {
	RegistrantProfileId      int    `json:"RegistrantProfileId" xml:"RegistrantProfileId"`
	CreateTime               string `json:"CreateTime" xml:"CreateTime"`
	UpdateTime               string `json:"UpdateTime" xml:"UpdateTime"`
	DefaultRegistrantProfile bool   `json:"DefaultRegistrantProfile" xml:"DefaultRegistrantProfile"`
	RegistrantName           string `json:"RegistrantName" xml:"RegistrantName"`
	RegistrantOrganization   string `json:"RegistrantOrganization" xml:"RegistrantOrganization"`
	Country                  string `json:"Country" xml:"Country"`
	Province                 string `json:"Province" xml:"Province"`
	City                     string `json:"City" xml:"City"`
	Address                  string `json:"Address" xml:"Address"`
	Email                    string `json:"Email" xml:"Email"`
	PostalCode               string `json:"PostalCode" xml:"PostalCode"`
	TelArea                  string `json:"TelArea" xml:"TelArea"`
	Telephone                string `json:"Telephone" xml:"Telephone"`
	TelExt                   string `json:"TelExt" xml:"TelExt"`
	EmailVerificationStatus  int    `json:"EmailVerificationStatus" xml:"EmailVerificationStatus"`
	RegistrantType           string `json:"RegistrantType" xml:"RegistrantType"`
	RealNameStatus           string `json:"RealNameStatus" xml:"RealNameStatus"`
	RegistrantProfileType    string `json:"RegistrantProfileType" xml:"RegistrantProfileType"`
}


text:
package com.qingbo.ginkgo.ygb.web.controller.admin;

import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang3.time.DateUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alibaba.fastjson.JSONObject;
import com.qingbo.ginkgo.ygb.base.enums.UploadImageType;
import com.qingbo.ginkgo.ygb.base.service.CodeListService;
import com.qingbo.ginkgo.ygb.base.service.TongjiService;
import com.qingbo.ginkgo.ygb.base.service.UploadImageService;
import com.qingbo.ginkgo.ygb.common.result.Result;
import com.qingbo.ginkgo.ygb.common.util.DateUtil;
import com.qingbo.ginkgo.ygb.common.util.MailUtil;
import com.qingbo.ginkgo.ygb.common.util.Pager;
import com.qingbo.ginkgo.ygb.common.util.PropertiesUtil;
import com.qingbo.ginkgo.ygb.common.util.RequestUtil;
import com.qingbo.ginkgo.ygb.common.util.SimpleLogFormater;
import com.qingbo.ginkgo.ygb.common.util.StringUtil;
import com.qingbo.ginkgo.ygb.common.util.UploadUtil;
import com.qingbo.ginkgo.ygb.customer.entity.User;
import com.qingbo.ginkgo.ygb.customer.enums.CustomerConstants;
import com.qingbo.ginkgo.ygb.customer.enums.CustomerConstants.Role;
import com.qingbo.ginkgo.ygb.customer.service.CustomerService;
import com.qingbo.ginkgo.ygb.customer.shiro.RequiresAdminUser;
import com.qingbo.ginkgo.ygb.customer.shiro.ShiroTool;
import com.qingbo.ginkgo.ygb.project.entity.CommissionDetail;
import com.qingbo.ginkgo.ygb.project.entity.CommissionTemplate;
import com.qingbo.ginkgo.ygb.project.entity.Guarantee;
import com.qingbo.ginkgo.ygb.project.entity.Investment;
import com.qingbo.ginkgo.ygb.project.entity.LoaneeInfo;
import com.qingbo.ginkgo.ygb.project.entity.Project;
import com.qingbo.ginkgo.ygb.project.entity.ProjectReview;
import com.qingbo.ginkgo.ygb.project.entity.Repayment;
import com.qingbo.ginkgo.ygb.project.enums.ProjectConstants;
import com.qingbo.ginkgo.ygb.project.enums.ProjectConstants.ProjectStatus;
import com.qingbo.ginkgo.ygb.project.service.CommissionTemplateService;
import com.qingbo.ginkgo.ygb.project.util.PeriodCounter;
import com.qingbo.ginkgo.ygb.web.biz.GuaranteeBizService;
import com.qingbo.ginkgo.ygb.web.biz.InvestmentBizService;
import com.qingbo.ginkgo.ygb.web.biz.ProjectBizService;
import com.qingbo.ginkgo.ygb.web.biz.ProjectReviewBizService;
import com.qingbo.ginkgo.ygb.web.biz.RepaymentBizService;
import com.qingbo.ginkgo.ygb.web.pojo.ProjectDetail;
import com.qingbo.ginkgo.ygb.web.pojo.VariableConstants;
import com.qingbo.ginkgo.ygb.web.util.AssistInfoUtil;
import com.qingbo.ginkgo.ygb.web.util.VelocityUtil;

@RequiresAdminUser
@Controller
@RequestMapping("admin/product")
public class ProductController {
	private final Logger logger = LoggerFactory.getLogger(this.getClass());

	@Autowired private UploadImageService uploadImageService;
	@Autowired private CustomerService customerService;
	@Autowired private CodeListService codeListService;
	@Autowired private CommissionTemplateService commissionTemplateService;
	@Autowired private TongjiService tongjiService;

	@Autowired private ProjectBizService projectBizService;
	@Resource private GuaranteeBizService guaranteeBizService;
	@Resource private AssistInfoUtil assistInfoUtil;
	@Resource private  InvestmentBizService investmentBizService;
	@Resource private  RepaymentBizService repaymentBizService;
	@Resource private ProjectReviewBizService projectReviewBizService;

	private final String PAGE_PATH = "admin/product/";
	private int pageSize = 10;

	/**
	 * 发布新产品
	 */
	@RequestMapping(value="productAdd", method=RequestMethod.GET)
	public String productAdd(HttpServletRequest request, Model model) {
		assistInfoUtil.init(model);
		return PAGE_PATH + "productAdd";
	}

	/**
	 * 发布新产品保存
	 * @param project
	 * @param guarantee
	 */
	@RequestMapping(value="productSave", method=RequestMethod.POST)
	public String productSave(Project project,LoaneeInfo loanee, Guarantee guarantee, HttpServletRequest request, Model model) {

		try{
			//解析借款人信息
			Result<User> borrowerResult = customerService.getUserByUserName(project.getLoaneeUserName());
			if(borrowerResult.success()) {
				User borrower = borrowerResult.getObject();
				project.setLoaneeId(borrower.getId());
			}
		}catch(Exception e){
			logger.error("发布产品失败,借款人信息解析出错," + e.getMessage());
			model.addAttribute("OK", "N");
			return PAGE_PATH + "productAdd";
		}

		//获取担保机构ID
		project.setGuaranteeUserId(guarantee.getUserId());

		try{
			//解析借款周期
			String investmentPeriod = "1";
			//借款期限1.固定期限 2.定制天数3.定制月份
			if ((VariableConstants.InvestmentPeriodType.FIX_PERIOD).equals(project.getPeriodType())) {
				investmentPeriod = RequestUtil.getStringParam(request, "periodTypeFIX_PERIOD", investmentPeriod);
			} else if ((VariableConstants.InvestmentPeriodType.DAYS).equals(project.getPeriodType())) {
				investmentPeriod = RequestUtil.getStringParam(request, "periodTypeDAYS", investmentPeriod);
			} else if ((VariableConstants.InvestmentPeriodType.MONTHS).equals(project.getPeriodType())) {
				investmentPeriod = RequestUtil.getStringParam(request, "periodTypeMONTHS", investmentPeriod);
			}
			project.setPeriod(investmentPeriod);
			//借款天数
			project.setPeriodDays(PeriodCounter.getDays(project.getPeriodType(), Integer.valueOf(project.getPeriod())));
		}catch(Exception e){
			logger.error("发布产品失败,借款周期解析出错," + e.getMessage());
			model.addAttribute("OK", "N");
			return PAGE_PATH + "productAdd";
		}

		try{
			//解析满标金额
			if(project.getSettleTerms().equalsIgnoreCase("FULL")){
				project.setSettleTermsAmount(project.getTotalAmount());
			}else if(project.getSettleTerms().equalsIgnoreCase("FIX_AMOUNT")){
				project.setSettleTermsAmount(BigDecimal.valueOf(RequestUtil.getDoubleParam(request,"settleTermsValueFIX_AMOUNT", 0.0)));
			}else if(project.getSettleTerms().equalsIgnoreCase("FIX_PERCENTAGE")){
				project.setSettleTermsAmount(project.getTotalAmount().multiply(BigDecimal.valueOf(0.01)).multiply(BigDecimal.valueOf(RequestUtil.getDoubleParam(request,"settleTermsValueFIX_PERCENTAGE", 0.0))));
			}
		}catch(Exception e){
			logger.error("发布产品失败,满标金额解析出错," + e.getMessage());
			model.addAttribute("OK", "N");
			return PAGE_PATH + "productAdd";
		}

		try{
			//处理投资收益年利率
			Result<CommissionTemplate> repayCommResult = commissionTemplateService.getCommissionTemplate(project.getRepayTemplateId());
			logger.info(SimpleLogFormater.formatResult(repayCommResult));
			if(!repayCommResult.success()){
				model.addAttribute("OK", "N");
				return PAGE_PATH + "productAdd";
			}
			CommissionTemplate repay = repayCommResult.getObject();
			BigDecimal rate = BigDecimal.ZERO;
			for(CommissionDetail detail:repay.getDetails()){
				if(CustomerConstants.Role.INVESTOR.getCode().equalsIgnoreCase(detail.getRole())){
					rate = detail.getRate();
				}
			}
			project.setInterestRate(rate);
		}catch(Exception e){
		}

		try{
			//最低投资额的其他投资额 未选择指定投资额
			if(project.getMinimalInvestment().compareTo(BigDecimal.ZERO)<1){
				Boolean minimumInvestmentAmountOther = RequestUtil.getBoolParam(request,"minimumInvestmentAmountOther", false);
				double minimumInvestmentAmountValue = 0;
				if (minimumInvestmentAmountOther) {
					minimumInvestmentAmountValue = RequestUtil.getDoubleParam(request,"minimumInvestmentAmountValue", minimumInvestmentAmountValue);
					project.setMinimalInvestment(BigDecimal.valueOf(minimumInvestmentAmountValue));
				}
			}

			//处理万元转换为元格式
			//处理融资总额
			project.setTotalAmount(project.getTotalAmount().multiply(BigDecimal.valueOf(10000)));
			//处理最低投资额
			project.setMinimalInvestment(project.getMinimalInvestment().multiply(BigDecimal.valueOf(10000)));
			//处理满标金额
			project.setSettleTermsAmount(project.getSettleTermsAmount().multiply(BigDecimal.valueOf(10000)));
		}catch(Exception e){
			logger.error("发布产品失败,最低投资额等解析出错," + e.getMessage());
			model.addAttribute("OK", "N");
			return PAGE_PATH + "productAdd";
		}

		try{
			//处理投资起止时间
			project.setInvestStartDate(DateUtil.parse(RequestUtil.getStringParam(request, "startDate", null)));
			project.setInvestEndDate(DateUtil.parse(RequestUtil.getStringParam(request, "endDate", null)));
		}catch(Exception e){
			logger.error("发布产品失败,投资起止时间处理出错," + e.getMessage());
			model.addAttribute("OK", "N");
			return PAGE_PATH + "productAdd";
		}

		try{
			//处理保荐人信息
			if(project.getSponsorUserName()!=null && !project.getSponsorUserName().equals("")) {
				Result<User> sponsorResult = customerService.getUserByUserName(project.getSponsorUserName());
				if(sponsorResult.success()) {
					User sponsor = sponsorResult.getObject();
					project.setSponsorUserId(sponsor.getId());
				}
			}
		}catch(Exception e){
			logger.error("发布产品失败,保荐人信息处理出错," + e.getMessage());
			model.addAttribute("OK", "N");
			return PAGE_PATH + "productAdd";
		}
		boolean uploadProjectImages = false;

		try{
			//项目操作日志
			ProjectReview pr = new ProjectReview();
			pr.setProjectId(0L);
			try{
				pr.setReviewerId(ShiroTool.userId()==null?0L:ShiroTool.userId());
				Result<User> actor = customerService.getUserByUserId(ShiroTool.userId());
				logger.info("ProductSave:"+SimpleLogFormater.formatResult(actor));
				if(actor.success()){
					pr.setReviewerUserName(actor.getObject().getUserName());
					pr.setReviewerName(actor.getObject().getUserProfile().getRealName());
				}
			}catch(Exception e){
				logger.error("ProductSave:CustomerService.getUserByUserId failed:by" + e.getMessage());
			}
			pr.setReviewCode("ADD Project");
			pr.setReviewName("产品发布");
			pr.setResult("");
			pr.setReason("");

			String loginId = String.valueOf(ShiroTool.userId());

			//创建项目
			try{
				Result<Project> projectResult = projectBizService.createProject(loginId, project, guarantee);
				logger.info("Create Project Result:"+SimpleLogFormater.formatResult(projectResult));
				if(projectResult.success()){
					uploadProjectImages = true;
					pr.setProjectId(projectResult.getObject().getId());
					loanee.setProjectId(projectResult.getObject().getId());
					pr.setResult("成功");
				}else{
					pr.setResult("失败");
				}
			}catch(Exception e){
				logger.error("ProjectBizService.createProject failed:by" + e.getMessage());
			}

			try{
				Result<ProjectReview> upReview = projectReviewBizService.create(loginId, pr);
				logger.info(SimpleLogFormater.formatResult(upReview));
			}catch(Exception e){
				logger.error("ProjectReviewBizService.create failed:by" + e.getMessage());
			}

			try{
				Result<LoaneeInfo> save = projectBizService.createLoaneeInfo(loanee, loginId);
				logger.info("ProductController Create LoaneeInfo Result:"+SimpleLogFormater.formatResult(save));
			}catch(Exception e){
				logger.error("ProductController Create LoaneeInfo failed:by" + e.getMessage());
			}

			if(uploadProjectImages) {
				//filesBase
				String filesBase = RequestUtil.getStringParam(request, "filesBase", null);
				String filesDiya = RequestUtil.getStringParam(request, "filesDiya", null);
				String filesDiaocha = RequestUtil.getStringParam(request, "filesDiaocha", null);
				String filesKuaiji = RequestUtil.getStringParam(request, "filesKuaiji", null);
				String filesLvshi = RequestUtil.getStringParam(request, "filesLvshi", null);
				String filesZichan = RequestUtil.getStringParam(request, "filesZichan", null);
				Map<String, List<String>> projectImages = new HashMap<String, List<String>>();
				projectImages.put(UploadImageType.BASE.getCode(), StringUtil.linesToList(filesBase));
				projectImages.put(UploadImageType.PLEDGE.getCode(), StringUtil.linesToList(filesDiya));
				projectImages.put(UploadImageType.INVESTIGATION.getCode(), StringUtil.linesToList(filesDiaocha));
				projectImages.put(UploadImageType.ACCOUNTANT_AUDIT.getCode(), StringUtil.linesToList(filesKuaiji));
				projectImages.put(UploadImageType.LAYWER_AUDIT.getCode(), StringUtil.linesToList(filesLvshi));
				projectImages.put(UploadImageType.ASSETS_APPRAISAL.getCode(), StringUtil.linesToList(filesZichan));
				uploadImageService.updateProjectImages(project.getId(), projectImages);

				UploadUtil.confirm(RequestUtil.getStringParam(request, "commitmentLetterPath", null));
			}
		}catch(Exception e){
			logger.error("发布产品失败,新建项目出错," + e.getMessage());
			model.addAttribute("OK", "N");
			return PAGE_PATH + "productAdd";
		}

		return "redirect:/admin/product/productAdd.html";
	}

	/**
	 * 产品发布审核结果,提供按照担保公司ID或者项目状态查询
	 * @param userId
	 * 担保公司ID
	 */
	@RequestMapping("productReviewed")
	public String productReviewed(Project search, HttpServletRequest request, Model model) {
		// 常量合集
		assistInfoUtil.init(model);

		// 返回查询条件
		model.addAttribute(VariableConstants.Entity_Search, search);

		// 项目状态字典
		model.addAttribute(VariableConstants.MAP_PROJECT_STATUS, ProjectConstants.ProjectStatus.getCodeNameMap());

		//未选择状态则设定状态
		if(search != null && "".equals(search.getStatus())){
			search.setStatus(ProjectStatus.APPROVED.getCode()+","+ProjectStatus.REJECT_PROJECT.getCode());
		}

		// 分页条件
		Pager pager = new Pager();
		pager.setPageSize(RequestUtil.getIntParam(request, "pageSize", pageSize));
		Integer totalRows = RequestUtil.getIntParam(request, "totalRows", null);
		if(totalRows!=null && totalRows>0) pager.init(totalRows);
		Integer currentPage = RequestUtil.getIntParam(request, "currentPage", null);
		if(currentPage!=null && currentPage>0) pager.page(currentPage);

		// 用户ID
		String actionUserId = String.valueOf(ShiroTool.userId());

		// 查询结果
		Result<Pager> result = projectBizService.detailList(actionUserId, search, pager);
		if(result.hasObject()){
			model.addAttribute("pager", result.getObject());
		}

		return PAGE_PATH + "productReviewed";
	}

	@RequestMapping("productReviewedDetail")
	public String projectReviewedDetail(Long id, Model model){
		// 常量合集
		assistInfoUtil.init(model);

		// 用户
		String userId = String.valueOf(ShiroTool.userId());

		// 项目详情
		ProjectDetail detail = projectBizService.projectDetail(id);
		model.addAttribute(VariableConstants.Entity_Project, detail);

		Result<LoaneeInfo> resultLoanee = projectBizService.getLoaneeInfo(id, String.valueOf(ShiroTool.userId()==null?0L:ShiroTool.userId()));
		model.addAttribute(VariableConstants.Entity_LoaneeInfo, resultLoanee.getObject());

		//插入分润模板信息
		if(detail != null){
			if(detail.getProject() != null){
				Result<CommissionTemplate> resultCommission = commissionTemplateService.getCommissionTemplate(detail.getProject().getFundingTemplateId());
				model.addAttribute(VariableConstants.Entity_CommissionTemplate_Funding,resultCommission.getObject());
				Result<CommissionTemplate> resultRepay = commissionTemplateService.getCommissionTemplate(detail.getProject().getRepayTemplateId());
				model.addAttribute(VariableConstants.Entity_CommissionTemplate_Repay,resultRepay.getObject());
			}
		}

		//插入审核记录
		Result<List<ProjectReview>> resultProjectview = projectReviewBizService.list(userId, id);
		if(resultProjectview.hasObject()){
			model.addAttribute(VariableConstants.List_ProjectReview, resultProjectview.getObject());
		}else{
			logger.error("获取审核记录失败:" + resultProjectview.getMessage());
		}

		return PAGE_PATH + "productReviewedDetail";
	}

	/**
	 * 项目管理
	 * 提供按照担保公司ID或者项目状态查询
	 */
	@RequestMapping("project")
	public String project(Project search, HttpServletRequest request, Model model) {
		// 常量合集
		assistInfoUtil.init(model);

		// 返回查询条件
		model.addAttribute(VariableConstants.Entity_Search, search);

		Pager pager = new Pager();
		pager.setPageSize(RequestUtil.getIntParam(request, "pageSize", pageSize));
		Integer totalRows = RequestUtil.getIntParam(request, "totalRows", null);
		if(totalRows != null && totalRows > 0) pager.init(totalRows);
		Integer currentPage = RequestUtil.getIntParam(request, "currentPage", null);
		if(currentPage!=null && currentPage>0) pager.page(currentPage);
		pager.setDirection("desc");
		pager.setProperties("id");
		String actionUserId = String.valueOf(ShiroTool.userId());

		Result<Pager> result = projectBizService.detailList(actionUserId, search, pager);
		if(result.success() && result.getObject() != null){
			model.addAttribute("pager", result.getObject());
		}

		/**
		SqlBuilder sqlBuilder = new SqlBuilder();
		sqlBuilder.from("project left join user borrower on project.loanee_id=borrower.id left join guarantee on project.guarantee_letter_id=guarantee.id left join user guaranteeUser on guarantee.user_id=guaranteeUser.id left join user_enterprise_profile ent on guaranteeUser.id=ent.user_id");
		sqlBuilder.like("borrower.user_name", request.getParameter("loanee"));
		sqlBuilder.between("project.total_amount", request.getParameter("moneyMin"), request.getParameter("moneyMax"));
		sqlBuilder.between("project.invest_start_date", request.getParameter("beginTime"), request.getParameter("endTime"));
		sqlBuilder.eq("ent.user_id", request.getParameter("guaranteeEnterprise"));
		sqlBuilder.like("project.name", request.getParameter("projectName"));
		sqlBuilder.eq("project.status", request.getParameter("projectStatus"));
		if(pager.notInitialized()) {
			sqlBuilder.select("count(project.id)");
			Result<Integer> count = tongjiService.count(sqlBuilder);
			if(count.success()) pager.init(count.getObject());
		}

		sqlBuilder.select("project.id,project.name,borrower.user_name,project.total_amount,project.settle_terms_amount,ent.enterprise_name,project.invest_start_date,project.invest_end_date,project.status");
		sqlBuilder.limit(PagerUtil.limit(pager));
		@SuppressWarnings("rawtypes")
		Result<List> list = tongjiService.list(sqlBuilder);
		if(list.success()) pager.setElements(list.getObject());

		model.addAttribute("pager", pager);
		model.addAttribute("guarantees", projectBizService.guarantees().getObject());
		model.addAttribute("projectStatus", codeListService.list(CodeListType.PROJECT_STATUS.getCode()).getObject());
		model.addAttribute("request", RequestUtil.stringMap(request));
		//*/
		return PAGE_PATH + "project";
	}

	/**
	 * 产品发布审核结果详情页
	 * @param id
	 * 项目ID
	 */
	@RequestMapping("projectDetail")
	public String projectDetail(Long id, Model model) {
		// 常量合集
		assistInfoUtil.init(model);

		// 项目详情
		ProjectDetail detail = projectBizService.projectDetail(id);
		model.addAttribute(VariableConstants.Entity_Project, detail);
		//借款人信息披露
		Result<LoaneeInfo> resultLoanee = projectBizService.getLoaneeInfo(id, String.valueOf(ShiroTool.userId()==null?0L:ShiroTool.userId()));
		model.addAttribute(VariableConstants.Entity_LoaneeInfo, resultLoanee.getObject());

		//插入担保函信息
		Result<Guarantee> resultGuarantee = guaranteeBizService.detail(null, detail.getProject().getGuaranteeLetterId());
		model.addAttribute(VariableConstants.Entity_Guarantee, resultGuarantee.getObject());

		//插入分润模板信息
		if(detail != null){
			if(detail.getProject() != null){
				Result<CommissionTemplate> resultCommission = commissionTemplateService.getCommissionTemplate(detail.getProject().getFundingTemplateId());
				model.addAttribute(VariableConstants.Entity_CommissionTemplate_Funding,resultCommission.getObject());
				Result<CommissionTemplate> resultRepay = commissionTemplateService.getCommissionTemplate(detail.getProject().getRepayTemplateId());
				model.addAttribute(VariableConstants.Entity_CommissionTemplate_Repay,resultRepay.getObject());
			}
		}

		// 插入投资信息
		Pager pager = new Pager();
		pager.setPageSize(200);
		pager.init(200);
		pager.page(0);
		Investment investment = new Investment();
		investment.setProjectId(id);
		Result<Pager> investmentShow = investmentBizService.list(null, investment, pager);
		model.addAttribute(VariableConstants.Pager_Investment,investmentShow.getObject());

		// 插入还款信息
		Pager pager1 = new Pager();
		pager1.setPageSize(200);
		pager1.init(200);
		pager1.page(0);
		Repayment repay = new Repayment();
		repay.setProjectId(id);
		Result<Pager> repayment = repaymentBizService.list(null, repay, pager1);
		model.addAttribute(VariableConstants.Pager_Repayment, repayment.getObject());

		return PAGE_PATH + "projectDetail";
	}

	/**
	 * 待审核产品列表
	 * 查询条件,按照担保公司ID查询,无其他查询条件
	 * @param userId
	 * 担保公司ID
	 */
	@RequestMapping("productReviewing")
	public String productReviewing(Long userId, Model model, HttpServletRequest request){
		//返回查询条件
		model.addAttribute(VariableConstants.Entity_Search, userId);

		// 担保机构列表
		assistInfoUtil.init(model);

		// 登录用户
		String actionUserId = String.valueOf(ShiroTool.userId());

		// 分页准备
		Pager pager = new Pager();
		pager.setPageSize(RequestUtil.getIntParam(request, "pageSize", pageSize));
		Integer totalRows = RequestUtil.getIntParam(request, "totalRows", null);
		if(totalRows!=null && totalRows>0) pager.init(totalRows);
		Integer currentPage = RequestUtil.getIntParam(request, "currentPage", null);
		if(currentPage!=null && currentPage>0) pager.page(currentPage);

		// 查询参数
		Project search = new Project();
		search.setStatus(ProjectConstants.ProjectStatus.PENDING_FOR_APPROVE.getCode());
		if(userId != null && userId > 0L){
			search.setGuaranteeUserId(String.valueOf(userId));
		}

		// 查询结果
		Result<Pager> result = projectBizService.detailList(actionUserId, search, pager);
		if(result.success() && result.getObject() != null){
			model.addAttribute("pager", result.getObject());
		}

		return PAGE_PATH + "productReviewing";
	}

	/**
	 * 产品待审核页--产品详情
	 * @param id
	 * 项目ID
	 */
	@RequestMapping("productReviewingEdit")
	public String productReviewingEdit(Long id, Model model, HttpServletRequest request) {
		// 常量合集
		assistInfoUtil.init(model);

		// 项目详情
		ProjectDetail detail = projectBizService.projectDetail(id);
		model.addAttribute(VariableConstants.Entity_Project, detail);

		Result<LoaneeInfo> resultLoanee = projectBizService.getLoaneeInfo(id, String.valueOf(ShiroTool.userId()==null?0L:ShiroTool.userId()));
		model.addAttribute(VariableConstants.Entity_LoaneeInfo, resultLoanee.getObject());

		//插入分润模板信息
		if(detail != null){
			if(detail.getProject() != null){
				Result<CommissionTemplate> resultCommission = commissionTemplateService.getCommissionTemplate(detail.getProject().getFundingTemplateId());
				model.addAttribute(VariableConstants.Entity_CommissionTemplate_Funding,resultCommission.getObject());
				Result<CommissionTemplate> resultRepay = commissionTemplateService.getCommissionTemplate(detail.getProject().getRepayTemplateId());
				model.addAttribute(VariableConstants.Entity_CommissionTemplate_Repay,resultRepay.getObject());
			}
		}

		return PAGE_PATH + "productReviewingEdit";
	}

	@RequestMapping("reviewProject")
	public String reviewProject(Long projectId, Model model, HttpServletRequest request) {

		// 参数
		boolean pass = RequestUtil.getBoolParam(request, "result", false);
		String reason = RequestUtil.getStringParam(request, "reason", "");
		String date = RequestUtil.getStringParam(request, "fixedTime", "");
		Date now = DateUtil.parse(date);

		// 用户
		String userId = String.valueOf(ShiroTool.userId());

		Result<Boolean> result = projectBizService.reviewed(projectId, userId, now, pass, reason);
		if(result.hasObject()){
			if(!result.getObject()){
				logger.error("审核失败 : " + result.getMessage());
			}
		}else{
			logger.error("审核失败 : " + result.getError());
		}
		return "redirect:/admin/product/productReviewing.html";
	}

	@ResponseBody
	@RequestMapping("checkusername")
	public JSONObject checkusername(String name){
		if(name == null || "".equals(name)) return null;
		Result<User> user = customerService.getUserByUserName(name);
		if(user.success() && user.hasObject()){
			JSONObject json = new JSONObject();
			if(Role.BORROWER.getCode().equalsIgnoreCase(user.getObject().getRole())){
				json.put("mark", "yes");
			}
			json.put("userName", name);
			json.put("realName", user.getObject().getUserProfile().getRealName());
			json.put("projectNum", "0");
			json.put("investmentNum", "0");
			return json;
		}
		return null;
	}

}


text:
//------------------------------------------------------------------------------
// <auto-generated>
//     This code was generated by a tool.
//
//     Changes to this file may cause incorrect behavior and will be lost if
//     the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------

namespace DotNetNuke.UI.Skins.Controls {

    public partial class TreeViewMenu {

        /// <summary>
        /// tblMain control.
        /// </summary>
        /// <remarks>
        /// Auto-generated field.
        /// To modify move field declaration from designer file to code-behind file.
        /// </remarks>
        protected global::System.Web.UI.HtmlControls.HtmlTable tblMain;

        /// <summary>
        /// cellHeader control.
        /// </summary>
        /// <remarks>
        /// Auto-generated field.
        /// To modify move field declaration from designer file to code-behind file.
        /// </remarks>
        protected global::System.Web.UI.HtmlControls.HtmlTableCell cellHeader;

        /// <summary>
        /// tblHeader control.
        /// </summary>
        /// <remarks>
        /// Auto-generated field.
        /// To modify move field declaration from designer file to code-behind file.
        /// </remarks>
        protected global::System.Web.UI.HtmlControls.HtmlTable tblHeader;

        /// <summary>
        /// lblHeader control.
        /// </summary>
        /// <remarks>
        /// Auto-generated field.
        /// To modify move field declaration from designer file to code-behind file.
        /// </remarks>
        protected global::System.Web.UI.WebControls.Label lblHeader;

        /// <summary>
        /// cellBody control.
        /// </summary>
        /// <remarks>
        /// Auto-generated field.
        /// To modify move field declaration from designer file to code-behind file.
        /// </remarks>
        protected global::System.Web.UI.HtmlControls.HtmlTableCell cellBody;
    }
}


text:
/**
* Module navigation.js
*
* Handles all navigation events for the theme.
*
*/
define(function(){

	// Allows the navigation to stick to the top when the user
	// scrolls past the header.  Adds margin-top property to
	// #main to allow smooth scrolling.
	var navContainer = $('#nav'),
		navScrolled = "nav-scrolled",
		headerHeight = $('header').height();

	$(window).scroll(function() {
		if ( $(this).scrollTop() > headerHeight-50 ) {
			navContainer.addClass(navScrolled);
		} else {
			navContainer.removeClass(navScrolled);
		}
	});
});


text:
package eu.bcvsolutions.idm.core.notification.repository;

import org.springframework.data.jpa.repository.Query;

import eu.bcvsolutions.idm.core.api.repository.AbstractEntityRepository;
import eu.bcvsolutions.idm.core.notification.entity.IdmNotificationLog;

/**
 * Repository for notification system
 *
 * @author Radek Tomiška
 *
 */
public interface IdmNotificationLogRepository extends AbstractEntityRepository<IdmNotificationLog> {

	@Override
	@Query("select count(e) from IdmNotificationLog e where TYPE(e) = IdmNotificationLog")
	long count();
}


text:
using System;
using System.IO;
using Microsoft.VisualStudio.Shell;
using static Microsoft.VisualStudio.Shell.RegistrationAttribute;
using System.Collections.Generic;
using TestsCommon.TestSupport;

namespace YetiVSI.Test.TestSupport
{
    public class RegistrationContextStub : RegistrationContext
    {
        public Dictionary<string, KeyStub> keys = new Dictionary<string, KeyStub>();

        public override Key CreateKey(string name)
        {
            var key = new KeyStub(name);
            keys.Add(name, key);
            return key;
        }

        public override void RemoveKey(string name)
        {
            keys.Remove(name);
        }

        #region Not Implemented
        public override string CodeBase
        {
            get
            {
                throw new NotImplementedTestDoubleException();
            }
        }

        public override string ComponentPath
        {
            get
            {
                throw new NotImplementedTestDoubleException();
            }
        }

        public override Type ComponentType
        {
            get
            {
                throw new NotImplementedTestDoubleException();
            }
        }

        public override string InprocServerPath
        {
            get
            {
                throw new NotImplementedTestDoubleException();
            }
        }

        public override TextWriter Log
        {
            get
            {
                throw new NotImplementedTestDoubleException();
            }
        }

        public override RegistrationMethod RegistrationMethod
        {
            get
            {
                throw new NotImplementedTestDoubleException();
            }
        }

        public override string RootFolder
        {
            get
            {
                throw new NotImplementedTestDoubleException();
            }
        }

        public override string EscapePath(string str)
        {
            throw new NotImplementedTestDoubleException();
        }

        public override void RemoveKeyIfEmpty(string name)
        {
            throw new NotImplementedTestDoubleException();
        }

        public override void RemoveValue(string keyname, string valuename)
        {
            throw new NotImplementedTestDoubleException();
        }
        #endregion
    }
}


text:
package org.apache.druid.server.initialization;

import com.fasterxml.jackson.annotation.JsonProperty;
import org.apache.druid.metadata.PasswordProvider;

import java.util.List;

public class TLSServerConfig
{
  @JsonProperty
  private String keyStorePath;

  @JsonProperty
  private String keyStoreType;

  @JsonProperty
  private String certAlias;

  @JsonProperty("keyStorePassword")
  private PasswordProvider keyStorePasswordProvider;

  @JsonProperty("keyManagerPassword")
  private PasswordProvider keyManagerPasswordProvider;

  @JsonProperty
  private String keyManagerFactoryAlgorithm;

  @JsonProperty
  private List<String> includeCipherSuites;

  @JsonProperty
  private List<String> excludeCipherSuites;

  @JsonProperty
  private List<String> includeProtocols;

  @JsonProperty
  private List<String> excludeProtocols;

  @JsonProperty
  private boolean requireClientCertificate = false;

  @JsonProperty
  private boolean requestClientCertificate = false;

  @JsonProperty
  private String trustStoreType;

  @JsonProperty
  private String trustStorePath;

  @JsonProperty
  private String trustStoreAlgorithm;

  @JsonProperty("trustStorePassword")
  private PasswordProvider trustStorePasswordProvider;

  @JsonProperty
  private boolean validateHostnames = true;

  @JsonProperty
  private String crlPath;

  public String getKeyStorePath()
  {
    return keyStorePath;
  }

  public String getKeyStoreType()
  {
    return keyStoreType;
  }

  public PasswordProvider getKeyStorePasswordProvider()
  {
    return keyStorePasswordProvider;
  }

  public String getCertAlias()
  {
    return certAlias;
  }

  public PasswordProvider getKeyManagerPasswordProvider()
  {
    return keyManagerPasswordProvider;
  }

  public String getKeyManagerFactoryAlgorithm()
  {
    return keyManagerFactoryAlgorithm;
  }

  public List<String> getIncludeCipherSuites()
  {
    return includeCipherSuites;
  }

  public List<String> getExcludeCipherSuites()
  {
    return excludeCipherSuites;
  }

  public List<String> getIncludeProtocols()
  {
    return includeProtocols;
  }

  public List<String> getExcludeProtocols()
  {
    return excludeProtocols;
  }

  public boolean isRequireClientCertificate()
  {
    return requireClientCertificate;
  }

  public boolean isRequestClientCertificate()
  {
    return requestClientCertificate;
  }

  public String getTrustStoreType()
  {
    return trustStoreType;
  }

  public String getTrustStorePath()
  {
    return trustStorePath;
  }

  public String getTrustStoreAlgorithm()
  {
    return trustStoreAlgorithm;
  }

  public PasswordProvider getTrustStorePasswordProvider()
  {
    return trustStorePasswordProvider;
  }

  public boolean isValidateHostnames()
  {
    return validateHostnames;
  }

  public String getCrlPath()
  {
    return crlPath;
  }

  @Override
  public String toString()
  {
    return "TLSServerConfig{" +
           "keyStorePath='" + keyStorePath + '\'' +
           ", keyStoreType='" + keyStoreType + '\'' +
           ", certAlias='" + certAlias + '\'' +
           ", keyManagerFactoryAlgorithm='" + keyManagerFactoryAlgorithm + '\'' +
           ", includeCipherSuites=" + includeCipherSuites +
           ", excludeCipherSuites=" + excludeCipherSuites +
           ", includeProtocols=" + includeProtocols +
           ", excludeProtocols=" + excludeProtocols +
           ", requireClientCertificate=" + requireClientCertificate +
           ", requestClientCertificate=" + requestClientCertificate +
           ", trustStoreType='" + trustStoreType + '\'' +
           ", trustStorePath='" + trustStorePath + '\'' +
           ", trustStoreAlgorithm='" + trustStoreAlgorithm + '\'' +
           ", validateHostnames='" + validateHostnames + '\'' +
           ", crlPath='" + crlPath + '\'' +
           '}';
  }
}


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

namespace _09.Holidays_Between_Two_Dates
{
    class Program
    {
        static void Main()
        {
            var startDate = DateTime.ParseExact(
                Console.ReadLine(),
                "dd.m.yyyy",
                CultureInfo.InvariantCulture);
            var endDate = DateTime.ParseExact(
                Console.ReadLine(),
                "dd.m.yyyy",
                CultureInfo.InvariantCulture);
            var holidaysCount = 0;
            for (var date = startDate; date <= endDate; date = date.AddDays(1))
                if (date.DayOfWeek == DayOfWeek.Saturday ||
                    date.DayOfWeek == DayOfWeek.Sunday)
                {
                    holidaysCount++;
                }
            Console.WriteLine(holidaysCount);
        }

    }
}


text:
<?xml version = '1.0' encoding = 'UTF-8'?>
<Table class="oracle.dbtools.crest.model.design.relational.Table" directorySegmentName="seg_0" id="0E086349-40B1-E73D-B969-D483F63D32E3" schemaObject="EDDC5778-3A4E-26F0-AC9B-D2FB2C3A83F7" name="USERS">
<createdBy>himrc</createdBy>
<createdTime>2016-02-17 19:30:29 UTC</createdTime>
<ownerDesignName>diagram</ownerDesignName>
<ordsAlias>table_1</ordsAlias>
<allowColumnReorder>false</allowColumnReorder>
<existDependencyGenerateInDDl>true</existDependencyGenerateInDDl>
<parsed>true</parsed>
<columns itemClass="oracle.dbtools.crest.model.design.relational.Column">
<Column name="USER_ID" id="CDF29BFD-2F1A-3607-C8EF-4BB84BC2E060">
<createdBy>himrc</createdBy>
<createdTime>2016-02-17 19:31:29 UTC</createdTime>
<ownerDesignName>diagram</ownerDesignName>
<useDomainConstraints>false</useDomainConstraints>
<use>1</use>
<logicalDatatype>LOGDT019</logicalDatatype>
<ownDataTypeParameters>,,</ownDataTypeParameters>
<autoIncrementColumn>true</autoIncrementColumn>
<autoIncrementCycle>false</autoIncrementCycle>
</Column>
<Column name="CREATED_AT" id="F5E2A8B2-F3E1-1B56-7642-5E16AC5D1443">
<createdBy>himrc</createdBy>
<createdTime>2016-02-17 19:31:48 UTC</createdTime>
<ownerDesignName>diagram</ownerDesignName>
<nullsAllowed>true</nullsAllowed>
<useDomainConstraints>false</useDomainConstraints>
<use>1</use>
<logicalDatatype>LOGDT015</logicalDatatype>
<defaultValue>CURRENT_TIMESTAMP</defaultValue>
<ownDataTypeParameters>,,</ownDataTypeParameters>
<autoIncrementCycle>false</autoIncrementCycle>
</Column>
<Column name="USERNAME" id="65579BF1-7D29-621D-E106-5ABCB88A09DB">
<createdBy>himrc</createdBy>
<createdTime>2016-02-17 19:31:40 UTC</createdTime>
<ownerDesignName>diagram</ownerDesignName>
<nullsAllowed>true</nullsAllowed>
<useDomainConstraints>false</useDomainConstraints>
<use>1</use>
<logicalDatatype>LOGDT024</logicalDatatype>
<dataTypeSize>20</dataTypeSize>
<ownDataTypeParameters>20,,</ownDataTypeParameters>
<autoIncrementCycle>false</autoIncrementCycle>
</Column>
</columns>
<indexes itemClass="oracle.dbtools.crest.model.design.relational.Index">
<ind_PK_UK id="266B954B-A7B3-0907-FAA4-09FF3ED1B2FC" name="USER_PK">
<createdBy>himrc</createdBy>
<createdTime>2016-02-17 19:32:52 UTC</createdTime>
<ownerDesignName>diagram</ownerDesignName>
<pk>true</pk>
<indexState>Primary Constraint</indexState>
<isSurrogateKey>false</isSurrogateKey>
<indexColumnUsage>
<colUsage columnID="CDF29BFD-2F1A-3607-C8EF-4BB84BC2E060"/>
</indexColumnUsage>
</ind_PK_UK>
</indexes>
</Table>


text:
from flask import Flask, session, redirect, render_template, jsonify, request, Response, url_for, send_file
from functools import wraps
import json
import sys
import logging
import os
from mylib import graph, personal
import requests
import shutil

DEBUG = False
#DEBUG = True

app = Flask(__name__)
app.config['SECRET_KEY'] = 'XXXXXX'

@app.before_request
def before_request():
    if session.get('username') is not None:
        return
    if request.path == '/login':
        return
    if request.path[-4:] == ".css":
        return
    if request.path[-3:] == ".js":
        return
    return redirect('/login')

@app.route('/login', methods=['GET', 'POST'])
def login():
    if request.method == 'POST' and is_valid_user():
        session['username'] = request.form['workerId']
        return redirect(url_for('index'))
    return render_template('login.html')

def is_valid_user():
    if request.form.get('workerId') is None:
        return False
    return True

@app.route('/logout', methods=['GET'])
def logout():
    session.pop('username', None)
    return redirect(url_for('login'))

def get_request(payload):
    payload['acl:consumerKey'] = os.environ["FRAMEWORX_KEY"]
    return requests.get("https://api.frameworxopendata.jp/api/v3/datapoints", params=payload)

def write_data(data_type):
    payload = {'rdf:type': "frameworx:" + data_type}
    data = get_request(payload)
    with open(data_type + ".json", 'w') as f:
        json.dump(data.json(), f)

def write_map(filename, dirname=""):
    payload = {'acl:consumerKey': os.environ["FRAMEWORX_KEY"]}
    r = requests.get("https://api.frameworxopendata.jp/api/v3/files/" + filename, params=payload, stream=True)
    if r.status_code == 200:
        with open(os.path.join(dirname, filename), 'wb') as f:
            r.raw.decode_content = True
            shutil.copyfileobj(r.raw, f)

def read_data(data_type):
    with open(data_type + ".json", 'r') as f:
        data = json.load(f)
    return data

def check_auth(username, password):
    return username == os.environ["APP_USER"] and password == os.environ["APP_PASS"]

def authenticate():
    return Response(
        'Could not verify your access level for that URL.\n',
        401,
        {'WWW-Authenticate': 'Basic realm="Login Required"'})

def requires_auth(f):
    @wraps(f)
    def decorated(*args, **kwargs):
        if DEBUG:
            auth = request.authorization
            if not auth or not check_auth(auth.username, auth.password):
                return authenticate()
        return f(*args, **kwargs)
    return decorated

@app.route('/_get_personal_log_data', methods=["POST"])
@requires_auth
def _get_personal_log_data():
    workerId = request.json[u'workerId']
    category = request.json[u'category']
    data = personal.get_log_data(workerId, category)
    return jsonify(data=json.dumps(data))

@app.route('/_get_personal_summary_data', methods=["POST"])
@requires_auth
def _get_personal_summary_data():
    workerId = int(request.json[u'workerId'])
    data = personal.get_summary_data(workerId)
    return jsonify(data=json.dumps(data))

@app.route('/_get_personal_map_data', methods=["POST"])
@requires_auth
def _get_personal_map_data():
    workerId = int(request.json[u'workerId'])
    data = personal.get_map_data(workerId)
    return jsonify(data=json.dumps(data))

@app.route('/image')
def image():
    dirname = "static/images/"
    filename = "warehouse_map_1.jpg"
    path = os.path.join(dirname, filename)
    if not os.path.exists(path):
        write_map(filename, dirname)
    return send_file(path, mimetype='image/jpg')

@app.route('/_step_graph', methods=["GET", "POST"])
@requires_auth
def _step_graph():
    return jsonify({"test": "aaa"})

@app.route('/_item_ranking', methods=["GET"])
@requires_auth
def _item_ranking():
    return jsonify(graph.getTotalItemNumData(os.environ["FRAMEWORX_KEY"]))

@app.route('/_cal_ranking', methods=["GET"])
@requires_auth
def _cal_ranking():
    return jsonify(graph.getVitalData(os.environ["FRAMEWORX_KEY"], "calorie"))

@app.route('/_distance_ranking', methods=["GET"])
@requires_auth
def _distance_ranking():
    return jsonify(graph.getMoveDistance(os.environ["FRAMEWORX_KEY"]))

@app.route('/_step_ranking', methods=["GET"])
@requires_auth
def _step_ranking():
    return jsonify(graph.getVitalData(os.environ["FRAMEWORX_KEY"], "step"))

@app.route('/_get_session', methods=["GET"])
@requires_auth
def _get_session():
    key = request.args['key']
    return session.get(key)

@app.route('/_get_key', methods=["GET"])
@requires_auth
def _get_key():
    return jsonify({"key": os.environ["FRAMEWORX_KEY"]})

@app.route("/")
@requires_auth
def index():
    return render_template("index.html")

@app.route("/index.html")
@requires_auth
def index_2():
    return render_template("index.html")

@app.route("/log.html")
@requires_auth
def log_page():
    return render_template("log.html")

@app.route("/ranking.html")
@requires_auth
def ranking_page():
    return render_template("ranking.html")

@app.route("/man.html")
@requires_auth
def man_page():
    return render_template("man.html")

if __name__ == "__main__":
    app.debug = True
    app.logger.addHandler(logging.StreamHandler(sys.stdout))
    if DEBUG:
        app.run(host="0.0.0.0", debug=True, threaded=True)
    else:
        app.run(threaded=True)


text:
import { ChangeDetectionStrategy, Component, Injector, OnInit } from '@angular/core';
import { FormControl, FormGroup } from '@angular/forms';
import { ChangeVoucherNotificationSettings } from 'app/api/models';
import { validateBeforeSubmit } from 'app/shared/helper';
import { VoucherBasePageComponent } from 'app/voucher/voucher-base-page.component';
import { BehaviorSubject } from 'rxjs';

@Component({
  selector: "voucher-notification-settings",
  templateUrl: 'voucher-notification-settings.component.html',
  changeDetection: ChangeDetectionStrategy.OnPush
})
export class VoucherNotificationSettingsComponent extends VoucherBasePageComponent implements OnInit {
  form: FormGroup;
  emailRequired$ = new BehaviorSubject(false);

  constructor(injector: Injector) {
    super(injector);
  }

  ngOnInit(): void {
    super.ngOnInit();
    this.buildForm();
    this.addEnterShortcut(() => this.confirm());
    this.addEscapeShortcut(() => this.cancel());
    this.title = this.i18n.voucher.notificationSettings.title;
    this.emailRequired$.next(this.isEmailRequired());
  }

  confirm() {
    if (!validateBeforeSubmit(this.form)) {
      return;
    }
    const settings: ChangeVoucherNotificationSettings = this.form.value;
    this.voucherService.changeVoucherInfoNotificationSettings({ token: this.state.token, pin: this.state.pin, body: settings })
      .subscribe(_resp => {
        this.notification.snackBar(this.i18n.voucher.notificationSettings.done);
        this.state.updateNotificationSettings(settings);
        this.router.navigate(["details"]);
      });
  }

  cancel() {
    this.router.navigate(['/details']);
  }

  isEmailRequired() {
    const enableNotifications = this.form.get('enableNotifications').value;
    return this.state.isSent() || (enableNotifications && !this.state.voucher.phoneConfiguration);
  }

  private buildForm() {
    const email = new FormControl(this.state.voucher.email, control => {
      const currVal = control.value;
      if (control.touched && !currVal && this.isEmailRequired()) {
        return {
          required: true
        };
      }
      return null;
    });
    const mobilePhone = new FormControl(this.state.voucher.mobilePhone);
    const enableNotifications = new FormControl(this.state.voucher.notificationsEnabled);
    enableNotifications.valueChanges.subscribe(() => this.emailRequired$.next(this.isEmailRequired()));

    this.form = new FormGroup({ email, mobilePhone, enableNotifications });
  }
}