text:
FROM nginx:alpine

COPY ./default.conf /etc/nginx/conf.d/default.conf

redpajama_set_name: RedPajamaGithub


text:
using UnityEngine;
using System.Collections;
using UnityEngine.UI;

public class OptionsLogic : MonoBehaviour
{
    public bool isRandom;
    public Conversations.Option[] options;
    public UnityEngine.Events.UnityAction<int> optionPressed;

    // Use this for initialization
    void Start()
    {

        if (isRandom)
        {
            reshuffle();
        }
        GameObject textChild = this.gameObject.transform.Find("Button").gameObject;
        textChild.GetComponentInChildren<Button>().onClick.AddListener(
            () => optionPressed(options[0].nextIndex));
        textChild.GetComponentInChildren<Button>().onClick.AddListener(
            () => Destroy());
        Text childTextComp = textChild.GetComponent<Text>();
        childTextComp.text = "1 - " + options[0].text;
        float prefHeight = childTextComp.preferredHeight;
        Vector3 position = textChild.transform.localPosition;
        position.y = prefHeight * (options.Length - 1) + 0.5f * prefHeight - 300;
        textChild.transform.localPosition = new Vector3(position.x, position.y, position.z);

        for (int i = 1; i < options.Length; ++i)
        {
            GameObject newText = Instantiate(textChild);

            Vector3 localPos = newText.transform.localPosition;
            localPos = new Vector3(localPos.x, localPos.y, localPos.z);
            newText.transform.SetParent(this.gameObject.transform);
            newText.transform.localPosition = localPos;
            newText.transform.localScale = new Vector3(1, 1, 1);

            int nextIndex = options[i].nextIndex;

            newText.GetComponentInChildren<Button>().onClick.AddListener(
                () => optionPressed(nextIndex));
            newText.GetComponentInChildren<Button>().onClick.AddListener(
                () => Destroy());
            newText.GetComponent<Text>().text = (i + 1) + " - " + options[i].text;
            position.y = position.y - prefHeight;
            newText.transform.localPosition = position;
        }
    }

    public void reshuffle()
    {

        // Knuth shuffle algorithm :: courtesy of Wikipedia :)
        int length = options.Length;
        for (int i = 0; i < length; ++i)
        {
            int r = UnityEngine.Random.Range(i, length);

            Conversations.Option indexOption = options[i];
            options[i] = options[r];
            options[r] = indexOption;
        }
    }

    // Update is called once per frame
    void Update()
    {
    }

    public void Destroy()
    {
        Destroy(this.gameObject);
    }
}


text:
Integrity Artifacts
=========

You can use integrity-artifacts to copy build artifacts from your integrity builds

Installation
=========

1. sudo gem install subakva-integrity-artifacts --source=http://gems.github.com
2. Add require 'integrity/notifier/artifacts' to config.ru
3. Enable the notifier on the project page
4. [Optional] Set "Artifact Root" to the file-system path where the artifacts should be saved
5. [Optional] Set "Config YAML" to the location of your artifacts config file relative to your repository root
6. Click "Update Project"

Example config.ru
=========

    #!/usr/bin/env ruby

    require "rubygems"
    require "integrity"

    require 'integrity/notifier/artifacts'

    # Load configuration and initialize Integrity
    Integrity.new(File.dirname(__FILE__) + "/config.yml")

    # You probably don't want to edit anything below
    Integrity::App.set :environment, ENV["RACK_ENV"] || :production
    Integrity::App.set :port,        8910

    run Integrity::App

Example artifacts.yml
=========

    ---
      rcov:
        output_dir: coverage
      metric_fu:
        output_dir: tmp/metric_fu

Example integrity.rake
=========

    namespace :integrity do
      desc "Execute the integrity build..."
      task :build do
        puts "Executing the integrity build......"

        Rake::Task['rcov'].invoke

        require 'metric_fu'
        MetricFu::Configuration.run do |fu|
          fu.metrics -= [:rcov] # running rcov seperately
          fu.metrics -= [:saikuro] # saikuro isn't working for this project...
        end
        Rake::Task['metrics:all'].invoke

        puts "Done."
      end
    end

Copyright
==========

Copyright (c) 2009 Jason Wadsworth. See LICENSE for details.


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"
  "http://www.w3.org/TR/html4/strict.dtd">

    <meta http-equiv="Content-type" content="text/html; charset=utf-8">
    <title>transform-origin vs. Transform Functions</title>


text:
package org.joshy.gfx.util;

import org.w3c.dom.*;
import org.xml.sax.ErrorHandler;
import org.xml.sax.SAXParseException;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import javax.xml.transform.stream.StreamSource;
import javax.xml.xpath.XPath;
import javax.xml.xpath.XPathConstants;
import javax.xml.xpath.XPathExpressionException;
import javax.xml.xpath.XPathFactory;
import java.io.*;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;

/**
 *  Description of the Class
 *
 *@author     joshy@joshy.org
 *@created    August 27, 2003
 */
public class x {

    /**
     *  Description of the Method
     *
     *@param  node  Description of the Parameter
     *@param  name  Description of the Parameter
     *@return       Description of the Return Value
     */
    public static Element child(Element node, String name) {
        NodeList nl = node.getElementsByTagName(name);
        if (nl == null) {
            return null;
        }
        return (Element) nl.item(0);
    }

    /**
     *  Description of the Method
     *
     *@param  node  Description of the Parameter
     *@param  name  Description of the Parameter
     *@return       Description of the Return Value
     */
    public static NodeList children(Element node, String name) {
        NodeList nl = node.getElementsByTagName(name);
        return nl;
    }

    public static List<Element> echildren(Element node) {
        List<Element> list = new ArrayList<Element>();
        NodeList nl = node.getChildNodes();
        for(int i=0; i<nl.getLength(); i++) {
            if(nl.item(i) instanceof Element) {
                list.add((Element) nl.item(i));
            }
        }
        return list;

    }

    /**
     *  Description of the Method
     *
     *@param  el  Description of the Parameter
     */
    public static void clear(Element el) {
        while (el.hasChildNodes()) {
            el.removeChild(el.getFirstChild());
        }
    }

    /**
     *  Description of the Method
     *
     *@param  string         Description of the Parameter
     *@return                Description of the Return Value
     *@exception  Exception  Description of the Exception
     */
    public static Document loadDocument(String string) throws Exception {
        return loadDocument(new FileInputStream(string));
    }

    public static Document loadDocument(URL url) throws Exception {
        DocumentBuilder builder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
        MyErrorHandler eh = new MyErrorHandler();
        builder.setErrorHandler(eh);
        Document doc = builder.parse(url.openStream(),url.toString());
        if(eh.err != null) {
            //u.p("throwing");
            throw eh.err;
        }
        return doc;
    }

    // public static Document loadDocument(Reader reader) throws Exception {
    //     DocumentBuilder builder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
    //     MyErrorHandler eh = new MyErrorHandler();
    //     builder.setErrorHandler(eh);
    //     Document doc = builder.parse(reader);
    //     if(eh.err != null) {
            //u.p("throwing");
    //         throw eh.err;
    //     }
    //     return doc;
    // }

    public static Document loadDocument(InputStream in) throws Exception {
        DocumentBuilder builder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
        MyErrorHandler eh = new MyErrorHandler();
        builder.setErrorHandler(eh);
        //u.p("before"+Thread.currentThread());
        Document doc = builder.parse(in);
        //u.p("after" + Thread.currentThread());
        //u.p("ex = " + eh.err);
        if(eh.err != null) {
            //u.p("throwing");
            throw eh.err;
        }
        return doc;
    }

    public static Document loadDocumentFromResource(String string, Object marker) throws Exception {
        InputStream in = marker.getClass().getResourceAsStream(string);
        Document doc = DocumentBuilderFactory.newInstance().newDocumentBuilder().parse(in);
        return doc;
    }

    /**
     *  Description of the Method
     *
     *@param  doc    Description of the Parameter
     *@param  name   Description of the Parameter
     *@param  value  Description of the Parameter
     *@return        Description of the Return Value
     */
    public static Element ne(Document doc, String name, String value) {
        return newElement(doc, name, value);
    }
    public static Element ne(Document doc, String name) {
        return newElement(doc,name);
    }
    public static Element ne(Element element, String name, String value) {
        return newElement(element.getOwnerDocument(),name,value);
    }
    public static Element ne(Element element, String name) {
        return newElement(element.getOwnerDocument(),name);
    }

    /**
     *  Description of the Method
     *
     *@return                Description of the Return Value
     *@exception  Exception  Description of the Exception
     */
    public static Document newDocument() throws Exception {
        Document output = DocumentBuilderFactory.newInstance().newDocumentBuilder().newDocument();
        return output;
    }

    public static Element newElement(Document doc, String name) {
        Element elem = doc.createElement(name);
        return elem;
    }

    public static Element newElement(Document doc, String name, String value) {
        if (value == null) {
            value = "";
        }
        Element elem = doc.createElement(name);
        Text text = doc.createTextNode(value);
        elem.appendChild(text);
        return elem;
    }

    public static void p(Node node) {
        p(node, "");
    }

    /**
     *  Description of the Method
     *
     *@param  doc  Description of the Parameter
     */
    public static void p(Document doc) {
        u.p("as document");
        u.p("<?xml version=\"1.0\"?>");
        DocumentType dt = doc.getDoctype();
        if (dt != null) {
            u.p("<!DOCTYPE " + dt.getName() + " PUBLIC \"" +
                dt.getPublicId() + "\" \"" +
                dt.getSystemId() + ">");
        }
        p((Node) doc);
    }

    /**
     *  Description of the Method
     *
     *@param  node  Description of the Parameter
     */
    public static void p(Node node, String tab) {
        if (node == null) {
            return;
        }
        //u.p(tab + "node type = " + node.getNodeType());
        if (node.getNodeType() == node.ENTITY_NODE) {
            u.p(tab + "entity node");
        }

        if (node.getNodeType() == node.ENTITY_REFERENCE_NODE) {
            u.p(tab + "------ entity ref node");
            u.p(tab + "ent: " + node.getNodeName());
            u.p(tab + node.getNodeValue());
            NodeList c = node.getChildNodes();
            Node n = c.item(0);
            //u.print_as_bytes(n.getNodeValue());
            //n.setNodeValue("blahfoo");
        }

        if (node.getNodeType() == node.TEXT_NODE) {
            if (!node.getNodeValue().trim().equals("")) {
                u.p(tab + node.getNodeValue());
            }
        }

        if (node.getNodeType() == node.ELEMENT_NODE) {
            NamedNodeMap atts = node.getAttributes();
            NodeList c = node.getChildNodes();
            u.pr(tab + "<" + node.getNodeName());

            if (atts.getLength() == 0) {
                if (c.getLength() == 0) {
                    u.p("/>");
                } else {
                    u.p(">");
                }
            }

            if (atts.getLength() == 1) {
                u.pr(" " + atts.item(0));
                if (c.getLength() == 0) {
                    u.p("/>");
                } else {
                    u.p(tab + ">");
                }
            }

            if (atts.getLength() > 1) {
                // print the attributes
                u.p(" " + atts.item(0));
                for (int i = 1; i < atts.getLength(); i++) {
                    u.p(tab + "  " + atts.item(i));
                }
                if (c.getLength() == 0) {
                    u.p(tab + "/>");
                } else {
                    u.p(tab + ">");
                }
            }
        }

        NodeList c = node.getChildNodes();
        for (int i = 0; i < c.getLength(); i++) {
            Node n = c.item(i);
            p(n, tab + "  ");
        }

        if ((node.getNodeType() == node.ELEMENT_NODE) && (node.getChildNodes().getLength() > 0)) {
            u.p(tab + "</" + node.getNodeName() + ">");
        }
    }

    /**
     *  Description of the Method
     *
     *@param  node  Description of the Parameter
     *@param  pw    Description of the Parameter
     */
    public static void p(Node node, PrintWriter pw) {
        pw.println("name=" + node.getNodeName() + "<br>");
        NodeList c = node.getChildNodes();
        for (int i = 0; i < c.getLength(); i++) {
            Node n = c.item(i);
            p(n, pw);
        }
    }

    /**
     *  Description of the Method
     *
     *@param  list  Description of the Parameter
     */
    public static void p(NodeList list) {
        u.p("node list: " + list.toString());
        u.p("size = " + list.getLength());
        for (int i = 0; i < list.getLength(); i++) {
            p(list.item(i));
        }
    }

    /**
     *  Description of the Method
     *
     *@param  doc            Description of the Parameter
     *@param  filename       Description of the Parameter
     *@exception  Exception  Description of the Exception
     */
    public static void saveDocument(Document doc, String filename) throws Exception {
        DOMSource xml_source = new DOMSource(doc);
        Transformer transformer = TransformerFactory.newInstance().newTransformer();
        StreamResult result = new StreamResult(filename);
        transformer.transform(xml_source, result);

        /*
        //u.p("about to save: " + doc);
        //x.p(doc);
        XMLSerializer xs = new XMLSerializer();
        xs.setOutputByteStream(new FileOutputStream(filename));
        OutputFormat of = new OutputFormat();
        of.setMethod("xml");
        of.setIndenting(true);
        //of.setPreserveEmptyAttributes(true);
        //of.setPreserveEmptyAttributes()
        of.setIndent(4);
        of.setPreserveSpace(false);
        of.setOmitDocumentType(true);
        xs.setOutputFormat(of);
        xs.serialize(doc);
        */
    }

    public static void writeDocument(PrintWriter writer, Document doc) throws IOException {
        write(writer,doc.getDocumentElement());
    }

    public static void write(PrintWriter writer, Node node) throws IOException {
        // handle atts
        if(node.getNodeType() == node.ATTRIBUTE_NODE) {
            u.p("att node = " + node);
            writer.print(" " + node.getNodeName() +"=\""+node.getNodeValue()+"\" ");
        }

        // <open tag>
        if(node.getNodeType() == node.ELEMENT_NODE) {
            u.p("element = " + node);
            writer.print("<"+node.getNodeName());
            NamedNodeMap atts = node.getAttributes();
            for(int i=0; i<atts.getLength(); i++) {
                Node att = atts.item(i);
                write(writer,att);
            }

            writer.print(">");
        }

        // if it's a text node
        if(node.getNodeType() == node.TEXT_NODE) {
            u.p("text node: " + node);
            writer.print(node.getNodeValue());
        }

        // if it's a cdata node
        if(node.getNodeType() == node.CDATA_SECTION_NODE) {
            writer.print("<![CDATA[");
            writer.print(node.getNodeValue());
            writer.print("]]>");
        }
        if(node.getNodeType() != node.ATTRIBUTE_NODE) {
            NodeList children = node.getChildNodes();
            for(int i=0; i<children.getLength(); i++) {
                write(writer,children.item(i));
            }
        }

        // </close tag>
        if(node.getNodeType() == node.ELEMENT_NODE) {
            u.p("close tag: " + node);
            writer.print("</"+node.getNodeName()+">\n");
        }
    }

    /**
     *  Description of the Method
     *
     *@param  node  Description of the Parameter
     *@return       Description of the Return Value
     */
    public static String text(Node node) {
        return text_child(node);
    }

    public static String textChild(Element node, String name) {
        return text_child(child(node,name));
    }
    public static String text_child(Node node) {
        if(node == null) {
            return "";
        }
        NodeList nl = node.getChildNodes();
        Node item = nl.item(0);
        if(item == null) {
            return "";
        }
        return item.getNodeValue();
    }

    public static String getAtt(Element node, String name) {
        return node.getAttribute(name);
    }
    public static String getChildAtt(Element node, String name, String attr) {
        Element child = child(node,name);
        if(child == null) { return null; }
        return getAtt(child,attr);
    }

    public static void transform(Document doc, URL xsl, OutputStream out,
        String pname, String pvalue)
        throws Exception {
        u.p("transforming with xsl: " + xsl);
        u.p("doc = " + doc);
        DOMSource xml_source = new DOMSource(doc);
        StreamSource xsl_source = new StreamSource(xsl.toString());
        Transformer transformer = TransformerFactory.newInstance().newTransformer(xsl_source);
        if (pname != null) {
            transformer.setParameter(pname, pvalue);
        }
        StreamResult result = new StreamResult(out);//pw);
        transformer.transform(xml_source, result);
    }

    public static void transform(Document doc, StreamSource xsl, StreamResult out,
            String pname, String pvalue) throws Exception {
        u.p("transforming with xsl: " + xsl);
        u.p("doc = " + doc);
        DOMSource xml_source = new DOMSource(doc);
        Transformer transformer = TransformerFactory.newInstance().newTransformer(xsl);
        if (pname != null) {
            transformer.setParameter(pname, pvalue);
        }
        transformer.transform(xml_source, out);
    }

    public static void transform(Document doc, InputStream xsl, OutputStream out, String pname, String pvalue) throws Exception {
        StreamSource xsl_source = new StreamSource(xsl);
        transform(doc,xsl_source,new StreamResult(out),pname,pvalue);
        //StreamResult result = new StreamResult(out);//pw);
    }

    public static void transform(Document doc, String xsl_filename, OutputStream out, String pname, String pvalue) throws Exception {
        transform(doc,new FileInputStream(xsl_filename),out,pname,pvalue);

    }

    public static void transform(Document doc, String xsl_filename, Writer out) throws Exception {
        transform(doc, new StreamSource(new FileInputStream(xsl_filename)), new StreamResult(out),null,null);
    }
    public static void transform(Document doc, String xsl_filename, OutputStream out) throws Exception {
        transform(doc, xsl_filename, out, null, null);
    }

    /* pseudo xpath stuff */

    public static String path(Node node, String xpath) {
        List paths = breakPath(xpath);
        for(int i=0; i<paths.size(); i++) {
            String sec = (String) paths.get(i);
            //u.p("testing: " + sec);
            //u.p("node = " + node.getNodeName());

            if(sec.equals("text()")) {
                //u.p("returning text(): " + node.getFirstChild().getNodeValue());
                return node.getFirstChild().getNodeValue();
            }

            NodeList nodes = node.getChildNodes();
            for(int j=0; j<nodes.getLength(); j++) {
                Node child = nodes.item(j);
                if(child.getNodeName().equals(sec)) {
                    //u.p("matched: " + sec);
                    node = child;
                    break;
                }
            }
        }
        return null;
    }

    public static String[] paths(Node node, String xpath) {
        List paths = breakPath(xpath);
        return null;
    }

    private static List breakPath(String path) {
        path = path.trim();
        List list = new ArrayList();
        // trim starting / if present
        if(path.startsWith("/")) {
            path = path.substring(1,path.length());
        }
        //u.p("breaking: " + path);
        // pull out each section between the /'s
        while(true) {
            //u.p("path = " + path);
            int n = path.indexOf("/");
            if(n < 0) {
                list.add(path);
                break;
            }
            String sec = path.substring(0,n);
            //u.p("found: " + sec);
            //u.p("n = " + n);
            list.add(sec);
            path = path.substring(n+1,path.length());
        }
        //u.p("returning: " + list);
        return list;
    }

    public static void p(Object obj) {
        if(obj instanceof Node) { p((Node)obj); return; }
        if(obj instanceof NodeList) { p((NodeList)obj); return; }
        if(obj instanceof Document) { p((Document)obj); return; }

        u.p(obj);

    }

    public static String xpathString(Node node, String xpath) throws XPathExpressionException {
        XPath xp = XPathFactory.newInstance().newXPath();
        return (String) xp.evaluate(xpath, node, XPathConstants.STRING);
    }

    public static List<Element> xpathElements(Node node, String xpath) throws XPathExpressionException {
        XPath xp = XPathFactory.newInstance().newXPath();

        NodeList nl = (NodeList) xp.evaluate(xpath, node, XPathConstants.NODESET);
        List<Element> list = new ArrayList<Element>();
        for(int i=0; i<nl.getLength(); i++) {
            list.add((Element) nl.item(i));
        }
        return list;
    }
}

class MyErrorHandler implements ErrorHandler {
            public Exception err;
            public void error(SAXParseException exception) {
                u.p("MyErrorHandler: error:");
                u.p(exception);
                err = exception;
            }

            public void fatalError(SAXParseException exception) {
                u.p("MyErrorHandler: fatal error:");
                u.p(exception);
                err = exception;
                u.p("set exception");
            }

            public void warning(SAXParseException exception) {
                u.p("MyErrorHandler: warning:");
                u.p(exception);
                //err = exception;
            }
        }


text:
package com.vivifram.second.hitalk.ui;

import android.content.Context;
import android.os.Bundle;
import android.util.SparseArray;
import android.view.MotionEvent;
import android.view.View;

import com.avos.avoscloud.AVCallback;
import com.avos.avoscloud.AVException;
import com.avos.avoscloud.im.v2.AVIMConversation;
import com.avos.avoscloud.im.v2.AVIMException;
import com.avos.avoscloud.im.v2.AVIMMessage;
import com.avos.avoscloud.im.v2.AVIMTypedMessage;
import com.avos.avoscloud.im.v2.callback.AVIMConversationCallback;
import com.avos.avoscloud.im.v2.callback.AVIMConversationCreatedCallback;
import com.avos.avoscloud.im.v2.callback.AVIMMessagesQueryCallback;
import com.avos.avoscloud.im.v2.messages.AVIMTextMessage;
import com.vivifram.second.hitalk.R;
import com.vivifram.second.hitalk.base.BaseActivity;
import com.vivifram.second.hitalk.base.EatMark;
import com.vivifram.second.hitalk.base.InterfaceInject;
import com.vivifram.second.hitalk.base.LayoutInject;
import com.vivifram.second.hitalk.bean.Constants;
import com.vivifram.second.hitalk.bean.Emojicon;
import com.vivifram.second.hitalk.bean.IMessageWrap;
import com.vivifram.second.hitalk.manager.chat.ClientManager;
import com.vivifram.second.hitalk.manager.chat.FriendsManager;
import com.vivifram.second.hitalk.ui.layout.ChatRoomLayout;
import com.vivifram.second.hitalk.ui.page.layout.ChatInputMenuLayout;
import com.vivifram.second.hitalk.ui.page.layout.ChatMessageListLayout;
import com.zuowei.dao.greendao.User;
import com.zuowei.utils.bridge.EaterManager;
import com.zuowei.utils.bridge.constant.EaterAction;
import com.zuowei.utils.bridge.params.ParamWrap;
import com.zuowei.utils.bridge.params.address.SchoolMateStateParam;
import com.zuowei.utils.bridge.params.chat.MessageParam;
import com.zuowei.utils.chat.ConversationUtils;
import com.zuowei.utils.common.NLog;
import com.zuowei.utils.common.NToast;
import com.zuowei.utils.common.SyncUtils;
import com.zuowei.utils.common.TagUtil;
import com.zuowei.utils.handlers.AbstractHandler;
import com.zuowei.utils.helper.ConversationCacheHelper;
import com.zuowei.utils.helper.HiTalkHelper;
import com.zuowei.utils.helper.SchoolmatesCacheHelper;
import com.zuowei.utils.helper.UserBeanCacheHelper;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.Objects;
import java.util.concurrent.Callable;

import bolts.Task;

/**
 * 项目名称:Hitalk
 * 类描述:
 * 创建人:zuowei
 * 创建时间:17-2-20 上午10:49
 * 修改人:zuowei
 * 修改时间:17-2-20 上午10:49
 * 修改备注:
 */

@LayoutInject(name = "ChatRoomLayout")
    public class ChatRoomActivity extends BaseActivity<ChatRoomLayout>{
    private static final String TAG = TagUtil.makeTag(ChatRoomActivity.class);

    private static void start(Context c,int key){
        start(c,ChatRoomActivity.class,key);
    }

    public static void start(Context c, int toType, String... UserIds) {
        SparseArray<List<String>> sparseArray = new SparseArray<>();
        sparseArray.put(toType, Arrays.asList(UserIds));
        int key = sparseArray.hashCode();
        ParamsPool.$().put(key, sparseArray);
        start(c, key);
    }

    public static void start(Context c, AVIMConversation conversation) {
        SparseArray sparseArray = new SparseArray();
        sparseArray.put(Constants.ParamsKey.Chat.TO_CONVERSATION, conversation);
        int key = sparseArray.hashCode();
        ParamsPool.$().put(key, sparseArray);
        start(c, key);
    }

    private AVIMConversation conversation;
    boolean isToFriend =  false;
    @Override
    protected void onCreate(Bundle arg0) {
        super.onCreate(arg0);
        setContentView(R.layout.activity_chat_room_layout);
        SparseArray chatParams = (SparseArray) params;
        List<String> toUserIds = null;
        AVIMConversation conversation = null;
        String toUserId = null;
        if (chatParams == null) {
            finish();
        }
        switch (chatParams.keyAt(0)){
            case Constants.ParamsKey.Chat.TO_FRIEND:
                    isToFriend = true;
                    toUserIds = (List<String>) chatParams.get(Constants.ParamsKey.Chat.TO_FRIEND);
                break;
            case Constants.ParamsKey.Chat.TO_SCHOOL_MATE:
                    toUserIds = (List<String>) chatParams.get(Constants.ParamsKey.Chat.TO_SCHOOL_MATE);
                break;
            case Constants.ParamsKey.Chat.TO_GROUP:
                    isToFriend = true;
                    toUserIds = (List<String>) chatParams.get(Constants.ParamsKey.Chat.TO_GROUP);
                break;
            case Constants.ParamsKey.Chat.TO_CONVERSATION:
                    conversation = (AVIMConversation) chatParams.get(Constants.ParamsKey.Chat.TO_CONVERSATION);
                break;
        }

        if (toUserIds != null) {
            if (toUserIds.size() == 1) {
                toUserId = toUserIds.get(0);
                if (toUserId != null) {
                    initWithUserId(toUserId);
                    return;
                }
            } else if (toUserIds.size() > 1){
                initWithUserids(toUserIds, toUserIds);
                return;
            }
        }

        if (conversation != null) {
            updateConversation(conversation, true);
            return;
        }

        NToast.shortToast(mAppCtx, getResources().getString(R.string.open_chat_room_failed));
        finish();
    }

    private void initWithUserids(List<String> toUserIds, final List<String> finalToUserIds) {
        UserBeanCacheHelper.getInstance().getCachedUsers(toUserIds, new AVCallback<List<User>>() {
            @Override
            protected void internalDone0(List<User> users, AVException e) {
                if (e == null && users != null && users.size() > 1) {
                    doInitChatRoom(users, finalToUserIds);

                } else {
                    NToast.shortToast(mAppCtx, getResources().getString(R.string.open_chat_room_failed));
                    finish();
                }
            }
        });
    }

    private void initWithUserId(String toUserId) {
        UserBeanCacheHelper.getInstance().getCachedUser(toUserId, new AVCallback<User>() {
            @Override
            protected void internalDone0(User user, AVException e) {
                if (e == null && user != null) {
                    doInitChatRoom(user);
                } else {
                    NToast.shortToast(mAppCtx, getResources().getString(R.string.open_chat_room_failed));
                    finish();
                }
            }
        });
    }

    private void updateConversation(AVIMConversation conversation, boolean toConverstaion) {
        if (!toConverstaion) {
            updateConversation(conversation);
        } else {
            List<String> members = new ArrayList<>(conversation.getMembers());
            if (members.size() == 2) {
                members.remove(HiTalkHelper.getInstance().getCurrentUserId());
                String userId = members.get(0);
                SchoolmatesCacheHelper.getInstance().getSchoolmateFriendState(userId)
                        .continueWith(task -> {
                            if (task.getResult() == Constants.SchoolMateState.REQUEST_STATE_FAILED) {
                                isToFriend = false;
                            } else {
                                isToFriend = true;
                            }
                            initWithUserId(userId);
                            return null;
                        }, Task.UI_THREAD_EXECUTOR);
            } else {
                isToFriend = false;
                updateConversation(conversation);
            }
        }
    }

    private void updateConversation(AVIMConversation conversation){
        this.conversation = conversation;
        mLayout.setTitle(conversation.getName());
        ConversationCacheHelper.getInstance().clearUnread(conversation.getConversationId());
        fetchMessages().continueWith(task -> {
            if (task.getResult() == null){
                NToast.shortToast(mAppCtx, getString(R.string.message_fetch_failed_warn));
            } else {
                mLayout.setMessageListFreshListener(new ChatMessageListLayout.IMessageListFreshListener() {
                    @Override
                    public void onRefresh() {
                        if (mLayout != null){
                            IMessageWrap firstMessage = mLayout.getChatLt().getFirstMessage();
                            if (firstMessage == null){
                                fetchMessages().continueWith(task -> {
                                    mLayout.getChatLt().finshRefresh();
                                    return null;
                                });
                            }else {
                                conversation.queryMessages(firstMessage.message_.getMessageId(),
                                        firstMessage.message_.getTimestamp(), 20, new AVIMMessagesQueryCallback() {
                                            @Override
                                            public void done(List<AVIMMessage> list, AVIMException e) {
                                                if (e == null && list != null){
                                                    mLayout.pushMessagesAndRefreshToTop(IMessageWrap.buildFrom(list,true));
                                                }
                                                mLayout.getChatLt().finshRefresh();
                                            }
                                        });

                            }
                        }
                    }

                    @Override
                    public void onLoadmore() {

                    }
                });
            }
            return null;
        });
    }

    private Task<List<AVIMMessage>> fetchMessages() {
        if (conversation != null) {
            return Task.callInBackground(new Callable<List<AVIMMessage>>() {
                List<AVIMMessage> queryResult;
                @Override
                public List<AVIMMessage> call() throws Exception {
                    int syncLatch = SyncUtils.getSyncLatch();
                    conversation.queryMessages(new AVIMMessagesQueryCallback() {
                        @Override
                        public void done(List<AVIMMessage> list, AVIMException e) {
                            if (filterException(e)) {
                                queryResult = list;
                            }
                            SyncUtils.notify(syncLatch);
                        }
                    });
                    SyncUtils.wait(syncLatch);
                    NLog.i(TagUtil.makeTag(getClass()),"fetchMessages queryResult = "+queryResult);
                    return queryResult;
                }
            }).continueWith(task -> {
                List<AVIMMessage> result = task.getResult();
                if (result != null && mLayout.getChatLt() != null){
                    mLayout.getChatLt().clear();
                    mLayout.pushMessagesAndRefreshToBottom(IMessageWrap.buildFrom(result,false));
                    return result;
                }
                return null;
            },Task.UI_THREAD_EXECUTOR);
        }
        return Task.forResult(null);
    }

    private boolean filterException(Exception e) {
        if(null != e) {
            NToast.shortToast(mAppCtx,e.getMessage());
        }

        return null == e;
    }

    private void doInitChatRoom(final User user) {
        if (!isToFriend) {
            mLayout.flowBar().show(true);
            mLayout.flowBar().setOnFlowBarActionListener(new ChatRoomLayout.FlowBar.OnFlowBarActionListener() {
                @Override
                public void onAddFriend() {
                    FriendsManager.FriendsManagerUIHelper.requestFriend(ChatRoomActivity.this, user.getObjectId(), task -> {
                        if (task.getResult()) {
                            SchoolmatesCacheHelper.getInstance().cache(user.getObjectId(), SchoolmatesCacheHelper.REQUEST_STATE_WATING);
                        }
                        EaterManager.getInstance().broadcast(new SchoolMateStateParam());
                        mLayout.flowBar().show(false);
                        return null;
                    });
                }

                @Override
                public void onCancel() {
                    mLayout.flowBar().show(false);
                }
            });
        }
        if (ClientManager.getInstance().isOpend()){
            ClientManager.getInstance().getClient().createConversation(Collections.singletonList(user.getObjectId()),
                    user.getNick(), null, false, true, new AVIMConversationCreatedCallback() {
                        @Override
                        public void done(AVIMConversation avimConversation, AVIMException e) {
                               if (e != null){
                                   NToast.shortToast(mAppCtx,getResources().getString(R.string.create_chat_room_failed));
                                   NLog.e(TAG, "conversation create failed");
                                   finish();
                               } else {
                                   updateConversation(avimConversation);
                               }
                        }
                    });
        } else {
            NLog.e(TAG,"client is not open");
            NToast.shortToast(mAppCtx,getResources().getString(R.string.open_chat_room_failed));
            finish();
        }
    }

    private void doInitChatRoom(List<User> users, List<String> userIds) {
        StringBuilder title = new StringBuilder();
        title.append(HiTalkHelper.getInstance().getCurrentUser().get(Constants.User.NICKNAME_C));
        title.append(",");
        for (User user : users) {
            title.append(user.getNick());
            title.append(",");
        }
        title.deleteCharAt(title.length() - 1);

        mLayout.flowBar().show(false);

        ConversationUtils.createGroupConversation(userIds, title.toString(), new AVIMConversationCreatedCallback() {
            @Override
            public void done(AVIMConversation avimConversation, AVIMException e) {
                if (e == null && avimConversation != null) {
                    updateConversation(avimConversation);
                } else {
                    NToast.shortToast(mAppCtx,getResources().getString(R.string.create_chat_room_failed));
                    NLog.e(TAG, "conversation create failed");
                    finish();
                }
            }
        });
    }

    @InterfaceInject(bindName = "chatInputMenuListener")
    ChatInputMenuLayout.ChatInputMenuListener chatInputMenuListener = new ChatInputMenuLayout.ChatInputMenuListener() {
        @Override
        public void onSendMessage(String content) {
            NLog.i(TAG, "onSendMessage content = "+content);
            EaterManager.getInstance().broadcast(MessageParam.obtainTextMessage(content, conversation));
        }

        @Override
        public void onBigExpressionClicked(Emojicon emojicon) {

        }

        @Override
        public boolean onPressToSpeakBtnTouch(View v, MotionEvent event) {
            return false;
        }
    };

    @InterfaceInject(bindName = "layoutActionListener")
    ChatRoomLayout.OnLayoutActionListener layoutActionListener = this::finish;

    @EatMark(action = EaterAction.ACTION_DO_CHECK_MESSAGE)
    class MessageReceiver extends AbstractHandler<MessageParam> {

        @Override
        public void doJobWithParam(ParamWrap<MessageParam> paramWrap) {
            MessageParam param = paramWrap.getParam();
            switch (param.mMessageAction){
                case MessageParam.MESSAGE_ACTION_RECEIVED:
                    onMessageReceived(param.conversation, param.message);
                    break;
                case MessageParam.MESSAGE_ACTION_SEND_TEXT:
                    NLog.i(TAG, "MESSAGE_ACTION_SEND_TEXT param.messageText = "+param.messageText);
                    if (isValidMessage(param)) {
                        sendTextMessage(param.messageText);
                    }
                    break;
                case MessageParam.MESSAGE_ACTION_SEND_IMAGE:
                    break;
                case MessageParam.MESSAGE_ACTION_SEND_LOCATION:
                    break;
                case MessageParam.MESSAGE_ACTION_SEND_VOICE:
                    break;
                case MessageParam.MESSAGE_ACTION_SEND_VIDEO:
                    break;
                case MessageParam.MESSAGE_ACTION_SEND_FILE:
                    break;
            }
        }
    }

    private boolean isValidMessage(MessageParam param) {
        return Objects.equals(param.conversation.getConversationId(), conversation.getConversationId());
    }

    private void sendTextMessage(String messageText) {
        AVIMTextMessage message = new AVIMTextMessage();
        message.setText(messageText);
        sendMessage(message);
    }

    private void onMessageReceived(AVIMConversation conversation, AVIMTypedMessage message) {
        NLog.i(TAG, "onMessageReceived");
        if(conversation != null && this.conversation != null &&
                conversation.getConversationId().equals(this.conversation.getConversationId())) {
            switch (message.getMessageType()){
                case IMessageWrap.MESSAGE_TYPE_TEXT:
                    mLayout.pushMessagesAndRefreshToBottom(IMessageWrap.buildFrom(Collections.singletonList(message), false));
                    break;
            }
        }
    }

    public void sendMessage(AVIMTypedMessage message) {
        this.sendMessage(message, true);
    }

    public void sendMessage(final AVIMTypedMessage message, boolean addToList) {
        message.setMessageIOType(AVIMMessage.AVIMMessageIOType.AVIMMessageIOTypeOut);
        if(addToList) {
            mLayout.pushMessages(IMessageWrap.buildFrom(message,false));
        }
        mLayout.getChatLt().refreshSelectLast();
        mLayout.getChatLt().postToList(() -> {
            if (conversation != null) {
                conversation.sendMessage(message, new AVIMConversationCallback() {
                    public void done(AVIMException e) {
                        IMessageWrap iMessageWrap = mLayout.getChatLt().findMessageWrap(message);
                        if (iMessageWrap != null &&
                                iMessageWrap.onIMessageStateChangedListener_ != null){
                            iMessageWrap.onIMessageStateChangedListener_.onIMessageStateChanged(message.getMessageStatus());
                        }
                    }
                });
            }
        });
    }
}


text:
/**
 * @flow
 */

import React from 'react'

/**
 * Use an abstract class if you need to share functions that aren't used in the redux cycle. EG Helper functions etc.
 *
 */

export default class AbstractHome extends React.Component {

    constructor(props) {
        super(props);
    }

    componentWillMount() {
        //React lifecycle methods are supported for both react and react native. You can use them here.
    }

    _testApiCall() {
        this.props.callAPI('api/guild/guild/guildHomepage/mkdir%20BossCollection', 'get')
            .then((response) => {
                return response.json()
            }
            )
            .then(result => {
                console.log(result);
            })
    }

}


text:
using namespace std;
using namespace info;
/////////////////////////////
BOOST_FIXTURE_TEST_SUITE(ClusterizeKMeansTestSuite, DistanceFixture)
;
BOOST_AUTO_TEST_CASE(testInfoGlobalClusterize) {
	//BOOST_TEST_MESSAGE("InfoGlobalClusterizeKMeans");
	IIndivProvider *pProvider = m_provider.get();
	BOOST_REQUIRE(pProvider != nullptr);
	size_t nbClusters = 5;
	size_t nbMaxIters = 100;
	indivclusters_vector oClusters;
	size_t  nbIters = info_global_clusterize_kmeans(pProvider, nbClusters, oClusters, nbMaxIters);
	BOOST_REQUIRE(nbIters > 0);
	BOOST_CHECK(nbIters < nbMaxIters);
	//BOOST_TEST_MESSAGE("NbIterations: " << nbIters);
	BOOST_FOREACH(const IndivCluster &oCluster, oClusters)
	{
		std::string ss;
		this->write_point(oCluster.center(), ss);
		//BOOST_TEST_MESSAGE("Cluster: " << oCluster.index() << "\t" << ss);
	}// oCluster
} //testInfoGlobalClusterize
BOOST_AUTO_TEST_CASE(testClusterizeKMeans) {
	//BOOST_TEST_MESSAGE("ClusterizeKMeans");
	IIndivProvider *pProvider = m_provider.get();
	BOOST_REQUIRE(pProvider != nullptr);
	size_t nbClusters = 5;
	size_t nbMaxIters = 100;
	ClusterizeKMeans oMeans(pProvider, nbClusters);
	BOOST_REQUIRE(oMeans.is_valid());
	bool bRet = oMeans.compute(nbMaxIters);
	BOOST_REQUIRE(bRet);
	double fIntra = 0, fInter = 0, fCrit = 0;
	bRet = oMeans.intra_inertia(fIntra);
	BOOST_CHECK(bRet);
	BOOST_CHECK(fIntra > 0);
	bRet = oMeans.inter_inertia(fInter);
	BOOST_CHECK(bRet);
	BOOST_CHECK(fInter > 0);
	bRet = oMeans.criteria(fCrit);
	BOOST_CHECK(bRet);
	BOOST_CHECK(fCrit > 0);
	//BOOST_TEST_MESSAGE("Criteria: " << fCrit << "\tIntra: " << fIntra << "\tInter: " << fInter);
	const indivclusters_vector & oClusters = oMeans.clusters();
	BOOST_FOREACH(const IndivCluster &oCluster, oClusters)
	{
		std::string ss;
		this->write_point(oCluster.center(), ss);
		//BOOST_TEST_MESSAGE("Cluster: " << oCluster.index() << "\t" << ss);
	}// oCluster
} //testClusterizeKMeans
BOOST_AUTO_TEST_CASE(testClusterizeKMeansCollector) {
	//BOOST_TEST_MESSAGE("ClusterizeKMeansCollector");
	IIndivProvider *pProvider = m_provider.get();
	BOOST_REQUIRE(pProvider != nullptr);
	size_t nbClusters = 5;
	size_t nbMaxIters = 100;
	size_t nbRuns = 10;
	ClusterizeKMeansCollector oCol;
	oCol.process(pProvider, nbClusters, nbMaxIters, nbRuns);
	const ClusterizeKMeans &oMeans = oCol.object();
	double fIntra = 0, fInter = 0, fCrit = 0;
	bool bRet = oMeans.intra_inertia(fIntra);
	BOOST_CHECK(bRet);
	BOOST_CHECK(fIntra > 0);
	bRet = oMeans.inter_inertia(fInter);
	BOOST_CHECK(bRet);
	BOOST_CHECK(fInter > 0);
	bRet = oMeans.criteria(fCrit);
	BOOST_CHECK(bRet);
	BOOST_CHECK(fCrit > 0);
	//BOOST_TEST_MESSAGE("Criteria: " << fCrit << "\tIntra: " << fIntra << "\tInter: " << fInter);
	const indivclusters_vector & oClusters = oMeans.clusters();
	BOOST_FOREACH(const IndivCluster &oCluster, oClusters)
	{
		std::string ss;
		this->write_point(oCluster.center(), ss);
	//	BOOST_TEST_MESSAGE("Cluster: " << oCluster.index() << "\t" << ss);
	}// oCluster
} //testClusterizeKMeansCollector
BOOST_AUTO_TEST_SUITE_END();


text:
Terminal (emulator)
-------------------
* [iTerm2 (OSX)](http://www.iterm2.com)
* [Hyper](https://github.com/zeit/hyper)
* Tmux

Bash
----
* [Bash Sensible](https://github.com/mrzool/bash-sensible)
* [Bash-it](https://github.com/Bash-it/bash-it)
* [Bashstrap (OSX only)](https://github.com/barryclark/bashstrap)
* https://github.com/sebglazebrook/aliases
* [bash-completion](https://github.com/scop/bash-completion) ([install on OSX](http://davidalger.com/development/bash-completion-on-os-x-with-brew/))

Commands (GNU CoreUtils for OSX)
-------------

Running GNU coreutils via Homebrew on your Mac? Here's a one-liner to get the manpages working!
https://gist.github.com/quickshiftin/9130153
* https://github.com/k4m4/terminals-are-sexy#package-managers

History
-------

* [Better Bash History](https://sanctum.geek.nz/arabesque/better-bash-history/)
* [histr](https://github.com/dvorka/hstr)

Prompt
------

* https://github.com/aitorpazos/awesome-prompt
* https://github.com/banga/powerline-shell
* https://github.com/riobard/bash-powerline
* https://github.com/nojhan/liquidprompt
* https://github.com/twolfson/sexy-bash-prompt

Terminal Font
-------------
* https://github.com/gabrielelana/awesome-terminal-fonts
* https://github.com/powerline/fonts

Help
----
* https://github.com/gleitz/howdoi
* https://github.com/tldr-pages/tldr/
* http://bropages.org/
* https://github.com/chrisallenlane/cheat
* https://github.com/lucaswerkmeister/cheats
* https://github.com/ttscoff/where/
* http://brettterpstra.com/2016/05/18/shell-tricks-halp-a-universal-help-tool/

Zsh
---
* https://github.com/unixorn/awesome-zsh-plugins
* [Antigen](https://github.com/zsh-users/antigen)
* [Oh-my-zsh](http://ohmyz.sh/)
* https://github.com/sorin-ionescu/prezto
* https://github.com/tarjoilija/zgen

Process Management
--------------------
* http://hisham.hm/htop/

Pager
-----
* http://www.jedsoft.org/most/

Escape sequences
----------------
* https://github.com/fidian/ansi

|
---
* http://www.ivarch.com/programs/pv.shtml

grep
----
* https://github.com/ggreer/the_silver_searcher

cd
--
* [fasd](https://github.com/clvv/fasd)

find
----
* https://github.com/junegunn/fzf
* https://github.com/peco/peco

ls
--
* https://github.com/ogham/exa

cat
---
* [prettyjson (.json)](https://github.com/rafeca/prettyjson)

cp
---
* https://github.com/AvianFlu/ncp

curl
----
* [HTTPie](https://httpie.org/)

which
-----
* https://github.com/ttscoff/where/


text:
module Tct.Jbc.Data.Problem
  ( Jbc (..)
  , fromString
  , JbcStrategy
  , JbcDeclaration

  , CTrs (..)
  ) where

import qualified Jat.CompGraph                      as J (JGraph)
import qualified Jat.PState                         as J (PairSharing, SignedIntDomain)
import qualified Jat.Utils.TRS                      as J (PARule, prettyCTRS)
import qualified Jinja.Program                      as J (ClassId, MethodId, Program)
import qualified Jinja.Program.Data                 as J (initP)
import qualified Jinja.Program.Parser               as J (fromString)

import qualified Tct.Core                           as T
import qualified Tct.Core.Common.Pretty             as PP
import qualified Tct.Core.Common.Xml                as Xml

--- * jinja ----------------------------------------------------------------------------------------------------------
-- j2j lib needs alex and happy  :(

-- newtype Jinja = Jinja (JJ.MapOfMapClasses (),[(String,[String])])

-- instance Show Jinja      where show (Jinja (m,b)) = JJ.prettySourceCode b m
-- instance PP.Pretty Jinja where pretty             = PP.text . show
-- instance Xml.Xml Jinja   where toXml _            = Xml.empty

-- toJinja :: String -> Jinja
-- toJinja = Jinja . JJ.processClasses

--- * jbc ------------------------------------------------------------------------------------------------------------

data Jbc = Jbc
  { program :: J.Program
  , entry   :: Maybe (J.ClassId, J.MethodId) } -- when Nothing we assume there is a main function
  deriving Show

instance PP.Pretty Jbc where pretty p = PP.text . show $ program p
instance Xml.Xml Jbc   where toXml _  = Xml.empty

-- toJbc' :: Jinja -> Jbc
-- toJbc' (Jinja (m,b)) = Jbc . J.initP . J.fromString $ JJ.prettyJBC b (JJ.compileClasses m)

fromString :: String -> Jbc
fromString = flip Jbc Nothing . J.initP . J.fromString

type JbcStrategy    = T.Strategy Jbc Jbc
type JbcDeclaration = T.StrategyDeclaration Jbc Jbc

--- * cTRS -----------------------------------------------------------------------------------------------------------

-- CTRSs: term rewriting + Peano Arithmetic
-- defined function symbols occur only at root position
-- for a rule f(t1,...,tn) -> g(t1',...,tn') C, we call t1,...,tn and t1',...,tn' argument positions

data CTrs = CTrs (J.JGraph J.SignedIntDomain J.PairSharing) [J.PARule] deriving Show

instance PP.Pretty CTrs where pretty (CTrs _ rs) = J.prettyCTRS rs
instance Xml.Xml CTrs   where toXml _            = Xml.empty


text:
package pourmaster.search;

import pourmaster.InvertedIndex;
import pourmaster.TermDictionary;
import pourmaster.fields.Field;
import pourmaster.postings.PostingsData;
import pourmaster.terms.Term;
import pourmaster.terms.TermOccurrence;
import pourmaster.util.IOIterator;
import pourmaster.util.PriorityQueueIterator;

import java.io.IOException;
import java.util.Collections;
import java.util.Iterator;
import java.util.PriorityQueue;

/**
 * Query for a single term in a specific field. Typically used with a
 * {@link MultiTermQuery}.
 */
public class TermQuery extends FieldQuery {

    private final Term term;

    public TermQuery(Term term, String fieldName) {
        super(fieldName);
        this.term = term;
    }

    @Override
    public Iterator<RankedDocumentId> search(InvertedIndex index) throws IOException {
        TermDictionary.TermData termData = index.getDictionary().findTerm(term);
        if (termData == null) {
            // No results
            return Collections.emptyIterator();
        }
        long documentCount = index.getDocIndex().getDocumentCount();
        final IOIterator<PostingsData> postingsData = index.getPostings().getDocumentsForTerm(termData.getPostingsIndex(), termData.getDocFrequency());
        Field queryField = index.getDocIndex().getFieldDataStore().getField(getField());
        int fieldId = queryField.getFieldId();
        PriorityQueue<RankedDocumentId> result = new PriorityQueue<RankedDocumentId>();
        // Normalize scores and add to result set
        while (postingsData.hasNext()) {
            PostingsData data = postingsData.next();
            long docId = data.getDocumentId();
            int tf = 0;
            for (TermOccurrence occurrence : data.getPositions()) {
                if (occurrence.getFieldId() == fieldId) {
                    tf++;
                }
            }
            if (tf > 0) {
                double idf = Math.log((double) documentCount / (double) (1 + termData.getFieldDocFrequency(queryField.getFieldId())));

                // Field length normalization
                float fieldNorm = index.getFieldNormsStore().getFieldNorm(fieldId, docId);
                result.add(new RankedDocumentId(docId, tf * idf * getBoost() * fieldNorm));
            }
        }
        return new PriorityQueueIterator<RankedDocumentId>(result);
    }

    @Override
    public double getBoost() {
        return super.getBoost();
    }

    public Term getTerm() {
        return term;
    }
}


text:
import { ChangeDetectionStrategy, ChangeDetectorRef, Component, Input, OnDestroy } from '@angular/core';
import { TranslateService } from '@ngx-translate/core';
import { Store } from '@ngxs/store';
import { IdName, LoadOpts, Project } from 'app/model/project.model';
import { ProjectFilter, TimelineFilter } from 'app/model/timeline.model';
import { ProjectStore } from 'app/service/project/project.store';
import { TimelineStore } from 'app/service/timeline/timeline.store';
import { AutoUnsubscribe } from 'app/shared/decorator/autoUnsubscribe';
import { ToastService } from 'app/shared/toast/ToastService';
import { FetchProject } from 'app/store/project.action';
import { ProjectState, ProjectStateModel } from 'app/store/project.state';
import cloneDeep from 'lodash-es/cloneDeep';
import { finalize, flatMap } from 'rxjs/operators';

@Component({
    selector: 'app-home-filter',
    templateUrl: './home.filter.html',
    styleUrls: ['./home.filter.scss'],
    changeDetection: ChangeDetectionStrategy.OnPush
})
@AutoUnsubscribe()
export class HomeFilterComponent implements OnDestroy {

    _filter: TimelineFilter;
    filterToEdit: TimelineFilter;

    @Input()
    set filter(data: TimelineFilter) {
        if (data) {
            this._filter = data;
            this.filterToEdit = cloneDeep(data);
        }
    }

    get filter() {
        return this.filterToEdit;
    }

    projects: Array<Project>;

    selectedProjectKey: string;

    loading = false;

    constructor(
        private store: Store,
        private _projectStore: ProjectStore,
        private _timelineStore: TimelineStore,
        private _translate: TranslateService,
        private _toast: ToastService,
        private _cd: ChangeDetectorRef
    ) {
        this._projectStore.getProjectsList().subscribe(ps => {
            if (ps) {
                this.projects = ps.toArray();
            }
        });
    }

    ngOnDestroy(): void {} // Should be set to use @AutoUnsubscribe with AOT

    addProject(): void {
        if (!this.selectedProjectKey || this.selectedProjectKey === '') {
            return;
        }
        if (this.filter.projects) {
            let exist = this.filter.projects.find(p => p.key === this.selectedProjectKey);
            if (exist) {
                return;
            }
        } else {
            this.filter.projects = new Array<ProjectFilter>();
        }

        let projFilter = new ProjectFilter();
        projFilter.key = this.selectedProjectKey;
        this.filter.projects.push(projFilter);
        this.loadProjectWorkflow(projFilter, true);

        this.selectedProjectKey = '';
    }

    removeProject(pf: ProjectFilter): void {
        this.filter.projects = this.filter.projects.filter(p => p.key !== pf.key);
    }

    // load workflow when opening dropdown
    loadProjectWorkflow(projFilter: ProjectFilter, mute: boolean) {
        if (projFilter.project) {
            return;
        }
        projFilter.loading = true;

        let opts = new Array<LoadOpts>();
        opts.push(new LoadOpts('withWorkflowNames', 'workflow_names'));

        this.store.dispatch(new FetchProject({
            projectKey: projFilter.key,
            opts
        })).pipe(
            finalize(() => {
                projFilter.loading = false;
                this._cd.markForCheck();
            }),
            flatMap(() => this.store.selectOnce(ProjectState))
        ).subscribe((proj: ProjectStateModel) => {
            projFilter.project = cloneDeep(proj.project);
            if (projFilter.project && projFilter.project.workflow_names) {
                projFilter.project.workflow_names.forEach(wn => {
                    if (mute) {
                        wn.mute = true;
                    } else {
                        let index = projFilter.workflow_names.findIndex(wwnn => wwnn === wn.name);
                        if (index >= 0) {
                            wn.mute = true;
                        } else {
                            wn.mute = false;
                        }
                    }
                });
                if (mute) {
                    projFilter.workflow_names = projFilter.project.workflow_names.map(idname => idname.name);
                }
            }
        });
    }

    updateWorkflowInFilter(w: IdName, projFilter: ProjectFilter): void {
        if (!projFilter.workflow_names) {
            projFilter.workflow_names = new Array<string>();
        }
        w.mute = !w.mute;
        if (!w.mute) {
            let index = projFilter.workflow_names.findIndex(wn => wn === w.name);
            if (index >= 0) {
                projFilter.workflow_names.splice(index, 1);
            }
        } else {
            let index = projFilter.workflow_names.findIndex(wn => wn === w.name);
            if (index === -1) {
                projFilter.workflow_names.push(w.name);
            }
        }
    }

    saveFilter(): void {
        this.loading = true;
        this._timelineStore.saveFilter(this.filter)
            .pipe(finalize(() => {
                this.loading = false;
                this._cd.markForCheck();
            }))
            .subscribe(() => {
                this._toast.success('', this._translate.instant('timeline_filter_updated'));
            });
    }
}


text:
ARG version

FROM ubuntu:${version}

RUN apt update -y && \
    apt install -y --no-install-recommends \
    build-essential \
    libffi-dev \
    libssl-dev \
    python-pip \
    python-pkg-resources \
    git \
    systemd

RUN pip2 install setuptools && \
    pip2 install ansible

RUN mkdir -p /etc/ansible && echo "[local]\nlocalhost ansible_connection=local" > /etc/ansible/hosts

ENTRYPOINT ["/bin/systemd"]


text:
<?php

namespace IPS\Login;

/* To prevent PHP errors (extending class does not exist) revealing path */
if ( !defined( '\IPS\SUITE_UNIQUE_KEY' ) )
{
	header( ( isset( $_SERVER['SERVER_PROTOCOL'] ) ? $_SERVER['SERVER_PROTOCOL'] : 'HTTP/1.0' ) . ' 403 Forbidden' );
	exit;
}

/**
 * Windows Live Login Handler
 */
class _Live extends LoginAbstract
{
	/**
	 * @brief	Icon
	 */
	public static $icon = 'windows';

	/**
	 * Get Form
	 *
	 * @param	\IPS\Http\Url	$url			The URL for the login page
	 * @param	bool			$ucp			Is UCP? (as opposed to login form)
	 * @param	\IPS\Http\Url	$destination	The URL to redirect to after a successful login
	 * @return	string
	 */
	public function loginForm( \IPS\Http\Url $url, $ucp = FALSE, \IPS\Http\Url $destination = NULL )
	{
		return \IPS\Theme::i()->getTemplate( 'login', 'core', 'global' )->live( (string) \IPS\Http\Url::external( 'https://login.live.com/oauth20_authorize.srf' )->setQueryString( array(
			'client_id'		=> $this->settings['client_id'],
			'scope'			=> 'wl.signin wl.emails wl.offline_access',
			'response_type'	=> 'code',
			'redirect_uri'	=> (string) \IPS\Http\Url::internal( 'applications/core/interface/microsoft/auth.php', 'none' ),
			'state'			=> ( $ucp ? 'ucp' : \IPS\Dispatcher::i()->controllerLocation ) . '-' . \IPS\Session::i()->csrfKey . '-' . ( $destination ? base64_encode( $destination ) : '' )
		) ) );
	}

	/**
	 * Authenticate
	 *
	 * @param	string	$url	The URL for the login page
	 * @param	\IPS\Member		$member	If we want to integrate this login method with an existing member, provide the member object
	 * @return	\IPS\Member
	 * @throws	\IPS\Login\Exception
	 */
	public function authenticate( $url, $member=NULL )
	{
		try
		{
			/* CSRF Check */
			if ( \IPS\Request::i()->state !== \IPS\Session::i()->csrfKey )
			{
				throw new \IPS\Login\Exception( 'CSRF_FAIL', \IPS\Login\Exception::INTERNAL_ERROR );
			}

			/* Send HTTP request */
			$response = \IPS\Http\Url::external( 'https://login.live.com/oauth20_token.srf' )->request()->post( array(
				'client_id'		=> $this->settings['client_id'],
				'redirect_uri'	=> (string) \IPS\Http\Url::internal( 'applications/core/interface/microsoft/auth.php', 'none' ),
				'client_secret'	=> $this->settings['client_secret'],
				'code'			=> \IPS\Request::i()->code,
				'grant_type'	=> 'authorization_code'
			) )->decodeJson();

			/* Check the response */
			if ( isset( $response['error'] ) or !isset( $response['access_token'] ) )
			{
				throw new \IPS\Login\Exception( 'generic_error', \IPS\Login\Exception::INTERNAL_ERROR );
			}

			/* Get user data */
			$userData = \IPS\Http\Url::external( "https://apis.live.net/v5.0/me?access_token={$response['access_token']}" )->request()->get()->decodeJson();

			/* Find or create member */
			$member = $this->createOrUpdateAccount( $member ?: \IPS\Member::load( $userData['id'], 'live_id' ), array(
				'live_id'		=> $userData['id'],
				'live_token'	=> $response['refresh_token'],
			), $this->settings['real_name'] ? $userData['name'] : NULL, $userData['emails']['preferred'], $response['access_token'], array( 'photo' => TRUE, 'cover' => FALSE, 'status' => '' ), 'IPS\core\ProfileSync\Microsoft' );

			/* Return */
			return $member;
		}
		catch ( \IPS\Http\Request\Exception $e )
   		{
	   		throw new \IPS\Login\Exception( 'generic_error', \IPS\Login\Exception::INTERNAL_ERROR );
   		}
	}

	/**
	 * Link Account
	 *
	 * @param	\IPS\Member	$member		The member
	 * @param	mixed		$details	Details as they were passed to the exception thrown in authenticate()
	 * @return	void
	 */
	public static function link( \IPS\Member $member, $details )
	{
		$userData = \IPS\Http\Url::external( "https://apis.live.net/v5.0/me?access_token={$details}" )->request()->get()->decodeJson();
		$member->live_id = $userData['id'];
		$member->live_token = $details;
		$member->save();
	}

	/**
	 * ACP Settings Form
	 *
	 * @param	string	$url	URL to redirect user to after successful submission
	 * @return	array	List of settings to save - settings will be stored to core_login_handlers.login_settings DB field
	 * @code
	 	return array( 'savekey'	=> new \IPS\Helpers\Form\[Type]( ... ), ... );
	 * @endcode
	 */
	public function acpForm()
	{
		\IPS\Output::i()->sidebar['actions'] = array(
			'help'	=> array(
				'title'		=> 'help',
				'icon'		=> 'question-circle',
				'link'		=> \IPS\Http\Url::ips( 'docs/login_live' ),
				'target'	=> '_blank',
				'class'		=> ''
			),
		);

		return array(
			'client_id'		=> new \IPS\Helpers\Form\Text( 'login_live_client', ( isset( $this->settings['client_id'] ) ) ? $this->settings['client_id'] : '', TRUE ),
			'client_secret'	=> new \IPS\Helpers\Form\Text( 'login_live_secret', ( isset( $this->settings['client_secret'] ) ) ? $this->settings['client_secret'] : '', TRUE ),
			'real_name'		=> new \IPS\Helpers\Form\YesNo( 'login_real_name', ( isset( $this->settings['real_name'] ) ) ? $this->settings['real_name'] : FALSE, TRUE )
		);
	}

	/**
	 * Test Settings
	 *
	 * @return	bool
	 * @throws	\IPS\Http\Request\Exception
	 * @throws	\UnexpectedValueException	If response code is not 200
	 */
	public function testSettings()
	{
		try
		{
			$response = \IPS\Http\Url::external( "https://login.live.com/oauth20_authorize.srf?client_id={$this->settings['client_id']}&scope=wl.signin%20wl.emails&response_type=code&redirect_uri=" )->request()->get();
			if ( $response->httpResponseCode != 200 )
			{
				throw new \InvalidArgumentException( \IPS\Member::loggedIn()->language()->addToStack('login_3p_bad', FALSE, array( 'sprintf' => array( \IPS\Member::loggedIn()->language()->addToStack('login_handler_Live') ) ) ) );
			}
		}
		catch ( \IPS\Http\Request\Exception $e )
		{
			throw new \InvalidArgumentException( \IPS\Member::loggedIn()->language()->addToStack('login_3p_bad', FALSE, array( 'sprintf' => array( \IPS\Member::loggedIn()->language()->addToStack('login_handler_Live') ) ) ) );
		}
		return TRUE;
	}

	/**
	 * Can a member sign in with this login handler?
	 * Used to ensure when a user disassociates a social login that they have some other way of logging in
	 *
	 * @param	\IPS\Member	$member	The member
	 * @return	bool
	 */
	public function canProcess( \IPS\Member $member )
	{
		return ( $member->live_id and $member->live_token );
	}

	/**
	 * Can a member change their email/password with this login handler?
	 *
	 * @param	string		$type	'email' or 'password'
	 * @param	\IPS\Member	$member	The member
	 * @return	bool
	 */
	public function canChange( $type, \IPS\Member $member )
	{
		return FALSE;
	}

}


text:
package helmutil

const (
	// DefaultIndexFilePerm is default permissions for index file.
	DefaultIndexFilePerm = 0644
)


text:
const events = require('events')
const bunyan = require('bunyan')

const GpgEventContext = require('./gpg-context')
const handleEvent = require('./handle-event')

module.exports = class Plugin extends events.EventEmitter {
  constructor () {
    super()
    this.log = bunyan.createLogger({
      name: 'GPG',
      level: process.env.LOG_LEVEL || 'debug',
      serializers: bunyan.stdSerializers
    })
    this.robot = null
  }

  load (robot) {
    if (!(this instanceof Plugin)) {
      throw new TypeError('Unexpected execution context for method call')
    }

    if (this.robot !== null) {
      this.emit('error', new Error('Plugin instance has already been loaded'))
    }

    this.robot = robot
    this.robot.on(['pull_request.opened', 'pull_request.synchronize'], async context => this.acceptEvent(context))

    this.log.debug('Registered webhook event handlers.')

    this.emit('loaded')
  }

  async acceptEvent (context) {
    if (!(this instanceof Plugin)) {
      throw new TypeError('Unexpected execution context for method call')
    }

    if (this.robot === null) {
      this.emit('error', new Error('Cannot accept event before load'))
      return
    }

    try {
      await handleEvent(new GpgEventContext(this.log, context))
      this.emit('event-handled')
    } catch (err) {
      this.emit('error', err)
    }
  }
}


text:
@class Element;

// This represents the element/:elementId/attribute virtual directory.
@interface Attribute : HTTPVirtualDirectory {
  Element *element_;
}

+ (Attribute *)attributeDirectoryForElement:(Element *)element;

// Designated initialiser. Does not retain the element as per
// parent retain pattern.
- (id)initForElement:(Element *)element;

@end

// This represents the element/:elementId/attribute/:name virtual directory.
// This directory is dynamically added by |Attribute| the first time a request
// is received for |:name|.
@interface NamedAttribute : HTTPVirtualDirectory {
  @private
  Element* element_;
  NSString* name_;
}

+ (NamedAttribute *)namedAttributeDirectoryForElement:(Element *)element
                                              andName:(NSString *)name;
- (id)initForElement:(Element *)element
             andName:(NSString *)name;
- (NSString *)getAttribute;

@end


text:
public class Solution {
    public int[] twoSum(int[] nums, int target) {
        HashMap<Integer, Integer> hashMap = new HashMap<>();

        for (int i = 0; i < nums.length; i++) {
            if (hashMap.get(target - nums[i]) != null) {
                return new int[]{hashMap.get(target - nums[i]), i};
            }
            hashMap.put(nums[i], i);
        }

        return new int[]{};
    }
}


text:
/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

$('[name="buyer_id"]').change(function () {
    $.ajax({
        url: "http://thejamunapub.com/Publication/index.php/admin/total_due/" + $('[name="buyer_id"]').val(),
        beforeSend: function (xhr) {
            xhr.overrideMimeType("text/plain; charset=x-user-defined");
        }
    })
            .done(function (data) {
                $("#total_due").html(data);
            });
});


text:
<?php

use yii\helpers\Html;
use yii\grid\GridView;

/* @var $this yii\web\View */
/* @var $searchModel frontend\models\search\BooksSearch */
/* @var $dataProvider yii\data\ActiveDataProvider */

$this->title = Yii::t('frontend', 'Books');
$this->params['breadcrumbs'][] = $this->title;
?>

<?= Html::encode($this->title) ?>

    <?php // echo $this->render('_search', ['model' => $searchModel]); ?>

        <?= Html::a(Yii::t('frontend', 'Create Books'), ['create'], ['class' => 'btn btn-success']) ?>

    <?= GridView::widget([
        'dataProvider' => $dataProvider,
        'filterModel' => $searchModel,
        'columns' => [
            ['class' => 'yii\grid\SerialColumn'],

            'id',
            'name',
            'date_create',
            'date_update',
            'preview:ntext',
            // 'date_publication',
            // 'author_id',

            ['class' => 'yii\grid\ActionColumn'],
        ],
    ]); ?>


text:
<template name="browserHome">

Start Menu

        {{#unless menuFlipped}}
        Welcome to EVEFleet! What would you like to do?

Create a fleet

Create a new fleet as the Fleet Commander.

Join a Fleet

Instructions on how to use the InGame Browser to join a fleet.

        {{else}}

          Your view is based entirely in the InGame Browser. You will see standing orders, fits and shiptypes for the fleet, and live killboard updates as your fleet proceeds with operations. The browser will also keep the FC updated about all of the fleet members. To join, simply go to the fleet URL given to you by your FC in the ingame browser. You can also go to "{{baseUrl}}" and chose from fleets available to you.

Back

        {{/unless}}

      {{#if showFleetForm}}
      {{>fleetSetupForm}}
      {{/if}}

</template>
<template name="fleetSetupForm">

    Set up your fleet!

      <form class="form-horizontal" action="javascript:void(0);">
        <fieldset>

              Fleet Name
            <input type="text" class="form-control" id="fleetName" placeholder="Fleet Name"/>

            MOTD
            <textarea style="max-width:380px;max-height:120px;min-height:120px;height:120px;" class="form-control" id="motd" placeholder="Fleet Description"></textarea>

            <button class="btn btn-primary" id="finalizeFleetBtn">Create Fleet</button>

        </fieldset>
      </form>

</template>


text:
namespace Merchello.Core.Persistence.Repositories
{
    using System;
    using System.Collections.Generic;
    using System.Linq;

    using Merchello.Core.Models;
    using Merchello.Core.Models.EntityBase;
    using Merchello.Core.Models.Rdbms;
    using Merchello.Core.Persistence.Factories;
    using Merchello.Core.Persistence.Querying;
    using Merchello.Core.Persistence.UnitOfWork;

    using Umbraco.Core;
    using Umbraco.Core.Cache;
    using Umbraco.Core.Logging;
    using Umbraco.Core.Persistence;
    using Umbraco.Core.Persistence.Querying;
    using Umbraco.Core.Persistence.SqlSyntax;

    /// <summary>
    /// Represents the NotificationMessageRepository
    /// </summary>
    internal class NotificationMessageRepository : MerchelloPetaPocoRepositoryBase<INotificationMessage>, INotificationMessageRepository
    {
        /// <summary>
        /// Initializes a new instance of the <see cref="NotificationMessageRepository"/> class.
        /// </summary>
        /// <param name="work">
        /// The work.
        /// </param>
        /// <param name="logger">
        /// The logger.
        /// </param>
        /// <param name="sqlSyntax">
        /// The SQL Syntax.
        /// </param>
        public NotificationMessageRepository(IDatabaseUnitOfWork work, ILogger logger, ISqlSyntaxProvider sqlSyntax)
            : base(work, logger, sqlSyntax)
        {
        }

        protected override INotificationMessage PerformGet(Guid key)
        {
            var sql = GetBaseQuery(false)
            .Where(GetBaseWhereClause(), new { Key = key });

            var dto = Database.Fetch<NotificationMessageDto>(sql).FirstOrDefault();

            if (dto == null)
                return null;

            var factory = new NotificationMessageFactory();
            return factory.BuildEntity(dto);
        }

        protected override IEnumerable<INotificationMessage> PerformGetAll(params Guid[] keys)
        {
            var dtos = new List<NotificationMessageDto>();

            if (keys.Any())
            {
                // This is to get around the WhereIn max limit of 2100 parameters and to help with performance of each WhereIn query
                var keyLists = keys.Split(400).ToList();

                // Loop the split keys and get them
                foreach (var keyList in keyLists)
                {
                    dtos.AddRange(Database.Fetch<NotificationMessageDto>(GetBaseQuery(false).WhereIn<NotificationMessageDto>(x => x.Key, keyList, SqlSyntax)));
                }
            }
            else
            {
                dtos = Database.Fetch<NotificationMessageDto>(GetBaseQuery(false));
            }

            var factory = new NotificationMessageFactory();
            foreach (var dto in dtos)
            {
                yield return factory.BuildEntity(dto);
            }
        }

        /// <summary>
        /// Gets a collection of <see cref="INotificationMessage"/> by query.
        /// </summary>
        /// <param name="query">
        /// The query.
        /// </param>
        /// <returns>
        /// The <see cref="IEnumerable{INotificationMessage}"/>.
        /// </returns>
        protected override IEnumerable<INotificationMessage> PerformGetByQuery(IQuery<INotificationMessage> query)
        {
            var sqlClause = GetBaseQuery(false);
            var translator = new SqlTranslator<INotificationMessage>(sqlClause, query);
            var sql = translator.Translate();

            var dtos = Database.Fetch<NotificationMessageDto>(sql);

            return dtos.DistinctBy(x => x.Key).Select(dto => Get(dto.Key));
        }

        /// <summary>
        /// Gets the base query.
        /// </summary>
        /// <param name="isCount">
        /// The is count.
        /// </param>
        /// <returns>
        /// The <see cref="Sql"/>.
        /// </returns>
        protected override Sql GetBaseQuery(bool isCount)
        {
            var sql = new Sql();
            sql.Select(isCount ? "COUNT(*)" : "*")
                .From<NotificationMessageDto>(SqlSyntax);

            return sql;
        }

        /// <summary>
        /// Gets the base where clause.
        /// </summary>
        /// <returns>
        /// The <see cref="string"/>.
        /// </returns>
        protected override string GetBaseWhereClause()
        {
            return "merchNotificationMessage.pk = @Key";
        }

        /// <summary>
        /// Gets a list of delete clauses.
        /// </summary>
        /// <returns>
        /// The <see cref="IEnumerable{String}"/>.
        /// </returns>
        protected override IEnumerable<string> GetDeleteClauses()
        {
            var list = new List<string>
            {
                "DELETE FROM merchNotificationMessage WHERE pk = @Key"
            };

            return list;
        }

        /// <summary>
        /// Adds a new item to the database.
        /// </summary>
        /// <param name="entity">
        /// The entity.
        /// </param>
        protected override void PersistNewItem(INotificationMessage entity)
        {
            ((Entity)entity).AddingEntity();

            var factory = new NotificationMessageFactory();
            var dto = factory.BuildDto(entity);

            Database.Insert(dto);

            entity.Key = dto.Key;

            entity.ResetDirtyProperties();
        }

        /// <summary>
        /// Updates an existing item in the database.
        /// </summary>
        /// <param name="entity">
        /// The entity.
        /// </param>
        protected override void PersistUpdatedItem(INotificationMessage entity)
        {
            ((Entity)entity).UpdatingEntity();

            var factory = new NotificationMessageFactory();
            var dto = factory.BuildDto(entity);

            Database.Update(dto);

            entity.ResetDirtyProperties();
        }
    }
}


text:
/**
 *
 */
package net.freecoder.restdemo.dao.impl;

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

import net.freecoder.restdemo.dao.SmsHistoryDao;
import net.freecoder.restdemo.model.WlsSmsHistory;

import org.hibernate.criterion.Criterion;
import org.hibernate.criterion.LogicalExpression;
import org.hibernate.criterion.Order;
import org.hibernate.criterion.Restrictions;
import org.hibernate.criterion.SimpleExpression;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;

/**
 * @author JiTing
 */
@Repository
@Transactional
public class SmsHistoryDaoImpl extends CommonDaoImpl<WlsSmsHistory> implements
		SmsHistoryDao {

	@Override
	public WlsSmsHistory get(String id) {
		return super.get(WlsSmsHistory.class, id);
	}

	@Override
	public List<WlsSmsHistory> getByWxAccountId(String wxAccountId) {
		String hql = "from WlsSmsHistory where wlsWxAccountId=:wlsWxAccountId";
		Map<String, String> params = new HashMap<String, String>(1);
		params.put("wlsWxAccountId", wxAccountId);
		return super.find(hql, params);
	}

	@Override
	public List<WlsSmsHistory> getByWxAccountId(String wxAccountId, Date start,
			Date end) {
		SimpleExpression eq = Restrictions.eq("wlsWxAccountId", wxAccountId);
		Criterion dateRange = Restrictions.between("appCreateTime", start, end);
		LogicalExpression and = Restrictions.and(eq, dateRange);
		Order desc = Order.desc("appCreateTime");
		List<WlsSmsHistory> list = super.find(WlsSmsHistory.class, and, desc);
		return list;
	}

	@Override
	public List<WlsSmsHistory> getByPhoneNumber(String phoneNumber) {
		String hql = "from WlsSmsHistory where phoneNumber like :phoneNumber";
		Map<String, String> params = new HashMap<String, String>(1);
		params.put("phoneNumber", "%" + phoneNumber + "%");
		return super.find(hql, params);
	}

	@Override
	public List<WlsSmsHistory> getByPhoneNumber(String phoneNumber, Date start,
			Date end) {
		SimpleExpression eq = Restrictions.eq("phoneNumber", phoneNumber);
		Criterion dateRange = Restrictions.between("appCreateTime", start, end);
		LogicalExpression and = Restrictions.and(eq, dateRange);
		Order desc = Order.desc("appCreateTime");
		List<WlsSmsHistory> list = super.find(WlsSmsHistory.class, and, desc);
		return list;
	}

	@Override
	public List<WlsSmsHistory> getByAccountPhone(String wxAccountId,
			String phoneNumber) {
		String hql = "from WlsSmsHistory where wlsWxAccountId=:wlsWxAccountId and phoneNumber like :phoneNumber";
		Map<String, String> params = new HashMap<String, String>(1);
		params.put("wlsWxAccountId", wxAccountId);
		params.put("phoneNumber", "%" + phoneNumber + "%");
		return super.find(hql, params);
	}

	@Override
	public List<WlsSmsHistory> getByAccountPhone(String wxAccountId,
			String phoneNumber, Date start, Date end) {
		SimpleExpression eqAccount = Restrictions.eq("wlsWxAccountId",
				wxAccountId);
		SimpleExpression eqPhone = Restrictions.eq("phoneNumber", phoneNumber);
		Criterion dateRange = Restrictions.between("appCreateTime", start, end);
		LogicalExpression and = Restrictions.and(eqAccount, eqPhone);
		LogicalExpression and2 = Restrictions.and(and, dateRange);
		Order desc = Order.desc("appCreateTime");
		List<WlsSmsHistory> list = super.find(WlsSmsHistory.class, and2, desc);
		return list;
	}

}


text: typedef void (*logprintf_t)(const char* format, ...);


text:
require "./ruler"

#-----------------------------------------------------------------------------
R("")

class Thing
	attr_accessor :name
	def initialize(options = {})
		@name = options[:name] || "unknown"
	end
	def to_s
		"> @name"
	end
	def to_a
		[@name]
	end
	alias_method :to_ary, :to_a

	def method_missing(method_name)
		puts "> Missing method: #{method_name}"
		super
	end
end

R("Create an object of Thing class and list its methods")
t0 = Thing.new
t0.methods.sort.each do |m|
	print "#REM #{m} "
end
puts

R("Check how respond_to? works")

puts t0.respond_to?(:to_s)
puts t0.respond_to?(:to_ss)

R("Try to redefine the respond_to method")
t0.instance_eval do
	def respond_to?(method_name)
		if method_name =~ /to_ss/
			true
		else
			super
		end
	end
end
puts t0.respond_to?(:to_s)
puts t0.respond_to?(:to_ss)


text:
<?php
/* @var $this \yii\web\View */
use yii\helpers\ArrayHelper;
use yii\widgets\Breadcrumbs;

/* @var $content string */

if (isset($this->blocks['sidebar'])) {
    $this->beginContent(__DIR__ . '/column2.php');
} else {
    $this->beginContent(__DIR__ . '/_main.php');
}
?>
<?php echo $content ?>

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


text:
Here is what to include in your request to make sure we implement a solution as quickly as possible.

## 1. Description
Describe the issue or propose a feature.

## 2. Exception
If you are seeing an exception, include the full exception details (message and stack trace).

```
Exception message:
Stack trace:
```

## 3. Fiddle or Project
If you are able,

Provide a Fiddle that reproduce the issue: https://dotnetfiddle.net/25Vjsn

Or provide a project/solution that we can run to reproduce the issue.
- Make sure the project compile
- Make sure to provide only the code that is required to reproduce the issue, not the whole project
- You can send private code here: info@zzzprojects.com

Otherwise, make sure to include as much information as possible to help our team to reproduce the issue.

## 4. Any further technical details
Add any relevant detail can help us, such as:

- HAP version:
- NET version (net45, .net core 3.1, etc.)


text:
package org.apache.slide.common;

import org.apache.slide.util.Messages;

/**
 * Unknown service declaration exception.
 *
 * @version $Revision: 1.2 $
 */
public class UnknownServiceDeclarationException extends SlideException {

    // ----------------------------------------------------------- Constructors

    /**
     * Constructor.
     *
     * @param serviceName Name of the unknown service
     */
    public UnknownServiceDeclarationException(String serviceName) {
        super(Messages.format
              (UnknownServiceDeclarationException.class.getName(),
               serviceName));
    }

}


text:
<?xml version="1.0" encoding="UTF-8" ?>
<testsuite tests="6" failures="0" name="hu.cegnev.todolistapp.business.TodoLogicTest" time="0.074" errors="0" skipped="0">
  <properties>
    <property name="java.runtime.name" value="Java(TM) SE Runtime Environment"/>
    <property name="sun.boot.library.path" value="C:\Program Files\Java\jdk1.8.0_40\jre\bin"/>
    <property name="java.vm.version" value="25.40-b25"/>
    <property name="user.country.format" value="HU"/>
    <property name="java.vm.vendor" value="Oracle Corporation"/>
    <property name="maven.multiModuleProjectDirectory" value="C:\Users\Daniel\IdeaProjects\TodoListApp"/>
    <property name="java.vendor.url" value="http://java.oracle.com/"/>
    <property name="path.separator" value=";"/>
    <property name="guice.disable.misplaced.annotation.check" value="true"/>
    <property name="java.vm.name" value="Java HotSpot(TM) 64-Bit Server VM"/>
    <property name="file.encoding.pkg" value="sun.io"/>
    <property name="user.script" value=""/>
    <property name="user.country" value="US"/>
    <property name="sun.java.launcher" value="SUN_STANDARD"/>
    <property name="sun.os.patch.level" value=""/>
    <property name="java.vm.specification.name" value="Java Virtual Machine Specification"/>
    <property name="user.dir" value="C:\Users\Daniel\IdeaProjects\TodoListApp"/>
    <property name="java.runtime.version" value="1.8.0_40-b26"/>
    <property name="java.awt.graphicsenv" value="sun.awt.Win32GraphicsEnvironment"/>
    <property name="java.endorsed.dirs" value="C:\Program Files\Java\jdk1.8.0_40\jre\lib\endorsed"/>
    <property name="os.arch" value="amd64"/>
    <property name="java.io.tmpdir" value="C:\Users\Daniel\AppData\Local\Temp\"/>
    <property name="line.separator" value="
"/>
    <property name="java.vm.specification.vendor" value="Oracle Corporation"/>
    <property name="user.variant" value=""/>
    <property name="os.name" value="Windows 8.1"/>
    <property name="classworlds.conf" value="C:\Program Files\Apache\Maven\bin\m2.conf"/>
    <property name="sun.jnu.encoding" value="Cp1250"/>
    <property name="java.library.path" value="C:\Program Files\Java\jdk1.8.0_40\bin;C:\Windows\Sun\Java\bin;C:\Windows\system32;C:\Windows;C:\ProgramData\Oracle\Java\javapath;C:\Windows\system32;C:\Windows;C:\Windows\System32\Wbem;C:\Windows\System32\WindowsPowerShell\v1.0\;C:\Program Files (x86)\Git\cmd;C:\Program Files (x86)\Skype\Phone\;C:\Users\Daniel\AppData\Local\Android\sdk\platform-tools;C:\Python32;C:\Python32\Scripts;C:\Users\Daniel\.gradle\wrapper\dists\gradle-2.2.1-all\c64ydeuardnfqctvr1gm30w53\gradle-2.2.1\bin;%Android_SDK_HOME%\tools;C:\Program Files\Apache\Maven\bin;C:\cygwin64\bin;;C:\Program Files (x86)\Heroku\bin;C:\Program Files (x86)\git\cmd;C:\Program Files\nodejs\;C:\sonar-runner\bin\;C:\Users\Daniel\AppData\Roaming\npm;."/>
    <property name="java.specification.name" value="Java Platform API Specification"/>
    <property name="java.class.version" value="52.0"/>
    <property name="sun.management.compiler" value="HotSpot 64-Bit Tiered Compilers"/>
    <property name="os.version" value="6.3"/>
    <property name="user.home" value="C:\Users\Daniel"/>
    <property name="user.timezone" value="Europe/Prague"/>
    <property name="java.awt.printerjob" value="sun.awt.windows.WPrinterJob"/>
    <property name="java.specification.version" value="1.8"/>
    <property name="file.encoding" value="Cp1250"/>
    <property name="user.name" value="Daniel"/>
    <property name="java.class.path" value="C:\Program Files\Apache\Maven\boot\plexus-classworlds-2.5.2.jar"/>
    <property name="java.vm.specification.version" value="1.8"/>
    <property name="sun.arch.data.model" value="64"/>
    <property name="java.home" value="C:\Program Files\Java\jdk1.8.0_40\jre"/>
    <property name="sun.java.command" value="org.codehaus.plexus.classworlds.launcher.Launcher clean install"/>
    <property name="java.specification.vendor" value="Oracle Corporation"/>
    <property name="user.language" value="en"/>
    <property name="user.language.format" value="hu"/>
    <property name="awt.toolkit" value="sun.awt.windows.WToolkit"/>
    <property name="java.vm.info" value="mixed mode"/>
    <property name="java.version" value="1.8.0_40"/>
    <property name="java.ext.dirs" value="C:\Program Files\Java\jdk1.8.0_40\jre\lib\ext;C:\Windows\Sun\Java\lib\ext"/>
    <property name="sun.boot.class.path" value="C:\Program Files\Java\jdk1.8.0_40\jre\lib\resources.jar;C:\Program Files\Java\jdk1.8.0_40\jre\lib\rt.jar;C:\Program Files\Java\jdk1.8.0_40\jre\lib\sunrsasign.jar;C:\Program Files\Java\jdk1.8.0_40\jre\lib\jsse.jar;C:\Program Files\Java\jdk1.8.0_40\jre\lib\jce.jar;C:\Program Files\Java\jdk1.8.0_40\jre\lib\charsets.jar;C:\Program Files\Java\jdk1.8.0_40\jre\lib\jfr.jar;C:\Program Files\Java\jdk1.8.0_40\jre\classes"/>
    <property name="sun.stderr.encoding" value="cp852"/>
    <property name="java.vendor" value="Oracle Corporation"/>
    <property name="maven.home" value="C:\Program Files\Apache\Maven"/>
    <property name="file.separator" value="\"/>
    <property name="java.vendor.url.bug" value="http://bugreport.sun.com/bugreport/"/>
    <property name="sun.cpu.endian" value="little"/>
    <property name="sun.io.unicode.encoding" value="UnicodeLittle"/>
    <property name="sun.stdout.encoding" value="cp852"/>
    <property name="sun.desktop" value="windows"/>
    <property name="sun.cpu.isalist" value="amd64"/>
  </properties>
  <testcase classname="hu.cegnev.todolistapp.business.TodoLogicTest" name="testAdd" time="0.074"/>
  <testcase classname="hu.cegnev.todolistapp.business.TodoLogicTest" name="testGetAvailableTodos" time="0"/>
  <testcase classname="hu.cegnev.todolistapp.business.TodoLogicTest" name="testTodoListName" time="0"/>
  <testcase classname="hu.cegnev.todolistapp.business.TodoLogicTest" name="testRemove" time="0"/>
  <testcase classname="hu.cegnev.todolistapp.business.TodoLogicTest" name="testUpdate" time="0"/>
  <testcase classname="hu.cegnev.todolistapp.business.TodoLogicTest" name="testCheckContainById" time="0"/>
</testsuite>


text:
angular.module('services', [])
    .factory('devicesService', function ($rootScope,$http,$q) {
        this.selected = null;
        $rootScope.baseUrl = 'http://192.168.1.44/TrakerBackEnd/web/';
	    return {
			getAll: getAll,
			addDevice:addDevice,
            activateOrDesactivate:activateOrDesactivate,
            setSelected:setSelected,
            getSelected:getSelected,
            updateDevice:updateDevice,
            deleteDevice:deleteDevice
		}

        function setSelected(value)
        {
            this.selected = value;
        }

        function getSelected(value)
        {
           return this.selected;
        }

	    function getAll (input) {

			    var defered = $q.defer();
			    var promise = defered.promise;

			    $http.post($rootScope.baseUrl + 'index.php?r=device/cargar',input)
				.success(function(result) {
					defered.resolve(result.data);
				})
				.error(function(err) {
					defered.reject(err)
				});

                return promise;
       }

       function activateOrDesactivate (input)
       {
               var defered = $q.defer();
			    var promise = defered.promise;

			    $http.post($rootScope.baseUrl+'index.php?r=device/activate', input)
				.success(function(result) {
					defered.resolve(result);
				})
				.error(function(err) {
					defered.reject(err)
				});
               return promise;
       }

 	   function addDevice (input) {
                var defered = $q.defer();
			    var promise = defered.promise;

			    $http.post($rootScope.baseUrl+'index.php?r=device/create', input)
				.success(function(result) {
					defered.resolve(result);
				})
				.error(function(err) {
					defered.reject(err)
				});
               return promise;
        }

        function updateDevice (input) {
                var defered = $q.defer();
			    var promise = defered.promise;

			    $http.post($rootScope.baseUrl+'index.php?r=device/update', input)
				.success(function(result) {
					defered.resolve(result);
				})
				.error(function(err) {
					defered.reject(err)
				});

               return promise;
        }

        function deleteDevice(input){
                var defered = $q.defer();
			    var promise = defered.promise;

			    $http.post($rootScope.baseUrl+'index.php?r=device/delete', input)
				.success(function(result) {
					defered.resolve(result);
				})
				.error(function(err) {
					defered.reject(err)
				});

               return promise;
        }

        function GenericCall(uri,input){

                var defered = $q.defer();
			    var promise = defered.promise;

			    $http.post(uri, input)
				.success(function(result) {
					defered.resolve(result);
				})
				.error(function(err) {
					defered.reject(err)
				});

               return promise;
        }

	});


text:
/* -*- Mode: C; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */

/* All files in libchula are Copyright (C) 2014 Alvaro Lopez Ortega.
 *
 *   Authors:
 *     * Alvaro Lopez Ortega <alvaro@alobbs.com>
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 *
 *     * Redistributions of source code must retain the above copyright
 *       notice, this list of conditions and the following disclaimer.
 *
 *     * Redistributions in binary form must reproduce the above
 *       copyright notice, this list of conditions and the following
 *       disclaimer in the documentation and/or other materials provided
 *       with the distribution.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
 * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
 * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
 * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
 * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */

#include "common-internal.h"
#include "logger_fd.h"
#include "util.h"

#include <time.h>
#include <errno.h>
#include <unistd.h>

static ret_t
do_render (void *self, chula_log_level_t level, chula_buffer_t *buf)
{
    size_t         re;
    time_t         now;
    struct tm      localtime;
    char           tmp[30];
    chula_buffer_t fake;

    UNUSED (self);

    /* Prefix */
    chula_log_get_level_buf (level, &fake);
    chula_buffer_prepend_str (buf, " ");
    chula_buffer_prepend_buf (buf, &fake);

    time (&now);
    chula_localtime (&now, &localtime);
    re = strftime (tmp, sizeof(tmp), "[%Y-%m-%d %H:%M:%S] ", &localtime);
    chula_buffer_prepend (buf, tmp, re);

    /* New line suffix */
    if (! chula_buffer_is_ending (buf, CHR_LF)) {
        chula_buffer_add_char (buf, CHR_LF);
    }

    return ret_ok;
}

static ret_t
do_log (void *self, chula_log_level_t level, chula_buffer_t *buf)
{
    int             re;
    chula_log_fd_t *log = CHULA_LOG_FD(self);

    UNUSED(level);

    do {
        re = write (log->fd, buf->buf, buf->len);
    } while ((re == -1) && (errno == EAGAIN));

    return ret_ok;
}

static ret_t
_fd_log (void *self, chula_log_level_t level, chula_buffer_t *buf)
{
    ret_t ret;

    ret = do_render (self, level, buf);
    if (unlikely (ret != ret_ok)) return ret;

    ret = do_log (self, level, buf);
    if (unlikely (ret != ret_ok)) return ret;

    return ret_ok;
}

static void
_fd_free (void *self)
{
    free (self);
}

ret_t
chula_log_fd_new (chula_log_fd_t **logger, int fd)
{
    CHULA_NEW_STRUCT (n, log_fd);

    n->fd              = fd;
    HPACK_LOG(n)->log  = _fd_log;
    HPACK_LOG(n)->free = _fd_free;

    *logger = n;
    return ret_ok;
}


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

namespace Simulator
{
    /// <summary>
    /// Information that the simulator maintains about each IP address for reporting purposes
    /// </summary>
    public class IpAddressDebugInfo
    {
        /// <summary>
        ///  Set if one or more benign users use this IP address to login
        /// </summary>
        public bool UsedByBenignUsers;

        /// <summary>
        /// Set if one or more attackers use this IP address either to guess legitimate user's passwords
        /// or to login to accounts the attackers control (e.g., to provide traffic that makes the IP look
        /// like it's in use by legitimate users.)
        /// </summary>
        public bool UsedByAttackers;

        /// <summary>
        /// Set if the IP is a proxy shared by many users
        /// </summary>
        public bool IsPartOfProxy;
    }

}


text:
weekly_roundup: true
title: "Roundup: requiring Ruby code, advent of code, the crypto-rich,
and things I learnt in 2018"
date: '2018-12-07 14:30:00 BST'
authors:
  - 'Neil van Beinum'
tags: # (Delete as appropriate)
- Culture

---

## A different way to require ruby code - [Murray S](/people#murray-steele)

https://github.com/ciconia/modulation/blob/master/README.md

In the past, the only solution for loading libraries in JavaScript was to just
include them in the page and hope there were no global clashes.  This is
obviously bad so many libraries appeared providing solutions to the problem.
They fought it out in the proving ground of popular opinion, and eventually we
got the ES6 module system and there was much rejoicing.  In ruby, we have
`require` and `load` statements, but every file we use with these is parsed,
run, and it's constants exposed in the global namespace.  This gem proposes an
alternative model that seems to me to be based on the ES6 module system.  Who
knows if something like this would ever become part of ruby itself, but the
ability to require only small parts of a library without worrying about
namespace clashes sounds really good to me.

## Advent of code 2018 - [Elena T](/people#elena-tanasoiu)

https://adventofcode.com/2018

Advent of code is live - one coding challenge every day until Christmas, if you're into that sort of thing.

## Four days trapped at sea with crypto's nouveau riche - [Elena T](/people#elena-tanasoiu)

https://breakermag.com/trapped-at-sea-with-cryptos-nouveau-riche/

How one person sets sail with the crypto-rich, a few hours after a bitcoin crash.

## 52 things I learned in 2018 - [Elena T](/people#elena-tanasoiu)

https://medium.com/fluxx-studio-notes/52-things-i-learned-in-2018-b07fc110d8e1

Surprisingly interesting read.

## Track of the Week - [Lawrence R](/people#lawrence-richards)

I've been binge watching Toast of London and hence the theme tune is in my head. It's pretty good and the video's a bit of a tear jerker.

<iframe width="560" height="315" src="https://www.youtube.com/embed/Rdqu-HObUbo" frameborder="0" allowfullscreen></iframe>

[Matt Berry – Take my hand](https://www.youtube.com/watch?v=Rdqu-HObUbo)