text:
import re;
import os;
import random;

class domesException(Exception):
    def __init__(self, value):
        self.value = value
    def __str__(self):
        return repr(self.value)

class Domes:

    def __init__(self, domesFile=None):

        self.domes = dict();
        self.file  = None;

        if domesFile != None:

            # save for later export
            self.file = domesFile;

            if os.path.isfile(domesFile):
                self.parseDomesFile(domesFile);

    def parseDomesFile(self,domesFile):

        # make sure the file exists before try to parse it
        if not os.path.isfile(domesFile):
            raise domesException("file "+domesFile+" does not exist");

        for line in open(domesFile,'r'):

            # remove the white spaces from both ends
            line = line.strip()

            # split the line into two parts (hopefully)
            lineParts = re.split('\W+',line)

            # check that the line is two parts
            if len(lineParts) != 2:
                os.sys.stderr.write("line: "+line+ " has invalid format and is being rejected\n")
                continue

            # assign the items
            stnId       = lineParts[0]
            domesNumber = lineParts[1].upper()

            self.addStnWithDomes(stnId, domesNumber);

    def size(self):
        return len(self.domes.keys());

    def containsStnId(self,stnId):
        return self.domes.has_key(stnId);

    def containsDomes(self, domesNumber):
        return domesNumber.upper() in self.domes.values();

    def generateDomesNumber(self):

        d5=  str(random.randint(0, 9)) \
           + str(random.randint(0, 9)) \
           + str(random.randint(0, 9)) \
           + str(random.randint(0, 9)) \
           + str(random.randint(0, 9));

        d = d5+"M"+"001";

        while self.containsDomes(d):

            d5=  str(random.randint(0, 9)) \
               + str(random.randint(0, 9)) \
               + str(random.randint(0, 9)) \
               + str(random.randint(0, 9)) \
               + str(random.randint(0, 9));

            d = d5+"M"+"001";

        return d;

    def addStn(self,stnId):

        if not self.containsStnId(stnId):
            self.domes[stnId] = self.generateDomesNumber();

        return stnId,self.domes[stnId]

    def addStnWithDomes(self,stnId,domesNumber):

        # make sure that the station does not already exist
        if self.containsStnId(stnId):
            raise domesException("stnId "+ stnId                   \
                                 + " already exists with DOMES# "  \
                                 + self.domesForStnId(stnId));

        # make sure that the domes number does not already exist
        if self.containsDomes(domesNumber):
            raise domesException("DOMES # "                     \
                                 +domesNumber+                  \
                                 " already exists for station " \
                                 + self.stnIdForDomes(domesNumber));

        self.domes[stnId] =  domesNumber;

    def stnIdForDomes(self,domesNumber):

        # do the reverse look up
        for k in self.domes.keys():
            if self.domes[k] == domesNumber:
                return k;

        return None;

    def domesForStnId(self,stnId):
        domes = None
        if self.domes.has_key(stnId):
            domes = self.domes[stnId];
        return domes

    def __iter__(self):
        for k in self.domes.keys():
            yield (k,self.domes[k])

    def export(self,exportPath=None):

        # make sure that there is some file to export to
        if self.file == None and exportPath == None:
            raise domesException(" no path for export");

        dst = None;
        if exportPath != None:
            dst = exportPath;
        else:
            dst = self.file;

        fid = open(dst,'w');

        for key in self.domes.keys():
            fid.write(key + " " + self.domes[key]+"\n");

        fid.close();

    def stn_list(self):
        return self.domes.keys()


text:
namespace JustBelot.Common
{
    using System;

    public class InvalidPlayerActionException : Exception
    {
        public InvalidPlayerActionException(IPlayer player, string message)
            : base(message)
        {
            this.Player = player;
        }

        public InvalidPlayerActionException(IPlayer player, string message, Exception innerException)
            : base(message, innerException)
        {
            this.Player = player;
        }

        public IPlayer Player { get; private set; }
    }
}

redpajama_set_name: RedPajamaGithub


text:
Kippt Export
===

A super simple Groovy process to export links from Kippt and prepare them for import into the new Google Bookmarks
Manager.

Prerequisites
===

**JDK**

This project requires Groovy.

Quick Use
===

    $ groovy KipptExport.groovy -u ajordens -a 5a57112xxxxxxxxxxxxxxxxxxxxxxxxxxxxxx004

Importing the resulting 'kippt-export-TIMESTAMP.html' into the Google Bookmarks Manager.

To Do
===

- Convert t.co links to their fully qualified equivalents (partially implemented).
- Support exporting nested groups of bookmarks from Kippt based on naming conventions.
- Pagination support (currently only import the first 200 links from each Kippt list).
- Avoid exporting links that have been previously imported in to the Google Bookmarks Manager.

Authors
===

Adam Jordens

Copyright and License
===

Copyright (C) 2014 Adam Jordens. Licensed under the MIT License.

See [LICENSE](https://raw.githubusercontent.com/ajordens/kippt-export/master/LICENSE) for more information.


text:
package def;
class Printer {
	public static String filename=System.currentTimeMillis()+".json";
	public static StringBuilder sb=new StringBuilder();
	public void println(Object str){
		System.out.println(str);
	}
	public void print(Object str){
		System.out.print(str);
	}
}


text:
package com.thinkinjava.holding;

import java.util.HashSet;
import java.util.LinkedHashSet;
import java.util.Random;
import java.util.Set;

public class SetOfInteger {
    public static void main(String[] args) {
        Random rand = new Random(47);
        Set<Integer> intSet = new LinkedHashSet<Integer>();
        for (int i = 0; i < 1000; i++) {
            intSet.add(rand.nextInt(40));
        }
        System.out.println(intSet);
    }
}


text: console.log("tests");


text:
require 'factory_bot'
FactoryBot.find_definitions
# for Spec expectation style
# class MiniTest::Test
# include FactoryGirl::Syntax::Methods
# end
module ActiveSupport
  class TestCase
    include FactoryBot::Syntax::Methods
  end
end


text:
module Poisol
  module ResponseMapper
    extend self

    def map webrick_request
      stub_request = get_stub_request webrick_request
      PoisolLog.info stub_request.to_s
      get_stub_response stub_request
    end

    def get_stub_request webrick_request
      stub_request = Request.new
      stub_request.type = webrick_request.request_method.downcase
      stub_request.url = webrick_request.request_uri.path
      stub_request.query = webrick_request.query_string
      stub_request.body = webrick_request.body
      stub_request
    end

    def get_stub_response stub_request
      stub = Stubs.get_match stub_request
      if stub.blank?
        log_error stub_request
        raise "No match found for request: #{stub_request.to_s} "
      end
      PoisolLog.info JSON.pretty_generate(stub.response.body)
      stub.response if stub.present?
    end

    def log_error request
      Kernel.puts request.to_s
      Kernel.puts "^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^No match found for above request"
      Kernel.puts "Registered requests are: #{Stubs.all.map{|stub| "\n#{stub.request.to_s}"}.join}\n--end--"
      PoisolLog.error "^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^No match found for above request"
      PoisolLog.error "Registered requests are: #{Stubs.all.map{|stub| "\n#{stub.request.to_s}"}.join}\n--end--"
    end

  end
end


text:
<?php
/**
 * Created by PhpStorm.
 * User: linyulin
 * Date: 17/4/24
 * Time: 上午11:08
 */

namespace Im050\WeChat\Collection;

use Illuminate\Support\Collection;
use Illuminate\Support\Str;
use Im050\WeChat\Collection\Element\MemberElement;

class ContactCollection extends Collection
{

    /**
     * 根据用户名获取具体联系人实例
     *
     * @param $username
     * @return MemberElement
     */
    public function getContactByUserName($username)
    {
        $member = @$this->offsetGet($username);
        if (!empty($member))
            return ContactFactory::create($member);
        else {
            try {
                $contact = $this->findContactFromAPI($username);
            } catch (\Exception $e) {
                app()->log->debug("find contact failed.", $e);
                return null;
            }
            if ($contact != null) {
                $this->put($username, $contact);
                return ContactFactory::create($contact);
            }
        }
        return null;
    }

    /**
     * 通过username获取成员详细信息
     *
     * @param $username
     * @return mixed|null
     */
    public function findContactFromAPI($username)
    {
        $data = app()->api->getBatchContact($username);
        $contactList = $data['ContactList'];
        if (!empty($contactList)) {
            return reset($contactList);
        } else {
            return null;
        }
    }

    /**
     * 根据字段搜索
     *
     * @param $field
     * @param $value
     * @param bool $blur
     * @return MemberElement|null
     */
    public function getContactByFields($field, $value, $blur = false)
    {
        $member = $this->find($value, $field, true, $blur);
        if (!empty($member)) {
            return ContactFactory::create($member);
        }
        return null;
    }

    /**
     * 根据微信账号获取具体联系人实例
     *
     * @param $alias
     * @param $blur
     * @return MemberElement|null
     */
    public function getContactByAlias($alias, $blur = false)
    {
        return $this->getContactByFields("Alias", $alias, $blur);
    }

    /**
     * 根据备注获取用户
     *
     * @param $remarkName
     * @param $blur
     * @return MemberElement|null
     */
    public function getContactByRemarkName($remarkName, $blur = false)
    {
        return $this->getContactByFields("RemarkName", $remarkName, $blur);
    }

    /**
     * 根据NickName获取群
     *
     * @param $nickName
     * @param $blur
     * @return MemberElement|null
     */
    public function getContactByNickName($nickName, $blur = false)
    {
        return $this->getContactByFields("NickName", $nickName, $blur);
    }

    /**
     * 获取女性联系人
     *
     * @return ContactCollection|mixed
     */
    public function getFemaleContacts()
    {
        return $this->find(2, 'Sex', false);
    }

    /**
     * 获取男性联系人
     *
     * @return ContactCollection|mixed
     */
    public function getMaleContacts()
    {
        return $this->find(1, 'Sex', false);
    }

    /**
     * 获取未知性别联系人
     *
     * @return ContactCollection|mixed
     */
    public function getUnknownSexContacts()
    {
        return $this->find(0, 'Sex', false);
    }

    /**
     * @param $search
     * @param $key
     * @param bool $first
     * @param bool $blur
     * @return mixed
     */
    public function find($search, $key, $first = false, $blur = false)
    {
        $objects = $this->filter(function ($item) use ($search, $key, $blur) {
            if (!isset($item[$key])) return false;
            if ($blur && Str::contains($item[$key], $search)) {
                return true;
            } elseif (!$blur && $item[$key] === $search) {
                return true;
            }
            return false;
        });

        return $first ? $objects->first() : $objects;
    }

    /**
     * 遍历元素
     *
     * @param callable $callback
     * @return $this
     */
    public function each(callable $callback)
    {
        foreach ($this->items as $key => $item) {
            if ($callback(ContactFactory::create($item), $key) === false) {
                break;
            }
        }
        return $this;
    }

}


text:
package main

import (
	"encoding/json"
	"flag"
	"fmt"
	"github.com/prometheus/client_golang/prometheus"
	"github.com/prometheus/client_golang/prometheus/promhttp"
	"github.com/takama/daemon"
	"log"
	"net/http"
	"os"
	"os/signal"
	"syscall"
	"time"
)

// #include <wiringPi.h>
// #cgo LDFLAGS: -lwiringPi
import "C"

// Initialize Prometheus metrics.
var (
	currentTemp = prometheus.NewGauge(prometheus.GaugeOpts{
		Name: "current_temp",
		Help: "Current CPU temp.",
	})

	totalFanOnTime = prometheus.NewCounterVec(
		prometheus.CounterOpts{
			Name: "total_fan_on_time",
			Help: "Total fan run time.",
		},
		[]string{"all"},
	)

	totalUptime = prometheus.NewCounterVec(
		prometheus.CounterOpts{
			Name: "total_uptime",
			Help: "Total uptime.",
		},
		[]string{"all"},
	)
)

const (
	// CPU temperature target, degrees C
	defaultTempTarget = 50.
	hysteresis        = float32(1.)

	pwmClockDivisor = 100

	/* Minimum duty cycle is the point below which the fan does
	/* not spin. This depends on both your fan and the switching
	/* transistor used. */
	defaultPwmDutyMin = 1
	pwmDutyMax        = 10

	// Temperature at which we give up attempting active fan speed control and set it to full speed.
	failsafeTemp = 65

	// how often to update
	delaySeconds = 30

	// GPIO-1/BCM "18"/Pin 12 on a Raspberry Pi 3
	defaultPin = 1

	// name of the service
	name        = "fancontrol"
	description = "cooling fan speed control based on CPU temperature"

	// Address on which daemon should be listen.
	addr = ":9977"
)

type FanControl struct {
	TempTarget     float32
	TempCurrent    float32
	PWMDutyMin     int
	PWMDutyMax     int
	PWMDutyCurrent int
	PWMPin         int
}

var myFanControl FanControl

var stdlog, errlog *log.Logger

func updateStats() {
	updateTicker := time.NewTicker(1 * time.Second)
	for {
		<-updateTicker.C
		totalUptime.With(prometheus.Labels{"all": "all"}).Inc()
		currentTemp.Set(float64(myFanControl.TempCurrent))
		if myFanControl.PWMDutyCurrent > 0 {
			totalFanOnTime.With(prometheus.Labels{"all": "all"}).Inc()
		}
	}
}

func fanControl() {
	prometheus.MustRegister(currentTemp)
	prometheus.MustRegister(totalFanOnTime)
	prometheus.MustRegister(totalUptime)

	go updateStats()

	cPin := C.int(myFanControl.PWMPin)

	C.wiringPiSetup()

	// Power on "test". Allows the user to verify that their fan is working.
	C.pinMode(cPin, C.OUTPUT)
	C.digitalWrite(cPin, C.HIGH)
	time.Sleep(5 * time.Second)
	C.digitalWrite(cPin, C.LOW)

	C.pwmSetMode(C.PWM_MODE_MS)
	C.pinMode(cPin, C.PWM_OUTPUT)
	C.pwmSetRange(C.uint(myFanControl.PWMDutyMax))
	C.pwmSetClock(pwmClockDivisor)
	C.pwmWrite(cPin, C.int(myFanControl.PWMDutyMin))
	myFanControl.TempCurrent = 0
	go cpuTempMonitor(func(cpuTemp float32) {
		if isCPUTempValid(cpuTemp) {
			myFanControl.TempCurrent = cpuTemp
		}
	})

	myFanControl.PWMDutyCurrent = 0

	delay := time.NewTicker(delaySeconds * time.Second)

	for {
		if myFanControl.TempCurrent > (myFanControl.TempTarget + hysteresis) {
			myFanControl.PWMDutyCurrent = iMax(iMin(myFanControl.PWMDutyMax, myFanControl.PWMDutyCurrent+1), myFanControl.PWMDutyMin)
		} else if myFanControl.TempCurrent < (myFanControl.TempTarget - hysteresis) {
			myFanControl.PWMDutyCurrent = iMax(myFanControl.PWMDutyCurrent-1, 0)
			if myFanControl.PWMDutyCurrent < myFanControl.PWMDutyMin {
				myFanControl.PWMDutyCurrent = 0
			}
		}
		//log.Println(myFanControl.TempCurrent, " ", myFanControl.PWMDutyCurrent)
		C.pwmWrite(cPin, C.int(myFanControl.PWMDutyCurrent))
		<-delay.C
		if myFanControl.PWMDutyCurrent == myFanControl.PWMDutyMax && myFanControl.TempCurrent >= failsafeTemp {
			// Reached the maximum temperature. We stop using PWM control and set the fan to "on" permanently.
			break
		}
	}

	// Default to "ON".
	C.pinMode(cPin, C.OUTPUT)
	C.digitalWrite(cPin, C.HIGH)
}

// Service has embedded daemon
type Service struct {
	daemon.Daemon
}

// Manage by daemon commands or run the daemon
func (service *Service) Manage() (string, error) {

	tempTarget := flag.Float64("temp", defaultTempTarget, "Target CPU Temperature, degrees C")
	pwmDutyMin := flag.Int("minduty", defaultPwmDutyMin, "Minimum PWM duty cycle")
	pin := flag.Int("pin", defaultPin, "PWM pin (wiringPi numbering)")
	flag.Parse()

	usage := "Usage: " + name + " install | remove | start | stop | status"
	// if received any kind of command, do it
	if flag.NArg() > 0 {
		command := os.Args[flag.NFlag()+1]
		switch command {
		case "install":
			return service.Install()
		case "remove":
			return service.Remove()
		case "start":
			return service.Start()
		case "stop":
			return service.Stop()
		case "status":
			return service.Status()
		default:
			return usage, nil
		}
	}

	myFanControl.TempTarget = float32(*tempTarget)
	myFanControl.PWMDutyMin = *pwmDutyMin
	myFanControl.PWMDutyMax = pwmDutyMax
	myFanControl.PWMPin = *pin

	go fanControl()

	// Set up channel on which to send signal notifications.
	// We must use a buffered channel or risk missing the signal
	// if we're not ready to receive when the signal is sent.
	interrupt := make(chan os.Signal, 1)
	signal.Notify(interrupt, os.Interrupt, os.Kill, syscall.SIGTERM)

	http.HandleFunc("/", handleStatusRequest)
	http.Handle("/metrics", promhttp.Handler())
	http.ListenAndServe(addr, nil)

	// interrupt by system signal
	for {
		killSignal := <-interrupt
		stdlog.Println("Got signal:", killSignal)
		if killSignal == os.Interrupt {
			return "Daemon was interrupted by system signal", nil
		}
		return "Daemon was killed", nil
	}
}

func handleStatusRequest(w http.ResponseWriter, r *http.Request) {
	statusJSON, _ := json.Marshal(&myFanControl)
	w.Write(statusJSON)
}

func init() {
	stdlog = log.New(os.Stdout, "", 0)
	errlog = log.New(os.Stderr, "", 0)
}

func main() {
	srv, err := daemon.New(name, description, []string{}...)
	if err != nil {
		errlog.Println("Error: ", err)
		os.Exit(1)
	}
	service := &Service{srv}
	status, err := service.Manage()
	if err != nil {
		errlog.Println(status, "\nError: ", err)
		os.Exit(1)
	}
	fmt.Println(status)
}


text:
require 'rails_helper'

RSpec.describe AssignmentsController, type: :controller do
  let(:responding_team)       { accepted_case.responding_team }
  let(:responder)             { responding_team.responders.first }
  let(:another_responder)     { create :responder, responding_teams: [responding_team] }

  let(:accepted_case)         { create :accepted_case }

  let(:assignment)            { accepted_case.responder_assignment }

  let(:service)               { instance_double UserReassignmentService }

  let(:params)                { { case_id: accepted_case.id,
                                   id: assignment.id,
                                   assignment: {
                                     user_id: another_responder.id
                                   }
                                 } }

  describe 'PATCH execute_reassign_user' do
    before(:each) do
      sign_in responder

      allow(UserReassignmentService).to receive(:new).and_return(service)
      allow(service).to receive(:call).and_return(:ok)
    end

    it 'authorises' do
      expect {
        patch :execute_reassign_user, params: params
      } .to require_permission(:assignments_execute_reassign_user?)
              .with_args(responder, accepted_case)
    end

    context 'foi case' do
      it 'calls UserReassignmentService' do
        patch :execute_reassign_user, params: params
        expect(UserReassignmentService).to have_received(:new).with(
                                             acting_user: responder,
                                             target_user: another_responder,
                                             assignment: assignment
                                           )
        expect(service).to have_received(:call)
      end

      it 'redirects to new_user_session_path' do
        patch :execute_reassign_user, params: params
        expect(response).to redirect_to case_path(id: accepted_case.id)
      end
    end

    context 'foi ico case' do
      let(:accepted_ico_foi_case) { create :accepted_ico_foi_case, responding_team: responding_team }
      let(:assignment)            { accepted_ico_foi_case.responder_assignment }
      let(:params)                { { case_id: accepted_ico_foi_case.id,
                                       id: assignment.id,
                                       assignment: {
                                         user_id: another_responder.id
                                       }
                                     } }

      it 'calls UserReassignmentService' do
        patch :execute_reassign_user, params: params
        expect(UserReassignmentService).to have_received(:new).with(
                                             acting_user: responder,
                                             target_user: another_responder,
                                             assignment: assignment
                                           )
        expect(service).to have_received(:call)
      end

      it 'redirects to new_user_session_path' do
        patch :execute_reassign_user, params: params
        expect(response).to redirect_to case_path(id: accepted_ico_foi_case.id)
      end
    end

    context 'offender sar complaint case' do
      let(:accepted_complaint_case) { create :accepted_complaint_case }
      let(:responding_team)         { accepted_complaint_case.responding_team }
      let(:responder)               { responding_team.responders.first }
      let(:another_responder)       { create :responder, responding_teams: [responding_team] }
      let(:assignment)              { accepted_complaint_case.responder_assignment }
      let(:params)                  { { case_id: accepted_complaint_case.id,
                                        id: assignment.id,
                                        assignment: {
                                          user_id: another_responder.id
                                        }
                                      } }

      it 'calls UserReassignmentService' do
        patch :execute_reassign_user, params: params
        expect(UserReassignmentService).to have_received(:new).with(
                                             acting_user: responder,
                                             target_user: another_responder,
                                             assignment: assignment
                                           )
        expect(service).to have_received(:call)
      end

      it 'redirects to new_user_session_path' do
        patch :execute_reassign_user, params: params
        expect(response).to redirect_to case_path(id: accepted_complaint_case.id)
      end
    end
  end
end


text:
import Mongoose = require('mongoose');
import * as Utils from "../core/metadata/utils";
import {searchUtils} from "../search/elasticSearchUtils";
var MongooseSchema = Mongoose.Schema;

export interface IMongooseSchemaOptions {
    options: Object,
    searchIndex: boolean;
}

class MongooseSchemaGenrator {
    createSchema(parsedSchema: any, mongooseOptions: IMongooseSchemaOptions): Object {
        var mongooseSchemaObj = new MongooseSchema(parsedSchema, mongooseOptions.options);
        if (mongooseOptions.searchIndex) {
            searchUtils.insertMongoosasticToSchema(mongooseSchemaObj);
        }
        return mongooseSchemaObj;
    }
}

export var schemaGenerator = new MongooseSchemaGenrator();


text:
ACCEPTED

#### According to
International Plant Names Index

#### Published in
null

#### Original name
Ocotea licanioides A.C.Sm.

### Remarks
null


text:
package org.jboss.sepro.service.ws;

import java.util.ArrayList;

import javax.annotation.Resource;
import javax.inject.Inject;
import javax.jws.HandlerChain;
import javax.jws.Oneway;
import javax.jws.WebMethod;
import javax.jws.WebService;
import javax.xml.namespace.QName;
import javax.xml.ws.BindingProvider;
import javax.xml.ws.WebServiceContext;
import javax.xml.ws.soap.Addressing;

import org.apache.cxf.headers.Header;
import org.apache.cxf.ws.addressing.impl.AddressingPropertiesImpl;
import org.jboss.sepro.service.IServiceLogger;
import org.jboss.sepro.service.ws.skeleton.AsyncEchoService;
import org.jboss.sepro.stereotype.WS;

@WebService(name = AsyncEcho.WS_NAME, serviceName = AsyncEcho.WS_SERVICE_NAME, targetNamespace = AsyncEcho.WS_NAMESPACE)
@HandlerChain(file = "/handler-chain.xml")
@Addressing
public class AsyncEcho {

    @Inject
    @WS
    IServiceLogger slogger;

    public final static String WS_NAME = "AsyncEcho";
    public final static String WS_SERVICE_NAME = "AsyncEchoService";
    public final static String WS_NAMESPACE = "http://sepro.jboss.org";

    @Resource
    private WebServiceContext context;

    @WebMethod
    @Oneway
    public void ping() {
        slogger.addServiceLog(getClass().getSimpleName(), "Ping");
        AddressingPropertiesImpl aprop = (AddressingPropertiesImpl) context.getMessageContext().get(
                "javax.xml.ws.addressing.context.inbound");
        if (aprop == null) {
            System.out.println("null");
            return;
        }
        String address = aprop.getReplyTo().getAddress().getValue();
        AsyncEchoService aes = new AsyncEchoService();
        org.jboss.sepro.service.ws.skeleton.AsyncEcho portType = aes.getAsyncEchoPort();

        BindingProvider provider = (BindingProvider) portType;
        provider.getRequestContext().put(BindingProvider.ENDPOINT_ADDRESS_PROPERTY, address);
        ArrayList<Header> headers = new ArrayList<Header>(1);
        headers.add(new Header(new QName("http://schemas.xmlsoap.org/ws/2004/08/addressing", "RelatesTo"), aprop
                .getMessageID().getValue()));
        provider.getResponseContext().put(Header.HEADER_LIST, headers);
        portType.callbackAsyncPing("asynchronous pong");
    }

    @WebMethod
    @Oneway
    public void callbackAsyncPing(String message) {

    }

}


text:
using System.Windows.Controls;
using System.Windows.Data;
using System;
using System.Windows;

namespace Xceed.Wpf.Toolkit.LiveExplorer.Samples.Zoombox.Views
{
  /// <summary>
  /// Interaction logic for ZoomboxView.xaml
  /// </summary>
  public partial class ZoomboxView : DemoView
  {
    public ZoomboxView()
    {
      InitializeComponent();
    }

    private void AdjustAnimationDuration( object sender, RoutedPropertyChangedEventArgs<double> e )
    {
      Slider slider = sender as Slider;
      if( slider == null )
        return;

      zoombox.AnimationDuration = System.TimeSpan.FromMilliseconds( slider.Value );
    }

    private void CoerceAnimationRatios( object sender, RoutedPropertyChangedEventArgs<double> e )
    {
      Slider slider = sender as Slider;
      if( slider == null )
        return;

      Slider otherRatio = ( sender == this.AccelerationSlider ) ? this.DecelerationSlider : this.AccelerationSlider;

      if( slider.Value + otherRatio.Value > 1 )
      {
        otherRatio.Value = 1 - slider.Value;
      }
    }
  }
}


text:
/**
 * Created by deepak.vishwakarma on 4/26/16.
 */
/*jslint browser: true*/
"use strict";
(function (window, d3) {
    function Utility() { // jshint ignore:line
    }
    Utility.prototype.defineReadonly = function defineReadonly(obj, key, value) {
        Object.defineProperty(obj, key, {
            configurable: true,
            value: value,
            writable: false
        });
    };
    //const utility = new Utility();
    var GraphNames;
    (function (GraphNames) {
        GraphNames[GraphNames.stacked = 1] = "stacked";
    })(GraphNames || (GraphNames = {}));
    function Stacked(options) {
        this.options = options;
        this.listeners = [];
    }
    Stacked.prototype.draw = function draw(updatedData){
        var that = this;
        var options = that.options;
        var defaults = DrawIt.defaults;
        var data = updatedData || options.data;
        var selector = options.selector;
        if(!selector || !data){
            throw "Missing data and selector";
        }
        var height = options.dim ? options.dim.height || defaults.height : defaults.height;
        var width = options.dim ? options.dim.width || defaults.width : defaults.width;
        var margin = {top: 20, right: 20, bottom: 30, left: 50};
        width = width - margin.left - margin.right;
        height = height - margin.top - margin.bottom;
        that.stack = d3.layout.stack()
            .values(function(d) { return d.values; })
            .x(function(d) { return new Date(Date.parse(d.date)); })
            .y(function(d) { return d.count; });

        var stacked = that.stack(data);
        that.maxY = d3.max(stacked, function(d) {
            return d3.max(d.values, function(d) {
                return d.y0 + d.y;
            });
        });
        that.yScale = d3.scale.linear()
            .range([height, 0])
            .domain([0, that.maxY]);
        that.xScale = d3.time.scale()
            .range([0, width])
            .domain(d3.extent(data[0].values, function(d) {
                return new Date(Date.parse(d.date));
            }))
            .nice(4);
        that.svg = d3.select("body").append(selector)
            .attr("width", width + margin.left + margin.right)
            .attr("height", height + margin.top + margin.bottom)
            .append("g")
            .attr("transform", "translate(" + margin.left + "," + margin.top + ")");
        that.colors = options.colors || d3.scale.category10();
        that.layers = that.svg.selectAll('g.layer')
            .data(stacked, function(d) { return d.name; })
            .enter()
            .append('g')
            .attr('class', 'layer')
            .attr('fill', function(d) { return that.colors(d.name); });
        that.layers.selectAll('rect')
            .data(function(d) { return d.values; })
            .enter()
            .append('rect')
            .attr('x', function(d) {return that.xScale(new Date(Date.parse(d.date))); })
            .attr('width', width / 3)
            .attr('y', function(d) {
                return that.yScale(d.y0 + d.y);
            }).attr('height', function(d) {
            return height - that.yScale(d.y);
        });
    };
    Stacked.prototype.on = function on(prop, event , callback){
        var that = this;
        if(typeof that[prop] === 'undefined'){
            throw "Event can\'t bind to "+prop;
        }
        that[prop].on(event, callback);
        var unbind = function () {
            console.log("Stopping listening events"+prop+":"+event);
            that[prop].on(event, null);  //this should remove the event listener
            that.listeners = that.listeners.filter(function (l){
                return l.id !== listener.id;
            });
        };
        var listener = {
            id:that.listeners.length,
            event:event,
            prop:prop,
            callback:callback,
            unbind:unbind
        };
        that.listeners.push(listener);
        return listener;
    };
    Stacked.prototype.unbind = function unbind(id){
        var listener = this.listeners[id];
        if(listener){
            console.log("Stopping listening events"+listener.prop+":"+listener.event);
            this[listener.prop].on(listener.event, null);  //this should remove the event listener
            this.listeners = this.listeners.filter(function (l){
                return l.id !== listener.id;
            });
        }
    };
    function DrawIt(options){
        var chart ;
        switch (options.type){
            case GraphNames.stacked:
                chart = new Stacked(options);
                break;
            default:
                throw "Invalid graph "+options.type;
        }
        return chart;
    }
    DrawIt.defaults = {
        height: 600,
        width: 600
    };
    DrawIt.GraphNames = GraphNames;
    if(window){
        window.DI = DrawIt;
        return window.DrawIt = DrawIt;
    }
    if(module){
        return module.exports = DrawIt;
    }
})(window, window.d3);


text:
// ----------------------------------------------------------------------------
// $Id: Properties.java,v 1.7 2004/01/14 23:17:42 rsdio Exp $
//
// Copyright (C) 2003, 2004 Free Software Foundation, Inc.
//
// This file is part of GNU Crypto.
//
// GNU Crypto is free software; you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation; either version 2, or (at your option)
// any later version.
//
// GNU Crypto is distributed in the hope that it will be useful, but
// WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
// General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program; see the file COPYING.  If not, write to the
//
//    Free Software Foundation Inc.,
//    59 Temple Place - Suite 330,
//    Boston, MA 02111-1307
//    USA
//
// Linking this library statically or dynamically with other modules is
// making a combined work based on this library.  Thus, the terms and
// conditions of the GNU General Public License cover the whole
// combination.
//
// As a special exception, the copyright holders of this library give
// you permission to link this library with independent modules to
// produce an executable, regardless of the license terms of these
// independent modules, and to copy and distribute the resulting
// executable under terms of your choice, provided that you also meet,
// for each linked independent module, the terms and conditions of the
// license of that module.  An independent module is a module which is
// not derived from or based on this library.  If you modify this
// library, you may extend this exception to your version of the
// library, but you are not obligated to do so.  If you do not wish to
// do so, delete this exception statement from your version.
// ----------------------------------------------------------------------------

import java.io.FileInputStream;
import java.io.IOException;
import java.io.PrintWriter;

import java.security.AccessController;
import java.security.PrivilegedAction;

import java.util.HashMap;
import java.util.PropertyPermission;

/**
 *
A global object containing build-specific properties that affect the
 * behaviour of the generated binaries from this library.

 *
 * @version $Revision: 1.7 $
 */
public final class Properties {

   // Debugging methods and variables
   // -------------------------------------------------------------------------

   private static final String NAME = "Properties";
   private static final boolean DEBUG = true;
//   private static final int debuglevel = 9;
   private static final PrintWriter err = new PrintWriter(System.out, true);
   private static void debug(final String s) {
      err.println(">>> "+NAME+": "+s);
   }

   // Constants and variables
   // -------------------------------------------------------------------------

   public static final String PROPERTIES_FILE = "gnu.crypto.properties.file";
   public static final String REPRODUCIBLE_PRNG = "gnu.crypto.with.reproducible.prng";
   public static final String CHECK_WEAK_KEYS = "gnu.crypto.with.check.for.weak.keys";
   public static final String DO_RSA_BLINDING = "gnu.crypto.with.rsa.blinding";

   private static final String TRUE = Boolean.TRUE.toString();
   private static final String FALSE = Boolean.FALSE.toString();
   private static final HashMap props = new HashMap();
   private static Properties singleton = null;

   private boolean reproducible = false;
   private boolean checkForWeakKeys = true;
   private boolean doRSABlinding = true;

   // Constructor(s)
   // -------------------------------------------------------------------------

   /** Trivial constructor to enforce Singleton pattern. */
   private Properties() {
      super();

      init();
   }

   // Class methods
   // -------------------------------------------------------------------------

   /**
    *
Returns the string representation of the library global configuration
    * property with the designated key.

    *
    * @param key the case-insensitive, non-null and non-empty name of a
    * configuration property.
    * @return the string representation of the designated property, or
    * null if such property is not yet set, or key is
    * empty.
    */
   public static synchronized final String getProperty(String key) {
      if (key == null) {
         return null;
      }
      SecurityManager sm = System.getSecurityManager();
      if (sm != null) {
         sm.checkPermission(new PropertyPermission(key, "read"));
      }
      key = key.trim().toLowerCase();
      if ("".equals(key)) {
         return null;
      }
      return (String) props.get(key);
   }

   /**
    *
Sets the value of a designated library global configuration property,
    * to a string representation of what should be a legal value.

    *
    * @param key the case-insensitive, non-null and non-empty name of a
    * configuration property.
    * @param value the non-null, non-empty string representation of a legal
    * value of the configuration property named by key.
    */
   public static synchronized final void setProperty(String key, String value) {
      if (key == null || value == null) {
         return;
      }
      key = key.trim().toLowerCase();
      if ("".equals(key)) {
         return;
      }
      value = value.trim();
      if ("".equals(value)) {
         return;
      }
      SecurityManager sm = System.getSecurityManager();
      if (sm != null) {
         sm.checkPermission(new PropertyPermission(key, "write"));
      }
      if (key.equals(REPRODUCIBLE_PRNG)
            && (value.equalsIgnoreCase(TRUE) || value.equalsIgnoreCase(FALSE))) {
         setReproducible(Boolean.valueOf(value).booleanValue());
      } else if (key.equals(CHECK_WEAK_KEYS)
            && (value.equalsIgnoreCase(TRUE) || value.equalsIgnoreCase(FALSE))) {
         setCheckForWeakKeys(Boolean.valueOf(value).booleanValue());
      } else if (key.equals(DO_RSA_BLINDING)
            && (value.equalsIgnoreCase(TRUE) || value.equalsIgnoreCase(FALSE))) {
         setDoRSABlinding(Boolean.valueOf(value).booleanValue());
      } else {
         props.put(key, value);
      }
   }

   /**
    *
A convenience method that returns, as a boolean, the library global
    * configuration property indicating if the default Pseudo Random Number
    * Generator produces, or not, the same bit stream when instantiated.

    *
    * @return true if the default PRNG produces the same bit stream
    * with every VM instance. Returns false if the default PRNG is
    * seeded with the time of day of its first invocation.
    */
   public static synchronized final boolean isReproducible() {
      SecurityManager sm = System.getSecurityManager();
      if (sm != null) {
         sm.checkPermission(new PropertyPermission(REPRODUCIBLE_PRNG, "read"));
      }
      return instance().reproducible;
   }

   /**
    *
A convenience method that returns, as a boolean, the library global
    * configuration property indicating if the implementations of symmetric
    * key block ciphers check, or not, for possible/potential weak and semi-weak
    * keys that may be produced in the course of generating round encryption
    * and/or decryption keys.

    *
    * @return true if the cipher implementations check for weak and
    * semi-weak keys. Returns false if the cipher implementations
    * do not check for weak or semi-weak keys.
    */
   public static synchronized final boolean checkForWeakKeys() {
      SecurityManager sm = System.getSecurityManager();
      if (sm != null) {
         sm.checkPermission(new PropertyPermission(CHECK_WEAK_KEYS, "read"));
      }
      return instance().checkForWeakKeys;
   }

   /**
    *
A convenience method that returns, as a boolean, the library global
    * configuration property indicating if RSA decryption (RSADP primitive),
    * does, or not, blinding against timing attacks.

    *
    * @return true if the RSA decryption primitive includes a
    * blinding operation. Returns false if the RSA decryption
    * primitive does not include the additional blinding operation.
    */
   public static synchronized final boolean doRSABlinding() {
      SecurityManager sm = System.getSecurityManager();
      if (sm != null) {
         sm.checkPermission(new PropertyPermission(DO_RSA_BLINDING, "read"));
      }
      return instance().doRSABlinding;
   }

   /**
    *
A convenience method to set the global property for reproducibility of
    * the default PRNG bit stream output.

    *
    * @param value if true then the default PRNG bit stream output
    * is the same with every invocation of the VM.
    */
   public static synchronized final void setReproducible(final boolean value) {
      SecurityManager sm = System.getSecurityManager();
      if (sm != null) {
         sm.checkPermission(new PropertyPermission(REPRODUCIBLE_PRNG, "write"));
      }
      instance().reproducible = value;
      props.put(REPRODUCIBLE_PRNG, String.valueOf(value));
   }

   /**
    *
A convenience method to set the global property for checking for weak
    * and semi-weak cipher keys.

    *
    * @param value if true then the cipher implementations will
    * invoke additional checks for weak and semi-weak key values that may get
    * generated.
    */
   public static synchronized final void setCheckForWeakKeys(final boolean value) {
      SecurityManager sm = System.getSecurityManager();
      if (sm != null) {
         sm.checkPermission(new PropertyPermission(CHECK_WEAK_KEYS, "write"));
      }
      instance().checkForWeakKeys = value;
      props.put(CHECK_WEAK_KEYS, String.valueOf(value));
   }

   /**
    *
A convenience method to set the global property fo adding a blinding
    * operation when executing the RSA decryption primitive.

    *
    * @param value if true then the code for performing the RSA
    * decryption primitive will include a blinding operation.
    */
   public static synchronized final void setDoRSABlinding(final boolean value) {
      SecurityManager sm = System.getSecurityManager();
      if (sm != null) {
         sm.checkPermission(new PropertyPermission(DO_RSA_BLINDING, "write"));
      }
      instance().doRSABlinding = value;
      props.put(DO_RSA_BLINDING, String.valueOf(value));
   }

   private static synchronized final Properties instance() {
      if (singleton == null) {
         singleton = new Properties();
      }
      return singleton;
   }

   // Instance methods
   // -------------------------------------------------------------------------

   private void init() {
      // default values
      props.put(REPRODUCIBLE_PRNG, new Boolean(reproducible).toString());
      props.put(CHECK_WEAK_KEYS,   new Boolean(checkForWeakKeys).toString());
      props.put(DO_RSA_BLINDING,   new Boolean(doRSABlinding).toString());

      // 1. allow site-wide override by reading a properties file
      String propFile = null;
      try {
         propFile = (String) AccessController.doPrivileged(
            new PrivilegedAction() {
               public Object run() {
                  return System.getProperty(PROPERTIES_FILE);
               }
            }
         );
      } catch (SecurityException se) {
         if (DEBUG) debug("Reading property "+PROPERTIES_FILE+" not allowed. Ignored.");
      }
      if (propFile != null) {
         try {
            final java.util.Properties temp = new java.util.Properties();
            final FileInputStream fin = new FileInputStream(propFile);
            temp.load(fin);
            temp.list(System.out);
            props.putAll(temp);
         } catch (IOException ioe) {
            if (DEBUG) debug("IO error reading "+propFile+": "+ioe.getMessage());
         } catch (SecurityException se) {
            if (DEBUG) debug("Security error reading "+propFile+": "+se.getMessage());
         }
      }

      // 2. allow vm-specific override by allowing -D options in launcher
      handleBooleanProperty(REPRODUCIBLE_PRNG);
      handleBooleanProperty(CHECK_WEAK_KEYS);
      handleBooleanProperty(DO_RSA_BLINDING);

      // re-sync the 'known' properties
      reproducible =     new Boolean((String) props.get(REPRODUCIBLE_PRNG)).booleanValue();
      checkForWeakKeys = new Boolean((String) props.get(CHECK_WEAK_KEYS)).booleanValue();
      doRSABlinding =    new Boolean((String) props.get(DO_RSA_BLINDING)).booleanValue();
   }

   private void handleBooleanProperty(final String name) {
      String s = null;
      try {
         s = System.getProperty(name);
      } catch (SecurityException x) {
         if (DEBUG) debug("SecurityManager forbids reading system properties. Ignored");
      }
      if (s != null) {
         s = s.trim().toLowerCase();
         // we have to test for explicit "true" or "false".  anything else may
         // hide valid value set previously
         if (s.equals(TRUE) || s.equals(FALSE)) {
            if (DEBUG) debug("Setting "+name+" to '"+s+"'");
            props.put(name, s);
         } else {
            if (DEBUG) debug("Invalid value for -D"+name+": "+s+". Ignored");
         }
      }
   }
}


text:
<!DOCTYPE html>

  <meta charset="utf-8">

  <meta name="viewport" content="width=device-width, initial-scale=1.0">

  <title>dyconnmap.graphs.mpc — dyconnmap  documentation</title>

  <link rel="stylesheet" href="../../../_static/css/theme.css" type="text/css" />
  <link rel="stylesheet" href="../../../_static/pygments.css" type="text/css" />

    <link rel="index" title="Index" href="../../../genindex.html" />
    <link rel="search" title="Search" href="../../../search.html" />

             dyconnmap

  <form id="rtd-search-form" class="wy-form" action="../../../search.html" method="get">
    <input type="text" name="q" placeholder="Search docs" />
    <input type="hidden" name="check_keywords" value="yes" />
    <input type="hidden" name="area" value="default" />
  </form>

dyconnmap package

          dyconnmap

 »

Module code »

dyconnmap.graphs.mpc

Source code for dyconnmap.graphs.mpc

""" Multilayer Participation Coefficient

|

-----

.. [Guillon2016] Guillon, J., Attal, Y., Colliot, O., La Corte, V., Dubois, B., Schwartz, D., ... & Fallani, F. D. V. (2017). Loss of brain inter-frequency hubs in Alzheimer's disease. Scientific reports, 7(1), 10879.
"""
# Author: Stavros Dimitriadis <stidimitriadis@gmail.com>
# Author: Avraam Marimpis <avraam.marimpis@gmail.com>

import numpy as np
import bct
from scipy import linalg as LA

[docs]def multilayer_pc_degree(mlgraph: np.ndarray) -> np.ndarray:
    """ Multilayer Participation Coefficient (Degree)

    Parameters
    ----------
    mlgraph : array-like, shape(n_layers, n_rois, n_rois)
        A multilayer (undirected) graph. Each layer consists of a graph.

    Returns
    -------
    mpc : array-like
        Participation coefficient based on the degree of the layers' nodes.
    """
    num_layers, num_rois, num_rois = np.shape(mlgraph)

    degrees = np.zeros((num_layers, num_rois))
    for i in range(num_layers):
        a_layer = np.squeeze(mlgraph[i, :, :])
        degrees[i] = bct.degrees_und(a_layer)

    normal_degrees = np.zeros((num_layers, num_rois))
    for i in range(num_rois):
        normal_degrees[:, i] = degrees[:, i] / np.sum(degrees[:, i])

    mpc = np.zeros((num_rois, 1))
    for i in range(num_rois):
        mpc[i] = (np.float32(num_layers) / (num_layers - 1)) * (
            1.0 - np.sum(np.power(normal_degrees[:, i], 2.0))
        )

    return mpc

[docs]def multilayer_pc_strength(mlgraph: np.ndarray) -> np.ndarray:
    """ Multilayer Participation Coefficient (Strength)

    Parameters
    ----------
    mlgraph : array-like, shape(n_layers, n_rois, n_rois)
        A multilayer (undirected) graph. Each layer consists of a graph.

    Returns
    -------
    mpc : array-like
        Participation coefficient based on the strength of the layers' nodes.
    """
    num_layers, num_rois, num_rois = np.shape(mlgraph)

    strs = np.zeros((num_layers, num_rois))
    for i in range(num_layers):
        for n in range(num_rois):
            strs[i, n] = np.sum(np.ravel(mlgraph[i, n, :]))

    normal_strs = np.zeros((num_layers, num_rois))
    for i in range(num_rois):
        normal_strs[:, i] = strs[:, i] / np.sum(strs[:, i])

    mpc = np.zeros((num_rois, 1))
    for i in range(num_rois):
        mpc[i] = (np.float32(num_layers) / (num_layers - 1)) * (
            1.0 - np.sum(np.power(normal_strs[:, i], 2.0))
        )

    return mpc

[docs]def multilayer_pc_gamma(mlgraph: np.ndarray) -> np.ndarray:
    """ Multilayer Participation Coefficient method from Guillon et al.

    Parameters
    ----------
    mlgraph : array-like, shape(n_layers, n_rois, n_rois)
        A multilayer graph.

    Returns
    -------
    gamma : array-like, shape(n_layers*n_rois, n_layers*n_rois)
        Returns the original multilayer graph flattened, with the off diagional
        containing the estimated interlayer multilayer participation coefficient.
    """
    num_layers, num_rois, _ = np.shape(mlgraph)

    flattened = LA.block_diag(*mlgraph)
    for s1 in range(num_layers - 1):
        l = list(range(0, num_layers - s1))

        if s1 == num_layers - 2:
            l = [0, num_layers - 1]

        offset = (s1 + 1) * num_rois

        tmp = mlgraph[l, :, :]
        connectivity = __interslice_coupling(tmp)
        # num_conn_layers, _ = np.shape(connectivity)
        values = connectivity.flatten()

        np.fill_diagonal(flattened[offset:], values)
        np.fill_diagonal(flattened[:, offset:], values)

    return flattened

def __interslice_coupling(mlgraph):
    """

    Parameters
    ----------
    mlgraph : array-like, shape(n_layers, n_rois, n_rois)
        A multilayer graph. Each layer consists of a graph.

    Returns
    -------
    gamma : array-like
        Description
    """
    num_layers, num_rois, _ = np.shape(mlgraph)

    gamma = np.zeros((num_layers - 1, num_rois))

    for l1 in range(num_layers - 1):
        for r1 in range(num_rois):
            sum1 = 0.0
            str1 = 0.0
            str2 = 0.0

            for r2 in range(num_rois):
                sum1 += mlgraph[l1, r1, r2] * mlgraph[l1 + 1, r1, r2]

            str1 = np.sum(mlgraph[l1, r1, :])
            str2 = np.sum(mlgraph[l1 + 1, r1, :])

            gamma[l1, r1] = sum1 / np.sqrt(str1 * str2)

    return gamma

        © Copyright 2021, Avraam Marimpis & Stavros Dimitriadis

    Built with Sphinx using a

    theme

    provided by Read the Docs.


text:
package org.orienteer.core.component.command;

import org.apache.wicket.ajax.AjaxRequestTarget;
import org.apache.wicket.event.Broadcast;
import org.apache.wicket.model.IModel;
import org.apache.wicket.model.StringResourceModel;
import org.orienteer.core.component.BootstrapType;
import org.orienteer.core.component.FAIconType;
import org.orienteer.core.component.table.OrienteerDataTable;

import com.orientechnologies.orient.core.metadata.schema.OClass;

/**
 * {@link Command} to show or hide parent things
 *
 * @param <T> the type of an entity to which this command can be applied
 */
public class ShowHideParentsCommand<T> extends AjaxCommand<T>
{
	private static final long serialVersionUID = 1L;
	private IModel<OClass> classModel;
	private IModel<Boolean> showHideParentModel;

	public ShowHideParentsCommand(IModel<OClass> classModel, OrienteerDataTable<T, ?> table, IModel<Boolean> showHideParentModel)
	{
		super(new StringResourceModel("command.showhide.${}", showHideParentModel), table);
		this.classModel = classModel;
		this.showHideParentModel = showHideParentModel;
		setIcon(FAIconType.reorder);
		setBootstrapType(BootstrapType.INFO);
	}

	@Override
	protected void onConfigure() {
		super.onConfigure();
		if(classModel!=null)
		{
			OClass oClass = classModel.getObject();
			setVisible(oClass!=null && oClass.getSuperClass()!=null);
		}
	}

	@Override
	public void onClick(AjaxRequestTarget target) {
		Boolean current = showHideParentModel.getObject();
		current = current!=null?!current:true;
		showHideParentModel.setObject(current);
	}

	@Override
	public void detachModels() {
		super.detachModels();
		if(classModel!=null) classModel.detach();
	}

}


text:
@font-face {
	font-family: 'Pretendard JP Variable';
	font-weight: 45 920;
	font-style: normal;
	font-display: swap;
	src: local('Pretendard JP Variable'), url('./woff2/PretendardJPVariable.woff2') format('woff2-variations');
}


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

<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Uses of Class com.communote.plugins.api.rest.v22.resource.timelinenote.timelinenotetag.TimelineNoteTagResource (Communote 3.5 API)</title>
<meta name="date" content="2019-02-02">
<link rel="stylesheet" type="text/css" href="../../../../../../../../../../stylesheet.css" title="Style">

JavaScript is disabled on your browser.

Skip navigation links

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

Prev

Next

Frames

No Frames

All Classes

Uses of Class
com.communote.plugins.api.rest.v22.resource.timelinenote.timelinenotetag.TimelineNoteTagResource

Packages that use TimelineNoteTagResource

Package
Description

com.communote.plugins.api.rest.v22.resource.timelinenote

Uses of TimelineNoteTagResource in com.communote.plugins.api.rest.v22.resource.timelinenote

Methods in com.communote.plugins.api.rest.v22.resource.timelinenote that return TimelineNoteTagResource

Modifier and Type
Method and Description

TimelineNoteTagResource[]
GetTimelineNoteParameter.getTags()

Returns the Tags.

TimelineNoteTagResource[]
GetCollectionTimelineNoteParameter.getTags()

Returns the Tags.

TimelineNoteTagResource[]
TimelineNoteResource.getTags()

Returns the Tags.

static TimelineNoteTagResource[]
TimelineNoteHelper.getTags(NoteData noteListDataItem)

Converts the tags of a note list data object into resources

Methods in com.communote.plugins.api.rest.v22.resource.timelinenote with parameters of type TimelineNoteTagResource

Modifier and Type
Method and Description

void
GetTimelineNoteParameter.setTags(TimelineNoteTagResource[] tags)

Sets Tags.

void
GetCollectionTimelineNoteParameter.setTags(TimelineNoteTagResource[] tags)

Sets Tags.

void
TimelineNoteResource.setTags(TimelineNoteTagResource[] tags)

Sets Tags.

Skip navigation links

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

Prev

Next

Frames

No Frames

All Classes

Copyright © 2019 Communote team. All rights reserved.


text:
namespace GOLD.Engine.Enums
{
    //NOTE: MUST MATCH FILE DEFINITION!!!
    public enum SymbolType
    {
        //Nonterminal
        Nonterminal = 0,
        //Passed to the parser
        Content,
        //Ignored by the parser
        Noise = 2,
        //End character (EOF)
        End = 3,
        //Group start
        GroupStart = 4,
        //Group end
        GroupEnd = 5,
        //Error symbol
        Error = 7
    }
}


text:
import {graphql, Link, useStaticQuery} from 'gatsby'
import React from 'react'
import styled from 'styled-components'

const TagsStyles = styled.div`
  color: var(--color);
  display: flex;
  flex-wrap: wrap;
  gap: 1rem;
  margin-bottom: 4rem;
  a {
    display: grid;
    grid-template-columns: auto 1fr;
    gap: 0 1rem;
    align-items: center;
    padding: 5px;
    background: var(--grey);
    border-radius: 2px;
    text-decoration: none;
    font-size: 2rem;
    font-size: clamp(1.5rem, 1.4vw, 2.5rem);
    .count {
      background: white;
      padding: 2px 5px;
    }
    /* &.active {
      background: var(--yellow);
    } */
    &[aria-current='page'] {
      background: var(--yellow);
    }
  }
`

export default function Tags({activeTag}) {
  const {posts} = useStaticQuery(graphql`
    query {
      posts: allMdx(
        sort: {fields: [frontmatter___date], order: DESC}
        filter: {
          frontmatter: {isPublished: {eq: true}}
          fileAbsolutePath: {regex: "//content/blog//"}
        }
      ) {
        edges {
          node {
            excerpt
            fields {
              slug
            }
            timeToRead
            frontmatter {
              date(formatString: "dddd DD MMMM YYYY")
              title
              tags
            }
          }
        }
      }
    }
  `)

  // loop thru the post and count the tags
  const tagsArrays = []
  for (const each of posts.edges) {
    const {tags} = each.node.frontmatter
    tagsArrays.push(...tags)
  }

  const tagsWithCount = tagsArrays.reduce((curr, prev) => {
    if (curr[prev]) {
      curr[prev] += 1
    } else {
      curr[prev] = 1
    }
    return curr
  }, {})

  return (
    <TagsStyles>
      <Link to="/tags">
        #All
        #{tagsArrays.length}
      </Link>
      {Object.entries(tagsWithCount).map(([tag, count], index) => (
        <Link
          key={index}
          to={`/tags/${tag}`}
          className={tag === activeTag ? 'active' : ''}
        >
          #{tag}
          #{count}
        </Link>
      ))}
    </TagsStyles>
  )
}


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

<meta http-equiv="Content-Type" content="text/html" charset="UTF-8">
<title>程序包 cn.changhong.chcare.core.webapi.server的使用</title>
<meta name="date" content="2014-11-26">
<link rel="stylesheet" type="text/css" href="../../../../../../stylesheet.css" title="Style">

您的浏览器已禁用 JavaScript。

概览

程序包

类

使用

树

已过时

索引

帮助

上一个

下一个

框架

无框架

所有类

程序包 cn.changhong.chcare.core.webapi.server
的使用

使用cn.changhong.chcare.core.webapi.server的程序包

程序包
说明

cn.changhong.chcare.core.webapi

cn.changhong.chcare.core.webapi.server

cn.changhong.chcare.core.webapi.util

cn.changhong.chcare.core.webapi使用的cn.changhong.chcare.core.webapi.server中的类

类和说明

AAppManagerService

AFamilyMsgBoardService

AFamilyService

与家庭相关的的接口定义

AFPhoneWebApiService

与功能机相关的接口定义

APhotowallWebApiService

与家庭墙功能相关接口定义

AsyncResponseCompletedHandler

shdjsahdjs
 dsaddfdsfdhgfhgf

ChCareWepApiServiceType

IAccountService

与账号相关服务的接口定义

IHealthService

ILocationService

IOfflineMessageService

IService

cn.changhong.chcare.core.webapi.server使用的cn.changhong.chcare.core.webapi.server中的类

类和说明

AsyncResponseCompletedHandler

shdjsahdjs
 dsaddfdsfdhgfhgf

CHCareWebApiProvider

CHCareWebApiProvider.WebApiServerType

ChCareWebApiRequestErrorType

ChCareWepApiServiceType

IService

cn.changhong.chcare.core.webapi.util使用的cn.changhong.chcare.core.webapi.server中的类

类和说明

ChCareWebApiRequestErrorType

概览

程序包

类

使用

树

已过时

索引

帮助

上一个

下一个

框架

无框架

所有类


text:
<?php
/**
 * Holder of replacement pairs for wiki links
 *
 * @file
 */

/**
 * @ingroup Parser
 */
class LinkHolderArray {
	var $internals = array(), $interwikis = array();
	var $size = 0;
	var $parent;
	protected $tempIdOffset;

	function __construct( $parent ) {
		$this->parent = $parent;
	}

	/**
	 * Reduce memory usage to reduce the impact of circular references
	 */
	function __destruct() {
		foreach ( $this as $name => $value ) {
			unset( $this->$name );
		}
	}

 	/**
	 * Don't serialize the parent object, it is big, and not needed when it is
	 * a parameter to mergeForeign(), which is the only application of
	 * serializing at present.
	 *
	 * Compact the titles, only serialize the text form.
	 */
	function __sleep() {
		foreach ( $this->internals as &$nsLinks ) {
			foreach ( $nsLinks as &$entry ) {
				unset( $entry['title'] );
			}
		}
		unset( $nsLinks );
		unset( $entry );

		foreach ( $this->interwikis as &$entry ) {
			unset( $entry['title'] );
		}
		unset( $entry );

		return array( 'internals', 'interwikis', 'size' );
	}

	/**
	 * Recreate the Title objects
	 */
	function __wakeup() {
		foreach ( $this->internals as &$nsLinks ) {
			foreach ( $nsLinks as &$entry ) {
				$entry['title'] = Title::newFromText( $entry['pdbk'] );
			}
		}
		unset( $nsLinks );
		unset( $entry );

		foreach ( $this->interwikis as &$entry ) {
			$entry['title'] = Title::newFromText( $entry['pdbk'] );
		}
		unset( $entry );
	}

	/**
	 * Merge another LinkHolderArray into this one
	 * @param $other LinkHolderArray
	 */
	function merge( $other ) {
		foreach ( $other->internals as $ns => $entries ) {
			$this->size += count( $entries );
			if ( !isset( $this->internals[$ns] ) ) {
				$this->internals[$ns] = $entries;
			} else {
				$this->internals[$ns] += $entries;
			}
		}
		$this->interwikis += $other->interwikis;
	}

	/**
	 * Merge a LinkHolderArray from another parser instance into this one. The
	 * keys will not be preserved. Any text which went with the old
	 * LinkHolderArray and needs to work with the new one should be passed in
	 * the $texts array. The strings in this array will have their link holders
	 * converted for use in the destination link holder. The resulting array of
	 * strings will be returned.
	 *
	 * @param $other LinkHolderArray
	 * @param $texts Array of strings
	 * @return Array
	 */
	function mergeForeign( $other, $texts ) {
		$this->tempIdOffset = $idOffset = $this->parent->nextLinkID();
		$maxId = 0;

		# Renumber internal links
		foreach ( $other->internals as $ns => $nsLinks ) {
			foreach ( $nsLinks as $key => $entry ) {
				$newKey = $idOffset + $key;
				$this->internals[$ns][$newKey] = $entry;
				$maxId = $newKey > $maxId ? $newKey : $maxId;
			}
		}
		$texts = preg_replace_callback( '/(<!--LINK \d+:)(\d+)(-->)/',
			array( $this, 'mergeForeignCallback' ), $texts );

		# Renumber interwiki links
		foreach ( $other->interwikis as $key => $entry ) {
			$newKey = $idOffset + $key;
			$this->interwikis[$newKey] = $entry;
			$maxId = $newKey > $maxId ? $newKey : $maxId;
		}
		$texts = preg_replace_callback( '/(<!--IWLINK )(\d+)(-->)/',
			array( $this, 'mergeForeignCallback' ), $texts );

		# Set the parent link ID to be beyond the highest used ID
		$this->parent->setLinkID( $maxId + 1 );
		$this->tempIdOffset = null;
		return $texts;
	}

	protected function mergeForeignCallback( $m ) {
		return $m[1] . ( $m[2] + $this->tempIdOffset ) . $m[3];
	}

	/**
	 * Get a subset of the current LinkHolderArray which is sufficient to
	 * interpret the given text.
	 */
	function getSubArray( $text ) {
		$sub = new LinkHolderArray( $this->parent );

		# Internal links
		$pos = 0;
		while ( $pos < strlen( $text ) ) {
			if ( !preg_match( '/<!--LINK (\d+):(\d+)-->/',
				$text, $m, PREG_OFFSET_CAPTURE, $pos ) )
			{
				break;
			}
			$ns = $m[1][0];
			$key = $m[2][0];
			$sub->internals[$ns][$key] = $this->internals[$ns][$key];
			$pos = $m[0][1] + strlen( $m[0][0] );
		}

		# Interwiki links
		$pos = 0;
		while ( $pos < strlen( $text ) ) {
			if ( !preg_match( '/<!--IWLINK (\d+)-->/', $text, $m, PREG_OFFSET_CAPTURE, $pos ) ) {
				break;
			}
			$key = $m[1][0];
			$sub->interwikis[$key] = $this->interwikis[$key];
			$pos = $m[0][1] + strlen( $m[0][0] );
		}
		return $sub;
	}

	/**
	 * Returns true if the memory requirements of this object are getting large
	 */
	function isBig() {
		global $wgLinkHolderBatchSize;
		return $this->size > $wgLinkHolderBatchSize;
	}

	/**
	 * Clear all stored link holders.
	 * Make sure you don't have any text left using these link holders, before you call this
	 */
	function clear() {
		$this->internals = array();
		$this->interwikis = array();
		$this->size = 0;
	}

	/**
	 * Make a link placeholder. The text returned can be later resolved to a real link with
	 * replaceLinkHolders(). This is done for two reasons: firstly to avoid further
	 * parsing of interwiki links, and secondly to allow all existence checks and
	 * article length checks (for stub links) to be bundled into a single query.
	 *
	 * @param $nt Title
	 */
	function makeHolder( $nt, $text = '', $query = array(), $trail = '', $prefix = ''  ) {
		wfProfileIn( __METHOD__ );
		if ( ! is_object($nt) ) {
			# Fail gracefully
			$retVal = "<!-- ERROR -->{$prefix}{$text}{$trail}";
		} else {
			# Separate the link trail from the rest of the link
			list( $inside, $trail ) = Linker::splitTrail( $trail );

			$entry = array(
				'title' => $nt,
				'text' => $prefix.$text.$inside,
				'pdbk' => $nt->getPrefixedDBkey(),
			);
			if ( $query !== array() ) {
				$entry['query'] = $query;
			}

			if ( $nt->isExternal() ) {
				// Use a globally unique ID to keep the objects mergable
				$key = $this->parent->nextLinkID();
				$this->interwikis[$key] = $entry;
				$retVal = "<!--IWLINK $key-->{$trail}";
			} else {
				$key = $this->parent->nextLinkID();
				$ns = $nt->getNamespace();
				$this->internals[$ns][$key] = $entry;
				$retVal = "<!--LINK $ns:$key-->{$trail}";
			}
			$this->size++;
		}
		wfProfileOut( __METHOD__ );
		return $retVal;
	}

	/**
	 * @todo FIXME: Update documentation. makeLinkObj() is deprecated.
	 * Replace <!--LINK--> link placeholders with actual links, in the buffer
	 * Placeholders created in Skin::makeLinkObj()
	 * Returns an array of link CSS classes, indexed by PDBK.
	 */
	function replace( &$text ) {
		wfProfileIn( __METHOD__ );

		$colours = $this->replaceInternal( $text );
		$this->replaceInterwiki( $text );

		wfProfileOut( __METHOD__ );
		return $colours;
	}

	/**
	 * Replace internal links
	 */
	protected function replaceInternal( &$text ) {
		if ( !$this->internals ) {
			return;
		}

		wfProfileIn( __METHOD__ );
		global $wgContLang;

		$colours = array();
		$linkCache = LinkCache::singleton();
		$output = $this->parent->getOutput();

		wfProfileIn( __METHOD__.'-check' );
		$dbr = wfGetDB( DB_SLAVE );
		$threshold = $this->parent->getOptions()->getStubThreshold();

		# Sort by namespace
		ksort( $this->internals );

		$linkcolour_ids = array();

		# Generate query
		$queries = array();
		foreach ( $this->internals as $ns => $entries ) {
			foreach ( $entries as $entry ) {
				$title = $entry['title'];
				$pdbk = $entry['pdbk'];

				# Skip invalid entries.
				# Result will be ugly, but prevents crash.
				if ( is_null( $title ) ) {
					continue;
				}

				# Check if it's a static known link, e.g. interwiki
				if ( $title->isAlwaysKnown() ) {
					$colours[$pdbk] = '';
				} elseif ( $ns == NS_SPECIAL ) {
					$colours[$pdbk] = 'new';
				} elseif ( ( $id = $linkCache->getGoodLinkID( $pdbk ) ) != 0 ) {
					$colours[$pdbk] = Linker::getLinkColour( $title, $threshold );
					$output->addLink( $title, $id );
					$linkcolour_ids[$id] = $pdbk;
				} elseif ( $linkCache->isBadLink( $pdbk ) ) {
					$colours[$pdbk] = 'new';
				} else {
					# Not in the link cache, add it to the query
					$queries[$ns][] = $title->getDBkey();
				}
			}
		}
		if ( $queries ) {
			$where = array();
			foreach( $queries as $ns => $pages ){
				$where[] = $dbr->makeList(
					array(
						'page_namespace' => $ns,
						'page_title' => $pages,
					),
					LIST_AND
				);
			}

			$res = $dbr->select(
				'page',
				array( 'page_id', 'page_namespace', 'page_title', 'page_is_redirect', 'page_len', 'page_latest' ),
				$dbr->makeList( $where, LIST_OR ),
				__METHOD__
			);

			# Fetch data and form into an associative array
			# non-existent = broken
			foreach ( $res as $s ) {
				$title = Title::makeTitle( $s->page_namespace, $s->page_title );
				$pdbk = $title->getPrefixedDBkey();
				$linkCache->addGoodLinkObjFromRow( $title, $s );
				$output->addLink( $title, $s->page_id );
				# @todo FIXME: Convoluted data flow
				# The redirect status and length is passed to getLinkColour via the LinkCache
				# Use formal parameters instead
				$colours[$pdbk] = Linker::getLinkColour( $title, $threshold );
				//add id to the extension todolist
				$linkcolour_ids[$s->page_id] = $pdbk;
			}
			unset( $res );
		}
		if ( count($linkcolour_ids) ) {
			//pass an array of page_ids to an extension
			wfRunHooks( 'GetLinkColours', array( $linkcolour_ids, &$colours ) );
		}
		wfProfileOut( __METHOD__.'-check' );

		# Do a second query for different language variants of links and categories
		if($wgContLang->hasVariants()) {
			$this->doVariants( $colours );
		}

		# Construct search and replace arrays
		wfProfileIn( __METHOD__.'-construct' );
		$replacePairs = array();
		foreach ( $this->internals as $ns => $entries ) {
			foreach ( $entries as $index => $entry ) {
				$pdbk = $entry['pdbk'];
				$title = $entry['title'];
				$query = isset( $entry['query'] ) ? $entry['query'] : array();
				$key = "$ns:$index";
				$searchkey = "<!--LINK $key-->";
				$displayText = $entry['text'];
				if ( $displayText === '' ) {
					$displayText = null;
				}
				if ( !isset( $colours[$pdbk] ) ) {
					$colours[$pdbk] = 'new';
				}
				$attribs = array();
				if ( $colours[$pdbk] == 'new' ) {
					$linkCache->addBadLinkObj( $title );
					$output->addLink( $title, 0 );
					$type = array( 'broken' );
				} else {
					if ( $colours[$pdbk] != '' ) {
						$attribs['class'] = $colours[$pdbk];
					}
					$type = array( 'known', 'noclasses' );
				}
				$replacePairs[$searchkey] = Linker::link( $title, $displayText,
						$attribs, $query, $type );
			}
		}
		$replacer = new HashtableReplacer( $replacePairs, 1 );
		wfProfileOut( __METHOD__.'-construct' );

		# Do the thing
		wfProfileIn( __METHOD__.'-replace' );
		$text = preg_replace_callback(
			'/(<!--LINK .*?-->)/',
			$replacer->cb(),
			$text);

		wfProfileOut( __METHOD__.'-replace' );
		wfProfileOut( __METHOD__ );
	}

	/**
	 * Replace interwiki links
	 */
	protected function replaceInterwiki( &$text ) {
		if ( empty( $this->interwikis ) ) {
			return;
		}

		wfProfileIn( __METHOD__ );
		# Make interwiki link HTML
		$output = $this->parent->getOutput();
		$replacePairs = array();
		foreach( $this->interwikis as $key => $link ) {
			$replacePairs[$key] = Linker::link( $link['title'], $link['text'] );
			$output->addInterwikiLink( $link['title'] );
		}
		$replacer = new HashtableReplacer( $replacePairs, 1 );

		$text = preg_replace_callback(
			'/<!--IWLINK (.*?)-->/',
			$replacer->cb(),
			$text );
		wfProfileOut( __METHOD__ );
	}

	/**
	 * Modify $this->internals and $colours according to language variant linking rules
	 */
	protected function doVariants( &$colours ) {
		global $wgContLang;
		$linkBatch = new LinkBatch();
		$variantMap = array(); // maps $pdbkey_Variant => $keys (of link holders)
		$output = $this->parent->getOutput();
		$linkCache = LinkCache::singleton();
		$threshold = $this->parent->getOptions()->getStubThreshold();
		$titlesToBeConverted = '';
		$titlesAttrs = array();

		// Concatenate titles to a single string, thus we only need auto convert the
		// single string to all variants. This would improve parser's performance
		// significantly.
		foreach ( $this->internals as $ns => $entries ) {
			foreach ( $entries as $index => $entry ) {
				$pdbk = $entry['pdbk'];
				// we only deal with new links (in its first query)
				if ( !isset( $colours[$pdbk] ) ) {
					$title = $entry['title'];
					$titleText = $title->getText();
					$titlesAttrs[] = array(
						'ns' => $ns,
						'key' => "$ns:$index",
						'titleText' => $titleText,
					);
					// separate titles with \0 because it would never appears
					// in a valid title
					$titlesToBeConverted .= $titleText . "\0";
				}
			}
		}

		// Now do the conversion and explode string to text of titles
		$titlesAllVariants = $wgContLang->autoConvertToAllVariants( $titlesToBeConverted );
		$allVariantsName = array_keys( $titlesAllVariants );
		foreach ( $titlesAllVariants as &$titlesVariant ) {
			$titlesVariant = explode( "\0", $titlesVariant );
		}
		$l = count( $titlesAttrs );
		// Then add variants of links to link batch
		for ( $i = 0; $i < $l; $i ++ ) {
			foreach ( $allVariantsName as $variantName ) {
				$textVariant = $titlesAllVariants[$variantName][$i];
				if ( $textVariant != $titlesAttrs[$i]['titleText'] ) {
					$variantTitle = Title::makeTitle( $titlesAttrs[$i]['ns'], $textVariant );
					if( is_null( $variantTitle ) ) {
						continue;
					}
					$linkBatch->addObj( $variantTitle );
					$variantMap[$variantTitle->getPrefixedDBkey()][] = $titlesAttrs[$i]['key'];
				}
			}
		}

		// process categories, check if a category exists in some variant
		$categoryMap = array(); // maps $category_variant => $category (dbkeys)
		$varCategories = array(); // category replacements oldDBkey => newDBkey
		foreach( $output->getCategoryLinks() as $category ){
			$variants = $wgContLang->autoConvertToAllVariants( $category );
			foreach($variants as $variant){
				if($variant != $category){
					$variantTitle = Title::newFromDBkey( Title::makeName(NS_CATEGORY,$variant) );
					if(is_null($variantTitle)) continue;
					$linkBatch->addObj( $variantTitle );
					$categoryMap[$variant] = $category;
				}
			}
		}

		if(!$linkBatch->isEmpty()){
			// construct query
			$dbr = wfGetDB( DB_SLAVE );
			$varRes = $dbr->select( 'page',
				array( 'page_id', 'page_namespace', 'page_title', 'page_is_redirect', 'page_len', 'page_latest' ),
				$linkBatch->constructSet( 'page', $dbr ),
				__METHOD__
			);

			$linkcolour_ids = array();

			// for each found variants, figure out link holders and replace
			foreach ( $varRes as $s ) {

				$variantTitle = Title::makeTitle( $s->page_namespace, $s->page_title );
				$varPdbk = $variantTitle->getPrefixedDBkey();
				$vardbk = $variantTitle->getDBkey();

				$holderKeys = array();
				if( isset( $variantMap[$varPdbk] ) ) {
					$holderKeys = $variantMap[$varPdbk];
					$linkCache->addGoodLinkObjFromRow( $variantTitle, $s );
					$output->addLink( $variantTitle, $s->page_id );
				}

				// loop over link holders
				foreach( $holderKeys as $key ) {
					list( $ns, $index ) = explode( ':', $key, 2 );
					$entry =& $this->internals[$ns][$index];
					$pdbk = $entry['pdbk'];

					if(!isset($colours[$pdbk])){
						// found link in some of the variants, replace the link holder data
						$entry['title'] = $variantTitle;
						$entry['pdbk'] = $varPdbk;

						// set pdbk and colour
						# @todo FIXME: Convoluted data flow
						# The redirect status and length is passed to getLinkColour via the LinkCache
						# Use formal parameters instead
						$colours[$varPdbk] = Linker::getLinkColour( $variantTitle, $threshold );
						$linkcolour_ids[$s->page_id] = $pdbk;
					}
				}

				// check if the object is a variant of a category
				if(isset($categoryMap[$vardbk])){
					$oldkey = $categoryMap[$vardbk];
					if($oldkey != $vardbk)
						$varCategories[$oldkey]=$vardbk;
				}
			}
			wfRunHooks( 'GetLinkColours', array( $linkcolour_ids, &$colours ) );

			// rebuild the categories in original order (if there are replacements)
			if(count($varCategories)>0){
				$newCats = array();
				$originalCats = $output->getCategories();
				foreach($originalCats as $cat => $sortkey){
					// make the replacement
					if( array_key_exists($cat,$varCategories) )
						$newCats[$varCategories[$cat]] = $sortkey;
					else $newCats[$cat] = $sortkey;
				}
				$output->setCategoryLinks($newCats);
			}
		}
	}

	/**
	 * Replace <!--LINK--> link placeholders with plain text of links
	 * (not HTML-formatted).
	 *
	 * @param $text String
	 * @return String
	 */
	function replaceText( $text ) {
		wfProfileIn( __METHOD__ );

		$text = preg_replace_callback(
			'/<!--(LINK|IWLINK) (.*?)-->/',
			array( &$this, 'replaceTextCallback' ),
			$text );

		wfProfileOut( __METHOD__ );
		return $text;
	}

	/**
	 * Callback for replaceText()
	 *
	 * @param $matches Array
	 * @return string
	 * @private
	 */
	function replaceTextCallback( $matches ) {
		$type = $matches[1];
		$key  = $matches[2];
		if( $type == 'LINK' ) {
			list( $ns, $index ) = explode( ':', $key, 2 );
			if( isset( $this->internals[$ns][$index]['text'] ) ) {
				return $this->internals[$ns][$index]['text'];
			}
		} elseif( $type == 'IWLINK' ) {
			if( isset( $this->interwikis[$key]['text'] ) ) {
				return $this->interwikis[$key]['text'];
			}
		}
		return $matches[0];
	}
}


text:
{{ name }}
{{ underline }}

.. automodule:: {{ fullname }}


text:
"""Support for DoorBird devices."""
import asyncio
import logging
import urllib
from urllib.error import HTTPError

from aiohttp import web
from doorbirdpy import DoorBird
import voluptuous as vol

from homeassistant.components.http import HomeAssistantView
from homeassistant.config_entries import SOURCE_IMPORT, ConfigEntry
from homeassistant.const import (
    ATTR_ENTITY_ID,
    CONF_DEVICES,
    CONF_HOST,
    CONF_NAME,
    CONF_PASSWORD,
    CONF_TOKEN,
    CONF_USERNAME,
    HTTP_OK,
    HTTP_UNAUTHORIZED,
)
from homeassistant.core import HomeAssistant, callback
from homeassistant.exceptions import ConfigEntryNotReady
import homeassistant.helpers.config_validation as cv
from homeassistant.helpers.network import get_url
from homeassistant.util import dt as dt_util, slugify

from .const import (
    CONF_EVENTS,
    DOMAIN,
    DOOR_STATION,
    DOOR_STATION_EVENT_ENTITY_IDS,
    DOOR_STATION_INFO,
    PLATFORMS,
)
from .util import get_doorstation_by_token

_LOGGER = logging.getLogger(__name__)

API_URL = f"/api/{DOMAIN}"

CONF_CUSTOM_URL = "hass_url_override"

RESET_DEVICE_FAVORITES = "doorbird_reset_favorites"

DEVICE_SCHEMA = vol.Schema(
    {
        vol.Required(CONF_HOST): cv.string,
        vol.Required(CONF_USERNAME): cv.string,
        vol.Required(CONF_PASSWORD): cv.string,
        vol.Required(CONF_TOKEN): cv.string,
        vol.Optional(CONF_EVENTS, default=[]): vol.All(cv.ensure_list, [cv.string]),
        vol.Optional(CONF_CUSTOM_URL): cv.string,
        vol.Optional(CONF_NAME): cv.string,
    }
)

CONFIG_SCHEMA = vol.Schema(
    {
        DOMAIN: vol.Schema(
            {vol.Required(CONF_DEVICES): vol.All(cv.ensure_list, [DEVICE_SCHEMA])}
        )
    },
    extra=vol.ALLOW_EXTRA,
)

async def async_setup(hass: HomeAssistant, config: dict):
    """Set up the DoorBird component."""
    hass.data.setdefault(DOMAIN, {})

    # Provide an endpoint for the doorstations to call to trigger events
    hass.http.register_view(DoorBirdRequestView)

    if DOMAIN in config and CONF_DEVICES in config[DOMAIN]:
        for index, doorstation_config in enumerate(config[DOMAIN][CONF_DEVICES]):
            if CONF_NAME not in doorstation_config:
                doorstation_config[CONF_NAME] = f"DoorBird {index + 1}"

            hass.async_create_task(
                hass.config_entries.flow.async_init(
                    DOMAIN, context={"source": SOURCE_IMPORT}, data=doorstation_config
                )
            )

    def _reset_device_favorites_handler(event):
        """Handle clearing favorites on device."""
        token = event.data.get("token")

        if token is None:
            return

        doorstation = get_doorstation_by_token(hass, token)

        if doorstation is None:
            _LOGGER.error("Device not found for provided token")
            return

        # Clear webhooks
        favorites = doorstation.device.favorites()

        for favorite_type in favorites:
            for favorite_id in favorites[favorite_type]:
                doorstation.device.delete_favorite(favorite_type, favorite_id)

    hass.bus.async_listen(RESET_DEVICE_FAVORITES, _reset_device_favorites_handler)

    return True

async def async_setup_entry(hass: HomeAssistant, entry: ConfigEntry):
    """Set up DoorBird from a config entry."""

    _async_import_options_from_data_if_missing(hass, entry)

    doorstation_config = entry.data
    doorstation_options = entry.options
    config_entry_id = entry.entry_id

    device_ip = doorstation_config[CONF_HOST]
    username = doorstation_config[CONF_USERNAME]
    password = doorstation_config[CONF_PASSWORD]

    device = DoorBird(device_ip, username, password)
    try:
        status = await hass.async_add_executor_job(device.ready)
        info = await hass.async_add_executor_job(device.info)
    except urllib.error.HTTPError as err:
        if err.code == HTTP_UNAUTHORIZED:
            _LOGGER.error(
                "Authorization rejected by DoorBird for %s@%s", username, device_ip
            )
            return False
        raise ConfigEntryNotReady from err
    except OSError as oserr:
        _LOGGER.error("Failed to setup doorbird at %s: %s", device_ip, oserr)
        raise ConfigEntryNotReady from oserr

    if not status[0]:
        _LOGGER.error(
            "Could not connect to DoorBird as %s@%s: Error %s",
            username,
            device_ip,
            str(status[1]),
        )
        raise ConfigEntryNotReady

    token = doorstation_config.get(CONF_TOKEN, config_entry_id)
    custom_url = doorstation_config.get(CONF_CUSTOM_URL)
    name = doorstation_config.get(CONF_NAME)
    events = doorstation_options.get(CONF_EVENTS, [])
    doorstation = ConfiguredDoorBird(device, name, events, custom_url, token)
    # Subscribe to doorbell or motion events
    if not await _async_register_events(hass, doorstation):
        raise ConfigEntryNotReady

    hass.data[DOMAIN][config_entry_id] = {
        DOOR_STATION: doorstation,
        DOOR_STATION_INFO: info,
    }

    entry.add_update_listener(_update_listener)

    for component in PLATFORMS:
        hass.async_create_task(
            hass.config_entries.async_forward_entry_setup(entry, component)
        )

    return True

async def async_unload_entry(hass: HomeAssistant, entry: ConfigEntry):
    """Unload a config entry."""

    unload_ok = all(
        await asyncio.gather(
            *[
                hass.config_entries.async_forward_entry_unload(entry, component)
                for component in PLATFORMS
            ]
        )
    )
    if unload_ok:
        hass.data[DOMAIN].pop(entry.entry_id)

    return unload_ok

async def _async_register_events(hass, doorstation):
    try:
        await hass.async_add_executor_job(doorstation.register_events, hass)
    except HTTPError:
        hass.components.persistent_notification.create(
            "Doorbird configuration failed.  Please verify that API "
            "Operator permission is enabled for the Doorbird user. "
            "A restart will be required once permissions have been "
            "verified.",
            title="Doorbird Configuration Failure",
            notification_id="doorbird_schedule_error",
        )
        return False

    return True

async def _update_listener(hass: HomeAssistant, entry: ConfigEntry):
    """Handle options update."""
    config_entry_id = entry.entry_id
    doorstation = hass.data[DOMAIN][config_entry_id][DOOR_STATION]

    doorstation.events = entry.options[CONF_EVENTS]
    # Subscribe to doorbell or motion events
    await _async_register_events(hass, doorstation)

@callback
def _async_import_options_from_data_if_missing(hass: HomeAssistant, entry: ConfigEntry):
    options = dict(entry.options)
    modified = False
    for importable_option in [CONF_EVENTS]:
        if importable_option not in entry.options and importable_option in entry.data:
            options[importable_option] = entry.data[importable_option]
            modified = True

    if modified:
        hass.config_entries.async_update_entry(entry, options=options)

class ConfiguredDoorBird:
    """Attach additional information to pass along with configured device."""

    def __init__(self, device, name, events, custom_url, token):
        """Initialize configured device."""
        self._name = name
        self._device = device
        self._custom_url = custom_url
        self.events = events
        self.doorstation_events = [self._get_event_name(event) for event in self.events]
        self._token = token

    @property
    def name(self):
        """Get custom device name."""
        return self._name

    @property
    def device(self):
        """Get the configured device."""
        return self._device

    @property
    def custom_url(self):
        """Get custom url for device."""
        return self._custom_url

    @property
    def token(self):
        """Get token for device."""
        return self._token

    def register_events(self, hass):
        """Register events on device."""
        # Get the URL of this server
        hass_url = get_url(hass)

        # Override url if another is specified in the configuration
        if self.custom_url is not None:
            hass_url = self.custom_url

        for event in self.doorstation_events:
            self._register_event(hass_url, event)

            _LOGGER.info("Successfully registered URL for %s on %s", event, self.name)

    @property
    def slug(self):
        """Get device slug."""
        return slugify(self._name)

    def _get_event_name(self, event):
        return f"{self.slug}_{event}"

    def _register_event(self, hass_url, event):
        """Add a schedule entry in the device for a sensor."""
        url = f"{hass_url}{API_URL}/{event}?token={self._token}"

        # Register HA URL as webhook if not already, then get the ID
        if not self.webhook_is_registered(url):
            self.device.change_favorite("http", f"Home Assistant ({event})", url)

        fav_id = self.get_webhook_id(url)

        if not fav_id:
            _LOGGER.warning(
                'Could not find favorite for URL "%s". ' 'Skipping sensor "%s"',
                url,
                event,
            )
            return

    def webhook_is_registered(self, url, favs=None) -> bool:
        """Return whether the given URL is registered as a device favorite."""
        favs = favs if favs else self.device.favorites()

        if "http" not in favs:
            return False

        for fav in favs["http"].values():
            if fav["value"] == url:
                return True

        return False

    def get_webhook_id(self, url, favs=None) -> str or None:
        """
        Return the device favorite ID for the given URL.

        The favorite must exist or there will be problems.
        """
        favs = favs if favs else self.device.favorites()

        if "http" not in favs:
            return None

        for fav_id in favs["http"]:
            if favs["http"][fav_id]["value"] == url:
                return fav_id

        return None

    def get_event_data(self):
        """Get data to pass along with HA event."""
        return {
            "timestamp": dt_util.utcnow().isoformat(),
            "live_video_url": self._device.live_video_url,
            "live_image_url": self._device.live_image_url,
            "rtsp_live_video_url": self._device.rtsp_live_video_url,
            "html5_viewer_url": self._device.html5_viewer_url,
        }

class DoorBirdRequestView(HomeAssistantView):
    """Provide a page for the device to call."""

    requires_auth = False
    url = API_URL
    name = API_URL[1:].replace("/", ":")
    extra_urls = [API_URL + "/{event}"]

    async def get(self, request, event):
        """Respond to requests from the device."""
        hass = request.app["hass"]

        token = request.query.get("token")

        device = get_doorstation_by_token(hass, token)

        if device is None:
            return web.Response(
                status=HTTP_UNAUTHORIZED, text="Invalid token provided."
            )

        if device:
            event_data = device.get_event_data()
        else:
            event_data = {}

        if event == "clear":
            hass.bus.async_fire(RESET_DEVICE_FAVORITES, {"token": token})

            message = f"HTTP Favorites cleared for {device.slug}"
            return web.Response(status=HTTP_OK, text=message)

        event_data[ATTR_ENTITY_ID] = hass.data[DOMAIN][
            DOOR_STATION_EVENT_ENTITY_IDS
        ].get(event)

        hass.bus.async_fire(f"{DOMAIN}_{event}", event_data)

        return web.Response(status=HTTP_OK, text="OK")


text:
'use strict';

var inherits = require('util').inherits;

function YAMLException(reason, mark) {
  // Super constructor
  Error.call(this);

  // Super helper method to include stack trace in error object
  Error.captureStackTrace(this, this.constructor);

  this.name = 'YAMLException';
  this.reason = reason;
  this.mark = mark;
  this.message = (this.reason || '(unknown reason)') + (this.mark ? ' ' + this.mark.toString() : '');
}

// Inherit from Error
inherits(YAMLException, Error);

YAMLException.prototype.toString = function toString(compact) {
  var result = this.name + ': ';

  result += this.reason || '(unknown reason)';

  if (!compact && this.mark) {
    result += ' ' + this.mark.toString();
  }

  return result;
};

module.exports = YAMLException;


text:
package com.fanlehai.java.exception;
// Each disposable object must be followed by a try-finally

class NeedsCleanup { // Construction can't fail
	private static long counter = 1;
	private final long id = counter++;

	public void dispose() {
		System.out.println("NeedsCleanup " + id + " disposed");
	}
}

class ConstructionException extends Exception {
}

class NeedsCleanup2 extends NeedsCleanup {
	// Construction can fail:
	public NeedsCleanup2() throws ConstructionException {
	}
}

public class CleanupIdiom {
	public static void main(String[] args) {
		// Section 1:
		NeedsCleanup nc1 = new NeedsCleanup();
		try {
			// ...
		} finally {
			nc1.dispose();
		}

		// Section 2:
		// If construction cannot fail you can group objects:
		NeedsCleanup nc2 = new NeedsCleanup();
		NeedsCleanup nc3 = new NeedsCleanup();
		try {
			// ...
		} finally {
			nc3.dispose(); // Reverse order of construction
			nc2.dispose();
		}

		// Section 3:
		// If construction can fail you must guard each one:
		try {
			NeedsCleanup2 nc4 = new NeedsCleanup2();
			try {
				NeedsCleanup2 nc5 = new NeedsCleanup2();
				try {
					// ...
				} finally {
					nc5.dispose();
				}
			} catch (ConstructionException e) { // nc5 constructor
				System.out.println(e);
			} finally {
				nc4.dispose();
			}
		} catch (ConstructionException e) { // nc4 constructor
			System.out.println(e);
		}
	}
} /* Output:
NeedsCleanup 1 disposed
NeedsCleanup 3 disposed
NeedsCleanup 2 disposed
NeedsCleanup 5 disposed
NeedsCleanup 4 disposed
*///:~


text:
@class OKSyntaxHighlighter;

@interface OKDemoAppDelegate : NSObject {
    IBOutlet NSWindow *window;
    IBOutlet NSTextView *textView;

    NSAttributedString *displayString;
}

- (IBAction)highlight:(id)sender;

@property (nonatomic, copy) NSAttributedString *displayString;
@end


text:
package com.example.sahilnaran.framework.application.injection;

import com.ericlouw.jinjectsu.jinjectsu.Jinjectsu;
import com.ericlouw.jinjectsu.jinjectsu.interfaces.IFactoryMethod;
import com.example.sahilnaran.api.HomeApi;
import com.example.sahilnaran.dataaccess.sqlite.cporm.github.mappers.GithubMapper;
import com.example.sahilnaran.integration.githubapi.config.RetrofitApiClient;
import com.example.sahilnaran.integration.githubapi.resources.repositories.IRepositoryResources;
import com.example.sahilnaran.integration.githubapi.resources.repositories.mappers.GithubRepositoryMapper;
import com.example.sahilnaran.presenters.home.IMainContract;
import com.example.sahilnaran.presenters.home.MainPresenter;
import com.example.sahilnaran.ui.home.MainActivity;

public abstract class InjectionConfiguration {

    Jinjectsu container;

    InjectionConfiguration(Jinjectsu container) {
        this.container = container;
    }

    public void configure() {
        configureApis();
        configureMappers();
        configurePreferences();
        configurePresenters();
        configureResources();
        configureRepositories();
        configureServices();
        configureViews();
    }

    private void configureApis() {
        this.container
                .bind(HomeApi.class).lifeStyleScoped(HomeApi.class);
    }

    private void configureMappers() {
        this.container
                .bind(GithubMapper.class).lifeStyleScoped(GithubMapper.class)
                .bind(GithubRepositoryMapper.class).lifestyleSingleton(GithubRepositoryMapper.class);
    }

    private void configurePresenters() {
        this.container
                .bind(IMainContract.Presenter.class).lifeStyleScoped(MainPresenter.class);
    }

    private void configureResources() {
        this.container
                .bind(IRepositoryResources.class).lifestyleSingleton(new IFactoryMethod<IRepositoryResources>() {
            @Override
            public IRepositoryResources create() {
                return new RetrofitApiClient().getClient().create(IRepositoryResources.class);
            }
        });
    }

    private void configureViews() {
        this.container
                .bind(IMainContract.View.class).lifeStyleScoped(MainActivity.class);
    }

    protected abstract void configurePreferences();

    protected abstract void configureServices();

    protected abstract void configureRepositories();
}


text:
package jiguang.chat.adapter;

import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.TextView;

import org.greenrobot.eventbus.EventBus;

import java.util.ArrayList;

import jiguang.chat.R;
import jiguang.chat.application.JGApplication;
import jiguang.chat.model.AppBean;
import jiguang.chat.utils.event.ImageEvent;

public class AppsAdapter extends BaseAdapter {

    private LayoutInflater inflater;
    private Context mContext;
    private ArrayList<AppBean> mDdata = new ArrayList<AppBean>();

    public AppsAdapter(Context context, ArrayList<AppBean> data) {
        this.mContext = context;
        this.inflater = LayoutInflater.from(context);
        if (data != null) {
            this.mDdata = data;
        }
    }

    @Override
    public int getCount() {
        return mDdata.size();
    }

    @Override
    public Object getItem(int position) {
        return mDdata.get(position);
    }

    @Override
    public long getItemId(int position) {
        return position;
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        ViewHolder viewHolder;
        if (convertView == null) {
            viewHolder = new ViewHolder();
            convertView = inflater.inflate(R.layout.item_app, null);
            viewHolder.iv_icon = (ImageView) convertView.findViewById(R.id.iv_icon);
            viewHolder.tv_name = (TextView) convertView.findViewById(R.id.tv_name);
            convertView.setTag(viewHolder);
        } else {
            viewHolder = (ViewHolder) convertView.getTag();
        }

        final AppBean appBean = mDdata.get(position);
        if (appBean != null) {
            viewHolder.iv_icon.setBackgroundResource(appBean.getIcon());
            viewHolder.tv_name.setText(appBean.getFuncName());
            convertView.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    if (appBean.getFuncName().equals("图片")) {
                        EventBus.getDefault().post(new ImageEvent(JGApplication.IMAGE_MESSAGE));
                    } else if (appBean.getFuncName().equals("拍摄")) {
                        EventBus.getDefault().post(new ImageEvent(JGApplication.TAKE_PHOTO_MESSAGE));
                    }else if (appBean.getFuncName().equals("位置")) {
                        EventBus.getDefault().post(new ImageEvent(JGApplication.TAKE_LOCATION));
                    }else if (appBean.getFuncName().equals("文件")) {
                        EventBus.getDefault().post(new ImageEvent(JGApplication.FILE_MESSAGE));
                    }else if (appBean.getFuncName().equals("视频")) {
                        EventBus.getDefault().post(new ImageEvent(JGApplication.TACK_VIDEO));
                    }else if (appBean.getFuncName().equals("语音")) {
                        EventBus.getDefault().post(new ImageEvent(JGApplication.TACK_VOICE));
                    }else if (appBean.getFuncName().equals("名片")) {
                        EventBus.getDefault().post(new ImageEvent(JGApplication.BUSINESS_CARD));
                    }
                }
            });
        }
        return convertView;
    }

    class ViewHolder {
        public ImageView iv_icon;
        public TextView tv_name;
    }
}


text:
tags: programming
layout: post
title: "CVS revision upgrade steps"
---

I don't do this often enough to be a pro, so this is partially a note for future reference. Occasionally I'll perform some numbskull maneuvers that exhibit themselves when I upgrade a CPAN module: the new version includes classes that have VERSION numbers older than ones already in the repository. (Somehow, merlyn always catches these. Magic.) Since I use CVS to generate my version strings, I'll need to tell CVS to upgrade the revision number. This is easy:

$ cvs commit -r 2.16 Foo.pm

However, this leaves a sticky tag on the file:

$ more CVS/Entries
/Foo.pm/2.16/Mon Sep 16 19:53:34 2002//T2.16

And if you try to change it and commit it, CVS will give you a nasty warning (which I can't remember right now) and refuse to commit the changes. To fix this you need to remove the sticky tag, which is also easy:

$ cvs update -A Foo.pm
$ more CVS/Entries
/Foo.pm/2.16/Mon Sep 16 19:53:34 2002//