text:
<file_sep>import Data.Maybe

data Tree a = Tree (Maybe (a, Tree a, Tree a))
            deriving (Show)
<file_sep>ave :: Fractional a => [a] -> a
ave xs = (sum xs) / fromIntegral (length xs)
<file_sep>kaibun :: [a] -> [a]
kaibun xs = xs ++ reverse xs
<file_sep>mySecond :: [a] -> Maybe a
mySecond xs = if null (tail xs)
              then Nothing
              else Just(head(tail xs))

tidySecond :: [a] -> Maybe a
tidySecond (_:x:_) = Just x
tidySecond _	   = Nothing
<file_sep>intersperse :: a -> [[a]] -> [a]
intersperse c [xs] = xs
intersperse c (x:xs) = x ++ [c] ++ intersperse c xs
intersperse c [] = []
<file_sep>-- ここが一番左のカラムです

    -- 最初の宣言はカラム4から始まっています
    firstBadIndentation = 1

  -- 2番目の宣言は最初のものより左にあり、これは不正です
  secondBadIndentation = 2
<file_sep>-- ここが一番左のカラムです

    -- トップレベルの宣言は任意のカラム
    firstGoodIndentation = 1

    -- それ以降すべての宣言で同じにすれば上手くいきます
    secondGoodIndentation = 2
<file_sep>import Data.List

subSort :: [[a]] -> [[a]]
subSort xs = sortBy compareLength xs
    where compareLength xs ys = compare (length xs) (length ys)
<file_sep>data List a = Cons a (List a)
            | Nil
            deriving (Show)

toList :: List a -> [a]
toList (Cons a as) = a : toList as
toList Nil = []

branch_name: refs/heads/master

repo_language: Haskell


text:
<repo_name>vnachev/LinuxPrograms172<file_sep>/nummberinfoarg.c
#include <stdio.h>
#include <stdlib.h>

int main(int argc, char *argv[])
{
   int num;
   if (argc != 2)
   {
      printf("Invalid input\n");
      return 1;
   }
   num = atoi(argv[1]);
   if (num == 0)
   {
      printf("Zero\n");
   }
   else if (num < 0)
   {
     printf("Negative\n");
   }
   else
   {
     printf("Positive\n");
   }
   return 0;
}
<file_sep>/README.md
# LinuxPrograms172
Simple Linux C programs

branch_name: refs/heads/main

languages: Markdown C

repo_language: Markdown


text:
<repo_name>ViAsmit/Blog-Django-React-<file_sep>/README.md
# YT-Django-DRF-Simple-Blog-Series-Simple-CRUD-Part-7

# Blog-Django-React
<file_sep>/Pipfile
[[source]]
url = "https://pypi.org/simple"
verify_ssl = true
name = "pypi"

[packages]
djangorestframework = "==3.11.1"
django-rest-knox = "*"
psycopg2-binary = "*"
django-heroku = "*"
gunicorn = "*"
whitenoise = "*"
asgiref = "==3.2.10"
django-cors-headers = "==3.5.0"
djangorestframework-simplejwt = "==4.6.0"
pytz = "==2020.1"
sqlparse = "==0.3.1"
Django = "==3.1.1"
PyJWT = "==1.7.1"
coreapi = "*"

[dev-packages]

[requires]
python_version = "3.8"
<file_sep>/build/precache-manifest.0a4d880032286e9a05c2fd75816fa7e5.js
self.__precacheManifest = (self.__precacheManifest || []).concat([
  {
    "revision": "38c3d6deab8bb0b30c23c2c3e101a652",
    "url": "/index.html"
  },
  {
    "revision": "9049e254ea496a621e92",
    "url": "/static/css/main.7f904051.chunk.css"
  },
  {
    "revision": "ca51f774a3087592bf2f",
    "url": "/static/js/2.ab849c25.chunk.js"
  },
  {
    "revision": "5e9b6f5c16b720e8a86875f97734673e",
    "url": "/static/js/2.ab849c25.chunk.js.LICENSE.txt"
  },
  {
    "revision": "9049e254ea496a621e92",
    "url": "/static/js/main.27d4ec1d.chunk.js"
  },
  {
    "revision": "b51f446d3a92a7eda648",
    "url": "/static/js/runtime-main.52f27345.js"
  }
]);

languages: Markdown TOML JavaScript

repo_name: ViAsmit/Blog-Django-React-


text:
<repo_name>jariiia/trustConfMaster<file_sep>/KendallTau.py
# -*- coding: utf-8; -*-
#
# This file contains an implementation of a generalised Kendall tau distance for partial rankings.
# The implementation follows the description in section 3.1 of the following article:
#
# <NAME>, et al. "Comparing and aggregating rankings with ties."
# Proceedings of the twenty-third ACM SIGMOD-SIGACT-SIGART symposium on Principles of database systems. ACM, 2004.
#

def rankingToBucketOrder(ranking):
    """
    :param ranking: A partial ranking defined as a list of tuples. The first element of the tuple is the item in
    the ranking, while the second element is the position of the element in the ranking. No ordering is assumed in
    the ranking.
    Example of partial ranking: [('a',1),('b',2),('c',1),('d',3),('e',2)]
    :return: A bucket order.
    """
    maxPosition = max([position for (item,position) in ranking])
    print "Max position:",maxPosition
    bucketOrder = [set() for i in range(maxPosition)]
    print "BucketOrder = ",bucketOrder
    for (item,position) in ranking:
        bucketOrder[position - 1].add(item)
    print "BucketOrder = ",bucketOrder
    return bucketOrder

def getBucketPosition(bucket,bucketOrder):
    if bucket in bucketOrder:
        bucketIndex = bucketOrder.index(bucket)
        total = (len(bucket) + 1) / 2.0
        for i in range(0,bucketIndex):
            total += len(bucketOrder[i])
        return total
    else:
        return -1

def getBucket(item,bucketOrder):
    for bucket in bucketOrder:
        if item in bucket:
            return bucket
    return set([])

def getItemPosition(item,bucketOrder):
    bucket = getBucket(item,bucketOrder)
    return getBucketPosition(bucket,bucketOrder)

def getPairs(domain):
    return [(x, y) for x in domain for y in domain if x != y and domain.index(x) < domain.index(y)]

def inSameBucket(i,j,bucketOrder):
    if getItemPosition(i,bucketOrder) == getItemPosition(j,bucketOrder):
        return True
    else:
        return False

def inSameOrder(i,j,bucketOrder1,bucketOrder2):
    iPositionInOrder1 = getItemPosition(i,bucketOrder1)
    jPositionInOrder1 = getItemPosition(j,bucketOrder1)
    iPositionInOrder2 = getItemPosition(i,bucketOrder2)
    jPositionInOrder2 = getItemPosition(j,bucketOrder2)
    return (iPositionInOrder1 > jPositionInOrder1 and iPositionInOrder2 > jPositionInOrder2) or (iPositionInOrder1 < jPositionInOrder1 and iPositionInOrder2 < jPositionInOrder2)

def kendallPairDistance(i,j,p,bucketOrder1,bucketOrder2):
    if not(inSameBucket(i,j,bucketOrder1)) and not(inSameBucket(i,j,bucketOrder2)):
        if inSameOrder(i,j,bucketOrder1,bucketOrder2):
            return 0
        else:
            return 1
    elif inSameBucket(i,j,bucketOrder1) and inSameBucket(i,j,bucketOrder2):
        return 0
    elif (inSameBucket(i,j,bucketOrder1) and not(inSameBucket(i,j,bucketOrder2))) or (not(inSameBucket(i,j,bucketOrder1)) and inSameBucket(i,j,bucketOrder2)):
        return p

def kendallDistance(p,domain,bucketOrder1,bucketOrder2):
    """
    This function computes the generalised Kendall tau distance for partial rankings
    :param p: penalty parameter
    :param domain: domain of the values ranked
    :param bucketOrder1: bucket order defining a partial ranking
    :param bucketOrder2: bucket order defining a partial ranking
    :return: Kendall tau distance
    """
    total = 0
    for (i,j) in getPairs(domain):
        total += kendallPairDistance(i,j,p,bucketOrder1,bucketOrder2)
    return total

if __name__ == "__main__":

    #
    # Examples
    #

    domain = ['a','b','c','d','e']

    bucketOrder1 = []
    bucketOrder2 = []
    bucketOrder3 = []
    bucketOrder4 = []
    bucketOrder5 = []
    bucketOrder6 = []

    bucket1 = set(['a', 'b'])
    bucket2 = set(['c'])
    bucket3 = set(['d','e'])

    bucket4 = set(['a'])
    bucket5 = set(['d','e'])
    bucket6 = set(['b','c'])

    bucket7 = set(['d','e'])
    bucket8 = set(['b','c'])
    bucket9 = set(['a'])

    bucket10 = set(['a'])
    bucket11 = set(['b'])
    bucket12 = set(['c'])
    bucket13 = set(['d'])
    bucket14 = set(['e'])

    bucketOrder1.append(bucket1)
    bucketOrder1.append(bucket2)
    bucketOrder1.append(bucket3)

    bucketOrder2.append(bucket4)
    bucketOrder2.append(bucket5)
    bucketOrder2.append(bucket6)

    bucketOrder3.append(bucket1)
    bucketOrder3.append(bucket2)
    bucketOrder3.append(bucket3)

    bucketOrder4.append(bucket7)
    bucketOrder4.append(bucket8)
    bucketOrder4.append(bucket9)

    bucketOrder5.append(bucket10)
    bucketOrder5.append(bucket11)
    bucketOrder5.append(bucket12)
    bucketOrder5.append(bucket13)
    bucketOrder5.append(bucket14)

    bucketOrder6.append(bucket12)
    bucketOrder6.append(bucket13)
    bucketOrder6.append(bucket10)
    bucketOrder6.append(bucket11)
    bucketOrder6.append(bucket14)

    # Test the generalised kendall distance for partial rankings

    print kendallDistance(0.5,domain,bucketOrder1,bucketOrder2)
    print kendallDistance(0.5,domain,bucketOrder1,bucketOrder3)
    print kendallDistance(0.5,domain,bucketOrder1,bucketOrder4)

    # Test the Kentall distance for "full" rankings (Wikipedia example)
    print kendallDistance(0.5,domain,bucketOrder5,bucketOrder6)

    # Using the ranking to bucket order function
    a = [('a',1),('b',2),('c',1),('d',3),('e',2)]
    b = [('a',2),('b',3),('c',3),('d',3),('e',1)]
    aBucketOrder = rankingToBucketOrder(a)
    bBucketOrder = rankingToBucketOrder(b)
    print kendallDistance(0.5,domain,aBucketOrder,bBucketOrder)<file_sep>/main.py
import numpy as np
import const
import heapq

# Define what to do when one or both opinions are undefined

def calculateSimilarity(x,y,d):
    return 0 if (x == np.inf or y == np.inf) else (1 - abs(x-y)/float(d))
   # return np.inf if (x == np.inf or y == np.inf) else abs(x-y)/float(d)

def calculateSimilarities(opinions,metaOpinions,domainSize):

    # Create similarity matrix as a 3-D array
    reviewers = opinions.shape[0]
    reviews = opinions.shape[1]
    similarity = np.zeros((reviewers,reviewers,reviews))
    for (i,j,p),value in np.ndenumerate(metaOpinions):
        if value == np.inf:
            # if o_i has no opinion about o_j's review for paper p, compute direct similarities between reviews
            s = calculateSimilarity(opinions[i,p],opinions[j,p],domainSize)
        else:
            # otherwise use the meta-opinion (normalised to be within [0..1])
            s = value /domainSize
        similarity[i,j,p] = s
    return similarity

def getPapersInCommon(opinions,i,j):
    commonReviews = opinions[i] + opinions[j]
    papersMask = (commonReviews != np.inf)
    arePapersInCommon = np.any(papersMask)
    return arePapersInCommon,papersMask

# The following function computes a trust graph value for two reviewers only if both wrote reviews for at least one common paper.

def initTrustGraph(trustGraph,similarities,opinions):
    for (i,j),value in np.ndenumerate(trustGraph):
        (papersInCommon,papersMask) = getPapersInCommon(opinions,i,j)
        # print (i,j),(papersInCommon,papersMask)
        if papersInCommon:
            trustGraph[i,j] = ((similarities[i,j,:] * papersMask).sum())/(papersMask[papersMask].size)
        else:
            trustGraph[i,j] = np.inf

# The following function builds a dictionary-based version of the trust graph so that the Dijkstra algorithm can operate more efficiently
# Obviously it can be embedded within the initTrustGraph function, but I keep it separate for the moment

def buildDictionaryTrustGraph(trustGraph):
    # Create dictionary to keep the list of edges
    reviewers = trustGraph.shape[0]
    dictTrustGraph = {key: {} for key in range(reviewers)}

    for (i,j),value in np.ndenumerate(trustGraph):
        if value != np.inf and i != j:
            (dictTrustGraph[i])[j] = value

    return dictTrustGraph

def largestValue(graph, start, end):
    """
    This function adapts the Dijkstra algorithm to compute the largest value between two nodes start and end.
    We assume that the distance between two nodes in the graph is some similarity value within [0..1].
    We compute the cost between two given nodes as a product of the distances between the nodes for a path connecting the two nodes.
    This implementation benefits from using a heap (a binary tree) for efficiency purposes.
    Since a push operation inserts the smallest value at the head of the heap, we invert costs when computing a path's cost.
    Instead of maximising cost, we minimise 1/cost, which is equivalent.
    """
    queue = [(1.0, start, [])]
    seen = set()
    while True:
        (cost, node, path) = heapq.heappop(queue)
        if node not in seen:
            path = path + [node]
            seen.add(node)
            if node == end:
                # Print for debugging purposes
                # print "Returning ", 1.0/cost, path
                # There is a sanity check to consider if the total path cost is infinite (it can be removed though)
                pathCost = 1.0/cost if cost!= np.inf else 0
                return pathCost,path
            for (neighbour, neighbourCost) in graph[node].iteritems():
                # Print for debugging purposes
                # print "From ", node, " to ", neighbour,": ", cost * 1.0/neighbour, ", Path: ", path
                # There is a sanity check to consider if neighbourCost is zero (it can be removed though)
                pathCost = cost * 1.0/neighbourCost if cost else np.inf
                heapq.heappush(queue, (pathCost, neighbour, path))

# The following function fills out the trust graph for those reviewers that did not review any paper together

def fillOutTrustGraph(trustGraph,dictTrustGraph):
    for (i,j),value in np.ndenumerate(trustGraph):
        if value == np.inf:
            largestCost, path = largestValue(dictTrustGraph,i,j)
            trustGraph[i,j] = largestCost

if __name__ == "__main__":

    #
    # INITIALISE DATA STRUCTURES
    #
    # Observations about papers
    # x dimension stands for observer
    # y dimension stands for paper

    observations = np.array([[np.inf,np.inf,10],[4,np.inf,5],[7,10,np.inf]])

    # Opinions range from 0 to 10
    # The following constant is employed for normalization purposes

    const.DOMAIN_SIZE = 10

    # Defining example 3-D matrix opinions about opinions

    # Example: No opinions about opinions

    opinionsOpinions = np.array([[[ 10,  10,  10],
            [ np.inf,  np.inf,  np.inf],
            [ np.inf,  np.inf,  np.inf]],
           [[ np.inf, np.inf, np.inf],
            [10, 10, 10],
            [np.inf, np.inf, np.inf]],
           [[np.inf, np.inf, np.inf],
            [np.inf, np.inf, np.inf],
            [10, 10, 10]]])

    # opinionsOpinions = np.array([[[ 10,  10,  10],
    #         [ np.inf,  np.inf,  np.inf],
    #         [ np.inf,  0,  3]],
    #        [[ np.inf, np.inf, 1],
    #         [10, 10, 10],
    #         [4, np.inf, 7]],
    #        [[np.inf, 0, 2],
    #         [6, np.inf, 6],
    #         [10, 10, 10]]])

    # obtaining i's opinions about j regarding all papers

    #print opinionsOpinions[i,j,:]

    # Example to test function longestPath

    # G = {'s':{'u':0.1, 'x':0.5}, 'u':{'v':0.1, 'x':0.2}, 'v':{'y':0.4}, 'x':{'u':0.3, 'v':0.9, 'y':0.2}, 'y':{'s':0.7, 'v':0.6}}

    # print longestPath(G,'s','y')

    # COMPUTE TRUST GRAPH

    # 1. Compute similarity matrix
    similarities = calculateSimilarities(observations,opinionsOpinions,const.DOMAIN_SIZE)
    print "\nSimilarity matrix\n"
    print similarities

    # 2. Initialise trust graph
    reviewers = observations.shape[0]
    trustGraph = np.ones((reviewers,reviewers)) * np.inf
    initTrustGraph(trustGraph,similarities,observations)
    print "\nInitial trust graph:\n"
    print trustGraph

    dictTrustGraph = buildDictionaryTrustGraph(trustGraph)
    print "\nDictionary-based representation of the trust graph:\n"
    print dictTrustGraph

    # 3. Fill out the rest of the trust graph by calling Dijkstra
    fillOutTrustGraph(trustGraph,dictTrustGraph)
    print "\nFinal contents of the trust graph:\n"
    print trustGraph

repo_language: Python

repo_name: jariiia/trustConfMaster


text:
<repo_name>ISO-B/ZiGate<file_sep>/interface.py
#! /usr/bin/python3
import serial
import threading
from binascii import (hexlify, unhexlify)
from time import (sleep, strftime)
from collections import OrderedDict

CLUSTERS = {b'0000':'General: Basic',
            b'0001':'General: Power Config',
            b'0002':'General: Temperature Config',
            b'0003':'General: Identify',
            b'0004':'General: Groups',
            b'0005':'General: Scenes',
            b'0006':'General: On/Off',
            b'0007':'General: On/Off Config',
            b'0008':'General: Level Control',
            b'0009':'General: Alarms',
            b'000A':'General: Time',
            b'000F':'General: Binary Input Basic',
            b'0020':'General: Poll Control',
            b'0019':'General: OTA',
            b'0101':'General: Door Lock',
            b'0201':'HVAC: Thermostat',
            b'0202':'HVAC: Fan Control',
            b'0300':'Lighting: Color Control',
            b'0400':'Measurement: Illuminance',
            b'0402':'Measurement: Temperature',
            b'0403':'Measurement: Atmospheric Pressure',
            b'0405':'Measurement: Humidity',
            b'0406':'Measurement: Occupancy Sensing',
            b'0500':'Security & Safety: IAS Zone',
            b'0702':'Smart Energy: Metering',
            b'0B05':'Misc: Diagnostics',
            b'1000':'ZLL: Commissioning',
            b'FF01':'Xiaomi private',
            b'FF02':'Xiaomi private'
          }

LOG_LEVELS = ['Emergency', 'Alert', 'Critical', 'Error', 'Warning', 'Notice', 'Information', 'Debug']

class ZiGate():

    def __init__(self, device="/dev/ttyUSB0"):
        self.conn = serial.Serial(device, 115200, timeout=0)
        self.buffer = b''
        self.thread = threading.Thread(target=self.read_data).start()
        self.devices = {}

    @staticmethod
    def zigate_encode(data):
        """encode all characters < 0x02 to avoid """
        encoded = []
        for x in data:
            if x < 0x10:
                encoded.append(0x02)
                encoded.append(x ^ 0x10)
            else:
                encoded.append(x)

        return encoded

    @staticmethod
    def zigate_decode(data):
        """reverse of zigate_encode to get back the real message"""
        encoded = False
        decoded_data = b''

        def bxor_join(b1, b2):  # use xor for bytes
            parts = []
            for b1, b2 in zip(b1, b2):
                parts.append(bytes([b1 ^ b2]))
            return b''.join(parts)

        for x in data:
            if bytes([x]) == b'\x02':
                encoded = True
            elif encoded is True:
                encoded = False
                decoded_data += bxor_join(bytes([x]), b'\x10')
            else:
                decoded_data += bytes([x])

        return decoded_data

    @staticmethod
    def checksum(cmd, length, data):
        tmp = 0
        tmp ^= cmd[0]
        tmp ^= cmd[1]
        tmp ^= length[0]
        tmp ^= length[1]
        if data:
            for x in data:
                tmp ^= x

        return tmp

    def set_device_property(self, addr, property_id, property_data):
        """
        log property / attribute value in a device based dictionnary
        please note that short addr is not stable if device is reset (still have to find the unique ID)
        """
        if not addr in self.devices:
            self.devices[addr] = {}
        self.devices[addr][property_id] = property_data

    def read_data(self):
        """Read ZiGate output and split messages"""
        while True:
            bytesavailable = self.conn.inWaiting()
            if bytesavailable > 0:
                self.buffer += self.conn.read(bytesavailable)
                endpos = self.buffer.find(b'\x03')
                if endpos != -1:
                    startpos = self.buffer.find(b'\x01')
                    data_to_decode = self.zigate_decode(self.buffer[startpos + 1:endpos]) # stripping starting 0x01 & ending 0x03
                    self.interpret_data(data_to_decode)
                    print('  # encoded : ', hexlify(self.buffer[startpos:endpos + 1]))
                    print('  # decoded : 01', ' '.join([format(x, '02x') for x in data_to_decode]).upper(),'03')
                    print('  (@timestamp : ', strftime("%H:%M:%S"), ')')
                    self.buffer = self.buffer[endpos + 1:]

    def send_data(self, cmd, data=""):
        """send data through ZiGate"""
        byte_cmd = bytes.fromhex(cmd)
        byte_data = bytes.fromhex(data)
        length = int(len(data)/2)
        byte_length = length.to_bytes(2, 'big')

        # --- non encoded version ---
        std_msg = [0x01]
        std_msg.extend(byte_cmd)
        std_msg.extend(byte_length)
        std_msg.append(self.checksum(byte_cmd, byte_length, byte_data))
        if data != "": std_msg.extend(byte_data)
        std_msg.append(0x03)

        # --- encoded version ---
        enc_msg = [0x01]
        enc_msg.extend(self.zigate_encode(byte_cmd))
        enc_msg.extend(self.zigate_encode(byte_length))
        enc_msg.append(self.checksum(byte_cmd, byte_length, byte_data))
        if data != "": enc_msg.extend(self.zigate_encode(byte_data))
        enc_msg.append(0x03)

        std_output = b''.join([bytes([x]) for x in std_msg])
        encoded_output = b''.join([bytes([x]) for x in enc_msg])
        print('--------------------------------------')
        print('REQUEST      : ', cmd, " ", data)
        print('  # standard : ', ' '.join([format(x, '02x') for x in std_output]).upper())
        print('  # encoded  : ', hexlify(encoded_output))
        print('(timestamp : ', strftime("%H:%M:%S"), ')')
        print('--------------------------------------')
        self.conn.write(encoded_output)

    @staticmethod
    def decode_struct(struct, msg):
        output = OrderedDict()
        while struct:
            key, elt_type = struct.popitem(last=False)
            # uint_8, 16, 32, 64 ... or predefined byte length
            if type(elt_type) == int:
                length = int(elt_type / 8)
                output[key] = hexlify(msg[:length])
                msg = msg[length:]
            # int (1 ou 2 bytes)
            elif elt_type in ('int', 'int8', 'int16'):
                if elt_type == 'int16':
                    index = 2
                else:
                    index = 1
                output[key] = int(hexlify(msg[:index]), 16)
                msg = msg[index:]
            # element gives length of next element in message (which could be raw)
            elif elt_type in ('len8', 'len16'):
                if elt_type == 'len16':
                    index = 2
                else:
                    index = 1
                length = int(hexlify(msg[0:index]), 16)
                output[key] = length
                msg = msg[index:]
                # let's get the next element
                key, elt_type = struct.popitem(last=False)
                if elt_type == 'raw':
                    output[key] = msg[:length]
                    msg = msg[length:]
                else:
                    output[key] = hexlify(msg[:length])
                    msg = msg[length:]
            # element gives number of next elements (which can be of a defined length)
            elif elt_type == 'count':
                count = int(hexlify(msg[:1]), 16)
                output[key] = count
                msg = msg[1:]
                # let's get the next element (list of elements referenced by the count)
                key, elt_type = struct.popitem(last=False)
                output[key] = []
                length = int(elt_type / 8)
                for i in range(count):
                    output[key].append(hexlify(msg[:length]))
                    msg = msg[length:]
            # remaining of the message
            elif elt_type == 'end':
                output[key] = hexlify(msg)
            # remaining of the message as raw data
            elif elt_type == 'rawend':
                output[key] = msg

        return output

    def interpret_data(self, data):
        """Interpret responses attributes"""
        msg_data = data[5:]
        msg_type = hexlify(data[0:2])

        # Do different things based on MsgType
        print('--------------------------------------')
        # Device Announce
        if msg_type == b'004d':
            struct = OrderedDict([('short_addr', 16), ('mac_addr', 64), ('mac_capability', 'rawend')])
            msg = self.decode_struct(struct, msg_data)

            self.set_device_property(msg['short_addr'], 'MAC', msg['mac_addr'])
            print('RESPONSE 004d : Device Announce')
            print('  * From address   : ', msg['short_addr'])
            print('  * MAC address    : ', msg['mac_addr'])
            print('  * MAC capability : ', msg['mac_capability'])

        # Status
        elif msg_type == b'8000':
            struct = OrderedDict([('status', 'int'), ('sequence', 8), ('packet_type', 16), ('info', 'rawend')])
            msg = self.decode_struct(struct, msg_data)

            if msg['status'] == 0:
                status_text = 'Success'
            elif msg['status'] == 1:
                status_text = 'Invalid parameters'
            elif msg['status'] == 2:
                status_text = 'Unhandled command'
            elif msg['status'] == 3:
                status_text = 'Command failed'
            elif msg['status'] == 4:
                status_text = 'Busy'
            elif msg['status'] == 5:
                status_text = 'Stack already started'
            elif msg['status'] >= 128:
                status_text = 'Failed with event code: %i' % msg['status']
            else:
                status_text = 'Unknown'

            print('RESPONSE 8000 : Status')
            print('  * Status              : ', status_text)
            print('  - Sequence            : ', msg['sequence'])
            print('  - Response to command : ', msg['packet_type'])
            if hexlify(msg['info']) != b'00':
                print('  - Additional msg: ', msg['info'])

        # Default Response
        elif msg_type == b'8001':
            struct = OrderedDict([('level', 'int'), ('info', 'rawend')])
            msg = self.decode_struct(struct, msg_data)

            print('RESPONSE 8001 : Log Message')
            print('  - Log Level : Log level ', LOG_LEVELS[msg['level']])
            print('  - Log Info  : ', msg['info'])

        # Version List
        elif msg_type == b'8010':
            struct = OrderedDict([('major', 'int16'), ('installer', 'int16')])
            msg = self.decode_struct(struct, msg_data)

            print('RESPONSE : Version List')
            print('  - Major version : ', msg['major'])
            print('  - Installer version : ', msg['installer'])

        # Node Descriptor
        elif msg_type == b'8042':
            struct = OrderedDict([('sequence', 8), ('status', 8), ('addr', 16), ('manufacturer_code', 16),
                                  ('max_rx', 16), ('max_tx', 16), ('server_mask', 16), ('descriptor_capability', 8),
                                  ('mac_flags', 8), ('max_buffer_size', 16), ('bit_field', 16),
                                  ])
            msg = self.decode_struct(struct, msg_data)

            server_mask_binary = format(int(msg['server_mask'], 16), '016b')
            descriptor_capability_binary = format(int(msg['descriptor_capability'], 16), '08b')
            mac_flags_binary = format(int(msg['mac_flags'], 16), '08b')
            bit_field_binary = format(int(msg['bit_field'], 16), '016b')

            server_mask_description = ['Primary trust center', 'Back up trust center', 'Primary binding cache',
                                       'Backup binding cache', 'Primary discovery cache', 'Backup discovery cache',
                                       'Network manager']  # Length 16, 7-15 Reserved
            descriptor_capability_description = ['Extended Active endpoint list',
                                                 'Extended simple descriptor list']  # Length 8, 2-7 Reserved
            mac_capability_description = ['Alternate PAN Coordinator', 'Device Type', 'Power source',
                                          'Receiver On when Idle', 'Reserved', 'Reserved', 'Security capability',
                                          'Allocate Address']  # Length 8
            bit_field_description = ['Logical type: Coordinator', 'Logical type: Router', 'Logical type: End Device',
                                     'Complex descriptor available', 'User descriptor available', 'Reserved',
                                     'Reserved', 'Reserved',
                                     'APS Flag', 'APS Flag', 'APS Flag', 'Frequency band', 'Frequency band',
                                     'Frequency band', 'Frequency band', 'Frequency band']  # Length 16

            print('RESPONSE 8042 : Node Descriptor')
            print('  - Sequence          : ', msg['sequence'])
            print('  - Status            : ', msg['status'])
            print('  - From address      : ', msg['addr'])
            print('  - Manufacturer code : ', msg['manufacturer_code'])
            print('  - Max Rx size       : ', msg['max_rx'])
            print('  - Max Tx size       : ', msg['max_tx'])
            print('  - Server mask       : ', msg['server_mask'])
            print('    - Binary          : ', server_mask_binary)
            for i, description in enumerate(server_mask_description, 1):
                print('    - %s : %s' % (description, 'Yes' if server_mask_binary[-i] == '1' else 'No'))
            print('  - Descriptor        : ', msg['descriptor_capability'])
            print('    - Binary          : ', descriptor_capability_binary)
            for i, description in enumerate(descriptor_capability_description, 1):
                print('    - %s : %s' % (description, 'Yes' if descriptor_capability_binary[-i] == '1' else 'No'))
            print('  - Mac flags         : ', msg['mac_flags'])
            print('    - Binary          : ', mac_flags_binary)
            for i, description in enumerate(mac_capability_description, 1):
                print('    - %s : %s' % (description, 'Yes' if mac_flags_binary[-i] == '1' else 'No'))
            print('  - Max buffer size   : ', msg['max_buffer_size'])
            print('  - Bit field         : ', msg['bit_field'])
            print('    - Binary          : ', bit_field_binary)
            for i, description in enumerate(bit_field_description, 1):
                print('    - %s : %s' % (description, 'Yes' if bit_field_binary[-i] == '1' else 'No'))

        # Cluster List
        elif msg_type == b'8043':
            struct = OrderedDict([('sequence', 8), ('status', 8), ('addr', 16), ('length', 8),
                                  ('endpoint', 8), ('profile', 16), ('device_id', 16), ('bit', 8),
                                  ('in_cluster_count', 'count'), ('in_cluster_list', 16),
                                  ('out_cluster_count', 'count'), ('out_cluster_list', 16),
                                  ])
            msg = self.decode_struct(struct, msg_data)

            print('RESPONSE 8043 : Cluster List')
            print('  - Sequence          : ', msg['sequence'])
            print('  - Status            : ', msg['status'])
            print('  - From address      : ', msg['addr'])
            print('  - Length            : ', msg['length'])
            print('  - EndPoint          : ', msg['endpoint'])
            print('  - Profile ID        : ', msg['profile'])
            print('  - Device ID         : ', msg['device_id'])
            print('  - IN cluster count  : ', msg['in_cluster_count'])
            for i, cluster_id in enumerate(msg['in_cluster_list']):
                print('    - Cluster %s : %s (%s)' % (i, cluster_id, CLUSTERS.get(cluster_id, 'unknown')))
            print('  - OUT cluster count  : ', msg['out_cluster_count'])
            for i, cluster_id in enumerate(msg['in_cluster_list']):
                print('    - Cluster %s : %s (%s)' % (i, cluster_id, CLUSTERS.get(cluster_id, 'unknown')))

        # Power Descriptor
        elif msg_type == b'8044':
            struct = OrderedDict([('sequence', 8), ('status', 8), ('bit_field', 16), ])
            msg = self.decode_struct(struct, msg_data)

            bit_field_binary = format(int(msg['bit_field'], 16), '016b')

            power_mode_description = {'0000': 'Receiver on when idle', '0001': 'Receiver switched on periodically',
                                      '0010': 'Receiver switched on when stimulated,'}  # Others Reserved
            power_sources = ['Permanent mains supply', 'Rechargeable battery', 'Disposable battery']  # 4th Reserved
            current_power_level = {'0000': 'Critically low', '0100': 'Approximately 33%', '1000': 'Approximately 66%',
                                   '1100': 'Approximately 100%'}

            print('RESPONSE 8044 : Power Descriptor')
            print('  - Sequence          : ', msg['sequence'])
            print('  - Status            : ', msg['status'])
            print('  - Bit field         : ', msg['bit_field'])
            print('    - Binary          : ', bit_field_binary)
            print('    - Current mode    : ', power_mode_description.get(bit_field_binary[-4:], 'Unknown'))
            print('    - Sources         : ')
            for i, description in enumerate(power_sources, 1):
                print('       - %s : %s %s' % (description, 'Yes' if bit_field_binary[8:12][-i] == '1' else 'No',
                                               '[CURRENT]' if bit_field_binary[4:8][-i] == '1' else ''))
            print('    - Level           : ', current_power_level.get(bit_field_binary[:4], 'Unknown'))

        # Endpoint List
        elif msg_type == b'8045':
            struct = OrderedDict([('sequence', 8), ('status', 8), ('addr', 16), ('endpoint_count', 'count'),
                                  ('endpoint_list', 8)
                                  ])
            msg = self.decode_struct(struct, msg_data)

            print('RESPONSE 8045 : Active Endpoints List')
            print('  - Sequence       : ', msg['sequence'])
            print('  - Status         : ', msg['status'])
            print('  - From address   : ', msg['addr'])
            print('  - EndPoint count : ', msg['endpoint_count'])
            for i, endpoint in enumerate(msg['endpoint_list']):
                print('    * EndPoint %s : %s' % (i, endpoint))

        # Default Response
        elif msg_type == b'8101':
            struct = OrderedDict([('sequence', 8), ('endpoint', 8), ('cluster', 16), ('command_id', 8),
                                  ('status', 8)
                                  ])
            msg = self.decode_struct(struct, msg_data)

            print('RESPONSE 8101 : Default Response')
            print('  - Sequence       : ', msg['sequence'])
            print('  - EndPoint       : ', msg['endpoint'])
            print('  - Cluster id     :  %s (%s)' % (msg['cluster'], CLUSTERS.get(msg['cluster'], 'unknown')))
            print('  - Command        : ', msg['command_id'])
            print('  - Status         : ', msg['status'])

        # Read attribute response, Attribute report, Write attribute response
        # Currently only support Xiaomi sensors. Other brands might calc things differently
        elif msg_type in (b'8100', b'8102', b'8110'):
            print('RESPONSE %s : Attribute Report / Response' % msg_type.decode())
            self.interpret_attribute(msg_data)

        # Route Discovery Confirmation
        elif msg_type == b'8701':
            print('RESPONSE 8701: Route Discovery Confirmation')
            print('  - Sequence       : ', hexlify(msg_data[:1]))
            print('  - Status         : ', hexlify(msg_data[1:2]))
            print('  - Network status : ', hexlify(msg_data[2:3]))
            print('  - Message data   : ', hexlify(msg_data))

        # No handling for this type of message
        else:
            print('RESPONSE %s : Unknown Message' % msg_type.decode())
            print('  - After decoding  : ', hexlify(data))
            print('  - MsgType         : ', msg_type)
            print('  - MsgLength       : ', hexlify(data[2:4]))
            print('  - ChkSum          : ', hexlify(data[4:5]))
            print('  - Data            : ', hexlify(msg_data))
            print('  - RSSI            : ', hexlify(data[-1:]))

    def interpret_attribute(self, msg_data):
        struct = OrderedDict([('sequence', 8),
                  ('short_addr', 16),
                  ('endpoint', 8),
                  ('cluster_id', 16),
                  ('attribute_id', 16),
                  ('attribute_status', 8),
                  ('attribute_type', 8),
                  ('attribute_size', 'len16'),
                  ('attribute_data', 'raw'),
                  ('end', 'rawend')
                 ])
        msg = self.decode_struct(struct, msg_data)
        device_addr = msg['short_addr']
        cluster_id = msg['cluster_id']
        attribute_id = msg['attribute_id']
        attribute_size = msg['attribute_size']
        attribute_data = msg['attribute_data']
        self.set_device_property(device_addr, (cluster_id, attribute_id), attribute_data)  # register tech value
        self.set_device_property(device_addr, 'Last seen', strftime('%Y-%m-%d %H:%M:%S'))

        if msg['sequence'] == b'00':
            print('  - Sensor type announce (Start after pairing 1)')
        elif msg['sequence'] == b'01':
            print('  - Something announce (Start after pairing 2)')

        # Device type
        if cluster_id == b'0000':
            if attribute_id == b'0005':
                self.set_device_property(device_addr, 'Type', attribute_data)
                print(' * type : ', attribute_data)
        # Button status
        elif cluster_id == b'0006':
            print('  * General: On/Off')
            if attribute_id == b'0000':
                if attribute_data == b'00':
                    print('  * Closed/Taken off/Press')
                else:
                    print('  * Open/Release button')
            elif attribute_id == b'8000':
                print('  * Multi click')
                print('  * Pressed: ', int(hexlify(attribute_data), 16), ' times')
        # Movement
        elif cluster_id == b'000c':  # Unknown cluster id
            print('  * Rotation horizontal')
        elif cluster_id == b'0012':  # Unknown cluster id
            if attribute_id == b'0055':
                if attribute_data == b'0000':
                    print('  * Shaking')
                elif attribute_data == b'0055':
                    print('  * Rotating vertical')
                    print('  * Rotated: ', int(hexlify(attribute_data), 16), '°')
                elif attribute_data == b'0103':
                    print('  * Sliding')
        # Temperature
        elif cluster_id == b'0402':
            temperature = int(hexlify(attribute_data), 16) / 100
            self.set_device_property(device_addr, 'Temperature', temperature)
            print('  * Measurement: Temperature'),
            print('  * Value: ', temperature, '°C')
        # Atmospheric Pressure
        elif cluster_id == b'0403':
            print('  * Atmospheric pressure')
            pressure = int(hexlify(attribute_data), 16)
            if attribute_id == b'0000':
                self.set_device_property(device_addr, 'Pressure', pressure)
                print('  * Value: ', pressure, 'mb')
            elif attribute_id == b'0010':
                self.set_device_property(device_addr, 'Pressure - detailed', pressure/10)
                print('  * Value: ', pressure/10, 'mb')
            elif attribute_id == b'0014':
                print('  * Value unknown')
        # Humidity
        elif cluster_id == b'0405':
            humidity = int(hexlify(attribute_data), 16) / 100
            self.set_device_property(device_addr, 'Humidity', humidity)
            print('  * Measurement: Humidity')
            print('  * Value: ', humidity, '%')
        # Presence Detection
        elif cluster_id == b'0406':
            print('   * Presence detection')  # Only sent when movement is detected

        print('  FROM ADDRESS      : ', msg['short_addr'])
        print('  - Source EndPoint : ', msg['endpoint'])
        print('  - Cluster ID      : ', msg['cluster_id'])
        print('  - Attribute ID    : ', msg['attribute_id'])
        print('  - Attribute type  : ', msg['attribute_type'])
        print('  - Attribute size  : ', msg['attribute_size'])
        print('  - Attribute data  : ', hexlify(msg['attribute_data']))

    def list_devices(self):
        print('-- DEVICE REPORT -------------------------')
        for addr in self.devices.keys():
            print('- addr : ', addr)
            for k,v in self.devices[addr].items():
                if type(k) is tuple:
                    print('    * ', k, ' : ', v,' (',CLUSTERS[k[0]],')')
                else:
                    print('    * ', k, ' : ', v)
        print('-- DEVICE REPORT - END -------------------')

if __name__ == "__main__":
    zigate = ZiGate()

repo_name: ISO-B/ZiGate


text:
<file_sep># EVE-help
eve欧服新手帮助工具

repo_name: tinykerman/EVE-help


text:
<repo_name>cormerao/limitless<file_sep>/homework-4/datepicker.js
(function(){
    'use strict';

    var datepicker = document.getElementById('datepicker-ui');
    var today;
    var monthIndex;
    var year;
    var months = new Array();

    function init() {
        today = new Date();
        monthIndex = today.getMonth();
        year = today.getFullYear();
        months[0] = "January";
        months[1] = "February";
        months[2] = "March";
        months[3] = "April";
        months[4] = "May";
        months[5] = "June";
        months[6] = "July";
        months[7] = "August";
        months[8] = "September";
        months[9] = "October";
        months[10] = "November";
        months[11] = "December";

        var nextMonth = document.createElement('div');
        nextMonth.innerHTML = ">";
        nextMonth.className = 'next-month';
        nextMonth.onclick = function() {
            incrementMonth();
        };
        datepicker.appendChild(nextMonth);

        var previousMonth = document.createElement('div');
        previousMonth.innerHTML = "<";
        previousMonth.className = 'previous-month';
        previousMonth.onclick = function() {
            decrementMonth();
        };
        datepicker.appendChild(nextMonth);
    }

    function incrementMonth() {
        monthIndex++;
        if (monthIndex > 11) {
            monthIndex = 0;
            year++;
        }
        displayDatepicker();
    }

    function decrementMonth() {
        monthIndex--;
        if (monthIndex < 0) {
            monthIndex = 11;
            year--;
        }
        displayDatepicker();
    }

    function displayDatepicker() {
        datepicker.innerHTML = months[monthIndex] + " " + year;
    }

    var d = new Date();
    var currentDate = {
        currentMonth: 12,
        currentYear: 2016

    };

    // var displayDatepicker = function() {
    //     var input = document.getElementById('datepicker');
    //     var datepicker = document.getElementById('datepicker-ui');
    //     input.onfocus = function() {
    //         datepicker.style.display = 'block';
    //     };
    //     input.addEventListener("focusout", function() {
    //         datepicker.style.display = 'none';
    //     });
    // };

    // displayDatepicker();

    init();
    displayDatepicker();

})();<file_sep>/README.md
-- Limitless work group --

All my homework assignments and session notes
- written in JavaScript

Author: <NAME><file_sep>/homework-6/homework-6.js
(function(){
    'use strict';

    var displayDomElementsControl = {
        genRandom: function(min, max) {
        	return Math.floor(Math.random() * (max - min + 1)) + min;
        },

        randomStringGen: function(minLength, maxLength) {
            var randomString = "";
            var charSet = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789.-_";
            var stringLength = this.genRandom(minLength, maxLength);

            for(var i = 0; i < stringLength; i++) {
                randomString += charSet.charAt(Math.floor(Math.random() * charSet.length));
            }

            return randomString;
        },

        randomStringArrayGen: function(arraySize, minLength, maxLength) {
            var stringArray = new Array(arraySize);

            for (var i = 0; i < arraySize; i++) {
                stringArray[i] = this.randomStringGen(minLength, maxLength);
            }

            return stringArray;
        },

        displayDomElements: function() {
            var array = this.randomStringArrayGen(200, 20, 35);
            var me = this;
            array.forEach(function(randomString) {
                me.addDomElement(randomString);
            });
        },

        addDomElement: function(randomString) {
            var ele = document.createElement('div');
            ele.innerHTML = randomString;
            ele.className = 'll-homework';
            document.getElementsByClassName("app__display")[0].appendChild(ele);
        }
    };

    var inputFilterControl = {

        ele: null,
        displayEle: null,

        init: function() {
            this.initEle();
            this.initEvent();
        },

        initEle: function() {
            this.displayEle = document.querySelector('.app__display');
            this.ele = document.querySelector('.js-test');
        },

        initEvent: function() {
            var me = this;
            me.ele.addEventListener('keyup', me.updateDisplayEle.bind(me, me.ele));
            me.ele.onpaste =  me.updateDisplayEle.bind(me, me.ele);
        },

        updateDisplayEle: function(input, event) {
            var value = input.value;
            this.filterElements(value);
        },

        filterElements: function(input) {
            var arr = document.querySelectorAll('.ll-homework, .filtered-out');

            var length = arr.length;
            for (var i = 0; i < length; i++) {
                arr[i].innerHTML = arr[i].innerHTML.replace(/<mark>|<\/mark>/g, "");
                if (!arr[i].innerText.includes(input)){
                    arr[i].className = "filtered-out";
                }
                else {
                    arr[i].className = "ll-homework";
                    arr[i].innerHTML = arr[i].innerHTML.replace(input, "<mark>"+input+"</mark>");
                }
            }
        }
    };

    displayDomElementsControl.displayDomElements();
    inputFilterControl.init();

})();<file_sep>/homework-3/homework-3.js
(function(){
    'use strict';

    var arrayToFilter = [];
    var filteredArray = [];

    function genRandom(min, max) {
    	return Math.floor(Math.random() * (max - min + 1)) + min;
    }

    function randomStringGen(minLength, maxLength) {
        var randomString = "";
        var charSet = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789.-_";
        var stringLength = genRandom(minLength, maxLength);

        for(var i = 0; i < stringLength; i++) {
            randomString += charSet.charAt(Math.floor(Math.random() * charSet.length));
        }

        return randomString;
    }

    function randomStringArrayGen(arraySize, minLength, maxLength) {
        var stringArray = new Array(arraySize);

        for (var i = 0; i < arraySize; i++) {
            stringArray[i] = randomStringGen(minLength, maxLength);
        }

        return stringArray;
    }

    function filterArray(arr) {
        return arr.filter(function(v) {
        	return v.match(/\d+/g) === null;
        });
    }

    function displayDomElements() {
        var array = randomStringArrayGen(300, 65, 80);
        array.forEach(function(randomString) {
            addDomElement(randomString);
        });
    }

    function addDomElement(randomString) {
        var ele = document.createElement('div');
        ele.innerHTML = randomString;
        ele.className = 'll-homework';
        document.body.appendChild(ele);

        var deleteSymbol = document.createElement('div');
        deleteSymbol.innerHTML = "❎";
        deleteSymbol.className = 'delete-symbol';
        deleteSymbol.onclick = function() {
            deleteElement(ele);
        };
        ele.appendChild(deleteSymbol);
    }

    function deleteElement(ele) {
        ele.parentElement.removeChild(ele);
    }

    console.log(randomStringGen(15, 25));                               // Exercise 1
    arrayToFilter = randomStringArrayGen(200, 25, 35);                  // Exercise 2
    filteredArray = filterArray(arrayToFilter);                         // Exercise 3
    console.log(filterArray(['ssfdds', 'adfd33dsf', '2ysdjlj', 'bb'])); // testing filterArray function
    displayDomElements();                                               // Exercise 4

})();<file_sep>/homework-5/homework-5.js
(function(){
    'use strict';

    var data = [
        {"Id":"1", "Name":"abc", "parent":""},
        {"Id":"2", "Name":"abc", "parent":"1"},
        {"Id":"3", "Name":"abc", "parent":"2"},
        {"Id":"4", "Name":"abc", "parent":"2"}
    ];

    function processData (data) {
        var processedData = {};
        var length = data.length;

        for (var i = 0; i < length; i++) {
            var children = [];

            for (var j = 0; j < length; j++) {
                if (data[i].Id === data[j].parent) {
                    children.push(data[j]);
                }
            }

            data[i].children = children;

            if (data[i].parent === "") processedData.root = data[i];
        }
        return processedData;
    }

    console.log(processData(data));

})();<file_sep>/Quicksort/quicksort.js
(function(){
    'use strict';

    var arr = [5, 8, 13, 11, 1, 6, 12, 3, 1, 5, 3, 9, 0, -1, 8, 12, 10, 7, 9, 2, 4];

    function quicksort(arr) {
        var object = partition(arr);

        if (object.left.length > 1) {
            object.left = quicksort(object.left);
        }

        if (object.right.length > 1) {
            object.right = quicksort(object.right);
        }

        return object.left.concat(object.equal).concat(object.right);
    }

    function partition(arr) {
        var size = arr.length;
        var pivot = arr[genRandomPivot(size)];
        var left = [];
        var right = [];
        var equal = [pivot];

        for (var i = 1; i < size; i++) {
            if (arr[i] < pivot) left.push(arr[i]);
            else if (arr[i] > pivot) right.push(arr[i]);
            else equal.push(arr[i]);
        }

        return {
            equal: equal,
            left: left,
            right: right
        };
    }

    function genRandomPivot(max) {
    	return Math.floor(Math.random() * (max - 1));
    }

    console.log(arr);
    console.log(quicksort(arr));

})();

languages: Markdown JavaScript

repo_name: cormerao/limitless