// Copyright 2009 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.

// The wire protocol for HTTP's "chunked" Transfer-Encoding.

// Package internal contains HTTP internals shared by net/http and
// net/http/httputil.
package internal

import (
	"bufio"
	"bytes"
	"errors"
	"fmt"
	"io"
)

const maxLineLength = 4096 // assumed <= bufio.defaultBufSize

var ErrLineTooLong = errors.New("header line too long")

// NewChunkedReader returns a new chunkedReader that translates the data read from r
// out of HTTP "chunked" format before returning it.
// The chunkedReader returns io.EOF when the final 0-length chunk is read.
//
// NewChunkedReader is not needed by normal applications. The http package
// automatically decodes chunking when reading response bodies.
func NewChunkedReader(r io.Reader) io.Reader {
	br, ok := r.(*bufio.Reader)
	if !ok {
		br = bufio.NewReader(r)
	}
	return &chunkedReader{r: br}
}

type chunkedReader struct {
	r        *bufio.Reader
	n        uint64 // unread bytes in chunk
	err      error
	buf      [2]byte
	checkEnd bool // whether need to check for \r\n chunk footer
}

func (cr *chunkedReader) beginChunk() {
	// chunk-size CRLF
	var line []byte
	line, cr.err = readChunkLine(cr.r)
	if cr.err != nil {
		return
	}
	cr.n, cr.err = parseHexUint(line)
	if cr.err != nil {
		return
	}
	if cr.n == 0 {
		cr.err = io.EOF
	}
}

func (cr *chunkedReader) chunkHeaderAvailable() bool {
	n := cr.r.Buffered()
	if n > 0 {
		peek, _ := cr.r.Peek(n)
		return bytes.IndexByte(peek, '\n') >= 0
	}
	return false
}

func (cr *chunkedReader) Read(b []uint8) (n int, err error) {
	for cr.err == nil {
		if cr.checkEnd {
			if n > 0 && cr.r.Buffered() < 2 {
				// We have some data. Return early (per the io.Reader
				// contract) instead of potentially blocking while
				// reading more.
				break
			}
			if _, cr.err = io.ReadFull(cr.r, cr.buf[:2]); cr.err == nil {
				if string(cr.buf[:]) != "\r\n" {
					cr.err = errors.New("malformed chunked encoding")
					break
				}
			}
			cr.checkEnd = false
		}
		if cr.n == 0 {
			if n > 0 && !cr.chunkHeaderAvailable() {
				// We've read enough. Don't potentially block
				// reading a new chunk header.
				break
			}
			cr.beginChunk()
			continue
		}
		if len(b) == 0 {
			break
		}
		rbuf := b
		if uint64(len(rbuf)) > cr.n {
			rbuf = rbuf[:cr.n]
		}
		var n0 int
		n0, cr.err = cr.r.Read(rbuf)
		n += n0
		b = b[n0:]
		cr.n -= uint64(n0)
		// If we're at the end of a chunk, read the next two
		// bytes to verify they are "\r\n".
		if cr.n == 0 && cr.err == nil {
			cr.checkEnd = true
		}
	}
	return n, cr.err
}

// Read a line of bytes (up to \n) from b.
// Give up if the line exceeds maxLineLength.
// The returned bytes are owned by the bufio.Reader
// so they are only valid until the next bufio read.
func readChunkLine(b *bufio.Reader) ([]byte, error) {
	p, err := b.ReadSlice('\n')
	if err != nil {
		// We always know when EOF is coming.
		// If the caller asked for a line, there should be a line.
		if err == io.EOF {
			err = io.ErrUnexpectedEOF
		} else if err == bufio.ErrBufferFull {
			err = ErrLineTooLong
		}
		return nil, err
	}
	if len(p) >= maxLineLength {
		return nil, ErrLineTooLong
	}
	p = trimTrailingWhitespace(p)
	p, err = removeChunkExtension(p)
	if err != nil {
		return nil, err
	}
	return p, nil
}

func trimTrailingWhitespace(b []byte) []byte {
	for len(b) > 0 && isASCIISpace(b[len(b)-1]) {
		b = b[:len(b)-1]
	}
	return b
}

func isASCIISpace(b byte) bool {
	return b == ' ' || b == '\t' || b == '\n' || b == '\r'
}

// removeChunkExtension removes any chunk-extension from p.
// For example,
//     "0" => "0"
//     "0;token" => "0"
//     "0;token=val" => "0"
//     `0;token="quoted string"` => "0"
func removeChunkExtension(p []byte) ([]byte, error) {
	semi := bytes.IndexByte(p, ';')
	if semi == -1 {
		return p, nil
	}
	// TODO: care about exact syntax of chunk extensions? We're
	// ignoring and stripping them anyway. For now just never
	// return an error.
	return p[:semi], nil
}

// NewChunkedWriter returns a new chunkedWriter that translates writes into HTTP
// "chunked" format before writing them to w. Closing the returned chunkedWriter
// sends the final 0-length chunk that marks the end of the stream but does
// not send the final CRLF that appears after trailers; trailers and the last
// CRLF must be written separately.
//
// NewChunkedWriter is not needed by normal applications. The http
// package adds chunking automatically if handlers don't set a
// Content-Length header. Using newChunkedWriter inside a handler
// would result in double chunking or chunking with a Content-Length
// length, both of which are wrong.
func NewChunkedWriter(w io.Writer) io.WriteCloser {
	return &chunkedWriter{w}
}

// Writing to chunkedWriter translates to writing in HTTP chunked Transfer
// Encoding wire format to the underlying Wire chunkedWriter.
type chunkedWriter struct {
	Wire io.Writer
}

// Write the contents of data as one chunk to Wire.
// NOTE: Note that the corresponding chunk-writing procedure in Conn.Write has
// a bug since it does not check for success of io.WriteString
func (cw *chunkedWriter) Write(data []byte) (n int, err error) {

	// Don't send 0-length data. It looks like EOF for chunked encoding.
	if len(data) == 0 {
		return 0, nil
	}

	if _, err = fmt.Fprintf(cw.Wire, "%x\r\n", len(data)); err != nil {
		return 0, err
	}
	if n, err = cw.Wire.Write(data); err != nil {
		return
	}
	if n != len(data) {
		err = io.ErrShortWrite
		return
	}
	if _, err = io.WriteString(cw.Wire, "\r\n"); err != nil {
		return
	}
	if bw, ok := cw.Wire.(*FlushAfterChunkWriter); ok {
		err = bw.Flush()
	}
	return
}

func (cw *chunkedWriter) Close() error {
	_, err := io.WriteString(cw.Wire, "0\r\n")
	return err
}

// FlushAfterChunkWriter signals from the caller of NewChunkedWriter
// that each chunk should be followed by a flush. It is used by the
// http.Transport code to keep the buffering behavior for headers and
// trailers, but flush out chunks aggressively in the middle for
// request bodies which may be generated slowly. See Issue 6574.
type FlushAfterChunkWriter struct {
	*bufio.Writer
}

func parseHexUint(v []byte) (n uint64, err error) {
	for i, b := range v {
		switch {
		case '0' <= b && b <= '9':
			b = b - '0'
		case 'a' <= b && b <= 'f':
			b = b - 'a' + 10
		case 'A' <= b && b <= 'F':
			b = b - 'A' + 10
		default:
			return 0, errors.New("invalid byte in chunk length")
		}
		if i == 16 {
			return 0, errors.New("http chunk length too large")
		}
		n <<= 4
		n |= uint64(b)
	}
	return
}

{'repo_name': 'golang/gofrontend', 'stars': '407', 'repo_language': 'Go', 'file_name': 'types.cc', 'mime_type': 'text/x-c', 'hash': -8798588428305689988, 'source_dataset': 'data'}


<?php
/**
 * Zend Framework
 *
 * LICENSE
 *
 * This source file is subject to the new BSD license that is bundled
 * with this package in the file LICENSE.txt.
 * It is also available through the world-wide-web at this URL:
 * http://framework.zend.com/license/new-bsd
 * If you did not receive a copy of the license and are unable to
 * obtain it through the world-wide-web, please send an email
 * to license@zend.com so we can send you a copy immediately.
 *
 * @category   Zend
 * @package    Zend_Translate
 * @copyright  Copyright (c) 2005-2012 Zend Technologies USA Inc. (http://www.zend.com)
 * @version    $Id: Tmx.php 24649 2012-02-26 03:37:54Z adamlundrigan $
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 */

/** Zend_Locale */
require_once 'Zend/Locale.php';

/** Zend_Translate_Adapter */
require_once 'Zend/Translate/Adapter.php';

/**
 * @category   Zend
 * @package    Zend_Translate
 * @copyright  Copyright (c) 2005-2012 Zend Technologies USA Inc. (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 */
class Zend_Translate_Adapter_Tmx extends Zend_Translate_Adapter {
    // Internal variables
    private $_file    = false;
    private $_useId   = true;
    private $_srclang = null;
    private $_tu      = null;
    private $_tuv     = null;
    private $_seg     = null;
    private $_content = null;
    private $_data    = array();

    /**
     * Load translation data (TMX file reader)
     *
     * @param  string  $filename  TMX file to add, full path must be given for access
     * @param  string  $locale    Locale has no effect for TMX because TMX defines all languages within
     *                            the source file
     * @param  array   $option    OPTIONAL Options to use
     * @throws Zend_Translation_Exception
     * @return array
     */
    protected function _loadTranslationData($filename, $locale, array $options = array())
    {
        $this->_data = array();
        if (!is_readable($filename)) {
            require_once 'Zend/Translate/Exception.php';
            throw new Zend_Translate_Exception('Translation file \'' . $filename . '\' is not readable.');
        }

        if (isset($options['useId'])) {
            $this->_useId = (boolean) $options['useId'];
        }

        $encoding = $this->_findEncoding($filename);
        $this->_file = xml_parser_create($encoding);
        xml_set_object($this->_file, $this);
        xml_parser_set_option($this->_file, XML_OPTION_CASE_FOLDING, 0);
        xml_set_element_handler($this->_file, "_startElement", "_endElement");
        xml_set_character_data_handler($this->_file, "_contentElement");

        if (!xml_parse($this->_file, file_get_contents($filename))) {
            $ex = sprintf('XML error: %s at line %d of file %s',
                          xml_error_string(xml_get_error_code($this->_file)),
                          xml_get_current_line_number($this->_file),
                          $filename);
            xml_parser_free($this->_file);
            require_once 'Zend/Translate/Exception.php';
            throw new Zend_Translate_Exception($ex);
        }

        return $this->_data;
    }

    /**
     * Internal method, called by xml element handler at start
     *
     * @param resource $file   File handler
     * @param string   $name   Elements name
     * @param array    $attrib Attributes for this element
     */
    protected function _startElement($file, $name, $attrib)
    {
        if ($this->_seg !== null) {
            $this->_content .= "<".$name;
            foreach($attrib as $key => $value) {
                $this->_content .= " $key=\"$value\"";
            }
            $this->_content .= ">";
        } else {
            switch(strtolower($name)) {
                case 'header':
                    if (empty($this->_useId) && isset($attrib['srclang'])) {
                        if (Zend_Locale::isLocale($attrib['srclang'])) {
                            $this->_srclang = Zend_Locale::findLocale($attrib['srclang']);
                        } else {
                            if (!$this->_options['disableNotices']) {
                                if ($this->_options['log']) {
                                    $this->_options['log']->notice("The language '{$attrib['srclang']}' can not be set because it does not exist.");
                                } else {
                                    trigger_error("The language '{$attrib['srclang']}' can not be set because it does not exist.", E_USER_NOTICE);
                                }
                            }

                            $this->_srclang = $attrib['srclang'];
                        }
                    }
                    break;
                case 'tu':
                    if (isset($attrib['tuid'])) {
                        $this->_tu = $attrib['tuid'];
                    }
                    break;
                case 'tuv':
                    if (isset($attrib['xml:lang'])) {
                        if (Zend_Locale::isLocale($attrib['xml:lang'])) {
                            $this->_tuv = Zend_Locale::findLocale($attrib['xml:lang']);
                        } else {
                            if (!$this->_options['disableNotices']) {
                                if ($this->_options['log']) {
                                    $this->_options['log']->notice("The language '{$attrib['xml:lang']}' can not be set because it does not exist.");
                                } else {
                                    trigger_error("The language '{$attrib['xml:lang']}' can not be set because it does not exist.", E_USER_NOTICE);
                                }
                            }

                            $this->_tuv = $attrib['xml:lang'];
                        }

                        if (!isset($this->_data[$this->_tuv])) {
                            $this->_data[$this->_tuv] = array();
                        }
                    }
                    break;
                case 'seg':
                    $this->_seg     = true;
                    $this->_content = null;
                    break;
                default:
                    break;
            }
        }
    }

    /**
     * Internal method, called by xml element handler at end
     *
     * @param resource $file   File handler
     * @param string   $name   Elements name
     */
    protected function _endElement($file, $name)
    {
        if (($this->_seg !== null) and ($name !== 'seg')) {
            $this->_content .= "</".$name.">";
        } else {
            switch (strtolower($name)) {
                case 'tu':
                    $this->_tu = null;
                    break;
                case 'tuv':
                    $this->_tuv = null;
                    break;
                case 'seg':
                    $this->_seg = null;
                    if (!empty($this->_srclang) && ($this->_srclang == $this->_tuv)) {
                        $this->_tu = $this->_content;
                    }

                    if (!empty($this->_content) or (!isset($this->_data[$this->_tuv][$this->_tu]))) {
                        $this->_data[$this->_tuv][$this->_tu] = $this->_content;
                    }
                    break;
                default:
                    break;
            }
        }
    }

    /**
     * Internal method, called by xml element handler for content
     *
     * @param resource $file File handler
     * @param string   $data Elements content
     */
    protected function _contentElement($file, $data)
    {
        if (($this->_seg !== null) and ($this->_tu !== null) and ($this->_tuv !== null)) {
            $this->_content .= $data;
        }
    }

    /**
     * Internal method, detects the encoding of the xml file
     *
     * @param string $name Filename
     * @return string Encoding
     */
    protected function _findEncoding($filename)
    {
        $file = file_get_contents($filename, null, null, 0, 100);
        if (strpos($file, "encoding") !== false) {
            $encoding = substr($file, strpos($file, "encoding") + 9);
            $encoding = substr($encoding, 1, strpos($encoding, $encoding[0], 1) - 1);
            return $encoding;
        }
        return 'UTF-8';
    }

    /**
     * Returns the adapter name
     *
     * @return string
     */
    public function toString()
    {
        return "Tmx";
    }
}

{'repo_name': 'Xtraball/Siberian', 'stars': '118', 'repo_language': 'JavaScript', 'file_name': 'edit.js', 'mime_type': 'text/plain', 'hash': 7582377650349200094, 'source_dataset': 'data'}


/*
 * Copyright (c) 2001-2004 Swedish Institute of Computer Science.
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without modification,
 * are permitted provided that the following conditions are met:
 *
 * 1. Redistributions of source code must retain the above copyright notice,
 *    this list of conditions and the following disclaimer.
 * 2. Redistributions in binary form must reproduce the above copyright notice,
 *    this list of conditions and the following disclaimer in the documentation
 *    and/or other materials provided with the distribution.
 * 3. The name of the author may not be used to endorse or promote products
 *    derived from this software without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED
 * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
 * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT
 * SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
 * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT
 * OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
 * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
 * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING
 * IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY
 * OF SUCH DAMAGE.
 *
 * This file is part of the lwIP TCP/IP stack.
 *
 * Author: Martin Hentschel <info@cl-soft.de>
 *
 */

#ifndef LWIP_HDR_APPS_SNMP_CORE_PRIV_H
#define LWIP_HDR_APPS_SNMP_CORE_PRIV_H

#include "lwip/apps/snmp_opts.h"

#if LWIP_SNMP /* don't build if not configured for use in lwipopts.h */

#include "lwip/apps/snmp_core.h"
#include "snmp_asn1.h"

#ifdef __cplusplus
extern "C" {
#endif

/* (outdated) SNMPv1 error codes
 * shall not be used by MIBS anymore, nevertheless required from core for properly answering a v1 request
 */
#define SNMP_ERR_NOSUCHNAME 2
#define SNMP_ERR_BADVALUE   3
#define SNMP_ERR_READONLY   4
/* error codes which are internal and shall not be used by MIBS
 * shall not be used by MIBS anymore, nevertheless required from core for properly answering a v1 request
 */
#define SNMP_ERR_TOOBIG               1
#define SNMP_ERR_AUTHORIZATIONERROR   16
#define SNMP_ERR_NOSUCHOBJECT         SNMP_VARBIND_EXCEPTION_OFFSET + SNMP_ASN1_CONTEXT_VARBIND_NO_SUCH_OBJECT
#define SNMP_ERR_ENDOFMIBVIEW         SNMP_VARBIND_EXCEPTION_OFFSET + SNMP_ASN1_CONTEXT_VARBIND_END_OF_MIB_VIEW

const struct snmp_node* snmp_mib_tree_resolve_exact(const struct snmp_mib *mib, const u32_t *oid, u8_t oid_len, u8_t* oid_instance_len);
const struct snmp_node* snmp_mib_tree_resolve_next(const struct snmp_mib *mib, const u32_t *oid, u8_t oid_len, struct snmp_obj_id* oidret);

typedef u8_t (*snmp_validate_node_instance_method)(struct snmp_node_instance*, void*);

u8_t snmp_get_node_instance_from_oid(const u32_t *oid, u8_t oid_len, struct snmp_node_instance* node_instance);
u8_t snmp_get_next_node_instance_from_oid(const u32_t *oid, u8_t oid_len, snmp_validate_node_instance_method validate_node_instance_method, void* validate_node_instance_arg, struct snmp_obj_id* node_oid, struct snmp_node_instance* node_instance);

#ifdef __cplusplus
}
#endif

#endif /* LWIP_SNMP */

#endif /* LWIP_HDR_APPS_SNMP_CORE_PRIV_H */

{'repo_name': 'ps2dev/ps2sdk', 'stars': '385', 'repo_language': 'C', 'file_name': 'time.h', 'mime_type': 'text/x-c', 'hash': 2172748837772099014, 'source_dataset': 'data'}


/************************************************************************************
Filename    :   Win32_ControlMethods.h
Content     :   Shared functionality for the VR control methods
Created     :   October 20th, 2014
Author      :   Tom Heath
Copyright   :   Copyright 2014 Oculus, Inc. All Rights reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*************************************************************************************/
#ifndef OVR_Win32_ControlMethods_h
#define OVR_Win32_ControlMethods_h

//-------------------------------------------
XMFLOAT3 GetEulerAngles(XMVECTOR q)
{
	XMFLOAT3 euler;
	XMFLOAT3 forward; XMStoreFloat3(&forward, XMVector3Rotate(XMVectorSet(0, 0, 1, 0), q));
	euler.y = atan2(forward.x , forward.z);
	float horizLength = sqrt(forward.x*forward.x + forward.z*forward.z);
	euler.x = atan2(forward.y, horizLength);
	XMFLOAT3 right; XMStoreFloat3(&right, XMVector3Rotate(XMVectorSet(1, 0, 0, 0), q));
	horizLength = sqrt(right.x*right.x + right.z*right.z);
	euler.z = atan2(right.y, horizLength);
	//Util.Output("Pitch = %0.0f, Yaw = %0.0f, Roll = %0.0f\n", XMConvertToDegrees(euler.x), XMConvertToDegrees(euler.y), XMConvertToDegrees(euler.z));
	return(euler);
}

//--------------------------------------------
XMVECTOR GetAutoYawRotation(VRLayer * vrLayer)
{
    // Increments in yaw are proportional to Rift yaw
    static float Yaw = 3.141f;
    XMVECTOR orientQuat= ConvertToXM(vrLayer->EyeRenderPose[0].Orientation);
	float yaw = GetEulerAngles(orientQuat).y;
    Yaw += yaw*0.02f;
    return (XMQuaternionRotationRollPitchYaw(0,Yaw,0));
}

//----------------------------------------------------------------------
bool WasItTapped(ovrVector3f linearAcc)
{
    const float thresholdForTap = 10.0f;
    const float thresholdForReset = 2.0f;
	float magOfAccel = XMVectorGetX(XMVector3Length(ConvertToXM(linearAcc)));
    static bool readyForNewSingleTap = false;
    if (magOfAccel < thresholdForReset)
        readyForNewSingleTap = true;
    if ((readyForNewSingleTap) && (magOfAccel > thresholdForTap))
    {
        readyForNewSingleTap = false;
        return(true);
    }
    return(false);
}

//---------------------------------------------------
float GetAccelJumpPosY(BasicVR * pBasicVR, ovrTrackingState * pTrackingState)
{
    // Change y position - note, we need to keep a version here
    // As the one in ActionFromInput will keep resetting us to height of the character
    static float yPos = ovr_GetFloat(pBasicVR->Session, OVR_KEY_EYE_HEIGHT, 0);
    static float yVel = 0;

    // Jump into air manually with '1' key
    if (DIRECTX.Key['1']) yVel += 0.01f;

    // Jump from head movement - note, its slightly counter intuitive - instead of responding to the 'up' accel,
    // it lets that one get absorbed by the ground, and acts on the deceleration from the upward movement.
	// Alternative : You could also try yVel += - min(0,jumpResponse*pTrackingState->HeadPose.LinearAcceleration.y);
	//               in the below code. This has facets that are interesting, in allowing multiple jumps,
	//               and eliminates any downward midair movement - but leaves the motion unbounded.
    const float jumpResponse = 0.0015f;
    yVel += - jumpResponse*pTrackingState->HeadPose.LinearAcceleration.y;

    // Add pseudo gravity
    yVel += -0.002f;

    // Increment position
    yPos += yVel;

    // Hit floor;
    if (yPos < 1.6f) ///ovr_GetFloat(pBasicVR->Session, OVR_KEY_EYE_HEIGHT, 0))  No longer works
    {
		yPos = 1.6f;/// ovr_GetFloat(pBasicVR->Session, OVR_KEY_EYE_HEIGHT, 0);
        yVel = 0;
    }

    return(yPos);
}

//-----------------------------------------------------------------------
XMVECTOR FindVelocityFromTilt(BasicVR * pBasicVR, VRLayer * vrLayer, ovrTrackingState * pTrackingState)
{
    // Find the orthogonal vectors resulting from combined rift and user yaw
	XMVECTOR orientQuat = ConvertToXM(vrLayer->EyeRenderPose[0].Orientation);
	XMFLOAT3 eulerFromRift = GetEulerAngles(orientQuat);

	XMVECTOR totalHorizRot = XMQuaternionMultiply(pBasicVR->MainCam->Rot,XMQuaternionRotationRollPitchYaw(0,eulerFromRift.y,0));
    XMVECTOR unitForwardVector = XMVector3Rotate(XMVectorSet(0,0,-1,0),totalHorizRot);
    XMVECTOR unitRightVector   = XMVector3Rotate(XMVectorSet(1,0,0,0),totalHorizRot);

    // Now feed into a static velocity.
    static XMVECTOR vel = XMVectorSet(0,0,0,0);

    // Hold down space if you want to look around, instead of move
    if (!DIRECTX.Key[' '])
    {
        const float tiltResponse = 0.0075f;
        vel = XMVectorAdd(vel, XMVectorScale(unitForwardVector,tiltResponse * tan( eulerFromRift.x ))); // Pitch
        vel = XMVectorSubtract(vel, XMVectorScale(unitRightVector,  tiltResponse * tan( eulerFromRift.z ))); // Roll
    }

    // We always have damping, to cap top speeds
    // and to damp to zero when space is released.
    vel = XMVectorScale(vel,0.98f);

    // Limit velocity
    const float maxSpeed = 0.1f;
    float speed = XMVectorGetX(XMVector3Length(vel));
	if (speed > maxSpeed) vel = XMVectorScale(vel, maxSpeed / speed);;

    return(vel);
}

#endif // OVR_Win32_ControlMethods_h

{'repo_name': 'jherico/OculusSDK', 'stars': '173', 'repo_language': 'C++', 'file_name': 'Logging_Tools.h', 'mime_type': 'text/x-c++', 'hash': 9159970542861174136, 'source_dataset': 'data'}


使用类扫描
------------------------------------
在一些情况下，经常会以类扫描的形式在启动时找到某些类。

Hasor是具备类扫描功能的，默认情况下 Hasor 在启动时不会进行类扫描。除非您使用了某些 Api 或插件引发了类扫描。

下面假定我们有一个接口，这个接口有若干实现类，例如 Module 接口。我们希望找到所有 Module 接口的实现类。那么可以这样：

.. code-block:: java
    :linenos:

    Set<Class<?>> aClass = apiBinder.findClass(Module.class);

再比如，我们有一个注解 @MappingTo 现在想找到标记了这个注解的所有类。那么可以这样：

.. code-block:: java
    :linenos:

    Set<Class<?>> aClass = apiBinder.findClass(MappingTo.class);

倘若我想寻找某个类的子类呢，可以这样：

.. code-block:: java
    :linenos:

    Set<Class<?>> aClass = apiBinder.findClass(AbstractUser.class);

下面要说的这些场景 Hasor 的类扫描机制是无法满足的。

1. 我想找到包含某个方法的所有类。
2. 我想找到方法上标记了某个注解的所有类。
3. 扫描类并返回要找的方法。
4. 根据某个特殊规则扫描并返回类的集合。

{'repo_name': 'zycgit/hasor', 'stars': '563', 'repo_language': 'Java', 'file_name': 'TokenTest.java', 'mime_type': 'text/x-java', 'hash': -5000870673074286171, 'source_dataset': 'data'}


package railo.runtime.com;

import java.util.Iterator;

import com.jacob.com.EnumVariant;

/**
 *
 */
public final class COMValueWrapperIterator implements Iterator {

    private EnumVariant enumVariant;
    private COMObject wrapper;

    /**
     * @param wrapper
     */
    public COMValueWrapperIterator(COMObject wrapper) {
        this.enumVariant=new EnumVariant(wrapper.getDispatch());
        this.wrapper=wrapper;
    }

    @Override
    public void remove() {
        enumVariant.safeRelease();
    }

    @Override
    public boolean hasNext() {
        return enumVariant.hasMoreElements();
    }

    @Override
    public Object next() {
        return COMUtil.toObject(wrapper,enumVariant.Next(),"",null);
    }
}

{'repo_name': 'getrailo/railo', 'stars': '247', 'repo_language': 'Java', 'file_name': 'JiraXXXX.cfc', 'mime_type': 'text/plain', 'hash': -3828319255742219344, 'source_dataset': 'data'}


# Traducerea kwin_clients.po în Română
# translation of kwin_clients to Romanian
# Copyright (C) 2008 This_file_is_part_of_KDE
# This file is distributed under the same license as the kwin_clients package.
#
# Laurenţiu Buzdugan <lbuz@rolix.org>, 2008".
# Sergiu Bivol <sergiu-bivol@mail.md>, 2008.
# Sergiu Bivol <sergiu@ase.md>, 2008, 2009, 2011, 2013.
# Cristian Oneț <onet.cristian@gmail.com>, 2011.
# Cristian Buzduga <cristianbzdg@gmail.com>, 2011.
msgid ""
msgstr ""
"Project-Id-Version: kwin_clients\n"
"Report-Msgid-Bugs-To: https://bugs.kde.org\n"
"POT-Creation-Date: 2020-03-18 03:45+0100\n"
"PO-Revision-Date: 2013-11-26 23:25+0200\n"
"Last-Translator: Sergiu Bivol <sergiu@ase.md>\n"
"Language-Team: Romanian <kde-i18n-ro@kde.org>\n"
"Language: ro\n"
"MIME-Version: 1.0\n"
"Content-Type: text/plain; charset=UTF-8\n"
"Content-Transfer-Encoding: 8bit\n"
"Plural-Forms: nplurals=3; plural=n==1 ? 0 : (n==0 || (n%100 > 0 && n%100 < "
"20)) ? 1 : 2;\n"
"X-Generator: Lokalize 1.5\n"

#: aurorae/src/aurorae.cpp:694
#, fuzzy, kde-format
#| msgctxt "@item:inlistbox Border size:"
#| msgid "Tiny"
msgctxt "@item:inlistbox Button size:"
msgid "Tiny"
msgstr "Minusculă"

#: aurorae/src/aurorae.cpp:695
#, kde-format
msgctxt "@item:inlistbox Button size:"
msgid "Normal"
msgstr "Normală"

#: aurorae/src/aurorae.cpp:696
#, kde-format
msgctxt "@item:inlistbox Button size:"
msgid "Large"
msgstr "Mare"

#: aurorae/src/aurorae.cpp:697
#, kde-format
msgctxt "@item:inlistbox Button size:"
msgid "Very Large"
msgstr "Foarte mare"

#: aurorae/src/aurorae.cpp:698
#, kde-format
msgctxt "@item:inlistbox Button size:"
msgid "Huge"
msgstr "Imensă"

#: aurorae/src/aurorae.cpp:699
#, fuzzy, kde-format
#| msgctxt "@item:inlistbox Border size:"
#| msgid "Very Huge"
msgctxt "@item:inlistbox Button size:"
msgid "Very Huge"
msgstr "Extrem de mare"

#: aurorae/src/aurorae.cpp:700
#, fuzzy, kde-format
#| msgctxt "@item:inlistbox Border size:"
#| msgid "Oversized"
msgctxt "@item:inlistbox Button size:"
msgid "Oversized"
msgstr "Supradimensionată"

#: aurorae/src/aurorae.cpp:703
#, fuzzy, kde-format
#| msgid "B&utton size:"
msgid "Button size:"
msgstr "Dimensiune b&uton:"

#. i18n: ectx: property (windowTitle), widget (QWidget, PlastikConfigDialog)
#: aurorae/themes/plastik/package/contents/ui/config.ui:14
#, kde-format
msgid "Config Dialog"
msgstr "Dialog de configurare"

#. i18n: ectx: property (title), widget (KButtonGroup, titleAlign)
#: aurorae/themes/plastik/package/contents/ui/config.ui:23
#, kde-format
msgid "Title &Alignment"
msgstr "&Aliniere titlu"

#. i18n: ectx: property (text), widget (QRadioButton, kcfg_titleAlignLeft)
#: aurorae/themes/plastik/package/contents/ui/config.ui:29
#, kde-format
msgid "Left"
msgstr "Stânga"

#. i18n: ectx: property (text), widget (QRadioButton, kcfg_titleAlignCenter)
#: aurorae/themes/plastik/package/contents/ui/config.ui:36
#, kde-format
msgid "Center"
msgstr "Centru"

#. i18n: ectx: property (text), widget (QRadioButton, kcfg_titleAlignRight)
#: aurorae/themes/plastik/package/contents/ui/config.ui:43
#, kde-format
msgid "Right"
msgstr "Dreapta"

#. i18n: ectx: property (whatsThis), widget (QCheckBox, kcfg_coloredBorder)
#: aurorae/themes/plastik/package/contents/ui/config.ui:53
#, kde-format
msgid ""
"Check this option if the window border should be painted in the titlebar "
"color. Otherwise it will be painted in the background color."
msgstr ""
"Bifați această opțiune dacă marginea ferestrei trebuie să fie pictată în "
"culoarea barei de titlu. Altfel va fi pictată în culoarea fundalului."

#. i18n: ectx: property (text), widget (QCheckBox, kcfg_coloredBorder)
#: aurorae/themes/plastik/package/contents/ui/config.ui:56
#, kde-format
msgid "Colored window border"
msgstr "Chenar de fereastră colorat"

#. i18n: ectx: property (whatsThis), widget (QCheckBox, kcfg_animateButtons)
#: aurorae/themes/plastik/package/contents/ui/config.ui:66
#, kde-format
msgid ""
"Check this option if you want the buttons to fade in when the mouse pointer "
"hovers over them and fade out again when it moves away."
msgstr ""
"Bifați această opțiune dacă doriți ca butoanele să apară gradual când "
"indicatorul de maus planează peste ele și să se estompeze iar când este dat "
"deoparte."

#. i18n: ectx: property (text), widget (QCheckBox, kcfg_animateButtons)
#: aurorae/themes/plastik/package/contents/ui/config.ui:69
#, kde-format
msgid "Animate buttons"
msgstr "Butoane animate"

{'repo_name': 'tildearrow/kwin-lowlatency', 'stars': '257', 'repo_language': 'C++', 'file_name': 'CMakeLists.txt', 'mime_type': 'text/plain', 'hash': -2819286127040041422, 'source_dataset': 'data'}


<!DOCTYPE html>

<meta name="generator" content="Hexo 3.9.0">
  <meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=2">
<meta name="theme-color" content="#222">

  <link rel="stylesheet" href="/ChineseBQB/lib/pace/pace-theme-minimal.min.css?v=1.0.2">

<link rel="stylesheet" href="/ChineseBQB/lib/font-awesome/css/font-awesome.min.css?v=4.6.2">

<link rel="stylesheet" href="/ChineseBQB/css/main.css?v=7.1.2">

  <link rel="apple-touch-icon" sizes="180x180" href="/ChineseBQB/images/apple-touch-icon-next.png?v=7.1.2">

  <link rel="icon" type="image/png" sizes="32x32" href="/ChineseBQB/images/favicon-32x32-next.png?v=7.1.2">

  <link rel="icon" type="image/png" sizes="16x16" href="/ChineseBQB/images/favicon-16x16-next.png?v=7.1.2">

  <link rel="mask-icon" href="/ChineseBQB/images/logo.svg?v=7.1.2" color="#222">

  <meta name="description" content="中国人的表情包">
<meta name="keywords" content="zhaoolee 木子昭 中国人的表情包">
<meta property="og:type" content="website">
<meta property="og:title" content="中国人的表情包">
<meta property="og:url" content="http://zhaoolee.github.io/ChineseBQB/tags/045MatchstickMen-火柴人BQB/index.html">
<meta property="og:site_name" content="中国人的表情包">
<meta property="og:description" content="中国人的表情包">
<meta property="og:locale" content="zh-CN">
<meta name="twitter:card" content="summary">
<meta name="twitter:title" content="中国人的表情包">
<meta name="twitter:description" content="中国人的表情包">

  <link rel="canonical" href="http://zhaoolee.github.io/ChineseBQB/tags/045MatchstickMen-火柴人BQB/">

  <title>标签: 045MatchstickMen_火柴人BQB | 中国人的表情包</title>

        中国人的表情包

zhaoolee 木子昭 中国人的表情包

    <button aria-label="切换导航栏">

    </button>

首页

关于

标签

分类

站点地图

搜索

      <input autocomplete="off" placeholder="搜索..." spellcheck="false" type="text" id="local-search-input">

<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/font-awesome/css/font-awesome.min.css">

045MatchstickMen_火柴人BQB标签

              045MatchstickMen_火柴人BQB

        <time class="post-time" itemprop="dateCreated" datetime="2020-04-24T13:44:46+08:00" content="2020-04-24">
          04-24
        </time>

zhaoolee

中国人的表情包

                    70
                    日志

                    70
                    分类

                    70
                    标签

                  GitHub

                  E-Mail

© 2020

  zhaoolee

          0%

{'repo_name': 'zhaoolee/ChineseBQB', 'stars': '7311', 'repo_language': 'JavaScript', 'file_name': 'index.md', 'mime_type': 'text/plain', 'hash': -7340032830398731464, 'source_dataset': 'data'}


package google

import (
	"fmt"
	"testing"

	"github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource"
)

func TestAccCloudRunService_cloudRunServiceUpdate(t *testing.T) {
	t.Parallel()

	project := getTestProjectFromEnv()
	name := "tftest-cloudrun-" + randString(t, 6)

	vcrTest(t, resource.TestCase{
		PreCheck:  func() { testAccPreCheck(t) },
		Providers: testAccProviders,
		Steps: []resource.TestStep{
			{
				Config: testAccCloudRunService_cloudRunServiceUpdate(name, project, "10", "600"),
			},
			{
				ResourceName:            "google_cloud_run_service.default",
				ImportState:             true,
				ImportStateVerify:       true,
				ImportStateVerifyIgnore: []string{"metadata.0.resource_version", "status.0.conditions"},
			},
			{
				Config: testAccCloudRunService_cloudRunServiceUpdate(name, project, "50", "300"),
			},
			{
				ResourceName:            "google_cloud_run_service.default",
				ImportState:             true,
				ImportStateVerify:       true,
				ImportStateVerifyIgnore: []string{"metadata.0.resource_version", "status.0.conditions"},
			},
		},
	})
}

func testAccCloudRunService_cloudRunServiceUpdate(name, project, concurrency, timeoutSeconds string) string {
	return fmt.Sprintf(`
resource "google_cloud_run_service" "default" {
  name     = "%s"
  location = "us-central1"

  metadata {
    namespace = "%s"
  }

  template {
    spec {
      containers {
        image = "gcr.io/cloudrun/hello"
        args  = ["arrgs"]
        ports {
          container_port = 8080
        }
      }
	  container_concurrency = %s
	  timeout_seconds = %s
    }
  }

  traffic {
    percent         = 100
    latest_revision = true
  }
}
`, name, project, concurrency, timeoutSeconds)
}

{'repo_name': 'terraform-providers/terraform-provider-google', 'stars': '1128', 'repo_language': 'Go', 'file_name': 'version.go', 'mime_type': 'text/plain', 'hash': -1044477182672415780, 'source_dataset': 'data'}


'use strict';

var PingppResource = require('../PingppResource');
var pingppMethod = PingppResource.method;

module.exports = PingppResource.extend({

  path: 'apps/{appId}/users/{userId}/settle_accounts',

  create: pingppMethod({
    method: 'POST',
    urlParams: ['appId', 'userId']
  }),

  list: pingppMethod({
    method: 'GET',
    urlParams: ['appId', 'userId']
  }),

  retrieve: pingppMethod({
    method: 'GET',
    path: '/{settleAccountId}',
    urlParams: ['appId', 'userId', 'settleAccountId']
  }),

  delete: pingppMethod({
    method: 'DELETE',
    path: '/{settleAccountId}',
    urlParams: ['appId', 'userId', 'settleAccountId']
  }),

});

{'repo_name': 'PingPlusPlus/pingpp-nodejs', 'stars': '174', 'repo_language': 'JavaScript', 'file_name': 'transfer_cancel.js', 'mime_type': 'text/plain', 'hash': -4471424148168209144, 'source_dataset': 'data'}


Copyright \(c\) Microsoft Corporation. All rights reserved.

static-field instance-field static-method instance-method

{'repo_name': 'microsoft/browsecloud', 'stars': '141', 'repo_language': 'TypeScript', 'file_name': 'az-service-template.json', 'mime_type': 'text/plain', 'hash': 1033915441573012944, 'source_dataset': 'data'}


<?php

declare(strict_types = 1);

namespace Construct\Constructors;

class Vagrant extends Constructor implements ConstructorContract
{
    /**
     * Generate Vagrant file.
     *
     * @return void
     */
    public function run()
    {
        if ($this->settings->withVagrantfile()) {
            $this->filesystem->copy(
                __DIR__ . '/../stubs/Vagrantfile.stub',
                $this->settings->getProjectLower() . '/' . 'Vagrantfile'
            );

            $this->gitAttributes->addExportIgnore('Vagrantfile');
        }
    }
}

{'repo_name': 'jonathantorres/construct', 'stars': '258', 'repo_language': 'PHP', 'file_name': 'README.stub', 'mime_type': 'text/plain', 'hash': -3176354354719738874, 'source_dataset': 'data'}


Keratotomy

A surgical operation involving cutting into the cornea of the eye. The most common form is radial keratotomy, performed to correct myopia.

{'repo_name': 'Showndarya/Hacktoberfest', 'stars': '177', 'repo_language': 'Python', 'file_name': 'Complacent_adjective.json', 'mime_type': 'text/plain', 'hash': -922041951516604371, 'source_dataset': 'data'}


// Copyright 2020 yuzu Emulator Project
// Licensed under GPLv2 or any later version
// Refer to the license.txt file included.

#pragma once

#include <cstddef>
#include <memory>
#include <utility>
#include <vector>

#include "common/common_types.h"
#include "video_core/query_cache.h"
#include "video_core/renderer_vulkan/vk_resource_pool.h"
#include "video_core/renderer_vulkan/wrapper.h"

namespace VideoCore {
class RasterizerInterface;
}

namespace Vulkan {

class CachedQuery;
class HostCounter;
class VKDevice;
class VKQueryCache;
class VKScheduler;

using CounterStream = VideoCommon::CounterStreamBase<VKQueryCache, HostCounter>;

class QueryPool final : public ResourcePool {
public:
    explicit QueryPool(const VKDevice& device, VKScheduler& scheduler, VideoCore::QueryType type);
    ~QueryPool() override;

    std::pair<VkQueryPool, u32> Commit();

    void Reserve(std::pair<VkQueryPool, u32> query);

protected:
    void Allocate(std::size_t begin, std::size_t end) override;

private:
    static constexpr std::size_t GROW_STEP = 512;

    const VKDevice& device;
    const VideoCore::QueryType type;

    std::vector<vk::QueryPool> pools;
    std::vector<bool> usage;
};

class VKQueryCache final
    : public VideoCommon::QueryCacheBase<VKQueryCache, CachedQuery, CounterStream, HostCounter> {
public:
    explicit VKQueryCache(VideoCore::RasterizerInterface& rasterizer,
                          Tegra::Engines::Maxwell3D& maxwell3d, Tegra::MemoryManager& gpu_memory,
                          const VKDevice& device, VKScheduler& scheduler);
    ~VKQueryCache();

    std::pair<VkQueryPool, u32> AllocateQuery(VideoCore::QueryType type);

    void Reserve(VideoCore::QueryType type, std::pair<VkQueryPool, u32> query);

    const VKDevice& Device() const noexcept {
        return device;
    }

    VKScheduler& Scheduler() const noexcept {
        return scheduler;
    }

private:
    const VKDevice& device;
    VKScheduler& scheduler;
    std::array<QueryPool, VideoCore::NumQueryTypes> query_pools;
};

class HostCounter final : public VideoCommon::HostCounterBase<VKQueryCache, HostCounter> {
public:
    explicit HostCounter(VKQueryCache& cache, std::shared_ptr<HostCounter> dependency,
                         VideoCore::QueryType type);
    ~HostCounter();

    void EndQuery();

private:
    u64 BlockingQuery() const override;

    VKQueryCache& cache;
    const VideoCore::QueryType type;
    const std::pair<VkQueryPool, u32> query;
    const u64 tick;
};

class CachedQuery : public VideoCommon::CachedQueryBase<HostCounter> {
public:
    explicit CachedQuery(VKQueryCache&, VideoCore::QueryType, VAddr cpu_addr, u8* host_ptr)
        : VideoCommon::CachedQueryBase<HostCounter>{cpu_addr, host_ptr} {}
};

} // namespace Vulkan

{'repo_name': 'yuzu-emu/yuzu-mainline', 'stars': '248', 'repo_language': 'C++', 'file_name': 'LUrlParser.cpp', 'mime_type': 'text/x-c', 'hash': 4290324138826226809, 'source_dataset': 'data'}


/*
 * Copyright (c) Microsoft Corporation. All rights reserved.
 * Licensed under the MIT License. See License.txt in the project root for
 * license information.
 *
 * Code generated by Microsoft (R) AutoRest Code Generator.
 * Changes may cause incorrect behavior and will be lost if the code is
 * regenerated.
 */

'use strict';

/**
 * The list of integration accounts.
 */
class IntegrationAccountListResult extends Array {
  /**
   * Create a IntegrationAccountListResult.
   * @property {string} [nextLink] The URL to get the next set of results.
   */
  constructor() {
    super();
  }

  /**
   * Defines the metadata of IntegrationAccountListResult
   *
   * @returns {object} metadata of IntegrationAccountListResult
   *
   */
  mapper() {
    return {
      required: false,
      serializedName: 'IntegrationAccountListResult',
      type: {
        name: 'Composite',
        className: 'IntegrationAccountListResult',
        modelProperties: {
          value: {
            required: false,
            serializedName: '',
            type: {
              name: 'Sequence',
              element: {
                  required: false,
                  serializedName: 'IntegrationAccountElementType',
                  type: {
                    name: 'Composite',
                    className: 'IntegrationAccount'
                  }
              }
            }
          },
          nextLink: {
            required: false,
            serializedName: 'nextLink',
            type: {
              name: 'String'
            }
          }
        }
      }
    };
  }
}

module.exports = IntegrationAccountListResult;

{'repo_name': 'Azure/azure-sdk-for-node', 'stars': '1121', 'repo_language': 'JavaScript', 'file_name': 'eventHubs.js', 'mime_type': 'text/plain', 'hash': 5808601018976403950, 'source_dataset': 'data'}


--- install.rb.orig	2009-09-21 00:15:47.000000000 +0900
+++ install.rb	2011-08-07 15:23:54.000000000 +0900
@@ -649,8 +649,10 @@
       sys_version = `uname -r`.to_f
       if sys_version < 8.0
         xcode_version = 0 # <= Xcode 1.5 on MacOS X 10.3
+      elsif sys_version >= 11.0
+        xcode_version = 620 # Lion uses Xcode 4.1 or later
       elsif /DevToolsCore-(\d+)/.match(`#{buildcommand} -version`)
-        xcode_version = $1.to_i
+        xcode_version = $1.to_i # Xcode 2.x or 3.x
       else
         xcode_version = 0 # unknown
       end

{'repo_name': 'macports/macports-ports', 'stars': '752', 'repo_language': 'Tcl', 'file_name': 'exo-mmintrin.diff', 'mime_type': 'text/x-diff', 'hash': 3058592359952911726, 'source_dataset': 'data'}


using Sharpen;

namespace android.content.pm
{
	/// Basic information about a package as specified in its manifest.
	/// <remarks>
	/// Basic information about a package as specified in its manifest.
	/// Utility class used in PackageManager methods
	/// </remarks>
	/// <hide></hide>
	[Sharpen.Sharpened]
	public class PackageInfoLite : android.os.Parcelable
	{
		/// The name of this package.
		/// <remarks>
		/// The name of this package.  From the <manifest> tag's "name"
		/// attribute.
		/// </remarks>
		public string packageName;

		/// Specifies the recommended install location.
		/// <remarks>
		/// Specifies the recommended install location. Can be one of
		/// <see cref="#PackageHelper">#PackageHelper</see>
		/// to install on internal storage
		/// <see cref="#PackageHelper">#PackageHelper</see>
		/// to install on external media
		/// <see cref="PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE">PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE
		/// 	</see>
		/// for storage errors
		/// <see cref="PackageHelper.RECOMMEND_FAILED_INVALID_APK">PackageHelper.RECOMMEND_FAILED_INVALID_APK
		/// 	</see>
		/// for parse errors.
		/// </remarks>
		public int recommendedInstallLocation;

		public int installLocation;

		public android.content.pm.VerifierInfo[] verifiers;

		public PackageInfoLite()
		{
		}

		[Sharpen.OverridesMethod(@"java.lang.Object")]
		public override string ToString()
		{
			return "PackageInfoLite{" + Sharpen.Util.IntToHexString(Sharpen.Util.IdentityHashCode
				(this)) + " " + packageName + "}";
		}

		[Sharpen.ImplementsInterface(@"android.os.Parcelable")]
		public virtual int describeContents()
		{
			return 0;
		}

		[Sharpen.ImplementsInterface(@"android.os.Parcelable")]
		public virtual void writeToParcel(android.os.Parcel dest, int parcelableFlags)
		{
			dest.writeString(packageName);
			dest.writeInt(recommendedInstallLocation);
			dest.writeInt(installLocation);
			if (verifiers == null || verifiers.Length == 0)
			{
				dest.writeInt(0);
			}
			else
			{
				dest.writeInt(verifiers.Length);
				dest.writeTypedArray(verifiers, parcelableFlags);
			}
		}

		private sealed class _Creator_73 : android.os.ParcelableClass.Creator<android.content.pm.PackageInfoLite
			>
		{
			public _Creator_73()
			{
			}

			[Sharpen.ImplementsInterface(@"android.os.Parcelable.Creator")]
			public android.content.pm.PackageInfoLite createFromParcel(android.os.Parcel source
				)
			{
				return new android.content.pm.PackageInfoLite(source);
			}

			[Sharpen.ImplementsInterface(@"android.os.Parcelable.Creator")]
			public android.content.pm.PackageInfoLite[] newArray(int size)
			{
				return new android.content.pm.PackageInfoLite[size];
			}
		}

		public static readonly android.os.ParcelableClass.Creator<android.content.pm.PackageInfoLite
			> CREATOR = new _Creator_73();

		private PackageInfoLite(android.os.Parcel source)
		{
			packageName = source.readString();
			recommendedInstallLocation = source.readInt();
			installLocation = source.readInt();
			int verifiersLength = source.readInt();
			if (verifiersLength == 0)
			{
				verifiers = new android.content.pm.VerifierInfo[0];
			}
			else
			{
				verifiers = new android.content.pm.VerifierInfo[verifiersLength];
				source.readTypedArray(verifiers, android.content.pm.VerifierInfo.CREATOR);
			}
		}
	}
}

{'repo_name': 'xamarin/XobotOS', 'stars': '1264', 'repo_language': 'Java', 'file_name': 'YesNoPreference.cs', 'mime_type': 'text/plain', 'hash': 3414686803587418109, 'source_dataset': 'data'}


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

import sbt._
import sbt.Keys._
import ProguardPlugin._

object Build extends sbt.Build {

  import Dependencies._
  import Unmanaged._

  val VERSION  = "0.2.7"
  val javaHome = sys.props("java.home").replace("/jre", "")

  lazy val proguard = proguardSettings ++ Seq(
    proguardOptions := Seq(
      "-keepclasseswithmembers public class * { public static void main(java.lang.String[]); }",
      "-keep class * implements org.xml.sax.EntityResolver",
      "-keep class com.github.zhongl.housemd.** { *;} ",
      "-keep class com.github.zhongl.yascli.** { *;} ",
      "-keepclassmembers class * { ** MODULE$;}",
      """-keepclassmembernames class scala.concurrent.forkjoin.ForkJoinPool {
          long eventCount;
          int  workerCounts;
          int  runControl;
          scala.concurrent.forkjoin.ForkJoinPool$WaitQueueNode syncStack;
          scala.concurrent.forkjoin.ForkJoinPool$WaitQueueNode spareStack;
      }""",
      """-keepclassmembernames class scala.concurrent.forkjoin.ForkJoinWorkerThread {
          int base;
          int sp;
          int runState;
      }""",
      "-keepclassmembernames class scala.concurrent.forkjoin.ForkJoinTask { int status; }",
      """-keepclassmembernames class scala.concurrent.forkjoin.LinkedTransferQueue {
          scala.concurrent.forkjoin.LinkedTransferQueue$PaddedAtomicReference head;
          scala.concurrent.forkjoin.LinkedTransferQueue$PaddedAtomicReference tail;
          scala.concurrent.forkjoin.LinkedTransferQueue$PaddedAtomicReference cleanMe;
      }"""),
    proguardLibraryJars := {
      (jdkJarPath: PathFinder).get
    }
  )

  private def jdkJarPath = {
    val home = new java.io.File(sys.props("java.home"))
    val rtJar = home / "lib" / "rt.jar"
    val toolsJar = home.getParentFile / "lib" / "tools.jar"
    val classesJar = home.getParentFile / "Classes" / "classes.jar"
    if (classesJar.asFile.exists()) // it means current os is Mac OSX
      Seq(classesJar.asFile)
    else if (rtJar.asFile.exists())
      Seq(rtJar.asFile, toolsJar.asFile)
    else
      throw new IllegalStateException("Unknown location for rt.jar")
  }

  lazy val root = Project(
    id = "housemd",
    base = file("."),
    settings = Defaults.defaultSettings ++ classpathSettings ++ proguard ++ Seq(
      name := "housemd",
      organization := "com.github.zhongl",
      version := VERSION,
      scalaVersion := "2.9.2",
      scalacOptions ++= Seq("-unchecked", "-deprecation"),
      resolvers += "Local Maven Repository" at "file://" + Path.userHome.absolutePath + "/.m2/repository",
      libraryDependencies := compileLibs ++ testLibs,
      packageOptions += Package.ManifestAttributes(
        ("Main-Class", "com.github.zhongl.housemd.house.House"),
        ("Agent-Class", "com.github.zhongl.housemd.duck.Duck"),
        ("Can-Retransform-Classes", "true"),
        ("Can-Redefine-Classes", "true"),
        ("Signature-Version", VERSION)
      ),
      parallelExecution in Test := false
    )
  )

  object Dependencies {
    lazy val testLibs = Seq(
      "org.mockito" % "mockito-all" % "1.9.0" % "test",
      "org.scalatest" %% "scalatest" % "1.7.2" % "test"
    )

    lazy val compileLibs = Seq(
      "asm" % "asm" % "3.3.1",
      "asm" % "asm-commons" % "3.3.1",
      "com.github.zhongl" %% "yascli" % "0.1.0",
      "org.scala-lang" % "scala-library" % "2.9.2",
      "com.cedarsoftware" % "json-io" % "2.7.3"
    )
  }

  object Unmanaged {
    lazy val toolsFile         = file(javaHome + "/lib/tools.jar")
    lazy val classpathSettings =
      if (toolsFile.exists()) Seq(
        unmanagedClasspath in Compile += Attributed.blank(toolsFile),
        unmanagedClasspath in Test <<= unmanagedClasspath in Compile
      )
      else Seq()
  }

}

{'repo_name': 'CSUG/HouseMD', 'stars': '682', 'repo_language': 'Scala', 'file_name': 'TraceTarget.java', 'mime_type': 'text/x-c', 'hash': 8254771978326359226, 'source_dataset': 'data'}


<!DOCTYPE html>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%@ taglib prefix="spring" uri="http://www.springframework.org/tags" %>

    <title></title>

<spring:message code="label.internalservererror.page.title"/>

<spring:message code="label.internalservererror.page.message"/>

{'repo_name': 'pkainulainen/spring-mvc-test-examples', 'stars': '316', 'repo_language': 'Java', 'file_name': 'config.properties', 'mime_type': 'text/plain', 'hash': -3439212022132783222, 'source_dataset': 'data'}


1=Erro genérico
context.script.not.existing=O arquivo de script para o contexto '%0' do job '%1' não existe neste aplicativo.
etl.process.executed=Processo ETL executado.
etl.process.started=Processo ETL iniciado. O fim do processo será notificado através do portlet de eventos.
job.exectuion.error=Erro ao executar o job.
job.not.existing=O job '%0' não existe nesta aplicativo.
main.script.not.existing=O arquivo de script para o job '%0' não existe neste aplicativo.
missing.document.template=Modelo de documento ausente.
missing.talend.job=Falta o nome do job Talend no modelo do documento.
missing.talend.lang=Falta o idioma do job Talend no modelo de documento.
missing.talend.project=Falta o nome do projeto Talend no modelo do documento.
properties.file.error=Erro ao ler o arquivo talend.properties.
repository.not.available=O repositório em tempo de execução não está disponível
template.parsing.error=Erro ao analisar o modelo do documento.

{'repo_name': 'KnowageLabs/Knowage-Server', 'stars': '244', 'repo_language': 'Java', 'file_name': 'AbstractModelEditingTest.java', 'mime_type': 'text/x-java', 'hash': -2236001887403030679, 'source_dataset': 'data'}


/* GStreamer
 * Copyright (C) <2009> Edward Hervey <bilboed@bilboed.com>
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Library General Public
 * License as published by the Free Software Foundation; either
 * version 2 of the License, or (at your option) any later version.
 *
 * This library 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
 * Library General Public License for more details.
 *
 * You should have received a copy of the GNU Library General Public
 * License along with this library; if not, write to the
 * Free Software Foundation, Inc., 51 Franklin St, Fifth Floor,
 * Boston, MA 02110-1301, USA.
 */

#include <stdio.h>
#include <stdlib.h>
#include <gst/gst.h>
#include "gst/glib-compat-private.h"

#define MAX_THREADS  1000

static guint64 nbbuffers;
static GMutex mutex;

static void *
run_test (void *user_data)
{
  gint threadid = GPOINTER_TO_INT (user_data);
  guint64 nb;
  GstBuffer *buf;
  GstClockTime start, end;

  g_mutex_lock (&mutex);
  g_mutex_unlock (&mutex);

  start = gst_util_get_timestamp ();

  g_assert (nbbuffers > 0);

  for (nb = nbbuffers; nb; nb--) {
    buf = gst_buffer_new ();
    gst_buffer_unref (buf);
  }

  end = gst_util_get_timestamp ();
  g_print ("total %" GST_TIME_FORMAT " - average %" GST_TIME_FORMAT
      "  - Thread %d\n", GST_TIME_ARGS (end - start),
      GST_TIME_ARGS ((end - start) / nbbuffers), threadid);

  g_thread_exit (NULL);
  return NULL;
}

gint
main (gint argc, gchar * argv[])
{
  GThread *threads[MAX_THREADS];
  gint num_threads;
  gint t;
  GstBuffer *tmp;
  GstClockTime start, end;

  gst_init (&argc, &argv);
  g_mutex_init (&mutex);

  if (argc != 3) {
    g_print ("usage: %s <num_threads> <nbbuffers>\n", argv[0]);
    exit (-1);
  }

  num_threads = atoi (argv[1]);
  nbbuffers = atoi (argv[2]);

  if (num_threads <= 0 || num_threads > MAX_THREADS) {
    g_print ("number of threads must be between 0 and %d\n", MAX_THREADS);
    exit (-2);
  }

  if (nbbuffers <= 0) {
    g_print ("number of buffers must be greater than 0\n");
    exit (-3);
  }

  g_mutex_lock (&mutex);
  /* Let's just make sure the GstBufferClass is loaded ... */
  tmp = gst_buffer_new ();

  printf ("main(): Creating %d threads.\n", num_threads);
  for (t = 0; t < num_threads; t++) {
    GError *error = NULL;

    threads[t] = g_thread_try_new ("bufferstresstest", run_test,
        GINT_TO_POINTER (t), &error);

    if (error) {
      printf ("ERROR: g_thread_try_new() %s\n", error->message);
      g_clear_error (&error);
      exit (-1);
    }
  }

  /* Signal all threads to start */
  start = gst_util_get_timestamp ();
  g_mutex_unlock (&mutex);

  for (t = 0; t < num_threads; t++) {
    if (threads[t])
      g_thread_join (threads[t]);
  }

  end = gst_util_get_timestamp ();
  g_print ("*** total %" GST_TIME_FORMAT " - average %" GST_TIME_FORMAT
      "  - Done creating %" G_GUINT64_FORMAT " buffers\n",
      GST_TIME_ARGS (end - start),
      GST_TIME_ARGS ((end - start) / (num_threads * nbbuffers)),
      num_threads * nbbuffers);

  gst_buffer_unref (tmp);

  return 0;
}

{'repo_name': 'GStreamer/gstreamer', 'stars': '760', 'repo_language': 'C', 'file_name': 'gstconcat.c', 'mime_type': 'text/x-c', 'hash': 4903021296981821989, 'source_dataset': 'data'}


<?php
$script = "
    CKEDITOR.on('dialogDefinition', function (ev) {
        var dialogName = ev.data.name;
        var dialogDefinition = ev.data.definition;

        // Remove upload tab from Link and Image dialog as it interferes with
        // CSRF protection and upload can be reached using the browse server tab
        if ( dialogName == 'link')
        {
           // remove Upload tab
           dialogDefinition.removeContents( 'upload' );
        }
        if ( dialogName == 'image')
        {
           // remove Upload tab
           dialogDefinition.removeContents( 'Upload' );
        }
    });
    ";

/**
* @todo This following three JS lines are a hack to keep the most common usage of
 in ExpressionScript from breaking the expression,
* because the HTML editor will insert linebreaks after every
, even if it is inside a ExpressionScript tag {}
* The proper way to fix this would be to merge a plugin like ShowProtected (https://github.com/IGx89/CKEditor-ShowProtected-Plugin)
* with LimeReplacementFields and in general use ProtectSource for ExpressionScript
* See https://stackoverflow.com/questions/2851068/prevent-ckeditor-from-formatting-code-in-source-mode
*/
$script.="CKEDITOR.on('instanceReady', function(event) {
        event.editor.dataProcessor.writer.setRules( 'br', { breakAfterOpen: 0 } );
    });

    var sReplacementFieldTitle = '".gT('Placeholder fields','js')."';
    var sReplacementFieldButton = '".gT('Insert/edit placeholder field','js')."';
    var editorwindowsHash = new Object();

    function find_popup_editor(fieldname)
    {
        var window = null;
        for (var key in editorwindowsHash)
        {
            if (key==fieldname && !editorwindowsHash[key].closed)
            {
                window = editorwindowsHash[key];
                return window;
            }
        }
        return null;
    }

    function start_popup_editor(fieldname, fieldtext, sid, gid, qid, fieldtype, action)
    {
        controlidena = fieldname + '_popupctrlena';
        controliddis = fieldname + '_popupctrldis';
        numwindows = editorwindowsHash.length;
        activepopup = find_popup_editor(fieldname);

        if (activepopup == null)
        {
            document.getElementsByName(fieldname)[0].readOnly=true;
            document.getElementById(controlidena).style.display='none';
            document.getElementById(controliddis).style.display='';
            popup = window.open('".$this->createUrl('admin/htmleditor_pop/sa/index')."/name/'+fieldname+'/text/'+fieldtext+'/type/'+fieldtype+'/action/'+action+'/sid/'+sid+'/gid/'+gid+'/qid/'+qid+'/lang/".App()->language."','', 'location=no, status=yes, scrollbars=auto, menubar=no, resizable=yes, width=690, height=500');

            editorwindowsHash[fieldname] = popup;
        }
        else
        {
            activepopup.focus();
        }
    }

    function updateCKeditor(fieldname,value)
    {
        var mypopup= editorwindowsHash[fieldname];
        if (mypopup)
        {
            var oMyEditor = mypopup.CKEDITOR.instances['MyTextarea'];
            if (oMyEditor) {oMyEditor.setData(value);}
            mypopup.focus();
        }
        else
        {
            var oMyEditor = CKEDITOR.instances[fieldname];
            oMyEditor.setData(value);
        }
    }

";

Yii::app()->getClientScript()->registerScript('ckEditorPreparingSettings', $script, LSYii_ClientScript::POS_BEGIN);

{'repo_name': 'LimeSurvey/LimeSurvey', 'stars': '1547', 'repo_language': 'JavaScript', 'file_name': 'plugin.js', 'mime_type': 'text/plain', 'hash': 7880242766392274032, 'source_dataset': 'data'}


<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">

	<meta http-equiv="content-type" content="text/html; charset=utf-8" />
	<meta name="robots" content="all" />
	<title>Вітаємо в Haiku!</title>
	<meta name="viewport" content="width=device-width, initial-scale=1.0" />
	<link rel="stylesheet" type="text/css" href="Haiku-doc.css" />

User guide

Українська ▼

Bahasa Indonesia

Català

Deutsch

English

Español

Français

Furlan

Italiano

Magyar

Polski

Português

Português (Brazil)

Română

Slovenčina

Suomi

Svenska

Türkçe

 中文 ［中文］

Русский

日本語

The translation of this page isn't yet complete. Until it is, unfinished parts use the English original.

Зміст

	Welcome to Haiku!

	Beware of Bugs

	Getting to know the system

	Installing new software

	Updating Haiku

	Wifi in Haiku

	Getting to know the API

	Getting in contact

Вітаємо в Haiku!

Thanks for checking out Haiku! This is our sixth public release. We hope to attract new developers to our project and give users a chance to check out Haiku. While this second beta release includes all major features planned for the final Haiku release, it still has many bugs and a few rough edges that need further polishing. However, we think that this release is quite usable and hope it lets you discover Haiku's great potential and that you share our excitement.

Відвідайте вебсайт нашого проекту Haiku-os.org для ознайомлення з останніми новинами та оголошеннями.

Остерігайтесь помилок

We have been working hard to fix potentially critical bugs, however, being a beta release, there are bound to be some left undiscovered.

We discourage using beta versions as a production system. Your data could be altered, mangled or downright destroyed. Keep up-to-date backups!

One of the main reasons for releasing a beta version is to attract more people to test the system and discover bugs or provide suggestions for future enhancements. Please file bugs and enhancements in our bug tracker after using its search function to avoid duplicates.

Система відслідковування помилок у Haiku (Bug Tracker)

Поради по повідомленнях про помилки

Знайомство з системою

While the first release(s) of Haiku will be very much like the BeOS R5, the operating system it is reimplementing, there are many additions and improvements that were developed by the Haiku team over the years. So, if you're a returning BeOS user or are new user, have a look at these links:

Haiku Quick Tour

 Настанова користувачеві Haiku

Get help and support and become a part of  the community

Встановлення додаткових програм

Most of the available software can be downloaded and installed with the application HaikuDepot that comes with Haiku.

Because of our binary and source compatibility, most BeOS applications run on Haiku. Many of those have been re-packaged for Haiku or still run unmodified. You'll find more information on installing new programs in the user guide's chapter on Applications.

Існує декілька колекцій програмного забезпечення створених товариством. Дивись сторінку Сайти програмного забезпечення (Software Sites) на нашому вебсайті.

Оновлення Haiku

Updating Haiku as well as third party packages is done with the application SoftwareUpdater. When it's finished, reboot.

For more details, see the guide Updating and downgrading your system on our website.

Wifi в Haiku

Haiku підтримує бездротові мережі з шифруванням WPA/WPA2 або WEP та звичайно незахищені з'єднання. Через відмінності у політиці ліцензування деяких виробників апаратного забезпечення може знадобитися ручне встановлення прошивки. Детальнішу інформацію про підтримуване обладнання, встановлення прошивки та процес під'єднання до бездротової мережі можна отримати у Настанові користувачеві Семінар: Бездротові мережі.

Знайомство з  API

Так як Haiku є відтворенням,  API її  таке ж як у BeOS R5 (з деякими виключеннями), Тому документація у  Be Book все ще актуальна. Завдяки компанії ACCESS, котрій належать права на інтелектуальну власність Be Inc., нам дозволено поширювати Be Book.

Відхилення від API BeOS та Haiku, конкретні доповнення зібрані в Haiku Book.

Існують інші ресурси, що допоможуть почати вивчення:

Start developing for Haiku

Браузер вихідного коду

 Be Book

The Haiku Book

Архів Be Newsletter

Бажаєте спілкування

Ви можете звязатися з розробниками, іншими користувачами, приєднатися до обговорення на IRC каналі(#haiku у вебчаті) , нашому форумі або в списках розсилки. Коли маса людей спілкується разом необхідно дотримуватись деяких правил для збереження ефективності спілкування. Почитайте Етикет списків розсилки.

IRC канали

Форуми

General mailing list

Development mailing list concerning Haiku itself

Mailing list for 3rd party application programmers

Огляд усіх списків розсилки

{'repo_name': 'haiku/haiku', 'stars': '971', 'repo_language': 'C++', 'file_name': 'bootstrap', 'mime_type': 'text/plain', 'hash': -6963820072475691373, 'source_dataset': 'data'}


export function formatKey(key, series) {
  if (/{{\s*key\s*}}/.test(series.label)) {
    return series.label.replace(/{{\s*key\s*}}/, key);
  }
  return key;
}

{'repo_name': 'sirensolutions/kibi', 'stars': '488', 'repo_language': 'JavaScript', 'file_name': 'angular_style_guide.md', 'mime_type': 'text/x-java', 'hash': -6864322852910946938, 'source_dataset': 'data'}


package org.jboss.resteasy.plugins.server.undertow.spring;

import io.undertow.servlet.api.DeploymentInfo;
import io.undertow.servlet.api.ServletInfo;
import org.jboss.resteasy.plugins.server.undertow.UndertowJaxrsServer;
import org.springframework.web.servlet.DispatcherServlet;

import static io.undertow.servlet.Servlets.servlet;

public class UndertowJaxrsSpringServer extends UndertowJaxrsServer {

   public static final String SERVLET_NAME = "ResteasyServlet";

   public DeploymentInfo undertowDeployment(String contextConfigLocation, String mapping) {
      if (mapping == null) mapping = "/";
      if (!mapping.startsWith("/")) mapping = "/" + mapping;
      if (!mapping.endsWith("/")) mapping += "/";
      mapping = mapping + "*";
      String prefix = null;

      if (!mapping.equals("/*"))
         prefix = mapping.substring(0, mapping.length() - 2);

      ServletInfo servlet =
            servlet(SERVLET_NAME, DispatcherServlet.class)
                  .setLoadOnStartup(1)
                  .addInitParam("contextConfigLocation", contextConfigLocation)
                  .addMapping(mapping);

      DeploymentInfo deployment = new DeploymentInfo()
            .addServlet(servlet);
      if (prefix != null)
         deployment.setContextPath(prefix);
      return deployment;

   }

}

{'repo_name': 'resteasy/Resteasy', 'stars': '894', 'repo_language': 'Java', 'file_name': 'module.xml', 'mime_type': 'text/xml', 'hash': 3193767863145756552, 'source_dataset': 'data'}


#!/usr/bin/env python
# vim:fileencoding=utf-8
# License: GPL v3 Copyright: 2018, Kovid Goyal <kovid at kovidgoyal.net>

import json
import os
import sys
from threading import Thread

from PyQt5.Qt import QIcon, QObject, Qt, QTimer, pyqtSignal
from PyQt5.QtWebEngineCore import QWebEngineUrlScheme

from calibre import as_unicode, prints
from calibre.constants import FAKE_PROTOCOL, VIEWER_APP_UID, islinux, iswindows
from calibre.gui2 import Application, error_dialog, setup_gui_option_parser
from calibre.gui2.viewer.ui import EbookViewer, is_float
from calibre.gui2.viewer.config import get_session_pref, vprefs
from calibre.ptempfile import reset_base_dir
from calibre.utils.config import JSONConfig
from calibre.utils.ipc import RC, viewer_socket_address

singleinstance_name = 'calibre_viewer'

def migrate_previous_viewer_prefs():
    new_prefs = vprefs
    if new_prefs['old_prefs_migrated']:
        return
    old_vprefs = JSONConfig('viewer')
    old_prefs = JSONConfig('viewer.py')
    with new_prefs:
        sd = new_prefs['session_data']
        fs = sd.get('standalone_font_settings', {})
        for k in ('serif', 'sans', 'mono'):
            defval = 'Liberation ' + k.capitalize()
            k += '_family'
            if old_prefs.get(k) and old_prefs[k] != defval:
                fs[k] = old_prefs[k]
        if old_prefs.get('standard_font') in ('serif', 'sans', 'mono'):
            fs['standard_font'] = old_prefs['standard_font']
        if old_prefs.get('minimum_font_size') is not None and old_prefs['minimum_font_size'] != 8:
            fs['minimum_font_size'] = old_prefs['minimum_font_size']
        sd['standalone_font_settings'] = fs

        ms = sd.get('standalone_misc_settings', {})
        ms['remember_window_geometry'] = bool(old_prefs.get('remember_window_size', False))
        ms['remember_last_read'] = bool(old_prefs.get('remember_current_page', True))
        ms['save_annotations_in_ebook'] = bool(old_prefs.get('copy_bookmarks_to_file', True))
        ms['singleinstance'] = bool(old_vprefs.get('singleinstance', False))
        sd['standalone_misc_settings'] = ms

        for k in ('top', 'bottom'):
            v = old_prefs.get(k + '_margin')
            if v != 20 and v is not None:
                sd['margin_' + k] = v
        v = old_prefs.get('side_margin')
        if v is not None and v != 40:
            sd['margin_left'] = sd['margin_right'] = v // 2

        if old_prefs.get('user_css'):
            sd['user_stylesheet'] = old_prefs['user_css']

        cps = {'portrait': 0, 'landscape': 0}
        cp = old_prefs.get('cols_per_screen_portrait')
        if cp and cp > 1:
            cps['portrait'] = cp
        cl = old_prefs.get('cols_per_screen_landscape')
        if cl and cl > 1:
            cps['landscape'] = cp
        if cps['portrait'] or cps['landscape']:
            sd['columns_per_screen'] = cps
        if old_vprefs.get('in_paged_mode') is False:
            sd['read_mode'] = 'flow'

        new_prefs.set('session_data', sd)
        new_prefs.set('old_prefs_migrated', True)

class EventAccumulator(QObject):

    got_file = pyqtSignal(object)

    def __init__(self, parent):
        QObject.__init__(self, parent)
        self.events = []

    def __call__(self, paths):
        for path in paths:
            if os.path.exists(path):
                self.events.append(path)
                self.got_file.emit(path)

    def flush(self):
        if self.events:
            self.got_file.emit(self.events[-1])
            self.events = []

def listen(listener, msg_from_anotherinstance):
    while True:
        try:
            conn = listener.accept()
        except Exception:
            break
        try:
            msg_from_anotherinstance.emit(conn.recv())
            conn.close()
        except Exception as e:
            prints('Failed to read message from other instance with error: %s' % as_unicode(e))

def create_listener():
    addr = viewer_socket_address()
    if islinux:
        from calibre.utils.ipc.server import LinuxListener as Listener
    else:
        from multiprocessing.connection import Listener
        if not iswindows:
            # On macOS (and BSDs, I am guessing), following a crash, the
            # listener socket file sticks around and needs to be explicitly
            # removed. It is safe to do this since we are already guaranteed to
            # be the owner of the socket by singleinstance()
            try:
                os.remove(addr)
            except Exception:
                pass
    return Listener(address=addr)

def ensure_single_instance(args, open_at):
    try:
        from calibre.utils.lock import singleinstance
        si = singleinstance(singleinstance_name)
    except Exception:
        import traceback
        error_dialog(None, _('Cannot start viewer'), _(
            'Failed to start viewer, could not insure only a single instance of the viewer is running. Click "Show Details" for more information'),
                    det_msg=traceback.format_exc(), show=True)
        raise SystemExit(1)
    if not si:
        if len(args) > 1:
            t = RC(print_error=True, socket_address=viewer_socket_address())
            t.start()
            t.join(3.0)
            if t.is_alive() or t.conn is None:
                error_dialog(None, _('Connect to viewer failed'), _(
                    'Unable to connect to existing E-book viewer window, try restarting the viewer.'), show=True)
                raise SystemExit(1)
            t.conn.send((os.path.abspath(args[1]), open_at))
            t.conn.close()
            prints('Opened book in existing viewer instance')
        raise SystemExit(0)
    listener = create_listener()
    return listener

def option_parser():
    from calibre.gui2.main_window import option_parser
    parser = option_parser(_('''\
%prog [options] file

View an e-book.
'''))
    a = parser.add_option
    a('--raise-window', default=False, action='store_true',
        help=_('If specified, the E-book viewer window will try to come to the '
               'front when started.'))
    a('--full-screen', '--fullscreen', '-f', default=False, action='store_true',
        help=_('If specified, the E-book viewer window will try to open '
               'full screen when started.'))
    a('--force-reload', default=False, action='store_true',
        help=_('Force reload of all opened books'))
    a('--open-at', default=None, help=_(
        'The position at which to open the specified book. The position is '
        'a location or position you can get by using the Go to->Location action in the viewer controls. '
        'Alternately, you can use the form toc:something and it will open '
        'at the location of the first Table of Contents entry that contains '
        'the string "something". The form toc-href:something will match the '
        'href (internal link destination) of toc nodes. The matching is exact, '
        'If you want to match a substring, use the form toc-href-contains:something. '
        'The form ref:something will use Reference mode references.'))
    a('--continue', default=False, action='store_true', dest='continue_reading',
        help=_('Continue reading at the previously opened book'))

    setup_gui_option_parser(parser)
    return parser

def main(args=sys.argv):
    # Ensure viewer can continue to function if GUI is closed
    os.environ.pop('CALIBRE_WORKER_TEMP_DIR', None)
    reset_base_dir()
    scheme = QWebEngineUrlScheme(FAKE_PROTOCOL.encode('ascii'))
    scheme.setSyntax(QWebEngineUrlScheme.Syntax.Host)
    scheme.setFlags(QWebEngineUrlScheme.SecureScheme)
    QWebEngineUrlScheme.registerScheme(scheme)
    override = 'calibre-ebook-viewer' if islinux else None
    processed_args = []
    internal_book_data = internal_book_data_path = None
    for arg in args:
        if arg.startswith('--internal-book-data='):
            internal_book_data_path = arg.split('=', 1)[1]
            continue
        processed_args.append(arg)
    if internal_book_data_path:
        try:
            with lopen(internal_book_data_path, 'rb') as f:
                internal_book_data = json.load(f)
        finally:
            try:
                os.remove(internal_book_data_path)
            except EnvironmentError:
                pass
    args = processed_args
    app = Application(args, override_program_name=override, windows_app_uid=VIEWER_APP_UID)

    parser = option_parser()
    opts, args = parser.parse_args(args)
    oat = opts.open_at
    if oat and not (
            oat.startswith('toc:') or oat.startswith('toc-href:') or oat.startswith('toc-href-contains:') or
            oat.startswith('epubcfi(/') or is_float(oat) or oat.startswith('ref:')):
        raise SystemExit('Not a valid --open-at value: {}'.format(opts.open_at))

    listener = None
    if get_session_pref('singleinstance', False):
        try:
            listener = ensure_single_instance(args, opts.open_at)
        except Exception as e:
            import traceback
            error_dialog(None, _('Failed to start viewer'), as_unicode(e), det_msg=traceback.format_exc(), show=True)
            raise SystemExit(1)

    acc = EventAccumulator(app)
    app.file_event_hook = acc
    app.load_builtin_fonts()
    app.setWindowIcon(QIcon(I('viewer.png')))
    migrate_previous_viewer_prefs()
    main = EbookViewer(
        open_at=opts.open_at, continue_reading=opts.continue_reading, force_reload=opts.force_reload,
        calibre_book_data=internal_book_data)
    main.set_exception_handler()
    if len(args) > 1:
        acc.events.append(os.path.abspath(args[-1]))
    acc.got_file.connect(main.handle_commandline_arg)
    main.show()
    main.msg_from_anotherinstance.connect(main.another_instance_wants_to_talk, type=Qt.QueuedConnection)
    if listener is not None:
        t = Thread(name='ConnListener', target=listen, args=(listener, main.msg_from_anotherinstance))
        t.daemon = True
        t.start()
    QTimer.singleShot(0, acc.flush)
    if opts.raise_window:
        main.raise_()
    if opts.full_screen:
        main.set_full_screen(True)

    app.exec_()
    if listener is not None:
        listener.close()

if __name__ == '__main__':
    sys.exit(main())

{'repo_name': 'norbusan/calibre-debian', 'stars': '327', 'repo_language': 'Python', 'file_name': 'sr@latin.po', 'mime_type': 'text/x-po', 'hash': -2257823711444585728, 'source_dataset': 'data'}


if [ ! "$_CBSD_NODES_SUBR" ]; then
_CBSD_NODES_SUBR=1
###

#update idle in SQLite for $1 nodename
idle_update()
{
	cbsdsqlrw nodes "UPDATE nodelist SET idle=datetime('now','localtime') WHERE nodename=\"${1}\""
}

# check age of ssh mux lock. If ctime greater than 1 minutes
# then out "Connected (uptime min)" and return 0
# else - out "Offline" and return 1
# required included inventory for $sqlreplica
# sample:
# if check_locktime /usr/jails/ftmp/shmux_199.48.133.74.lock >/dev/null 2>&1; then
#    echo "OK"
#  fi
check_locktime()
{
	#always return online if no shmux activated
	[ "${sqlreplica}" = "0" ] && return 0

	local cur_time=$( ${DATE_CMD} +%s )
	local difftime

	[ ! -f "${1}" ] && return 1

	eval $( ${STAT_CMD} -s ${1} )
	difftime=$(( ( cur_time - st_mtime ) / 60 ))

	if [ ${difftime} -lt 1 ]; then
		return 1
	else
		echo "${difftime}"
		return 0
	fi
}

# idle must be set (or specified via $1 )
# $ip (of nodes) must be set
conv_idle()
{
	local _res

	status="Disconnected" # default state

	[ -n "${1}" ] && idle="${1}"

	[ -z "${idle}" ] && return 1

	if [ ${sqlreplica} -eq 1 ]; then
		_res=$( check_locktime ${ftmpdir}/shmux_${ip}.lock )
		[ $? -eq 0 ] && status="Connected" && idle=${_res} && return 0
	fi

	idle_time=$( ${DATE_CMD} -j -f "%Y-%m-%d %H:%M:%S" "${idle}" "+%s" )

	_res=$(( ( curtime - idle_time ) / 60 ))
	idle="${_res}"
}

# return $node as selected node by id or name from list
# -s "is subject for list"
# -a [0|1] show only active (status=on jail): 0, or all: 1
select_node_by_list()
{
	local _res _id i=0
	local subject="List of online nodes:"
	local active="0" # only online

	local sqldelimer=" "

	while getopts "a:r:s:e:" opt; do
		case "$opt" in
			a) active="${OPTARG}" ;;
			s) subject="${OPTARG}" ;;
		esac
		shift $(($OPTIND - 1))
	done

	eval $( cbsdsqlro nodes SELECT nodename,ip FROM nodelist | while read nodename ip status; do
		mystatus=

		if ! check_locktime ${ftmpdir}/shmux_${ip}.lock >/dev/null 2>&1; then
			mystatus="1"   # Offline
		else
			mystatus="0"   # Online
		fi

		[ "${mystatus}" != "${active}" ] && continue

		echo "local nodename${i}=\"${nodename}\"
		echo "local ip${i}=\"${ip}\"

		i=$(( i + 1 ))
	done )

	for i in $( ${SEQ_CMD} 0 255 ); do
		eval _mynode="\$nodename${i}"
		[ -z "${_mynode}" ] && break
		[ "${_mynode}" = "${nodename}" ] && _mynode="${BOLD}local${N0_COLOR}"
		eval _ip="\$ip${i}"
		[ -z "${_ip}" ] && break;

		[ $i -eq 0 ] && ${ECHO} "${N1_COLOR}${subject}${N0_COLOR}"
		${ECHO} "${BOLD}${i} .. ${N2_COLOR}${_mynode} ${N0_COLOR}on ${N2_COLOR}${_ip}${N0_COLOR}"
	done

	[ $i -eq 0 ] && err 1 "${N1_COLOR}No node found${N0_COLOR}"
	echo
	printf "${BOLD}Enter id 0-${i} or node name:${N0_COLOR} "
	set -e
	read _id
	set +e
	if ! is_number ${_id}; then
		eval node="\$nodename${_id}"
	else
		eval node="${_id}"
	fi

	remote=2 # for autoremote
}

# return 1 when there is no sqlreplica enabled and/or
# no any nodes added
# return 0 when sqlreplica on AND
# and at least one node has been added.
# e.g:
#   if is_cluster_mode; then
#        echo "is cluster mode"
#   fi
is_cluster_mode()
{
	# autosettings for alljails and shownode
	if [ ${sqlreplica} -ne 0 ]; then
		nodes_exist=$( cbsdsqlro nodes SELECT ip FROM nodelist LIMIT 1 )
		[ -n "${nodes_exist}" ] && return 0
	fi
	return 1
}

# return node status by nodename
# return 0 when node added and active/online
# return 1 when no node or node is offline
# -n "must be nodename"
# -e 1 - also export status in $node_<md5sum of nodename>_online
# e.g:
#   if node_is_online -n ${rnodename}; then
#      echo "Online"
#   fi
# or via vars:
#   node_is_online -n ${rnodename} -e 1 ||true
#   md5_node_name=$( /sbin/md5 -q -s ${rnodename} )
#   eval online=\$node_${md5_node_name}_online
#   echo ${online}
node_is_online()
{
	local _res _ret _node _ip _md5_export _md5_node_name

	while getopts "e:n:" opt; do
		case "${opt}" in
			e) _md5_export="${OPTARG}" ;;
			n) _node="${OPTARG}" ;;
		esac
		shift $(($OPTIND - 1))
	done

	[ -z "${_node}" ] && return 1
	[ -z "${_md5_export}" ] && _md5_export=0

	_ip=$( cbsdsqlro nodes SELECT ip FROM nodelist WHERE nodename=\"${_node}\" LIMIT 1 )
	[ -z "${_ip}" ] && return 1

	_res=$( check_locktime ${ftmpdir}/shmux_${_ip}.lock )
	_ret=$?
	[ ${_md5_export} -eq 0 ] && return ${_ret}

	_md5_node_name=$( ${MD5_CMD} -q -s ${_node} )

	case ${_ret} in
		0)
			# is online
			eval node_${_md5_node_name}_online=1
			;;
		*)
			# is offline
			eval node_${_md5_node_name}_online=0
			;;
	esac
}

# check that the directories are common
#
check_for_shared_dir()
{
	local _dir _node
	local _local_id _remote_id

	while getopts "d:n:" opt; do
		case "${opt}" in
			d) _dir="${OPTARG}" ;;
			n) _node="${OPTARG}" ;;
		esac
		shift $(($OPTIND - 1))
	done

	if [ -z "${_dir}" ]; then
		${ECHO} "${N1_COLOR}check_for_shared_dir: no dir: ${N2_COLOR}${_dir}${N0_COLOR}"
		return 1
	fi
	if [ -z "${_node}" ]; then
		${ECHO} "${N1_COLOR}check_for_shared_dir: empty node${N0_COLOR}"
		return 1
	fi

	if [ ! -r ${workdir}/${_dir}/dir.id ]; then
		${ECHO} "${N1_COLOR}no dir.id in directory: ${N2_COLOR}${i}${N0_COLOR}"
		return 1
	fi

	_local_id=$( ${CAT_CMD} ${workdir}/${_dir}/dir.id | ${TR_CMD} -d \\r | ${AWK_CMD} '/./{print $1}' )
	_remote_id=$( rexe tryoffline=1 node=${_node} ${CAT_CMD} ~cbsd/${_dir}/dir.id 2>/dev/null | ${TR_CMD} -d \\r | ${AWK_CMD} '/./{print $1}' )

	if [ -z "${_local_id}" ]; then
		${ECHO} "${N1_COLOR}check_for_shared_dir: empty id for dir: ${N2_COLOR}${_dir}${N0_COLOR}"
		return 1
	fi
	if [ -z "${_remote_id}" ]; then
		${ECHO} "${N1_COLOR}check_for_shared_dir: empty id for dir: ${N2_COLOR}${_dir}${N0_COLOR}"
		return 1
	fi

	if [ "${_local_id}" = "${_remote_id}" ]; then
		return 0
	else
		return 1
	fi
}

# users custom script for executing in master host with nodes action
# -a <action> - is source dir name ( add.d remove.d )
# -n ${nodename}
# -i ${ip}
# -p ${port}
# -k ${keyfile}
external_exec_master_node_script()
{
	local _res
	local _dir
	local _nodename _ip _port _keyfile

	while getopts "a:n:i:p:k:" opt; do
		case "${opt}" in
			a) _dir="${OPTARG}" ;;
			n) _nodename="${OPTARG}" ;;
			i) _ip="${OPTARG}" ;;
			p) _port="${OPTARG}" ;;
			k) _keyfile="${OPTARG}" ;;
		esac
		shift $(($OPTIND - 1))
	done

	[ -z "${_dir}" ] && return 1

	local _srcdir="${nodedir}/${_dir}"

	[ ! -d "${_srcdir}" ] && return 0
	[ -z "$( ${LS_CMD} ${_srcdir}/ )" ] && return 0

	local CBSDPATH="${PATH}"
	# reset CBSD PATH
	# it is necessary that the calling of any commands from external hooks
	# does not conflict with the same CBSD commands that the user does not expect
	export PATH="/sbin:/bin:/usr/sbin:/usr/bin:/usr/local/sbin:/usr/local/bin"

	${FIND_CMD} "${_srcdir}" \( -type l -or -type f \) -and \( -perm +111 \) -depth 1 -maxdepth 1 -exec ${BASENAME_CMD} {} \; | while read _file; do
		${ECHO} "${N1_COLOR}Execute master node script: ${N2_COLOR}${_file}${N0_COLOR}"
		${ECHO} "${N1_COLOR} :: ${_srcdir}/${_file} -n ${_nodename} -i ${_ip} -p ${_port} -k ${_keyfile}${N0_COLOR}"
		${_srcdir}/${_file} -n ${_nodename} -i ${_ip} -p ${_port} -k ${_keyfile}
	done

	# restore CBSD PATH
	export PATH="${CBSDPATH}"
}

# return $node_list variable if node variable is mask for multiple nodes's
node_is_multiple()
{
	node_list=

	[ -z "${node}" ] && return 0
	# We accept node with wildcard '*' e.g.: node*, *hoster*
	# node as mask?
	local is_mask=0

	local _pref=$( substr --pos=0 --len=1 --str=${node} )

	if [ "${_pref}" = "*" ]; then
		is_mask=1
	else
		strpos --str="${node}" --search="*"
		is_mask=$?
	fi

	if [ ${is_mask} -ne 0 ]; then
		node_mask=$( echo ${node} | ${TR_CMD} "*" "%" )
		node_list=$( cbsdsqlro nodes SELECT nodename FROM nodelist WHERE nodename LIKE \"${node_mask}\" | ${XARGS_CMD} )
	fi
}

###
fi

{'repo_name': 'cbsd/cbsd', 'stars': '391', 'repo_language': 'C', 'file_name': 'xunregister', 'mime_type': 'text/x-shellscript', 'hash': 5095911823953842168, 'source_dataset': 'data'}


using System;
using System.Runtime.InteropServices;

namespace Vlc.DotNet.Core.Interops.Signatures
{
    /// <summary>
    /// Callback prototype to display a picture.
    /// When the video frame needs to be shown, as determined by the media playback
    /// clock, the display callback is invoked.
    /// </summary>
    /// <param name="userData">
    /// Private pointer as passed to <see cref="SetVideoCallbacks"/>
    /// </param>
    /// <param name="picture">
    /// Private pointer returned from <see cref="LockVideoCallback"/>.
    /// </param>
    [LibVlcFunction("libvlc_video_display_cb")]
    [UnmanagedFunctionPointer(CallingConvention.Cdecl)]
    public delegate void DisplayVideoCallback(IntPtr userData, IntPtr picture);
}

{'repo_name': 'ZeBobo5/Vlc.DotNet', 'stars': '753', 'repo_language': 'C#', 'file_name': 'VlcMediaInstanceExtensions.cs', 'mime_type': 'text/plain', 'hash': -1801697875497213619, 'source_dataset': 'data'}


/*
XOWA: the XOWA Offline Wiki Application
Copyright (C) 2012-2017 gnosygnu@gmail.com

XOWA is licensed under the terms of the General Public License (GPL) Version 3,
or alternatively under the terms of the Apache License Version 2.0.

You may use XOWA according to either of these licenses as is most appropriate
for your project on a case-by-case basis.

The terms of each license can be found in the source code repository:

GPLv3 License: https://github.com/gnosygnu/xowa/blob/master/LICENSE-GPLv3.txt
Apache License: https://github.com/gnosygnu/xowa/blob/master/LICENSE-APACHE2.txt
*/
package gplx.xowa.htmls.bridges.dbuis.tbls; import gplx.*; import gplx.xowa.*; import gplx.xowa.htmls.*; import gplx.xowa.htmls.bridges.*; import gplx.xowa.htmls.bridges.dbuis.*;
public class Dbui_btn_itm {
	public Dbui_btn_itm(String cmd, String img, String text) {this.cmd = cmd; this.img = img; this.text = text;}
	public String Key() {return text;}
	public String Cmd() {return cmd;} private final String cmd;
	public String Img() {return img;} private final String img;
	public String Text() {return text;} private final String text;
	public static final Dbui_btn_itm[] Ary_empty = new Dbui_btn_itm[0];
}

{'repo_name': 'gnosygnu/xowa', 'stars': '220', 'repo_language': 'Java', 'file_name': 'xowa_user_cfg.gfs', 'mime_type': 'text/plain', 'hash': -7635311346290085843, 'source_dataset': 'data'}


# Python爬虫--代理池维护
## 写在前面
以前爬取拉勾网数据的时候，爬了几十条数据之后就因为IP访问频繁而被封，那时候去网上查的可以使用代理IP，网上有很多免费的代理IP，稳定性虽然不高但是可用，用requests
发送请求时，只需要把代理IP以字典的形式传入参数即可，那时候使用代理，直接去网上复制粘贴的几个代理IP就拿来用了。

最近学习崔庆才老师的爬虫教程接触到了代理池系统，才认识到，对于一个高效的爬虫系统，直接利用数据结构封装一下网上复制粘贴的代理IP来进行爬虫真的是小打小闹，
构建一个高效的代理池系统也是爬虫工程的一部分。代理池系统主要实现：自动去网上获取代理，自动存储，自动检测，向爬虫提供获取接口。

大致思路：
1. 去代理网站上爬取大量代理IP，并将其存储在redis数据库。
2. 定时获取redis中的所有代理IP，检测每一个代理IP是否可用。
3. 通过flask，对外提供获取代理IP的接口，如果想要使用代理池中的代理IP，只需要访问我们提供的接口即可。

[代理池代码实现](https://github.com/daacheng/PythonBasic/tree/master/agent_pool)
## 代理池系统具体实现思路
![](https://github.com/daacheng/PythonBasic/blob/master/pic/proxypool.png)

### 1、存储模块
存储模块：主要实现的功能是，去一些免费代理网站爬取大量的代理IP，并存储至redis数据库中。redis的Sorted Set结构是一个有序集合，我们会对每一个爬取到的代理IP
设置一个初始化的优先级10，Sorted Set也是通过这个优先级来进行排序的。

该模块中主要写三个脚本：
1. Crawler.py: 爬取各代理网站中的代理IP的脚本。
2. RedisClient.py:自定义一个redis的客户端类，封装一些操作redis数据库的方法。比如添加、删除、查询等操作。
3. Getter.py: 主要是利用(或者说是调度)Crawler，RedisClient这两个对象，实现存储模块的功能（获取IP+存储）
#### Crawler.py

    import requests
    from pyquery import PyQuery as pq
    from bs4 import BeautifulSoup

    """
        爬取代理网站的免费代理并返回
    """

    class Crawler(object):

        def get_crawler_proxy(self):
            # proxy_list = self.crawl_xici()
            proxy_list = self.crawl_66()
            return proxy_list

        def crawl_66(self):
            """
                爬取66代理
            """
            print('爬取66代理......')
            proxies = set()
            for i in range(1, 35):

                url = 'http://www.66ip.cn/areaindex_' + str(i) + '/1.html'
                headers = {
                    'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8',
                    'Accept-Encoding': 'gzip, deflate',
                    'Accept-Language': 'zh-CN,zh;q=0.9',
                    'Host': 'www.66ip.cn',
                    'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/68.0.3440.106 Safari/537.36'
                }

                res = requests.get(url, headers=headers)
                soup = BeautifulSoup(res.text, 'html.parser')
                items = soup.select('.footer table tr')

                for i in range(1, len(items)):
                    tds = items[i].select('td')
                    ip = tds[0].string
                    port = tds[1].string
                    proxy = ip + ':' + port
                    if proxy:
                        # print(proxy.replace(' ', ''))
                        proxies.add(proxy.replace(' ', ''))
            return list(proxies)

#### RedisClient.py

    import random
    import redis

    REDIS_HOST = '127.0.0.1'
    REDIS_PORT = 6379
    # redis的Sorted Set结构的key
    REDIS_KEY = 'proxies'
    # 初始化优先级的值为10
    INITAL_SCORE = 10
    # 优先级最小值
    MIN_SCORE =0
    # 优先级最大值
    MAX_SCORE = 100

    """
        利用redis的Sorted Set结构, 从redis中添加、查询、获取代理,以及修改代理的优先级
    """

    class RedisClient(object):

        def __init__(self, host=REDIS_HOST, port=REDIS_PORT):
            print('redis连接成功......')
            self.redisdb = redis.StrictRedis(host=host, port=port)

        def add(self, proxy, score=INITAL_SCORE):
            """
                添加代理,利用redis的Sorted Set结构存储
                zadd函数的三个参数：key是'proxies',按照score确定代理的优先级排序，value为代理proxy
                如果proxy已经存在redis中，就不添加; 新添加进来的代理proxy默认优先级为10
            """
            if not self.redisdb.zscore(REDIS_KEY, proxy):
                self.redisdb.zadd(REDIS_KEY, score, proxy)

        def get_proxy(self):
            """
                先获取优先级最高的代理，如果有，就从优先级最高的代理中挑一个，如果没有，就按优先级前十的proxy中随便选一个
            """
            # 返回key为REDIS_KEY的zset结构中score在给定区间(100,100)的元素
            res = self.redisdb.zrangebyscore(REDIS_KEY, MAX_SCORE, MAX_SCORE)
            if len(res):
                proxy = random.choice(res)
            else:
                if self.redisdb.zrevrange(REDIS_KEY, 0, 10):
                    proxy = random.choice(self.redisdb.zrevrange(REDIS_KEY, 0, 10))
                else:
                    raise Exception
            return proxy

        def decrease(self, proxy):
            """
                降低代理proxy的优先级score的值
                检测到代理proxy不可用是，就降低这个代理的优先级,优先级降低至0，就删除该代理proxy
            """
            score = self.redisdb.zscore(REDIS_KEY, proxy)
            if score and score > MIN_SCORE:
                self.redisdb.zincrby(REDIS_KEY, proxy, -1)
            else:
                self.redisdb.zrem(REDIS_KEY, proxy)

        def exist(self, proxy):
            """
                判断代理是否存在
            """
            score = self.redisdb.zscore(REDIS_KEY, proxy)
            if score:
                return True
            else:
                return False

        def max(self, proxy):
            """
                检测到代理可用，就将其优先级设置成最大100
            """
            self.redisdb.zadd(REDIS_KEY, MAX_SCORE, proxy)

        def get_proxy_count(self):
            """
                获取redis中代理数量
            """
            return self.redisdb.zcard(REDIS_KEY)

        def get_all_proxy(self):
            """
                获取全部代理proxy
            """
            return self.redisdb.zrangebyscore(REDIS_KEY, MIN_SCORE, MAX_SCORE)

#### Getter.py

    from Crawler import Crawler
    from RedisClient import RedisClient

    FULL_COUNT = 2000

    class Getter(object):

        def __init__(self):
            self.redis_client = RedisClient()
            self.crawler = Crawler()

        def is_full(self):
            """
                判断代理池是否满了
            """
            if self.redis_client.get_proxy_count() >= FULL_COUNT:
                return True
            else:
                return False

        def run(self):
            """
                将爬取到的代理存入redis
            """
            if not self.is_full():
                proxy_list = self.crawler.get_crawler_proxy()
                for proxy in proxy_list:
                    self.redis_client.add(proxy)

### 2、检测模块
检测模块：主要是针对爬取到的大量的代理IP，去检测这些代理IP是否可用，在存储模块中，初始抓取到的代理IP存储至redis的有序集合中，初始优先级为10，通过检测模块，
检测每一个代理IP，如果IP可用，及将其优先级设置为100，如果不可用，就将其优先级减1，如果优先级为0时，就将其从redis有序集合中删除。

检测模块利用的是异步http请求库aiohttp，其实用requests请求也是可以的，对于大量的代理IP检测，异步请求只需要将请求发送，不需要等待结果，效率会高一些。

Tester.py

    import RedisClient
    import asyncio
    import aiohttp
    import traceback
    import time

    """
        检测模块
    """

    # 用来测试代理是否可用的地址
    test_url = 'http://weixin.sogou.com/weixin?type=2&query=Python'

    class Tester(object):

        def __init__(self):
            self.redisdb = RedisClient.RedisClient()

        """
            通过async关键字创建一个协程函数
        """
        async def test_proxy(self, proxy):
            """
                检测代理的可用性
            """
            conn = aiohttp.TCPConnector(verify_ssl=False)
            async with aiohttp.ClientSession(connector=conn) as session:
                try:
                    if isinstance(proxy, bytes):
                        proxy = proxy.decode('utf-8')
                    real_proxy = 'http://' + proxy
                    print('正在检测 : %s' % real_proxy)
                    async with session.get(test_url, proxy=real_proxy, timeout=15) as res:
                        if res.status == 200:
                            # 说明代理可用,将其优先级置为最大
                            self.redisdb.max(proxy)
                            print('代理可用 : %s' % proxy)
                        else:
                            # 代理不可用，就降低其优先级
                            self.redisdb.decrease(proxy)
                            print('代理不可用 : %s' % proxy)
                except Exception as e:
                    self.redisdb.decrease(proxy)
                    print('代理不可用 : %s (%s)' % (proxy, e))

        def run(self):
            print('启动检测模块......')
            try:
                # 获取redis中所有爬取到的代理
                proxies = self.redisdb.get_all_proxy()
                loop = asyncio.get_event_loop()

                # 分批检测
                for i in range(0, len(proxies), 50):
                    test_proxies = proxies[i:i+50]
                    tasks = []
                    for test_proxy in test_proxies:
                        # 调用协程函数，返回协程对象
                        coroutine = self.test_proxy(test_proxy)
                        tasks.append(coroutine)
                    loop.run_until_complete(asyncio.wait(tasks))
                    time.sleep(5)
            except Exception as e:
                print('检测模块出错！！！')

### 3、通过flask向外提供获取代理IP的接口
通过flask可以很简单的创建一个web服务器，对外提供url接口，用户只需要请求指定的url，即可获取redis中的代理IP。

其实我们也可以直接在爬虫代码中连接redis获取优先级最高的代理IP拿来用，为什么要通过接口的形式去获取redis中的数据呢？这主要是一种设计思想吧，接口的方式
比较灵活，同时也能隐藏redis的连接信息，比较安全。

#### WebAPI_to_get_proxy.py

    from flask import Flask, g
    import RedisClient

    """
        对外提供web接口，通过提供的web接口，来获取redis中的代理
        g是上下文对象，处理请求时，用于临时存储的对象，每次请求都会重设这个变量。比如：我们可以获取一些临时请求的用户信息。
    """

    app = Flask(__name__)

    @app.route('/')
    def index():
        return '
欢迎来到daacheng代理池系统
'

    def get():
        if not hasattr(g, 'redis'):
            g.redis = RedisClient.RedisClient()
        return g.redis

    @app.route('/random')
    def get_random_proxy():
        # 从代理池中返回一个代理
        redisdb = get()
        return redisdb.get_proxy()

    @app.route('/count')
    def count():
        # 查询代理池中代理的个数
        redisdb = get()
        return str(redisdb.get_proxy_count())

    @app.route('/all')
    def get_all():
        # 查询代理池中代理的个数
        redisdb = get()
        return str(redisdb.get_all_proxy())

    if __name__ == '__main__':
        app.run()

## 4、调度模块
调度模块：主要是调度获取模块，和检测模块。启动两个进程，一个进程定时去爬取代理IP+存储，一个进程定时去检测获取到的代理IP是否可用。

controller.py

    from Getter import Getter
    from Tester import Tester
    import multiprocessing
    import time

    """
        调度模块
    """
    class Controller(object):

        """
            获取功能：爬取代理网站，将代理存储到redis
        """
        def control_get(self):
            getter = Getter()
            while True:
                getter.run()
                time.sleep(20)

        """
            检测功能，检测redis中的代理是否可用
        """
        def control_test(self):
            tester = Tester()
            while True:
                tester.run()
                time.sleep(20)

        def run(self):
            print('代理池开始运行了......')
            # 两个进程
            get = multiprocessing.Process(target=self.control_get)
            get.start()
            test = multiprocessing.Process(target=self.control_test)
            test.start()

    if __name__ == '__main__':
        control = Controller()
        control.run()

{'repo_name': 'daacheng/PythonBasic', 'stars': '304', 'repo_language': 'HTML', 'file_name': 'Linux文件目录管理命令.md', 'mime_type': 'text/plain', 'hash': -637531738669423544, 'source_dataset': 'data'}