text:
using namespace std;

#include <openssl/dh.h>
#include <openssl/evp.h>
#include <openssl/hmac.h>
#include <openssl/ssl.h>

#include <srs_core_autofree.hpp>
#include <srs_kernel_buffer.hpp>
#include <srs_kernel_log.hpp>
#include <srs_kernel_utility.hpp>
#include <srs_rtmp_handshake.hpp>

static srs_error_t hmac_encode(const std::string& algo, const char* key, const int& key_length,
        const char* input, const int input_length, char* output, unsigned int& output_length)
{
    srs_error_t err = srs_success;

    const EVP_MD* engine = NULL;
    if (algo == "sha512") {
        engine = EVP_sha512();
    } else if(algo == "sha256") {
        engine = EVP_sha256();
    } else if(algo == "sha1") {
        engine = EVP_sha1();
    } else if(algo == "md5") {
        engine = EVP_md5();
    } else if(algo == "sha224") {
        engine = EVP_sha224();
    } else if(algo == "sha384") {
        engine = EVP_sha384();
    } else {
        return srs_error_new(ERROR_RTC_STUN, "unknown algo=%s", algo.c_str());
    }

    HMAC_CTX* ctx = HMAC_CTX_new();
    if (ctx == NULL) {
        return srs_error_new(ERROR_RTC_STUN, "hmac init faied");
    }

    if (HMAC_Init_ex(ctx, key, key_length, engine, NULL) < 0) {
        HMAC_CTX_free(ctx);
        return srs_error_new(ERROR_RTC_STUN, "hmac init faied");
    }

    if (HMAC_Update(ctx, (const unsigned char*)input, input_length) < 0) {
        HMAC_CTX_free(ctx);
        return srs_error_new(ERROR_RTC_STUN, "hmac update faied");
    }

    if (HMAC_Final(ctx, (unsigned char*)output, &output_length) < 0) {
        HMAC_CTX_free(ctx);
        return srs_error_new(ERROR_RTC_STUN, "hmac final faied");
    }

    HMAC_CTX_free(ctx);

    return err;
}

SrsStunPacket::SrsStunPacket()
{
    message_type = 0;
    local_ufrag = "";
    remote_ufrag = "";
    use_candidate = false;
    ice_controlled = false;
    ice_controlling = false;
    mapped_port = 0;
    mapped_address = 0;
}

SrsStunPacket::~SrsStunPacket()
{
}

bool SrsStunPacket::is_binding_request() const
{
    return message_type == BindingRequest;
}

bool SrsStunPacket::is_binding_response() const
{
    return message_type == BindingResponse;
}

uint16_t SrsStunPacket::get_message_type() const
{
    return message_type;
}

std::string SrsStunPacket::get_username() const
{
    return username;
}

std::string SrsStunPacket::get_local_ufrag() const
{
    return local_ufrag;
}

std::string SrsStunPacket::get_remote_ufrag() const
{
    return remote_ufrag;
}

std::string SrsStunPacket::get_transcation_id() const
{
    return transcation_id;
}

uint32_t SrsStunPacket::get_mapped_address() const
{
    return mapped_address;
}

uint16_t SrsStunPacket::get_mapped_port() const
{
    return mapped_port;
}

bool SrsStunPacket::get_ice_controlled() const
{
    return ice_controlled;
}

bool SrsStunPacket::get_ice_controlling() const
{
    return ice_controlling;
}

bool SrsStunPacket::get_use_candidate() const
{
    return use_candidate;
}

void SrsStunPacket::set_message_type(const uint16_t& m)
{
    message_type = m;
}

void SrsStunPacket::set_local_ufrag(const std::string& u)
{
    local_ufrag = u;
}

void SrsStunPacket::set_remote_ufrag(const std::string& u)
{
    remote_ufrag = u;
}

void SrsStunPacket::set_transcation_id(const std::string& t)
{
    transcation_id = t;
}

void SrsStunPacket::set_mapped_address(const uint32_t& addr)
{
    mapped_address = addr;
}

void SrsStunPacket::set_mapped_port(const uint32_t& port)
{
    mapped_port = port;
}

srs_error_t SrsStunPacket::decode(const char* buf, const int nb_buf)
{
    srs_error_t err = srs_success;

    SrsBuffer* stream = new SrsBuffer(const_cast<char*>(buf), nb_buf);
    SrsAutoFree(SrsBuffer, stream);

    if (stream->left() < 20) {
        return srs_error_new(ERROR_RTC_STUN, "invalid stun packet, size=%d", stream->size());
    }

    message_type = stream->read_2bytes();
    uint16_t message_len = stream->read_2bytes();
    string magic_cookie = stream->read_string(4);
    transcation_id = stream->read_string(12);

    if (nb_buf != 20 + message_len) {
        return srs_error_new(ERROR_RTC_STUN, "invalid stun packet, message_len=%d, nb_buf=%d", message_len, nb_buf);
    }

    while (stream->left() >= 4) {
        uint16_t type = stream->read_2bytes();
        uint16_t len = stream->read_2bytes();

        if (stream->left() < len) {
            return srs_error_new(ERROR_RTC_STUN, "invalid stun packet");
        }

        string val = stream->read_string(len);
        // padding
        if (len % 4 != 0) {
            stream->read_string(4 - (len % 4));
        }

        switch (type) {
            case Username: {
                username = val;
                size_t p = val.find(":");
                if (p != string::npos) {
                    local_ufrag = val.substr(0, p);
                    remote_ufrag = val.substr(p + 1);
                    srs_verbose("stun packet local_ufrag=%s, remote_ufrag=%s", local_ufrag.c_str(), remote_ufrag.c_str());
                }
                break;
            }

			case UseCandidate: {
                use_candidate = true;
                srs_verbose("stun use-candidate");
                break;
            }

            // @see: https://tools.ietf.org/html/draft-ietf-ice-rfc5245bis-00#section-5.1.2
			// One agent full, one lite:  The full agent MUST take the controlling
            // role, and the lite agent MUST take the controlled role.  The full
            // agent will form check lists, run the ICE state machines, and
            // generate connectivity checks.
			case IceControlled: {
                ice_controlled = true;
                srs_verbose("stun ice-controlled");
                break;
            }

			case IceControlling: {
                ice_controlling = true;
                srs_verbose("stun ice-controlling");
                break;
            }

            default: {
                srs_verbose("stun type=%u, no process", type);
                break;
            }
        }
    }

    return err;
}

srs_error_t SrsStunPacket::encode(const string& pwd, SrsBuffer* stream)
{
    if (is_binding_response()) {
        return encode_binding_response(pwd, stream);
    }

    return srs_error_new(ERROR_RTC_STUN, "unknown stun type=%d", get_message_type());
}

// FIXME: make this function easy to read
srs_error_t SrsStunPacket::encode_binding_response(const string& pwd, SrsBuffer* stream)
{
    srs_error_t err = srs_success;

    string property_username = encode_username();
    string mapped_address = encode_mapped_address();

    stream->write_2bytes(BindingResponse);
    stream->write_2bytes(property_username.size() + mapped_address.size());
    stream->write_4bytes(kStunMagicCookie);
    stream->write_string(transcation_id);
    stream->write_string(property_username);
    stream->write_string(mapped_address);

    stream->data()[2] = ((stream->pos() - 20 + 20 + 4) & 0x0000FF00) >> 8;
    stream->data()[3] = ((stream->pos() - 20 + 20 + 4) & 0x000000FF);

    char hmac_buf[20] = {0};
    unsigned int hmac_buf_len = 0;
    if ((err = hmac_encode("sha1", pwd.c_str(), pwd.size(), stream->data(), stream->pos(), hmac_buf, hmac_buf_len)) != srs_success) {
        return srs_error_wrap(err, "hmac encode failed");
    }

    string hmac = encode_hmac(hmac_buf, hmac_buf_len);

    stream->write_string(hmac);
    stream->data()[2] = ((stream->pos() - 20 + 8) & 0x0000FF00) >> 8;
    stream->data()[3] = ((stream->pos() - 20 + 8) & 0x000000FF);

    uint32_t crc32 = srs_crc32_ieee(stream->data(), stream->pos(), 0) ^ 0x5354554E;

    string fingerprint = encode_fingerprint(crc32);

    stream->write_string(fingerprint);

    stream->data()[2] = ((stream->pos() - 20) & 0x0000FF00) >> 8;
    stream->data()[3] = ((stream->pos() - 20) & 0x000000FF);

    return err;
}

string SrsStunPacket::encode_username()
{
    char buf[1460];
    SrsBuffer* stream = new SrsBuffer(buf, sizeof(buf));
    SrsAutoFree(SrsBuffer, stream);

    string username = remote_ufrag + ":" + local_ufrag;

    stream->write_2bytes(Username);
    stream->write_2bytes(username.size());
    stream->write_string(username);

    if (stream->pos() % 4 != 0) {
        static char padding[4] = {0};
        stream->write_bytes(padding, 4 - (stream->pos() % 4));
    }

    return string(stream->data(), stream->pos());
}

string SrsStunPacket::encode_mapped_address()
{
    char buf[1460];
    SrsBuffer* stream = new SrsBuffer(buf, sizeof(buf));
    SrsAutoFree(SrsBuffer, stream);

    stream->write_2bytes(XorMappedAddress);
    stream->write_2bytes(8);
    stream->write_1bytes(0); // ignore this bytes
    stream->write_1bytes(1); // ipv4 family
    stream->write_2bytes(mapped_port ^ (kStunMagicCookie >> 16));
    stream->write_4bytes(mapped_address ^ kStunMagicCookie);

    return string(stream->data(), stream->pos());
}

string SrsStunPacket::encode_hmac(char* hmac_buf, const int hmac_buf_len)
{
    char buf[1460];
    SrsBuffer* stream = new SrsBuffer(buf, sizeof(buf));
    SrsAutoFree(SrsBuffer, stream);

    stream->write_2bytes(MessageIntegrity);
    stream->write_2bytes(hmac_buf_len);
    stream->write_bytes(hmac_buf, hmac_buf_len);

    return string(stream->data(), stream->pos());
}

string SrsStunPacket::encode_fingerprint(uint32_t crc32)
{
    char buf[1460];
    SrsBuffer* stream = new SrsBuffer(buf, sizeof(buf));
    SrsAutoFree(SrsBuffer, stream);

    stream->write_2bytes(Fingerprint);
    stream->write_2bytes(4);
    stream->write_4bytes(crc32);

    return string(stream->data(), stream->pos());
}


text:
#pragma once

#include <stdint.h>
#include <sys/cdefs.h>

#include <string>

void backtrace_startup();
void backtrace_shutdown();
size_t backtrace_get(uintptr_t* frames, size_t frame_count);
void backtrace_log(const uintptr_t* frames, size_t frame_count);
std::string backtrace_string(const uintptr_t* frames, size_t frame_count);

redpajama_set_name: RedPajamaGithub


text:
class Hash
  def stringify_keys!
    keys.each do |key|
      self[key.to_s] = delete(key)
    end
    self
  end
end


text:
> * 原文链接 : [Welcome Snackbar, Goodbye Toast!](http://www.technotalkative.com/part-2-welcome-snackbar-goodbye-toast/)
* 原文作者 : [Paresh Mayani](http://en.gravatar.com/pareshnmayani)
* [译文出自 :  开发技术前线 www.devtf.cn](http://www.devtf.cn)
* 译者 : [objectlife](https://github.com/objectlife)
* 校对者: [Mr.Simple](https://github.com/bboyfeiyu)
* 状态 : 完成

欢迎来到Android design support library系列教程第二部分,第一部分我们讨论了[Floating action button](http://www.technotalkative.com/part-1-floating-action-button/)的一些attributes 和 常见issues。

今天我们讨论一下另一个组件"Snackbar".

Welcome Snackbar, Goodbye Toast!

> "Providing lightweight, quick feedback about an operation is a perfect opportunity to use a snackbar."

Snackbar是design support library中另一个组件,使用Snackbar我们可以在屏幕底部(大多时候)快速弹出消息,它和Toast非常相似,但是它更灵活一些。

* 当它显示一段时间后或用户与屏幕交互时它会自动消失。
* 可以自定义action-可选操作。
* swiping it off the screen可以让FAB消失
* 它是context sensitive message(自己理解吧),所以这些消息是UI screen的一部分并且它是显示在所有屏幕其它元素之上(屏幕最顶层),并不是像Toast一样覆盖在屏幕上。
* 同一时间只能显示一个snackbar。

Snackbar基本上继承了和Toast一样的方法和属性,例如LENGTH_LONG 和 LENGTH_SHORT用于设置显示时长。

##如何使用

我们看一下如何使用:

```java

Snackbar.make(view, message, duration)
       .setAction(action message, click listener)
       .show();

```

###方法:

* *make()*  – 生成Snackbar消息
* *setAction()*  – 设置action
* *make()*  – 显示Snackbar消息

###属性:

* make()方法的第一个参数是一个view, snackbar会试着寻找一个父view来hold这个view. Snackbar将遍历整个view tree 来寻找一个合适的父view,它可能是一个coordinatorLayout也可能是window decor's content view,随便哪一个都行。
* 正如上面所提到,duration参数和Toast中的duration参数类似,只能是LENGTH_SHORT 或 LENGTH_LONG,不能是其它任何随机数。

###示例:

```java

Snackbar.make(rootlayout, "Hello SnackBar!", Snackbar.LENGTH_SHORT)
       .setAction("Undo", new View.OnClickListener() {
           @Override
           public void onClick(View v) {
               // Perform anything for the action selected
           }
       })
       .show();

```

部局文件中rootlayout是framelayout并且添加了FAB(Floating action button),看一下FAB示例:

点击FAB查看结果:

![](http://www.technotalkative.com/wp-content/uploads/2015/06/Snackbar-framelayout1.gif)

程序没问题,但是对于用户体验来说并不太好,它应该向上移一些,如下图所示:

> Having a CoordinatorLayout in your view hierarchy allows Snackbar to enable certain features, such as swipe-to-dismiss and automatically moving of widgets like FloatingActionButton.

我们在该系列文章的下一部分讨论CoordinatorLayout。

![](http://www.technotalkative.com/wp-content/uploads/2015/06/Snackbar-with-CoordinatorLayout1.gif)

###配置Snackbar可选操作

我们可以使用额外的可选操作来配置snackbar,比如*setActionTextColor* 和 *setDuration*:

```java

Snackbar.make(rootlayout, "Hello SnackBar!", Snackbar.LENGTH_SHORT)
       .setAction("Undo", new View.OnClickListener() {
           @Override
           public void onClick(View v) {
               // Perform anything for the action selected
           }
       })
       .setActionTextColor(R.color.material_blue)
       .setDuration(4000).show();

```

下载示例代码:[https://github.com/PareshMayani/DesignSupportLibraryExamples](https://github.com/PareshMayani/DesignSupportLibraryExamples)

参考文档:
[https://developer.android.com/reference/android/support/design/widget/Snackbar.html](https://developer.android.com/reference/android/support/design/widget/Snackbar.html)

###总结

在这部分文章中,我们讨论了Snackbar,它和TOAST很相似,但是它更灵活一些。Snackbar中可以定义action,当用户与屏幕交互时或者显示一段时间后会自动消失。

通过 CoordinatorLayout我们可以看到更多的effects 和 behaviours,在该系列文章中后续会讨论它。


text:
<?php
/**
 * Jetpack Compatibility File.
 *
 * @link https://jetpack.com/
 *
 * @package crraftunderboot
 */
/**
 * Jetpack setup function.
 *
 * See: https://jetpack.com/support/infinite-scroll/
 * See: https://jetpack.com/support/responsive-videos/
 */
function crraftunderboot_jetpack_setup() {
	// Add theme support for Infinite Scroll.
	add_theme_support( 'infinite-scroll', array(
		'container' => 'main',
		'render'    => 'crraftunderboot_infinite_scroll_render',
		'footer'    => 'page',
	) );
	// Add theme support for Responsive Videos.
	add_theme_support( 'jetpack-responsive-videos' );
}
add_action( 'after_setup_theme', 'crraftunderboot_jetpack_setup' );
/**
 * Custom render function for Infinite Scroll.
 */
function crraftunderboot_infinite_scroll_render() {
	while ( have_posts() ) {
		the_post();
		if ( is_search() ) :
		    get_template_part( 'template-parts/content', 'search' );
		else :
		    get_template_part( 'template-parts/content', get_post_format() );
		endif;
	}
}


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

namespace Boolean_Variable
{
    class Program
    {
        static void Main(string[] args)
        {
            string boolean = Console.ReadLine();

            string yesOrNo = Convert.ToBoolean(boolean) ? "Yes" : "No";

            Console.WriteLine(yesOrNo);
        }
    }
}


text:
class Unavailability
  attr_accessor :record, :type
  def initialize record
    @record = record
    @type = record.class.to_s.downcase.to_sym
  end
end


text:
package org.tinyesb.orchestration;

/**
 * Created by Neranjana Karunaratne on 21/05/2017.
 */
public class ExecutionException extends Exception {

    public ExecutionException() {
    }

    public ExecutionException(String message) {
        super(message);
    }

    public ExecutionException(String message, Throwable cause) {
        super(message, cause);
    }

    public ExecutionException(Throwable cause) {
        super(cause);
    }

    public ExecutionException(String message, Throwable cause, boolean enableSuppression, boolean writableStackTrace) {
        super(message, cause, enableSuppression, writableStackTrace);
    }
}


text:
/*Write a program that extracts from a given text all dates that match the format DD.MM.YYYY. Display them in the standard date format for Canada.*/

using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;

class ExtractsDates
{
    static void Main()
    {
        Console.WriteLine("Extracting all dates that match the format DD.MM.YYYY");
        Console.Write("Enter a text: ");
        string s = Console.ReadLine();

        DateTime date;
        foreach (Match item in Regex.Matches(s, @"\b\d{2}.\d{2}.\d{4}\b"))
        {
            if (DateTime.TryParseExact(item.Value, "dd.MM.yyyy", CultureInfo.InvariantCulture, DateTimeStyles.None, out date))
            {
                Console.WriteLine(date.ToString(CultureInfo.GetCultureInfo("en-CA").DateTimeFormat.ShortDatePattern));
            }
        }

        //string buildS = " " + s + " ";
        //char[] chars = new char[] { ' ', ',', '.', '!', '?' };
        //string buildSub;
        //for (int i = 0; i < buildS.Length; i++)
        //{
        //    int firstIndexDot = buildS.IndexOf(".", i);
        //    if (firstIndexDot != -1)
        //    {
        //        int secondIndexDot = buildS.LastIndexOf(" ", indexAt);
        //        //Console.WriteLine(leftSpace);
        //        int rightSpace = buildS.IndexOf(" ", indexAt);
        //        buildSub = buildS.Substring(leftSpace, rightSpace - leftSpace).Trim(chars);
        //        if (leftSpace < indexAt - 1 && indexAt + 3 < rightSpace && buildSub.LastIndexOf(".", buildSub.Length - 3, 3) != -1)
        //        {
        //            Console.WriteLine(buildSub);
        //        }
        //        i = rightSpace;
        //    }

        //}

    }
}


text:
/**
 *
 */
package com.ms.bean;

/**
 * @author Amit.Agnihotri
 *
 */
public class PaymentFormBean extends FormBean{

	private Integer paymentId;

	private String feeSlipIds;
	private Integer studentId;
	private String amount;
	private String disAmount;
	private Byte paymentType;
	private String chkDDNo;
	private String bankName;
	private String issueDate;
	private String challanNum;
	private String depositDate;
	private String comment;

	private Integer feeSummaryId ;
	private String monthIds ;
	private String quarterlyIds ;
	private String halsyrlyIds;
	private String anuallyIds;

	/**
	 * @return the paymentId
	 */
	public Integer getPaymentId() {
		return paymentId;
	}
	/**
	 * @param paymentId the paymentId to set
	 */
	public void setPaymentId(Integer paymentId) {
		this.paymentId = paymentId;
	}
	/**
	 * @return the amount
	 */
	public String getAmount() {
		return amount;
	}
	/**
	 * @param amount the amount to set
	 */
	public void setAmount(String amount) {
		this.amount = amount;
	}
	/**
	 * @return the disAmount
	 */
	public String getDisAmount() {
		return disAmount;
	}
	/**
	 * @param disAmount the disAmount to set
	 */
	public void setDisAmount(String disAmount) {
		this.disAmount = disAmount;
	}

	/**
	 * @return the feeSlipIds
	 */
	public String getFeeSlipIds() {
		return feeSlipIds;
	}
	/**
	 * @param feeSlipIds the feeSlipIds to set
	 */
	public void setFeeSlipIds(String feeSlipIds) {
		this.feeSlipIds = feeSlipIds;
	}
	/**
	 * @return the chkDDNo
	 */
	public String getChkDDNo() {
		return chkDDNo;
	}
	/**
	 * @param chkDDNo the chkDDNo to set
	 */
	public void setChkDDNo(String chkDDNo) {
		this.chkDDNo = chkDDNo;
	}
	/**
	 * @return the bankName
	 */
	public String getBankName() {
		return bankName;
	}
	/**
	 * @param bankName the bankName to set
	 */
	public void setBankName(String bankName) {
		this.bankName = bankName;
	}
	/**
	 * @return the issueDate
	 */
	public String getIssueDate() {
		return issueDate;
	}
	/**
	 * @param issueDate the issueDate to set
	 */
	public void setIssueDate(String issueDate) {
		this.issueDate = issueDate;
	}
	/**
	 * @return the challanNum
	 */
	public String getChallanNum() {
		return challanNum;
	}
	/**
	 * @param challanNum the challanNum to set
	 */
	public void setChallanNum(String challanNum) {
		this.challanNum = challanNum;
	}
	/**
	 * @return the depositDate
	 */
	public String getDepositDate() {
		return depositDate;
	}
	/**
	 * @param depositDate the depositDate to set
	 */
	public void setDepositDate(String depositDate) {
		this.depositDate = depositDate;
	}

	/**
	 * @return the monthIds
	 */
	public String getMonthIds() {
		return monthIds;
	}
	/**
	 * @param monthIds the monthIds to set
	 */
	public void setMonthIds(String monthIds) {
		this.monthIds = monthIds;
	}
	/**
	 * @return the quarterlyIds
	 */
	public String getQuarterlyIds() {
		return quarterlyIds;
	}
	/**
	 * @param quarterlyIds the quarterlyIds to set
	 */
	public void setQuarterlyIds(String quarterlyIds) {
		this.quarterlyIds = quarterlyIds;
	}
	/**
	 * @return the halsyrlyIds
	 */
	public String getHalsyrlyIds() {
		return halsyrlyIds;
	}
	/**
	 * @param halsyrlyIds the halsyrlyIds to set
	 */
	public void setHalsyrlyIds(String halsyrlyIds) {
		this.halsyrlyIds = halsyrlyIds;
	}
	/**
	 * @return the anuallyIds
	 */
	public String getAnuallyIds() {
		return anuallyIds;
	}
	/**
	 * @param anuallyIds the anuallyIds to set
	 */
	public void setAnuallyIds(String anuallyIds) {
		this.anuallyIds = anuallyIds;
	}
	/**
	 * @return the feeSummaryId
	 */
	public Integer getFeeSummaryId() {
		return feeSummaryId;
	}
	/**
	 * @param feeSummaryId the feeSummaryId to set
	 */
	public void setFeeSummaryId(Integer feeSummaryId) {
		this.feeSummaryId = feeSummaryId;
	}
	/**
	 * @return the studentId
	 */
	public Integer getStudentId() {
		return studentId;
	}
	/**
	 * @param studentId the studentId to set
	 */
	public void setStudentId(Integer studentId) {
		this.studentId = studentId;
	}
	/**
	 * @return the paymentType
	 */
	public Byte getPaymentType() {
		return paymentType;
	}
	/**
	 * @param paymentType the paymentType to set
	 */
	public void setPaymentType(Byte paymentType) {
		this.paymentType = paymentType;
	}
	/**
	 * @return the comment
	 */
	public String getComment() {
		return comment;
	}
	/**
	 * @param comment the comment to set
	 */
	public void setComment(String comment) {
		this.comment = comment;
	}

}


text:
layout: index
description: Victoria BC's programmers whisky society. Connecting technical people through whisky to share their passions and pick up new technologies.
---

{ Who Is Whisky Oriented Development? }

  We're people who work in the tech industry in Victoria, Canada.  We organize periodic whisky tasting events that seat 30 people.  In each tasting a mix of newcomers and regulars get a chance to sample some fine whisky, learn a little bit about it, and socialize.  We're also a Slack channel (new member signup) where people hang out everyday.

  The organizers are Graham Baradoy, Jeffery Grajkowski, Hez Ronningen and Jamie Starke.

{ Who Can Come? }

  Anyone in tech who wants to have nerdy conversations and drink whisky!  If you can sit in a chair and drink liquid then we can teach you the rest.  Whisky is a good social lubricant and it's easy to make friends in the relaxed atmosphere.

{ How Can I Get In Touch? }

  All emails can go to contact@whiskydev.com.

{ Our Latest Announcement }

  {% assign post = site.posts.first %}

    {{ post.date | date_to_string }}
    {{ post.title }}


text:
import requests
import time
import random
import os
import re
try:
    from urllib.parse import urljoin
except ImportError:
    from urlparse import urljoin

try:
    from lxml import html
    from lxml.html.defs import link_attrs as html_link_attrs
except ImportError:
    html = None

try:
    import cssselect
except ImportError:
    cssselect = None

from . import loader, configuration, util
from .util import (getPageContent, makeSequence, get_system_uid, urlopen,
        getDirname, unescape, tagre, normaliseURL, prettyMatcherList)
from .comic import ComicStrip
from .output import out
from .events import getHandler

class Scraper(object):
    '''Base class for all comic scraper, but without a specific scrape implementation.'''

    # The URL for the comic strip
    url = None

    # A string that is interpolated with the strip index to yield the URL for a particular strip.
    stripUrl = None

    # Stop search for previous URLs at this URL
    firstStripUrl = None

    # if more than one image per URL is expected
    multipleImagesPerStrip = False

    # set to False if previous URLs do not match the strip URL (ie. because of redirects)
    prevUrlMatchesStripUrl = True

    # set to True if this comic contains adult content
    adult = False

    # set to True if this comic will not get updated anymore
    endOfLife = False

    # langauge of the comic (two-letter ISO 639-1 code)
    lang = 'en'

    # an expression that will locate the URL for the previous strip in a page
    # this can also be a list or tuple
    prevSearch = None

    # an expression that will locate the strip image URLs strip in a page
    # this can also be a list or tuple
    imageSearch = None

    # an expression to store a text together with the image
    # sometimes comic strips have additional text info for each comic
    textSearch = None

    # Is the additional text required or optional?  When it is required (the
    # default), you see an error message whenever a comic page is encountered
    # that does not have the text
    textOptional = False

    # usually the index format help
    help = ''

    # HTTP session storing cookies
    session = requests.session()

    def __init__(self, indexes=None):
        """Initialize internal variables."""
        self.urls = set()
        if indexes:
            self.indexes = tuple(sorted(indexes))
        else:
            self.indexes = tuple()
        self.skippedUrls = set()
        self.hitFirstStripUrl = False

    def __cmp__(self, other):
        """Compare scraper by name and index list."""
        if not isinstance(other, Scraper):
            return 1
        # first, order by name
        d = cmp(self.getName(), other.getName())
        if d != 0:
            return d
        # then by indexes
        return cmp(self.indexes, other.indexes)

    def __hash__(self):
        """Get hash value from name and index list."""
        return hash((self.getName(), self.indexes))

    def shouldSkipUrl(self, url, data):
        """Determine if search for images in given URL should be skipped."""
        return False

    def getComicStrip(self, url, data):
        """Get comic strip downloader for given URL and data."""
        imageUrls = self.fetchUrls(url, data, self.imageSearch)
        # map modifier function on image URLs
        imageUrls = [self.imageUrlModifier(x, data) for x in imageUrls]
        # remove duplicate URLs
        imageUrls = set(imageUrls)
        if len(imageUrls) > 1 and not self.multipleImagesPerStrip:
            out.warn(u"Found %d images instead of 1 at %s with expressions %s" % (len(imageUrls), url, prettyMatcherList(self.imageSearch)))
            image = sorted(imageUrls)[0]
            out.warn(u"Choosing image %s" % image)
            imageUrls = (image,)
        elif not imageUrls:
            out.warn(u"Found no images at %s with expressions %s" % (url, prettyMatcherList(self.imageSearch)))
        if self.textSearch:
            text = self.fetchText(url, data, self.textSearch, optional=self.textOptional)
        else:
            text = None
        return ComicStrip(self.getName(), url, imageUrls, self.namer, self.session, text=text)

    def getStrips(self, maxstrips=None):
        """Get comic strips."""
        if maxstrips:
            word = u"strip" if maxstrips == 1 else "strips"
            msg = u'Retrieving %d %s' % (maxstrips, word)
        else:
            msg = u'Retrieving all strips'
        if self.indexes:
            if len(self.indexes) == 1:
                msg += u" for index %s" % self.indexes[0]
            else:
                msg += u" for indexes %s" % self.indexes
            # Always call starter() since it might initialize cookies.
            # See for example Oglaf comic.
            self.starter()
            urls = [self.getIndexStripUrl(index) for index in self.indexes]
        else:
            urls = [self.getLatestUrl()]
        if self.adult:
            msg += u" (including adult content)"
        out.info(msg)
        for url in urls:
            for strip in self.getStripsFor(url, maxstrips):
                yield strip

    def getStripsFor(self, url, maxstrips):
        """Get comic strips for an URL. If maxstrips is a positive number, stop after
        retrieving the given number of strips."""
        self.hitFirstStripUrl = False
        seen_urls = set()
        while url:
            out.info(u'Get strip URL %s' % url, level=1)
            data = self.getPage(url)
            if self.shouldSkipUrl(url, data):
                out.info(u'Skipping URL %s' % url)
                self.skippedUrls.add(url)
            else:
                try:
                    yield self.getComicStrip(url, data)
                except ValueError as msg:
                    # image not found
                    out.exception(msg)
            if self.firstStripUrl == url:
                out.debug(u"Stop at first URL %s" % url)
                self.hitFirstStripUrl = True
                break
            if maxstrips is not None:
                maxstrips -= 1
                if maxstrips <= 0:
                    break
            prevUrl = self.getPrevUrl(url, data)
            seen_urls.add(url)
            if prevUrl in seen_urls:
                # avoid recursive URL loops
                out.warn(u"Already seen previous URL %r" % prevUrl)
                break
            url = prevUrl
            if url:
                # wait up to 2 seconds for next URL
                time.sleep(1.0 + random.random())

    def getPrevUrl(self, url, data):
        """Find previous URL."""
        prevUrl = None
        if self.prevSearch:
            try:
                prevUrl = self.fetchUrl(url, data, self.prevSearch)
            except ValueError as msg:
                # assume there is no previous URL, but print a warning
                out.warn(u"%s Assuming no previous comic strips exist." % msg)
            else:
                prevUrl = self.prevUrlModifier(prevUrl)
                out.debug(u"Found previous URL %s" % prevUrl)
                getHandler().comicPageLink(self.getName(), url, prevUrl)
        return prevUrl

    def getIndexStripUrl(self, index):
        """Get comic strip URL from index."""
        return self.stripUrl % index

    @classmethod
    def getName(cls):
        """Get scraper name."""
        if hasattr(cls, 'name'):
            return cls.name
        return cls.__name__

    @classmethod
    def starter(cls):
        """Get starter URL from where to scrape comic strips."""
        return cls.url

    @classmethod
    def namer(cls, imageUrl, pageUrl):
        """Return filename for given image and page URL."""
        return None

    @classmethod
    def prevUrlModifier(cls, prevUrl):
        """Optional modification of parsed previous URLs. Useful if
        there are domain redirects. The default implementation does
        not modify the URL.
        """
        return prevUrl

    @classmethod
    def imageUrlModifier(cls, imageUrl, data):
        """Optional modification of parsed image URLs. Useful if the URL
        needs to be fixed before usage. The default implementation does
        not modify the URL. The given data is the URL page data.
        """
        return imageUrl

    def getLatestUrl(self):
        """Get starter URL from where to scrape comic strips."""
        return self.starter()

    @classmethod
    def vote(cls):
        """Cast a public vote for this comic."""
        url = configuration.VoteUrl + 'count/'
        uid = get_system_uid()
        data = {"name": cls.getName().replace('/', '_'), "uid": uid}
        page = urlopen(url, cls.session, data=data)
        return page.text

    def getCompleteFile(self, basepath):
        """Get filename indicating all comics are downloaded."""
        dirname = getDirname(self.getName())
        return os.path.join(basepath, dirname, "complete.txt")

    def isComplete(self, basepath):
        """Check if all comics are downloaded."""
        return os.path.isfile(self.getCompleteFile(basepath))

    def setComplete(self, basepath):
        """Set complete flag for this comic, ie. all comics are downloaded."""
        if self.endOfLife:
            filename = self.getCompleteFile(basepath)
            if not os.path.exists(filename):
                with open(filename, 'w') as f:
                    f.write('All comics should be downloaded here.')

    @classmethod
    def getPage(cls, url):
        """
        Fetch a page and return the opaque repesentation for the data parameter
        of fetchUrls and fetchText.

        Implementation notes: While this base class does not restrict how the
        returned data is structured, subclasses (specific scrapers) should specify
        how this data works, since the stracture is passed into different methods
        which can be defined by comic modules and these methods should be able to
        use the data if they so desire... (Affected methods: shouldSkipUrl,
        imageUrlModifier)
        """
        raise ValueError("No implementation for getPage!")

    @classmethod
    def fetchUrls(cls, url, data, urlSearch):
        raise ValueError("No implementation for fetchUrls!")

    @classmethod
    def fetchUrl(cls, url, data, urlSearch):
        return cls.fetchUrls(url, data, urlSearch)[0]

    @classmethod
    def fetchText(cls, url, data, textSearch, optional):
        raise ValueError("No implementation for fetchText!")

    @classmethod
    def getDisabledReasons(cls):
        """
        Get a dict of reasons why this comic module is disabled. The key is a
        short (unique) identifier, the value is a string explaining why the
        module is deactivated. If the module is not disabled, just return an
        empty dict.
        """
        return {}

class _BasicScraper(Scraper):
    """
    Scraper base class that matches regular expressions against HTML pages.

    Subclasses of this scraper should use compiled regular expressions as
    values for prevSearch, imageSearch and textSearch.

    Implementation note: The return value of getPage is a tuple: the first
    element is the raw HTML page text, the second element is the base URL (if
    any).
    """

    BASE_SEARCH = re.compile(tagre("base", "href", '([^"]*)'))

    @classmethod
    def getPage(cls, url):
        content = getPageContent(url, cls.session)
        # determine base URL
        baseUrl = None
        match = cls.BASE_SEARCH.search(content)
        if match:
            baseUrl = match.group(1)
        else:
            baseUrl = url
        return (content, baseUrl)

    @classmethod
    def fetchUrls(cls, url, data, urlSearch):
        """Search all entries for given URL pattern(s) in a HTML page."""
        searchUrls = []
        searches = makeSequence(urlSearch)
        for search in searches:
            for match in search.finditer(data[0]):
                searchUrl = match.group(1)
                if not searchUrl:
                    raise ValueError("Pattern %s matched empty URL at %s." % (search.pattern, url))
                out.debug(u'matched URL %r with pattern %s' % (searchUrl, search.pattern))
                searchUrls.append(normaliseURL(urljoin(data[1], searchUrl)))
            if searchUrls:
                # do not search other links if one pattern matched
                break
        if not searchUrls:
            patterns = [x.pattern for x in searches]
            raise ValueError("Patterns %s not found at URL %s." % (patterns, url))
        return searchUrls

    @classmethod
    def fetchText(cls, url, data, textSearch, optional):
        """Search text entry for given text pattern in a HTML page."""
        if textSearch:
            match = textSearch.search(data[0])
            if match:
                text = match.group(1)
                out.debug(u'matched text %r with pattern %s' % (text, textSearch.pattern))
                return unescape(text).strip()
            if optional:
                return None
            else:
                raise ValueError("Pattern %s not found at URL %s." % (textSearch.pattern, url))
        else:
            return None

class _ParserScraper(Scraper):
    """
    Scraper base class that uses a HTML parser and XPath expressions.

    All links are resolved before XPath searches are applied, so all URLs are
    absolute!

    Subclasses of this class should use XPath expressions as values for
    prevSearch, imageSearch and textSearch. When the XPath directly selects an
    attribute, it is used as the output.

    All those searches try to do something intelligent when they match a
    complete HTML Element: prevSearch and imageSearch try to find a "link
    attribute" and use that as URL. textSearch strips all tags from the content
    of the HTML element and returns that.
    """

    # Switch between CSS and XPath selectors for this class. Since CSS needs
    # another Python module, XPath is the default for now.
    css = False

    @classmethod
    def getPage(cls, url):
        tree = html.document_fromstring(getPageContent(url, cls.session))
        tree.make_links_absolute(url)
        return tree

    @classmethod
    def fetchUrls(cls, url, data, urlSearch):
        """Search all entries for given XPath in a HTML page."""
        searchUrls = []
        if cls.css:
            searchFun = data.cssselect
        else:
            searchFun = data.xpath
        searches = makeSequence(urlSearch)
        for search in searches:
            for match in searchFun(search):
                try:
                    for attrib in html_link_attrs:
                        if attrib in match.attrib:
                            searchUrls.append(match.get(attrib))
                except AttributeError:
                    searchUrls.append(str(match))
            if searchUrls:
                # do not search other links if one pattern matched
                break
        if not searchUrls:
            raise ValueError("XPath %s not found at URL %s." % (searches, url))
        return searchUrls

    @classmethod
    def fetchText(cls, url, data, textSearch, optional):
        """Search text entry for given text XPath in a HTML page."""
        if textSearch:
            text = ''
            for match in data.xpath(textSearch):
                try:
                    text += ' ' + match.text_content()
                except AttributeError:
                    text += ' ' + unicode(match)
            if text.strip() == '':
                if optional:
                    return None
                else:
                    raise ValueError("XPath %s did not match anything at URL %s." % (textSearch, url))
            out.debug(u'Matched text %r with XPath %s' % (text, textSearch))
            return unescape(text).strip()
        else:
            return None

    @classmethod
    def getDisabledReasons(cls):
        res = {}
        if cls.css and cssselect is None:
            res['css'] = u"This module needs the cssselect (python-cssselect) python module which is not installed."
        if html is None:
            res['lxml'] = u"This module needs the lxml (python-lxml) python module which is not installed."
        return res

def find_scraperclasses(comic, multiple_allowed=False):
    """Get a list comic scraper classes. Can return more than one entries if
    multiple_allowed is True, else it raises a ValueError if multiple
    modules match. The match is a case insensitive substring search."""
    if not comic:
        raise ValueError("empty comic name")
    candidates = []
    cname = comic.lower()
    for scraperclass in get_scraperclasses():
        lname = scraperclass.getName().lower()
        if lname == cname:
            # perfect match
            if not multiple_allowed:
                return [scraperclass]
            else:
                candidates.append(scraperclass)
        elif cname in lname:
            candidates.append(scraperclass)
    if len(candidates) > 1 and not multiple_allowed:
        comics = ", ".join(x.getName() for x in candidates)
        raise ValueError('multiple comics found: %s' % comics)
    elif not candidates:
        raise ValueError('comic %r not found' % comic)
    return candidates

_scraperclasses = None
def get_scraperclasses():
    """Find all comic scraper classes in the plugins directory.
    The result is cached.
    @return: list of Scraper classes
    @rtype: list of Scraper
    """
    global _scraperclasses
    if _scraperclasses is None:
        out.debug(u"Loading comic modules...")
        modules = loader.get_modules('plugins')
        plugins = loader.get_plugins(modules, Scraper)
        _scraperclasses = list(plugins)
        check_scrapers()
        out.debug(u"... %d modules loaded." % len(_scraperclasses))
    return _scraperclasses

def check_scrapers():
    """Check for duplicate scraper class names."""
    d = {}
    for scraperclass in _scraperclasses:
        name = scraperclass.getName().lower()
        if name in d:
            name1 = scraperclass.getName()
            name2 = d[name].getName()
            raise ValueError('duplicate scrapers %s and %s found' % (name1, name2))
        d[name] = scraperclass

def make_scraper(classname, scraperType = _BasicScraper, **attributes):
    """Make a new scraper class with given name and attributes."""
    return type(classname, (scraperType,), attributes)


text:
<?php

namespace App\Controllers;
use View;
use App\Controllers\AdminController;

/**
 * Description of MenuController
 *
 * @author ajis
 */
class MenuController extends AdminController {
   public function index() {

        return View::make('menu.index');
    }

}


text:
$(document).ready(function () {
  init_chart();
  socket.emit('get_all_data',"");
});


text:
from Adafruit_I2C import Adafruit_I2C
from time import sleep

class Adafruit_CharLCDPlate(Adafruit_I2C):

    # ----------------------------------------------------------------------
    # Constants

    # Port expander registers
    MCP23017_IOCON_BANK0    = 0x0A  # IOCON when Bank 0 active
    MCP23017_IOCON_BANK1    = 0x15  # IOCON when Bank 1 active
    # These are register addresses when in Bank 1 only:
    MCP23017_GPIOA          = 0x09
    MCP23017_IODIRB         = 0x10
    MCP23017_GPIOB          = 0x19

    # Port expander input pin definitions
    SELECT                  = 0
    RIGHT                   = 1
    DOWN                    = 2
    UP                      = 3
    LEFT                    = 4

    # LED colors
    OFF                     = 0x00
    RED                     = 0x01
    GREEN                   = 0x02
    BLUE                    = 0x04
    YELLOW                  = RED + GREEN
    TEAL                    = GREEN + BLUE
    VIOLET                  = RED + BLUE
    WHITE                   = RED + GREEN + BLUE
    ON                      = RED + GREEN + BLUE

    # LCD Commands
    LCD_CLEARDISPLAY        = 0x01
    LCD_RETURNHOME          = 0x02
    LCD_ENTRYMODESET        = 0x04
    LCD_DISPLAYCONTROL      = 0x08
    LCD_CURSORSHIFT         = 0x10
    LCD_FUNCTIONSET         = 0x20
    LCD_SETCGRAMADDR        = 0x40
    LCD_SETDDRAMADDR        = 0x80

    # Flags for display on/off control
    LCD_DISPLAYON           = 0x04
    LCD_DISPLAYOFF          = 0x00
    LCD_CURSORON            = 0x02
    LCD_CURSOROFF           = 0x00
    LCD_BLINKON             = 0x01
    LCD_BLINKOFF            = 0x00

    # Flags for display entry mode
    LCD_ENTRYRIGHT          = 0x00
    LCD_ENTRYLEFT           = 0x02
    LCD_ENTRYSHIFTINCREMENT = 0x01
    LCD_ENTRYSHIFTDECREMENT = 0x00

    # Flags for display/cursor shift
    LCD_DISPLAYMOVE = 0x08
    LCD_CURSORMOVE  = 0x00
    LCD_MOVERIGHT   = 0x04
    LCD_MOVELEFT    = 0x00

    # ----------------------------------------------------------------------
    # Constructor

    def __init__(self, busnum=-1, addr=0x20, debug=False):

        self.i2c = Adafruit_I2C(addr, busnum, debug)

        # I2C is relatively slow.  MCP output port states are cached
        # so we don't need to constantly poll-and-change bit states.
        self.porta, self.portb, self.ddrb = 0, 0, 0b00010000

        # Set MCP23017 IOCON register to Bank 0 with sequential operation.
        # If chip is already set for Bank 0, this will just write to OLATB,
        # which won't seriously bother anything on the plate right now
        # (blue backlight LED will come on, but that's done in the next
        # step anyway).
        self.i2c.bus.write_byte_data(
          self.i2c.address, self.MCP23017_IOCON_BANK1, 0)

        # Brute force reload ALL registers to known state.  This also
        # sets up all the input pins, pull-ups, etc. for the Pi Plate.
        self.i2c.bus.write_i2c_block_data(
          self.i2c.address, 0,
          [ 0b00111111,   # IODIRA    R+G LEDs=outputs, buttons=inputs
            self.ddrb ,   # IODIRB    LCD D7=input, Blue LED=output
            0b00111111,   # IPOLA     Invert polarity on button inputs
            0b00000000,   # IPOLB
            0b00000000,   # GPINTENA  Disable interrupt-on-change
            0b00000000,   # GPINTENB
            0b00000000,   # DEFVALA
            0b00000000,   # DEFVALB
            0b00000000,   # INTCONA
            0b00000000,   # INTCONB
            0b00000000,   # IOCON
            0b00000000,   # IOCON
            0b00111111,   # GPPUA     Enable pull-ups on buttons
            0b00000000,   # GPPUB
            0b00000000,   # INTFA
            0b00000000,   # INTFB
            0b00000000,   # INTCAPA
            0b00000000,   # INTCAPB
            self.porta,   # GPIOA
            self.portb,   # GPIOB
            self.porta,   # OLATA     0 on all outputs; side effect of
            self.portb ]) # OLATB     turning on R+G+B backlight LEDs.

        # Switch to Bank 1 and disable sequential operation.
        # From this point forward, the register addresses do NOT match
        # the list immediately above.  Instead, use the constants defined
        # at the start of the class.  Also, the address register will no
        # longer increment automatically after this -- multi-byte
        # operations must be broken down into single-byte calls.
        self.i2c.bus.write_byte_data(
          self.i2c.address, self.MCP23017_IOCON_BANK0, 0b10100000)

        self.displayshift   = (self.LCD_CURSORMOVE |
                               self.LCD_MOVERIGHT)
        self.displaymode    = (self.LCD_ENTRYLEFT |
                               self.LCD_ENTRYSHIFTDECREMENT)
        self.displaycontrol = (self.LCD_DISPLAYON |
                               self.LCD_CURSOROFF |
                               self.LCD_BLINKOFF)

        self.write(0x33) # Init
        self.write(0x32) # Init
        self.write(0x28) # 2 line 5x8 matrix
        self.write(self.LCD_CLEARDISPLAY)
        self.write(self.LCD_CURSORSHIFT    | self.displayshift)
        self.write(self.LCD_ENTRYMODESET   | self.displaymode)
        self.write(self.LCD_DISPLAYCONTROL | self.displaycontrol)
        self.write(self.LCD_RETURNHOME)

    # ----------------------------------------------------------------------
    # Write operations

    # The LCD data pins (D4-D7) connect to MCP pins 12-9 (PORTB4-1), in
    # that order.  Because this sequence is 'reversed,' a direct shift
    # won't work.  This table remaps 4-bit data values to MCP PORTB
    # outputs, incorporating both the reverse and shift.
    flip = ( 0b00000000, 0b00010000, 0b00001000, 0b00011000,
             0b00000100, 0b00010100, 0b00001100, 0b00011100,
             0b00000010, 0b00010010, 0b00001010, 0b00011010,
             0b00000110, 0b00010110, 0b00001110, 0b00011110 )

    # Low-level 4-bit interface for LCD output.  This doesn't actually
    # write data, just returns a byte array of the PORTB state over time.
    # Can concatenate the output of multiple calls (up to 8) for more
    # efficient batch write.
    def out4(self, bitmask, value):
        hi = bitmask | self.flip[value >> 4]
        lo = bitmask | self.flip[value & 0x0F]
        return [hi | 0b00100000, hi, lo | 0b00100000, lo]

    # The speed of LCD accesses is inherently limited by I2C through the
    # port expander.  A 'well behaved program' is expected to poll the
    # LCD to know that a prior instruction completed.  But the timing of
    # most instructions is a known uniform 37 mS.  The enable strobe
    # can't even be twiddled that fast through I2C, so it's a safe bet
    # with these instructions to not waste time polling (which requires
    # several I2C transfers for reconfiguring the port direction).
    # The D7 pin is set as input when a potentially time-consuming
    # instruction has been issued (e.g. screen clear), as well as on
    # startup, and polling will then occur before more commands or data
    # are issued.

    pollables = ( LCD_CLEARDISPLAY, LCD_RETURNHOME )

    # Write byte, list or string value to LCD
    def write(self, value, char_mode=False):
        """ Send command/data to LCD """

        # If pin D7 is in input state, poll LCD busy flag until clear.
        if self.ddrb & 0b00010000:
            lo = (self.portb & 0b00000001) | 0b01000000
            hi = lo | 0b00100000 # E=1 (strobe)
            self.i2c.bus.write_byte_data(
              self.i2c.address, self.MCP23017_GPIOB, lo)
            while True:
                # Strobe high (enable)
                self.i2c.bus.write_byte(self.i2c.address, hi)
                # First nybble contains busy state
                bits = self.i2c.bus.read_byte(self.i2c.address)
                # Strobe low, high, low.  Second nybble (A3) is ignored.
                self.i2c.bus.write_i2c_block_data(
                  self.i2c.address, self.MCP23017_GPIOB, [lo, hi, lo])
                if (bits & 0b00000010) == 0: break # D7=0, not busy
            self.portb = lo

            # Polling complete, change D7 pin to output
            self.ddrb &= 0b11101111
            self.i2c.bus.write_byte_data(self.i2c.address,
              self.MCP23017_IODIRB, self.ddrb)

        bitmask = self.portb & 0b00000001   # Mask out PORTB LCD control bits
        if char_mode: bitmask |= 0b10000000 # Set data bit if not a command

        # If string or list, iterate through multiple write ops
        if isinstance(value, str):
            last = len(value) - 1 # Last character in string
            data = []             # Start with blank list
            for i, v in enumerate(value): # For each character...
                # Append 4 bytes to list representing PORTB over time.
                # First the high 4 data bits with strobe (enable) set
                # and unset, then same with low 4 data bits (strobe 1/0).
                data.extend(self.out4(bitmask, ord(v)))
                # I2C block data write is limited to 32 bytes max.
                # If limit reached, write data so far and clear.
                # Also do this on last byte if not otherwise handled.
                if (len(data) >= 32) or (i == last):
                    self.i2c.bus.write_i2c_block_data(
                      self.i2c.address, self.MCP23017_GPIOB, data)
                    self.portb = data[-1] # Save state of last byte out
                    data       = []       # Clear list for next iteration
        elif isinstance(value, list):
            # Same as above, but for list instead of string
            last = len(value) - 1
            data = []
            for i, v in enumerate(value):
                data.extend(self.out4(bitmask, v))
                if (len(data) >= 32) or (i == last):
                    self.i2c.bus.write_i2c_block_data(
                      self.i2c.address, self.MCP23017_GPIOB, data)
                    self.portb = data[-1]
                    data       = []
        else:
            # Single byte
            data = self.out4(bitmask, value)
            self.i2c.bus.write_i2c_block_data(
              self.i2c.address, self.MCP23017_GPIOB, data)
            self.portb = data[-1]

        # If a poll-worthy instruction was issued, reconfigure D7
        # pin as input to indicate need for polling on next call.
        if (not char_mode) and (value in self.pollables):
            self.ddrb |= 0b00010000
            self.i2c.bus.write_byte_data(self.i2c.address,
              self.MCP23017_IODIRB, self.ddrb)

    # ----------------------------------------------------------------------
    # Utility methods

    def begin(self, cols, lines):
        self.currline = 0
        self.numlines = lines
        self.numcols = cols
        self.clear()

    # Puts the MCP23017 back in Bank 0 + sequential write mode so
    # that other code using the 'classic' library can still work.
    # Any code using this newer version of the library should
    # consider adding an atexit() handler that calls this.
    def stop(self):
        self.porta = 0b11000000  # Turn off LEDs on the way out
        self.portb = 0b00000001
        sleep(0.0015)
        self.i2c.bus.write_byte_data(
          self.i2c.address, self.MCP23017_IOCON_BANK1, 0)
        self.i2c.bus.write_i2c_block_data(
          self.i2c.address, 0,
          [ 0b00111111,   # IODIRA
            self.ddrb ,   # IODIRB
            0b00000000,   # IPOLA
            0b00000000,   # IPOLB
            0b00000000,   # GPINTENA
            0b00000000,   # GPINTENB
            0b00000000,   # DEFVALA
            0b00000000,   # DEFVALB
            0b00000000,   # INTCONA
            0b00000000,   # INTCONB
            0b00000000,   # IOCON
            0b00000000,   # IOCON
            0b00111111,   # GPPUA
            0b00000000,   # GPPUB
            0b00000000,   # INTFA
            0b00000000,   # INTFB
            0b00000000,   # INTCAPA
            0b00000000,   # INTCAPB
            self.porta,   # GPIOA
            self.portb,   # GPIOB
            self.porta,   # OLATA
            self.portb ]) # OLATB

    def clear(self):
        self.write(self.LCD_CLEARDISPLAY)

    def home(self):
        self.write(self.LCD_RETURNHOME)

    row_offsets = ( 0x00, 0x40, 0x14, 0x54 )
    def setCursor(self, col, row):
        if row > self.numlines: row = self.numlines - 1
        elif row < 0:           row = 0
        self.write(self.LCD_SETDDRAMADDR | (col + self.row_offsets[row]))

    def display(self):
        """ Turn the display on (quickly) """
        self.displaycontrol |= self.LCD_DISPLAYON
        self.write(self.LCD_DISPLAYCONTROL | self.displaycontrol)

    def noDisplay(self):
        """ Turn the display off (quickly) """
        self.displaycontrol &= ~self.LCD_DISPLAYON
        self.write(self.LCD_DISPLAYCONTROL | self.displaycontrol)

    def cursor(self):
        """ Underline cursor on """
        self.displaycontrol |= self.LCD_CURSORON
        self.write(self.LCD_DISPLAYCONTROL | self.displaycontrol)

    def noCursor(self):
        """ Underline cursor off """
        self.displaycontrol &= ~self.LCD_CURSORON
        self.write(self.LCD_DISPLAYCONTROL | self.displaycontrol)

    def ToggleCursor(self):
        """ Toggles the underline cursor On/Off """
        self.displaycontrol ^= self.LCD_CURSORON
        self.write(self.LCD_DISPLAYCONTROL | self.displaycontrol)

    def blink(self):
        """ Turn on the blinking cursor """
        self.displaycontrol |= self.LCD_BLINKON
        self.write(self.LCD_DISPLAYCONTROL | self.displaycontrol)

    def noBlink(self):
        """ Turn off the blinking cursor """
        self.displaycontrol &= ~self.LCD_BLINKON
        self.write(self.LCD_DISPLAYCONTROL | self.displaycontrol)

    def ToggleBlink(self):
        """ Toggles the blinking cursor """
        self.displaycontrol ^= self.LCD_BLINKON
        self.write(self.LCD_DISPLAYCONTROL | self.displaycontrol)

    def scrollDisplayLeft(self):
        """ These commands scroll the display without changing the RAM """
        self.displayshift = self.LCD_DISPLAYMOVE | self.LCD_MOVELEFT
        self.write(self.LCD_CURSORSHIFT | self.displayshift)

    def scrollDisplayRight(self):
        """ These commands scroll the display without changing the RAM """
        self.displayshift = self.LCD_DISPLAYMOVE | self.LCD_MOVERIGHT
        self.write(self.LCD_CURSORSHIFT | self.displayshift)

    def leftToRight(self):
        """ This is for text that flows left to right """
        self.displaymode |= self.LCD_ENTRYLEFT
        self.write(self.LCD_ENTRYMODESET | self.displaymode)

    def rightToLeft(self):
        """ This is for text that flows right to left """
        self.displaymode &= ~self.LCD_ENTRYLEFT
        self.write(self.LCD_ENTRYMODESET | self.displaymode)

    def autoscroll(self):
        """ This will 'right justify' text from the cursor """
        self.displaymode |= self.LCD_ENTRYSHIFTINCREMENT
        self.write(self.LCD_ENTRYMODESET | self.displaymode)

    def noAutoscroll(self):
        """ This will 'left justify' text from the cursor """
        self.displaymode &= ~self.LCD_ENTRYSHIFTINCREMENT
        self.write(self.LCD_ENTRYMODESET | self.displaymode)

    def createChar(self, location, bitmap):
        self.write(self.LCD_SETCGRAMADDR | ((location & 7) << 3))
        self.write(bitmap, True)
        self.write(self.LCD_SETDDRAMADDR)

    def message(self, text, limitMode = 0):
        """ Send string to LCD. Newline wraps to next line"""
        lines = str(text).split('\n')       # Split at newline(s)
        for i, line in enumerate(lines):    # For each substring...
            if i == 1:                      # If newline(s),
                self.write(0xC0)             # set DDRAM address to 2nd line
            elif i == 2:
                self.write(0x94)
            elif i >= 3:
                self.write(0xD4)
            """Now depending on the limit mode set by the function call this will handle """
            lineLength = len(line)
            limit = self.numcols
            if limitMode <= 0:
                self.write(line, True)
            elif lineLength >= limit and limitMode == 1:
                '''With the limit mode set to 1 the line is truncated
                at the number of columns available on the display'''
                limitedLine = line[0:self.numcols]
                self.write(limitedLine, True)
            elif lineLength >= limit and limitMode == 2:
                '''With the limit mode set to 2 the line is truncated
                at the number of columns minus 3 to add in an elipse'''
                limitedLine = line[0:self.numcols-3]+'...'
                self.write(limitedLine, True)
            elif lineLength >= limit and limitMode >= 3:
                '''Future todo, add in proper, "line after line" cariage return'''
            else:
                self.write(line, True)

    def backlight(self, color):
        c          = ~color
        self.porta = (self.porta & 0b00111111) | ((c & 0b011) << 6)
        self.portb = (self.portb & 0b11111110) | ((c & 0b100) >> 2)
        # Has to be done as two writes because sequential operation is off.
        self.i2c.bus.write_byte_data(
          self.i2c.address, self.MCP23017_GPIOA, self.porta)
        self.i2c.bus.write_byte_data(
          self.i2c.address, self.MCP23017_GPIOB, self.portb)

    # Read state of single button
    def buttonPressed(self, b):
        return (self.i2c.readU8(self.MCP23017_GPIOA) >> b) & 1

    # Read and return bitmask of combined button state
    def buttons(self):
        return self.i2c.readU8(self.MCP23017_GPIOA) & 0b11111

    # ----------------------------------------------------------------------
    # Test code

if __name__ == '__main__':

    lcd = Adafruit_CharLCDPlate()
    lcd.begin(16, 4)
    lcd.clear()
    lcd.message("Adafruit RGB LCD\nPlate w/Key\npa\nd!")
    sleep(1)

    col = (('Red' , lcd.RED) , ('Yellow', lcd.YELLOW), ('Green' , lcd.GREEN),
           ('Teal', lcd.TEAL), ('Blue'  , lcd.BLUE)  , ('Violet', lcd.VIOLET),
           ('Off' , lcd.OFF) , ('On'    , lcd.ON))

    print("Cycle thru backlight colors")
    for c in col:
       print(c[0])
       lcd.clear()
       lcd.message(c[0])
       lcd.backlight(c[1])
       sleep(0.5)

    btn = ((lcd.SELECT, 'Select', lcd.ON),
           (lcd.LEFT  , 'Left'  , lcd.RED),
           (lcd.UP    , 'Up'    , lcd.BLUE),
           (lcd.DOWN  , 'Down'  , lcd.GREEN),
           (lcd.RIGHT , 'Right' , lcd.VIOLET))

    print("Try buttons on plate")
    lcd.clear()
    lcd.message("Try buttons")
    prev = -1
    while True:
        for b in btn:
            if lcd.buttonPressed(b[0]):
                if b is not prev:
                    print(b[1])
                    lcd.clear()
                    lcd.message(b[1])
                    lcd.backlight(b[2])
                    prev = b
                break


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
Annals d'École National d'Agric. de Montpellier, Série 2 9: 278 (1910)

#### Original name
Actinothecium quercinum G. Arnaud

### Remarks
null


text:
@interface GooglePlusLoadActivityViewController ()

@end

@implementation GooglePlusLoadActivityViewController

-(void )attemptToLoginToGoogle{
    [[GooglePlusLoginSessionHelper sharedInstance] attemptToSignInUser];
}

-(void)dealloc{
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}

-(void )addGoogleHelperNotificationCallBacks{
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(googlePlusUserSignedIn:) name:kGooglePlusNotificationSignedIn object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(googlePlusUserSignedInErrorOccured:) name:kGooglePlusNotificationSignInErrorOccured object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(googlePlusUserReturenedWithOutAttemptToSignIn:) name:kGooglePlusNotificationUserReturnedBackWithOutAttemptToSignIn object:nil];

}

-(void)viewDidLoad{

    [super viewDidLoad];
    [self addGoogleHelperNotificationCallBacks];

    self.loadingMessage = @"Signing to Google+...";
}

-(void)viewDidAppear:(BOOL)animated{
    [super viewDidAppear:animated];

    [self attemptToLoginToGoogle];
}

//*****************************************************
#pragma mark - Notifications
//*****************************************************

-(void )googlePlusUserSignedIn:(NSNotification *)sender{
    [[[UIAlertView alloc] initWithTitle:@"User signed in with google+" message:@"Since in back end Google+ provider is not added, currently we cannot proced with sign in with to shopex server" delegate:nil cancelButtonTitle:@"Ok" otherButtonTitles: nil] show];
    [self dismissViewControllerAnimated:YES completion:NULL];
}

-(void )googlePlusUserSignedInErrorOccured:(NSNotification *)sender{
    NSError *error = sender.object;
    [[[UIAlertView alloc] initWithTitle:@"Failed to sign in with google+" message:error.localizedDescription delegate:nil cancelButtonTitle:@"Ok" otherButtonTitles: nil] show];

    [self dismissViewControllerAnimated:YES completion:NULL];
}

-(void )googlePlusUserReturenedWithOutAttemptToSignIn:(NSNotification *)sender{
    [self dismissViewControllerAnimated:YES completion:NULL];
}

@end


text:
namespace Questionnaire.Data.Migrations
{
    using System;
    using System.Data.Entity.Migrations;

    public partial class Rev001 : DbMigration
    {
        public override void Up()
        {
            DropIndex("dbo.QuestionBases_MultipleTextItem", new[] { "MultipleTextQuestionId" });
            AddColumn("dbo.QuestionBases_Rating", "minRateDescription", c => c.String(maxLength: 256));
            AddColumn("dbo.QuestionBases_Rating", "maxRateDescription", c => c.String(maxLength: 256));
            AddColumn("dbo.Choices", "SurveyId", c => c.Int(nullable: false));
            AddColumn("dbo.MatrixRows", "SurveyId", c => c.Int(nullable: false));
            AlterColumn("dbo.QuestionBases_MultipleTextItem", "MultipleTextQuestionId", c => c.Int());
            CreateIndex("dbo.Choices", "SurveyId");
            CreateIndex("dbo.MatrixRows", "SurveyId");
            CreateIndex("dbo.QuestionBases_MultipleTextItem", "MultipleTextQuestionId");
            AddForeignKey("dbo.Choices", "SurveyId", "dbo.Surveys", "Id", cascadeDelete: true);
            AddForeignKey("dbo.MatrixRows", "SurveyId", "dbo.Surveys", "Id", cascadeDelete: true);
            DropColumn("dbo.QuestionBases_Rating", "mininumRateDescription");
            DropColumn("dbo.QuestionBases_Rating", "maximumRateDescription");
        }

        public override void Down()
        {
            AddColumn("dbo.QuestionBases_Rating", "maximumRateDescription", c => c.String(maxLength: 256));
            AddColumn("dbo.QuestionBases_Rating", "mininumRateDescription", c => c.String(maxLength: 256));
            DropForeignKey("dbo.MatrixRows", "SurveyId", "dbo.Surveys");
            DropForeignKey("dbo.Choices", "SurveyId", "dbo.Surveys");
            DropIndex("dbo.QuestionBases_MultipleTextItem", new[] { "MultipleTextQuestionId" });
            DropIndex("dbo.MatrixRows", new[] { "SurveyId" });
            DropIndex("dbo.Choices", new[] { "SurveyId" });
            AlterColumn("dbo.QuestionBases_MultipleTextItem", "MultipleTextQuestionId", c => c.Int(nullable: false));
            DropColumn("dbo.MatrixRows", "SurveyId");
            DropColumn("dbo.Choices", "SurveyId");
            DropColumn("dbo.QuestionBases_Rating", "maxRateDescription");
            DropColumn("dbo.QuestionBases_Rating", "minRateDescription");
            CreateIndex("dbo.QuestionBases_MultipleTextItem", "MultipleTextQuestionId");
        }
    }
}


text:
package com.github.adiesner.jenkins.bitbucketprcoveragestatus;

import org.apache.commons.io.FileUtils;

import java.io.File;
import java.io.IOException;

/*
<counter type="INSTRUCTION" missed="1" covered="4"/>
    <counter type="LINE" missed="1" covered="2"/>
    <counter type="COMPLEXITY" missed="1" covered="2"/>
    <counter type="METHOD" missed="1" covered="2"/>
    <counter type="CLASS" missed="0" covered="1"/>
 */
class JacocoParser implements CoverageReportParser {

    private static final String MISSED_XPATH = "/report/counter[@type='LINE']/@missed";
    private static final String COVERAGE_XPATH = "/report/counter[@type='LINE']/@covered";

    private float getByXpath(final String filePath, final String content, final String xpath) {
        try {
            return Float.parseFloat(XmlUtils.findInXml(content, xpath));
        } catch (NumberFormatException e) {
            throw new IllegalArgumentException(
                    "Strange Jacoco report!\n" +
                            "File path: " + filePath + "\n" +
                            "Can't extract float value by XPath: " + xpath + "\n" +
                            "from:\n" + content);
        }
    }

    @Override
    public float get(final String jacocoFilePath) {
        final String content;
        try {
            content = FileUtils.readFileToString(new File(jacocoFilePath));
        } catch (IOException e) {
            throw new IllegalArgumentException(
                    "Can't read Jacoco report by path: " + jacocoFilePath);
        }

        final float lineMissed = getByXpath(jacocoFilePath, content, MISSED_XPATH);
        final float lineCovered = getByXpath(jacocoFilePath, content, COVERAGE_XPATH);
        final float lines = lineCovered + lineMissed;
        if (lines == 0) {
            return 0;
        } else {
            return lineCovered / (lines);
        }
    }

}


text:
import os
from setuptools import setup, find_packages
from setuptools.command.build_ext import build_ext
from setuptools import Extension
import sys

class CMakeBuild(build_ext):
    """
    Runs cmake and make install instead of a traditional C/C++ extension build.
    """
    def run(self):
        build_dir = os.path.dirname(os.path.realpath(__file__))
        for cmd, target in [("cmake", ""), ("make -j -C", "install")]:
            if os.system("%s %s %s" % (cmd, build_dir, target)) != 0:
                print("ERROR: Failed to run %s" % cmd)
                sys.exit(1)
        #copy to cuda lib dir/ the cuda lib dir will be in path, so cudanet should automatically work
        os.system("cp %s/cudanet/libcconv2_cudanet.so /usr/local/cuda/lib64" % (build_dir))

cudanet = Extension('cudanet.libcudanet', sources = [],
                    runtime_library_dirs=['cudanet'])
install_requires = ['numpy', ]
test_requires = ['nose', ]

setup(name="cudanet",
      version="0.2.8",
      description="Provides a set of cudamat like functions using cuda-convnet2 kernels",
      ext_modules = [cudanet],
      packages=['cudanet','cudanet.layers'],
      author="Alex Khrizevsky, Nervanasys, and Tim Dettmers",
      author_email="tim.dettmers@gmail.com",
      url="https://code.google.com/p/cuda-convnet2/",
      install_requires=install_requires,
      tests_require=test_requires,
      cmdclass={'build_ext': CMakeBuild},
)


text:
package cip.byteinputlexer;

import cip.Location;
import cip.lexer.Lexeme;

/**
 * DefaultPragmaBuilder XXX
 */
class DefaultPragmaBuilder implements DirectiveBuilder {
    // cip/changes/lex-pragma

    DefaultPragmaBuilder() {
    }

    public int buildChar(byte b, Location l) throws Exception {
        return Lexeme.CHAR_LITERAL;
    }

    public void buildIdChunk(byte[] buffer, int start, int end, Location l)
            throws Exception {
    }

    public int buildId(byte[] buffer, int start, int end, Location l)
            throws Exception {
        return Lexeme.ID_LITERAL;
    }

    public void buildStringChunk(byte[] buffer, int start, int end, Location l)
            throws Exception {
    }

    public void buildStringChar(byte b, Location l) throws Exception {
    }

    public int buildString(byte[] buffer, int start, int end, Location l)
            throws Exception {
        return Lexeme.STRING_LITERAL;
    }

    public int buildInt(long value, int type, Location l) throws Exception {
        return Lexeme.INT_LITERAL;
    }

    public int buildKeyword(int keyword, Location l) throws Exception {
        return keyword;
    }

    public int buildOperator(byte[] buffer, int start, int end,
                             int symbol, Location l) throws Exception {
        return symbol;
    }

    public int buildLineEnd(int rv) throws Exception {
        return rv|EOL;
    }

    public int buildInputEnd(Location l) throws Exception {
        return EOL;
    }
}


text:
"""
VDisk module
"""

from rest_framework import viewsets
from rest_framework.permissions import IsAuthenticated
from rest_framework.decorators import action
from ovs.dal.lists.vdisklist import VDiskList
from ovs.dal.hybrids.vdisk import VDisk
from ovs.dal.hybrids.vmachine import VMachine
from ovs.dal.hybrids.vpool import VPool
from ovs.lib.vdisk import VDiskController
from backend.decorators import required_roles, load, return_list, return_object, return_task, log

class VDiskViewSet(viewsets.ViewSet):
    """
    Information about vDisks
    """
    permission_classes = (IsAuthenticated,)
    prefix = r'vdisks'
    base_name = 'vdisks'

    @log()
    @required_roles(['read'])
    @return_list(VDisk)
    @load()
    def list(self, vmachineguid=None, vpoolguid=None):
        """
        Overview of all vDisks
        """
        if vmachineguid is not None:
            vmachine = VMachine(vmachineguid)
            return vmachine.vdisks
        elif vpoolguid is not None:
            vpool = VPool(vpoolguid)
            return vpool.vdisks
        return VDiskList.get_vdisks()

    @log()
    @required_roles(['read'])
    @return_object(VDisk)
    @load(VDisk)
    def retrieve(self, vdisk):
        """
        Load information about a given vDisk
        """
        return vdisk

    @action()
    @log()
    @required_roles(['read', 'write'])
    @return_task()
    @load(VDisk)
    def rollback(self, vdisk, timestamp):
        """
        Rollbacks a vDisk to a given timestamp
        """
        return VDiskController.rollback.delay(diskguid=vdisk.guid,
                                              timestamp=timestamp)


text:
---
uid: SolidEdgePart.MidSurfaces.Add(System.Double,System.Int32)
summary:
remarks:
syntax:
    parameters:
    - id: dOffsetValue
      description: Specifies the distance the surface is to be offset.
    - id: RefLayer
      description: Specifies whether the offset is measured from the top face (value of 1) or the bottom face (value of 0) of the part.
---


text:
package org.spockframework.util;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * A version number with format major.minor.micro-qualifier.
 */
@Immutable
public final class VersionNumber implements Comparable<VersionNumber> {
  public static final VersionNumber UNKNOWN = new VersionNumber(0, 0, 0, null);

	private static final Pattern versionPattern = Pattern.compile("(\\d+)(?:\\.(\\d+))?+(?:\\.(\\d+))?+(?:[-\\.](.+))?");
	private static final String versionTemplate = "%d.%d.%d%s";

	private final int major;
	private final int minor;
	private final int micro;
  private final String qualifier;

	public VersionNumber(int major, int minor, int micro, @Nullable String qualifier) {
		this.major = major;
		this.minor = minor;
		this.micro = micro;
    this.qualifier = qualifier;
	}

	public int getMajor() {
		return major;
	}

	public int getMinor() {
		return minor;
	}

	public int getMicro() {
		return micro;
	}

	public String getQualifier() {
    return qualifier;
  }

	public int compareTo(VersionNumber other) {
		if (major != other.major) return major - other.major;
		if (minor != other.minor) return minor - other.minor;
		if (micro != other.micro) return micro - other.micro;
    return NullSafe.compare(qualifier, other.qualifier);
	}

	public boolean equals(Object other) {
		return other instanceof VersionNumber && compareTo((VersionNumber)other) == 0;
	}

  public int hashCode() {
    int result = major;
    result = 31 * result + minor;
    result = 31 * result + micro;
    result = 31 * result + NullSafe.hashCode(qualifier);
    return result;
  }

  public String toString() {
		return String.format(versionTemplate, major, minor, micro, qualifier == null ? "" : "-" + qualifier);
	}

	public static VersionNumber parse(String versionString) {
    if (versionString == null) return UNKNOWN;
		Matcher m = versionPattern.matcher(versionString);
		if (!m.matches()) return UNKNOWN;

		int major = Integer.valueOf(m.group(1));
		String minorString = m.group(2);
		int minor = minorString == null ? 0 : Integer.valueOf(minorString);
		String microString = m.group(3);
		int micro = microString == null ? 0 : Integer.valueOf(microString);
    String qualifier = m.group(4);

		return new VersionNumber(major, minor, micro, qualifier);
	}
}


text:
<?php
namespace TheSeer\phpDox\Generator {

    class MemberCollection extends AbstractCollection {

        /**
         * @return MemberObject
         */
        public function current() {
            return new MemberObject($this->getCurrentNode());
        }

    }

}


text:
var screenInstance = null;

function Screen() {
  nw.allocateObject(this, {});
  this._numListener = 0;
}
require('util').inherits(Screen, exports.Base);

// Override the addListener method.
Screen.prototype.on = Screen.prototype.addListener = function(ev, callback) {
  if ( ev != "displayBoundsChanged" && ev != "displayAdded" && ev != "displayRemoved" )
    throw new String('only following event can be listened: displayBoundsChanged, displayAdded, displayRemoved');

  var onRemoveListener = function (type, listener) {
    if (this._numListener > 0) {
      this._numListener--;
      if (this._numListener == 0) {
        process.EventEmitter.prototype.removeListener.apply(this, ["removeListener", onRemoveListener]);
        nw.callStaticMethodSync('Screen', 'RemoveScreenChangeCallback', [ this.id ]);
      }
    }
  };

  if(this._numListener == 0) {
    if (nw.callStaticMethodSync('Screen', 'AddScreenChangeCallback', [ this.id ]) == false ) {
      throw new String('nw.callStaticMethodSync(Screen, AddScreenChangeCallback) fails');
      return;
    }
    process.EventEmitter.prototype.addListener.apply(this, ["removeListener", onRemoveListener]);
  }

  // Call parent.
  process.EventEmitter.prototype.addListener.apply(this, arguments);
  this._numListener++;
}

// Route events.
Screen.prototype.handleEvent = function(ev) {
  arguments[1] = JSON.parse(arguments[1]);
  // Call parent.
  this.emit.apply(this, arguments);
}

Screen.prototype.__defineGetter__('screens', function() {
  return JSON.parse(nw.callStaticMethodSync('Screen', 'GetScreens', [ ]));
});

// ======== Screen functions End ========

// Store App object in node's context.
exports.Screen = {
Init: function() {
  if (screenInstance == null) {
    screenInstance = new Screen();
  }
  exports.Screen = screenInstance;
  return screenInstance;
}
};


text:
package io.pivotal.strepsirrhini.chaoslemur;

import java.util.ArrayList;
import java.util.List;
import java.util.function.Function;
import java.util.function.Supplier;

final class Precedence<T> {

    private final Object monitor = new Object();

    private final List<Supplier<T>> suppliers = new ArrayList<>();

    Precedence<T> candidate(Supplier<T> supplier) {
        synchronized (this.monitor) {
            this.suppliers.add(supplier);
            return this;
        }
    }

    Precedence<T> candidate(T value) {
        return candidate(() -> value);
    }

    T get() {
        return get(Function.<T>identity());
    }

    <U> U get(Function<T, U> f) {
        synchronized (this.monitor) {
            for (Supplier<T> supplier : this.suppliers) {
                T value = supplier.get();

                if (value != null) {
                    return f.apply(value);
                }
            }

            throw new IllegalStateException("No non-null values supplied");
        }
    }
}


text:
'use strict';

var mysql   = require('mysql'); // https://www.npmjs.org/package/mysql
var Debug   = require("../lib/_Debug");
var util    = require("util");
var crypto  = require('crypto');

var MYSQL_RECONNECT_TIMER=10*1000; // 10s timeout in bewteen two MYSQL reconnects

// ConnectDB is done on at creation time and asynchronously on PROTOCOL_CONNECTION_LOST
var CreateConnection =function (backend) {

    backend.Debug (4, "MySQL creating connection [%s]", backend.uid);
    backend.base = mysql.createConnection(backend.opts);
    backend.count ++;

    // register event for asynchronous server errors
    backend.base.on('error', function(err) {
        backend.Debug (1, "MySQL server error=[%s]", err);
        // Sever was restarted or network connection was lost let restart connection
        if(err.code === 'PROTOCOL_CONNECTION_LOST') {
             backend.Debug (4, "MySQL connection lost [%s/%d] automatic connect retry in 10s]", backend.uid, backend.count);
             setTimeout(function () {CreateConnection (backend);}, MYSQL_RECONNECT_TIMER);

        } else {
            throw err;  // server variable configures this)
        };
    });

    // force an initial connectiion at object construction time
    backend.base.connect (function(err) {
        if (err) {
             backend.Debug (4, "MySQL connection fail [%s/%d] automatic connect retry in 10s]", backend.uid, backend.count);
             setTimeout(function () {CreateConnection (backend);}, MYSQL_RECONNECT_TIMER);

        } else {
            backend.Debug (5,"MySQL Connect Done [%s]",  backend.uid);
        }
    });
};

// Create MySQL Backend object
function BackendStorage (gateway, opts){

    // prepare ourself to make debug possible
    this.debug   =opts.mysql.debug || opts.debug;
    this.gateway =gateway;
    this.count=0;  // stat for connection retry

    this.opts= {
            host     : opts.mysql.hostname || "localhost",
            user     : opts.mysql.username,
            password : opts.mysql.password,
            database : opts.mysql.basename || opts.username,
            typeCast : true,
            dateStrings: false,
            timezone: 'utc'
    };
    this.uid ="mysql:" + opts.mysql.username + "@" + opts.mysql.hostname + "/" + opts.mysql.basename;

    // create initial connection handler to database
    CreateConnection (this);
};

// Import debug method
BackendStorage.prototype.Debug = Debug;

// Create MySQL Backend object
BackendStorage.prototype.CheckTablesExits = function () {
    this.Debug (0,"Hoops this backend does not support CheckTablesExits");
}

// Typically would create an entry inside device database table
BackendStorage.prototype.CreateDev = function (devid, data) {
    var self=this;
    this.Debug (3,"Add to MySql device:%s data=%j", devid, data);
    var gateway=this.gateway;

    var queryString = "INSERT INTO usr_trackers set ?";
    var post  = {
             imeinum    : devid.toString()
            ,nickname   : data.devname
            ,phonenum   : data.callsign
            ,token      : crypto.createHash('sha1').update (new Date().toString()).digest("hex")
            ,created_at : new Date()
            ,updated_at : new Date()
    };

    // added ALTER TABLE devices ADD UNIQUE INDEX devid (uniqueId);
    var sqlQuery = this.base.query(queryString, post);

    // on sucess this command is call once per selected row [hopefully only one in this case]
    sqlQuery.on("result", function(result) {
        gateway.event.emit ("notice", "ADD-DEVICE", "in MySQL", result);
    });

    sqlQuery.on("error", function(err) {
        self.Debug (0,'MySql Error creating device err=%s', err);
        gateway.event.emit ("notice", "ERROR-DEVICE", "insert MySQL", devid, err);
    });
};

// Typically would create an entry inside device database table
BackendStorage.prototype.RemoveDev = function (devid) {
    this.Debug (3,"Remove entry in DB for device:%s", devid);
    var gateway=this.gateway;

    var queryString = "delete from usr_trackers where imeinum =" + devid;
    var sqlQuery = this.base.query(queryString);

    // on sucess this command is call once per selected row [hopefully only one in this case]
    sqlQuery.on("result", function(result) {
        gateway.event.emit ("notice", "DROP-DEVICE", "in MySQL", devid);
    });

    sqlQuery.on("error", function() {
        gateway.event.emit ("notice", "ERROR DEVICE", "from to remove MySQL", devid, err);
    });
};

// Query are done asynchronously and function will return before result is knowned
BackendStorage.prototype.LoginDev = function (device) {
    var self=this;
    this.Debug (6,"Login MySQL device:%s devid=%s", device.uid, device.devid);

    // selectQuery = 'SELECT * FROM devices where uniqueId = 359710043551135';
    var queryString = "SELECT * From usr_trackers WHERE imeinum = " + device.devid;
    var sqlQuery = this.base.query(queryString);

    // on sucess this command is call once per selected row [hopefully only one in this case]
    sqlQuery.on("result", function (result) {
        self.Debug(9, "sqlQuery %j", result);

        // update active device pool [note device.devid is set by GpsdClient before SQL login]
        device.name  = result.nickname; // friendly name extracted from database
        device.sqlid = result.id;       // this is MySQL unique ID and not device's DEVID
        device.token = result.token;    // access token for REST API
        device.logged = true;           // marked device as knowned from database
    });

    sqlQuery.on("error", function (err) {
        self.Debug(0, "MySql ERROR Login devid=%d err=%s", device.devid, err);
    });
};

// Query are done asynchronously and function will return before result is known
BackendStorage.prototype.LogoutDev = function (device) {
    this.Debug(4, "Logout Device:%s", device.uid);

    // change device status to logout
    device.logged = false;
};

BackendStorage.prototype.TempryLoggin = function (device) {
    this.Debug(5, "TempryLogin Device:%s", device.uid);
    this.event.emit("dev-tmp", device);
};

BackendStorage.prototype.IgnorePosDev = function (device) {
    this.Debug(6, "IgnoreDev Device:%s", device.uid);
    this.event.emit("dev-ign", device);
};

// If Elapsed Moved cannot be retreived from device session, we compute it from DB
BackendStorage.prototype.FixeMovedElapsed = function (device, data, rowid) {
    var self=this;
    var sqlQuery= "Select  id,lat,lon,acquired_at from geo_tracks where tracker_id=" +  device.sqlid + " AND ID < " + rowid
        + " ORDER BY ID DESC LIMIT 1";
    this.Debug (4, "sqlQuery=%s", sqlQuery);

    this.base.query (sqlQuery , function (err, result) {
        if (err) {
            self.Debug (0,"MySql FixeMovedElapsed devid=%d Err=%s",device.sqlid, err);
        } else {
            var moved   = device.Distance (result[0], data);
            var elapsed = parseInt ((data.acquired_at - result[0].acquired_at)/1000);

            self.Debug (4, "FixeMovedElapsed oldrow=%d newrow=%d elapsed=%d moved=%d", result[0].id, rowid, elapsed, moved);

            var queryString = "UPDATE geo_tracks set moved=" + moved + ",elapsed=" + elapsed + " where id=" + rowid;
            self.base.query (queryString, function (err, result) {
                if (err) {
                    self.Debug (0,"MySql FixeMovedElapsed devsqlid=%d Query=%s Err=%s",device.sqlid, queryString, err);
                }
            });
        }
    });
};

// Query are done asynchronously and function will return before result is knowned
BackendStorage.prototype.UpdatePosDev = function (device, data) {
    var self=this;
    this.Debug (6,"Updating Track MySQL devid=%s", device.devid);
    this.Debug (3,'%j', data)

    // INSERT INTO positions (device_id, time, valid, latitude, longitude, altitude, speed, course, power)
    var queryString = "INSERT INTO geo_tracks" + " set ?";

    // add tracker foreign key id
    data['tracker_id'] = device.sqlid;

    // launch insertion of new position asynchronously
    var insertQuery = this.base.query(queryString, data);

    insertQuery.on("error", function(err) {
        self.Debug (0,"MySql ERROR UpdatePosDev %s err=%s", queryString, err);
    });

    // if moved is unknown from session try to fix it from DB
    insertQuery.on("result", function(result) {
        if (data.moved === -1) {
            self.Debug (0,"MySql Sucess insertid= %d", result.insertId);
            self.FixeMovedElapsed (device, data, result.insertId)
        }
    });
};

BackendStorage.prototype.UpdateAlarmDev = function (device, data) {
    var self=this;
    this.Debug (6,"Updating Alarm MySQL devid=%s", device.devid);

    // INSERT INTO positions (device_id, time, valid, latitude, longitude, altitude, speed, course, power)
    var queryString = "INSERT INTO geo_tracks" + " set ?";

    this.Debug (3,'%j', data)

    // add tracker foreign key id
    data['tracker_id'] = device.sqlid;

    // launch insertion of new position asynchronously
    var insertQuery = this.base.query(queryString, data);

    // if moved is unknown from session try to fix it from DB
    insertQuery.on("result", function(result) {
        if (data.moved === -1) {
            self.Debug (0,"MySql Sucess insertid= %d", result.insertId);
            self.FixeMovedElapsed (device, data, result.insertId)
        }
    });

    insertQuery.on("error", function(err) {
        self.Debug (0,"MySql ERROR LookupDev %s err=%s", queryString, err);
    });
};

BackendStorage.prototype.UpdateObdDev = function (device, data) {
    var self=this;
    if (!data.rpm) return;   // if engine not running ignore packet

    this.Debug (6,"Updating OBD MySQL devid=%s", device.devid);

    // INSERT INTO positions (device_id, time, valid, latitude, longitude, altitude, speed, course, power)
    var queryString = "INSERT INTO geo_obds" + " set ?";
    this.Debug (3,'%j', data)

    // add tracker foreign key id
    data['tracker_id'] = device.sqlid;

    // launch insertion of new position asynchronously
    var insertQuery = this.base.query(queryString, data);

    insertQuery.on("error", function(err) {
        self.Debug (0,"MySql ERROR UpdateOdbDev %s err=%s", queryString, err);
    });
};

// Write last X positions on Telnet/Console for active devices only !!!
BackendStorage.prototype.LookupDev = function (callback, devid, args) {
    var self=this;
    var device= this.gateway.activeClients [devid]; // device.sqlid was updated at authentication

    var sqlQuery= "Select  lat,lon,sog,cog,alt,acquired_at from geo_tracks where tracker_id=" +  device.sqlid
        + " ORDER BY acquired_at DESC LIMIT " + args;
    this.Debug (4, "sqlQuery=%s", sqlQuery);

    this.base.query (sqlQuery , function (err, dbresult) {
        if (err) {
            self.Debug (0,"MySql LookupDev devid=%d Err=%s",devid, err);
        } else {
            callback(dbresult);
        }
    });
};

// export the class
module.exports = BackendStorage; // http://openmymind.net/2012/2/3/Node-Require-and-Exports/


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">

<TITLE>TNativeXml.SaveToStream</TITLE>
    <META http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
    <META name="GENERATOR" content="Doc-O-Matic">
    <LINK rel="STYLESHEET" href="default.css" type="text/css">

NativeXml Help

Content | Index | Reference

TNativeXml.SaveToStream

TNativeXml

procedure SaveToStream(Stream: TStream); virtual;

Description

Call SaveToStream to save the XML document to the Stream. Stream can be any TStream descendant. Set XmlFormat to xfReadable if you want the stream to contain indentations to make the XML more human-readable. This is not the default and also not compliant with the XML specification. See SaveToFile for information on how to save in special encoding.


text:
namespace Poco {
namespace Net {

class Net_API MulticastSocket: public DatagramSocket
	/// A MulticastSocket is a special DatagramSocket
	/// that can be used to send packets to and receive
	/// packets from multicast groups.
{
public:
	MulticastSocket();
		/// Creates the multicast socket.

	explicit MulticastSocket(IPAddress::Family family);
		/// Creates an unconnected datagram socket.
		///
		/// The socket will be created for the
		/// given address family.

	MulticastSocket(const SocketAddress& address, bool reuseAddress = false);
		/// Creates a datagram socket and binds it
		/// to the given address.
		///
		/// Depending on the address family, the socket
		/// will be either an IPv4 or an IPv6 socket.

	MulticastSocket(const Socket& socket);
		/// Creates the DatagramSocket with the SocketImpl
		/// from another socket. The SocketImpl must be
		/// a DatagramSocketImpl, otherwise an InvalidArgumentException
		/// will be thrown.

	~MulticastSocket();
		/// Destroys the DatagramSocket.

	MulticastSocket& operator = (const Socket& socket);
		/// Assignment operator.
		///
		/// Releases the socket's SocketImpl and
		/// attaches the SocketImpl from the other socket and
		/// increments the reference count of the SocketImpl.

	void setInterface(const NetworkInterface& interfc);
		/// Sets the interface used for sending multicast packets.
		///
		/// To select the default interface, specify an empty
		/// interface.
		///
		/// This is done by setting the IP_MULTICAST_IF/IPV6_MULTICAST_IF
		/// socket option.

	NetworkInterface getInterface() const;
		/// Returns the interface used for sending multicast packets.

	void setLoopback(bool flag);
		/// Enable or disable loopback for multicast packets.
		///
		/// Sets the value of the IP_MULTICAST_LOOP/IPV6_MULTICAST_LOOP
		/// socket option.

	bool getLoopback() const;
		/// Returns true iff loopback for multicast packets is enabled,
		/// false otherwise.

	void setTimeToLive(unsigned value);
		/// Specifies the TTL/hop limit for outgoing packets.
		///
		/// Sets the value of the IP_MULTICAST_TTL/IPV6_MULTICAST_HOPS
		/// socket option.

	unsigned getTimeToLive() const;
		/// Returns the TTL/hop limit for outgoing packets.

	void joinGroup(const IPAddress& groupAddress);
		/// Joins the specified multicast group at the default interface.

	void joinGroup(const IPAddress& groupAddress, const NetworkInterface& interfc);
		/// Joins the specified multicast group at the given interface.

	void leaveGroup(const IPAddress& groupAddress);
		/// Leaves the specified multicast group at the default interface.

	void leaveGroup(const IPAddress& groupAddress, const NetworkInterface& interfc);
		/// Leaves the specified multicast group at the given interface.

private:
	static NetworkInterface findFirstInterface(const IPAddress& groupAddress);
		/// Returns first multicast-eligible network interface.
};

} } // namespace Poco::Net

#endif // POCO_NET_HAS_INTERFACE

#endif // Net_MulticastSocket_INCLUDED


text:
import json

class RestAPI:
    def __init__(self, database=None):
        self.database = database or {'users': []}

    def update(self):
        for user in self.database['users']:
            owed_by = user['owed_by']
            owes = user['owes']
            for debtor in list(owed_by.keys()):
                if debtor in owes:
                    diff = 0
                    if debtor in owes:
                        diff = owes[debtor]
                        del owes[debtor]
                    if debtor in owed_by:
                        diff -= owed_by[debtor]
                        del owed_by[debtor]
                    if diff > 0:
                        owes[debtor] = diff
                    elif diff < 0:
                        owed_by[debtor] = -diff
            user['balance'] = sum(owed_by.values()) - sum(owes.values())

    def get(self, url, payload=None):
        if payload is not None:
            payload = json.loads(payload)
        if url == '/users':
            if payload is None:
                return json.dumps(self.database)
            else:
                return json.dumps({
                    'users': [
                        user for user in self.database['users']
                        if user['name'] in payload['users']
                    ]
                })
        return None

    def post(self, url, payload=None):
        result = None
        if payload is not None:
            payload = json.loads(payload)
        if url == '/add':
            if payload is not None:
                name = payload['user']
                users = self.database['users']
                user = None
                for idx in users:
                    if idx['name'] == name:
                        user = idx
                        break
                if user is None:
                    new_user = {
                        'name': name,
                        'owes': {},
                        'owed_by': {},
                        'balance': 0
                    }
                    users.append(new_user)
                    self.update()
                    result = json.dumps(new_user)
        elif url == '/iou':
            if payload is not None:
                lender_name = payload['lender']
                borrower_name = payload['borrower']
                amount = payload['amount']
                lender = borrower = None
                for user in self.database['users']:
                    if user['name'] == lender_name:
                        lender = user
                    elif user['name'] == borrower_name:
                        borrower = user
                if lender is not None and borrower is not None:
                    lender['owed_by'].setdefault(borrower_name, 0)
                    lender['owed_by'][borrower_name] += amount
                    borrower['owes'].setdefault(lender_name, 0)
                    borrower['owes'][lender_name] += amount
                    self.update()
                    result = self.get(
                        '/users',
                        json.dumps({'users': [lender_name, borrower_name]})
                    )
        return result


text:
import {SuperMap} from '../SuperMap';
import {Util} from '../commontypes/Util';
import {CommonServiceBase} from './CommonServiceBase';

/**
 * @class SuperMap.DatasourceService
 * @category iServer Data Datasource
 * @classdesc 数据源查询服务。
 * @param {string} url - 服务的访问地址。如访问World Data服务,只需将url设为:http://localhost:8090/iserver/services/data-world/rest/data 即可。
 * @param {Object} options - 参数。

 * @param {Object} options.eventListeners - 事件监听器对象。有processCompleted属性可传入处理完成后的回调函数。processFailed属性传入处理失败后的回调函数。
 * @param {SuperMap.DataFormat} [options.format=SuperMap.DataFormat.GEOJSON] - 查询结果返回格式,目前支持 iServerJSON 和 GeoJSON 两种格式。参数格式为 "ISERVER","GEOJSON"。
 * @param {string}options.datasource - 要查询的数据集所在的数据源名称。

 * @param {string}options.dataset - 要查询的数据集名称。

 * @param {boolean} [options.crossOrigin] - 是否允许跨域请求。
 * @param {Object} [options.headers] - 请求头。
 * @extends {SuperMap.CommonServiceBase}
 */

export class DatasourceService extends CommonServiceBase {

    constructor(url, options) {
        super(url, options);
        if (options) {
            Util.extend(this, options);
        }
        this.CLASS_NAME = "SuperMap.DatasourceService";
    }

    /**
     * @function SuperMap.DatasourceService.prototype.destroy
     * @override
     */
    destroy() {
        super.destroy();
    }

    /**
     * @function SuperMap.DatasourceService.prototype.getDatasourceService
     * @description 执行服务,查询数据源信息。
     */
    getDatasourceService(datasourceName) {
        var me = this;
        me.url = Util.urlPathAppend(me.url,`datasources/name/${datasourceName}`);
        me.request({
            method: "GET",
            data: null,
            scope: me,
            success: me.serviceProcessCompleted,
            failure: me.serviceProcessFailed
        });
    }

    /**
     * @function SuperMap.DatasourceService.prototype.getDatasourcesService
     * @description 执行服务,查询数据源信息。
     */
    getDatasourcesService() {
        var me = this;
        me.url = Util.urlPathAppend(me.url,`datasources`);
        me.request({
            method: "GET",
            data: null,
            scope: me,
            success: me.serviceProcessCompleted,
            failure: me.serviceProcessFailed
        });
    }
    /**
     * @function SuperMap.DatasourceService.prototype.setDatasourceService
     * @description 执行服务,查询数据源信息。
     */
    setDatasourceService(params) {
        if (!params) {
            return;
        }
        var me = this;
        var jsonParamsStr = Util.toJSON(params);
        me.request({
            method: "PUT",
            data: jsonParamsStr,
            scope: me,
            success: me.serviceProcessCompleted,
            failure: me.serviceProcessFailed
        });
    }
}

SuperMap.DatasourceService = DatasourceService;