text:
package com.abina.poi;

/**
 * @author abina
 * @Data 2018-03-08
 */
public class WordUtil {

	/**
	 * @方法名称 exportCtrAtch
	 * @功能描述
生成合同附件

	 * @作者 zouyaobin@tansun.com.cn
	 * @创建时间 2018年3月7日 上午9:32:47
	 * @param params
	 * @param response
	 * @throws FileNotFoundException
	 * @throws IOException
	 */
	@RequestMapping(value="/exportCtrAtch")
	public void exportCtrAtch(QueryCtrVO queryVo, HttpServletResponse response) {

		//1.查询数据,拼装替换 Map,
		Map<String, Object> ctrInfMap = ctrApi.getCtrInfMap(queryVo);
		if (CollectionUtil.isEmpty(ctrInfMap)) {
			return;
		}
		Map<String, String> mappingMap = buildMappingMap(ctrInfMap);
		String templateFileName = templateFileName(ctrInfMap);
		//2.获取文档路径
		StringBuffer sbPath = new StringBuffer();
		sbPath.append(this.getRequest().getSession().getServletContext().getRealPath("/"));
		sbPath.append(File.separator).append("static").append(File.separator).append("template").append(File.separator).append("ctr").append(File.separator);

		File tempFile = null;
		try {
			//3.替换文档内容,并创建临时文件写入
			XWPFDocument document = replaceWord(sbPath.toString() + templateFileName, mappingMap);
			tempFile = FileUtil.createTempFile(new File(sbPath.toString()));
			OutputStream os = new FileOutputStream(tempFile);
			document.write(os);
			os.close();

			//4.读取临时文件,并生成新文档
			InputStream tempIs = new FileInputStream(tempFile);
			String agent = getRequest().getHeader("User-Agent");
			boolean isMSIE = (agent != null && agent.indexOf("MSIE") != -1);
			if (isMSIE) {
				templateFileName = URLEncoder.encode(templateFileName, "UTF-8");
			} else {
				templateFileName = new String(templateFileName.getBytes("UTF-8"), "ISO-8859-1");
			}
			response.reset();
			response.setContentType("application/vnd.ms-word;charset=UTF-8");
			response.setHeader("Content-Disposition","attachment; filename=" + templateFileName);
			response.setHeader("Content-Length", tempFile.length() + "");
			ServletOutputStream out = response.getOutputStream();
			byte[] b=new byte[1024];
			int len;
			while((len = tempIs.read(b))!=-1){
			    out.write(b, 0, len);
			}
			tempIs.close();
			out.close();
		} catch (IORuntimeException e) {
			e.printStackTrace();
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			if(tempFile != null) {
				tempFile.delete();
			}
		}
	}

	/**
	 * @方法名称 buildMappingMap
	 * @功能描述
构建映射替换集合对象,格式:${ctrId} => ctrId

	 * @作者 zouyaobin@tansun.com.cn
	 * @创建时间 2018年3月8日 上午10:01:57
	 * @param ctrInf
	 * @return
	 */
	public Map<String, String> buildMappingMap(Map<String, Object> ctrInf) {
		Map<String, String> replaceMap = new HashMap<String, String>();
		//合同基础信息
		replaceMap.put("${ctrId}", MapUtils.getString(ctrInf, "ctrId", ""));
		replaceMap.put("${cstNm}", MapUtils.getString(ctrInf, "cstNm", ""));

		//合同客户信息 = 债权人
		Map<String, Object> cstQueryParams = new HashMap<String, Object>();
		cstQueryParams.put("cstId", MapUtils.getString(ctrInf, "cstId"));
		Map<String, Object> cstBscInf = customerApi.getBizCstBscInfByParams(cstQueryParams);
		replaceMap.put("${rgstAdr}", MapUtils.getString(cstBscInf, "rgstAdr", ""));
		replaceMap.put("${ctcPsn}", MapUtils.getString(ctrInf, "ctcPsn", ""));
		replaceMap.put("${ctcPsnTel}", MapUtils.getString(ctrInf, "ctcPsnTel", ""));
		replaceMap.put("${email}", MapUtils.getString(ctrInf, "email", ""));

		//债务人信息
		QueryCtrVO oblgVo = new QueryCtrVO();
		oblgVo.setCtrSn(MapUtil.getString(ctrInf, "ctrSn"));
		Map<String, Object> rltvOblgMap = ctrApi.getRltvOblgMap(oblgVo);
		replaceMap.put("${oblgCstNm}", MapUtils.getString(rltvOblgMap, "cstNm", ""));
//		replaceMap.put("XX商业", ""); TODO
		return replaceMap;
	}

	/**
	 * @方法名称 templateFileName
	 * @功能描述
获取模板文档名称

	 * @作者 zouyaobin@tansun.com.cn
	 * @创建时间 2018年3月8日 上午9:56:00
	 * @param ctrInfMap
	 * @return
	 */
	private static String templateFileName(Map<String, Object> ctrInfMap) {
		String tempFileName = "应收账款转让合同.docx";
		String pdId = MapUtil.getString(ctrInfMap, "pdId");
		if (DictUtil.getDictValue("ProNm", "ProNm_0").equals(pdId)) { //应收账款
			tempFileName = "应收账款转让合同.docx"; //TODO
		}
		if (DictUtil.getDictValue("ProNm", "ProNm_1").equals(pdId)) { //销售回购
			tempFileName = "应收账款转让合同.docx";
		}
		if (DictUtil.getDictValue("ProNm", "ProNm_2").equals(pdId)) { //代理采购
			tempFileName = "应收账款转让合同.docx"; //TODO
		}
		return tempFileName;
	}

	/**
	 * @方法名称 replaceWord
	 * @功能描述
替换 word 文档中的指定字符

	 * @作者 zouyaobin@tansun.com.cn
	 * @创建时间 2018年3月8日 上午9:38:22
	 * @param filePath 读取模板文件地址(含文件名)
	 * @param replaceMap 替换的新旧值 Map
	 * @return word 文档对象
	 * @throws IOException
	 */
	public static XWPFDocument replaceWord(String filePath, Map<String, String> replaceMap) throws IOException {
		XWPFDocument document = new XWPFDocument(POIXMLDocument.openPackage(filePath));
		Iterator<XWPFParagraph> itPara = document.getParagraphsIterator();
		int idx = 0;
		while (itPara.hasNext()) {
			XWPFParagraph paragraph = (XWPFParagraph) itPara.next();
			int size = paragraph.getRuns().size();
			if (size == 0) {
				continue;
			}
			String paragraphText = StringUtils.join(paragraph.getRuns().toArray());
			//存在标识,才替换
			if (paragraphText.contains("$")) {
				for (Map.Entry<String, String> entry : replaceMap.entrySet()) {
					paragraphText = paragraphText.replace(entry.getKey(), entry.getValue());
				}
				for (int i = (size - 1); i >= 0; i--) {
					paragraph.removeRun(i);
				}
				XWPFRun newRun = paragraph.insertNewRun(0);
				newRun.setText(paragraphText, 0);
				newRun.setFontFamily("宋体");
				if (idx == 0) {
					newRun.setFontSize(12);
				} else {
					newRun.setFontSize(14);
				}
				idx ++ ;
			}
		}
		return document;
	}
}


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

/*
Author: Chao Ma (mctt90@gmail.com)

This file provides stringprintf utilities.
*/

#ifndef F2M_BASE_STRING_PRINTF_H_
#define F2M_BASE_STRING_PRINTF_H_

#include <string>

//------------------------------------------------------------------------------
// This code comes from the re2 project host on Google Code
// (http://code.google.com/p/re2/), in particular, the following source file
// http://code.google.com/p/re2/source/browse/util/stringprintf.cc
//------------------------------------------------------------------------------

//------------------------------------------------------------------------------
// For example:
//
//  std::string str = StringPrintf("%d", 1);    /* str = "1"  */
//  SStringPrintf(&str, "%d", 2);               /* str = "2"  */
//  StringAppendF(&str, "%d", 3);               /* str = "23" */
//------------------------------------------------------------------------------

std::string StringPrintf(const char* format, ...);
void SStringPrintf(std::string* dst, const char* format, ...);
void StringAppendF(std::string* dst, const char* format, ...);

#endif // F2M_BASE_STRING_PRINTF_H_

redpajama_set_name: RedPajamaGithub


text:
<!DOCTYPE html>

<dialog id="bottom">

You can't Escape when this textbox has focus: <input id="swallow-input" type="text">

You can Escape even if this textbox has focus: <input id="normal-input" type="text">

</dialog>
<dialog id="top">

</dialog>


text:
<resources>
    <string name="app_name">Ultra Debugger Sample App</string>
    <string name="type_address_description">Please connect your smartphone and computer to same network, open browser on computer and type address:</string>
    <string name="unknown_ip">Unknown IP address</string>
    <string name="ip_format">http://%1$s:%2$d</string>
</resources>


text:
@interface DiscoverHotTagView : UIView
{
    UIView      * _backView;
    UIImageView * _imgView;
    UIView      * _maskView;
    UILabel     * _tagLabel;
}

-(id)initWithFrame:(CGRect)frame AndIndex:(NSInteger )index;

-(void)setDiscoverHotTagViewWithModal:(DiscoverHotTagModal *)modal;

@end


text:
package net.coding.program.task;

import android.content.DialogInterface;
import android.content.Intent;
import android.support.v4.app.Fragment;

import net.coding.program.common.ui.BackActivity;
import net.coding.program.R;
import net.coding.program.common.Global;
import net.coding.program.model.TaskObject;
import net.coding.program.project.detail.TopicAddActivity;
import net.coding.program.project.detail.TopicAddActivity.TopicData;
import net.coding.program.project.detail.TopicEditFragment;

import org.androidannotations.annotations.AfterViews;
import org.androidannotations.annotations.EActivity;
import org.androidannotations.annotations.Extra;
import org.json.JSONException;
import org.json.JSONObject;

@EActivity(R.layout.activity_task_description)
public class TaskDescriptionActivity extends BackActivity implements TaskDescrip, TopicEditFragment.SaveData {

    @Extra
    TaskObject.TaskDescription descriptionData;

    @Extra
    int taskId;

    @Extra
    String projectPath;
//    int projectId;

    String HOST_DESCRIPTION = Global.HOST_API + "/task/%s/description";

    TaskDespEditFragment editFragment;
    Fragment previewFragment;
    private TopicData modifyData = new TopicData();

    @AfterViews
    protected final void initTaskDescriptionActivity() {
        editFragment = TaskDespEditFragment_.builder().build();
        previewFragment = TaskDespPreviewFragment_.builder().build();

        String markdown = descriptionData.markdown;
        if (markdown.isEmpty()) {
            getSupportFragmentManager().beginTransaction().replace(R.id.container, editFragment).commit();
        } else {
            modifyData.content = markdown;
            getSupportFragmentManager().beginTransaction().replace(R.id.container, previewFragment).commit();
        }
    }

    @Override
    public void onBackPressed() {
        if (editFragment.isContentModify()) {
            showDialog("任务描述", "确定放弃此次编辑?", new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    finish();
                }
            });
        } else {
            finish();
        }
    }

    @Override
    public void parseJson(int code, JSONObject respanse, String tag, int pos, Object data) throws JSONException {
        if (tag.equals(HOST_DESCRIPTION)) {
            hideProgressDialog();
            if (code == 0) {
                showButtomToast("修改描述成功");
                setResult(RESULT_OK);
                finish();
            } else {
                showErrorMsg(code, respanse);
            }
        }
    }

    @Override
    public void closeAndSave(String s) {
        Intent intent = new Intent();
        intent.putExtra("data", s);
        setResult(RESULT_OK, intent);
        finish();
    }

    @Override
    public String createLocateHtml(String s) {
        try {
            final String bubble = Global.readTextFile(getAssets().open("topic-android"));
            return bubble.replace("${webview_content}", s);
        } catch (Exception e) {
            Global.errorLog(e);
            return "";
        }
    }

    @Override
    public void saveData(TopicData data) {
        modifyData = data;
    }

    @Override
    public TopicAddActivity.TopicData loadData() {
        return modifyData;
    }

    @Override
    public void switchPreview() {
        getSupportFragmentManager().beginTransaction().replace(R.id.container, previewFragment).commit();
    }

    @Override
    public void switchEdit() {
        getSupportFragmentManager().beginTransaction().replace(R.id.container, editFragment).commit();
    }

    @Override
    public void exit() {
        Intent intent = new Intent();
        intent.putExtra("data", modifyData.content);
        setResult(RESULT_OK, intent);
        finish();
    }

    @Override
    public String getProjectPath() {
        return projectPath;
    }

    // 有任务的项目必定是私有项目
    @Override
    public boolean isProjectPublic() {
        return false;
    }
}


text:
import {Component} from '@angular/core';
import {ActivatedRoute} from '@angular/router';

@Component({
  selector: 'aux-comp',
  template: `

Hello There!!

Message: {{message}}

Name: {{name}}

  `
})
export default class RouterData2 {
  public message: string;
  public name: string;
  private params$: any;

  constructor(private activatedRoute: ActivatedRoute) { }

  ngOnInit() {
    const name = 'name';
    const message = 'message';
    this.params$ = this.activatedRoute.params.subscribe(params => {
      this.name = params[name];
      this.message = params[message];
    });
  }

  ngOnDestroy() {
    this.params$.unsubscribe();
  }
}


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
null

#### Original name
Sticta arvidssonii D.J. Galloway

### Remarks
null


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using DesktopCharacter.Model.Repository;
using DesktopCharacter.Model.Service.Slack;
using DesktopCharacter.Model.Service.TimeSignal;
using DesktopCharacter.Model.Service.Twitter;
using DesktopCharacter.Model.AI;
using NLog;

namespace DesktopCharacter.Model.Locator
{
    class ServiceLocator
    {

        public static ServiceLocator Instance { get; } = new ServiceLocator();
        private static Logger logger = LogManager.GetCurrentClassLogger();

        //毎回インスタンスを作成するスコープ
        private readonly InstanceContext prototypeContext = new PrototypeInstanceContext();
        //インスタンスを破棄しないシングルトンスコープ
        private readonly InstanceContext applicationContext = new InstanceContext();
        //コンフィグを更新した時にインスタンスを作りなおすスコープ
        private readonly InstanceContext configBaseContext = new InstanceContext();

        private ServiceLocator()
        {
        }

        /// <summary>
        /// ServiceLocatorの初期化
        /// </summary>
        public void InitializeServiceLocator()
        {
            logger.Info("InitializeServiceLocator");
            RegistFactories();
            InitializeContexts();
        }

        private void RegistFactories()
        {
            logger.Info("=== Begin RegiserFactories ===");
            RegisterByPrototypeScope<TwitterRepository>(() => new TwitterRepository());
            RegisterByConfigBaseScope<TwitterService>(() => new TwitterService());
            RegisterByConfigBaseScope<CodicRepository>(() => new CodicRepository());
            RegisterByPrototypeScope<WindowPositionRepository>(() => new WindowPositionRepository());
            RegisterByApplicationScope<BabumiConfigRepository>(() => new BabumiConfigRepository());
            RegisterByApplicationScope<ITimeSignalService>(() => new CompositeTimeSignalService(
                    new Service.TimeSignal.Impl.AnimationTimeSignal(),
                    new Service.TimeSignal.Impl.SimpleTimeSignalService())
                );
            RegisterByApplicationScope<BlackBoard>(() => new BlackBoard());
            RegisterByPrototypeScope<SlackUserRepository>(() => new SlackUserRepository());
            RegisterByConfigBaseScope<ISlackService>(() => new SlackService());
            logger.Info("=== End RegistFactories ===");
        }

        private void InitializeContexts()
        {
            logger.Info("InitializeContexts");
            InstanceContext[] contexts = { applicationContext, configBaseContext, prototypeContext };
            //インスタンスを最初に用意
            foreach (var instanceContext in contexts)
            {
                instanceContext.Initialize();
            }
            //全てのコンテキストの用意が終わってから呼び出し
            foreach (var instanceContext in contexts)
            {
                instanceContext.CallInitializeAll();
            }
        }

        /// <summary>
        /// インスタンスを取得
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <returns></returns>
        public T GetInstance<T>()
        {
            InstanceContext[] contexts = {applicationContext, configBaseContext, prototypeContext};
            foreach (var instanceContext in contexts)
            {
                var instance = instanceContext.GetInstance<T>();
                if (instance != null)
                {
                    return instance;
                }
            }
            throw new NullReferenceException("Instance not found.");
        }

        /// <summary>
        /// 設定が更新された時にインスタンスを作りなおす
        /// </summary>
        public void ClearConfigBaseContext()
        {
            logger.Info("ClearConfigBaseContext");
            configBaseContext.ClearCacheAll();
            configBaseContext.Initialize();
            configBaseContext.CallInitializeAll();
        }

        private void RegisterByPrototypeScope<T>(Func<T> instanceFactory) where T: class
        {
            prototypeContext.RegisterFactory<T>(instanceFactory);
            logger.Info("Scope=Prototype Type={0}", typeof(T).FullName);
        }

        private void RegisterByApplicationScope<T>(Func<T> instanceFactory) where T : class
        {
            applicationContext.RegisterFactory<T>(instanceFactory);
            logger.Info("Scope=Application Type={0}", typeof(T).FullName);
        }

        private void RegisterByConfigBaseScope<T>(Func<T> instanceFactory) where T : class
        {
            configBaseContext.RegisterFactory<T>(instanceFactory);
            logger.Info("Scope=ConfigBase Type={0}", typeof(T).FullName);
        }
    }

    /// <summary>
    /// インスタンスの生存管理を行うコンテキスト
    /// </summary>
    public class InstanceContext
    {
        //インスタンスを作成するファクトリ
        protected readonly Dictionary<Type, Func<object>> Factory = new Dictionary<Type, Func<object>>();
        //作成したインスタンスのキャッシュ
        private readonly Dictionary<Type, object> _instance = new Dictionary<Type, object>();

        /// <summary>
        /// 型からインスタンスを返します。<br/>
        /// キャッシュインスタンスか新しいインスタンスを返すかはInstanceContextのスコープに依存します。
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <returns></returns>
        public virtual T GetInstance<T>()
        {
            var type = typeof(T);

            //インスタンスキャッシュから探す
            object o;
            if (_instance.TryGetValue(type, out o))
            {
                return (T)o;
            }

            //見つからないのでファクトリを探す
            Func<object> func;
            if (!Factory.TryGetValue(type, out func))
            {
                return default(T);
            }
            //見つかればファクトリからインスタンスを初期化
            o = func?.Invoke();
            if (o is IInitializable)
            {
                var initializable = (IInitializable) o;
                initializable.Initialize();
            }

            _instance.Add(type, o);
            return (T) o;
        }

        /// <summary>
        /// 全てのインスタンスを作成し、インスタンスキャッシュに詰める
        /// </summary>
        public virtual void Initialize()
        {
            ClearCacheAll();
            foreach (var keyValuePair in Factory)
            {
                _instance.Add(keyValuePair.Key, keyValuePair.Value.Invoke());
            }
        }

        /// <summary>
        /// 初期化メソッドを呼び出す
        /// </summary>
        public virtual void CallInitializeAll()
        {
            foreach (var value in _instance.Values)
            {
                (value as IInitializable)?.Initialize();
            }
        }

        /// <summary>
        /// 全てのインスタンスキャッシュを削除します。
        /// </summary>
        public void ClearCacheAll()
        {
            //インスタンスの後処理
            foreach (var disposable in _instance.Values.OfType<IDisposable>())
            {
                disposable.Dispose();
            }
            _instance.Clear();
        }

        /// <summary>
        /// 指定の型のインスタンスキャッシュを削除します。
        /// </summary>
        /// <param name="type"></param>
        public void ClearChacheByType(Type type)
        {
            _instance.Remove(type);
        }

        public void RegisterFactory<T>(Func<T> instanceFactory) where T : class
        {
            Factory.Add(typeof(T), instanceFactory);
        }
    }

    class PrototypeInstanceContext : InstanceContext
    {
        public override T GetInstance<T>()
        {
            Func<object> func;
            if (!Factory.TryGetValue(typeof(T), out func))
            {
                return default(T);
            }

            var obj =  func.Invoke();

            if (!(obj is IInitializable)) return (T) obj;

            var initializable = (IInitializable)obj;
            initializable.Initialize();
            return (T) obj;
        }

        public override void Initialize()
        {
            //何もしない
        }

        public override void CallInitializeAll()
        {
            //何もしない
        }
    }

    interface IInitializable
    {
        void Initialize();
    }
}


text:
package org.apache.hadoop.hdfs.server.datanode;

import java.io.File;
import java.io.IOException;
import java.util.Iterator;
import java.util.TreeMap;

import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.hadoop.classification.InterfaceAudience;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.hdfs.protocol.Block;
import org.apache.hadoop.hdfs.protocol.ExtendedBlock;

/**
 * DataBlockScanner manages block scanning for all the block pools. For each
 * block pool a {@link BlockPoolSliceScanner} is created which runs in a separate
 * thread to scan the blocks for that block pool. When a {@link BPOfferService}
 * becomes alive or dies, blockPoolScannerMap in this class is updated.
 */
@InterfaceAudience.Private
public class DataBlockScanner implements Runnable {
  public static final Log LOG = LogFactory.getLog(DataBlockScanner.class);
  private final DataNode datanode;
  private final FSDatasetInterface dataset;
  private final Configuration conf;

  /**
   * Map to find the BlockPoolScanner for a given block pool id. This is updated
   * when a BPOfferService becomes alive or dies.
   */
  private final TreeMap<String, BlockPoolSliceScanner> blockPoolScannerMap =
    new TreeMap<String, BlockPoolSliceScanner>();
  Thread blockScannerThread = null;

  DataBlockScanner(DataNode datanode, FSDatasetInterface dataset, Configuration conf) {
    this.datanode = datanode;
    this.dataset = dataset;
    this.conf = conf;
  }

  public void run() {
    String currentBpId = "";
    boolean firstRun = true;
    while (datanode.shouldRun && !Thread.interrupted()) {
      //Sleep everytime except in the first interation.
      if (!firstRun) {
        try {
          Thread.sleep(5000);
        } catch (InterruptedException ex) {
          // Interrupt itself again to set the interrupt status
          blockScannerThread.interrupt();
          continue;
        }
      } else {
        firstRun = false;
      }

      BlockPoolSliceScanner bpScanner = getNextBPScanner(currentBpId);
      if (bpScanner == null) {
        // Possible if thread is interrupted
        continue;
      }
      currentBpId = bpScanner.getBlockPoolId();
      // If BPOfferService for this pool is not alive, don't process it
      if (!datanode.isBPServiceAlive(currentBpId)) {
        LOG.warn("Block Pool " + currentBpId + " is not alive");
        // Remove in case BP service died abruptly without proper shutdown
        removeBlockPool(currentBpId);
        continue;
      }
      bpScanner.scanBlockPoolSlice();
    }
  }

  // Wait for at least one block pool to be up
  private void waitForInit(String bpid) {
    UpgradeManagerDatanode um = null;
    if(bpid != null && !bpid.equals(""))
      um = datanode.getUpgradeManagerDatanode(bpid);

    while ((um != null && ! um.isUpgradeCompleted())
        || (getBlockPoolSetSize() < datanode.getAllBpOs().length)
        || (getBlockPoolSetSize() < 1)) {
      try {
        Thread.sleep(5000);
      } catch (InterruptedException e) {
        blockScannerThread.interrupt();
        return;
      }
    }
  }

  /**
   * Find next block pool id to scan. There should be only one current
   * verification log file. Find which block pool contains the current
   * verification log file and that is used as the starting block pool id. If no
   * current files are found start with first block-pool in the blockPoolSet.
   * However, if more than one current files are found, the one with latest
   * modification time is used to find the next block pool id.
   */
  private BlockPoolSliceScanner getNextBPScanner(String currentBpId) {

    String nextBpId = null;
    while ((nextBpId == null) && datanode.shouldRun
        && !blockScannerThread.isInterrupted()) {
      waitForInit(currentBpId);
      synchronized (this) {
        if (getBlockPoolSetSize() > 0) {
          // Find nextBpId by finding the last modified current log file, if any
          long lastScanTime = -1;
          Iterator<String> bpidIterator = blockPoolScannerMap.keySet()
              .iterator();
          while (bpidIterator.hasNext()) {
            String bpid = bpidIterator.next();
            for (FSDatasetInterface.FSVolumeInterface vol : dataset.getVolumes()) {
              try {
                File currFile = BlockPoolSliceScanner.getCurrentFile(vol, bpid);
                if (currFile.exists()) {
                  long lastModified = currFile.lastModified();
                  if (lastScanTime < lastModified) {
                    lastScanTime = lastModified;
                    nextBpId = bpid;
                  }
                }
              } catch (IOException e) {
                LOG.warn("Received exception: ", e);
              }
            }
          }

          // nextBpId can still be null if no current log is found,
          // find nextBpId sequentially.
          if (nextBpId == null) {
            if ("".equals(currentBpId)) {
              nextBpId = blockPoolScannerMap.firstKey();
            } else {
              nextBpId = blockPoolScannerMap.higherKey(currentBpId);
              if (nextBpId == null) {
                nextBpId = blockPoolScannerMap.firstKey();
              }
            }
          }
          if (nextBpId != null) {
            return getBPScanner(nextBpId);
          }
        }
      }
      LOG.warn("No block pool is up, going to wait");
      try {
        Thread.sleep(5000);
      } catch (InterruptedException ex) {
        LOG.warn("Received exception: " + ex);
        blockScannerThread.interrupt();
        return null;
      }
    }
    return null;
  }

  private synchronized int getBlockPoolSetSize() {
    return blockPoolScannerMap.size();
  }

  private synchronized BlockPoolSliceScanner getBPScanner(String bpid) {
    return blockPoolScannerMap.get(bpid);
  }

  private synchronized String[] getBpIdList() {
    return blockPoolScannerMap.keySet().toArray(
        new String[blockPoolScannerMap.keySet().size()]);
  }

  public void addBlock(ExtendedBlock block) {
    BlockPoolSliceScanner bpScanner = getBPScanner(block.getBlockPoolId());
    if (bpScanner != null) {
      bpScanner.addBlock(block);
    } else {
      LOG.warn("No block pool scanner found for block pool id: "
          + block.getBlockPoolId());
    }
  }

  public synchronized boolean isInitialized(String bpid) {
    BlockPoolSliceScanner bpScanner = getBPScanner(bpid);
    if (bpScanner != null) {
      return bpScanner.isInitialized();
    }
    return false;
  }

  public synchronized void printBlockReport(StringBuilder buffer,
      boolean summary) {
    String[] bpIdList = getBpIdList();
    if (bpIdList == null || bpIdList.length == 0) {
      buffer.append("Periodic block scanner is not yet initialized. "
          + "Please check back again after some time.");
      return;
    }
    for (String bpid : bpIdList) {
      BlockPoolSliceScanner bpScanner = getBPScanner(bpid);
      buffer.append("\n\nBlock report for block pool: "+bpid + "\n");
      bpScanner.printBlockReport(buffer, summary);
      buffer.append("\n");
    }
  }

  public void deleteBlock(String poolId, Block toDelete) {
    BlockPoolSliceScanner bpScanner = getBPScanner(poolId);
    if (bpScanner != null) {
      bpScanner.deleteBlock(toDelete);
    } else {
      LOG.warn("No block pool scanner found for block pool id: "
          + poolId);
    }
  }

  public void deleteBlocks(String poolId, Block[] toDelete) {
    BlockPoolSliceScanner bpScanner = getBPScanner(poolId);
    if (bpScanner != null) {
      bpScanner.deleteBlocks(toDelete);
    } else {
      LOG.warn("No block pool scanner found for block pool id: "
          + poolId);
    }
  }

  public synchronized void shutdown() {
    if (blockScannerThread != null) {
      blockScannerThread.interrupt();
    }
  }

  public synchronized void addBlockPool(String blockPoolId) {
    if (blockPoolScannerMap.get(blockPoolId) != null) {
      return;
    }
    BlockPoolSliceScanner bpScanner = new BlockPoolSliceScanner(datanode, dataset,
        conf, blockPoolId);
    try {
      bpScanner.init();
    } catch (IOException ex) {
      LOG.warn("Failed to initialized block scanner for pool id="+blockPoolId);
      return;
    }
    blockPoolScannerMap.put(blockPoolId, bpScanner);
    LOG.info("Added bpid=" + blockPoolId + " to blockPoolScannerMap, new size="
        + blockPoolScannerMap.size());
  }

  public synchronized void removeBlockPool(String blockPoolId) {
    blockPoolScannerMap.remove(blockPoolId);
    LOG.info("Removed bpid="+blockPoolId+" from blockPoolScannerMap");
  }

  // This method is used for testing
  long getBlocksScannedInLastRun(String bpid) throws IOException {
    BlockPoolSliceScanner bpScanner = getBPScanner(bpid);
    if (bpScanner == null) {
      throw new IOException("Block Pool: "+bpid+" is not running");
    } else {
      return bpScanner.getBlocksScannedInLastRun();
    }
  }

  public void start() {
    blockScannerThread = new Thread(this);
    blockScannerThread.setDaemon(true);
    blockScannerThread.start();
  }

  @InterfaceAudience.Private
  public static class Servlet extends HttpServlet {
    private static final long serialVersionUID = 1L;

    public void doGet(HttpServletRequest request,
                      HttpServletResponse response) throws IOException {
      response.setContentType("text/plain");

      DataNode datanode = (DataNode) getServletContext().getAttribute("datanode");
      DataBlockScanner blockScanner = datanode.blockScanner;

      boolean summary = (request.getParameter("listblocks") == null);

      StringBuilder buffer = new StringBuilder(8*1024);
      if (blockScanner == null) {
        LOG.warn("Periodic block scanner is not running");
        buffer.append("Periodic block scanner is not running. " +
                      "Please check the datanode log if this is unexpected.");
      } else {
        blockScanner.printBlockReport(buffer, summary);
      }
      response.getWriter().write(buffer.toString()); // extra copy!
    }
  }

}


text:
import vendor from "./vendor";
import vendor3 from "./vendor3";

var $ = require('./jquery');

// some module
// console.log(vendor);
// require('./com')
System.import("./async1");
System.import("./async2");


text:
"""
 AUTHOR: Gabriel Bassett
 DATE: 12-17-2013
 DEPENDENCIES: a list of modules requiring installation
 Copyright 2014 Gabriel Bassett

 LICENSE:
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.

 DESCRIPTION:
 Functions necessary to enrich the context graph

"""
# PRE-USER SETUP
from datetime import timedelta

########### NOT USER EDITABLE ABOVE THIS POINT #################

# USER VARIABLES
CYMRU_CONFIG_FILE = "cymru.yapsy-plugin"
NAME = 'cymru'

########### NOT USER EDITABLE BELOW THIS POINT #################

## IMPORTS
import networkx as nx
from yapsy.IPlugin import IPlugin
import logging
import ConfigParser
from datetime import datetime # timedelta imported above
import dateutil  # to parse variable time strings
import uuid
import imp
import ipaddress
import inspect

## SETUP

__author__ = "Gabriel Bassett"
loc = inspect.getfile(inspect.currentframe())
i = loc.rfind("/")
loc = loc[:i+1]
config = ConfigParser.SafeConfigParser()
config.readfp(open(loc + CYMRU_CONFIG_FILE))

if config.has_section('Core'):
    if 'name' in config.options('Core'):
        NAME= config.get('Core', 'name')
if config.has_section('Configuration') and 'cymru_module' in config.options('Configuration'):
    cymru_file = config.get('Configuration', 'cymru_module')
    if cymru_file[0] != "/":
        cymru_file = loc + cymru_file
    i = cymru_file.rfind("/")
    cymru_dir = cymru_file[:i]
    cymru_module = cymru_file[i+1:].strip(".py")
    with open("/tmp/output", 'w') as f:
        f.write(cymru_dir + "\n")
        f.write(cymru_module + "\n")
        f.write(cymru_file + "\n")
    try:
        fp, pathname, description = imp.find_module(cymru_module, [cymru_dir])
        cymru_api = imp.load_module(cymru_module, fp, pathname, description)
        module_import_success = True
    except:
        module_import_success = False
        raise
else:
    module_import_success = False

## EXECUTION
class PluginOne(IPlugin):
    def __init__(self):
        pass

    def configure(self):
        """

        :return: return list of [configure success (bool), name, description, list of acceptable inputs, resource cost (1-10, 1=low), speed (1-10, 1=fast)]
        """
        config_options = config.options("Configuration")

        if 'cost' in config_options:
            cost = config.get('Configuration', 'cost')
        else:
            cost = 9999
        if 'speed' in config_options:
            speed = config.get('Configuration', 'speed')
        else:
            speed = 9999

        if 'type' in config_options:
            plugin_type = config.get('Configuration', 'type')
        else:
            logging.error("'Type' not specified in config file.")
            return [None, False, NAME, "Takes a list of IPs and returns ASN and BGP information as networkx graph of the information.", None, cost, speed]

        if 'inputs' in config_options:
            inputs = config.get('Configuration', 'Inputs')
            inputs = [l.strip().lower() for l in inputs.split(",")]
        else:
            logging.error("No input types specified in config file.")
            return [plugin_type, False, NAME, "Takes a list of IPs and returns ASN and BGP information as networkx graph of the information.", None, cost, speed]

        if not module_import_success:
            logging.error("Module import failure caused configuration failure.")
            return [plugin_type, False, NAME, "Takes a list of IPs and returns ASN and BGP information as networkx graph of the information.", inputs, cost, speed]
        else:
            return [plugin_type, True, NAME, "Takes a list of IPs and returns ASN and BGP information as networkx graph of the information.", inputs, cost, speed]

    def run(self, ips, start_time = ""):
        """ str, str -> networkx multiDiGraph

        :param ips: list of IP addresses to enrich in the graph
        :param start_time: string in ISO 8601 combined date and time format (e.g. 2014-11-01T10:34Z) or datetime object.
        :return: subgraph

        Note: based on From https://gist.github.com/zakird/11196064
        """

        # Parse the start_time
        if type(start_time) is str:
            try:
                time = dateutil.parser.parse(start_time).strftime("%Y-%m-%dT%H:%M:%SZ")
            except:
                time = datetime.utcnow().strftime("%Y-%m-%dT%H:%M:%SZ")
        elif type(start_time) is datetime:
            time = start_time.strftime("%Y-%m-%dT%H:%M:%SZ")
        else:
            time = datetime.utcnow().strftime("%Y-%m-%dT%H:%M:%SZ")

        # Since sometimes I just pass in an IP, we'll fix it here.
        if type(ips) == str:
            ips = [ips]

        # Validate IP
        for ip in ips:
            _ = ipaddress.ip_address(unicode(ip))

        g = nx.MultiDiGraph()

        # Create cymru ASN enrichment node
        cymru_asn_uri = "class=attribute&key={0}&value={1}".format("enrichment", "cymru_asn_enrichment")
        attributes = {
            'class': 'attribute',
            'key': 'enrichment',
            "value": "cymru_asn_enrichment",
            'uri': cymru_asn_uri,
            'start_time': time
        }
        g.add_node(cymru_asn_uri, attributes)

    #    print ips

        a = cymru_api.CymruIPtoASNService()

        for result in a.query(ips):
            try:
                t = dateutil.parser(result.allocated_at).strftime("%Y-%m-%dT%H:%M:%SZ")
            except:
                t = time
            # Create ip's node
            ip_uri = "class=attribute&key={0}&value={1}".format("ip", result.ip_address)
            g.add_node(ip_uri, {
                'class': 'attribute',
                'key': "ip",
                "value": result.ip_address,
                "start_time": time,
                "uri": ip_uri
            })

            # link to cymru ASN enrichment
            edge_attr = {
                "relationship": "describedBy",
                "origin": "cymru_asn_enrichment",
                "start_time": time,
            }
            source_hash = uuid.uuid3(uuid.NAMESPACE_URL, ip_uri)
            dest_hash = uuid.uuid3(uuid.NAMESPACE_URL, cymru_asn_uri)
            edge_uri = "source={0}&destionation={1}".format(str(source_hash), str(dest_hash))
            rel_chain = "relationship"
            while rel_chain in edge_attr:
                edge_uri = edge_uri + "&{0}={1}".format(rel_chain,edge_attr[rel_chain])
                rel_chain = edge_attr[rel_chain]
            if "origin" in edge_attr:
                edge_uri += "&{0}={1}".format("origin", edge_attr["origin"])
            edge_attr["uri"] = edge_uri
            g.add_edge(ip_uri, cymru_asn_uri, edge_uri, edge_attr)

            # Create bgp prefix node
            bgp_uri = "class=attribute&key={0}&value={1}".format("bgp", result.bgp_prefix)
            attributes = {
                'class': 'attribute',
                'key': 'bgp',
                'value': result.bgp_prefix,
                'uri': bgp_uri,
                'start_time': time
            }
            g.add_node(bgp_uri, attributes)

            # Link bgp prefix node to ip
            edge_attr = {
                "relationship": "describedBy",
                "origin": "cymru_asn_enrichment",
                "start_time": time,
            }
            source_hash = uuid.uuid3(uuid.NAMESPACE_URL, ip_uri)
            dest_hash = uuid.uuid3(uuid.NAMESPACE_URL, bgp_uri)
            edge_uri = "source={0}&destionation={1}".format(str(source_hash), str(dest_hash))
            rel_chain = "relationship"
            while rel_chain in edge_attr:
                edge_uri = edge_uri + "&{0}={1}".format(rel_chain,edge_attr[rel_chain])
                rel_chain = edge_attr[rel_chain]
            if "origin" in edge_attr:
                edge_uri += "&{0}={1}".format("origin", edge_attr["origin"])
            edge_attr["uri"] = edge_uri
            g.add_edge(ip_uri, bgp_uri, edge_uri, edge_attr)

            # create asn node
            asn_uri = "class=attribute&key={0}&value={1}".format("asn", result.as_number)
            attributes = {
                'class': 'attribute',
                'key': 'asn',
                'value': result.as_number,
                'uri': asn_uri,
                'start_time': time
            }
            try:
                attributes['owner'] = result.as_name
            except:
                pass
            g.add_node(asn_uri, attributes)

            # link bgp prefix to asn node
            edge_attr = {
                "relationship": "describedBy",
                "origin": "cymru_asn_enrichment",
                "start_time": t,
            }
            source_hash = uuid.uuid3(uuid.NAMESPACE_URL, ip_uri)
            dest_hash = uuid.uuid3(uuid.NAMESPACE_URL, asn_uri)
            edge_uri = "source={0}&destionation={1}".format(str(source_hash), str(dest_hash))
            rel_chain = "relationship"
            while rel_chain in edge_attr:
                edge_uri = edge_uri + "&{0}={1}".format(rel_chain,edge_attr[rel_chain])
                rel_chain = edge_attr[rel_chain]
            if "origin" in edge_attr:
                edge_uri += "&{0}={1}".format("origin", edge_attr["origin"])
            edge_attr["uri"] = edge_uri
            g.add_edge(ip_uri, asn_uri, edge_uri, edge_attr)

        # Return the data enriched IP as a graph
        return g


text:
zmodload zsh/datetime
zmodload zsh/stat
zmodload zsh/mathfunc

base=${BASE:-${ROOT:-/}var/tmp}
namedConf=${NAMED_CONF:-$(mktemp -p ${base} named.conf.XXXXXX)}

master=64.33.128.10
slaves=( 10.123.128.80 10.123.128.11 10.123.128.12 10.123.128.211 10.123.128.212 )

masterAXFR=$(mktemp -p ${base} master-axfr.XXXXXX)

slaveAXFR=$(mktemp -p ${base} slave-axfr.XXXXXX)

# clean up after ourselves
trap "rm -f ${namedConf} ${masterAXFR} ${slaveAXFR}; exit" 0 1 2

sudo scp root@bucky.airstreamcomm.net:/etc/named.conf ${namedConf}

# note: ${zones} is an array
zones=( $(grep "^zone" ${namedConf} | sed '1d' | cut -d"\"" -f2 | sort) )

startTime=${EPOCHSECONDS}

for domain in ${zones}
do
    rm -f ${masterAXFR} ${slaveAXFR}

    print "; ---------------   start ${domain}   ---------------"

    # get the zone from the master
    dig +nocmd +nostats @${master} ${domain} axfr > ${masterAXFR}

    # flag errors and move on
    if fgrep --quiet 'Transfer failed.' ${masterAXFR}
    then
	print "; -- ${domain}"
	cat ${masterAXFR}
	continue
    fi

    for slave in ${slaves}
    do
	rm -f ${slaveAXFR}

        # get the zone from the master
	dig +nocmd +nostats @${slave} ${domain} axfr > ${slaveAXFR}

        # flag errors and move on
	if fgrep --quiet 'Transfer failed.' ${slaveAXFR}
	then
	    printf "; -- %s -- %s: %s\n" ${slave} ${domain} "$(cat ${slaveAXFR})"
	    continue
	fi

	# compare the zone transfer results with the master
	if ! diff -q -i --ignore-all-space --ignore-matching-lines='IN[[:space:]][[:space:]]*SOA' ${masterAXFR} ${slaveAXFR} 2>& 1 > /dev/null
	then
	    print "; -- differences between ${master} and ${slave} for ${domain}"
	    diff -i --ignore-all-space --ignore-matching-lines='IN[[:space:]][[:space:]]*SOA' ${masterAXFR} ${slaveAXFR}
	    print ";\n"
	else
	    print "; -- ${domain}: ${slave} matches ${master}"
	fi
    done

    print "; ---------------    end  ${domain}   ---------------"
done

endTime=${EPOCHSECONDS}

print $(strftime "Start: %Y-%m-%d %T" ${startTime})
print $(strftime "Start: %Y-%m-%d %T" ${endTime})
print $(strftime "Duration: %T" $((endTime - startTime)) )


text:
package com.bazaarvoice.elasticsearch.client;

import org.elasticsearch.action.delete.DeleteRequestBuilder;
import org.elasticsearch.action.delete.DeleteResponse;
import org.elasticsearch.action.index.IndexRequestBuilder;
import org.testng.annotations.Test;

import static org.testng.Assert.assertEquals;
import static org.testng.Assert.assertTrue;

public class DeleteTest extends JerseyRestClientTest {

    public static final String ID = "delete-test-id-1";

    @Test public void testDelete() {
        final IndexRequestBuilder indexRequestBuilder = restClient().prepareIndex("testidx", "testtype", ID).setSource("field", "value").setRefresh(true);
        indexRequestBuilder.execute().actionGet();

        final DeleteRequestBuilder deleteRequestBuilder = restClient().prepareDelete("testidx", "testtype", ID);
        final DeleteResponse deleteResponse = deleteRequestBuilder.execute().actionGet();
        assertEquals(deleteResponse.getIndex(), "testidx");
        assertEquals(deleteResponse.getType(), "testtype");
        assertEquals(deleteResponse.getId(), ID);
        assertEquals(deleteResponse.getVersion(), 2);
        assertTrue(deleteResponse.isFound());
    }
}


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
in Flörke, Mag. Neuesten Entdeck. Gesammten Naturk. Ges. Naturf. Freunde Berlin 3: 127 (1809)

#### Original name
Pulmonaria praemorsa Bory

### Remarks
null


text:
#ifndef __UIEditBoxIMPLMAC_H__
#define __UIEditBoxIMPLMAC_H__

#include "platform/CCPlatformConfig.h"

#if (CC_TARGET_PLATFORM == CC_PLATFORM_MAC)

#include "UIEditBoxImpl.h"

@class UIEditBoxImplMac;

NS_CC_BEGIN

namespace ui {

class EditBox;

class EditBoxImplMac : public EditBoxImpl
{
public:
    /**
     * @js NA
     */
    EditBoxImplMac(EditBox* pEditText);
    /**
     * @js NA
     * @lua NA
     */
    virtual ~EditBoxImplMac();

    virtual bool initWithSize(const Size& size);
    virtual void setFont(const char* pFontName, int fontSize);
    virtual void setFontColor(const Color4B& color);
    virtual void setPlaceholderFont(const char* pFontName, int fontSize);
    virtual void setPlaceholderFontColor(const Color4B& color);
    virtual void setInputMode(EditBox::InputMode inputMode);
    virtual void setInputFlag(EditBox::InputFlag inputFlag);
    virtual void setMaxLength(int maxLength);
    virtual int  getMaxLength();
    virtual void setReturnType(EditBox::KeyboardReturnType returnType);
    virtual bool isEditing();

    virtual void setText(const char* pText);
    virtual const char* getText(void);
    virtual void setPlaceHolder(const char* pText);
    virtual void setPosition(const Vec2& pos);
    virtual void setVisible(bool visible);
    virtual void setContentSize(const Size& size);
    virtual void setAnchorPoint(const Vec2& anchorPoint);
    /**
     * @js NA
     * @lua NA
     */
    virtual void draw(Renderer *renderer, const Mat4 &transform, uint32_t flags)override;
    virtual void doAnimationWhenKeyboardMove(float duration, float distance);
    virtual void openKeyboard();
    virtual void closeKeyboard();
    virtual void updatePosition(float dt) override;
    /**
     * @js NA
     * @lua NA
     */
    virtual void onEnter(void);
private:
    NSPoint    convertDesignCoordToScreenCoord(const Vec2& designCoord, bool bInRetinaMode);
    void       adjustTextFieldPosition();
    NSFont*    constructFont(const char* fontName, int fontSize);
    Size              _contentSize;
    Vec2              _position;
    Vec2              _anchorPoint;
    int               _maxTextLength;
    bool              _inRetinaMode;
    UIEditBoxImplMac* _sysEdit;
};

}

NS_CC_END

#endif // #if (CC_TARGET_PLATFORM == CC_PLATFORM_MAC)

#endif /* __UIEditBoxIMPLMAC_H__ */


text:
package org.apache.hadoop.mapred.jobcontrol;

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

import org.apache.hadoop.classification.InterfaceAudience;
import org.apache.hadoop.classification.InterfaceStability;
import org.apache.hadoop.mapreduce.lib.jobcontrol.ControlledJob;

/**
 **/
@InterfaceAudience.Public
@InterfaceStability.Stable
public class JobControl extends
    org.apache.hadoop.mapreduce.lib.jobcontrol.JobControl {

  /**
   * Construct a job control for a group of jobs.
   * @param groupName a name identifying this group
   */
  public JobControl(String groupName) {
    super(groupName);
  }

  static ArrayList<Job> castToJobList(List<ControlledJob> cjobs) {
    ArrayList<Job> ret = new ArrayList<Job>();
    for (ControlledJob job : cjobs) {
      ret.add((Job)job);
    }
    return ret;
  }

  /**
   * @return the jobs in the waiting state
   */
  public ArrayList<Job> getWaitingJobs() {
    return castToJobList(super.getWaitingJobList());
  }

  /**
   * @return the jobs in the running state
   */
  public ArrayList<Job> getRunningJobs() {
    return castToJobList(super.getRunningJobList());
  }

  /**
   * @return the jobs in the ready state
   */
  public ArrayList<Job> getReadyJobs() {
    return castToJobList(super.getReadyJobsList());
  }

  /**
   * @return the jobs in the success state
   */
  public ArrayList<Job> getSuccessfulJobs() {
    return castToJobList(super.getSuccessfulJobList());
  }

  public ArrayList<Job> getFailedJobs() {
    return castToJobList(super.getFailedJobList());
  }

  /**
   * Add a collection of jobs
   *
   * @param jobs
   */
  public void addJobs(Collection <Job> jobs) {
    for (Job job : jobs) {
      addJob(job);
    }
  }

  /**
   * @return the thread state
   */
  public int getState() {
    ThreadState state = super.getThreadState();
    if (state == ThreadState.RUNNING) {
      return 0;
    }
    if (state == ThreadState.SUSPENDED) {
      return 1;
    }
    if (state == ThreadState.STOPPED) {
      return 2;
    }
    if (state == ThreadState.STOPPING) {
      return 3;
    }
    if (state == ThreadState.READY ) {
      return 4;
    }
    return -1;
  }

}


text:
DEFINE_int32(tokens_reserve_size, 1400000,
             "Reserve the specified size of token buffer in advance.");

namespace mozc {
namespace dictionary {
namespace {

// Functor to sort a sequence of Tokens first by value and then by key.
struct OrderByValueThenByKey {
  bool operator()(const Token *l, const Token *r) const {
    const int comp = l->value.compare(r->value);
    return comp == 0 ? (l->key < r->key) : (comp < 0);
  }
};

// Provides a view of Token iterator as a pair of value and key.  Used to look
// up tokens from a sorted range of Token pointers using value and key.
struct AsValueAndKey : public AdapterBase<pair<StringPiece, StringPiece> > {
  value_type operator()(vector<Token *>::const_iterator iter) const {
    const Token *token = *iter;
    return pair<StringPiece, StringPiece>(token->value, token->key);
  }
};

// Provides a view of Token iterator as a value string.  Used to look up tokens
// from a sorted range of Tokens using value.
struct AsValue : public AdapterBase<StringPiece> {
  value_type operator()(vector<Token *>::const_iterator iter) const {
    return StringPiece((*iter)->value);
  }
};

// Parses one line of reading correction file.  Since the result is returned as
// StringPieces, |line| needs to outlive |value_key|.
void ParseReadingCorrectionTSV(const string &line,
                               pair<StringPiece, StringPiece> *value_key) {
  // Format: value\terror\tcorrect
  SplitIterator<SingleDelimiter> iter(line, "\t");
  CHECK(!iter.Done());
  value_key->first = iter.Get();
  iter.Next();
  CHECK(!iter.Done());
  value_key->second = iter.Get();
}

// Helper function to parse an integer from a string.
inline bool SafeStrToInt(StringPiece s, int *n) {
  uint32 u32 = 0;
  const bool ret = NumberUtil::SafeStrToUInt32(s, &u32);
  *n = u32;
  return ret;
}

// Helper functions to get const iterators.
inline vector<Token *>::const_iterator CBegin(const vector<Token *> &tokens) {
  return tokens.begin();
}

inline vector<Token *>::const_iterator CEnd(const vector<Token *> &tokens) {
  return tokens.end();
}

}  // namespace

TextDictionaryLoader::TextDictionaryLoader(const POSMatcher &pos_matcher)
    : pos_matcher_(&pos_matcher) {
}

TextDictionaryLoader::~TextDictionaryLoader() {
  Clear();
}

bool TextDictionaryLoader::RewriteSpecialToken(Token *token,
                                               StringPiece label) const {
  CHECK(token);
  if (label.empty()) {
    return true;
  }
  if (Util::StartsWith(label, "SPELLING_CORRECTION")) {
    token->attributes = Token::SPELLING_CORRECTION;
    return true;
  }
  if (Util::StartsWith(label, "ZIP_CODE")) {
    token->lid = pos_matcher_->GetZipcodeId();
    token->rid = pos_matcher_->GetZipcodeId();
    return true;
  }
  if (Util::StartsWith(label, "ENGLISH")) {
    // TODO(noriyukit): Might be better to use special POS for english words.
    token->lid = pos_matcher_->GetIsolatedWordId();
    token->rid = pos_matcher_->GetIsolatedWordId();
    return true;
  }
  LOG(ERROR) << "Unknown special label: " << label;
  return false;
}

void TextDictionaryLoader::Load(const string &dictionary_filename,
                                const string &reading_correction_filename) {
  LoadWithLineLimit(dictionary_filename, reading_correction_filename, -1);
}

void TextDictionaryLoader::LoadWithLineLimit(
    const string &dictionary_filename,
    const string &reading_correction_filename,
    int limit) {
  Clear();

  // Roughly allocate buffers for Token pointers.
  if (limit < 0) {
    tokens_.reserve(FLAGS_tokens_reserve_size);
    limit = numeric_limits<int>::max();
  } else {
    tokens_.reserve(limit);
  }

  // Read system dictionary.
  {
    InputMultiFile file(dictionary_filename);
    string line;
    while (limit > 0 && file.ReadLine(&line)) {
      Util::ChopReturns(&line);
      Token *token = ParseTSVLine(line);
      if (token) {
        tokens_.push_back(token);
        --limit;
      }
    }
    LOG(INFO) << tokens_.size() << " tokens from " << dictionary_filename;
  }

  if (reading_correction_filename.empty() || limit <= 0) {
    return;
  }

  // Prepare for loading reading corrections. We sort |tokens_| first by value
  // and then by key so that we can perform the following operations both in
  // O(log(N)), where N is the size of tokens.
  //   1. Checking the existence of any key-value pairs: This can be done by
  //      binary-searching for a pair of value and key.
  //   2. Accessing all the tokens that have the same value: Since tokens are
  //      also sorted in order of value, this can be done by finding a range of
  //      tokens that have the same value.
  sort(tokens_.begin(), tokens_.end(), OrderByValueThenByKey());

  vector<Token *> reading_correction_tokens;
  LoadReadingCorrectionTokens(reading_correction_filename, tokens_,
                              &limit, &reading_correction_tokens);
  const size_t tokens_size = tokens_.size();
  tokens_.resize(tokens_size + reading_correction_tokens.size());
  for (size_t i = 0; i < reading_correction_tokens.size(); ++i) {
    // |tokens_| takes the ownership of each allocated token.
    tokens_[tokens_size + i] = reading_correction_tokens[i];
  }
}

// Loads reading correction data into |tokens|.  The second argument is used to
// determine costs of reading correction tokens and must be sorted by
// OrderByValueThenByKey().  The output tokens are newly allocated and the
// caller is responsible to delete them.
void TextDictionaryLoader::LoadReadingCorrectionTokens(
    const string &reading_correction_filename,
    const vector<Token *> &ref_sorted_tokens,
    int *limit,
    vector<Token *> *tokens) {
  // Load reading correction entries.
  int reading_correction_size = 0;

  InputMultiFile file(reading_correction_filename);
  string line;
  while (file.ReadLine(&line)) {
    if (line.empty() || line[0] == '#') {
      continue;
    }

    // Parse TSV line in a pair of value and key (Note: first element is value
    // and the second key).
    Util::ChopReturns(&line);
    pair<StringPiece, StringPiece> value_key;
    ParseReadingCorrectionTSV(line, &value_key);

    // Filter the entry if this key value pair already exists in the system
    // dictionary.
    if (binary_search(
            MakeIteratorAdapter(ref_sorted_tokens.begin(), AsValueAndKey()),
            MakeIteratorAdapter(ref_sorted_tokens.end(), AsValueAndKey()),
            value_key)) {
      VLOG(1) << "System dictionary has the same key-value: " << line;
      continue;
    }

    // Since reading correction entries lack POS and cost, we recover those
    // fields from a token in the system dictionary that has the same value.
    // Since multple tokens may have the same value, from such tokens, we
    // select the one that has the maximum cost.
    typedef vector<Token *>::const_iterator TokenIterator;
    typedef IteratorAdapter<TokenIterator, AsValue> AsValueIterator;
    typedef pair<AsValueIterator, AsValueIterator> Range;
    Range range = equal_range(
        MakeIteratorAdapter(CBegin(ref_sorted_tokens), AsValue()),
        MakeIteratorAdapter(CEnd(ref_sorted_tokens), AsValue()),
        value_key.first);
    TokenIterator begin = range.first.base(), end = range.second.base();
    if (begin == end) {
      VLOG(1) << "Cannot find the value in system dicitonary - ignored:"
              << line;
      continue;
    }
    // Now [begin, end) contains all the tokens that have the same value as
    // this reading correction entry.  Next, find the token that has the
    // maximum cost in [begin, end).  Note that linear search is sufficiently
    // fast here because the size of the range is small.
    const Token *max_cost_token = *begin;
    for (++begin; begin != end; ++begin) {
      if ((*begin)->cost > max_cost_token->cost) {
        max_cost_token = *begin;
      }
    }

    // The cost is calculated as -log(prob) * 500.
    // We here assume that the wrong reading appear with 1/100 probability
    // of the original (correct) reading.
    const int kCostPenalty = 2302;      // -log(1/100) * 500;
    scoped_ptr<Token> token(new Token);
    value_key.second.CopyToString(&token->key);
    token->value = max_cost_token->value;
    token->lid = max_cost_token->lid;
    token->rid = max_cost_token->rid;
    token->cost = max_cost_token->cost + kCostPenalty;
    // We don't set SPELLING_CORRECTION. The entries in reading_correction
    // data are also stored in rewriter/correction_rewriter.cc.
    // reading_correction_rewriter annotates the spelling correction
    // notations.
    token->attributes = Token::NONE;
    tokens->push_back(token.release());
    ++reading_correction_size;
    if (--*limit <= 0) {
      break;
    }
  }
  LOG(INFO) << reading_correction_size << " tokens from "
            << reading_correction_filename;
}

void TextDictionaryLoader::Clear() {
  STLDeleteElements(&tokens_);
}

void TextDictionaryLoader::CollectTokens(vector<Token *> *res) const {
  DCHECK(res);
  res->reserve(res->size() + tokens_.size());
  res->insert(res->end(), tokens_.begin(), tokens_.end());
}

Token *TextDictionaryLoader::ParseTSVLine(StringPiece line) const {
  vector<StringPiece> columns;
  Util::SplitStringUsing(line, "\t", &columns);
  return ParseTSV(columns);
}

Token *TextDictionaryLoader::ParseTSV(
    const vector<StringPiece> &columns) const {
  CHECK_LE(5, columns.size()) << "Lack of columns: " << columns.size();

  scoped_ptr<Token> token(new Token);

  // Parse key, lid, rid, cost, value.
  Util::NormalizeVoicedSoundMark(columns[0], &token->key);
  CHECK(SafeStrToInt(columns[1], &token->lid))
      << "Wrong lid: " << columns[1];
  CHECK(SafeStrToInt(columns[2], &token->rid))
      << "Wrong rid: " << columns[2];
  CHECK(SafeStrToInt(columns[3], &token->cost))
      << "Wrong cost: " << columns[3];
  Util::NormalizeVoicedSoundMark(columns[4], &token->value);

  // Optionally, label (SPELLING_CORRECTION, ZIP_CODE, etc.) may be provided in
  // column 6.
  if (columns.size() > 5) {
    CHECK(RewriteSpecialToken(token.get(), columns[5]))
        << "Invalid label: " << columns[5];
  }
  return token.release();
}

}  // namespace dictionary
}  // namespace mozc


text:
// This code contains NVIDIA Confidential Information and is disclosed to you
// under a form of NVIDIA software license agreement provided separately to you.
//
// Notice
// NVIDIA Corporation and its licensors retain all intellectual property and
// proprietary rights in and to this software and related documentation and
// any modifications thereto. Any use, reproduction, disclosure, or
// distribution of this software and related documentation without an express
// license agreement from NVIDIA Corporation is strictly prohibited.
//
// ALL NVIDIA DESIGN SPECIFICATIONS, CODE ARE PROVIDED "AS IS.". NVIDIA MAKES
// NO WARRANTIES, EXPRESSED, IMPLIED, STATUTORY, OR OTHERWISE WITH RESPECT TO
// THE MATERIALS, AND EXPRESSLY DISCLAIMS ALL IMPLIED WARRANTIES OF NONINFRINGEMENT,
// MERCHANTABILITY, AND FITNESS FOR A PARTICULAR PURPOSE.
//
// Information and code furnished is believed to be accurate and reliable.
// However, NVIDIA Corporation assumes no responsibility for the consequences of use of such
// information or for any infringement of patents or other rights of third parties that may
// result from its use. No license is granted by implication or otherwise under any patent
// or patent rights of NVIDIA Corporation. Details are subject to change without notice.
// This code supersedes and replaces all information previously supplied.
// NVIDIA Corporation products are not authorized for use as critical
// components in life support devices or systems without express written approval of
// NVIDIA Corporation.
//
// Copyright (c) 2008-2012 NVIDIA Corporation. All rights reserved.
// Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved.
// Copyright (c) 2001-2004 NovodeX AG. All rights reserved.

#ifndef PX_PHYSICS_GEOMETRYHELPERS
#define PX_PHYSICS_GEOMETRYHELPERS
/** \addtogroup geomutils
@{
*/

#include "common/PxPhysXCommon.h"
#include "PxGeometry.h"
#include "PxBoxGeometry.h"
#include "PxSphereGeometry.h"
#include "PxCapsuleGeometry.h"
#include "PxPlaneGeometry.h"
#include "PxConvexMeshGeometry.h"
#include "PxTriangleMeshGeometry.h"
#include "PxHeightFieldGeometry.h"
#include "foundation/PxPlane.h"
#include "foundation/PxTransform.h"
#include "foundation/PxUnionCast.h"

#ifndef PX_DOXYGEN
namespace physx
{
#endif

/**
\brief Geometry holder class

This class contains enough space to hold a value of any PxGeometry subtype.

Its principal use is as a convenience class to allow geometries to be returned polymorphically
from functions. See PxShape::getGeometry();
*/

PX_ALIGN_PREFIX(4)
class PxGeometryHolder
{
public:
	PX_FORCE_INLINE PxGeometryType::Enum getType() const
	{
		return any().getType();
	}

	PX_FORCE_INLINE PxGeometry& any()
	{
		return *PxUnionCast<PxGeometry*>(&bytes.geometry);
	}

	PX_FORCE_INLINE const PxGeometry& any() const
	{
		return *PxUnionCast<const PxGeometry*>(&bytes.geometry);
	}

	PX_FORCE_INLINE PxSphereGeometry& sphere()
	{
		return get<PxSphereGeometry, PxGeometryType::eSPHERE>();
	}

	PX_FORCE_INLINE const PxSphereGeometry& sphere() const
	{
		return get<const PxSphereGeometry, PxGeometryType::eSPHERE>();
	}

	PX_FORCE_INLINE PxPlaneGeometry& plane()
	{
		return get<PxPlaneGeometry, PxGeometryType::ePLANE>();
	}

	PX_FORCE_INLINE const PxPlaneGeometry& plane() const
	{
		return get<const PxPlaneGeometry, PxGeometryType::ePLANE>();
	}

	PX_FORCE_INLINE PxCapsuleGeometry& capsule()
	{
		return get<PxCapsuleGeometry, PxGeometryType::eCAPSULE>();
	}

	PX_FORCE_INLINE const PxCapsuleGeometry& capsule() const
	{
		return get<const PxCapsuleGeometry, PxGeometryType::eCAPSULE>();
	}

	PX_FORCE_INLINE PxBoxGeometry& box()
	{
		return get<PxBoxGeometry, PxGeometryType::eBOX>();
	}

	PX_FORCE_INLINE const PxBoxGeometry& box() const
	{
		return get<const PxBoxGeometry, PxGeometryType::eBOX>();
	}

	PX_FORCE_INLINE PxConvexMeshGeometry& convexMesh()
	{
		return get<PxConvexMeshGeometry, PxGeometryType::eCONVEXMESH>();
	}

	PX_FORCE_INLINE const PxConvexMeshGeometry& convexMesh() const
	{
		return get<const PxConvexMeshGeometry, PxGeometryType::eCONVEXMESH>();
	}

	PX_FORCE_INLINE PxTriangleMeshGeometry& triangleMesh()
	{
		return get<PxTriangleMeshGeometry, PxGeometryType::eTRIANGLEMESH>();
	}

	PX_FORCE_INLINE const PxTriangleMeshGeometry& triangleMesh() const
	{
		return get<const PxTriangleMeshGeometry, PxGeometryType::eTRIANGLEMESH>();
	}

	PX_FORCE_INLINE PxHeightFieldGeometry& heightField()
	{
		return get<PxHeightFieldGeometry, PxGeometryType::eHEIGHTFIELD>();
	}

	PX_FORCE_INLINE const PxHeightFieldGeometry& heightField() const
	{
		return get<const PxHeightFieldGeometry, PxGeometryType::eHEIGHTFIELD>();
	}

	private:
		template<typename T, PxGeometryType::Enum type> T& get()
		{
			PX_ASSERT(getType() == type);
			return static_cast<T&>(any());
		}

		template<typename T, PxGeometryType::Enum type> T& get() const
		{
			PX_ASSERT(getType() == type);
			return static_cast<T&>(any());
		}

	union {
		PxU8	geometry[sizeof(PxGeometry)];
		PxU8	box[sizeof(PxBoxGeometry)];
		PxU8	sphere[sizeof(PxSphereGeometry)];
		PxU8	capsule[sizeof(PxCapsuleGeometry)];
		PxU8	plane[sizeof(PxPlaneGeometry)];
		PxU8	convex[sizeof(PxConvexMeshGeometry)];
		PxU8	mesh[sizeof(PxTriangleMeshGeometry)];
		PxU8	heightfield[sizeof(PxHeightFieldGeometry)];
	} bytes;
}
PX_ALIGN_SUFFIX(4);

#ifndef PX_DOXYGEN
} // namespace physx
#endif

/** @} */
#endif


text:
package im.mange.backdoor.expect

trait Expectation {
  def isVerified: Boolean
  def describeFailure: String
}

case class Verify(expectation: Expectation)


text:
require 'ads_common/savon_service'
require 'dfp_api/v201508/creative_service_registry'

module DfpApi; module V201508; module CreativeService
  class CreativeService < AdsCommon::SavonService
    def initialize(config, endpoint)
      namespace = 'https://www.google.com/apis/ads/publisher/v201508'
      super(config, endpoint, namespace, :v201508)
    end

    def create_creatives(*args, &block)
      return execute_action('create_creatives', args, &block)
    end

    def create_creatives_to_xml(*args)
      return get_soap_xml('create_creatives', args)
    end

    def get_creatives_by_statement(*args, &block)
      return execute_action('get_creatives_by_statement', args, &block)
    end

    def get_creatives_by_statement_to_xml(*args)
      return get_soap_xml('get_creatives_by_statement', args)
    end

    def update_creatives(*args, &block)
      return execute_action('update_creatives', args, &block)
    end

    def update_creatives_to_xml(*args)
      return get_soap_xml('update_creatives', args)
    end

    private

    def get_service_registry()
      return CreativeServiceRegistry
    end

    def get_module()
      return DfpApi::V201508::CreativeService
    end
  end
end; end; end


text:
/*
 * File: strlib.cpp
 * ----------------
 * This file implements the strlib.h interface.
 */

#include <cctype>
#include <iomanip>
#include <iostream>
#include <sstream>
#include "error.h"
#include "strlib.h"
using namespace std;

/* Function prototypes */

/*
 * Implementation notes: numeric conversion
 * ----------------------------------------
 * These functions use the <sstream> library to perform the conversion.
 */

string integerToString(int n) {
   ostringstream stream;
   stream << n;
   return stream.str();
}

int stringToInteger(string str) {
   istringstream stream(str);
   int value;
   stream >> value >> ws;
   if (stream.fail() || !stream.eof()) {
      error("stringToInteger: Illegal integer format (" + str + ")");
   }
   return value;
}

string realToString(double d) {
   ostringstream stream;
   stream << uppercase << d;
   return stream.str();
}

double stringToReal(string str) {
   istringstream stream(str);
   double value;
   stream >> value >> ws;
   if (stream.fail() || !stream.eof()) {
      error("stringToReal: Illegal floating-point format (" + str + ")");
   }
   return value;
}

/*
 * Implementation notes: case conversion
 * -------------------------------------
 * The functions toUpperCase and toLowerCase return a new string whose
 * characters appear in the desired case. These implementations rely on
 * the fact that the characters in the string are copied when the
 * argument is passed to the function, which makes it possible to change
 * the case of the copy without affecting the original.
 */

string toUpperCase(string str) {
   int nChars = str.length();
   for (int i = 0; i < nChars; i++) {
      str[i] = toupper(str[i]);
   }
   return str;
}

string toLowerCase(string str) {
   int nChars = str.length();
   for (int i = 0; i < nChars; i++) {
      str[i] = tolower(str[i]);
   }
   return str;
}

/*
 * Implementation notes: equalsIgnoreCase
 * --------------------------------------
 * This implementation uses a for loop to cycle through the characters in
 * each string.  Converting each string to uppercase and then comparing
 * the results makes for a shorter but less efficient implementation.
 */

bool equalsIgnoreCase(string s1, string s2) {
   if (s1.length() != s2.length()) return false;
   int nChars = s1.length();
   for (int i = 0; i < nChars; i++) {
      if (tolower(s1[i]) != tolower(s2[i])) return false;
   }
   return true;
}

/*
 * Implementation notes: startsWith, endsWith
 * ------------------------------------------
 * These implementations are overloaded to allow the second argument to
 * be either a string or a character.
 */

bool startsWith(string str, string prefix) {
   if (str.length() < prefix.length()) return false;
   int nChars = prefix.length();
   for (int i = 0; i < nChars; i++) {
      if (str[i] != prefix[i]) return false;
   }
   return true;
}

bool startsWith(string str, char prefix) {
   return str.length() > 0 && str[0] == prefix;
}

bool endsWith(string str, string suffix) {
   int nChars = suffix.length();
   int start = str.length() - nChars;
   if (start < 0) return false;
   for (int i = 0; i < nChars; i++) {
      if (str[start + i] != suffix[i]) return false;
   }
   return true;
}

bool endsWith(string str, char suffix) {
   return str.length() > 0 && str[str.length() - 1] == suffix;
}

string trim(string str) {
   int finish = str.length() - 1;
   while (finish >= 0 && isspace(str[finish])) {
      finish--;
   }
   int start = 0;
   while (start <= finish && isspace(str[start])) {
      start++;
   }
   return str.substr(start, finish - start + 1);
}

/*
 * Implementation notes: readQuotedString and writeQuotedString
 * ------------------------------------------------------------
 * Most of the work in these functions has to do with escape sequences.
 */

static const string STRING_DELIMITERS = ",:)}]\n";

bool stringNeedsQuoting(const string & str) {
   int n = str.length();
   for (int i = 0; i < n; i++) {
      char ch = str[i];
      if (isspace(ch)) return false;
      if (STRING_DELIMITERS.find(ch) != string::npos) return true;
   }
   return false;
}

void readQuotedString(istream & is, string & str) {
   str = "";
   char ch;
   while (is.get(ch) && isspace(ch)) {
      /* Empty */
   }
   if (is.fail()) return;
   if (ch == '\'' || ch == '"') {
      char delim = ch;
      while (is.get(ch) && ch != delim) {
         if (is.fail()) error("Unterminated string");
         if (ch == '\\') {
            if (!is.get(ch)) error("Unterminated string");
            if (isdigit(ch) || ch == 'x') {
               int maxDigits = 3;
               int base = 8;
               if (ch == 'x') {
                  base = 16;
                  maxDigits = 2;
               }
               int result = 0;
               int digit = 0;
               for (int i = 0; i < maxDigits && ch != delim; i++) {
                  if (isdigit(ch)) {
                     digit = ch - '0';
                  } else if (base == 16 && isxdigit(ch)) {
                     digit = toupper(ch) - 'A' + 10;
                  } else {
                     break;
                  }
                  result = base * result + digit;
                  if (!is.get(ch)) error("Unterminated string");
               }
               ch = char(result);
               is.unget();
            } else {
               switch (ch) {
                case 'a': ch = '\a'; break;
                case 'b': ch = '\b'; break;
                case 'f': ch = '\f'; break;
                case 'n': ch = '\n'; break;
                case 'r': ch = '\r'; break;
                case 't': ch = '\t'; break;
                case 'v': ch = '\v'; break;
                case '"': ch = '"'; break;
                case '\'': ch = '\''; break;
                case '\\': ch = '\\'; break;
               }
            }
         }
         str += ch;
      }
   } else {
      str += ch;
      int endTrim = 0;
      while (is.get(ch) && STRING_DELIMITERS.find(ch) == string::npos) {
         str += ch;
         if (!isspace(ch)) endTrim = str.length();
      }
      if (is) is.unget();
      str = str.substr(0, endTrim);
   }
}

void writeQuotedString(ostream & os, const string & str, bool forceQuotes) {
   if (!forceQuotes && stringNeedsQuoting(str)) forceQuotes = true;
   if (forceQuotes) os << '"';
   int len = str.length();
   for (int i = 0; i < len; i++) {
      char ch = str.at(i);
      switch (ch) {
       case '\a': os << "\\a"; break;
       case '\b': os << "\\b"; break;
       case '\f': os << "\\f"; break;
       case '\n': os << "\\n"; break;
       case '\r': os << "\\r"; break;
       case '\t': os << "\\t"; break;
       case '\v': os << "\\v"; break;
       case '\\': os << "\\\\"; break;
       default:
         if (isprint(ch) && ch != '"') {
            os << ch;
         } else {
            ostringstream oss;
            oss << oct << setw(3) << setfill('0') << (int(ch) & 0xFF);
            os << "\\" << oss.str();
         }
      }
   }
   if (forceQuotes) os << '"';
}


text:
class AppControllerProfileObserver;
@class AppShimMenuController;
class BookmarkMenuBridge;
class CommandUpdater;
class GURL;
class HandoffActiveURLObserverBridge;
@class HandoffManager;
class HistoryMenuBridge;
class Profile;
@class ProfileMenuController;
class QuitWithAppsController;
class ScopedKeepAlive;

namespace ui {
class WorkAreaWatcherObserver;
}

// The application controller object, created by loading the MainMenu nib.
// This handles things like responding to menus when there are no windows
// open, etc and acts as the NSApplication delegate.
@interface AppController : NSObject<NSUserInterfaceValidations,
                                    NSMenuDelegate,
                                    NSApplicationDelegate> {
 @private
  // Manages the state of the command menu items.
  std::unique_ptr<CommandUpdater> menuState_;

  // The profile last used by a Browser. It is this profile that was used to
  // build the user-data specific main menu items.
  Profile* lastProfile_;

  // The ProfileObserver observes the ProfileAttrbutesStorage and gets notified
  // when a profile has been deleted.
  std::unique_ptr<AppControllerProfileObserver>
      profileAttributesStorageObserver_;

  // Management of the bookmark menu which spans across all windows
  // (and Browser*s). |profileBookmarkMenuBridgeMap_| is a cache that owns one
  // pointer to a BookmarkMenuBridge for each profile. |bookmarkMenuBridge_| is
  // a weak pointer that is updated to match the corresponding cache entry
  // during a profile switch.
  BookmarkMenuBridge* bookmarkMenuBridge_;
  std::map<base::FilePath, BookmarkMenuBridge*> profileBookmarkMenuBridgeMap_;

  std::unique_ptr<HistoryMenuBridge> historyMenuBridge_;

  // Controller that manages main menu items for packaged apps.
  base::scoped_nsobject<AppShimMenuController> appShimMenuController_;

  // The profile menu, which appears right before the Help menu. It is only
  // available when multiple profiles is enabled.
  base::scoped_nsobject<ProfileMenuController> profileMenuController_;

  // If we're told to open URLs (in particular, via |-application:openFiles:| by
  // Launch Services) before we've launched the browser, we queue them up in
  // |startupUrls_| so that they can go in the first browser window/tab.
  std::vector<GURL> startupUrls_;
  BOOL startupComplete_;

  // Outlets for the close tab/window menu items so that we can adjust the
  // commmand-key equivalent depending on the kind of window and how many
  // tabs it has.
  IBOutlet NSMenuItem* closeTabMenuItem_;
  IBOutlet NSMenuItem* closeWindowMenuItem_;

  // Outlet for the help menu so we can bless it so Cocoa adds the search item
  // to it.
  IBOutlet NSMenu* helpMenu_;

  // If we are expecting a workspace change in response to a reopen
  // event, the time we got the event. A null time otherwise.
  base::TimeTicks reopenTime_;

  // Observers that listen to the work area changes.
  base::ObserverList<ui::WorkAreaWatcherObserver> workAreaChangeObservers_;

  std::unique_ptr<PrefChangeRegistrar> profilePrefRegistrar_;
  PrefChangeRegistrar localPrefRegistrar_;

  // Displays a notification when quitting while apps are running.
  scoped_refptr<QuitWithAppsController> quitWithAppsController_;

  // Responsible for maintaining all state related to the Handoff feature.
  base::scoped_nsobject<HandoffManager> handoffManager_;

  // Observes changes to the active URL.
  std::unique_ptr<HandoffActiveURLObserverBridge>
      handoff_active_url_observer_bridge_;

  // This will be true after receiving a NSWorkspaceWillPowerOffNotification.
  BOOL isPoweringOff_;

  // Request to keep the browser alive during that object's lifetime.
  std::unique_ptr<ScopedKeepAlive> keep_alive_;
}

@property(readonly, nonatomic) BOOL startupComplete;
@property(readonly, nonatomic) Profile* lastProfile;

// Helper method used to update the "Signin" menu item in the main menu and the
// wrench menu to reflect the current signed in state.
+ (void)updateSigninItem:(id)signinItem
              shouldShow:(BOOL)showSigninMenuItem
          currentProfile:(Profile*)profile;

- (void)didEndMainMessageLoop;

// Try to close all browser windows, and if that succeeds then quit.
- (BOOL)tryToTerminateApplication:(NSApplication*)app;

// Stop trying to terminate the application. That is, prevent the final browser
// window closure from causing the application to quit.
- (void)stopTryingToTerminateApplication:(NSApplication*)app;

// Indicate that the system is powering off or logging out.
- (void)willPowerOff:(NSNotification*)inNotification;

// Returns true if there is a modal window (either window- or application-
// modal) blocking the active browser. Note that tab modal dialogs (HTTP auth
// sheets) will not count as blocking the browser. But things like open/save
// dialogs that are window modal will block the browser.
- (BOOL)keyWindowIsModal;

// Called when the user picks a menu item when there are no key windows, or when
// there is no foreground browser window. Calls through to the browser object to
// execute the command. This assumes that the command is supported and doesn't
// check, otherwise it should have been disabled in the UI in
// |-validateUserInterfaceItem:|.
- (void)commandDispatch:(id)sender;

// Show the preferences window, or bring it to the front if it's already
// visible.
- (IBAction)showPreferences:(id)sender;

// Redirect in the menu item from the expected target of "File's
// Owner" (NSApplication) for a Branded About Box
- (IBAction)orderFrontStandardAboutPanel:(id)sender;

// Toggles the "Confirm to Quit" preference.
- (IBAction)toggleConfirmToQuit:(id)sender;

// Delegate method to return the dock menu.
- (NSMenu*)applicationDockMenu:(NSApplication*)sender;

// Get the URLs that Launch Services expects the browser to open at startup.
- (const std::vector<GURL>&)startupUrls;

- (BookmarkMenuBridge*)bookmarkMenuBridge;
- (HistoryMenuBridge*)historyMenuBridge;

// Subscribes/unsubscribes from the work area change notification.
- (void)addObserverForWorkAreaChange:(ui::WorkAreaWatcherObserver*)observer;
- (void)removeObserverForWorkAreaChange:(ui::WorkAreaWatcherObserver*)observer;

// Initializes the AppShimMenuController. This enables changing the menu bar for
// apps.
- (void)initAppShimMenuController;

// Called when the user has changed browser windows, meaning the backing profile
// may have changed. This can cause a rebuild of the user-data menus. This is a
// no-op if the new profile is the same as the current one. This will always be
// the original profile and never incognito.
- (void)windowChangedToProfile:(Profile*)profile;

@end

#endif  // __OBJC__

// Functions that may be accessed from non-Objective-C C/C++ code.

namespace app_controller_mac {

// True if we are currently handling an IDC_NEW_{TAB,WINDOW} command. Used in
// SessionService::Observe() to get around windows/linux and mac having
// different models of application lifetime.
bool IsOpeningNewWindow();

}  // namespace app_controller_mac

#endif


text:
layout: post
title: You Should Turn on 2FA
---

[John Podesta's phishing e-mail](https://wikileaks.org/podesta-emails/emailid/36355)


text:
using System;
using ECommon.Socketing;

namespace ECommon.Remoting
{
    public class SocketRequestHandlerContext : IRequestHandlerContext
    {
        public ITcpConnection Connection { get; private set; }
        public Action<RemotingResponse> SendRemotingResponse { get; private set; }

        public SocketRequestHandlerContext(ITcpConnection connection, Action<byte[]> sendReplyAction)
        {
            Connection = connection;
            SendRemotingResponse = remotingResponse =>
            {
                sendReplyAction(BuildRemotingServerMessage(remotingResponse));
            };
        }

        private static byte[] BuildRemotingServerMessage(RemotingResponse remotingResponse)
        {
            byte[] remotingResponseData = RemotingUtil.BuildResponseMessage(remotingResponse);
            var remotingServerMessage = new RemotingServerMessage(
                RemotingServerMessageType.RemotingResponse,
                100,
                remotingResponseData,
                null);
            return RemotingUtil.BuildRemotingServerMessage(remotingServerMessage);
        }
    }
}


text:
"""
this pipeline quantify expression level of both host and virus
"""
#=============  import required packages  =================
import sys,os
sys.path.append('/home/shangzhong/Codes/Pipeline')
sys.stdout = os.fdopen(sys.stdout.fileno(), 'w', 0) # disable buffer
from Modules.f00_Message import Message
from Modules.p01_FileProcess import get_parameters,remove
from Modules.p02_ParseFasta import fq2fa
from Modules.f01_list_trim_fq import list_files,Trimmomatic
from Modules.f02_aligner_command import gsnap,STAR,gsnap_Db,blastn
from Modules.f03_samtools import sam2bam_sort,extract_bam
from Modules.f07_picard import sam2fastq
from Modules.f12_trinity import Trinity
from blast2fasta import blast2fa,merge_fa
from p04_ParseBlast import annotateBlast
#=============  define some parameters  ===================
parFile = sys.argv[1]
#parFile = '/data/shangzhong/DetectVirus/01_DetectVirus_Parameters.txt'
param = get_parameters(parFile)
thread = param['thread']
email = param['email']
startMessage = param['startMessage']
endMessage = param['endMessage']
seqType = param['seqType']
#-------------  sequence parameters  ----------------------
host_fa = param['hostRefSequence']
host_annotation = param['hostAnnotation']
host_AnnotationSource = param['hostAnnotationSource']
virus_ref_fa = param['virusRefSequence']
virus_annotation = param['virusAnnotation']
virus_AnnotationSource = param['virusAnnotationSource']
#-------------  software parameters  ----------------------
file_path = param['filePath']
aligner = param['aligner']
host_alignerDb = param['host_alignerDb']
virus_alignerDb = param['virus_alignerDb']
trim = param['trim']
phred = param['phred']

picard = param['picard']
trimmomatic = param['trimmomatic']
trimmoAdapter = param['trimmoAdapter']
#-------------  specific parameters for gsnap  ------------
host_gsnapDbName = param['host_gsnapDbName']
host_gsnapAnnotation = param['host_gsnapAnnotation']
virus_gsnapDbName = param['virus_gsnapDbName']
virus_gsnapAnnotation = param['virus_gsnapAnnotation']
#------------- blast parameters ---------------------------
blast_Db = param['blast_Db']
runBlastAfterAssemble = param['runBlastAfterAssemble']
blast_nt_DB = param['blast_nt_DB']
#===============================================================================
#          1. map to host reference genome
#===============================================================================
#========  (0) enter the directory ========================
os.chdir(file_path)
Message(startMessage,email)

#========  (1) read files  ================================
fastqFiles = list_files(file_path)
if trim == 'True':
    fastqFiles = Trimmomatic(trimmomatic,fastqFiles,phred)
print 'list file succeed'
print 'fastqFiles is: ',fastqFiles
#========  (2) align fastq files to host ================================
try:
    if aligner == 'gsnap':
        # check index
        if os.listdir(host_alignerDb) == []:
            gsnap_Db(host_fa,host_alignerDb,host_gsnapDbName,host_gsnapAnnotation)
        map_files = gsnap(fastqFiles,host_alignerDb, host_gsnapDbName,host_gsnapAnnotation,thread) # [file.sam]
    else:
        map_files = STAR(fastqFiles,host_alignerDb,thread)
    print 'host align succeed'
    print 'map_files is: ',map_files
except:
    print 'host align failed'
    Message('host align failed',email)
    raise
#========  (3) sam to bam and sort  ================================
try:
    sorted_bams = sam2bam_sort(map_files,thread)  # [file.sort.bam]
    print 'host sorted succeed'
    print 'sorted_bam is: ',sorted_bams
except:
    print 'host sorted failed'
    Message('host sorted failed',email)
    raise
#========  (4) extract reads that unmapped to host  =====
try:
    unmap2host_bams = extract_bam(sorted_bams,'unmap',seqType,thread) # [file.sort.unmap.bam]
    print 'extract unmap2host_bams succeed'
    print 'unmap2host_bams is: ',unmap2host_bams
    remove(sorted_bams)
    # rename files
    for f in unmap2host_bams: os.rename(f,f[:-4]+'2host.bam')
    unmap2host_bams = [f[:-4]+'2host.bam' for f in unmap2host_bams] # [file.sort.unmap2host.bam]
except:
    print 'extract unmap2host_bams failed'
    Message('extract unmap2host_bams failed',email)
    raise
#========  (6) unmap2host_bams to fastq.gz =========================
try:
    unmap2host_fq_gzs = sam2fastq(picard,unmap2host_bams,seqType) # [[file.sort.unmap2host.fq.gz]]
    # compress to gz file
    #for fq in unmap2host_fqs: ('gzip {fq}').format(fq=fq)
    #unmap2host_fq_gzs = [f+'.gz' for f in unmap2host_fqs]  # file.sort.unmap2host.fq.gz
    print 'unmap2host_fq_gzs succeed'
    print 'unmap2host_fq_gzs is: ',unmap2host_fq_gzs
    remove(unmap2host_bams)
except:
    print 'unmap2host_fq_gzs failed'
    Message('unmap2host_fq_gzs failed',email)
    raise
#===========================================================================
#                 2. Map to virus reference genome
#===========================================================================
#========  (1) align unmap2host_fq to virus  =========================
try:
    if aligner == 'gsnap':
        # check index
        if os.listdir(virus_alignerDb) == []:
            gsnap_Db(virus_ref_fa,virus_alignerDb,virus_gsnapDbName,virus_gsnapAnnotation)
        # align the reads
        map_files = gsnap(unmap2host_fq_gzs,virus_alignerDb, virus_gsnapDbName,virus_gsnapAnnotation,thread)
    else:
        map_files = STAR(unmap2host_fq_gzs,virus_alignerDb,thread)  # [file.sort.unmap2host.sam]
    print 'virus align succeed'
    print 'map_files is: ',map_files
    remove(unmap2host_fq_gzs)
except:
    print 'virus align failed'
    Message('virus align failed',email)
    raise
#========  (2) sam to bam and sort  ================================
try:
    sorted_bams = sam2bam_sort(map_files,thread)    # [file.sort.unmap2host.sort.bam]
    print 'virus sorted succeed'
    print 'sorted_bams is: ',sorted_bams
except:
    print 'virus sorted failed'
    Message('virus sorted failed',email)
    raise
#========  (3) extract reads that mapped and unmapped to virus  ============================
try:
    map2virus_bams = extract_bam(sorted_bams,'map',seqType,thread)     # [file.sort.unmap2host.sort.map.bam]
    unmap2virus_bams = extract_bam(sorted_bams,'unmap',seqType,thread) # [file.sort.unmap2host.sort.unmap.bam]
    # rename files
    for f in map2virus_bams: os.rename(f,f[:-29]+'.only2virus.bam')
    map2virus_bams = [f[:-29]+'.only2virus.bam' for f in map2virus_bams]     # [file.only2virus.bam]
    for f in unmap2virus_bams: os.rename(f,f[:-31]+'.map2neither.bam')        # [file.map2neither.bam]
    unmap2virus_bams = [f[:-31]+'.map2neither.bam' for f in unmap2virus_bams]
    print 'extract map and unmap2virus_bams succeed'
    print 'map2virus_bams is: ',map2virus_bams,'unmap2virus_bams is: ',unmap2virus_bams
    remove(sorted_bams)
except:
    print 'extract map and unmap2virus_bams failed'
    Message('extract map and unmap2virus_bams failed',email)
    raise
#========  (4) transfer the mapped and unmapped to virus bam to fastq  =======
try:
    map2virus_fq_gzs = sam2fastq(picard,map2virus_bams,seqType)     # [[file.only2virus.fq.gz]]
    unmap2virus_fq_gzs = sam2fastq(picard,unmap2virus_bams,seqType) # [[file.map2neither.fq.gz]]
    print 'transfer from bam to fq succeed'
    print 'map2virus_fq_gzs is: ',map2virus_fq_gzs,'unmap2virus_fq_gzs',unmap2virus_fq_gzs
    remove(map2virus_bams);remove(unmap2virus_bams)
except:
    print 'transfer from bam to fq failed'
    Message('transfer from bam to fq failed',email)
    raise
#========  (5) transfer the unmapped to virus fastq to fasta =================
try:
    only2virus_faFiles = fq2fa(map2virus_fq_gzs)      # [file.only2virus.fa.gz]
    map2neither_faFiles = fq2fa(unmap2virus_fq_gzs)       # [file.map2neither.fa.gz]
    print 'fq files to fa files succeed'
    print 'only2virus_faFiles is: ',only2virus_faFiles,'map2neither_faFiles is: ',map2neither_faFiles
    remove(map2virus_fq_gzs); remove(unmap2virus_fq_gzs)
except:
    print 'fq files to fa files failed'
    Message('fq files to fa files failed',email)
    raise
#========  (6) map the unmapped to virus fa files with blastn ======================================
try:
    virus_blast = blastn(map2neither_faFiles,blast_Db,thread)  # [file.map2niether.txt]
    print 'blast to virus succeed'
    print 'virus_blast is: ',virus_blast
except:
    print 'blast to virus failed'
    Message('blast to virus failed',email)
    raise
#========  (7) extract reads from blast results ================================
try:
    blastFas = blast2fa(virus_blast,map2neither_faFiles,seqType)   # file.map2neither.blast.fa.gz
    print 'extract reads from blast tabular txt succeed'
    print 'blastFas is: ', blastFas
    remove(virus_blast)
except:
    print 'extract reads from lbast tabular txt failed'
    Message('extract reads from blast tabular txt failed',email)
    raise
#========  (8) merge blast mapped with gsnap mapped ==========================
try:
    mergedFa = merge_fa(seqType,only2virus_faFiles,blastFas)
    print 'merge fa files for Trinity succeed'
    print 'mergedFa is: ',mergedFa
except:
    print 'merge fa files for Trinity failed'
    Message('merge fa files for Trinity',email)
    raise
#========  (9) assemble the reads using trinity ==============================
try:
    Trinity(mergedFa,thread)
    print 'assemble using Trinity succeed'
    remove(mergedFa)
except:
    print 'assemble using Trinity failed'
    Message('assemble using Trinity failed',email)
    raise
#========  (10) run blast to get homology ==============================
if runBlastAfterAssemble == 'Yes':
    ### 1. blast assembled fa file
    faFiles = ['trinity_out_dir/Trinity.fasta']
    try:
        blast_assemble_result = blastn(faFiles,blast_nt_DB,thread)
        print 'blast assembled fa succeed'
        print 'blast_assemble_result is: ',blast_assemble_result
    except:
        print 'blast assembled fa failed'
        Message('blast assembled fa failed',email)
        raise
    ### 2. annotate the blast result
    try:
        annotateBlast(blast_assemble_result[0],'nucleotide')
        print 'annotate blast succeed'
    except:
        print 'annotate blast failed'
        Message('annotate blast failed',email)
        raise
Message(endMessage,email)


text:
import { expect } from '../test_helper';
import movieReducer from '../../src/reducers/movies';

describe('Movies Reducer', () => {
  it('handles action with unknown type', () => {
    expect(movieReducer(undefined, {})).to.eql([]);
  });

  it('handles action of type ADD_MOVIE', () => {
    const action = { type: 'ADD_MOVIE', title: 'new_movie' };
    const state = [];
    expect(movieReducer(state, action)).to.eql([{
      title: 'new_movie',
      images: []
    }]);
  });

  it('handles action of type DELETE_MOVIE', () => {
    const action = { type: 'DELETE_MOVIE' };
    const state = [ { title: 'new_movie', images: [] } ];
    expect(movieReducer(state, action)).to.eql([]);
  });

  it('handles action of type ADD_IMAGE_TO_MOVIE', () => {
    const action = { type: 'ADD_IMAGE_TO_MOVIE', movieIndex: 1, image: "dummy data" };
    const state = [
      { title: 'Star Wars', images: [] },
      { title: 'Amelie', images: [] },
    ];
    const desiredState = [
      { title: 'Star Wars', images: [] },
      { title: 'Amelie', images: ["dummy data"] },
    ];
    expect(movieReducer(state, action)).to.eql(desiredState);
  });
});


text:
package com.cs.rest.controller;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import com.cs.Constants.Status;
import com.cs.mongo.model.LedgerAccount;
import com.cs.mongo.model.LedgerTransactions;
import com.cs.request.models.LedgerSearchParams;
import com.cs.request.models.LedgerTransactionsParams;
import com.cs.rest.services.LedgerAccountServices;
import com.cs.rest.services.SessionManagementService;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;

@CrossOrigin
@RestController
public class LedgerController {

	@Autowired
	LedgerAccountServices ledgerAccountServices;
	@Autowired
	private SessionManagementService sessionManagementService;

	@RequestMapping(value = "/createLedger", method = RequestMethod.POST)
	public ResponseEntity<String> createLedger(@RequestBody LedgerAccount ledgerAccount) {
		String sttus = "Invalid";
	    HttpHeaders httpHeaders = new HttpHeaders();
	    if (ledgerAccount != null) {
	    	String sessionResponse = sessionManagementService.validateSession(ledgerAccount.getSession_id());
	    	if(sessionResponse.equalsIgnoreCase(Status.sessionInvalid))
	    	    return new ResponseEntity<String>(Status.sessionInvalid, httpHeaders,HttpStatus.UNAUTHORIZED);

	    	sttus = ledgerAccountServices.addLedgerAccount(ledgerAccount);
	    }
	    return new ResponseEntity<String>(sttus, httpHeaders,HttpStatus.OK);
	}

	@RequestMapping(value = "/searchLedgerAccount", method = RequestMethod.POST)
	public ResponseEntity<List<LedgerAccount>> searchLedgerAccount(@RequestBody LedgerSearchParams ledgerSearchParams) {
	    HttpHeaders httpHeaders = new HttpHeaders();
		String sessionResponse = sessionManagementService.validateSession(ledgerSearchParams.getSession_id());
    	if(sessionResponse.equalsIgnoreCase(Status.sessionInvalid))
    	    return new ResponseEntity<List<LedgerAccount>>(null, httpHeaders,HttpStatus.UNAUTHORIZED);

		List<LedgerAccount> status = ledgerAccountServices.searchLegerAccount(ledgerSearchParams);

	    return new ResponseEntity<List<LedgerAccount>>(status, httpHeaders,HttpStatus.OK);
	}

	@RequestMapping(value = "/ledgerAccountInformation", method = RequestMethod.POST)
	public ResponseEntity<LedgerAccount> ledgerAccountInformation(@RequestBody String requestInputParam) {
		Map<String, String> retMap = new Gson().fromJson(requestInputParam, new TypeToken<HashMap<String, Object>>() {}.getType());
		 HttpHeaders httpHeaders = new HttpHeaders();
		String sessionResponse = sessionManagementService.validateSession(retMap.get("session_id"));
    	if(sessionResponse.equalsIgnoreCase(Status.sessionInvalid))
    	    return new ResponseEntity<LedgerAccount>(null, httpHeaders,HttpStatus.UNAUTHORIZED);

		LedgerAccount ledgerAccount = ledgerAccountServices.getledgerAccountInformation(retMap.get("ledger_id"),retMap.get("session_id"));

	    return new ResponseEntity<LedgerAccount>(ledgerAccount, httpHeaders,HttpStatus.OK);
	}

	//LedgerTransactionsParams
	@RequestMapping(value = "/ledgerTransactionIformation", method = RequestMethod.POST)
	public ResponseEntity<List<LedgerTransactions>> ledgerTransactionIformation(@RequestBody String requestInputParam) {
		Map<String, String> retMap = new Gson().fromJson(requestInputParam, new TypeToken<HashMap<String, Object>>() {}.getType());
		HttpHeaders httpHeaders = new HttpHeaders();
		String sessionResponse = sessionManagementService.validateSession(retMap.get("session_id"));
    	if(sessionResponse.equalsIgnoreCase(Status.sessionInvalid))
    	    return new ResponseEntity<List<LedgerTransactions>>(null, httpHeaders,HttpStatus.UNAUTHORIZED);

		List<LedgerTransactions> listLedgerTransactions = ledgerAccountServices.getledgerTransactionIformation(retMap.get("ledger_id"),retMap.get("session_id"));
	    return new ResponseEntity<List<LedgerTransactions>>(listLedgerTransactions, httpHeaders,HttpStatus.OK);
	}

	@RequestMapping(value = "/createLedgerTransaction", method = RequestMethod.POST)
	public ResponseEntity<String> createLedgerTransaction(@RequestBody LedgerTransactionsParams ledgerTransactionsParams) {
		String status = "Invalid";
		  HttpHeaders httpHeaders = new HttpHeaders();
		  String sessionResponse = sessionManagementService.validateSession(ledgerTransactionsParams.getSession_id());
	    	if(sessionResponse.equalsIgnoreCase(Status.sessionInvalid))
	    	    return new ResponseEntity<String>(Status.sessionInvalid, httpHeaders,HttpStatus.UNAUTHORIZED);

		status = ledgerAccountServices.createLedgerTransaction(ledgerTransactionsParams);

	    return new ResponseEntity<String>(status, httpHeaders,HttpStatus.OK);
	}

}