text:
#ifndef _LINUX_MEMCONTROL_H
#define _LINUX_MEMCONTROL_H
#include <linux/cgroup.h>
#include <linux/vm_event_item.h>

struct mem_cgroup;
struct page_cgroup;
struct page;
struct mm_struct;

/* Stats that can be updated by kernel. */
enum mem_cgroup_page_stat_item {
	MEMCG_NR_FILE_MAPPED, /* # of pages charged as file rss */
};

struct mem_cgroup_reclaim_cookie {
	struct zone *zone;
	int priority;
	unsigned int generation;
};

#ifdef CONFIG_CGROUP_MEM_RES_CTLR
/*
 * All "charge" functions with gfp_mask should use GFP_KERNEL or
 * (gfp_mask & GFP_RECLAIM_MASK). In current implementatin, memcg doesn't
 * alloc memory but reclaims memory from all available zones. So, "where I want
 * memory from" bits of gfp_mask has no meaning. So any bits of that field is
 * available but adding a rule is better. charge functions' gfp_mask should
 * be set to GFP_KERNEL or gfp_mask & GFP_RECLAIM_MASK for avoiding ambiguous
 * codes.
 * (Of course, if memcg does memory allocation in future, GFP_KERNEL is sane.)
 */

extern int mem_cgroup_newpage_charge(struct page *page, struct mm_struct *mm,
				gfp_t gfp_mask);
/* for swap handling */
extern int mem_cgroup_try_charge_swapin(struct mm_struct *mm,
		struct page *page, gfp_t mask, struct mem_cgroup **memcgp);
extern void mem_cgroup_commit_charge_swapin(struct page *page,
					struct mem_cgroup *memcg);
extern void mem_cgroup_cancel_charge_swapin(struct mem_cgroup *memcg);

extern int mem_cgroup_cache_charge(struct page *page, struct mm_struct *mm,
					gfp_t gfp_mask);

struct lruvec *mem_cgroup_zone_lruvec(struct zone *, struct mem_cgroup *);
struct lruvec *mem_cgroup_page_lruvec(struct page *, struct zone *);

/* For coalescing uncharge for reducing memcg' overhead*/
extern void mem_cgroup_uncharge_start(void);
extern void mem_cgroup_uncharge_end(void);

extern void mem_cgroup_uncharge_page(struct page *page);
extern void mem_cgroup_uncharge_cache_page(struct page *page);

extern void mem_cgroup_out_of_memory(struct mem_cgroup *memcg, gfp_t gfp_mask,
				     int order);
bool __mem_cgroup_same_or_subtree(const struct mem_cgroup *root_memcg,
				  struct mem_cgroup *memcg);
int task_in_mem_cgroup(struct task_struct *task, const struct mem_cgroup *memcg);

extern struct mem_cgroup *try_get_mem_cgroup_from_page(struct page *page);
extern struct mem_cgroup *mem_cgroup_from_task(struct task_struct *p);
extern struct mem_cgroup *try_get_mem_cgroup_from_mm(struct mm_struct *mm);

extern struct mem_cgroup *parent_mem_cgroup(struct mem_cgroup *memcg);
extern struct mem_cgroup *mem_cgroup_from_cont(struct cgroup *cont);

static inline
int mm_match_cgroup(const struct mm_struct *mm, const struct mem_cgroup *cgroup)
{
	struct mem_cgroup *memcg;
	int match;

	rcu_read_lock();
	memcg = mem_cgroup_from_task(rcu_dereference((mm)->owner));
	match = __mem_cgroup_same_or_subtree(cgroup, memcg);
	rcu_read_unlock();
	return match;
}

extern struct cgroup_subsys_state *mem_cgroup_css(struct mem_cgroup *memcg);

extern int
mem_cgroup_prepare_migration(struct page *page,
	struct page *newpage, struct mem_cgroup **memcgp, gfp_t gfp_mask);
extern void mem_cgroup_end_migration(struct mem_cgroup *memcg,
	struct page *oldpage, struct page *newpage, bool migration_ok);

struct mem_cgroup *mem_cgroup_iter(struct mem_cgroup *,
				   struct mem_cgroup *,
				   struct mem_cgroup_reclaim_cookie *);
void mem_cgroup_iter_break(struct mem_cgroup *, struct mem_cgroup *);

/*
 * For memory reclaim.
 */
int mem_cgroup_inactive_anon_is_low(struct lruvec *lruvec);
int mem_cgroup_inactive_file_is_low(struct lruvec *lruvec);
int mem_cgroup_select_victim_node(struct mem_cgroup *memcg);
unsigned long mem_cgroup_get_lru_size(struct lruvec *lruvec, enum lru_list);
void mem_cgroup_update_lru_size(struct lruvec *, enum lru_list, int);
extern void mem_cgroup_print_oom_info(struct mem_cgroup *memcg,
					struct task_struct *p);
extern void mem_cgroup_replace_page_cache(struct page *oldpage,
					struct page *newpage);

#ifdef CONFIG_CGROUP_MEM_RES_CTLR_SWAP
extern int do_swap_account;
#endif

static inline bool mem_cgroup_disabled(void)
{
	if (mem_cgroup_subsys.disabled)
		return true;
	return false;
}

void __mem_cgroup_begin_update_page_stat(struct page *page, bool *locked,
					 unsigned long *flags);

extern atomic_t memcg_moving;

static inline void mem_cgroup_begin_update_page_stat(struct page *page,
					bool *locked, unsigned long *flags)
{
	if (mem_cgroup_disabled())
		return;
	rcu_read_lock();
	*locked = false;
	if (atomic_read(&memcg_moving))
		__mem_cgroup_begin_update_page_stat(page, locked, flags);
}

void __mem_cgroup_end_update_page_stat(struct page *page,
				unsigned long *flags);
static inline void mem_cgroup_end_update_page_stat(struct page *page,
					bool *locked, unsigned long *flags)
{
	if (mem_cgroup_disabled())
		return;
	if (*locked)
		__mem_cgroup_end_update_page_stat(page, flags);
	rcu_read_unlock();
}

void mem_cgroup_update_page_stat(struct page *page,
				 enum mem_cgroup_page_stat_item idx,
				 int val);

static inline void mem_cgroup_inc_page_stat(struct page *page,
					    enum mem_cgroup_page_stat_item idx)
{
	mem_cgroup_update_page_stat(page, idx, 1);
}

static inline void mem_cgroup_dec_page_stat(struct page *page,
					    enum mem_cgroup_page_stat_item idx)
{
	mem_cgroup_update_page_stat(page, idx, -1);
}

unsigned long mem_cgroup_soft_limit_reclaim(struct zone *zone, int order,
						gfp_t gfp_mask,
						unsigned long *total_scanned);
u64 mem_cgroup_get_limit(struct mem_cgroup *memcg);

void mem_cgroup_count_vm_event(struct mm_struct *mm, enum vm_event_item idx);
#ifdef CONFIG_TRANSPARENT_HUGEPAGE
void mem_cgroup_split_huge_fixup(struct page *head);
#endif

#ifdef CONFIG_DEBUG_VM
bool mem_cgroup_bad_page_check(struct page *page);
void mem_cgroup_print_bad_page(struct page *page);
#endif
#else /* CONFIG_CGROUP_MEM_RES_CTLR */
struct mem_cgroup;

static inline int mem_cgroup_newpage_charge(struct page *page,
					struct mm_struct *mm, gfp_t gfp_mask)
{
	return 0;
}

static inline int mem_cgroup_cache_charge(struct page *page,
					struct mm_struct *mm, gfp_t gfp_mask)
{
	return 0;
}

static inline int mem_cgroup_try_charge_swapin(struct mm_struct *mm,
		struct page *page, gfp_t gfp_mask, struct mem_cgroup **memcgp)
{
	return 0;
}

static inline void mem_cgroup_commit_charge_swapin(struct page *page,
					  struct mem_cgroup *memcg)
{
}

static inline void mem_cgroup_cancel_charge_swapin(struct mem_cgroup *memcg)
{
}

static inline void mem_cgroup_uncharge_start(void)
{
}

static inline void mem_cgroup_uncharge_end(void)
{
}

static inline void mem_cgroup_uncharge_page(struct page *page)
{
}

static inline void mem_cgroup_uncharge_cache_page(struct page *page)
{
}

static inline struct lruvec *mem_cgroup_zone_lruvec(struct zone *zone,
						    struct mem_cgroup *memcg)
{
	return &zone->lruvec;
}

static inline struct lruvec *mem_cgroup_page_lruvec(struct page *page,
						    struct zone *zone)
{
	return &zone->lruvec;
}

static inline struct mem_cgroup *try_get_mem_cgroup_from_page(struct page *page)
{
	return NULL;
}

static inline struct mem_cgroup *try_get_mem_cgroup_from_mm(struct mm_struct *mm)
{
	return NULL;
}

static inline int mm_match_cgroup(struct mm_struct *mm,
		struct mem_cgroup *memcg)
{
	return 1;
}

static inline int task_in_mem_cgroup(struct task_struct *task,
				     const struct mem_cgroup *memcg)
{
	return 1;
}

static inline struct cgroup_subsys_state
		*mem_cgroup_css(struct mem_cgroup *memcg)
{
	return NULL;
}

static inline int
mem_cgroup_prepare_migration(struct page *page, struct page *newpage,
	struct mem_cgroup **memcgp, gfp_t gfp_mask)
{
	return 0;
}

static inline void mem_cgroup_end_migration(struct mem_cgroup *memcg,
		struct page *oldpage, struct page *newpage, bool migration_ok)
{
}

static inline struct mem_cgroup *
mem_cgroup_iter(struct mem_cgroup *root,
		struct mem_cgroup *prev,
		struct mem_cgroup_reclaim_cookie *reclaim)
{
	return NULL;
}

static inline void mem_cgroup_iter_break(struct mem_cgroup *root,
					 struct mem_cgroup *prev)
{
}

static inline bool mem_cgroup_disabled(void)
{
	return true;
}

static inline int
mem_cgroup_inactive_anon_is_low(struct lruvec *lruvec)
{
	return 1;
}

static inline int
mem_cgroup_inactive_file_is_low(struct lruvec *lruvec)
{
	return 1;
}

static inline unsigned long
mem_cgroup_get_lru_size(struct lruvec *lruvec, enum lru_list lru)
{
	return 0;
}

static inline void
mem_cgroup_update_lru_size(struct lruvec *lruvec, enum lru_list lru,
			      int increment)
{
}

static inline void
mem_cgroup_print_oom_info(struct mem_cgroup *memcg, struct task_struct *p)
{
}

static inline void mem_cgroup_begin_update_page_stat(struct page *page,
					bool *locked, unsigned long *flags)
{
}

static inline void mem_cgroup_end_update_page_stat(struct page *page,
					bool *locked, unsigned long *flags)
{
}

static inline void mem_cgroup_inc_page_stat(struct page *page,
					    enum mem_cgroup_page_stat_item idx)
{
}

static inline void mem_cgroup_dec_page_stat(struct page *page,
					    enum mem_cgroup_page_stat_item idx)
{
}

static inline
unsigned long mem_cgroup_soft_limit_reclaim(struct zone *zone, int order,
					    gfp_t gfp_mask,
					    unsigned long *total_scanned)
{
	return 0;
}

static inline
u64 mem_cgroup_get_limit(struct mem_cgroup *memcg)
{
	return 0;
}

static inline void mem_cgroup_split_huge_fixup(struct page *head)
{
}

static inline
void mem_cgroup_count_vm_event(struct mm_struct *mm, enum vm_event_item idx)
{
}
static inline void mem_cgroup_replace_page_cache(struct page *oldpage,
				struct page *newpage)
{
}
#endif /* CONFIG_CGROUP_MEM_RES_CTLR */

#if !defined(CONFIG_CGROUP_MEM_RES_CTLR) || !defined(CONFIG_DEBUG_VM)
static inline bool
mem_cgroup_bad_page_check(struct page *page)
{
	return false;
}

static inline void
mem_cgroup_print_bad_page(struct page *page)
{
}
#endif

enum {
	UNDER_LIMIT,
	SOFT_LIMIT,
	OVER_LIMIT,
};

struct sock;
#ifdef CONFIG_CGROUP_MEM_RES_CTLR_KMEM
void sock_update_memcg(struct sock *sk);
void sock_release_memcg(struct sock *sk);
#else
static inline void sock_update_memcg(struct sock *sk)
{
}
static inline void sock_release_memcg(struct sock *sk)
{
}
#endif /* CONFIG_CGROUP_MEM_RES_CTLR_KMEM */
#endif /* _LINUX_MEMCONTROL_H */


text:
## ------------------------------------------------------------------------
## Licensed to the Apache Software Foundation (ASF) under one or more
## contributor license agreements.  See the NOTICE file distributed with
## this work for additional information regarding copyright ownership.
## The ASF licenses this file to You under the Apache License, Version 2.0
## (the "License"); you may not use this file except in compliance with
## the License.  You may obtain a copy of the License at
##
## http://www.apache.org/licenses/LICENSE-2.0
##
## Unless required by applicable law or agreed to in writing, software
## distributed under the License is distributed on an "AS IS" BASIS,
## WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
## See the License for the specific language governing permissions and
## limitations under the License.
## ------------------------------------------------------------------------
package ${package};

import org.apache.camel.main.Main;

/**
 * Main class that boot the Camel application
 */
public final class MyApplication {

    private MyApplication() {
    }

    public static void main(String[] args) throws Exception {
        // use Camels Main class
        Main main = new Main();
        // lets use a configuration class (you can specify multiple classes)
        // (properties are automatic loaded from application.properties)
        main.configure().addConfigurationClass(MyConfiguration.class);
        // and add the routes (you can specify multiple classes)
        main.configure().addRoutesBuilder(MyRouteBuilder.class);
        // now keep the application running until the JVM is terminated (ctrl + c or sigterm)
        main.run(args);
    }

}

redpajama_set_name: RedPajamaGithub


text: The source of my [personal website](https://thomasbandt.com).


text:
@if (count($errors) > 0)

Error:

                    @foreach ($errors->all() as $error)

{{ $error }}

                    @endforeach

@endif

@if(Session::has('warning'))

Error:

                    {{ Session::get('warning') }}

@endif

@if(App::isDownForMaintenance())

Maintenance Mode is on!

                    This is just a reminder to let you know that the maintenance mode is on meaning that users can not access website.
                    So please make it quick.

@endif

@if(Session::has('status'))

                    {{ Session::get('status') }}

@endif


text:
package com.rst.tryx;

import java.awt.Color;
import java.awt.FlowLayout;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.Socket;
import java.net.SocketTimeoutException;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.ArrayList;
import java.util.List;
import java.util.Properties;

import javax.activation.MimetypesFileTypeMap;
import javax.swing.JApplet;
import javax.swing.JButton;
import javax.swing.JFileChooser;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JProgressBar;
import javax.swing.SwingWorker;

import com.rst.tryx.SftpUtil.RespHeader;

public class ResumeUploadApplet extends JApplet {

	/**
	 * serialVersionUID
	 */
	private static final long serialVersionUID = 4745155080907340562L;

	public static final String FIELD_NAME_UPLOAD_FILE_INSTANCE = "UPLOAD_FILE_INSTANCE";
	public static final String FIELD_NAME_UPLOAD_THUMBNAIL_INSTANCE = "UPLOAD_THUMBNAIL_INSTANCE";

	public static final String PARAM_FILECSID = "fileCsId";
	public static final String PARAM_FILENAME = "fileName";
	public static final String PARAM_LASTMODIFYDATE = "lastModifyDate";
	public static final String PARAM_FILESIZE = "fileSize";
	public static final String PARAM_FILETYPE = "fileType";
	public static final String PARAM_FORCE_OP = "forceOperation";
	public static final String PARAM_REQUESTTOKEN = "requestToken";
	public static final String PARAM_THUMBNAIL_UPLOAD = "thumbnailUpload";

	// RESP FLAG DEFINE
	public static final String RESP_FLAG_OK = "OK";
	public static final String RESP_FLAG_PARAM_ERR = "PARAM_ERR";
	public static final String RESP_FLAG_INPROGRESS_ERR = "INPROGRESS_ERR";
	public static final String RESP_FLAG_COMPLETED_WARN = "COMPLETED_WARN";
	public static final String RESP_FLAG_NOT_COMPLETED_ERR = "NOT_COMPLETED_ERR";
	public static final String RESP_FLAG_FILEBYTES_ERR = "FILEBYTES_ERR";
	public static final String RESP_FLAG_REQUEST_FMT_ERR = "REQUEST_FMT_ERR";
	public static final String RESP_FLAG_REQUEST_CONTENT_ERR = "REQUEST_CONTENT_ERR";
	public static final String RESP_FLAG_REQUEST_TOKEN_ERR = "REQUEST_TOKEN_ERR";
	public static final String RESP_FLAG_IO_ERR = "IO_ERR";

	private static final String OP_INIT = "[上传初始化操作]";
	private static final String OP_DELETE = "[删除文件操作]";
	private static final String OP_UPLOAD = "[上传文件操作]";
	private static final String OP_CANCEL = "[取消上传操作]";
	private static final String OP_STOP = "[中断上传操作]";
	private static final String OP_ST_OK = "处理成功";
	private static final String OP_ST_FAIL = "处理失败";

	public static final String PARAM_UPLOAD_FILE_ELE_ID = "uploadFileElementId";
	private static final String DEFAULT_UPLOAD_FILE_ELE_ID = "uploadFileId";

	private static final byte MAX_RETRY_TIMES = 3;

	private static final String BLANK_STR = "";

	private static final int READ_TIMEOUT = 10000; // never timeout

	private static final int SOCK_PF_CT = 0; // connection time.
	private static final int SOCK_PF_LL = 0; // low latency.
	private static final int SOCK_PF_HB = 1;

	private static final int FILENAME_MAX_LEN = 25;

	private static final String FILENAME_ELLIPSIS = "...";

	private static String HOST = "localhost";

	private static int PORT = 62953;

	private static String SERVICE_URL = "http://localhost:8080/cl/ResumeUploadServlet";

	private static final MimetypesFileTypeMap MIMETYPE_MAPPER = new MimetypesFileTypeMap();

//	private static CloseableHttpClient HTTP_CLIENT;

	private JPanel mainPanel;
	// private JPanel centerPanel;
	private JPanel bottomPanel;
	private JPanel statusPanel;

	private JLabel statusLabel;

	private JPanel filenamePanel;
	private JPanel fileSizePanel;
	private JLabel filenameLabel;
	private JLabel fileSizeLabel;
	private JLabel filenameTitle;
	private JLabel fileSizeTitle;

	private JPanel progressPanel;
	private JProgressBar progressBar;

	private JButton browseButton;
	private JButton uploadButton;
	private JButton deleteButton;

	private JFileChooser fileChooser;
	private File uploadTargetFile;

	private JsonResponse currentResp;
	private byte reTryTime;
	private String uploadFileElementId;

	private SftpUploadWorker sftpUploadWorker;

	@Override
	public void init() {
		super.init();

		InputStream propIs = null;
		try {
			propIs = ResumeUploadApplet.class
					.getResourceAsStream("/upload_conf.properties");
			Properties prop = new Properties();
			prop.load(propIs);
			if (null != propIs) {
				propIs.close();
			}
			SERVICE_URL = prop.getProperty("service_url");
			HOST = prop.getProperty("uploadServerHost");
			PORT = Integer.valueOf(prop.getProperty("uploadServerPort"));

		} catch (IOException ioe) {
		} finally {
			try {
				if (null != propIs) {
					propIs.close();
				}
			} catch (IOException innerIoe) {
				propIs = null;
			}
		}

		if (null == SERVICE_URL) {
			System.exit(1);
		}

		reTryTime = MAX_RETRY_TIMES;

		if (null != this.getParameter(PARAM_UPLOAD_FILE_ELE_ID)
				&& !BLANK_STR.equals(this
						.getParameter(PARAM_UPLOAD_FILE_ELE_ID))) {
			uploadFileElementId = this.getParameter(PARAM_UPLOAD_FILE_ELE_ID);
		} else {
			uploadFileElementId = DEFAULT_UPLOAD_FILE_ELE_ID;
		}

		// 初始化面板设置
		this.mainPanel = new JPanel();
		this.mainPanel.setLayout(new GridLayout(5, 1));
		this.setContentPane(mainPanel);

		initCenterPanel();
		mainPanel.add(filenamePanel);
		mainPanel.add(fileSizePanel);
		mainPanel.add(progressPanel);

		initBottomPanel();
		this.mainPanel.add(bottomPanel);

		initStatusPanel();
		this.mainPanel.add(statusPanel);

//		HTTP_CLIENT = HttpClients.createDefault();
//		if (null == HTTP_CLIENT) {
//			statusFail("HTTP引擎初始化操作");
//		}
	}

	private void initCenterPanel() {

		filenamePanel = new JPanel();
		filenamePanel.setLayout(new FlowLayout(FlowLayout.LEFT));
		filenameTitle = new JLabel(" 文件名称: ");
		filenameLabel = new JLabel();
		filenamePanel.add(filenameTitle);
		filenamePanel.add(filenameLabel);

		fileSizePanel = new JPanel();
		fileSizePanel.setLayout(new FlowLayout(FlowLayout.LEFT));
		fileSizeTitle = new JLabel(" 文件大小: ");
		fileSizeLabel = new JLabel();
		fileSizePanel.add(fileSizeTitle);
		fileSizePanel.add(fileSizeLabel);

		progressPanel = new JPanel();
		progressPanel.setLayout(new FlowLayout(FlowLayout.LEFT));
		progressPanel.add(initProgressBar());
		progressPanel.add(initBrowseButton());
	}

	private JProgressBar initProgressBar() {
		progressBar = new JProgressBar(0, 100);
		progressBar.setBackground(Color.WHITE);
		progressBar.setStringPainted(true);
		return progressBar;
	}

	private void initBottomPanel() {
		bottomPanel = new JPanel();
		bottomPanel.setLayout(new FlowLayout(FlowLayout.LEFT));
		bottomPanel.add(initUploadButton());
		bottomPanel.add(initDeleteButton());
	}

	private void initStatusPanel() {
		statusPanel = new JPanel();
		statusPanel.setLayout(new FlowLayout(FlowLayout.LEFT));
		statusLabel = new JLabel("准备就绪。");
		statusLabel.setForeground(Color.BLACK);
		statusPanel.add(statusLabel);
	}

	private JButton initBrowseButton() {
		browseButton = new JButton("浏览文件");
		browseButton.addActionListener(new BrowseButtonActionListener());
		return browseButton;
	}

	private JButton initUploadButton() {
		uploadButton = new JButton("开始上传");
		uploadButton.setEnabled(false);
		uploadButton.addActionListener(new UploadButtonActionListener());
		return uploadButton;
	}

	private JButton initDeleteButton() {
		deleteButton = new JButton("删除文件");
		deleteButton.setEnabled(false);
		deleteButton.addActionListener(new DeleteButtonActionListener());
		return deleteButton;
	}

	private void uploadFileSelected(File file) {
		reTryTime = MAX_RETRY_TIMES;
		String filePath = file.getAbsolutePath();
		if (FILENAME_MAX_LEN < filePath.length()) {
			filenameLabel.setText(filePath.substring(0, FILENAME_MAX_LEN)
					+ FILENAME_ELLIPSIS);
		} else {
			filenameLabel.setText(filePath);
		}
		filenameLabel.setToolTipText(filePath);
		fileSizeLabel.setText(FileAnalyse.number(file.length()));
		queryStatus(file, true);
	}

	void statusConnFail() {
		wran("网络连接异常,请重新选择上传文件。");
		browseButton.setEnabled(true);
	}

	void statusOk(String operation) {
		statusLabel.setForeground(Color.BLACK);
		statusLabel
				.setText(null == operation ? OP_ST_OK : operation + OP_ST_OK);
	}

	void statusFail(String operation) {
		statusLabel.setForeground(Color.RED);
		statusLabel.setText(null == operation ? OP_ST_FAIL : operation
				+ OP_ST_FAIL);
	}

	void info(String msg) {
		status(true, msg);
	}

	void wran(String msg) {
		status(false, msg);
	}

	void status(boolean isInfo, String msg) {
		statusLabel.setForeground(isInfo ? Color.BLACK : Color.RED);
		statusLabel.setText(msg);
	}

	private boolean queryStatus(File file, boolean isNoise) {
		return queryStatus(file, isNoise, false);
	}

	private boolean queryStatus(File file, boolean isNoise, boolean force) {
		String resp = httpGet(initQueryStatusUri(file, force));
		if (null == resp) {
			statusConnFail();
			return false;
		}
		try {
//			currentResp = GSON.fromJson(resp, JsonResponse.class);
		} catch (Exception e) {
			// parse response error.
			statusConnFail();
			return false;
		}
		if (null == currentResp || null == currentResp.flag
				|| BLANK_STR.equals(currentResp.flag.trim())) {
			// parse response error.
			statusConnFail();
			return false;
		}

		switch (currentResp.flag) {
		case RESP_FLAG_OK: {
			uploadTargetFile = file;
			progressBar.setValue(calcProgress(
					currentResp.files.get(0).uploadedBytes,
					uploadTargetFile.length()));
			statusOk(OP_INIT);
			uploadButton.setEnabled(true);
			return true;
		}
		case RESP_FLAG_COMPLETED_WARN: {
			statusOk(OP_INIT);
			if (isNoise) {
				if (confirm("该文件已经上传成功,是否删除该文件后重新上传。")) {
					// re upload.
					queryStatus(file, false, true);
				} else {
					// same with complete upload
					uploadTargetFile = file;
					jquery$Val(uploadFileElementId, currentResp.files.get(0).csid);
					progressBar.setValue(calcProgress(
							currentResp.files.get(0).uploadedBytes,
							uploadTargetFile.length()));
					deleteButton.setEnabled(true);
					return false;
				}
			}
			break;
		}
		case RESP_FLAG_INPROGRESS_ERR: {
			if (isNoise)
				alert("该文件正在上传,请勿重复操作。");
			break;
		}
		default: {
			if (isNoise)
				alert("上传文件数据不合法,系统无法处理。");
			statusFail(OP_INIT);
		}
		}
		return false;
	}

	private void deleteCallback(String resp) {
		if (null == resp) {
			statusConnFail();
			return;
		}
		try {
//			currentResp = GSON.fromJson(resp, JsonResponse.class);
		} catch (Exception e) {
			// parse response error.
			statusConnFail();
			return;
		}
		if (null == currentResp || null == currentResp.flag
				|| BLANK_STR.equals(currentResp.flag.trim())) {
			// parse response error.
			statusConnFail();
			return;
		}
		progressBar.setValue(0);
		browseButton.setEnabled(true);
		deleteButton.setEnabled(false);
		uploadButton.setEnabled(false);
		switch (currentResp.flag) {
		case RESP_FLAG_OK: {
			alert("删除文件完成。");
			filenameLabel.setText(BLANK_STR);
			fileSizeLabel.setText(BLANK_STR);
			statusOk(OP_DELETE);
			break;
		}
		case RESP_FLAG_INPROGRESS_ERR: {
			alert("该文件正在上传,无法删除,请勿重复操作,可选择其他文件进行操作。");
			statusFail(OP_DELETE);
			break;
		}
		case RESP_FLAG_PARAM_ERR: {
			alert("删除文件数据不合法,系统无法处理,可选择其他文件进行操作。");
			statusFail(OP_DELETE);
			break;
		}
		default: {
			alert("未知错误,系统无法处理,请联系系统管理员,可选择其他文件进行操作。");
			statusFail(OP_DELETE);
		}
		}
	}

	private void uploadDoneCallback(SftpUtil.RespHeader resp) {
		if (null == resp) {
			statusConnFail();
			return;
		}

		switch (resp.getCmd()) {
		case SftpUtil.CMD_EOT: {
			if (resp.isSuccess()) {
				alert("文件上传完成。");
				statusOk(OP_UPLOAD);
				jquery$Val(uploadFileElementId, currentResp.files.get(0).csid);
				deleteButton.setEnabled(true);
				return;
			} else {
				// upload failure
				// alert("文件上传失败。");
				break;
			}
		}
		case SftpUtil.CMD_CAN: {
			if (resp.isSuccess()) {
				alert("取消上传成功。");
				statusOk(OP_CANCEL);
				jquery$Val(uploadFileElementId, BLANK_STR);
				return;
			}
			statusFail(OP_CANCEL);
			alert("系统级异常,请联系系统管理员处理。");
			return;
		}
		case SftpUtil.CMD_STOP: {
			if (resp.isSuccess()) {
				alert("中断上传成功。");
				statusOk(OP_STOP);
				jquery$Val(uploadFileElementId, BLANK_STR);
				if (queryStatus(uploadTargetFile, false, true)) {
					uploadButton.setEnabled(true);
					statusOk(OP_INIT);
					return;
				}
			}
			statusFail(OP_STOP);
			alert("系统级异常,请联系系统管理员处理。");
			return;
		}
		case SftpUtil.CMD_ETB: {
			break;
		}
		default: {
			break;
		}
		}
		statusFail(OP_UPLOAD);
		alert("系统级异常,请联系系统管理员处理。");
	}

	private URI initDeleteUri(JsonResponse uploadedResp) {

		return null;
	}

	private URI initQueryStatusUri(File file, boolean force) {

		return null;
	}

	private static final String parseResponse(Object obj) throws IOException {

		return null;
	}

	private String httpDelete(URI uri) {

		return null;
	}

	private String httpGet(URI uri) {

		return null;
	}

	class ReceiveThread extends Thread {

		private InputStream sockInputStream;

		ReceiveThread(InputStream is) {
			sockInputStream = is;
		}

		@Override
		public void run() {
			try {
				if (null != sockInputStream) {
					long lastProgress = sftpUploadWorker.countBytesCurrentSession;
					while (true) {
						try {
							RespHeader resp = SftpUtil
									.receiveResp(sockInputStream);
							uploadDoneCallback(resp);
							return;
						} catch (SocketTimeoutException ste) {
							if (sftpUploadWorker.countBytesCurrentSession > lastProgress) {
								lastProgress = sftpUploadWorker.countBytesCurrentSession;
								continue;
							}
							uploadDoneCallback(null);
							break;
						}
					}
				}
			} catch (IOException ioe) {
				uploadDoneCallback(null);
			} finally {
				try {
					if (null != sockInputStream) {
						sockInputStream.close();
					}
				} catch (IOException ioe) {
					sockInputStream = null;
				}
			}
		}
	}

	class SftpUploadWorker extends SwingWorker<SftpUtil.RespHeader, Integer> {

		long countBytesCurrentSession;

		SftpUploadWorker() {
			countBytesCurrentSession = 0;
		}

		@Override
		protected SftpUtil.RespHeader doInBackground() throws Exception {

			browseButton.setEnabled(false);
			uploadButton.setEnabled(false);
			deleteButton.setEnabled(false);

			Socket sock = null;
			OutputStream sockOutputStream = null;
			InputStream sockInputStream = null;
			FileInputStream fis = null;
			SftpUtil.ChunkLimitInputStream chunkedStream = null;
			try {
				sock = new Socket(HOST, PORT);
				sock.setPerformancePreferences(SOCK_PF_CT, SOCK_PF_LL,
						SOCK_PF_HB);
				sock.setKeepAlive(true);
				sock.setSoTimeout(READ_TIMEOUT);
				sock.setTcpNoDelay(true);

				sockOutputStream = sock.getOutputStream();

				Thread recevieThread = new ReceiveThread(sock.getInputStream());
				recevieThread.start();

				long lastUploadedBytes = currentResp.files.get(0).uploadedBytes;
				long fileLen = uploadTargetFile.length();

				SftpUtil.ReqHeader header = SftpUtil.ReqHeader.create(
						currentResp.files.get(0).csid.trim(),
						currentResp.token.trim(), fileLen, fileLen
								- lastUploadedBytes);
				SftpUtil.sendReq(sockOutputStream, header);

				SftpUtil.sendCmd(sockOutputStream, SftpUtil.CMD_STX);

				fis = new FileInputStream(uploadTargetFile);
				fis.skip(lastUploadedBytes);
				chunkedStream = new SftpUtil.ChunkLimitInputStream(fis,
						SftpUtil.CHUNK_SIZE);
				byte[] buf = new byte[10240];
				int countOfClip = 0;

				// int countOfChunk = 0;
				while ((countOfClip = chunkedStream.read(buf)) > -1) {

					if (0 < countOfClip) {
						// countOfChunk += countOfClip;
						countBytesCurrentSession += countOfClip;
						sockOutputStream.write(buf, 0, countOfClip);
						sockOutputStream.flush();
					}

					if (chunkedStream.isChunkLimit()) {
						SftpUtil.sendCmd(sockOutputStream, SftpUtil.CMD_ETB);
						// countOfChunk = 0;
						chunkedStream.resetChunkLimit();
					}

					publish(calcProgress(lastUploadedBytes
							+ countBytesCurrentSession, fileLen));
				}

				SftpUtil.sendCmd(sockOutputStream, SftpUtil.CMD_EOT);

				recevieThread.join();

			} catch (IOException ioe) {
				ioe.printStackTrace();
			} finally {
				try {
					if (null != sockOutputStream) {
						sockOutputStream.close();
					}
				} catch (IOException ioe) {
					sockOutputStream = null;
				}
				try {
					if (null != sockInputStream) {
						sockInputStream.close();
					}
				} catch (IOException ioe) {
					sockInputStream = null;
				}
				try {
					if (null != chunkedStream) {
						chunkedStream.close();
					}
				} catch (IOException ioe) {
					chunkedStream = null;
				}
				try {
					if (null != fis) {
						fis.close();
					}
				} catch (IOException ioe) {
					fis = null;
				}
				try {
					if (null != sock) {
						sock.close();
					}
				} catch (IOException ioe) {
					sock = null;
				}
			}

			return null;
		}

		@Override
		protected void process(List<Integer> chunks) {
			for (Integer p : chunks) {
				progressBar.setValue(p);
			}
		}

		@Override
		protected void done() {
			// try {
			// //progressBar.setValue(calcProgress());
			// uploadDoneCallback(get());
			// } catch (Exception e) {
			// uploadDoneCallback(null);
			// }
		}
	}

	int calcProgress(float uploaded, float total) {
		return (int) (uploaded / total * 100);
	}

	class BrowseButtonActionListener implements ActionListener {
		@Override
		public void actionPerformed(ActionEvent event) {
			fileChooser = new JFileChooser();
			fileChooser.setMultiSelectionEnabled(false);
			fileChooser.setFileSelectionMode(JFileChooser.FILES_ONLY);
			if (JFileChooser.APPROVE_OPTION == fileChooser.showOpenDialog(null)) {
				jquery$Val(uploadFileElementId, BLANK_STR);
				uploadFileSelected(fileChooser.getSelectedFile());
			}
		}
	}

	class UploadButtonActionListener implements ActionListener {
		@Override
		public void actionPerformed(ActionEvent event) {
			jquery$Val(uploadFileElementId, BLANK_STR);
			sftpUploadWorker = new SftpUploadWorker();
			sftpUploadWorker.execute();
		}
	}

	class DeleteButtonActionListener implements ActionListener {
		@Override
		public void actionPerformed(ActionEvent event) {
			jquery$Val(uploadFileElementId, BLANK_STR);
			deleteCallback(httpDelete(initDeleteUri(currentResp)));
		}
	}

	public void alert(String msg) {
		JOptionPane.showMessageDialog(this, msg);
	}

	public boolean confirm(String msg) {
		return JOptionPane.YES_OPTION == JOptionPane.showConfirmDialog(this,
				msg) ? true : false;
	}

	@Override
	public void stop() {
		super.stop();
//		try {
//			HTTP_CLIENT.close();
//		} catch (IOException ioe) {
//		} finally {
//			try {
//				if (null != HTTP_CLIENT) {
//					HTTP_CLIENT.close();
//				}
//			} catch (Exception e) {
//				HTTP_CLIENT = null;
//			}
//		}
	}

	void jquery$Val(String eleId, String val) {
//		JSObject win = JSObject.getWindow(this);
//		win.eval("$('#" + eleId + "').val('" + val.trim() + "');");
	}

	public static class JsonResponse {
		public String token;
		public String flag;
		public String csId;
		public List<FileRefrence> files = new ArrayList<FileRefrence>();

		JsonResponse addFile(FileRefrence file) {
			files.add(file);
			return this;
		}
	}

	public static class FileRefrence {
		public String csid;
		public String name;
		public String url;
		public String thumbnailUrl;
		public long size;
		public long uploadedBytes;
		public String error;
		public String mimeType;
	}

	public static class FileAnalyse {

		private static final long MODULUS_B = 0;
		private static final long MODULUS_KB = 10;
		private static final long MODULUS_MB = 20;
		private static final long MODULUS_GB = 30;
		private static final long MODULUS_TB = 40;
		private static final long SIZE_B = 1;
		private static final long SIZE_KB = 1 << MODULUS_KB;
		private static final long SIZE_MB = 1 << MODULUS_MB;
		private static final long SIZE_GB = 1 << MODULUS_GB;
		private static final long SIZE_TB = SIZE_GB << MODULUS_KB;

		private static final String NUM_POINT = ".";
		private static final int DECIMAL_LIMIT = 3;

		private static final String UNIT_TB = "T ";
		private static final String UNIT_GB = "G ";
		private static final String UNIT_MB = "M ";
		private static final String UNIT_KB = "K ";
		private static final String UNIT_B = "B ";

		private static final long[] MODULUS = { MODULUS_TB, MODULUS_GB,
				MODULUS_MB, MODULUS_KB, MODULUS_B };
		private static final long[] SIZES = { SIZE_TB, SIZE_GB, SIZE_MB,
				SIZE_KB, SIZE_B };
		private static final String[] UNITS = { UNIT_TB, UNIT_GB, UNIT_MB,
				UNIT_KB, UNIT_B };

		private static final String ZERO_SEQ_TEMPLATE = "000";

		private static final String ZERO_BYTE = "0B";

		public static String number(long len) {
			if (1 > len)
				return ZERO_BYTE;
			boolean flag = false;
			StringBuilder integer = new StringBuilder();
			StringBuilder decimal = new StringBuilder();
			String unit = null;
			long x = 0;
			for (int i = 0; i < SIZES.length; i++) {
				x = len >> MODULUS[i];
				if (x < 1)
					continue;
				if (flag) {
					char[] sx = String.valueOf(x).toCharArray();
					char[] subDecimal = ZERO_SEQ_TEMPLATE.toCharArray();
					int limit = sx.length > subDecimal.length ? subDecimal.length
							: sx.length;
					for (int k = 0; k < sx.length && k < subDecimal.length; k++) {
						subDecimal[subDecimal.length - limit + k] = sx[k];
					}
					decimal.append(subDecimal);
					if (decimal.length() > 1)
						break;
				} else {
					integer.append(x);
					unit = UNITS[i];
					flag = true;
				}
				len = len - (x * SIZES[i]);
			}
			return integer.toString()
					+ (decimal.length() > 0 ? NUM_POINT
							+ (decimal.length() > 1 ? decimal.substring(0,
									DECIMAL_LIMIT) : decimal.toString()) : "")
					+ unit;
		}
	}
}


text:
import logging

class CoreException(Exception):
    def __init__(self):
        self._logged = False

    def log(self, logh, msg, level=logging.ERROR):
        logh.log(level, msg)
        self._logged = True

# Derived exceptions
class NotImplementedError(CoreException):
    pass

class NoProviderAvailableError(CoreException):
    pass


text:
import reducer from '../reducer'
import * as actions from '../actions'

const df = {
  illusts: [],
}

test('default action', () => {
  // $FlowFixMe
  expect(reducer(df, { type: 'default action' })).toMatchSnapshot()
})

test('POPOVER_SUCCESS', () => {
  expect(reducer(df, actions.popoverSuccess([1, 2, 3]))).toMatchSnapshot()
})

test('CLEAR', () => {
  const s = { illusts: [1, 2, 3] }
  expect(reducer(s, actions.clear())).toMatchSnapshot()
})


text:
package client

import (
	"gopkg.in/validator.v2"
)

type TemplateListing struct {
	Name string `json:"name" validate:"nonzero"`
}

func (s TemplateListing) Validate() error {

	return validator.Validate(s)
}


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
in Li, Miao, Zhang & Liu, Mycol. Res. 107(7): 890 (2003)

#### Original name
Monacrosporium janus S.D. Li & Xing Z. Liu

### Remarks
null


text:
<?php
return array(
	'login' => 'connect/login/{provider}',
	'endpoint' => 'connect/endpoint',
);


text:
package com.palantir.atlasdb.keyvalue.api.cache;

import com.google.common.collect.ImmutableMap;
import com.google.common.collect.ImmutableSet;
import com.google.common.util.concurrent.ListenableFuture;
import com.palantir.atlasdb.futures.AtlasFutures;
import com.palantir.atlasdb.keyvalue.api.Cell;
import com.palantir.atlasdb.keyvalue.api.ColumnSelection;
import com.palantir.atlasdb.keyvalue.api.RowResult;
import com.palantir.atlasdb.keyvalue.api.TableReference;
import com.palantir.lock.watch.CommitUpdate;
import java.util.Map;
import java.util.NavigableMap;
import java.util.Set;
import java.util.function.Function;

public final class NoOpTransactionScopedCache implements TransactionScopedCache {
    private NoOpTransactionScopedCache() {}

    public static TransactionScopedCache create() {
        return new NoOpTransactionScopedCache();
    }

    @Override
    public void write(TableReference tableReference, Map<Cell, byte[]> values) {}

    @Override
    public void delete(TableReference tableReference, Set<Cell> cells) {}

    @Override
    public Map<Cell, byte[]> get(
            TableReference tableReference,
            Set<Cell> cells,
            Function<Set<Cell>, ListenableFuture<Map<Cell, byte[]>>> valueLoader) {
        return AtlasFutures.getUnchecked(getAsync(tableReference, cells, valueLoader));
    }

    @Override
    public ListenableFuture<Map<Cell, byte[]>> getAsync(
            TableReference tableReference,
            Set<Cell> cells,
            Function<Set<Cell>, ListenableFuture<Map<Cell, byte[]>>> valueLoader) {
        return valueLoader.apply(cells);
    }

    @Override
    public NavigableMap<byte[], RowResult<byte[]>> getRows(
            TableReference tableRef,
            Iterable<byte[]> rows,
            ColumnSelection columnSelection,
            Function<Set<Cell>, Map<Cell, byte[]>> cellLoader,
            Function<Iterable<byte[]>, NavigableMap<byte[], RowResult<byte[]>>> rowLoader) {
        return rowLoader.apply(rows);
    }

    @Override
    public void finalise() {}

    @Override
    public ValueDigest getValueDigest() {
        return ValueDigest.of(ImmutableMap.of());
    }

    @Override
    public HitDigest getHitDigest() {
        return HitDigest.of(ImmutableSet.of());
    }

    @Override
    public TransactionScopedCache createReadOnlyCache(CommitUpdate commitUpdate) {
        return ReadOnlyTransactionScopedCache.create(NoOpTransactionScopedCache.create());
    }
}


text:
package org.springframework.android.reader;

import android.content.Intent;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;

/**
 * @author Roy Clarkson
 */
public class RssActivity extends AbstractMenuActivity {

	// ***************************************
	// AbstractMenuActivity methods
	// ***************************************
	@Override
	protected String getDescription() {
		return getResources().getString(R.string.text_rss_description);
	}

	@Override
	protected String[] getMenuItems() {
		return getResources().getStringArray(R.array.rss_activity_options);
	}

	@Override
	protected OnItemClickListener getMenuOnItemClickListener() {
		return new AdapterView.OnItemClickListener() {
			public void onItemClick(AdapterView<?> parentView, View childView, int position, long id) {
				Intent intent = new Intent();

				switch (position) {
				case 0:
					intent.setClass(parentView.getContext(), RssSyndFeedActivity.class);
					startActivity(intent);
					break;
				case 1:
					intent.setClass(parentView.getContext(), RssChannelActivity.class);
					startActivity(intent);
					break;
				default:
					break;
				}
			}
		};
	}
}


text:
namespace bpy = boost::python;
using namespace foundation;
using namespace renderer;
using namespace std;

namespace
{
    auto_release_ptr<Camera> create_camera(
        const string&       model,
        const string&       name,
        const bpy::dict&    params)
    {
        CameraFactoryRegistrar factories;
        const ICameraFactory* factory = factories.lookup(model.c_str());

        if (factory)
            return factory->create(name.c_str(), bpy_dict_to_param_array(params));
        else
        {
            PyErr_SetString(PyExc_RuntimeError, "Camera model not found");
            bpy::throw_error_already_set();
        }

        return auto_release_ptr<Camera>();
    }

    TransformSequence* camera_get_transform_sequence(Camera* camera)
    {
        return &(camera->transform_sequence());
    }
}

void bind_camera()
{
    bpy::class_<Camera, auto_release_ptr<Camera>, bpy::bases<Entity>, boost::noncopyable>("Camera", bpy::no_init)
        .def("get_model_metadata", &detail::get_entity_model_metadata<CameraFactoryRegistrar>).staticmethod("get_model_metadata")
        .def("get_input_metadata", &detail::get_entity_input_metadata<CameraFactoryRegistrar>).staticmethod("get_input_metadata")
        .def("__init__", bpy::make_constructor(create_camera))
        .def("get_model", &Camera::get_model)
        .def("transform_sequence", camera_get_transform_sequence, bpy::return_value_policy<bpy::reference_existing_object>())
        .def("get_shutter_open_time", &Camera::get_shutter_open_time)
        .def("get_shutter_close_time", &Camera::get_shutter_close_time)
        .def("get_shutter_middle_time", &Camera::get_shutter_middle_time)
        ;
}


text:
"use strict";

Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.default = _default;

function _default() {
  var eventTarget = document.body.appendChild(document.createComment(''));
  var eventListener, eventKey;
  return {
    on: function on(type, listener, key) {
      eventKey = key;

      eventListener = function eventListener(e) {
        listener(e.detail);
      };

      eventTarget.addEventListener(type, eventListener);
    },
    once: function once(type, listener, key) {
      eventKey = key;

      eventListener = function eventListener(e) {
        listener(e.detail);
      };

      eventTarget.addEventListener(type, eventListener, {
        once: true
      });
    },
    off: function off(type, key) {
      if (eventListener && eventKey === key) {
        eventTarget.removeEventListener(type, eventListener);
      }
    },
    emit: function emit(type, detail) {
      eventTarget.dispatchEvent(new CustomEvent(type, {
        detail: detail
      }));
    }
  };
}


text:
using System;
using System.Collections.Generic;
using System.Text;

namespace PmSys.Components
{

    /// <summary>
    /// 系统信息类
    /// </summary>
    [Serializable]
    public class sys_SystemInfoTable
    {

        #region "Private Variables"
        private string _DB_Option_Action_;  // 操作方法 Insert:增加 Update:修改 Delete:删除
        private int _SystemID = 0;  // 自动ID
		private string _S_Name = "签证管理系统";  // 系统名称
        private string _S_Version = "1.0.7";  // 版本号
        private string _S_Licensed = ""; //序列号
        private sys_ConfigDataTable _S_SystemConfigData = new sys_ConfigDataTable(); //系统配置信息
        private sys_FrameWorkInfoTable _S_FrameWorkInfo = new sys_FrameWorkInfoTable();

        #endregion

        #region "Public Variables"
        /// <summary>
        /// 操作方法 Insert:增加 Update:修改 Delete:删除
        /// </summary>
        public string DB_Option_Action_
        {
            set { this._DB_Option_Action_ = value; }
            get { return this._DB_Option_Action_; }
        }

        /// <summary>
        /// 自动ID
        /// </summary>
        public int SystemID
        {
            set { this._SystemID = value; }
            get { return this._SystemID; }
        }

        /// <summary>
        /// 系统名称
        /// </summary>
        public string S_Name
        {
            set { this._S_Name = value; }
            get { return this._S_Name; }
        }

        /// <summary>
        /// 版本号
        /// </summary>
        public string S_Version
        {
            set { this._S_Version = value; }
            get { return this._S_Version; }
        }

        /// <summary>
        /// 序列号
        /// </summary>
        public string S_Licensed
        {
            set {
                this._S_Licensed = value;
                _S_FrameWorkInfo.S_Licensed = value;
            }
            get { return this._S_Licensed; }
        }

        /// <summary>
        /// 系统配置信息
        /// </summary>
        public sys_ConfigDataTable S_SystemConfigData
        {
            get{
                return _S_SystemConfigData;
            }
            set{
                _S_SystemConfigData = value;
            }
        }
        /// <summary>
        /// 系统版本信息
        /// </summary>
        public sys_FrameWorkInfoTable S_FrameWorkInfo
        {
            get {
                return _S_FrameWorkInfo;
            }
            set {
                _S_FrameWorkInfo = value;
            }
        }
        #endregion

    }
}


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

var app = express();
/* GET home page. */
router.get('/', function(req, res, next) {
  res.render('index', { title: 'Express' });
});

router.use(function timeLog(req,res,next){
  console.log('Time: ', Date.now())
  next();
})

router.get('/about',function(req,res){
  res.send('about biiikadsjfkldsjklfjsdlf')
})

module.exports = router;


text:
require "active_support/concern"
require "active_support/core_ext/object/blank"
require "active_model/naming"
require "active_model/conversion"

module Ashikawa
  module AR
    module Base
      extend ActiveSupport::Concern

      included do
        class_eval do
          extend ActiveModel::Naming
          include ActiveModel::Conversion

          attr_accessor :id
          attr_accessor :status

          def self.collection_name
            self.model_name.collection
          end

          def self.collection
            database[collection_name]
          end

          def self.database
            Setup.databases[:default]
          end

          def self.from_raw_document(raw_document)
            document = self.new raw_document.to_hash
            document.id = raw_document.id
            document.status = :persisted
            document
          end

          def self.from_raw_documents(raw_documents)
            raw_documents.map do |raw_document|
              from_raw_document raw_document
            end
          end
        end
      end
    end
  end
end


text:
require_relative 'spec_helper'
#######################################################
describe Mastermind::GameEngine do

  before :each do
    @game_engine = Mastermind::GameEngine.new
    @message = Mastermind::Message.new
  end
  describe "#new" do
    it "returns a new GameEngine object" do
      expect(@game_engine).to be_a Mastermind::GameEngine
    end
  end

  describe"#start" do
    it "should print the two messages welcome and request" do
      allow(@game_engine).to receive(:user_input).and_return(nil)
      expect{@game_engine.start}.to output(/WELCOME/).to_stdout
      expect{@game_engine.start}.to output(/\(p\)lay/).to_stdout
      # puts "finished start"
    end
  end

  describe"#user_input" do
    it "should check for user choice and show quit message " do
      allow(@game_engine).to receive(:gets).and_return("q")
      allow(@game_engine).to receive(:puts).and_return(nil)
      allow(@message).to receive(:quit_msg).and_return(nil)
      expect(@game_engine.user_input).to be nil
      # puts "started user_input"
    end

    it "should check for user input and play game " do
      allow(@game_engine).to receive(:play).and_return(nil)
      allow(@game_engine).to receive(:gets).and_return("p")
      allow(@game_engine).to receive(:puts).and_return(nil)
      expect(@game_engine.user_input).to be nil
    end

    it "should check for user choice and show instruction message " do
      allow(@game_engine).to receive(:gets).and_return("i")
      allow(@game_engine).to receive(:puts).and_return(nil)
      expect(@game_engine.user_input(true)).to be nil
    end
  end

  describe"#game_level" do
    it "should throw error if called without an argument" do
      expect{@game_engine.game_level}.to raise_error (ArgumentError)
    end
    it "should return the advanced level according to user choice" do
      expect(@game_engine.game_level("a")).to eql(:advanced)
    end
    it "should return the beginner level according to user choice" do
      expect(@game_engine.game_level("b")).to eql(:beginner)
    end
    it "should return the medium level according to user choice" do
      expect(@game_engine.game_level("m")).to eql(:medium)
    end
  end

  describe"#play" do
    it "should print the level message and call code generator" do
      allow(@game_engine).to receive(:puts).and_return(nil)
      allow(@game_engine.codegen).to receive(:code_generator).and_return(nil)
      allow(@game_engine).to receive(:gets).and_return("b")
      expect(@game_engine.play).to be nil
    end
  end

end
########################################################


text:
<?php /* @var $this Controller */ ?>
<?php $this->beginContent('//layouts/main'); ?>

						<img src="<?php echo Yii::app()->request->baseUrl; ?>/images/utplogo.png">

						<button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#navbar" aria-expanded="false" aria-controls="navbar">
				            Toggle navigation

				        </button>

							<?php $this->widget('zii.widgets.CMenu',array(
								'encodeLabel' => false,
								'activeCssClass'=>'active',
			  					'activateParents'=>true,
								'htmlOptions'=>array("class"=>"nav navbar-nav"),
								'submenuHtmlOptions'=>array("class"=>"dropdown-menu menu-secundario"),
								'items'=>array(
									array(
										'label'=>'Inicio',
										'url'=>array('/site/index')
									),
									array(
										'label'=>'Mantenimiento ',
										'url'=>array('#'),
										'linkOptions'=>array('class'=>'dropdown-toggle', 'data-toggle'=>'dropdown', 'role'=>'button', 'aria-haspopup'=>'true', 'aria-expanded'=>'false'),
								      	'itemOptions'=>array('class'=>'dropdown'),

								      	'items'=>array(
								      		array('label'=>'Alumno', 'url'=>array('/alumno/admin')),
								        	array('label'=>'Carrera', 'url'=>array('/carrera/admin')),
								        	array('label'=>'Ciclo', 'url'=>array('/ciclo/admin')),
								        	array('label'=>'Curso', 'url'=>array('/curso/admin')),
								        	array('label'=>'Sección', 'url'=>array('/seccion/admin')),
								        	array('label'=>'Profesor', 'url'=>array('/profesor/admin')),
								        	array('label'=>'Rol', 'url'=>array('/rol/admin')),
								        	array('label'=>'Usuario', 'url'=>array('/usuario/admin')),
								      	),
									),

									array(
										'label'=>'Programación de Curso',
										'url'=>array('/cursoprogramado/index',
										'view'=>'about')
									),
									array(
										'label'=>'Matrícula',
										'url'=>array('/site/page',
										'view'=>'about')
									),
									/*array(
										'label'=>'Contact',
										'url'=>array('/site/contact')
									),*/
									array(
										'label'=>'Login',
										'url'=>array('/site/login'),
										'visible'=>Yii::app()->user->isGuest),
									array(
										'label'=>'Logout ('.Yii::app()->user->name.')',
										'url'=>array('/site/logout'),
										'visible'=>!Yii::app()->user->isGuest)
								),
							)); ?>

Bienvenido

Maritza Milla Tarazona

ADMINISTRADOR

Último Acceso: <?php echo date('d-m-y'); ?>

			<?php if(isset($this->breadcrumbs)):?>
				<?php $this->widget('zii.widgets.CBreadcrumbs', array(
					'htmlOptions'=>array("class"=>"breadcrumb"),
					'links'=>$this->breadcrumbs,
				)); ?>
			<?php endif?>

			    	<button type="button" class="btn btn-primary btn-xs" data-toggle="offcanvas">Perfil</button>

				<?php
					$this->beginWidget('zii.widgets.CPortlet', array(
						'title'=>'',
					));
					$this->widget('zii.widgets.CMenu', array(
						'encodeLabel' => false,
						'items'=>$this->menu,
						'htmlOptions'=>array('class'=>'nav nav-pills'),
					));
					$this->endWidget();
				?>

					<?php echo $content; ?>

<?php $this->endContent(); ?>


text:
'use strict'

const Code = require('code')
const expect = Code.expect
const Got = require('got')
const Hub = require('./../packages/websub-hub')
const MongoInMemory = require('mongo-in-memory')
const Sinon = require('sinon')
const Nock = require('nock')
const { parse } = require('url')
const delay = require('delay')
const MongoClient = require('mongodb').MongoClient

describe('TTL subscriptions', function() {
  // The background task that removes expired documents runs every 60 seconds.
  // As a result, documents may remain in a collection during the period between the expiration of the document and the running of the background task.
  this.timeout(65000)

  const PORT = 3000
  let hub
  let mongoInMemory
  let topic = ''
  let counter = 0

  before(done => {
    mongoInMemory = new MongoInMemory()
    mongoInMemory.start(() => done())
  })

  before(function() {
    hub = Hub({
      logLevel: 'debug',
      mongo: {
        url: mongoInMemory.getMongouri('hub')
      }
    })
    return hub.listen()
  })

  before(done => {
    MongoClient.connect(
      mongoInMemory.getMongouri('hub'),
      function onConnect(err, client) {
        if (err) {
          done(err)
          return
        }
        const db = client.db('admin')
        db.command(
          { setParameter: 1, ttlMonitorSleepSecs: 5 },
          (err, result) => {
            if (err) {
              done(err)
              return
            }
            done()
          }
        )
      }
    )
  })

  // In order to produce unique subscriptions
  beforeEach(() => {
    topic = `http://testblog-n${counter++}.de`
  })

  after(function(done) {
    hub.close().then(() => {
      mongoInMemory.stop(() => done())
    })
  })

  it('Should delete subscription when lease_seconds is over', async function() {
    const callbackUrl = 'http://127.0.0.1:3001'
    const createSubscriptionBody = {
      'hub.callback': callbackUrl,
      'hub.mode': 'subscribe',
      'hub.topic': topic + '/feeds',
      'hub.lease_seconds': 1
    }

    const verifyIntentMock = Nock(callbackUrl)
      .get('/')
      .query(true)
      .reply(uri => {
        const query = parse(uri, true).query
        return [
          200,
          { ...createSubscriptionBody, 'hub.challenge': query['hub.challenge'] }
        ]
      })

    let response = await Got.post(`http://localhost:${PORT}/`, {
      form: true,
      body: createSubscriptionBody
    })

    expect(response.statusCode).to.be.equals(200)

    await delay(60000)

    response = await Got.get(`http://localhost:${PORT}/subscriptions`, {
      json: true
    })

    console.log(response.body)
    expect(response.body.length).to.be.equals(0)

    verifyIntentMock.done()
  })

  it('Subscriber can re-request the subscription in order to renew the subscription', async function() {})
})


text:
package com.zms.zpc.emulator.board.time;

import com.zms.zpc.emulator.board.*;
import com.zms.zpc.emulator.board.helper.BaseIODevice;
import com.zms.zpc.emulator.board.pci.PCSpeaker;

import java.io.*;

public class IntervalTimer extends BaseIODevice {

    private static final int RW_STATE_LSB = 1;
    private static final int RW_STATE_MSB = 2;
    private static final int RW_STATE_WORD = 3;
    private static final int RW_STATE_WORD_2 = 4;
    private static final int MODE_INTERRUPT_ON_TERMINAL_COUNT = 0;
    private static final int MODE_HARDWARE_RETRIGGERABLE_ONE_SHOT = 1;
    private static final int MODE_RATE_GENERATOR = 2;
    private static final int MODE_SQUARE_WAVE = 3;
    private static final int MODE_SOFTWARE_TRIGGERED_STROBE = 4;
    private static final int MODE_HARDWARE_TRIGGERED_STROBE = 5;
    private static final int CONTROL_ADDRESS = 3;
    public static final int PIT_FREQ = /*Option.useBochs.isSet() ? 1193181 :*/ 1193182;
    private TimerChannel[] channels;
    private InterruptController irqDevice;
    private Clock timingSource;
    public PCSpeaker speaker;
    private boolean madeNewTimer;
    private boolean ioportRegistered;
    private int ioPortBase;
    private int irq;
    //private BochsPIT bochs;

    public MotherBoard mb;

    public int[] getState() {
        int[] state = new int[3 * 4];
        channels[0].getState(state, 0);
        channels[1].getState(state, 4);
        channels[2].getState(state, 8);
        return state;
    }

    private static final long scale64(long input, int multiply, int divide) {
        long rl = (0xffffffffl & input) * multiply;
        long rh = (input >>> 32) * multiply;

        rh += (rl >> 32);

        long resultHigh = 0xffffffffl & (rh / divide);
        long resultLow = 0xffffffffl & ((((rh % divide) << 32) + (rl & 0xffffffffl)) / divide);

        return (resultHigh << 32) | resultLow;
    }

    /**
     * Construct a new Interval Timer which will register at ioports
     * ioPort to ioPort+3.  Interrupt requests will be
     * sent on the supplied channel number.
     *
     * @param ioPort ioport base address.
     * @param irq    interrupt channel number.
     */
    public IntervalTimer(MotherBoard mb, int ioPort, int irq) {
        this.mb = mb;
        this.irq = irq;
        ioPortBase = ioPort;
        /*if (Option.useBochs.isSet()) {
            bochs = new BochsPIT(Option.ips.intValue(150000000));
        }*/
        this.init();
    }

    protected void init() {
        for (int address : ioPortsRequested()) {
            mb.ios.register(address, this);
        }
        this.irqDevice = mb.pic;
        this.timingSource = mb.vc;
        if (channels == null) {
            channels = new TimerChannel[3];
            for (int i = 0; i < channels.length; i++) {
                channels[i] = new TimerChannel(i);
            }
            channels[0].setIRQTimer(timingSource.newTimer(channels[0]));
            channels[0].setIRQ(irq);
        }
        ioportRegistered = true;
    }

    public void saveState(DataOutput output) throws IOException {
        output.writeInt(channels.length);
        for (TimerChannel channel : channels) {
            channel.saveState(output);
        }
    }

    public void loadState(DataInput input) throws IOException {
        madeNewTimer = false;
        ioportRegistered = false;
        int len = input.readInt();
        channels = new TimerChannel[len];
        for (int i = 0; i < channels.length; i++) {
            //if (i>10) System.exit(0);
            channels[i] = new TimerChannel(i);
            channels[i].loadState(input);
        }
    }

    public int[] ioPortsRequested() {
        return new int[]{ioPortBase, ioPortBase + 1, ioPortBase + 2, ioPortBase + 3};
    }

    public int ioPortRead32(int address) {
        return (ioPortRead16(address) & 0xffff) | ((ioPortRead16(address + 2) << 16) & 0xffff0000);
    }

    public int ioPortRead16(int address) {
        return (ioPortRead8(address) & 0xff) | ((ioPortRead8(address + 1) << 8) & 0xff00);
    }

    public int ioPortRead8(int address) {
        if ((address & 3) == 3)
            return 0; // read from control word register
        return channels[address & 0x3].read();
    }

    public void ioPortWrite32(int address, int data) {
        this.ioPortWrite16(address, 0xffff & data);
        this.ioPortWrite16(address + 2, 0xffff & (data >>> 16));
    }

    public void ioPortWrite16(int address, int data) {
        this.ioPortWrite8(address, 0xff & data);
        this.ioPortWrite8(address + 1, 0xff & (data >>> 8));
    }

    public void ioPortWrite8(int address, int data) {
        data &= 0xff;
        address &= 0x3;
        if (address == CONTROL_ADDRESS) { //writing control word
            int channel = data >>> 6;
            if (channel == 3) { // read back command
                for (channel = 0; channel < 3; channel++) {
                    if (0 != (data & (2 << channel))) // if channel enabled
                    {
                        channels[channel].readBack(data);
                    }
                }
            } else {
                channels[channel].writeControlWord(data);
            }
        } else //writing to a channels counter
        {
            channels[address].write(data);
            if (address == 2) //notify PCSpeaker of timer change
            {
                speaker.play();
            }
        }
    }

    public void reset() {
        /*irqDevice = null;
        timingSource = null;
        ioportRegistered = false;*/
    }

    /**
     * Get the output pin state of the specified channel.
     *
     * @param channel selected channel index.
     * @return counter output pin level.
     */
    public int getOut(int channel) {
        return channels[channel].getOut(getTime());
    }

    public int getMode(int channel) {
        return channels[channel].getMode();
    }

    public int getInitialCount(int channel) {
        return channels[channel].getInitialCount();
    }

    /**
     * Get the gate pin state of the specified channel.
     *

     * The gate pin indicates whether the selected channel is enabled or
     * disabled.  A logic high level indicates enabled and logic low indicates
     * disabled.
     *
     * @param channel selected channel index.
     * @return counter gate pin level.
     */
    public boolean getGate(int channel) {
        return channels[channel].gate;
    }

    /**
     * Set the gate pin state of the specified channel.
     *

     * Broadly speaking setting the gate low will disable the timer, and setting
     * it high will enable the timer, although exact behaviour is dependent on
     * the current channel mode.
     *
     * @param channel selected channel index.
     * @param value   required gate status.
     */
    public void setGate(int channel, boolean value) {
        channels[channel].setGate(value);
    }

    private long getTime() {
        return timingSource.getEmulatedMicros();
    }

    private long getTickRate() {
        return 1000000; // use micro second units
    }

    private int conversionFactor() {
        return (int) (timingSource.getTickRate() / getTickRate());
    }

    enum RW_Status {LSByte, MSByte, LSByte_Multple, MSByte_multiple}

    public class TimerChannel implements TimerResponsive {
        private int countValue; // U32
        private int outputLatch; // U16
        private int inputLatch; // U16

        private boolean countLatched_LSB;
        private boolean countLatched_MSB;
        private boolean statusLatched;

        private boolean nullCount;
        private boolean gate;

        private int statusLatch; // U8
        private RW_Status readState = RW_Status.LSByte;
        private RW_Status writeState = RW_Status.LSByte;
        private int rwMode;// 2 bits from command word register
        private int mode; // 3 bits from command word register
        private boolean bcd; /* uimplemented */

        private long countStartCycles; // currently these are microseconds
        /* irq handling */
        private long nextChangeTime;
        private Timer irqTimer;
        private int irq;

        public TimerChannel(int index) {
            mode = MODE_SQUARE_WAVE;
            gate = true;
            loadCount(0);
            nullCount = true;
        }

        private void getState(int[] buf, int start) {
            buf[start] = getCount() % 0x10000;
            buf[start + 1] = gate ? 1 : 0;
            buf[start + 2] = getOut(getTime());
            buf[start + 3] = 0;
        }

        public void saveState(DataOutput output) throws IOException {
            output.writeInt(countValue);
            output.writeInt(outputLatch);
            output.writeInt(inputLatch);
            output.writeInt((countLatched_MSB ? 2 : 0) | (countLatched_LSB ? 1 : 0));
            output.writeBoolean(statusLatched);
            output.writeBoolean(gate);
            output.writeInt(statusLatch);
            output.writeInt(readState.ordinal());
            output.writeInt(writeState.ordinal());
            output.writeInt(rwMode);
            output.writeInt(mode);
            output.writeInt(bcd ? 1 : 0);
            output.writeLong(countStartCycles);
            output.writeLong(nextChangeTime);
            if (irqTimer == null) {
                output.writeInt(0);
            } else {
                output.writeInt(1);
                irqTimer.saveState(output);
            }
        }

        public void loadState(DataInput input) throws IOException {
            countValue = input.readInt();
            outputLatch = input.readInt();
            inputLatch = input.readInt();
            int cl = input.readInt();
            countLatched_LSB = (cl & 1) != 0;
            countLatched_MSB = (cl & 2) != 0;
            statusLatched = input.readBoolean();
            gate = input.readBoolean();
            statusLatch = input.readInt();
            readState = RW_Status.values()[input.readInt()];
            writeState = RW_Status.values()[input.readInt()];
            rwMode = input.readInt();
            mode = input.readInt();
            bcd = input.readInt() != 0;
            countStartCycles = input.readLong();
            nextChangeTime = input.readLong();
            int test = input.readInt();
            if (test == 1) {
                irqTimer = timingSource.newTimer(this);
                irqTimer.loadState(input);
            }
        }

        public int read() {
            if (statusLatched) {
                if (countLatched_MSB && (readState == RW_Status.MSByte_multiple))
                    throw new IllegalStateException("status is latched and count half read");
                statusLatched = false;
                return statusLatch;
            }
            // latched count read
            if (countLatched_LSB) {
                // read LSB
                if (readState == RW_Status.LSByte_Multple) {
                    readState = RW_Status.MSByte_multiple;
                }
                countLatched_LSB = false;
                return outputLatch & 0xff;
            }
            if (countLatched_MSB) {
                // read MSB
                if (readState == RW_Status.MSByte_multiple) {
                    readState = RW_Status.LSByte_Multple;
                }
                countLatched_MSB = false;
                return (outputLatch >> 8) & 0xff;
            }
            if (!((readState == RW_Status.MSByte) || (readState == RW_Status.MSByte_multiple))) {
                // read LSB
                if (readState == RW_Status.LSByte_Multple)
                    readState = RW_Status.MSByte_multiple;
                return getCount() & 0xff;
            } else {
                if (readState == RW_Status.MSByte_multiple)
                    readState = RW_Status.LSByte_Multple;
                return (getCount() >> 8) & 0xff;
            }
        }

        public void readBack(int data) {
            if (0 == (data & 0x20)) //latch count
            {
                latchCount();
            }

            if (0 == (data & 0x10)) //latch status
            {
                latchStatus();
            }
        }

        private void latchCount() {
            // do nothing if previous latch state hasn't been read
            if (!countLatched_LSB && !countLatched_MSB) {
                switch (readState) {
                    case MSByte:
                        outputLatch = 0xffff & getCount();
                        countLatched_MSB = true;
                        break;
                    case LSByte:
                        outputLatch = 0xffff & getCount();
                        countLatched_LSB = true;
                        break;
                    case LSByte_Multple:
                        outputLatch = 0xffff & getCount();
                        countLatched_LSB = true;
                        countLatched_MSB = true;
                        break;
                    case MSByte_multiple:
                        readState = RW_Status.LSByte_Multple;
                        outputLatch = 0xffff & getCount();
                        countLatched_LSB = true;
                        countLatched_MSB = true;
                        break;
                }
            }
        }

        private void latchStatus() {
            if (!statusLatched) {

                statusLatch = (getOut(getTime()) << 7) | (nullCount ? 0x40 : 0x00) | (rwMode << 4) | (mode << 1) | (bcd ? 1 : 0);
                statusLatched = true;
            }
        }

        public void write(int data) {
            switch (writeState) {
                default:
                    throw new IllegalStateException("write counter in invalid write state");
                case LSByte:
                    loadCount(0xff & data);
                    break;
                case MSByte:
                    loadCount((0xff & data) << 8);
                    break;
                case LSByte_Multple:
                    //null count setting is delayed until after second byte is written
                    inputLatch = data;
                    writeState = RW_Status.MSByte_multiple;
                    break;
                case MSByte_multiple:
                    writeState = RW_Status.LSByte_Multple;
                    loadCount((0xff & inputLatch) | ((0xff & data) << 8));
                    break;
            }
        }

        public void writeControlWord(int data) {
            int RW = (data >> 4) & 3;
            if (RW == 0) {
                latchCount();
            } else {
                nullCount = true;
                countLatched_LSB = false;
                countLatched_MSB = false;
                statusLatched = false;
                inputLatch = 0;
                rwMode = RW;
                bcd = (data & 1) != 0;
                mode = (data >> 1) & 7;
                switch (RW) {
                    case 1:
                        // set read state to LSB
                        readState = RW_Status.LSByte;
                        writeState = RW_Status.LSByte;
                        break;
                    case 2:
                        // set read state to MSB
                        readState = RW_Status.MSByte;
                        writeState = RW_Status.MSByte;
                        break;
                    case 3:
                        // set read state to LSB multiple
                        readState = RW_Status.LSByte_Multple;
                        writeState = RW_Status.LSByte_Multple;
                        break;
                    default:
                        throw new IllegalStateException("Invalid RW access field in control word write of PIT");
                }
            }
        }

        public void setGate(boolean value) {
            switch (mode) {
                default:
                case MODE_INTERRUPT_ON_TERMINAL_COUNT:
                case MODE_SOFTWARE_TRIGGERED_STROBE:
                    /* XXX: just disable/enable counting */
                    break;
                case MODE_HARDWARE_RETRIGGERABLE_ONE_SHOT:
                case MODE_HARDWARE_TRIGGERED_STROBE:
                    if (!gate && value) {
                        /* restart counting on rising edge */
                        countStartCycles = timingSource.getEmulatedNanos();
                        irqTimerUpdate(countStartCycles);
                    }
                    break;
                case MODE_RATE_GENERATOR:
                case MODE_SQUARE_WAVE:
                    if (!gate && value) {
                        /* restart counting on rising edge */
                        countStartCycles = timingSource.getEmulatedNanos();
                        irqTimerUpdate(countStartCycles);
                    }
                    /* XXX: disable/enable counting */
                    break;
            }
            this.gate = value;
        }

        private int getCount() {
            long now = scale64(timingSource.getEmulatedNanos() - countStartCycles, PIT_FREQ, (int) timingSource.getTickRate());

            switch (mode) {
                case MODE_INTERRUPT_ON_TERMINAL_COUNT:
                case MODE_HARDWARE_RETRIGGERABLE_ONE_SHOT:
                case MODE_SOFTWARE_TRIGGERED_STROBE:
                case MODE_HARDWARE_TRIGGERED_STROBE:
                    return (int) ((countValue - now) & 0xffffl);
                case MODE_SQUARE_WAVE:
                    return (int) (countValue - ((2 * now) % countValue));
                case MODE_RATE_GENERATOR:
                default:
                    return (int) (countValue - (now % countValue));
            }
        }

        private int getOut(long now) {
            switch (mode) {
                default:
                case MODE_INTERRUPT_ON_TERMINAL_COUNT:
                    if (now >= countValue) {
                        return 1;
                    } else {
                        return 0;
                    }
                case MODE_HARDWARE_RETRIGGERABLE_ONE_SHOT:
                    if (now < countValue) {
                        return 1;
                    } else {
                        return 0;
                    }
                case MODE_RATE_GENERATOR:
                    if ((now % countValue) == countValue - 1)
                        return 0;
                    else
                        return 1;
                case MODE_SQUARE_WAVE:
                    if ((now % countValue) < ((countValue + 1) >>> 1)) {
                        return 1;
                    } else {
                        return 0;
                    }
                case MODE_SOFTWARE_TRIGGERED_STROBE:
                case MODE_HARDWARE_TRIGGERED_STROBE:
                    if (now == countValue) {
                        return 1;
                    } else {
                        return 0;
                    }
            }
        }

        private long getNextTransitionTime(long currentTime) {
            switch (mode) {
                default:
                case MODE_INTERRUPT_ON_TERMINAL_COUNT:
                case MODE_HARDWARE_RETRIGGERABLE_ONE_SHOT: {
                    if (currentTime < countValue) {
                        return countValue;
                    } else {
                        return -1;
                    }
                }
                case MODE_RATE_GENERATOR: {
                    long base = (currentTime / countValue) * countValue;
                    if ((currentTime == base)) {
                        return base + countValue - 1;
                    } else {
                        return base + countValue;
                    }
                }
                case MODE_SQUARE_WAVE: {
                    long base = (currentTime / countValue) * countValue;
                    long period2 = ((countValue + 1) >>> 1);
                    if ((currentTime - base) < period2) {
                        return base + period2;
                    } else {
                        return base + countValue;
                    }
                }
                case MODE_SOFTWARE_TRIGGERED_STROBE:
                case MODE_HARDWARE_TRIGGERED_STROBE: {
                    if (currentTime < countValue) {
                        return countValue;
                    } else if (currentTime == countValue) {
                        return countValue + 1;
                    } else {
                        return -1;
                    }
                }
            }
        }

        private void loadCount(int value) {
            nullCount = false;
            if (value == 0) {
                value = 0x10000;
            }
            countStartCycles = timingSource.getEmulatedNanos();
            countValue = value;
            this.irqTimerUpdate(0);
        }

        private void irqTimerUpdate(long currentTime) {
            if (irqTimer == null) {
                return;
            }
            nextChangeTime = getNextTransitionTime(currentTime);

            int out = getOut(currentTime);
            irqDevice.setIRQ(irq, out);
//            long nanos = convertCyclesToNanos(convertPitTicksToCycles(countStartCycles, nextChangeTime));
            long nanos = countStartCycles + scale64(nextChangeTime, 1000000000, PIT_FREQ);

            if (irqTimer.getExpiry() == nanos) // we need to trigger the next int now
            {
                irqTimer.setExpiry(nanos);
                timingSource.updateAndProcess(0);
            } else {
                if (nextChangeTime != -1) {
                    irqTimer.setExpiry(nanos);
                } else {
                    irqTimer.disable();
                }
            }
        }

        public int getMode() {
            return this.mode;
        }

        public int getInitialCount() {
            return this.countValue;
        }

        public void callback() {
            this.irqTimerUpdate(nextChangeTime);
        }

        public void setIRQTimer(Timer object) {
            irqTimer = object;
        }

        public void setIRQ(int irq) {
            this.irq = irq;
        }

        public int getType() {
            return 2;
        }
    }

    public boolean initialised() {
        return ((irqDevice != null) && (timingSource != null)) && ioportRegistered;
    }

    public boolean updated() {
        return /*(irqDevice.updated() && timingSource.updated()) &&*/ ioportRegistered;
    }

    public String toString() {
        return "Intel i8254 Interval Timer";
    }

}


text:
"""API for using the api (anaconda-client, downloads and conda)."""

# Standard library imports
import json
import os
import tempfile

# Third party imports
from qtpy.QtCore import QObject, Signal

# Local imports
from conda_manager.api.client_api import ClientAPI
from conda_manager.api.conda_api import CondaAPI
from conda_manager.api.download_api import DownloadAPI, RequestsDownloadAPI

class _ManagerAPI(QObject):
    """Anaconda Manager API process worker."""

    sig_repodata_updated = Signal(object)
    sig_repodata_errored = Signal()

    def __init__(self):
        """Anaconda Manager API process worker."""
        super(_ManagerAPI, self).__init__()

        # API's
        self._conda_api = CondaAPI()
        self._client_api = ClientAPI()
        self._download_api = DownloadAPI(load_rc_func=self._conda_api.load_rc)
        self._requests_download_api = RequestsDownloadAPI(
            load_rc_func=self._conda_api.load_rc)
        self.ROOT_PREFIX = self._conda_api.ROOT_PREFIX

        # Vars
        self._checking_repos = None
        self._data_directory = None
        self._files_downloaded = None
        self._repodata_files = None
        self._valid_repos = None

        # Expose some methods for convenient access. Methods return a worker
        self.conda_create = self._conda_api.create
        self.conda_create_yaml = self._conda_api.create_from_yaml
        self.conda_clone = self._conda_api.clone_environment
        self.conda_dependencies = self._conda_api.dependencies
        self.conda_get_condarc_channels = self._conda_api.get_condarc_channels
        self.conda_install = self._conda_api.install
        self.conda_remove = self._conda_api.remove
        self.conda_terminate = self._conda_api.terminate_all_processes
        self.conda_config_add = self._conda_api.config_add
        self.conda_config_remove = self._conda_api.config_remove
        self.pip_list = self._conda_api.pip_list
        self.pip_remove = self._conda_api.pip_remove

        # No workers are returned for these methods
        self.conda_clear_lock = self._conda_api.clear_lock
        self.conda_environment_exists = self._conda_api.environment_exists
        self.conda_get_envs = self._conda_api.get_envs
        self.conda_linked = self._conda_api.linked
        self.conda_get_prefix_envname = self._conda_api.get_prefix_envname
        self.conda_package_version = self._conda_api.package_version
        self.conda_platform = self._conda_api.get_platform

        # These download methods return a worker
        get_api_info = self._requests_download_api.get_api_info
        is_valid_url = self._requests_download_api.is_valid_api_url
        is_valid_channel = self._requests_download_api.is_valid_channel
        terminate = self._requests_download_api.terminate
        self.download_requests = self._requests_download_api.download
        self.download_async = self._download_api.download
        self.download_async_terminate = self._download_api.terminate
        self.download_is_valid_url = self._requests_download_api.is_valid_url
        self.download_is_valid_api_url = is_valid_url
        self.download_get_api_info = lambda: get_api_info(
            self._client_api.get_api_url())
        self.download_is_valid_channel = is_valid_channel
        self.download_requests_terminate = terminate

        # These client methods return a worker
        self.client_store_token = self._client_api.store_token
        self.client_remove_token = self._client_api.remove_token
        self.client_login = self._client_api.login
        self.client_logout = self._client_api.logout
        self.client_load_repodata = self._client_api.load_repodata
        self.client_prepare_packages_data = self._client_api.prepare_model_data
        self.client_user = self._client_api.user
        self.client_domain = self._client_api.domain
        self.client_set_domain = self._client_api.set_domain
        self.client_packages = self._client_api.packages
        self.client_multi_packages = self._client_api.multi_packages
        self.client_organizations = self._client_api.organizations
        self.client_load_token = self._client_api.load_token
        self.client_get_api_url = self._client_api.get_api_url
        self.client_set_api_url = self._client_api.set_api_url

    # --- Helper methods
    # -------------------------------------------------------------------------
    def _set_repo_urls_from_channels(self, channels):
        """
        Convert a channel into a normalized repo name including.

        Channels are assumed in normalized url form.
        """
        repos = []
        sys_platform = self._conda_api.get_platform()

        for channel in channels:
            url = '{0}/{1}/repodata.json.bz2'.format(channel, sys_platform)
            repos.append(url)

        return repos

    def _check_repos(self, repos):
        """Check if repodata urls are valid."""
        self._checking_repos = []
        self._valid_repos = []

        for repo in repos:
            worker = self.download_is_valid_url(repo)
            worker.sig_finished.connect(self._repos_checked)
            worker.repo = repo
            self._checking_repos.append(repo)

    def _repos_checked(self, worker, output, error):
        """Callback for _check_repos."""
        if worker.repo in self._checking_repos:
            self._checking_repos.remove(worker.repo)

        if output:
            self._valid_repos.append(worker.repo)

        if len(self._checking_repos) == 0:
            self._download_repodata(self._valid_repos)

    def _repo_url_to_path(self, repo):
        """Convert a `repo` url to a file path for local storage."""
        repo = repo.replace('http://', '')
        repo = repo.replace('https://', '')
        repo = repo.replace('/', '_')

        return os.sep.join([self._data_directory, repo])

    def _download_repodata(self, checked_repos):
        """Dowload repodata."""
        self._files_downloaded = []
        self._repodata_files = []
        self.__counter = -1

        if checked_repos:
            for repo in checked_repos:
                path = self._repo_url_to_path(repo)
                self._files_downloaded.append(path)
                self._repodata_files.append(path)
                worker = self.download_async(repo, path)
                worker.url = repo
                worker.path = path
                worker.sig_finished.connect(self._repodata_downloaded)
        else:
            # Empty, maybe there is no internet connection
            # Load information from conda-meta and save that file
            path = self._get_repodata_from_meta()
            self._repodata_files = [path]
            self._repodata_downloaded()

    def _get_repodata_from_meta(self):
        """Generate repodata from local meta files."""
        path = os.sep.join([self.ROOT_PREFIX, 'conda-meta'])
        packages = os.listdir(path)
        meta_repodata = {}
        for pkg in packages:
            if pkg.endswith('.json'):
                filepath = os.sep.join([path, pkg])
                with open(filepath, 'r') as f:
                    data = json.load(f)

                if 'files' in data:
                    data.pop('files')
                if 'icondata' in data:
                    data.pop('icondata')

                name = pkg.replace('.json', '')
                meta_repodata[name] = data

        meta_repodata_path = os.sep.join([self._data_directory,
                                          'offline.json'])
        repodata = {'info': [],
                    'packages': meta_repodata}

        with open(meta_repodata_path, 'w') as f:
            json.dump(repodata, f, sort_keys=True,
                      indent=4, separators=(',', ': '))

        return meta_repodata_path

    def _repodata_downloaded(self, worker=None, output=None, error=None):
        """Callback for _download_repodata."""
        if worker:
            self._files_downloaded.remove(worker.path)

            if worker.path in self._files_downloaded:
                self._files_downloaded.remove(worker.path)

        if len(self._files_downloaded) == 0:
            self.sig_repodata_updated.emit(list(set(self._repodata_files)))

    # --- Public API
    # -------------------------------------------------------------------------
    def repodata_files(self, channels=None):
        """
        Return the repodata paths based on `channels` and the `data_directory`.

        There is no check for validity here.
        """
        if channels is None:
            channels = self.conda_get_condarc_channels()

        repodata_urls = self._set_repo_urls_from_channels(channels)

        repopaths = []

        for repourl in repodata_urls:
            fullpath = os.sep.join([self._repo_url_to_path(repourl)])
            repopaths.append(fullpath)

        return repopaths

    def set_data_directory(self, data_directory):
        """Set the directory where repodata and metadata are stored."""
        self._data_directory = data_directory

    def update_repodata(self, channels=None):
        """Update repodata from channels or use condarc channels if None."""
        norm_channels = self.conda_get_condarc_channels(channels=channels,
                                                        normalize=True)
        repodata_urls = self._set_repo_urls_from_channels(norm_channels)
        self._check_repos(repodata_urls)

    def update_metadata(self):
        """
        Update the metadata available for packages in repo.continuum.io.

        Returns a download worker.
        """
        if self._data_directory is None:
            raise Exception('Need to call `api.set_data_directory` first.')

        metadata_url = 'https://repo.continuum.io/pkgs/metadata.json'
        filepath = os.sep.join([self._data_directory, 'metadata.json'])
        worker = self.download_requests(metadata_url, filepath)
        return worker

    def check_valid_channel(self,
                            channel,
                            conda_url='https://conda.anaconda.org'):
        """Check if channel is valid."""
        if channel.startswith('https://') or channel.startswith('http://'):
            url = channel
        else:
            url = "{0}/{1}".format(conda_url, channel)

        if url[-1] == '/':
            url = url[:-1]
        plat = self.conda_platform()
        repodata_url = "{0}/{1}/{2}".format(url, plat, 'repodata.json')
        worker = self.download_is_valid_url(repodata_url)
        worker.url = url
        return worker

MANAGER_API = None

def ManagerAPI():
    """Manager API threaded worker."""
    global MANAGER_API

    if MANAGER_API is None:
        MANAGER_API = _ManagerAPI()

    return MANAGER_API

# --- Local testing
# -----------------------------------------------------------------------------
def finished(worker, output, error):  # pragma: no cover
    """Print information on test finished."""
    print(worker, output, error)

def download_finished(url, path):  # pragma: no cover
    """Print information on downlaod finished."""
    print(url, path)

def repodata_updated(repos):  # pragma: no cover
    """Print information on repodata updated."""
    print(repos)

def test():  # pragma: no cover
    """Main local test."""
    from conda_manager.utils.qthelpers import qapplication

    app = qapplication()
    api = ManagerAPI()
    api.sig_repodata_updated.connect(repodata_updated)
    data_directory = tempfile.mkdtemp()
    api.set_data_directory(data_directory)
    worker = api.update_metadata()
    worker.sig_download_finished.connect(download_finished)
    api.update_repodata()
    app.exec_()

if __name__ == '__main__':  # pragma: no cover
    test()


text:
/*!
 * This is a banner
 */

/**
 * @return {Object} Instance of the current Strings object
 * @api public
 */


text:
class AssessmentUserDataController < ApplicationController
  # inherited from ApplicationController
  before_action :set_assessment
  before_action :set_aud
  rescue_from ActionView::MissingTemplate do |_exception|
    redirect_to("/home/error_404")
  end

  action_auth_level :edit, :instructor
  def edit
    @breadcrumbs << (view_context.link_to "Gradesheet", [:viewGradesheet, @course, @assessment])
  end

  action_auth_level :update, :instructor
  def update
    if @aud.update(edit_aud_params)
      flash[:success] = "Grade type updated!"
      redirect_to([:viewGradesheet, @course, @assessment]) and return
    else
      flash[:error] = "Error updating grade type!"
      redirect_to action: :edit and return
    end
  end

private

  def set_aud
    @aud = @assessment.assessment_user_data.find(params[:id])
  end

  def edit_aud_params
    params.require(:assessment_user_datum).permit(:grade_type)
  end
end


text:
#import <React/RCTView.h>

@class RCTWebView;

/**
 * Special scheme used to pass messages to the injectedJavaScript
 * code without triggering a page load. Usage:
 *
 *   window.location.href = RCTJSNavigationScheme + '://hello'
 */
extern NSString *const RCTJSNavigationScheme;

@protocol RCTWebViewDelegate <NSObject>

- (BOOL)webView:(RCTWebView *)webView
shouldStartLoadForRequest:(NSMutableDictionary<NSString *, id> *)request
   withCallback:(RCTDirectEventBlock)callback;

@end

@interface RCTWebView : RCTView

@property (nonatomic, weak) id<RCTWebViewDelegate> delegate;

@property (nonatomic, copy) NSDictionary *source;
@property (nonatomic, assign) UIEdgeInsets contentInset;
@property (nonatomic, assign) BOOL automaticallyAdjustContentInsets;
@property (nonatomic, assign) BOOL messagingEnabled;
@property (nonatomic, copy) NSString *injectedJavaScript;
@property (nonatomic, assign) BOOL scalesPageToFit;

- (void)goForward;
- (void)goBack;
- (void)reload;
- (void)stopLoading;
- (void)postMessage:(NSString *)message;
- (void)injectJavaScript:(NSString *)script;

@end


text:
<title>
Keeping the fire of hope burning
</title>

<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
<?php include "../../legacy-includes/Script.htmlf" ?>

<?php include "../../legacy-includes/TopLogo.htmlf" ?>

<?php include "../../legacy-includes/TopAd.htmlf" ?>

<?php include "../../legacy-includes/LeftButtons.htmlf" ?>

<?php include "../../legacy-includes/BodyInsert.htmlf" ?>

OBITURARY: PAUL FOOT

Keeping the fire of hope burning

By Bill Roberts | July 23, 2004 | Page 11

PAUL FOOT, one of Britain's finest investigative journalists and a revolutionary socialist whose speeches and books inspired tens of thousands, died of a heart attack on July 19 at the age of 66. Paul was a founding member of the Socialist Workers Party in Britain and was its most optimistic and inspiring voice.

He was born into an upper-class family, and several relatives have been members of parliament. Yet despite this background, he could electrify working-class audiences. His wit and incisive analysis of the stupidity and incompetence of the British ruling class, delivered in an unpretentious way, gave confidence to workers that they could rule themselves.

Paul died at Stansted Airport on his way to a family vacation in Ireland. He had recovered from a thoracic aortic aneurysm in 1999, which left him unconscious and near death for several weeks. But he rallied and returned to political activity as a writer, a speaker and political candidate--running most recently for mayor of the London borough of Hackney as a revolutionary socialist.

Paul was a well-known columnist in Britain. For many years, he had a full page to himself in the mass circulation Daily Mirror. He had a 10-year run as columnist for the Guardian and wrote regularly for many other publications, including the London Review of Books.

Paul was also a cofounder of Private Eye, a muckraking magazine known for sticking its finger in the eye of the British establishment. Paul was best known for his investigative work around cases of injustice, uncovering the truth behind some of the British justice system's most outrageous frame-ups. He was also a passionate reader of the revolutionary poet Shelley and wrote two books about him.

Paul became a socialist in Glasgow while training as a reporter on the Daily Record. There, he joined a small group of revolutionary socialists in the small Socialist Review Group and became active in the rough-and-tumble politics of the "Red Clyde." The Review group went on to found the International Socialists, and later the Socialist Workers Party.

Paul was a writer and columnist for the SWP's Socialist Worker for many years. Paul was honored for his journalism several times. In 1972 and 1989, he was named Journalist of the Year by the What the Papers Say Awards. He won the same title from the British Press Awards in 1980, and was honored as Journalist of the Decade in 2000 by the What the Papers Say Awards.

Paul was ever-optimistic as he sifted through capitalism's injustices, using every ounce of his talents to right some wrong. As Clive Anderson said in presenting Paul with the Journalist of the Decade award in 2000, "Our final award goes to a journalist who has stuck closely to his principles and, to the chagrin of the authorities, has been proven right time and time again."

This optimism could be felt even more keenly when Paul spoke out for socialism. There is no space large enough to say what this often-shy man meant to me and tens of thousands of others who listened to his lectures with awe and inspiration.

Every summer, at the annual Marxism conference in London, his meetings were filled to overflowing. When I attended my first Paul Foot meeting, I found myself on the stage, behind the speaker, because there was no other place to sit. Even with his back to me, Paul's words lifted me up--especially when he concluded with Shelley's words "Rise like lions, we are many, they are few."

Whether he was running for office as a socialist, taking on the British state, championing a strike, or singing the praises of Shelley's poetry, Paul Foot kept the flame of hope--so central to the socialist vision--burning.

He had much more to contribute, and we will miss him dearly. Our thoughts are with his family--especially his partner Clare, their 10-year-old daughter Kate, and his other children Monica, Tom, John and Matt.

<?php include "../../legacy-includes/BottomNavLinks.htmlf" ?>

<?php include "../../legacy-includes/RightAdFolder.htmlf" ?>


text:
Fabricator(:user) do
  name     'Test User'
  email    'example@example.com'
  password 'changeme'
  password_confirmation 'changeme'
  # required if the Devise Confirmable module is used
  # confirmed_at Time.now
end


text:
% scanCount = GetScanCountIm( myobj )
%
%     Returns number of IMEC scans since current run started
%     or zero if not running.
%
function [ret] = GetScanCountIm( s )

    ret = str2double( DoQueryCmd( s, 'GETSCANCOUNTIM' ) );
end


text: Asynchronous threaded webserver for Nim Language [http://www.nim-lang.org](http://nim-lang.org/)