text
stringlengths 2
100k
| meta
dict |
---|---|
<?php
class GetAllHeadersTest extends \PHPUnit_Framework_TestCase
{
/**
* @dataProvider testWorksData
*/
public function testWorks($test_type, $expected, $server)
{
foreach ($server as $key => $val) {
$_SERVER[$key] = $val;
}
$result = getallheaders();
$this->assertEquals($expected, $result, "Error testing $test_type works.");
}
public function testWorksData()
{
return array(
array(
'normal case',
array(
'Key-One' => 'foo',
'Key-Two' => 'bar',
'Another-Key-For-Testing' => 'baz'
),
array(
'HTTP_KEY_ONE' => 'foo',
'HTTP_KEY_TWO' => 'bar',
'HTTP_ANOTHER_KEY_FOR_TESTING' => 'baz'
)
),
array(
'Content-Type',
array(
'Content-Type' => 'two'
),
array(
'HTTP_CONTENT_TYPE' => 'one',
'CONTENT_TYPE' => 'two'
)
),
array(
'Content-Length',
array(
'Content-Length' => '222'
),
array(
'CONTENT_LENGTH' => '222',
'HTTP_CONTENT_LENGTH' => '111'
)
),
array(
'Content-Length (HTTP_CONTENT_LENGTH only)',
array(
'Content-Length' => '111'
),
array(
'HTTP_CONTENT_LENGTH' => '111'
)
),
array(
'Content-MD5',
array(
'Content-Md5' => 'aef123'
),
array(
'CONTENT_MD5' => 'aef123',
'HTTP_CONTENT_MD5' => 'fea321'
)
),
array(
'Content-MD5 (HTTP_CONTENT_MD5 only)',
array(
'Content-Md5' => 'f123'
),
array(
'HTTP_CONTENT_MD5' => 'f123'
)
),
array(
'Authorization (normal)',
array(
'Authorization' => 'testing'
),
array(
'HTTP_AUTHORIZATION' => 'testing',
)
),
array(
'Authorization (redirect)',
array(
'Authorization' => 'testing redirect'
),
array(
'REDIRECT_HTTP_AUTHORIZATION' => 'testing redirect',
)
),
array(
'Authorization (PHP_AUTH_USER + PHP_AUTH_PW)',
array(
'Authorization' => 'Basic ' . base64_encode('foo:bar')
),
array(
'PHP_AUTH_USER' => 'foo',
'PHP_AUTH_PW' => 'bar'
)
),
array(
'Authorization (PHP_AUTH_DIGEST)',
array(
'Authorization' => 'example-digest'
),
array(
'PHP_AUTH_DIGEST' => 'example-digest'
)
)
);
}
}
| {
"pile_set_name": "Github"
} |
# -*- mode: TCL; fill-column: 75; tab-width: 8; coding: iso-latin-1-unix -*-
#
# $Id: Variable.tcl,v 1.4 2001/12/09 05:04:02 idiscovery Exp $
#
# Variable.tcl --
#
# Routines in this file are used to set up and operate variables
# for classes that support the -variable option
#
# Copyright (c) 1993-1999 Ioi Kim Lam.
# Copyright (c) 2000-2001 Tix Project Group.
#
# See the file "license.terms" for information on usage and redistribution
# of this file, and for a DISCLAIMER OF ALL WARRANTIES.
#
# tixVariable:ConfigVariable --
#
# Set up the -variable option for the object $w
#
# Side effects:
#
# data(-variable) is changed to the name of the global variable
# if the global variable exists, data(-value) takes the value of this
# variable.
# if the global variable does not exist, it is created with the
# current data(-value)
#
# Return value:
#
# true is data(-value) is changed, indicating that data(-command)
# should be invoked.
#
proc tixVariable:ConfigVariable {w arg} {
upvar #0 $w data
set changed 0
if {$data(-variable) != ""} {
uplevel #0 \
[list trace vdelete $data(-variable) w "tixVariable:TraceProc $w"]
}
if {$arg != ""} {
if {[uplevel #0 info exists [list $arg]]} {
# This global variable exists, we use its value
#
set data(-value) [uplevel #0 set [list $arg]]
set changed 1
} else {
# This global variable does not exist; let's set it
#
uplevel #0 [list set $arg $data(-value)]
}
uplevel #0 \
[list trace variable $arg w "tixVariable:TraceProc $w"]
}
return $changed
}
proc tixVariable:UpdateVariable {w} {
upvar #0 $w data
if {$data(-variable) != ""} {
uplevel #0 \
[list trace vdelete $data(-variable) w "tixVariable:TraceProc $w"]
uplevel #0 \
[list set $data(-variable) $data(-value)]
uplevel #0 \
[list trace variable $data(-variable) w "tixVariable:TraceProc $w"]
# just in case someone has another trace and restricted my change
#
set data(-value) [uplevel #0 set [list $data(-variable)]]
}
}
proc tixVariable:TraceProc {w name1 name2 op} {
upvar #0 $w data
set varname $data(-variable)
if {[catch {$w config -value [uplevel #0 [list set $varname]]} err]} {
uplevel #0 [list set $varname [list [$w cget -value]]]
error $err
}
return
}
proc tixVariable:DeleteVariable {w} {
upvar #0 $w data
# Must delete the trace command of the -variable
#
if {$data(-variable) != ""} {
uplevel #0 \
[list trace vdelete $data(-variable) w "tixVariable:TraceProc $w"]
}
}
| {
"pile_set_name": "Github"
} |
/*
Copyright The Kubernetes Authors.
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.
*/
// Code generated by informer-gen. DO NOT EDIT.
package v2beta1
import (
internalinterfaces "k8s.io/client-go/informers/internalinterfaces"
)
// Interface provides access to all the informers in this group version.
type Interface interface {
// HorizontalPodAutoscalers returns a HorizontalPodAutoscalerInformer.
HorizontalPodAutoscalers() HorizontalPodAutoscalerInformer
}
type version struct {
factory internalinterfaces.SharedInformerFactory
namespace string
tweakListOptions internalinterfaces.TweakListOptionsFunc
}
// New returns a new Interface.
func New(f internalinterfaces.SharedInformerFactory, namespace string, tweakListOptions internalinterfaces.TweakListOptionsFunc) Interface {
return &version{factory: f, namespace: namespace, tweakListOptions: tweakListOptions}
}
// HorizontalPodAutoscalers returns a HorizontalPodAutoscalerInformer.
func (v *version) HorizontalPodAutoscalers() HorizontalPodAutoscalerInformer {
return &horizontalPodAutoscalerInformer{factory: v.factory, namespace: v.namespace, tweakListOptions: v.tweakListOptions}
}
| {
"pile_set_name": "Github"
} |
// @warnings{no-unused}
module test;
type number int32; // @error{a type name must start with an upper case character}
| {
"pile_set_name": "Github"
} |
<?php
/*
* Copyright 2014 Google Inc.
*
* 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.
*/
class Google_Service_AndroidPublisher_DeveloperComment extends Google_Model
{
protected $lastModifiedType = 'Google_Service_AndroidPublisher_Timestamp';
protected $lastModifiedDataType = '';
public $text;
/**
* @param Google_Service_AndroidPublisher_Timestamp
*/
public function setLastModified(Google_Service_AndroidPublisher_Timestamp $lastModified)
{
$this->lastModified = $lastModified;
}
/**
* @return Google_Service_AndroidPublisher_Timestamp
*/
public function getLastModified()
{
return $this->lastModified;
}
public function setText($text)
{
$this->text = $text;
}
public function getText()
{
return $this->text;
}
}
| {
"pile_set_name": "Github"
} |
<h4><i class="fa fa-magic"></i> Custom fields:</h4>
{{-- add fields --}}
{!! Form::open(["route" => 'users.profile.addfield', 'class' => 'form-add-profile-field', 'role' => 'form']) !!}
<div class="form-group">
<div class="input-group">
<span class="input-group-addon form-button button-add-profile-field"><span class="glyphicon glyphicon-plus-sign add-input"></span></span>
{!! Form::text('description','',['class' =>'form-control','placeholder' => 'Custom field name']) !!}
{!! Form::hidden('user_id',$user_profile->user_id) !!}
</div>
</div>
{!! Form::close() !!}
{{-- delete fields --}}
@foreach($custom_profile->getAllTypesWithValues() as $profile_data)
{!! Form::open(["route" => 'users.profile.deletefield', 'name' => $profile_data->id, 'role' => 'form']) !!}
<div class="form-group">
<div class="input-group">
<span class="input-group-addon form-button button-del-profile-field" name="{!! $profile_data->id !!}"><span
class="glyphicon glyphicon-minus-sign add-input"></span></span>
{!! Form::text('profile_description', $profile_data->description, ['class' => 'form-control', 'readonly' => 'readonly']) !!}
{!! Form::hidden('id', $profile_data->id) !!}
{!! Form::hidden('user_id',$user_profile->user_id) !!}
</div>
</div>
{!! Form::close() !!}
@endforeach
@section('footer_scripts')
@parent
<script>
$(".button-add-profile-field").click(function () {
$('.form-add-profile-field').submit();
});
$(".button-del-profile-field").click(function () {
if (!confirm('Are you sure to delete this field?')) return;
// submit the form with the same name
name = $(this).attr('name');
$('form[name=' + name + ']').submit();
});
</script>
@stop | {
"pile_set_name": "Github"
} |
/****************************************************************************
**
** Copyright (C) 2020 The Qt Company Ltd.
** Contact: https://www.qt.io/licensing/
**
** This file is part of Qt Creator.
**
** Commercial License Usage
** Licensees holding valid commercial Qt licenses may use this file in
** accordance with the commercial license agreement provided with the
** Software or, alternatively, in accordance with the terms contained in
** a written agreement between you and The Qt Company. For licensing terms
** and conditions see https://www.qt.io/terms-conditions. For further
** information use the contact form at https://www.qt.io/contact-us.
**
** GNU General Public License Usage
** Alternatively, this file may be used under the terms of the GNU
** General Public License version 3 as published by the Free Software
** Foundation with exceptions as appearing in the file LICENSE.GPL3-EXCEPT
** included in the packaging of this file. Please review the following
** information to ensure the GNU General Public License requirements will
** be met: https://www.gnu.org/licenses/gpl-3.0.html.
**
****************************************************************************/
#pragma once
#include "transitioneditorconstants.h"
#include <timelineeditor/timelineitem.h>
#include <timelineeditor/timelinemovableabstractitem.h>
#include <modelnode.h>
#include <qmltimeline.h>
QT_FORWARD_DECLARE_CLASS(QComboBox)
QT_FORWARD_DECLARE_CLASS(QPainter)
namespace QmlDesigner {
class TransitionEditorSectionItem;
class TransitionEditorPropertyItem;
class TransitionEditorBarItem : public TimelineMovableAbstractItem
{
Q_DECLARE_TR_FUNCTIONS(TimelineBarItem)
enum class Location { Undefined, Center, Left, Right };
public:
explicit TransitionEditorBarItem(TransitionEditorSectionItem *parent);
explicit TransitionEditorBarItem(TransitionEditorPropertyItem *parent);
void itemMoved(const QPointF &start, const QPointF &end) override;
void commitPosition(const QPointF &point) override;
protected:
void scrollOffsetChanged() override;
void paint(QPainter *painter,
const QStyleOptionGraphicsItem *option,
QWidget *widget = nullptr) override;
void hoverMoveEvent(QGraphicsSceneHoverEvent *) override;
void contextMenuEvent(QGraphicsSceneContextMenuEvent *event) override;
void mousePressEvent(QGraphicsSceneMouseEvent *event) override;
private:
TransitionEditorSectionItem *sectionItem() const;
TransitionEditorPropertyItem *propertyItem() const;
void dragInit(const QRectF &rect, const QPointF &pos);
void dragCenter(QRectF rect, const QPointF &pos, qreal min, qreal max);
void dragHandle(QRectF rect, const QPointF &pos, qreal min, qreal max);
bool handleRects(const QRectF &rect, QRectF &left, QRectF &right) const;
bool isActiveHandle(Location location) const;
void setOutOfBounds(Location location);
bool validateBounds(qreal pivot);
private:
Location m_handle = Location::Undefined;
Location m_bounds = Location::Undefined;
qreal m_pivot = 0.0;
QRectF m_oldRect;
static constexpr qreal minimumBarWidth = 2.0
* static_cast<qreal>(TimelineConstants::sectionHeight);
};
class TransitionEditorSectionItem : public TimelineItem
{
Q_OBJECT
public:
enum { Type = TransitionEditorConstants::transitionEditorSectionItemUserType };
static TransitionEditorSectionItem *create(const ModelNode &animation,
TimelineItem *parent);
void invalidateBar();
int type() const override;
static void updateData(QGraphicsItem *item);
static void invalidateBar(QGraphicsItem *item);
static void updateDataForTarget(QGraphicsItem *item, const ModelNode &target, bool *b);
void moveAllDurations(qreal offset);
void scaleAllDurations(qreal scale);
qreal firstFrame();
AbstractView *view() const;
bool isSelected() const;
ModelNode targetNode() const;
void updateData();
protected:
void paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget) override;
void mouseDoubleClickEvent(QGraphicsSceneMouseEvent *event) override;
void mousePressEvent(QGraphicsSceneMouseEvent *event) override;
void mouseReleaseEvent(QGraphicsSceneMouseEvent *event) override;
void resizeEvent(QGraphicsSceneResizeEvent *event) override;
void contextMenuEvent(QGraphicsSceneContextMenuEvent *event) override;
private:
void invalidateHeight();
void invalidateProperties();
bool collapsed() const;
qreal rulerWidth() const;
void toggleCollapsed();
void createPropertyItems();
const QList<QGraphicsItem *> propertyItems() const;
TransitionEditorSectionItem(TimelineItem *parent = nullptr);
ModelNode m_targetNode;
ModelNode m_animationNode;
TransitionEditorBarItem *m_barItem = nullptr;
TimelineItem *m_dummyItem = nullptr;
};
} // namespace QmlDesigner
| {
"pile_set_name": "Github"
} |
<?php
/*
* This file is part of the Sylius package.
*
* (c) Paweł Jędrzejewski
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
declare(strict_types=1);
namespace spec\Sylius\Bundle\AddressingBundle\Validator\Constraints;
use PhpSpec\ObjectBehavior;
use Sylius\Bundle\AddressingBundle\Validator\Constraints\ProvinceAddressConstraint;
final class ProvinceAddressConstraintSpec extends ObjectBehavior
{
function it_is_initializable(): void
{
$this->shouldHaveType(ProvinceAddressConstraint::class);
}
function it_has_targets(): void
{
$this->getTargets()->shouldReturn('class');
}
function it_is_validated_by(): void
{
$this->validatedBy()->shouldReturn('sylius_province_address_validator');
}
}
| {
"pile_set_name": "Github"
} |
/*-
* Copyright (c) 1995
* The Regents of the University of California. 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.
* 4. Neither the name of the University nor the names of its contributors
* may be used to endorse or promote products derived from this software
* without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
* OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
* OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
*
* @(#)arith.h 1.1 (Berkeley) 5/4/95
* $FreeBSD: head/bin/sh/arith.h 223060 2011-06-13 21:03:27Z jilles $
*/
#include "shell.h"
#define DIGITS(var) (3 + (2 + CHAR_BIT * sizeof((var))) / 3)
arith_t arith(const char *);
void arith_lex_reset(void);
| {
"pile_set_name": "Github"
} |
export interface Environment {
buildId: string;
sourceBranch: string;
createdTimeUtc: string;
status: string;
lastUpdatedOn?: string;
hostname?: string;
pullRequestTitle?: string;
}
| {
"pile_set_name": "Github"
} |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
#-:-:-:-:-:-:-:-:-:-:-:-:#
# TIDoS Framework #
#-:-:-:-:-:-:-:-:-:-:-:-:#
#This file is a part of TIDoS Framework
#https://github.com/0xInfection/TIDoS-Framework
errorsig = [ "[<a href='function.main'>function.main</a>",
"[<a href='function.include'>function.include</a>",
"Failed opening",
"for inclusion",
"failed to open stream:",
"open_basedir restriction in effect",
"root:",
"sbin",
"nologin",
"DB_NAME",
"daemon:",
"DOCUMENT_ROOT=",
"PATH=",
"HTTP_ACCEPT_ENCODING=",
"HTTP_USER_AGENT",
"GET /",
"apache_port=",
"cpanel/logs/access",
"allow_login_autocomplete",
"database_prefix=",
"emailusersbandwidth",
"adminuser=",
"error]",
"[client",
"log",
"[error] [client",
"File does not exist:",
"proc/self/fd/",
"State: R (running)",
"Tgid:",
"TracerPid:",
"Uid:",
"/proc/self/status"
]
| {
"pile_set_name": "Github"
} |
<?xml version="1.0"?>
<config version="7.1.0" urldb="paloaltonetworks">
<mgt-config>
<users>
<entry name="admin">
<phash>$1$mqubfegw$aQwb/NSxN0.O8bUvpQG59.</phash>
<permissions>
<role-based>
<superuser>yes</superuser>
</role-based>
</permissions>
</entry>
</users>
</mgt-config>
<shared>
<application/>
<application-group/>
<service/>
<service-group/>
<botnet>
<configuration>
<http>
<dynamic-dns>
<enabled>yes</enabled>
<threshold>5</threshold>
</dynamic-dns>
<malware-sites>
<enabled>yes</enabled>
<threshold>5</threshold>
</malware-sites>
<recent-domains>
<enabled>yes</enabled>
<threshold>5</threshold>
</recent-domains>
<ip-domains>
<enabled>yes</enabled>
<threshold>10</threshold>
</ip-domains>
<executables-from-unknown-sites>
<enabled>yes</enabled>
<threshold>5</threshold>
</executables-from-unknown-sites>
</http>
<other-applications>
<irc>yes</irc>
</other-applications>
<unknown-applications>
<unknown-tcp>
<destinations-per-hour>10</destinations-per-hour>
<sessions-per-hour>10</sessions-per-hour>
<session-length>
<maximum-bytes>100</maximum-bytes>
<minimum-bytes>50</minimum-bytes>
</session-length>
</unknown-tcp>
<unknown-udp>
<destinations-per-hour>10</destinations-per-hour>
<sessions-per-hour>10</sessions-per-hour>
<session-length>
<maximum-bytes>100</maximum-bytes>
<minimum-bytes>50</minimum-bytes>
</session-length>
</unknown-udp>
</unknown-applications>
</configuration>
<report>
<topn>100</topn>
<scheduled>yes</scheduled>
</report>
</botnet>
<local-user-database>
<user-group>
<entry name="test_user_id"/>
</user-group>
</local-user-database>
<content-preview>
<application/>
<application-type>
<category/>
<technology/>
</application-type>
</content-preview>
</shared>
<devices>
<entry name="localhost.localdomain">
<network>
<interface>
<ethernet>
<entry name="ethernet1/1">
<layer3>
<ipv6>
<neighbor-discovery>
<router-advertisement>
<enable>no</enable>
</router-advertisement>
</neighbor-discovery>
</ipv6>
<ndp-proxy>
<enabled>no</enabled>
</ndp-proxy>
<lldp>
<enable>no</enable>
</lldp>
<ip>
<entry name="10.5.173.91/24"/>
</ip>
<interface-management-profile>PingSSHHttps</interface-management-profile>
</layer3>
</entry>
<entry name="ethernet1/2">
<layer3>
<ipv6>
<neighbor-discovery>
<router-advertisement>
<enable>no</enable>
</router-advertisement>
</neighbor-discovery>
</ipv6>
<ndp-proxy>
<enabled>no</enabled>
</ndp-proxy>
<lldp>
<enable>no</enable>
</lldp>
<ip>
<entry name="10.5.174.91/24"/>
</ip>
<interface-management-profile>PingSSHHttps</interface-management-profile>
</layer3>
</entry>
<entry name="ethernet1/3">
<tap/>
</entry>
</ethernet>
<tunnel>
<units>
<entry name="tunnel.1"/>
</units>
</tunnel>
</interface>
<profiles>
<monitor-profile>
<entry name="default">
<interval>3</interval>
<threshold>5</threshold>
<action>wait-recover</action>
</entry>
</monitor-profile>
<interface-management-profile>
<entry name="Pingable">
<ping>yes</ping>
</entry>
<entry name="PingSSHHttps">
<https>yes</https>
<ssh>yes</ssh>
<ping>yes</ping>
</entry>
</interface-management-profile>
</profiles>
<ike>
<crypto-profiles>
<ike-crypto-profiles>
<entry name="default">
<encryption>
<member>aes-128-cbc</member>
<member>3des</member>
</encryption>
<hash>
<member>sha1</member>
</hash>
<dh-group>
<member>group2</member>
</dh-group>
<lifetime>
<hours>8</hours>
</lifetime>
</entry>
<entry name="Suite-B-GCM-128">
<encryption>
<member>aes-128-cbc</member>
</encryption>
<hash>
<member>sha256</member>
</hash>
<dh-group>
<member>group19</member>
</dh-group>
<lifetime>
<hours>8</hours>
</lifetime>
</entry>
<entry name="Suite-B-GCM-256">
<encryption>
<member>aes-256-cbc</member>
</encryption>
<hash>
<member>sha384</member>
</hash>
<dh-group>
<member>group20</member>
</dh-group>
<lifetime>
<hours>8</hours>
</lifetime>
</entry>
</ike-crypto-profiles>
<ipsec-crypto-profiles>
<entry name="default">
<esp>
<encryption>
<member>aes-128-cbc</member>
<member>3des</member>
</encryption>
<authentication>
<member>sha1</member>
</authentication>
</esp>
<dh-group>group2</dh-group>
<lifetime>
<hours>1</hours>
</lifetime>
</entry>
<entry name="Suite-B-GCM-128">
<esp>
<encryption>
<member>aes-128-gcm</member>
</encryption>
<authentication>
<member>none</member>
</authentication>
</esp>
<dh-group>group19</dh-group>
<lifetime>
<hours>1</hours>
</lifetime>
</entry>
<entry name="Suite-B-GCM-256">
<esp>
<encryption>
<member>aes-256-gcm</member>
</encryption>
<authentication>
<member>none</member>
</authentication>
</esp>
<dh-group>group20</dh-group>
<lifetime>
<hours>1</hours>
</lifetime>
</entry>
</ipsec-crypto-profiles>
<global-protect-app-crypto-profiles>
<entry name="default">
<encryption>
<member>aes-128-cbc</member>
</encryption>
<authentication>
<member>sha1</member>
</authentication>
</entry>
</global-protect-app-crypto-profiles>
</crypto-profiles>
<gateway>
<entry name="IKEForIPSec">
<authentication>
<pre-shared-key>
<key>-AQ==zPJb3ngM1sGjXlfX2+Qk6rbdv1I=ucInIpBmFcnkQK7zF4VO1w==</key>
</pre-shared-key>
</authentication>
<protocol>
<ikev1>
<dpd>
<enable>yes</enable>
</dpd>
</ikev1>
<ikev2>
<dpd>
<enable>yes</enable>
</dpd>
</ikev2>
</protocol>
<protocol-common>
<nat-traversal>
<enable>no</enable>
</nat-traversal>
<fragmentation>
<enable>no</enable>
</fragmentation>
</protocol-common>
<local-address>
<interface>ethernet1/1</interface>
</local-address>
<peer-address>
<ip>10.5.173.90</ip>
</peer-address>
</entry>
</gateway>
</ike>
<qos>
<profile>
<entry name="default">
<class>
<entry name="class1">
<priority>real-time</priority>
</entry>
<entry name="class2">
<priority>high</priority>
</entry>
<entry name="class3">
<priority>high</priority>
</entry>
<entry name="class4">
<priority>medium</priority>
</entry>
<entry name="class5">
<priority>medium</priority>
</entry>
<entry name="class6">
<priority>low</priority>
</entry>
<entry name="class7">
<priority>low</priority>
</entry>
<entry name="class8">
<priority>low</priority>
</entry>
</class>
</entry>
</profile>
</qos>
<virtual-router>
<entry name="default">
<protocol>
<bgp>
<enable>no</enable>
<dampening-profile>
<entry name="default">
<cutoff>1.25</cutoff>
<reuse>0.5</reuse>
<max-hold-time>900</max-hold-time>
<decay-half-life-reachable>300</decay-half-life-reachable>
<decay-half-life-unreachable>900</decay-half-life-unreachable>
<enable>yes</enable>
</entry>
</dampening-profile>
<routing-options>
<graceful-restart>
<enable>yes</enable>
</graceful-restart>
<as-format>2-byte</as-format>
</routing-options>
</bgp>
</protocol>
<ecmp>
<algorithm>
<ip-modulo/>
</algorithm>
</ecmp>
<interface>
<member>ethernet1/1</member>
<member>ethernet1/2</member>
<member>tunnel.1</member>
</interface>
</entry>
</virtual-router>
<tunnel>
<ipsec>
<entry name="FromFW-A">
<auto-key>
<ike-gateway>
<entry name="IKEForIPSec"/>
</ike-gateway>
</auto-key>
<tunnel-monitor>
<enable>no</enable>
</tunnel-monitor>
<tunnel-interface>tunnel.1</tunnel-interface>
</entry>
</ipsec>
</tunnel>
</network>
<deviceconfig>
<system>
<ip-address>10.5.172.91</ip-address>
<netmask>255.255.255.0</netmask>
<update-server>updates.paloaltonetworks.com</update-server>
<update-schedule>
<threats>
<recurring>
<weekly>
<day-of-week>wednesday</day-of-week>
<at>01:02</at>
<action>download-only</action>
</weekly>
</recurring>
</threats>
<wildfire>
<recurring>
<every-hour>
<action>download-only</action>
</every-hour>
</recurring>
</wildfire>
<global-protect-datafile>
<recurring>
<weekly>
<action>download-and-install</action>
<at>00:15</at>
<day-of-week>sunday</day-of-week>
</weekly>
</recurring>
</global-protect-datafile>
</update-schedule>
<timezone>US/Pacific</timezone>
<service>
<disable-telnet>yes</disable-telnet>
<disable-http>yes</disable-http>
</service>
<hostname>PA-VM-B</hostname>
<default-gateway>10.5.172.1</default-gateway>
<dns-setting>
<servers>
<primary>10.43.2.10</primary>
<secondary>8.8.8.8</secondary>
</servers>
</dns-setting>
<panorama-server>10.5.172.92</panorama-server>
</system>
<setting>
<config>
<rematch>yes</rematch>
</config>
<management>
<hostname-type-in-syslog>FQDN</hostname-type-in-syslog>
</management>
</setting>
</deviceconfig>
<vsys>
<entry name="vsys1">
<application/>
<application-group/>
<zone>
<entry name="new zone">
<network>
<layer3>
<member></member>
</layer3>
</network>
</entry>
<entry name="untrusted-l3">
<network>
<layer3>
<member>ethernet1/1</member>
</layer3>
</network>
</entry>
<entry name="trusted-l3">
<network>
<layer3>
<member>ethernet1/2</member>
<member>tunnel.1</member>
</layer3>
</network>
</entry>
<entry name="tap_zone">
<network>
<tap>
<member>ethernet1/3</member>
</tap>
</network>
</entry>
</zone>
<service/>
<service-group/>
<schedule/>
<rulebase>
<security>
<rules>
<entry name="UserSpecific">
<to>
<member>untrusted-l3</member>
</to>
<from>
<member>trusted-l3</member>
</from>
<source>
<member>any</member>
</source>
<destination>
<member>any</member>
</destination>
<source-user>
<member>any</member>
</source-user>
<category>
<member>any</member>
</category>
<application>
<member>any</member>
</application>
<service>
<member>application-default</member>
</service>
<hip-profiles>
<member>any</member>
</hip-profiles>
<action>allow</action>
</entry>
<entry name="tap_log">
<to>
<member>tap_zone</member>
</to>
<from>
<member>tap_zone</member>
</from>
<source>
<member>any</member>
</source>
<destination>
<member>any</member>
</destination>
<source-user>
<member>any</member>
</source-user>
<category>
<member>any</member>
</category>
<application>
<member>any</member>
</application>
<service>
<member>application-default</member>
</service>
<hip-profiles>
<member>any</member>
</hip-profiles>
<action>allow</action>
<log-start>yes</log-start>
</entry>
</rules>
</security>
</rulebase>
<import>
<network>
<interface>
<member>ethernet1/1</member>
<member>ethernet1/2</member>
<member>tunnel.1</member>
<member>ethernet1/3</member>
</interface>
</network>
</import>
<address-group>
<entry name="dag-1">
<dynamic>
<filter>'aws-tag.aws:cloudformation:logical-id.ServerInstance' and 'instanceState.running'</filter>
</dynamic>
</entry>
</address-group>
</entry>
</vsys>
</entry>
</devices>
</config>
| {
"pile_set_name": "Github"
} |
<?xml version='1.0' encoding='utf-8'?>
<?grc format='1' created='3.7.11'?>
<flow_graph>
<timestamp>Tue Nov 4 10:04:33 2014</timestamp>
<block>
<key>options</key>
<param>
<key>author</key>
<value></value>
</param>
<param>
<key>window_size</key>
<value>1280, 1024</value>
</param>
<param>
<key>category</key>
<value>[IEEE802.15.4]</value>
</param>
<param>
<key>comment</key>
<value></value>
</param>
<param>
<key>description</key>
<value></value>
</param>
<param>
<key>_enabled</key>
<value>True</value>
</param>
<param>
<key>_coordinate</key>
<value>(10, 10)</value>
</param>
<param>
<key>_rotation</key>
<value>0</value>
</param>
<param>
<key>generate_options</key>
<value>hb</value>
</param>
<param>
<key>hier_block_src_path</key>
<value>.:</value>
</param>
<param>
<key>id</key>
<value>ieee802_15_4_oqpsk_headerless_phy</value>
</param>
<param>
<key>max_nouts</key>
<value>0</value>
</param>
<param>
<key>qt_qss_theme</key>
<value></value>
</param>
<param>
<key>realtime_scheduling</key>
<value></value>
</param>
<param>
<key>run_command</key>
<value>{python} -u {filename}</value>
</param>
<param>
<key>run_options</key>
<value>prompt</value>
</param>
<param>
<key>run</key>
<value>True</value>
</param>
<param>
<key>thread_safe_setters</key>
<value></value>
</param>
<param>
<key>title</key>
<value>IEEE802.15.4 OQPSK Headerless PHY</value>
</param>
</block>
<block>
<key>variable</key>
<param>
<key>comment</key>
<value></value>
</param>
<param>
<key>_enabled</key>
<value>True</value>
</param>
<param>
<key>_coordinate</key>
<value>(200, 12)</value>
</param>
<param>
<key>_rotation</key>
<value>0</value>
</param>
<param>
<key>id</key>
<value>samp_rate</value>
</param>
<param>
<key>value</key>
<value>4000000</value>
</param>
</block>
<block>
<key>analog_quadrature_demod_cf</key>
<param>
<key>alias</key>
<value></value>
</param>
<param>
<key>comment</key>
<value></value>
</param>
<param>
<key>affinity</key>
<value></value>
</param>
<param>
<key>_enabled</key>
<value>0</value>
</param>
<param>
<key>_coordinate</key>
<value>(190, 604)</value>
</param>
<param>
<key>_rotation</key>
<value>0</value>
</param>
<param>
<key>gain</key>
<value>1</value>
</param>
<param>
<key>id</key>
<value>analog_quadrature_demod_cf_0</value>
</param>
<param>
<key>maxoutbuf</key>
<value>0</value>
</param>
<param>
<key>minoutbuf</key>
<value>0</value>
</param>
</block>
<block>
<key>blocks_complex_to_float</key>
<param>
<key>alias</key>
<value></value>
</param>
<param>
<key>comment</key>
<value></value>
</param>
<param>
<key>affinity</key>
<value></value>
</param>
<param>
<key>_enabled</key>
<value>True</value>
</param>
<param>
<key>_coordinate</key>
<value>(722, 396)</value>
</param>
<param>
<key>_rotation</key>
<value>180</value>
</param>
<param>
<key>id</key>
<value>blocks_complex_to_float_0</value>
</param>
<param>
<key>maxoutbuf</key>
<value>0</value>
</param>
<param>
<key>minoutbuf</key>
<value>0</value>
</param>
<param>
<key>vlen</key>
<value>1</value>
</param>
</block>
<block>
<key>blocks_delay</key>
<param>
<key>alias</key>
<value></value>
</param>
<param>
<key>comment</key>
<value></value>
</param>
<param>
<key>affinity</key>
<value></value>
</param>
<param>
<key>delay</key>
<value>2</value>
</param>
<param>
<key>_enabled</key>
<value>True</value>
</param>
<param>
<key>_coordinate</key>
<value>(585, 392)</value>
</param>
<param>
<key>_rotation</key>
<value>180</value>
</param>
<param>
<key>id</key>
<value>blocks_delay_0</value>
</param>
<param>
<key>maxoutbuf</key>
<value>0</value>
</param>
<param>
<key>minoutbuf</key>
<value>0</value>
</param>
<param>
<key>num_ports</key>
<value>1</value>
</param>
<param>
<key>type</key>
<value>float</value>
</param>
<param>
<key>vlen</key>
<value>1</value>
</param>
</block>
<block>
<key>blocks_float_to_complex</key>
<param>
<key>alias</key>
<value></value>
</param>
<param>
<key>comment</key>
<value></value>
</param>
<param>
<key>affinity</key>
<value></value>
</param>
<param>
<key>_enabled</key>
<value>True</value>
</param>
<param>
<key>_coordinate</key>
<value>(395, 396)</value>
</param>
<param>
<key>_rotation</key>
<value>180</value>
</param>
<param>
<key>id</key>
<value>blocks_float_to_complex_0</value>
</param>
<param>
<key>maxoutbuf</key>
<value>0</value>
</param>
<param>
<key>minoutbuf</key>
<value>0</value>
</param>
<param>
<key>vlen</key>
<value>1</value>
</param>
</block>
<block>
<key>blocks_multiply_xx</key>
<param>
<key>alias</key>
<value></value>
</param>
<param>
<key>comment</key>
<value></value>
</param>
<param>
<key>affinity</key>
<value></value>
</param>
<param>
<key>_enabled</key>
<value>True</value>
</param>
<param>
<key>_coordinate</key>
<value>(909, 396)</value>
</param>
<param>
<key>_rotation</key>
<value>180</value>
</param>
<param>
<key>id</key>
<value>blocks_multiply_xx_0</value>
</param>
<param>
<key>type</key>
<value>complex</value>
</param>
<param>
<key>maxoutbuf</key>
<value>0</value>
</param>
<param>
<key>minoutbuf</key>
<value>0</value>
</param>
<param>
<key>num_inputs</key>
<value>2</value>
</param>
<param>
<key>vlen</key>
<value>1</value>
</param>
</block>
<block>
<key>blocks_packed_to_unpacked_xx</key>
<param>
<key>bits_per_chunk</key>
<value>4</value>
</param>
<param>
<key>alias</key>
<value></value>
</param>
<param>
<key>comment</key>
<value></value>
</param>
<param>
<key>affinity</key>
<value></value>
</param>
<param>
<key>_enabled</key>
<value>True</value>
</param>
<param>
<key>endianness</key>
<value>gr.GR_LSB_FIRST</value>
</param>
<param>
<key>_coordinate</key>
<value>(641, 205)</value>
</param>
<param>
<key>_rotation</key>
<value>0</value>
</param>
<param>
<key>id</key>
<value>blocks_packed_to_unpacked_xx_0</value>
</param>
<param>
<key>maxoutbuf</key>
<value>0</value>
</param>
<param>
<key>minoutbuf</key>
<value>0</value>
</param>
<param>
<key>num_ports</key>
<value>1</value>
</param>
<param>
<key>type</key>
<value>byte</value>
</param>
</block>
<block>
<key>blocks_pdu_to_tagged_stream</key>
<param>
<key>alias</key>
<value></value>
</param>
<param>
<key>comment</key>
<value></value>
</param>
<param>
<key>affinity</key>
<value></value>
</param>
<param>
<key>_enabled</key>
<value>True</value>
</param>
<param>
<key>_coordinate</key>
<value>(393, 213)</value>
</param>
<param>
<key>_rotation</key>
<value>0</value>
</param>
<param>
<key>id</key>
<value>blocks_pdu_to_tagged_stream_0_0_0</value>
</param>
<param>
<key>type</key>
<value>byte</value>
</param>
<param>
<key>tag</key>
<value>pdu_length</value>
</param>
<param>
<key>maxoutbuf</key>
<value>0</value>
</param>
<param>
<key>minoutbuf</key>
<value>0</value>
</param>
</block>
<block>
<key>blocks_repeat</key>
<param>
<key>alias</key>
<value></value>
</param>
<param>
<key>comment</key>
<value></value>
</param>
<param>
<key>affinity</key>
<value></value>
</param>
<param>
<key>_enabled</key>
<value>True</value>
</param>
<param>
<key>_coordinate</key>
<value>(1116, 213)</value>
</param>
<param>
<key>_rotation</key>
<value>0</value>
</param>
<param>
<key>id</key>
<value>blocks_repeat_0</value>
</param>
<param>
<key>interp</key>
<value>4</value>
</param>
<param>
<key>maxoutbuf</key>
<value>0</value>
</param>
<param>
<key>minoutbuf</key>
<value>0</value>
</param>
<param>
<key>type</key>
<value>complex</value>
</param>
<param>
<key>vlen</key>
<value>1</value>
</param>
</block>
<block>
<key>blocks_sub_xx</key>
<param>
<key>alias</key>
<value></value>
</param>
<param>
<key>comment</key>
<value></value>
</param>
<param>
<key>affinity</key>
<value></value>
</param>
<param>
<key>_enabled</key>
<value>0</value>
</param>
<param>
<key>_coordinate</key>
<value>(629, 608)</value>
</param>
<param>
<key>_rotation</key>
<value>0</value>
</param>
<param>
<key>id</key>
<value>blocks_sub_xx_0</value>
</param>
<param>
<key>type</key>
<value>float</value>
</param>
<param>
<key>maxoutbuf</key>
<value>0</value>
</param>
<param>
<key>minoutbuf</key>
<value>0</value>
</param>
<param>
<key>num_inputs</key>
<value>2</value>
</param>
<param>
<key>vlen</key>
<value>1</value>
</param>
</block>
<block>
<key>blocks_vector_source_x</key>
<param>
<key>alias</key>
<value></value>
</param>
<param>
<key>comment</key>
<value></value>
</param>
<param>
<key>affinity</key>
<value></value>
</param>
<param>
<key>_enabled</key>
<value>True</value>
</param>
<param>
<key>_coordinate</key>
<value>(1068, 422)</value>
</param>
<param>
<key>_rotation</key>
<value>180</value>
</param>
<param>
<key>id</key>
<value>blocks_vector_source_x_0</value>
</param>
<param>
<key>maxoutbuf</key>
<value>0</value>
</param>
<param>
<key>minoutbuf</key>
<value>0</value>
</param>
<param>
<key>type</key>
<value>complex</value>
</param>
<param>
<key>repeat</key>
<value>True</value>
</param>
<param>
<key>tags</key>
<value>[]</value>
</param>
<param>
<key>vlen</key>
<value>1</value>
</param>
<param>
<key>vector</key>
<value>[0, sin(pi/4), 1, sin(3*pi/4)]</value>
</param>
</block>
<block>
<key>digital_chunks_to_symbols_xx</key>
<param>
<key>alias</key>
<value></value>
</param>
<param>
<key>comment</key>
<value></value>
</param>
<param>
<key>affinity</key>
<value></value>
</param>
<param>
<key>dimension</key>
<value>16</value>
</param>
<param>
<key>_enabled</key>
<value>True</value>
</param>
<param>
<key>_coordinate</key>
<value>(852, 205)</value>
</param>
<param>
<key>_rotation</key>
<value>0</value>
</param>
<param>
<key>id</key>
<value>digital_chunks_to_symbols_xx_0</value>
</param>
<param>
<key>in_type</key>
<value>byte</value>
</param>
<param>
<key>maxoutbuf</key>
<value>0</value>
</param>
<param>
<key>minoutbuf</key>
<value>0</value>
</param>
<param>
<key>num_ports</key>
<value>1</value>
</param>
<param>
<key>out_type</key>
<value>complex</value>
</param>
<param>
<key>symbol_table</key>
<value>[(1+1j), (-1+1j), (1-1j), (-1+1j), (1+1j), (-1-1j), (-1-1j), (1+1j), (-1+1j), (-1+1j), (-1-1j), (1-1j), (-1-1j), (1-1j), (1+1j), (1-1j), (1-1j), (-1-1j), (1+1j), (-1-1j), (1-1j), (-1+1j), (-1+1j), (1-1j), (-1-1j), (-1-1j), (-1+1j), (1+1j), (-1+1j), (1+1j), (1-1j), (1+1j), (-1+1j), (-1+1j), (-1-1j), (1-1j), (-1-1j), (1-1j), (1+1j), (1-1j), (1+1j), (-1+1j), (1-1j), (-1+1j), (1+1j), (-1-1j), (-1-1j), (1+1j), (-1-1j), (-1-1j), (-1+1j), (1+1j), (-1+1j), (1+1j), (1-1j), (1+1j), (1-1j), (-1-1j), (1+1j), (-1-1j), (1-1j), (-1+1j), (-1+1j), (1-1j), (-1-1j), (1-1j), (1+1j), (1-1j), (1+1j), (-1+1j), (1-1j), (-1+1j), (1+1j), (-1-1j), (-1-1j), (1+1j), (-1+1j), (-1+1j), (-1-1j), (1-1j), (-1+1j), (1+1j), (1-1j), (1+1j), (1-1j), (-1-1j), (1+1j), (-1-1j), (1-1j), (-1+1j), (-1+1j), (1-1j), (-1-1j), (-1-1j), (-1+1j), (1+1j), (1+1j), (-1-1j), (-1-1j), (1+1j), (-1+1j), (-1+1j), (-1-1j), (1-1j), (-1-1j), (1-1j), (1+1j), (1-1j), (1+1j), (-1+1j), (1-1j), (-1+1j), (1-1j), (-1+1j), (-1+1j), (1-1j), (-1-1j), (-1-1j), (-1+1j), (1+1j), (-1+1j), (1+1j), (1-1j), (1+1j), (1-1j), (-1-1j), (1+1j), (-1-1j), (1+1j), (1-1j), (1+1j), (-1+1j), (1-1j), (-1+1j), (1+1j), (-1-1j), (-1-1j), (1+1j), (-1+1j), (-1+1j), (-1-1j), (1-1j), (-1-1j), (1-1j), (1-1j), (1+1j), (1-1j), (-1-1j), (1+1j), (-1-1j), (1-1j), (-1+1j), (-1+1j), (1-1j), (-1-1j), (-1-1j), (-1+1j), (1+1j), (-1+1j), (1+1j), (-1-1j), (1+1j), (-1+1j), (-1+1j), (-1-1j), (1-1j), (-1-1j), (1-1j), (1+1j), (1-1j), (1+1j), (-1+1j), (1-1j), (-1+1j), (1+1j), (-1-1j), (-1+1j), (1-1j), (-1-1j), (-1-1j), (-1+1j), (1+1j), (-1+1j), (1+1j), (1-1j), (1+1j), (1-1j), (-1-1j), (1+1j), (-1-1j), (1-1j), (-1+1j), (-1-1j), (1-1j), (-1-1j), (1-1j), (1+1j), (1-1j), (1+1j), (-1+1j), (1-1j), (-1+1j), (1+1j), (-1-1j), (-1-1j), (1+1j), (-1+1j), (-1+1j), (-1+1j), (1+1j), (-1+1j), (1+1j), (1-1j), (1+1j), (1-1j), (-1-1j), (1+1j), (-1-1j), (1-1j), (-1+1j), (-1+1j), (1-1j), (-1-1j), (-1-1j), (1-1j), (-1+1j), (1+1j), (-1-1j), (-1-1j), (1+1j), (-1+1j), (-1+1j), (-1-1j), (1-1j), (-1-1j), (1-1j), (1+1j), (1-1j), (1+1j), (-1+1j), (1+1j), (-1-1j), (1-1j), (-1+1j), (-1+1j), (1-1j), (-1-1j), (-1-1j), (-1+1j), (1+1j), (-1+1j), (1+1j), (1-1j), (1+1j), (1-1j), (-1-1j)]</value>
</param>
</block>
<block>
<key>digital_clock_recovery_mm_xx</key>
<param>
<key>alias</key>
<value></value>
</param>
<param>
<key>comment</key>
<value></value>
</param>
<param>
<key>affinity</key>
<value></value>
</param>
<param>
<key>_enabled</key>
<value>0</value>
</param>
<param>
<key>_coordinate</key>
<value>(770, 589)</value>
</param>
<param>
<key>_rotation</key>
<value>0</value>
</param>
<param>
<key>gain_mu</key>
<value>0.03</value>
</param>
<param>
<key>gain_omega</key>
<value>0.000225</value>
</param>
<param>
<key>id</key>
<value>digital_clock_recovery_mm_xx_0</value>
</param>
<param>
<key>maxoutbuf</key>
<value>0</value>
</param>
<param>
<key>minoutbuf</key>
<value>0</value>
</param>
<param>
<key>mu</key>
<value>0.5</value>
</param>
<param>
<key>omega_relative_limit</key>
<value>0.0002</value>
</param>
<param>
<key>omega</key>
<value>2</value>
</param>
<param>
<key>type</key>
<value>float</value>
</param>
</block>
<block>
<key>foo_burst_tagger</key>
<param>
<key>alias</key>
<value></value>
</param>
<param>
<key>comment</key>
<value></value>
</param>
<param>
<key>affinity</key>
<value></value>
</param>
<param>
<key>_enabled</key>
<value>True</value>
</param>
<param>
<key>_coordinate</key>
<value>(183, 401)</value>
</param>
<param>
<key>_rotation</key>
<value>180</value>
</param>
<param>
<key>id</key>
<value>foo_burst_tagger_0</value>
</param>
<param>
<key>maxoutbuf</key>
<value>0</value>
</param>
<param>
<key>minoutbuf</key>
<value>0</value>
</param>
<param>
<key>mult</key>
<value>128</value>
</param>
<param>
<key>tag_name</key>
<value>pmt.intern("pdu_length")</value>
</param>
</block>
<block>
<key>ieee802_15_4_access_code_prefixer</key>
<param>
<key>alias</key>
<value></value>
</param>
<param>
<key>comment</key>
<value></value>
</param>
<param>
<key>affinity</key>
<value></value>
</param>
<param>
<key>_enabled</key>
<value>2</value>
</param>
<param>
<key>_coordinate</key>
<value>(176, 217)</value>
</param>
<param>
<key>_rotation</key>
<value>0</value>
</param>
<param>
<key>id</key>
<value>ieee802_15_4_access_code_prefixer_0</value>
</param>
<param>
<key>maxoutbuf</key>
<value>0</value>
</param>
<param>
<key>minoutbuf</key>
<value>0</value>
</param>
</block>
<block>
<key>ieee802_15_4_packet_sink</key>
<param>
<key>alias</key>
<value></value>
</param>
<param>
<key>comment</key>
<value></value>
</param>
<param>
<key>affinity</key>
<value></value>
</param>
<param>
<key>_enabled</key>
<value>0</value>
</param>
<param>
<key>_coordinate</key>
<value>(1006, 621)</value>
</param>
<param>
<key>_rotation</key>
<value>0</value>
</param>
<param>
<key>id</key>
<value>ieee802_15_4_packet_sink_0</value>
</param>
<param>
<key>maxoutbuf</key>
<value>0</value>
</param>
<param>
<key>minoutbuf</key>
<value>0</value>
</param>
<param>
<key>th</key>
<value>10</value>
</param>
</block>
<block>
<key>import</key>
<param>
<key>alias</key>
<value></value>
</param>
<param>
<key>comment</key>
<value></value>
</param>
<param>
<key>_enabled</key>
<value>True</value>
</param>
<param>
<key>_coordinate</key>
<value>(296, 12)</value>
</param>
<param>
<key>_rotation</key>
<value>0</value>
</param>
<param>
<key>id</key>
<value>import_0</value>
</param>
<param>
<key>import</key>
<value>from math import sin, pi</value>
</param>
</block>
<block>
<key>note</key>
<param>
<key>alias</key>
<value></value>
</param>
<param>
<key>comment</key>
<value></value>
</param>
<param>
<key>_enabled</key>
<value>True</value>
</param>
<param>
<key>_coordinate</key>
<value>(633, 156)</value>
</param>
<param>
<key>_rotation</key>
<value>0</value>
</param>
<param>
<key>id</key>
<value>note_0</value>
</param>
<param>
<key>note</key>
<value>lower nipple is sent first</value>
</param>
</block>
<block>
<key>note</key>
<param>
<key>alias</key>
<value></value>
</param>
<param>
<key>comment</key>
<value></value>
</param>
<param>
<key>_enabled</key>
<value>True</value>
</param>
<param>
<key>_coordinate</key>
<value>(176, 164)</value>
</param>
<param>
<key>_rotation</key>
<value>0</value>
</param>
<param>
<key>id</key>
<value>note_0_0</value>
</param>
<param>
<key>note</key>
<value>Access Code Prefixer typically applies preamble, SFD, and PHY data unit length</value>
</param>
</block>
<block>
<key>note</key>
<param>
<key>alias</key>
<value></value>
</param>
<param>
<key>comment</key>
<value></value>
</param>
<param>
<key>_enabled</key>
<value>True</value>
</param>
<param>
<key>_coordinate</key>
<value>(846, 158)</value>
</param>
<param>
<key>_rotation</key>
<value>0</value>
</param>
<param>
<key>id</key>
<value>note_1</value>
</param>
<param>
<key>note</key>
<value>maps chunks of 4 bis directly to qpsk symbols</value>
</param>
</block>
<block>
<key>note</key>
<param>
<key>alias</key>
<value></value>
</param>
<param>
<key>comment</key>
<value></value>
</param>
<param>
<key>_enabled</key>
<value>True</value>
</param>
<param>
<key>_coordinate</key>
<value>(1074, 358)</value>
</param>
<param>
<key>_rotation</key>
<value>180</value>
</param>
<param>
<key>id</key>
<value>note_2</value>
</param>
<param>
<key>note</key>
<value>half sine pulse shape</value>
</param>
</block>
<block>
<key>note</key>
<param>
<key>alias</key>
<value></value>
</param>
<param>
<key>comment</key>
<value></value>
</param>
<param>
<key>_enabled</key>
<value>True</value>
</param>
<param>
<key>_coordinate</key>
<value>(1085, 161)</value>
</param>
<param>
<key>_rotation</key>
<value>0</value>
</param>
<param>
<key>id</key>
<value>note_3</value>
</param>
<param>
<key>note</key>
<value>4 samples per (chip) symbol</value>
</param>
</block>
<block>
<key>note</key>
<param>
<key>alias</key>
<value></value>
</param>
<param>
<key>comment</key>
<value></value>
</param>
<param>
<key>_enabled</key>
<value>True</value>
</param>
<param>
<key>_coordinate</key>
<value>(534, 344)</value>
</param>
<param>
<key>_rotation</key>
<value>0</value>
</param>
<param>
<key>id</key>
<value>note_4</value>
</param>
<param>
<key>note</key>
<value>delay quadrature component to get O-QPSK</value>
</param>
</block>
<block>
<key>note</key>
<param>
<key>alias</key>
<value></value>
</param>
<param>
<key>comment</key>
<value></value>
</param>
<param>
<key>_enabled</key>
<value>True</value>
</param>
<param>
<key>_coordinate</key>
<value>(288, 331)</value>
</param>
<param>
<key>_rotation</key>
<value>0</value>
</param>
<param>
<key>id</key>
<value>note_5</value>
</param>
<param>
<key>note</key>
<value>RRC filter missing</value>
</param>
</block>
<block>
<key>note</key>
<param>
<key>alias</key>
<value></value>
</param>
<param>
<key>comment</key>
<value></value>
</param>
<param>
<key>_enabled</key>
<value>True</value>
</param>
<param>
<key>_coordinate</key>
<value>(1064, 20)</value>
</param>
<param>
<key>_rotation</key>
<value>0</value>
</param>
<param>
<key>id</key>
<value>note_6</value>
</param>
<param>
<key>note</key>
<value>Credit to Bastian Bloessl and gr-ieee802-15-4 for these modules</value>
</param>
</block>
<block>
<key>pad_sink</key>
<param>
<key>comment</key>
<value></value>
</param>
<param>
<key>_enabled</key>
<value>True</value>
</param>
<param>
<key>_coordinate</key>
<value>(24, 409)</value>
</param>
<param>
<key>_rotation</key>
<value>180</value>
</param>
<param>
<key>id</key>
<value>pad_sink_0</value>
</param>
<param>
<key>type</key>
<value>complex</value>
</param>
<param>
<key>label</key>
<value>txout</value>
</param>
<param>
<key>num_streams</key>
<value>1</value>
</param>
<param>
<key>optional</key>
<value>True</value>
</param>
<param>
<key>vlen</key>
<value>1</value>
</param>
</block>
<block>
<key>pad_sink</key>
<param>
<key>comment</key>
<value></value>
</param>
<param>
<key>_enabled</key>
<value>0</value>
</param>
<param>
<key>_coordinate</key>
<value>(1175, 621)</value>
</param>
<param>
<key>_rotation</key>
<value>0</value>
</param>
<param>
<key>id</key>
<value>pad_sink_1</value>
</param>
<param>
<key>type</key>
<value>message</value>
</param>
<param>
<key>label</key>
<value>rxout</value>
</param>
<param>
<key>num_streams</key>
<value>1</value>
</param>
<param>
<key>optional</key>
<value>True</value>
</param>
<param>
<key>vlen</key>
<value>1</value>
</param>
</block>
<block>
<key>pad_source</key>
<param>
<key>comment</key>
<value></value>
</param>
<param>
<key>_enabled</key>
<value>0</value>
</param>
<param>
<key>_coordinate</key>
<value>(33, 604)</value>
</param>
<param>
<key>_rotation</key>
<value>0</value>
</param>
<param>
<key>id</key>
<value>pad_source_0</value>
</param>
<param>
<key>label</key>
<value>rxin</value>
</param>
<param>
<key>num_streams</key>
<value>1</value>
</param>
<param>
<key>optional</key>
<value>True</value>
</param>
<param>
<key>type</key>
<value>complex</value>
</param>
<param>
<key>vlen</key>
<value>1</value>
</param>
</block>
<block>
<key>pad_source</key>
<param>
<key>comment</key>
<value></value>
</param>
<param>
<key>_enabled</key>
<value>True</value>
</param>
<param>
<key>_coordinate</key>
<value>(19, 213)</value>
</param>
<param>
<key>_rotation</key>
<value>0</value>
</param>
<param>
<key>id</key>
<value>pad_source_1</value>
</param>
<param>
<key>label</key>
<value>txin</value>
</param>
<param>
<key>num_streams</key>
<value>1</value>
</param>
<param>
<key>optional</key>
<value>True</value>
</param>
<param>
<key>type</key>
<value>message</value>
</param>
<param>
<key>vlen</key>
<value>1</value>
</param>
</block>
<block>
<key>single_pole_iir_filter_xx</key>
<param>
<key>alpha</key>
<value>0.00016</value>
</param>
<param>
<key>alias</key>
<value></value>
</param>
<param>
<key>comment</key>
<value></value>
</param>
<param>
<key>affinity</key>
<value></value>
</param>
<param>
<key>_enabled</key>
<value>0</value>
</param>
<param>
<key>_coordinate</key>
<value>(407, 638)</value>
</param>
<param>
<key>_rotation</key>
<value>0</value>
</param>
<param>
<key>id</key>
<value>single_pole_iir_filter_xx_0</value>
</param>
<param>
<key>maxoutbuf</key>
<value>0</value>
</param>
<param>
<key>minoutbuf</key>
<value>0</value>
</param>
<param>
<key>type</key>
<value>float</value>
</param>
<param>
<key>vlen</key>
<value>1</value>
</param>
</block>
<connection>
<source_block_id>analog_quadrature_demod_cf_0</source_block_id>
<sink_block_id>blocks_sub_xx_0</sink_block_id>
<source_key>0</source_key>
<sink_key>0</sink_key>
</connection>
<connection>
<source_block_id>analog_quadrature_demod_cf_0</source_block_id>
<sink_block_id>single_pole_iir_filter_xx_0</sink_block_id>
<source_key>0</source_key>
<sink_key>0</sink_key>
</connection>
<connection>
<source_block_id>blocks_complex_to_float_0</source_block_id>
<sink_block_id>blocks_delay_0</sink_block_id>
<source_key>1</source_key>
<sink_key>0</sink_key>
</connection>
<connection>
<source_block_id>blocks_complex_to_float_0</source_block_id>
<sink_block_id>blocks_float_to_complex_0</sink_block_id>
<source_key>0</source_key>
<sink_key>0</sink_key>
</connection>
<connection>
<source_block_id>blocks_delay_0</source_block_id>
<sink_block_id>blocks_float_to_complex_0</sink_block_id>
<source_key>0</source_key>
<sink_key>1</sink_key>
</connection>
<connection>
<source_block_id>blocks_float_to_complex_0</source_block_id>
<sink_block_id>foo_burst_tagger_0</sink_block_id>
<source_key>0</source_key>
<sink_key>0</sink_key>
</connection>
<connection>
<source_block_id>blocks_multiply_xx_0</source_block_id>
<sink_block_id>blocks_complex_to_float_0</sink_block_id>
<source_key>0</source_key>
<sink_key>0</sink_key>
</connection>
<connection>
<source_block_id>blocks_packed_to_unpacked_xx_0</source_block_id>
<sink_block_id>digital_chunks_to_symbols_xx_0</sink_block_id>
<source_key>0</source_key>
<sink_key>0</sink_key>
</connection>
<connection>
<source_block_id>blocks_pdu_to_tagged_stream_0_0_0</source_block_id>
<sink_block_id>blocks_packed_to_unpacked_xx_0</sink_block_id>
<source_key>0</source_key>
<sink_key>0</sink_key>
</connection>
<connection>
<source_block_id>blocks_repeat_0</source_block_id>
<sink_block_id>blocks_multiply_xx_0</sink_block_id>
<source_key>0</source_key>
<sink_key>1</sink_key>
</connection>
<connection>
<source_block_id>blocks_sub_xx_0</source_block_id>
<sink_block_id>digital_clock_recovery_mm_xx_0</sink_block_id>
<source_key>0</source_key>
<sink_key>0</sink_key>
</connection>
<connection>
<source_block_id>blocks_vector_source_x_0</source_block_id>
<sink_block_id>blocks_multiply_xx_0</sink_block_id>
<source_key>0</source_key>
<sink_key>0</sink_key>
</connection>
<connection>
<source_block_id>digital_chunks_to_symbols_xx_0</source_block_id>
<sink_block_id>blocks_repeat_0</sink_block_id>
<source_key>0</source_key>
<sink_key>0</sink_key>
</connection>
<connection>
<source_block_id>digital_clock_recovery_mm_xx_0</source_block_id>
<sink_block_id>ieee802_15_4_packet_sink_0</sink_block_id>
<source_key>0</source_key>
<sink_key>0</sink_key>
</connection>
<connection>
<source_block_id>foo_burst_tagger_0</source_block_id>
<sink_block_id>pad_sink_0</sink_block_id>
<source_key>0</source_key>
<sink_key>0</sink_key>
</connection>
<connection>
<source_block_id>ieee802_15_4_access_code_prefixer_0</source_block_id>
<sink_block_id>blocks_pdu_to_tagged_stream_0_0_0</sink_block_id>
<source_key>out</source_key>
<sink_key>pdus</sink_key>
</connection>
<connection>
<source_block_id>ieee802_15_4_packet_sink_0</source_block_id>
<sink_block_id>pad_sink_1</sink_block_id>
<source_key>out</source_key>
<sink_key>in</sink_key>
</connection>
<connection>
<source_block_id>pad_source_0</source_block_id>
<sink_block_id>analog_quadrature_demod_cf_0</sink_block_id>
<source_key>0</source_key>
<sink_key>0</sink_key>
</connection>
<connection>
<source_block_id>pad_source_1</source_block_id>
<sink_block_id>ieee802_15_4_access_code_prefixer_0</sink_block_id>
<source_key>out</source_key>
<sink_key>in</sink_key>
</connection>
<connection>
<source_block_id>single_pole_iir_filter_xx_0</source_block_id>
<sink_block_id>blocks_sub_xx_0</sink_block_id>
<source_key>0</source_key>
<sink_key>1</sink_key>
</connection>
</flow_graph>
| {
"pile_set_name": "Github"
} |
'use strict';
Object.defineProperty(exports, '__esModule', { value: true });
var prefix = 'fab';
var iconName = 'replyd';
var width = 448;
var height = 512;
var ligatures = [];
var unicode = 'f3e6';
var svgPathData = 'M320 480H128C57.6 480 0 422.4 0 352V160C0 89.6 57.6 32 128 32h192c70.4 0 128 57.6 128 128v192c0 70.4-57.6 128-128 128zM193.4 273.2c-6.1-2-11.6-3.1-16.4-3.1-7.2 0-13.5 1.9-18.9 5.6-5.4 3.7-9.6 9-12.8 15.8h-1.1l-4.2-18.3h-28v138.9h36.1v-89.7c1.5-5.4 4.4-9.8 8.7-13.2 4.3-3.4 9.8-5.1 16.2-5.1 4.6 0 9.8 1 15.6 3.1l4.8-34zm115.2 103.4c-3.2 2.4-7.7 4.8-13.7 7.1-6 2.3-12.8 3.5-20.4 3.5-12.2 0-21.1-3-26.5-8.9-5.5-5.9-8.5-14.7-9-26.4h83.3c.9-4.8 1.6-9.4 2.1-13.9.5-4.4.7-8.6.7-12.5 0-10.7-1.6-19.7-4.7-26.9-3.2-7.2-7.3-13-12.5-17.2-5.2-4.3-11.1-7.3-17.8-9.2-6.7-1.8-13.5-2.8-20.6-2.8-21.1 0-37.5 6.1-49.2 18.3s-17.5 30.5-17.5 55c0 22.8 5.2 40.7 15.6 53.7 10.4 13.1 26.8 19.6 49.2 19.6 10.7 0 20.9-1.5 30.4-4.6 9.5-3.1 17.1-6.8 22.6-11.2l-12-23.6zm-21.8-70.3c3.8 5.4 5.3 13.1 4.6 23.1h-51.7c.9-9.4 3.7-17 8.2-22.6 4.5-5.6 11.5-8.5 21-8.5 8.2-.1 14.1 2.6 17.9 8zm79.9 2.5c4.1 3.9 9.4 5.8 16.1 5.8 7 0 12.6-1.9 16.7-5.8s6.1-9.1 6.1-15.6-2-11.6-6.1-15.4c-4.1-3.8-9.6-5.7-16.7-5.7-6.7 0-12 1.9-16.1 5.7-4.1 3.8-6.1 8.9-6.1 15.4s2 11.7 6.1 15.6zm0 100.5c4.1 3.9 9.4 5.8 16.1 5.8 7 0 12.6-1.9 16.7-5.8s6.1-9.1 6.1-15.6-2-11.6-6.1-15.4c-4.1-3.8-9.6-5.7-16.7-5.7-6.7 0-12 1.9-16.1 5.7-4.1 3.8-6.1 8.9-6.1 15.4 0 6.6 2 11.7 6.1 15.6z';
exports.definition = {
prefix: prefix,
iconName: iconName,
icon: [
width,
height,
ligatures,
unicode,
svgPathData
]};
exports.faReplyd = exports.definition;
exports.prefix = prefix;
exports.iconName = iconName;
exports.width = width;
exports.height = height;
exports.ligatures = ligatures;
exports.unicode = unicode;
exports.svgPathData = svgPathData; | {
"pile_set_name": "Github"
} |
'use strict'
const utils = require('./utils')
const config = require('../config/index')
const isProduction = process.env.NODE_ENV === 'production'
module.exports = {
loaders: utils.cssLoaders({
sourceMap: isProduction
? config.build.productionSourceMap
: config.dev.cssSourceMap,
extract: isProduction
}),
transformToRequire: {
video: 'src',
source: 'src',
img: 'src',
image: 'xlink:href'
}
}
| {
"pile_set_name": "Github"
} |
import HTMLElement from './HTMLElement'
export default class HTMLMediaElement extends HTMLElement {
constructor(tagName) {
super(tagName)
}
addTextTrack() {}
captureStream() {}
fastSeek() {}
load() {}
pause() {}
play() {}
}
| {
"pile_set_name": "Github"
} |
<resources>
<string name="app_name">Datasource</string>
</resources>
| {
"pile_set_name": "Github"
} |
using System.Runtime.CompilerServices;
using ClassicUO.Input;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;
namespace ClassicUO.Renderer
{
internal class Camera
{
private float[] _cameraZoomValues = new float[1] {1f};
private Matrix _projection;
private Matrix _transform = Matrix.Identity, _inverseTransform = Matrix.Identity;
private bool _updateMatrixes = true, _updateProjection = true;
private int _zoomIndex;
public Matrix ViewTransformMatrix => TransformMatrix /** ProjectionMatrix*/;
public Matrix ProjectionMatrix
{
get
{
if (_updateProjection)
{
Matrix.CreateOrthographicOffCenter
(
0,
Bounds.Width,
Bounds.Height,
0,
0,
-1,
out _projection
);
_updateProjection = false;
}
return _projection;
}
}
public Matrix TransformMatrix
{
get
{
UpdateMatrices();
return _transform;
}
}
public Matrix InverseTransformMatrix
{
get
{
UpdateMatrices();
return _inverseTransform;
}
}
public float Zoom
{
get => _cameraZoomValues[_zoomIndex];
set
{
if (_cameraZoomValues[_zoomIndex] != value)
{
// TODO: coding a better way to set zoom
for (_zoomIndex = 0; _zoomIndex < _cameraZoomValues.Length; ++_zoomIndex)
{
if (_cameraZoomValues[_zoomIndex] == value)
{
break;
}
}
// hack to trigger the bounds check and update matrices
ZoomIndex = _zoomIndex;
}
}
}
public int ZoomIndex
{
get => _zoomIndex;
set
{
_updateMatrixes = true;
_zoomIndex = value;
if (_zoomIndex < 0)
{
_zoomIndex = 0;
}
else if (_zoomIndex >= _cameraZoomValues.Length)
{
_zoomIndex = _cameraZoomValues.Length - 1;
}
}
}
public int ZoomValuesCount => _cameraZoomValues.Length;
public Rectangle Bounds;
public Vector2 Origin;
public Point Position;
public void SetZoomValues(float[] values)
{
_cameraZoomValues = values;
}
public void SetGameWindowBounds(int x, int y, int width, int height)
{
if (Bounds.X != x || Bounds.Y != y || Bounds.Width != width || Bounds.Height != height)
{
Bounds.X = x;
Bounds.Y = y;
Bounds.Width = width;
Bounds.Height = height;
Origin.X = width / 2f;
Origin.Y = height / 2f;
//Position = Origin;
_updateMatrixes = true;
_updateProjection = true;
}
}
public void SetPosition(int x, int y)
{
if (Position.X != x || Position.Y != y)
{
Position.X = x;
Position.Y = y;
_updateMatrixes = true;
}
}
public void SetPositionOffset(int x, int y)
{
SetPosition(Position.X + x, Position.Y + y);
}
public Viewport GetViewport()
{
return new Viewport
(
Bounds.X,
Bounds.Y,
Bounds.Width,
Bounds.Height
);
}
public void Update()
{
UpdateMatrices();
}
public Point ScreenToWorld(Point point)
{
UpdateMatrices();
Transform(ref point, ref _inverseTransform, out point);
return point;
}
public Point WorldToScreen(Point point)
{
UpdateMatrices();
Transform(ref point, ref _transform, out point);
return point;
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
private static void Transform(ref Point position, ref Matrix matrix, out Point result)
{
float x = position.X * matrix.M11 + position.Y * matrix.M21 + matrix.M41;
float y = position.X * matrix.M12 + position.Y * matrix.M22 + matrix.M42;
result.X = (int) x;
result.Y = (int) y;
}
public Point MouseToWorldPosition()
{
Point mouse = Mouse.Position;
mouse.X -= Bounds.X;
mouse.Y -= Bounds.Y;
return ScreenToWorld(mouse);
}
private void UpdateMatrices()
{
if (!_updateMatrixes)
{
return;
}
Matrix temp;
Matrix.CreateTranslation(-Origin.X, -Origin.Y, 0f, out _transform);
float zoom = 1f / Zoom;
if (zoom != 1f)
{
Matrix.CreateScale(zoom, zoom, 1f, out temp);
Matrix.Multiply(ref _transform, ref temp, out _transform);
}
Matrix.CreateTranslation(Origin.X, Origin.Y, 0f, out temp);
Matrix.Multiply(ref _transform, ref temp, out _transform);
Matrix.Invert(ref _transform, out _inverseTransform);
_updateMatrixes = false;
}
}
} | {
"pile_set_name": "Github"
} |
// Copyright Joyent, Inc. and other Node contributors.
//
// Permission is hereby granted, free of charge, to any person obtaining a
// copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to permit
// persons to whom the Software is furnished to do so, subject to the
// following conditions:
//
// The above copyright notice and this permission notice shall be included
// in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
// USE OR OTHER DEALINGS IN THE SOFTWARE.
if (!process.versions.openssl) {
console.error('Skipping because node compiled without OpenSSL.');
process.exit(0);
}
var common = require('../common');
var assert = require('assert');
var fs = require('fs');
var tls = require('tls');
var path = require('path');
// https://github.com/joyent/node/issues/1218
// uncatchable exception on TLS connection error
(function() {
var cert = fs.readFileSync(path.join(common.fixturesDir, 'test_cert.pem'));
var key = fs.readFileSync(path.join(common.fixturesDir, 'test_key.pem'));
var errorEmitted = false;
process.on('exit', function() {
assert.ok(errorEmitted);
});
var conn = tls.connect({cert: cert, key: key, port: common.PORT}, function() {
assert.ok(false); // callback should never be executed
});
conn.on('error', function() {
errorEmitted = true;
});
})();
// SSL_accept/SSL_connect error handling
(function() {
var cert = fs.readFileSync(path.join(common.fixturesDir, 'test_cert.pem'));
var key = fs.readFileSync(path.join(common.fixturesDir, 'test_key.pem'));
var errorEmitted = false;
process.on('exit', function() {
assert.ok(errorEmitted);
});
var conn = tls.connect({
cert: cert,
key: key,
port: common.PORT,
ciphers: 'rick-128-roll'
}, function() {
assert.ok(false); // callback should never be executed
});
conn.on('error', function() {
errorEmitted = true;
});
})();
| {
"pile_set_name": "Github"
} |
sys$library:ucx$ipc.olb/library
| {
"pile_set_name": "Github"
} |
package com.netflix.conductor.dao.es6.index;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.google.common.collect.ImmutableMap;
import com.netflix.conductor.common.metadata.events.EventExecution;
import com.netflix.conductor.common.metadata.events.EventHandler;
import com.netflix.conductor.common.metadata.tasks.Task;
import com.netflix.conductor.common.metadata.tasks.TaskExecLog;
import com.netflix.conductor.common.run.SearchResult;
import com.netflix.conductor.common.run.TaskSummary;
import com.netflix.conductor.common.run.Workflow;
import com.netflix.conductor.common.run.WorkflowSummary;
import com.netflix.conductor.common.utils.JsonMapperProvider;
import com.netflix.conductor.core.events.queue.Message;
import com.netflix.conductor.elasticsearch.ElasticSearchConfiguration;
import com.netflix.conductor.elasticsearch.ElasticSearchRestClientBuilderProvider;
import com.netflix.conductor.elasticsearch.EmbeddedElasticSearch;
import com.netflix.conductor.elasticsearch.SystemPropertiesElasticSearchConfiguration;
import com.netflix.conductor.elasticsearch.es6.EmbeddedElasticSearchV6;
import com.netflix.conductor.support.TestUtils;
import org.elasticsearch.client.Response;
import org.elasticsearch.client.RestClient;
import org.elasticsearch.client.RestClientBuilder;
import org.joda.time.DateTime;
import org.junit.After;
import org.junit.AfterClass;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.Reader;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.TimeZone;
import java.util.UUID;
import java.util.concurrent.TimeUnit;
import java.util.function.Supplier;
import static org.awaitility.Awaitility.await;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
public class TestElasticSearchRestDAOV6 {
private static final SimpleDateFormat SIMPLE_DATE_FORMAT = new SimpleDateFormat("yyyyMMWW");
private static final String INDEX_PREFIX = "conductor";
private static final String WORKFLOW_DOC_TYPE = "workflow";
private static final String TASK_DOC_TYPE = "task";
private static final String MSG_DOC_TYPE = "message";
private static final String EVENT_DOC_TYPE = "event";
private static final String LOG_INDEX_PREFIX = "task_log";
private static ElasticSearchConfiguration configuration;
private static RestClient restClient;
private static ElasticSearchRestDAOV6 indexDAO;
private static EmbeddedElasticSearch embeddedElasticSearch;
private static ObjectMapper objectMapper;
private @interface HttpMethod {
String GET = "GET";
String POST = "POST";
String PUT = "PUT";
String HEAD = "HEAD";
String DELETE = "DELETE";
}
@BeforeClass
public static void startServer() throws Exception {
System.setProperty(ElasticSearchConfiguration.EMBEDDED_PORT_PROPERTY_NAME, "9204");
System.setProperty(ElasticSearchConfiguration.ELASTIC_SEARCH_URL_PROPERTY_NAME, "http://localhost:9204");
System.setProperty(ElasticSearchConfiguration.ELASTIC_SEARCH_INDEX_BATCH_SIZE_PROPERTY_NAME, "1");
configuration = new SystemPropertiesElasticSearchConfiguration();
String host = configuration.getEmbeddedHost();
int port = configuration.getEmbeddedPort();
String clusterName = configuration.getEmbeddedClusterName();
embeddedElasticSearch = new EmbeddedElasticSearchV6(clusterName, host, port);
embeddedElasticSearch.start();
ElasticSearchRestClientBuilderProvider restClientProvider =
new ElasticSearchRestClientBuilderProvider(configuration);
RestClientBuilder restClientBuilder = restClientProvider.get();
restClient = restClientBuilder.build();
Map<String, String> params = new HashMap<>();
params.put("wait_for_status", "yellow");
params.put("timeout", "30s");
restClient.performRequest("GET", "/_cluster/health", params);
objectMapper = new JsonMapperProvider().get();
indexDAO = new ElasticSearchRestDAOV6(restClientBuilder, configuration, objectMapper);
}
@AfterClass
public static void closeClient() throws Exception {
if (restClient != null) {
restClient.close();
}
embeddedElasticSearch.stop();
}
@Before
public void setup() throws Exception {
indexDAO.setup();
}
@After
public void tearDown() throws Exception {
deleteAllIndices();
}
private static void deleteAllIndices() throws IOException {
Response beforeResponse = restClient.performRequest(HttpMethod.GET, "/_cat/indices");
Reader streamReader = new InputStreamReader(beforeResponse.getEntity().getContent());
BufferedReader bufferedReader = new BufferedReader(streamReader);
String line;
while ((line = bufferedReader.readLine()) != null) {
String[] fields = line.split("\\s");
String endpoint = String.format("/%s", fields[2]);
restClient.performRequest(HttpMethod.DELETE, endpoint);
}
}
private boolean indexExists(final String index) throws IOException {
return indexDAO.doesResourceExist("/" + index);
}
private boolean doesMappingExist(final String index, final String mappingName) throws IOException {
return indexDAO.doesResourceExist("/" + index + "/_mapping/" + mappingName);
}
@Test
public void assertInitialSetup() throws IOException {
SIMPLE_DATE_FORMAT.setTimeZone(TimeZone.getTimeZone("GMT"));
String workflowIndex = INDEX_PREFIX + "_" + WORKFLOW_DOC_TYPE;
String taskIndex = INDEX_PREFIX + "_" + TASK_DOC_TYPE;
String taskLogIndex = INDEX_PREFIX + "_" + LOG_INDEX_PREFIX + "_" + SIMPLE_DATE_FORMAT.format(new Date());
String messageIndex = INDEX_PREFIX + "_" + MSG_DOC_TYPE + "_" + SIMPLE_DATE_FORMAT.format(new Date());
String eventIndex = INDEX_PREFIX + "_" + EVENT_DOC_TYPE + "_" + SIMPLE_DATE_FORMAT.format(new Date());
assertTrue("Index 'conductor_workflow' should exist", indexExists("conductor_workflow"));
assertTrue("Index 'conductor_task' should exist", indexExists("conductor_task"));
assertTrue("Index '" + taskLogIndex + "' should exist", indexExists(taskLogIndex));
assertTrue("Index '" + messageIndex + "' should exist", indexExists(messageIndex));
assertTrue("Index '" + eventIndex + "' should exist", indexExists(eventIndex));
assertTrue("Mapping 'workflow' for index 'conductor' should exist", doesMappingExist(workflowIndex, WORKFLOW_DOC_TYPE));
assertTrue("Mapping 'task' for index 'conductor' should exist", doesMappingExist(taskIndex, TASK_DOC_TYPE));
}
@Test
public void shouldIndexWorkflow() {
Workflow workflow = TestUtils.loadWorkflowSnapshot("workflow");
WorkflowSummary summary = new WorkflowSummary(workflow);
indexDAO.indexWorkflow(workflow);
assertWorkflowSummary(workflow.getWorkflowId(), summary);
}
@Test
public void shouldIndexWorkflowAsync() throws Exception {
Workflow workflow = TestUtils.loadWorkflowSnapshot("workflow");
WorkflowSummary summary = new WorkflowSummary(workflow);
indexDAO.asyncIndexWorkflow(workflow).get();
assertWorkflowSummary(workflow.getWorkflowId(), summary);
}
@Test
public void shouldRemoveWorkflow() {
Workflow workflow = TestUtils.loadWorkflowSnapshot("workflow");
indexDAO.indexWorkflow(workflow);
// wait for workflow to be indexed
List<String> workflows = tryFindResults(() -> searchWorkflows(workflow.getWorkflowId()), 1);
assertEquals(1, workflows.size());
indexDAO.removeWorkflow(workflow.getWorkflowId());
workflows = tryFindResults(() -> searchWorkflows(workflow.getWorkflowId()), 0);
assertTrue("Workflow was not removed.", workflows.isEmpty());
}
@Test
public void shouldAsyncRemoveWorkflow() throws Exception {
Workflow workflow = TestUtils.loadWorkflowSnapshot("workflow");
indexDAO.indexWorkflow(workflow);
// wait for workflow to be indexed
List<String> workflows = tryFindResults(() -> searchWorkflows(workflow.getWorkflowId()), 1);
assertEquals(1, workflows.size());
indexDAO.asyncRemoveWorkflow(workflow.getWorkflowId()).get();
workflows = tryFindResults(() -> searchWorkflows(workflow.getWorkflowId()), 0);
assertTrue("Workflow was not removed.", workflows.isEmpty());
}
@Test
public void shouldUpdateWorkflow() {
Workflow workflow = TestUtils.loadWorkflowSnapshot("workflow");
WorkflowSummary summary = new WorkflowSummary(workflow);
indexDAO.indexWorkflow(workflow);
indexDAO.updateWorkflow(workflow.getWorkflowId(), new String[]{"status"}, new Object[]{Workflow.WorkflowStatus.COMPLETED});
summary.setStatus(Workflow.WorkflowStatus.COMPLETED);
assertWorkflowSummary(workflow.getWorkflowId(), summary);
}
@Test
public void shouldAsyncUpdateWorkflow() throws Exception {
Workflow workflow = TestUtils.loadWorkflowSnapshot("workflow");
WorkflowSummary summary = new WorkflowSummary(workflow);
indexDAO.indexWorkflow(workflow);
indexDAO.asyncUpdateWorkflow(workflow.getWorkflowId(), new String[]{"status"}, new Object[]{Workflow.WorkflowStatus.FAILED}).get();
summary.setStatus(Workflow.WorkflowStatus.FAILED);
assertWorkflowSummary(workflow.getWorkflowId(), summary);
}
@Test
public void shouldIndexTask() {
Workflow workflow = TestUtils.loadWorkflowSnapshot("workflow");
Task task = workflow.getTasks().get(0);
TaskSummary summary = new TaskSummary(task);
indexDAO.indexTask(task);
List<String> tasks = tryFindResults(() -> searchTasks(workflow));
assertEquals(summary.getTaskId(), tasks.get(0));
}
@Test
public void indexTaskWithBatchSizeTwo() throws Exception {
embeddedElasticSearch.stop();
startElasticSearchWithBatchSize(2);
String correlationId = "some-correlation-id";
Task task = new Task();
task.setTaskId("some-task-id");
task.setWorkflowInstanceId("some-workflow-instance-id");
task.setTaskType("some-task-type");
task.setStatus(Task.Status.FAILED);
task.setInputData(new HashMap<String, Object>() {{ put("input_key", "input_value"); }});
task.setCorrelationId(correlationId);
task.setTaskDefName("some-task-def-name");
task.setReasonForIncompletion("some-failure-reason");
indexDAO.indexTask(task);
indexDAO.indexTask(task);
await()
.atMost(5, TimeUnit.SECONDS)
.untilAsserted(() -> {
SearchResult<String> result = indexDAO
.searchTasks("correlationId='" + correlationId + "'", "*", 0, 10000, null);
assertTrue("should return 1 or more search results", result.getResults().size() > 0);
assertEquals("taskId should match the indexed task", "some-task-id", result.getResults().get(0));
});
embeddedElasticSearch.stop();
startElasticSearchWithBatchSize(1);
}
private void startElasticSearchWithBatchSize(int i) throws Exception {
System.setProperty(ElasticSearchConfiguration.ELASTIC_SEARCH_INDEX_BATCH_SIZE_PROPERTY_NAME, String.valueOf(i));
configuration = new SystemPropertiesElasticSearchConfiguration();
String host = configuration.getEmbeddedHost();
int port = configuration.getEmbeddedPort();
String clusterName = configuration.getEmbeddedClusterName();
embeddedElasticSearch = new EmbeddedElasticSearchV6(clusterName, host, port);
embeddedElasticSearch.start();
ElasticSearchRestClientBuilderProvider restClientProvider =
new ElasticSearchRestClientBuilderProvider(configuration);
RestClientBuilder restClientBuilder = restClientProvider.get();
restClient = restClientBuilder.build();
Map<String, String> params = new HashMap<>();
params.put("wait_for_status", "yellow");
params.put("timeout", "30s");
restClient.performRequest("GET", "/_cluster/health", params);
objectMapper = new JsonMapperProvider().get();
indexDAO = new ElasticSearchRestDAOV6(restClientBuilder, configuration, objectMapper);
}
@Test
public void shouldIndexTaskAsync() throws Exception {
Workflow workflow = TestUtils.loadWorkflowSnapshot("workflow");
Task task = workflow.getTasks().get(0);
TaskSummary summary = new TaskSummary(task);
indexDAO.asyncIndexTask(task).get();
List<String> tasks = tryFindResults(() -> searchTasks(workflow));
assertEquals(summary.getTaskId(), tasks.get(0));
}
@Test
public void shouldAddTaskExecutionLogs() {
List<TaskExecLog> logs = new ArrayList<>();
String taskId = uuid();
logs.add(createLog(taskId, "log1"));
logs.add(createLog(taskId, "log2"));
logs.add(createLog(taskId, "log3"));
indexDAO.addTaskExecutionLogs(logs);
List<TaskExecLog> indexedLogs = tryFindResults(() -> indexDAO.getTaskExecutionLogs(taskId), 3);
assertEquals(3, indexedLogs.size());
assertTrue("Not all logs was indexed", indexedLogs.containsAll(logs));
}
@Test
public void shouldAddTaskExecutionLogsAsync() throws Exception {
List<TaskExecLog> logs = new ArrayList<>();
String taskId = uuid();
logs.add(createLog(taskId, "log1"));
logs.add(createLog(taskId, "log2"));
logs.add(createLog(taskId, "log3"));
indexDAO.asyncAddTaskExecutionLogs(logs).get();
List<TaskExecLog> indexedLogs = tryFindResults(() -> indexDAO.getTaskExecutionLogs(taskId), 3);
assertEquals(3, indexedLogs.size());
assertTrue("Not all logs was indexed", indexedLogs.containsAll(logs));
}
@Test
public void shouldAddMessage() {
String queue = "queue";
Message message1 = new Message(uuid(), "payload1", null);
Message message2 = new Message(uuid(), "payload2", null);
indexDAO.addMessage(queue, message1);
indexDAO.addMessage(queue, message2);
List<Message> indexedMessages = tryFindResults(() -> indexDAO.getMessages(queue), 2);
assertEquals(2, indexedMessages.size());
assertTrue("Not all messages was indexed", indexedMessages.containsAll(Arrays.asList(message1, message2)));
}
@Test
public void shouldAddEventExecution() {
String event = "event";
EventExecution execution1 = createEventExecution(event);
EventExecution execution2 = createEventExecution(event);
indexDAO.addEventExecution(execution1);
indexDAO.addEventExecution(execution2);
List<EventExecution> indexedExecutions = tryFindResults(() -> indexDAO.getEventExecutions(event), 2);
assertEquals(2, indexedExecutions.size());
assertTrue("Not all event executions was indexed", indexedExecutions.containsAll(Arrays.asList(execution1, execution2)));
}
@Test
public void shouldAsyncAddEventExecution() throws Exception {
String event = "event2";
EventExecution execution1 = createEventExecution(event);
EventExecution execution2 = createEventExecution(event);
indexDAO.asyncAddEventExecution(execution1).get();
indexDAO.asyncAddEventExecution(execution2).get();
List<EventExecution> indexedExecutions = tryFindResults(() -> indexDAO.getEventExecutions(event), 2);
assertEquals(2, indexedExecutions.size());
assertTrue("Not all event executions was indexed", indexedExecutions.containsAll(Arrays.asList(execution1, execution2)));
}
@Test
public void shouldAddIndexPrefixToIndexTemplate() throws Exception {
String json = TestUtils.loadJsonResource("expected_template_task_log");
String content = indexDAO.loadTypeMappingSource("/template_task_log.json");
assertEquals(json, content);
}
@Test
public void shouldSearchRecentRunningWorkflows() throws Exception {
Workflow oldWorkflow = TestUtils.loadWorkflowSnapshot("workflow");
oldWorkflow.setStatus(Workflow.WorkflowStatus.RUNNING);
oldWorkflow.setUpdateTime(new DateTime().minusHours(2).toDate().getTime());
Workflow recentWorkflow = TestUtils.loadWorkflowSnapshot("workflow");
recentWorkflow.setStatus(Workflow.WorkflowStatus.RUNNING);
recentWorkflow.setUpdateTime(new DateTime().minusHours(1).toDate().getTime());
Workflow tooRecentWorkflow = TestUtils.loadWorkflowSnapshot("workflow");
tooRecentWorkflow.setStatus(Workflow.WorkflowStatus.RUNNING);
tooRecentWorkflow.setUpdateTime(new DateTime().toDate().getTime());
indexDAO.indexWorkflow(oldWorkflow);
indexDAO.indexWorkflow(recentWorkflow);
indexDAO.indexWorkflow(tooRecentWorkflow);
Thread.sleep(1000);
List<String> ids = indexDAO.searchRecentRunningWorkflows(2, 1);
assertEquals(1, ids.size());
assertEquals(recentWorkflow.getWorkflowId(), ids.get(0));
}
private void assertWorkflowSummary(String workflowId, WorkflowSummary summary) {
assertEquals(summary.getWorkflowType(), indexDAO.get(workflowId, "workflowType"));
assertEquals(String.valueOf(summary.getVersion()), indexDAO.get(workflowId, "version"));
assertEquals(summary.getWorkflowId(), indexDAO.get(workflowId, "workflowId"));
assertEquals(summary.getCorrelationId(), indexDAO.get(workflowId, "correlationId"));
assertEquals(summary.getStartTime(), indexDAO.get(workflowId, "startTime"));
assertEquals(summary.getUpdateTime(), indexDAO.get(workflowId, "updateTime"));
assertEquals(summary.getEndTime(), indexDAO.get(workflowId, "endTime"));
assertEquals(summary.getStatus().name(), indexDAO.get(workflowId, "status"));
assertEquals(summary.getInput(), indexDAO.get(workflowId, "input"));
assertEquals(summary.getOutput(), indexDAO.get(workflowId, "output"));
assertEquals(summary.getReasonForIncompletion(), indexDAO.get(workflowId, "reasonForIncompletion"));
assertEquals(String.valueOf(summary.getExecutionTime()), indexDAO.get(workflowId, "executionTime"));
assertEquals(summary.getEvent(), indexDAO.get(workflowId, "event"));
assertEquals(summary.getFailedReferenceTaskNames(), indexDAO.get(workflowId, "failedReferenceTaskNames"));
}
private <T> List<T> tryFindResults(Supplier<List<T>> searchFunction) {
return tryFindResults(searchFunction, 1);
}
private <T> List<T> tryFindResults(Supplier<List<T>> searchFunction, int resultsCount) {
List<T> result = Collections.emptyList();
for (int i = 0; i < 20; i++) {
result = searchFunction.get();
if (result.size() == resultsCount) {
return result;
}
try {
Thread.sleep(100);
} catch (InterruptedException e) {
throw new RuntimeException(e.getMessage(), e);
}
}
return result;
}
private List<String> searchWorkflows(String workflowId) {
return indexDAO.searchWorkflows("", "workflowId:\"" + workflowId + "\"", 0, 100, Collections.emptyList()).getResults();
}
private List<String> searchTasks(Workflow workflow) {
return indexDAO.searchTasks("", "workflowId:\"" + workflow.getWorkflowId() + "\"", 0, 100, Collections.emptyList()).getResults();
}
private TaskExecLog createLog(String taskId, String log) {
TaskExecLog taskExecLog = new TaskExecLog(log);
taskExecLog.setTaskId(taskId);
return taskExecLog;
}
private EventExecution createEventExecution(String event) {
EventExecution execution = new EventExecution(uuid(), uuid());
execution.setName("name");
execution.setEvent(event);
execution.setCreated(System.currentTimeMillis());
execution.setStatus(EventExecution.Status.COMPLETED);
execution.setAction(EventHandler.Action.Type.start_workflow);
execution.setOutput(ImmutableMap.of("a", 1, "b", 2, "c", 3));
return execution;
}
private String uuid() {
return UUID.randomUUID().toString();
}
}
| {
"pile_set_name": "Github"
} |
/*
==============================================================================
This file is part of the JUCE library.
Copyright (c) 2015 - ROLI Ltd.
Permission is granted to use this software under the terms of either:
a) the GPL v2 (or any later version)
b) the Affero GPL v3
Details of these licenses can be found at: www.gnu.org/licenses
JUCE is distributed in the hope that it will be useful, but WITHOUT ANY
WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
A PARTICULAR PURPOSE. See the GNU General Public License for more details.
------------------------------------------------------------------------------
To release a closed-source product which uses JUCE, commercial licenses are
available: visit www.juce.com for more information.
==============================================================================
*/
#ifndef JUCE_AUDIOPROCESSORGRAPH_H_INCLUDED
#define JUCE_AUDIOPROCESSORGRAPH_H_INCLUDED
//==============================================================================
/**
A type of AudioProcessor which plays back a graph of other AudioProcessors.
Use one of these objects if you want to wire-up a set of AudioProcessors
and play back the result.
Processors can be added to the graph as "nodes" using addNode(), and once
added, you can connect any of their input or output channels to other
nodes using addConnection().
To play back a graph through an audio device, you might want to use an
AudioProcessorPlayer object.
*/
class JUCE_API AudioProcessorGraph : public AudioProcessor,
private AsyncUpdater
{
public:
//==============================================================================
/** Creates an empty graph. */
AudioProcessorGraph();
/** Destructor.
Any processor objects that have been added to the graph will also be deleted.
*/
~AudioProcessorGraph();
//==============================================================================
/** Represents one of the nodes, or processors, in an AudioProcessorGraph.
To create a node, call AudioProcessorGraph::addNode().
*/
class JUCE_API Node : public ReferenceCountedObject
{
public:
//==============================================================================
/** The ID number assigned to this node.
This is assigned by the graph that owns it, and can't be changed.
*/
const uint32 nodeId;
/** The actual processor object that this node represents. */
AudioProcessor* getProcessor() const noexcept { return processor; }
/** A set of user-definable properties that are associated with this node.
This can be used to attach values to the node for whatever purpose seems
useful. For example, you might store an x and y position if your application
is displaying the nodes on-screen.
*/
NamedValueSet properties;
//==============================================================================
/** A convenient typedef for referring to a pointer to a node object. */
typedef ReferenceCountedObjectPtr<Node> Ptr;
private:
//==============================================================================
friend class AudioProcessorGraph;
const ScopedPointer<AudioProcessor> processor;
bool isPrepared;
Node (uint32 nodeId, AudioProcessor*) noexcept;
void setParentGraph (AudioProcessorGraph*) const;
void prepare (double newSampleRate, int newBlockSize, AudioProcessorGraph*);
void unprepare();
JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (Node)
};
//==============================================================================
/** Represents a connection between two channels of two nodes in an AudioProcessorGraph.
To create a connection, use AudioProcessorGraph::addConnection().
*/
struct JUCE_API Connection
{
public:
//==============================================================================
Connection (uint32 sourceNodeId, int sourceChannelIndex,
uint32 destNodeId, int destChannelIndex) noexcept;
//==============================================================================
/** The ID number of the node which is the input source for this connection.
@see AudioProcessorGraph::getNodeForId
*/
uint32 sourceNodeId;
/** The index of the output channel of the source node from which this
connection takes its data.
If this value is the special number AudioProcessorGraph::midiChannelIndex, then
it is referring to the source node's midi output. Otherwise, it is the zero-based
index of an audio output channel in the source node.
*/
int sourceChannelIndex;
/** The ID number of the node which is the destination for this connection.
@see AudioProcessorGraph::getNodeForId
*/
uint32 destNodeId;
/** The index of the input channel of the destination node to which this
connection delivers its data.
If this value is the special number AudioProcessorGraph::midiChannelIndex, then
it is referring to the destination node's midi input. Otherwise, it is the zero-based
index of an audio input channel in the destination node.
*/
int destChannelIndex;
private:
//==============================================================================
JUCE_LEAK_DETECTOR (Connection)
};
//==============================================================================
/** Deletes all nodes and connections from this graph.
Any processor objects in the graph will be deleted.
*/
void clear();
/** Returns the number of nodes in the graph. */
int getNumNodes() const noexcept { return nodes.size(); }
/** Returns a pointer to one of the nodes in the graph.
This will return nullptr if the index is out of range.
@see getNodeForId
*/
Node* getNode (const int index) const noexcept { return nodes [index]; }
/** Searches the graph for a node with the given ID number and returns it.
If no such node was found, this returns nullptr.
@see getNode
*/
Node* getNodeForId (const uint32 nodeId) const;
/** Adds a node to the graph.
This creates a new node in the graph, for the specified processor. Once you have
added a processor to the graph, the graph owns it and will delete it later when
it is no longer needed.
The optional nodeId parameter lets you specify an ID to use for the node, but
if the value is already in use, this new node will overwrite the old one.
If this succeeds, it returns a pointer to the newly-created node.
*/
Node* addNode (AudioProcessor* newProcessor, uint32 nodeId = 0);
/** Deletes a node within the graph which has the specified ID.
This will also delete any connections that are attached to this node.
*/
bool removeNode (uint32 nodeId);
//==============================================================================
/** Returns the number of connections in the graph. */
int getNumConnections() const { return connections.size(); }
/** Returns a pointer to one of the connections in the graph. */
const Connection* getConnection (int index) const { return connections [index]; }
/** Searches for a connection between some specified channels.
If no such connection is found, this returns nullptr.
*/
const Connection* getConnectionBetween (uint32 sourceNodeId,
int sourceChannelIndex,
uint32 destNodeId,
int destChannelIndex) const;
/** Returns true if there is a connection between any of the channels of
two specified nodes.
*/
bool isConnected (uint32 possibleSourceNodeId,
uint32 possibleDestNodeId) const;
/** Returns true if it would be legal to connect the specified points. */
bool canConnect (uint32 sourceNodeId, int sourceChannelIndex,
uint32 destNodeId, int destChannelIndex) const;
/** Attempts to connect two specified channels of two nodes.
If this isn't allowed (e.g. because you're trying to connect a midi channel
to an audio one or other such nonsense), then it'll return false.
*/
bool addConnection (uint32 sourceNodeId, int sourceChannelIndex,
uint32 destNodeId, int destChannelIndex);
/** Deletes the connection with the specified index. */
void removeConnection (int index);
/** Deletes any connection between two specified points.
Returns true if a connection was actually deleted.
*/
bool removeConnection (uint32 sourceNodeId, int sourceChannelIndex,
uint32 destNodeId, int destChannelIndex);
/** Removes all connections from the specified node. */
bool disconnectNode (uint32 nodeId);
/** Returns true if the given connection's channel numbers map on to valid
channels at each end.
Even if a connection is valid when created, its status could change if
a node changes its channel config.
*/
bool isConnectionLegal (const Connection* connection) const;
/** Performs a sanity checks of all the connections.
This might be useful if some of the processors are doing things like changing
their channel counts, which could render some connections obsolete.
*/
bool removeIllegalConnections();
//==============================================================================
/** A special number that represents the midi channel of a node.
This is used as a channel index value if you want to refer to the midi input
or output instead of an audio channel.
*/
static const int midiChannelIndex;
//==============================================================================
/** A special type of AudioProcessor that can live inside an AudioProcessorGraph
in order to use the audio that comes into and out of the graph itself.
If you create an AudioGraphIOProcessor in "input" mode, it will act as a
node in the graph which delivers the audio that is coming into the parent
graph. This allows you to stream the data to other nodes and process the
incoming audio.
Likewise, one of these in "output" mode can be sent data which it will add to
the sum of data being sent to the graph's output.
@see AudioProcessorGraph
*/
class JUCE_API AudioGraphIOProcessor : public AudioPluginInstance
{
public:
/** Specifies the mode in which this processor will operate.
*/
enum IODeviceType
{
audioInputNode, /**< In this mode, the processor has output channels
representing all the audio input channels that are
coming into its parent audio graph. */
audioOutputNode, /**< In this mode, the processor has input channels
representing all the audio output channels that are
going out of its parent audio graph. */
midiInputNode, /**< In this mode, the processor has a midi output which
delivers the same midi data that is arriving at its
parent graph. */
midiOutputNode /**< In this mode, the processor has a midi input and
any data sent to it will be passed out of the parent
graph. */
};
//==============================================================================
/** Returns the mode of this processor. */
IODeviceType getType() const noexcept { return type; }
/** Returns the parent graph to which this processor belongs, or nullptr if it
hasn't yet been added to one. */
AudioProcessorGraph* getParentGraph() const noexcept { return graph; }
/** True if this is an audio or midi input. */
bool isInput() const noexcept;
/** True if this is an audio or midi output. */
bool isOutput() const noexcept;
//==============================================================================
AudioGraphIOProcessor (const IODeviceType type);
~AudioGraphIOProcessor();
const String getName() const override;
void fillInPluginDescription (PluginDescription&) const override;
void prepareToPlay (double newSampleRate, int estimatedSamplesPerBlock) override;
void releaseResources() override;
void processBlock (AudioSampleBuffer&, MidiBuffer&) override;
const String getInputChannelName (int channelIndex) const override;
const String getOutputChannelName (int channelIndex) const override;
bool isInputChannelStereoPair (int index) const override;
bool isOutputChannelStereoPair (int index) const override;
bool silenceInProducesSilenceOut() const override;
double getTailLengthSeconds() const override;
bool acceptsMidi() const override;
bool producesMidi() const override;
bool hasEditor() const override;
AudioProcessorEditor* createEditor() override;
int getNumPrograms() override;
int getCurrentProgram() override;
void setCurrentProgram (int) override;
const String getProgramName (int) override;
void changeProgramName (int, const String&) override;
void getStateInformation (juce::MemoryBlock& destData) override;
void setStateInformation (const void* data, int sizeInBytes) override;
/** @internal */
void setParentGraph (AudioProcessorGraph*);
private:
const IODeviceType type;
AudioProcessorGraph* graph;
JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (AudioGraphIOProcessor)
};
//==============================================================================
const String getName() const override;
void prepareToPlay (double, int) override;
void releaseResources() override;
void processBlock (AudioSampleBuffer&, MidiBuffer&) override;
void reset() override;
void setNonRealtime (bool) noexcept override;
void setPlayHead (AudioPlayHead*) override;
const String getInputChannelName (int) const override;
const String getOutputChannelName (int) const override;
bool isInputChannelStereoPair (int) const override;
bool isOutputChannelStereoPair (int) const override;
bool silenceInProducesSilenceOut() const override;
double getTailLengthSeconds() const override;
bool acceptsMidi() const override;
bool producesMidi() const override;
bool hasEditor() const override { return false; }
AudioProcessorEditor* createEditor() override { return nullptr; }
int getNumPrograms() override { return 0; }
int getCurrentProgram() override { return 0; }
void setCurrentProgram (int) override { }
const String getProgramName (int) override { return String(); }
void changeProgramName (int, const String&) override { }
void getStateInformation (juce::MemoryBlock&) override;
void setStateInformation (const void* data, int sizeInBytes) override;
private:
//==============================================================================
ReferenceCountedArray<Node> nodes;
OwnedArray<Connection> connections;
uint32 lastNodeId;
AudioSampleBuffer renderingBuffers;
OwnedArray<MidiBuffer> midiBuffers;
Array<void*> renderingOps;
friend class AudioGraphIOProcessor;
AudioSampleBuffer* currentAudioInputBuffer;
AudioSampleBuffer currentAudioOutputBuffer;
MidiBuffer* currentMidiInputBuffer;
MidiBuffer currentMidiOutputBuffer;
void handleAsyncUpdate() override;
void clearRenderingSequence();
void buildRenderingSequence();
bool isAnInputTo (uint32 possibleInputId, uint32 possibleDestinationId, int recursionCheck) const;
JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (AudioProcessorGraph)
};
#endif // JUCE_AUDIOPROCESSORGRAPH_H_INCLUDED
| {
"pile_set_name": "Github"
} |
// Copyright Aleksey Gurtovoy 2000-2004
//
// Distributed under the Boost Software License, Version 1.0.
// (See accompanying file LICENSE_1_0.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt)
//
// *Preprocessed* version of the main "less_equal.hpp" header
// -- DO NOT modify by hand!
namespace boost { namespace mpl {
template<
typename Tag1
, typename Tag2
>
struct less_equal_impl
: if_c<
( BOOST_MPL_AUX_NESTED_VALUE_WKND(int, Tag1)
> BOOST_MPL_AUX_NESTED_VALUE_WKND(int, Tag2)
)
, aux::cast2nd_impl< less_equal_impl< Tag1,Tag1 >,Tag1, Tag2 >
, aux::cast1st_impl< less_equal_impl< Tag2,Tag2 >,Tag1, Tag2 >
>::type
{
};
/// for Digital Mars C++/compilers with no CTPS/TTP support
template<> struct less_equal_impl< na,na >
{
template< typename U1, typename U2 > struct apply
{
typedef apply type;
BOOST_STATIC_CONSTANT(int, value = 0);
};
};
template< typename Tag > struct less_equal_impl< na,Tag >
{
template< typename U1, typename U2 > struct apply
{
typedef apply type;
BOOST_STATIC_CONSTANT(int, value = 0);
};
};
template< typename Tag > struct less_equal_impl< Tag,na >
{
template< typename U1, typename U2 > struct apply
{
typedef apply type;
BOOST_STATIC_CONSTANT(int, value = 0);
};
};
template< typename T > struct less_equal_tag
{
typedef typename T::tag type;
};
template<
typename BOOST_MPL_AUX_NA_PARAM(N1)
, typename BOOST_MPL_AUX_NA_PARAM(N2)
>
struct less_equal
: less_equal_impl<
typename less_equal_tag<N1>::type
, typename less_equal_tag<N2>::type
>::template apply< N1,N2 >::type
{
BOOST_MPL_AUX_LAMBDA_SUPPORT(2, less_equal, (N1, N2))
};
BOOST_MPL_AUX_NA_SPEC2(2, 2, less_equal)
}}
namespace boost { namespace mpl {
template<>
struct less_equal_impl< integral_c_tag,integral_c_tag >
{
template< typename N1, typename N2 > struct apply
: bool_< ( BOOST_MPL_AUX_VALUE_WKND(N1)::value <= BOOST_MPL_AUX_VALUE_WKND(N2)::value ) >
{
};
};
}}
| {
"pile_set_name": "Github"
} |
// ------------------------------------------------------------------------------
// Copyright (c) Microsoft Corporation. All Rights Reserved. Licensed under the MIT License. See License in the project root for license information.
// ------------------------------------------------------------------------------
package com.microsoft.graph.requests.extensions;
import com.microsoft.graph.http.IRequestBuilder;
import com.microsoft.graph.core.ClientException;
import com.microsoft.graph.concurrency.ICallback;
import com.microsoft.graph.models.extensions.EducationUser;
import com.microsoft.graph.models.extensions.EducationSchool;
import java.util.Arrays;
import java.util.EnumSet;
import com.microsoft.graph.requests.extensions.IEducationSchoolCollectionWithReferencesRequestBuilder;
import com.microsoft.graph.requests.extensions.IEducationSchoolCollectionWithReferencesPage;
import com.microsoft.graph.requests.extensions.EducationSchoolCollectionResponse;
import com.microsoft.graph.models.extensions.EducationSchool;
import com.google.gson.JsonObject;
import com.google.gson.annotations.SerializedName;
import com.google.gson.annotations.Expose;
import com.microsoft.graph.http.BaseCollectionPage;
// **NOTE** This file was generated by a tool and any changes will be overwritten.
/**
* The class for the Education School Collection With References Page.
*/
public class EducationSchoolCollectionWithReferencesPage extends BaseCollectionPage<EducationSchool, IEducationSchoolCollectionWithReferencesRequestBuilder> implements IEducationSchoolCollectionWithReferencesPage {
/**
* A collection page for EducationSchool
*
* @param response the serialized EducationSchoolCollectionResponse from the service
* @param builder the request builder for the next collection page
*/
public EducationSchoolCollectionWithReferencesPage(final EducationSchoolCollectionResponse response, final IEducationSchoolCollectionWithReferencesRequestBuilder builder) {
super(response.value, builder, response.additionalDataManager());
}
}
| {
"pile_set_name": "Github"
} |
= ntpmon(1)
:man version: @NTPSEC_VERSION@
include::../docs/include-man.ad[]
ntpmon - real-time NTP status monitor
include::../docs/includes/ntpmon-body.adoc[]
== EXIT STATUS
Always returns 0.
// end
| {
"pile_set_name": "Github"
} |
import Application from '../components/Application';
import Relay from 'react-relay';
export default Relay.createContainer(Application, {
fragments: {
example: () => Relay.QL`
fragment on Example {
text,
id
}
`
}
}); | {
"pile_set_name": "Github"
} |
# Setting Up Your QMK Environment
Before you can build keymaps, you need to install some software and set up your build environment. This only has to be done once no matter how many keyboards you plan to compile firmware for.
## 1. Download Software
There are a few pieces of software you'll need to get started.
### Text Editor
You'll need a program that can edit and save **plain text** files. If you're on Windows you can make do with Notepad, and on Linux you can use gedit. Both of these are simple but functional text editors. On macOS, be careful with the default TextEdit app: it will not save plain text files unless you explicitly select _Make Plain Text_ from the _Format_ menu.
You can also download and install a dedicated text editor like [Sublime Text](https://www.sublimetext.com/) or [VS Code](https://code.visualstudio.com/). This is probably the best way to go regardless of platform, as these programs are specifically made for editing code.
?> Not sure which text editor to use? Laurence Bradford wrote [a great introduction](https://learntocodewith.me/programming/basics/text-editors/) to the subject.
### QMK Toolbox
QMK Toolbox is an optional graphical program for Windows and macOS that allows you to both program and debug your custom keyboard. You will likely find it invaluable for easily flashing your keyboard and viewing debug messages that it prints.
[Download the latest release here.](https://github.com/qmk/qmk_toolbox/releases/latest)
* For Windows: `qmk_toolbox.exe` (portable) or `qmk_toolbox_install.exe` (installer)
* For macOS: `QMK.Toolbox.app.zip` (portable) or `QMK.Toolbox.pkg` (installer)
### A Unix-like Environment
Linux and macOS come with unix shells you can execute already. You will only need to setup your build environment.
On Windows you will need to install MSYS2 or WSL and use those environments. Instructions for setting up MSYS2 are provided below.
## 2. Prepare Your Build Environment :id=set-up-your-environment
We've tried to make QMK as easy to set up as possible. You only have to prepare your Linux or Unix environment, then let QMK install the rest.
?> If you haven't worked with the Linux/Unix command line before, there are a few basic concepts and commands you should learn. These resources will teach you enough to be able to work with QMK:<br>
[Must Know Linux Commands](https://www.guru99.com/must-know-linux-commands.html)<br>
[Some Basic Unix Commands](https://www.tjhsst.edu/~dhyatt/superap/unixcmd.html)
### Windows
You will need to install MSYS2, Git, and the QMK CLI.
Follow the installation instructions on the [MSYS2 homepage](http://www.msys2.org). Close any open MSYS terminals and open a new MinGW 64-bit terminal. **NOTE: This is *not* the same as the MSYS terminal that opens when installation is completed.**
Then, run the following:
pacman --needed --noconfirm --disable-download-timeout -S git mingw-w64-x86_64-toolchain mingw-w64-x86_64-python3-pip
python3 -m pip install qmk
### macOS
You will need to install Homebrew. Follow the instructions on the [Homebrew homepage](https://brew.sh).
After Homebrew is installed run this command:
brew install qmk/qmk/qmk
### Linux
You will need to install Git and Python. It's very likely that you already have both, but if not, one of the following commands should install them:
* Debian / Ubuntu / Devuan: `sudo apt install git python3 python3-pip`
* Fedora / Red Hat / CentOS: `sudo yum install git python3 python3-pip`
* Arch / Manjaro: `sudo pacman -S git python python-pip python-setuptools libffi`
Install the global CLI to bootstrap your system:
`python3 -m pip install --user qmk` (on Arch-based distros you can also try the `qmk` package from AUR (**note**: it's maintained by a community member): `yay -S qmk`)
### FreeBSD
You will need to install Git and Python. It's possible that you already have both, but if not, run the following commands to install them:
pkg install git python3
Make sure that `$HOME/.local/bin` is added to your `$PATH` so that locally install Python packages are available.
Once installed, you can install QMK CLI:
python3 -m pip install --user qmk
## 3. Run QMK Setup :id=set-up-qmk
After installing QMK you can set it up with this command:
qmk setup
In most situations you will want to answer Yes to all of the prompts.
?>**Note on Debian, Ubuntu and their derivatives**:
It's possible, that you will get an error saying something like: `bash: qmk: command not found`.
This is due to a [bug](https://bugs.debian.org/cgi-bin/bugreport.cgi?bug=839155) Debian introduced with their Bash 4.4 release, which removed `$HOME/.local/bin` from the PATH. This bug was later fixed on Debian and Ubuntu.
Sadly, Ubuntu reitroduced this bug and is [yet to fix it](https://bugs.launchpad.net/ubuntu/+source/bash/+bug/1588562).
Luckily, the fix is easy. Run this as your user: `echo 'PATH="$HOME/.local/bin:$PATH"' >> $HOME/.bashrc && source $HOME/.bashrc`
?>**Note on FreeBSD**:
It is suggested to run `qmk setup` as a non-`root` user to start with, but this will likely identify packages that need to be installed to your
base system using `pkg`. However the installation will probably fail when run as an unprivileged user.
To manually install the base dependencies, run `./util/qmk_install.sh` either as `root`, or with `sudo`.
Once that completes, re-run `qmk setup` to complete the setup and checks.
?> If you already know [how to use GitHub](getting_started_github.md), we recommend that you create your own fork and use `qmk setup <github_username>/qmk_firmware` to clone your personal fork. If you don't know what that means you can safely ignore this message.
## 4. Test Your Build Environment
Now that your QMK build environment is set up, you can build a firmware for your keyboard. Start by trying to build the keyboard's default keymap. You should be able to do that with a command in this format:
qmk compile -kb <keyboard> -km default
For example, to build a firmware for a Clueboard 66% you would use:
qmk compile -kb clueboard/66/rev3 -km default
When it is done you should have a lot of output that ends similar to this:
```
Linking: .build/clueboard_66_rev3_default.elf [OK]
Creating load file for flashing: .build/clueboard_66_rev3_default.hex [OK]
Copying clueboard_66_rev3_default.hex to qmk_firmware folder [OK]
Checking file size of clueboard_66_rev3_default.hex [OK]
* The firmware size is fine - 26356/28672 (2316 bytes free)
```
## 5. Configure Your Build Environment (Optional)
You can configure your build environment to set the defaults and make working with QMK less tedious. Let's do that now!
Most people new to QMK only have 1 keyboard. You can set this keyboard as your default with the `qmk config` command. For example, to set your default keyboard to `clueboard/66/rev4`:
qmk config user.keyboard=clueboard/66/rev4
You can also set your default keymap name. Most people use their GitHub username here, and we recommend that you do too.
qmk config user.keymap=<github_username>
After this you can leave those arguments off and compile your keyboard like this:
qmk compile
# Creating Your Keymap
You are now ready to create your own personal keymap! Move on to [Building Your First Firmware](newbs_building_firmware.md) for that.
| {
"pile_set_name": "Github"
} |
More unit tests for Chaco
=========================
These tests require an installed backend for traitsui such as PyQt or wx.
| {
"pile_set_name": "Github"
} |
/*
* Copyright (c) 2000-2003,2005 Silicon Graphics, Inc.
* All Rights Reserved.
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License as
* published by the Free Software Foundation.
*
* This program is distributed in the hope that it would be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*/
#include "xfs.h"
#include "xfs_fs.h"
#include "xfs_types.h"
#include "xfs_log.h"
#include "xfs_trans.h"
#include "xfs_sb.h"
#include "xfs_ag.h"
#include "xfs_mount.h"
#include "xfs_da_btree.h"
#include "xfs_bmap_btree.h"
#include "xfs_dinode.h"
#include "xfs_inode.h"
#include "xfs_inode_item.h"
#include "xfs_error.h"
#include "xfs_dir2.h"
#include "xfs_dir2_format.h"
#include "xfs_dir2_priv.h"
#include "xfs_trace.h"
/*
* Prototypes for internal functions.
*/
static void xfs_dir2_sf_addname_easy(xfs_da_args_t *args,
xfs_dir2_sf_entry_t *sfep,
xfs_dir2_data_aoff_t offset,
int new_isize);
static void xfs_dir2_sf_addname_hard(xfs_da_args_t *args, int objchange,
int new_isize);
static int xfs_dir2_sf_addname_pick(xfs_da_args_t *args, int objchange,
xfs_dir2_sf_entry_t **sfepp,
xfs_dir2_data_aoff_t *offsetp);
#ifdef DEBUG
static void xfs_dir2_sf_check(xfs_da_args_t *args);
#else
#define xfs_dir2_sf_check(args)
#endif /* DEBUG */
#if XFS_BIG_INUMS
static void xfs_dir2_sf_toino4(xfs_da_args_t *args);
static void xfs_dir2_sf_toino8(xfs_da_args_t *args);
#endif /* XFS_BIG_INUMS */
/*
* Inode numbers in short-form directories can come in two versions,
* either 4 bytes or 8 bytes wide. These helpers deal with the
* two forms transparently by looking at the headers i8count field.
*
* For 64-bit inode number the most significant byte must be zero.
*/
static xfs_ino_t
xfs_dir2_sf_get_ino(
struct xfs_dir2_sf_hdr *hdr,
xfs_dir2_inou_t *from)
{
if (hdr->i8count)
return get_unaligned_be64(&from->i8.i) & 0x00ffffffffffffffULL;
else
return get_unaligned_be32(&from->i4.i);
}
static void
xfs_dir2_sf_put_ino(
struct xfs_dir2_sf_hdr *hdr,
xfs_dir2_inou_t *to,
xfs_ino_t ino)
{
ASSERT((ino & 0xff00000000000000ULL) == 0);
if (hdr->i8count)
put_unaligned_be64(ino, &to->i8.i);
else
put_unaligned_be32(ino, &to->i4.i);
}
xfs_ino_t
xfs_dir2_sf_get_parent_ino(
struct xfs_dir2_sf_hdr *hdr)
{
return xfs_dir2_sf_get_ino(hdr, &hdr->parent);
}
static void
xfs_dir2_sf_put_parent_ino(
struct xfs_dir2_sf_hdr *hdr,
xfs_ino_t ino)
{
xfs_dir2_sf_put_ino(hdr, &hdr->parent, ino);
}
/*
* In short-form directory entries the inode numbers are stored at variable
* offset behind the entry name. The inode numbers may only be accessed
* through the helpers below.
*/
static xfs_dir2_inou_t *
xfs_dir2_sfe_inop(
struct xfs_dir2_sf_entry *sfep)
{
return (xfs_dir2_inou_t *)&sfep->name[sfep->namelen];
}
xfs_ino_t
xfs_dir2_sfe_get_ino(
struct xfs_dir2_sf_hdr *hdr,
struct xfs_dir2_sf_entry *sfep)
{
return xfs_dir2_sf_get_ino(hdr, xfs_dir2_sfe_inop(sfep));
}
static void
xfs_dir2_sfe_put_ino(
struct xfs_dir2_sf_hdr *hdr,
struct xfs_dir2_sf_entry *sfep,
xfs_ino_t ino)
{
xfs_dir2_sf_put_ino(hdr, xfs_dir2_sfe_inop(sfep), ino);
}
/*
* Given a block directory (dp/block), calculate its size as a shortform (sf)
* directory and a header for the sf directory, if it will fit it the
* space currently present in the inode. If it won't fit, the output
* size is too big (but not accurate).
*/
int /* size for sf form */
xfs_dir2_block_sfsize(
xfs_inode_t *dp, /* incore inode pointer */
xfs_dir2_data_hdr_t *hdr, /* block directory data */
xfs_dir2_sf_hdr_t *sfhp) /* output: header for sf form */
{
xfs_dir2_dataptr_t addr; /* data entry address */
xfs_dir2_leaf_entry_t *blp; /* leaf area of the block */
xfs_dir2_block_tail_t *btp; /* tail area of the block */
int count; /* shortform entry count */
xfs_dir2_data_entry_t *dep; /* data entry in the block */
int i; /* block entry index */
int i8count; /* count of big-inode entries */
int isdot; /* entry is "." */
int isdotdot; /* entry is ".." */
xfs_mount_t *mp; /* mount structure pointer */
int namelen; /* total name bytes */
xfs_ino_t parent = 0; /* parent inode number */
int size=0; /* total computed size */
mp = dp->i_mount;
count = i8count = namelen = 0;
btp = xfs_dir2_block_tail_p(mp, hdr);
blp = xfs_dir2_block_leaf_p(btp);
/*
* Iterate over the block's data entries by using the leaf pointers.
*/
for (i = 0; i < be32_to_cpu(btp->count); i++) {
if ((addr = be32_to_cpu(blp[i].address)) == XFS_DIR2_NULL_DATAPTR)
continue;
/*
* Calculate the pointer to the entry at hand.
*/
dep = (xfs_dir2_data_entry_t *)
((char *)hdr + xfs_dir2_dataptr_to_off(mp, addr));
/*
* Detect . and .., so we can special-case them.
* . is not included in sf directories.
* .. is included by just the parent inode number.
*/
isdot = dep->namelen == 1 && dep->name[0] == '.';
isdotdot =
dep->namelen == 2 &&
dep->name[0] == '.' && dep->name[1] == '.';
#if XFS_BIG_INUMS
if (!isdot)
i8count += be64_to_cpu(dep->inumber) > XFS_DIR2_MAX_SHORT_INUM;
#endif
if (!isdot && !isdotdot) {
count++;
namelen += dep->namelen;
} else if (isdotdot)
parent = be64_to_cpu(dep->inumber);
/*
* Calculate the new size, see if we should give up yet.
*/
size = xfs_dir2_sf_hdr_size(i8count) + /* header */
count + /* namelen */
count * (uint)sizeof(xfs_dir2_sf_off_t) + /* offset */
namelen + /* name */
(i8count ? /* inumber */
(uint)sizeof(xfs_dir2_ino8_t) * count :
(uint)sizeof(xfs_dir2_ino4_t) * count);
if (size > XFS_IFORK_DSIZE(dp))
return size; /* size value is a failure */
}
/*
* Create the output header, if it worked.
*/
sfhp->count = count;
sfhp->i8count = i8count;
xfs_dir2_sf_put_parent_ino(sfhp, parent);
return size;
}
/*
* Convert a block format directory to shortform.
* Caller has already checked that it will fit, and built us a header.
*/
int /* error */
xfs_dir2_block_to_sf(
xfs_da_args_t *args, /* operation arguments */
struct xfs_buf *bp,
int size, /* shortform directory size */
xfs_dir2_sf_hdr_t *sfhp) /* shortform directory hdr */
{
xfs_dir2_data_hdr_t *hdr; /* block header */
xfs_dir2_block_tail_t *btp; /* block tail pointer */
xfs_dir2_data_entry_t *dep; /* data entry pointer */
xfs_inode_t *dp; /* incore directory inode */
xfs_dir2_data_unused_t *dup; /* unused data pointer */
char *endptr; /* end of data entries */
int error; /* error return value */
int logflags; /* inode logging flags */
xfs_mount_t *mp; /* filesystem mount point */
char *ptr; /* current data pointer */
xfs_dir2_sf_entry_t *sfep; /* shortform entry */
xfs_dir2_sf_hdr_t *sfp; /* shortform directory header */
trace_xfs_dir2_block_to_sf(args);
dp = args->dp;
mp = dp->i_mount;
/*
* Make a copy of the block data, so we can shrink the inode
* and add local data.
*/
hdr = kmem_alloc(mp->m_dirblksize, KM_SLEEP);
memcpy(hdr, bp->b_addr, mp->m_dirblksize);
logflags = XFS_ILOG_CORE;
if ((error = xfs_dir2_shrink_inode(args, mp->m_dirdatablk, bp))) {
ASSERT(error != ENOSPC);
goto out;
}
/*
* The buffer is now unconditionally gone, whether
* xfs_dir2_shrink_inode worked or not.
*
* Convert the inode to local format.
*/
dp->i_df.if_flags &= ~XFS_IFEXTENTS;
dp->i_df.if_flags |= XFS_IFINLINE;
dp->i_d.di_format = XFS_DINODE_FMT_LOCAL;
ASSERT(dp->i_df.if_bytes == 0);
xfs_idata_realloc(dp, size, XFS_DATA_FORK);
logflags |= XFS_ILOG_DDATA;
/*
* Copy the header into the newly allocate local space.
*/
sfp = (xfs_dir2_sf_hdr_t *)dp->i_df.if_u1.if_data;
memcpy(sfp, sfhp, xfs_dir2_sf_hdr_size(sfhp->i8count));
dp->i_d.di_size = size;
/*
* Set up to loop over the block's entries.
*/
btp = xfs_dir2_block_tail_p(mp, hdr);
ptr = (char *)xfs_dir3_data_entry_p(hdr);
endptr = (char *)xfs_dir2_block_leaf_p(btp);
sfep = xfs_dir2_sf_firstentry(sfp);
/*
* Loop over the active and unused entries.
* Stop when we reach the leaf/tail portion of the block.
*/
while (ptr < endptr) {
/*
* If it's unused, just skip over it.
*/
dup = (xfs_dir2_data_unused_t *)ptr;
if (be16_to_cpu(dup->freetag) == XFS_DIR2_DATA_FREE_TAG) {
ptr += be16_to_cpu(dup->length);
continue;
}
dep = (xfs_dir2_data_entry_t *)ptr;
/*
* Skip .
*/
if (dep->namelen == 1 && dep->name[0] == '.')
ASSERT(be64_to_cpu(dep->inumber) == dp->i_ino);
/*
* Skip .., but make sure the inode number is right.
*/
else if (dep->namelen == 2 &&
dep->name[0] == '.' && dep->name[1] == '.')
ASSERT(be64_to_cpu(dep->inumber) ==
xfs_dir2_sf_get_parent_ino(sfp));
/*
* Normal entry, copy it into shortform.
*/
else {
sfep->namelen = dep->namelen;
xfs_dir2_sf_put_offset(sfep,
(xfs_dir2_data_aoff_t)
((char *)dep - (char *)hdr));
memcpy(sfep->name, dep->name, dep->namelen);
xfs_dir2_sfe_put_ino(sfp, sfep,
be64_to_cpu(dep->inumber));
sfep = xfs_dir2_sf_nextentry(sfp, sfep);
}
ptr += xfs_dir2_data_entsize(dep->namelen);
}
ASSERT((char *)sfep - (char *)sfp == size);
xfs_dir2_sf_check(args);
out:
xfs_trans_log_inode(args->trans, dp, logflags);
kmem_free(hdr);
return error;
}
/*
* Add a name to a shortform directory.
* There are two algorithms, "easy" and "hard" which we decide on
* before changing anything.
* Convert to block form if necessary, if the new entry won't fit.
*/
int /* error */
xfs_dir2_sf_addname(
xfs_da_args_t *args) /* operation arguments */
{
int add_entsize; /* size of the new entry */
xfs_inode_t *dp; /* incore directory inode */
int error; /* error return value */
int incr_isize; /* total change in size */
int new_isize; /* di_size after adding name */
int objchange; /* changing to 8-byte inodes */
xfs_dir2_data_aoff_t offset = 0; /* offset for new entry */
int old_isize; /* di_size before adding name */
int pick; /* which algorithm to use */
xfs_dir2_sf_hdr_t *sfp; /* shortform structure */
xfs_dir2_sf_entry_t *sfep = NULL; /* shortform entry */
trace_xfs_dir2_sf_addname(args);
ASSERT(xfs_dir2_sf_lookup(args) == ENOENT);
dp = args->dp;
ASSERT(dp->i_df.if_flags & XFS_IFINLINE);
/*
* Make sure the shortform value has some of its header.
*/
if (dp->i_d.di_size < offsetof(xfs_dir2_sf_hdr_t, parent)) {
ASSERT(XFS_FORCED_SHUTDOWN(dp->i_mount));
return XFS_ERROR(EIO);
}
ASSERT(dp->i_df.if_bytes == dp->i_d.di_size);
ASSERT(dp->i_df.if_u1.if_data != NULL);
sfp = (xfs_dir2_sf_hdr_t *)dp->i_df.if_u1.if_data;
ASSERT(dp->i_d.di_size >= xfs_dir2_sf_hdr_size(sfp->i8count));
/*
* Compute entry (and change in) size.
*/
add_entsize = xfs_dir2_sf_entsize(sfp, args->namelen);
incr_isize = add_entsize;
objchange = 0;
#if XFS_BIG_INUMS
/*
* Do we have to change to 8 byte inodes?
*/
if (args->inumber > XFS_DIR2_MAX_SHORT_INUM && sfp->i8count == 0) {
/*
* Yes, adjust the entry size and the total size.
*/
add_entsize +=
(uint)sizeof(xfs_dir2_ino8_t) -
(uint)sizeof(xfs_dir2_ino4_t);
incr_isize +=
(sfp->count + 2) *
((uint)sizeof(xfs_dir2_ino8_t) -
(uint)sizeof(xfs_dir2_ino4_t));
objchange = 1;
}
#endif
old_isize = (int)dp->i_d.di_size;
new_isize = old_isize + incr_isize;
/*
* Won't fit as shortform any more (due to size),
* or the pick routine says it won't (due to offset values).
*/
if (new_isize > XFS_IFORK_DSIZE(dp) ||
(pick =
xfs_dir2_sf_addname_pick(args, objchange, &sfep, &offset)) == 0) {
/*
* Just checking or no space reservation, it doesn't fit.
*/
if ((args->op_flags & XFS_DA_OP_JUSTCHECK) || args->total == 0)
return XFS_ERROR(ENOSPC);
/*
* Convert to block form then add the name.
*/
error = xfs_dir2_sf_to_block(args);
if (error)
return error;
return xfs_dir2_block_addname(args);
}
/*
* Just checking, it fits.
*/
if (args->op_flags & XFS_DA_OP_JUSTCHECK)
return 0;
/*
* Do it the easy way - just add it at the end.
*/
if (pick == 1)
xfs_dir2_sf_addname_easy(args, sfep, offset, new_isize);
/*
* Do it the hard way - look for a place to insert the new entry.
* Convert to 8 byte inode numbers first if necessary.
*/
else {
ASSERT(pick == 2);
#if XFS_BIG_INUMS
if (objchange)
xfs_dir2_sf_toino8(args);
#endif
xfs_dir2_sf_addname_hard(args, objchange, new_isize);
}
xfs_trans_log_inode(args->trans, dp, XFS_ILOG_CORE | XFS_ILOG_DDATA);
return 0;
}
/*
* Add the new entry the "easy" way.
* This is copying the old directory and adding the new entry at the end.
* Since it's sorted by "offset" we need room after the last offset
* that's already there, and then room to convert to a block directory.
* This is already checked by the pick routine.
*/
static void
xfs_dir2_sf_addname_easy(
xfs_da_args_t *args, /* operation arguments */
xfs_dir2_sf_entry_t *sfep, /* pointer to new entry */
xfs_dir2_data_aoff_t offset, /* offset to use for new ent */
int new_isize) /* new directory size */
{
int byteoff; /* byte offset in sf dir */
xfs_inode_t *dp; /* incore directory inode */
xfs_dir2_sf_hdr_t *sfp; /* shortform structure */
dp = args->dp;
sfp = (xfs_dir2_sf_hdr_t *)dp->i_df.if_u1.if_data;
byteoff = (int)((char *)sfep - (char *)sfp);
/*
* Grow the in-inode space.
*/
xfs_idata_realloc(dp, xfs_dir2_sf_entsize(sfp, args->namelen),
XFS_DATA_FORK);
/*
* Need to set up again due to realloc of the inode data.
*/
sfp = (xfs_dir2_sf_hdr_t *)dp->i_df.if_u1.if_data;
sfep = (xfs_dir2_sf_entry_t *)((char *)sfp + byteoff);
/*
* Fill in the new entry.
*/
sfep->namelen = args->namelen;
xfs_dir2_sf_put_offset(sfep, offset);
memcpy(sfep->name, args->name, sfep->namelen);
xfs_dir2_sfe_put_ino(sfp, sfep, args->inumber);
/*
* Update the header and inode.
*/
sfp->count++;
#if XFS_BIG_INUMS
if (args->inumber > XFS_DIR2_MAX_SHORT_INUM)
sfp->i8count++;
#endif
dp->i_d.di_size = new_isize;
xfs_dir2_sf_check(args);
}
/*
* Add the new entry the "hard" way.
* The caller has already converted to 8 byte inode numbers if necessary,
* in which case we need to leave the i8count at 1.
* Find a hole that the new entry will fit into, and copy
* the first part of the entries, the new entry, and the last part of
* the entries.
*/
/* ARGSUSED */
static void
xfs_dir2_sf_addname_hard(
xfs_da_args_t *args, /* operation arguments */
int objchange, /* changing inode number size */
int new_isize) /* new directory size */
{
int add_datasize; /* data size need for new ent */
char *buf; /* buffer for old */
xfs_inode_t *dp; /* incore directory inode */
int eof; /* reached end of old dir */
int nbytes; /* temp for byte copies */
xfs_dir2_data_aoff_t new_offset; /* next offset value */
xfs_dir2_data_aoff_t offset; /* current offset value */
int old_isize; /* previous di_size */
xfs_dir2_sf_entry_t *oldsfep; /* entry in original dir */
xfs_dir2_sf_hdr_t *oldsfp; /* original shortform dir */
xfs_dir2_sf_entry_t *sfep; /* entry in new dir */
xfs_dir2_sf_hdr_t *sfp; /* new shortform dir */
/*
* Copy the old directory to the stack buffer.
*/
dp = args->dp;
sfp = (xfs_dir2_sf_hdr_t *)dp->i_df.if_u1.if_data;
old_isize = (int)dp->i_d.di_size;
buf = kmem_alloc(old_isize, KM_SLEEP);
oldsfp = (xfs_dir2_sf_hdr_t *)buf;
memcpy(oldsfp, sfp, old_isize);
/*
* Loop over the old directory finding the place we're going
* to insert the new entry.
* If it's going to end up at the end then oldsfep will point there.
*/
for (offset = XFS_DIR3_DATA_FIRST_OFFSET(dp->i_mount),
oldsfep = xfs_dir2_sf_firstentry(oldsfp),
add_datasize = xfs_dir2_data_entsize(args->namelen),
eof = (char *)oldsfep == &buf[old_isize];
!eof;
offset = new_offset + xfs_dir2_data_entsize(oldsfep->namelen),
oldsfep = xfs_dir2_sf_nextentry(oldsfp, oldsfep),
eof = (char *)oldsfep == &buf[old_isize]) {
new_offset = xfs_dir2_sf_get_offset(oldsfep);
if (offset + add_datasize <= new_offset)
break;
}
/*
* Get rid of the old directory, then allocate space for
* the new one. We do this so xfs_idata_realloc won't copy
* the data.
*/
xfs_idata_realloc(dp, -old_isize, XFS_DATA_FORK);
xfs_idata_realloc(dp, new_isize, XFS_DATA_FORK);
/*
* Reset the pointer since the buffer was reallocated.
*/
sfp = (xfs_dir2_sf_hdr_t *)dp->i_df.if_u1.if_data;
/*
* Copy the first part of the directory, including the header.
*/
nbytes = (int)((char *)oldsfep - (char *)oldsfp);
memcpy(sfp, oldsfp, nbytes);
sfep = (xfs_dir2_sf_entry_t *)((char *)sfp + nbytes);
/*
* Fill in the new entry, and update the header counts.
*/
sfep->namelen = args->namelen;
xfs_dir2_sf_put_offset(sfep, offset);
memcpy(sfep->name, args->name, sfep->namelen);
xfs_dir2_sfe_put_ino(sfp, sfep, args->inumber);
sfp->count++;
#if XFS_BIG_INUMS
if (args->inumber > XFS_DIR2_MAX_SHORT_INUM && !objchange)
sfp->i8count++;
#endif
/*
* If there's more left to copy, do that.
*/
if (!eof) {
sfep = xfs_dir2_sf_nextentry(sfp, sfep);
memcpy(sfep, oldsfep, old_isize - nbytes);
}
kmem_free(buf);
dp->i_d.di_size = new_isize;
xfs_dir2_sf_check(args);
}
/*
* Decide if the new entry will fit at all.
* If it will fit, pick between adding the new entry to the end (easy)
* or somewhere else (hard).
* Return 0 (won't fit), 1 (easy), 2 (hard).
*/
/*ARGSUSED*/
static int /* pick result */
xfs_dir2_sf_addname_pick(
xfs_da_args_t *args, /* operation arguments */
int objchange, /* inode # size changes */
xfs_dir2_sf_entry_t **sfepp, /* out(1): new entry ptr */
xfs_dir2_data_aoff_t *offsetp) /* out(1): new offset */
{
xfs_inode_t *dp; /* incore directory inode */
int holefit; /* found hole it will fit in */
int i; /* entry number */
xfs_mount_t *mp; /* filesystem mount point */
xfs_dir2_data_aoff_t offset; /* data block offset */
xfs_dir2_sf_entry_t *sfep; /* shortform entry */
xfs_dir2_sf_hdr_t *sfp; /* shortform structure */
int size; /* entry's data size */
int used; /* data bytes used */
dp = args->dp;
mp = dp->i_mount;
sfp = (xfs_dir2_sf_hdr_t *)dp->i_df.if_u1.if_data;
size = xfs_dir2_data_entsize(args->namelen);
offset = XFS_DIR3_DATA_FIRST_OFFSET(mp);
sfep = xfs_dir2_sf_firstentry(sfp);
holefit = 0;
/*
* Loop over sf entries.
* Keep track of data offset and whether we've seen a place
* to insert the new entry.
*/
for (i = 0; i < sfp->count; i++) {
if (!holefit)
holefit = offset + size <= xfs_dir2_sf_get_offset(sfep);
offset = xfs_dir2_sf_get_offset(sfep) +
xfs_dir2_data_entsize(sfep->namelen);
sfep = xfs_dir2_sf_nextentry(sfp, sfep);
}
/*
* Calculate data bytes used excluding the new entry, if this
* was a data block (block form directory).
*/
used = offset +
(sfp->count + 3) * (uint)sizeof(xfs_dir2_leaf_entry_t) +
(uint)sizeof(xfs_dir2_block_tail_t);
/*
* If it won't fit in a block form then we can't insert it,
* we'll go back, convert to block, then try the insert and convert
* to leaf.
*/
if (used + (holefit ? 0 : size) > mp->m_dirblksize)
return 0;
/*
* If changing the inode number size, do it the hard way.
*/
#if XFS_BIG_INUMS
if (objchange) {
return 2;
}
#else
ASSERT(objchange == 0);
#endif
/*
* If it won't fit at the end then do it the hard way (use the hole).
*/
if (used + size > mp->m_dirblksize)
return 2;
/*
* Do it the easy way.
*/
*sfepp = sfep;
*offsetp = offset;
return 1;
}
#ifdef DEBUG
/*
* Check consistency of shortform directory, assert if bad.
*/
static void
xfs_dir2_sf_check(
xfs_da_args_t *args) /* operation arguments */
{
xfs_inode_t *dp; /* incore directory inode */
int i; /* entry number */
int i8count; /* number of big inode#s */
xfs_ino_t ino; /* entry inode number */
int offset; /* data offset */
xfs_dir2_sf_entry_t *sfep; /* shortform dir entry */
xfs_dir2_sf_hdr_t *sfp; /* shortform structure */
dp = args->dp;
sfp = (xfs_dir2_sf_hdr_t *)dp->i_df.if_u1.if_data;
offset = XFS_DIR3_DATA_FIRST_OFFSET(dp->i_mount);
ino = xfs_dir2_sf_get_parent_ino(sfp);
i8count = ino > XFS_DIR2_MAX_SHORT_INUM;
for (i = 0, sfep = xfs_dir2_sf_firstentry(sfp);
i < sfp->count;
i++, sfep = xfs_dir2_sf_nextentry(sfp, sfep)) {
ASSERT(xfs_dir2_sf_get_offset(sfep) >= offset);
ino = xfs_dir2_sfe_get_ino(sfp, sfep);
i8count += ino > XFS_DIR2_MAX_SHORT_INUM;
offset =
xfs_dir2_sf_get_offset(sfep) +
xfs_dir2_data_entsize(sfep->namelen);
}
ASSERT(i8count == sfp->i8count);
ASSERT(XFS_BIG_INUMS || i8count == 0);
ASSERT((char *)sfep - (char *)sfp == dp->i_d.di_size);
ASSERT(offset +
(sfp->count + 2) * (uint)sizeof(xfs_dir2_leaf_entry_t) +
(uint)sizeof(xfs_dir2_block_tail_t) <=
dp->i_mount->m_dirblksize);
}
#endif /* DEBUG */
/*
* Create a new (shortform) directory.
*/
int /* error, always 0 */
xfs_dir2_sf_create(
xfs_da_args_t *args, /* operation arguments */
xfs_ino_t pino) /* parent inode number */
{
xfs_inode_t *dp; /* incore directory inode */
int i8count; /* parent inode is an 8-byte number */
xfs_dir2_sf_hdr_t *sfp; /* shortform structure */
int size; /* directory size */
trace_xfs_dir2_sf_create(args);
dp = args->dp;
ASSERT(dp != NULL);
ASSERT(dp->i_d.di_size == 0);
/*
* If it's currently a zero-length extent file,
* convert it to local format.
*/
if (dp->i_d.di_format == XFS_DINODE_FMT_EXTENTS) {
dp->i_df.if_flags &= ~XFS_IFEXTENTS; /* just in case */
dp->i_d.di_format = XFS_DINODE_FMT_LOCAL;
xfs_trans_log_inode(args->trans, dp, XFS_ILOG_CORE);
dp->i_df.if_flags |= XFS_IFINLINE;
}
ASSERT(dp->i_df.if_flags & XFS_IFINLINE);
ASSERT(dp->i_df.if_bytes == 0);
i8count = pino > XFS_DIR2_MAX_SHORT_INUM;
size = xfs_dir2_sf_hdr_size(i8count);
/*
* Make a buffer for the data.
*/
xfs_idata_realloc(dp, size, XFS_DATA_FORK);
/*
* Fill in the header,
*/
sfp = (xfs_dir2_sf_hdr_t *)dp->i_df.if_u1.if_data;
sfp->i8count = i8count;
/*
* Now can put in the inode number, since i8count is set.
*/
xfs_dir2_sf_put_parent_ino(sfp, pino);
sfp->count = 0;
dp->i_d.di_size = size;
xfs_dir2_sf_check(args);
xfs_trans_log_inode(args->trans, dp, XFS_ILOG_CORE | XFS_ILOG_DDATA);
return 0;
}
int /* error */
xfs_dir2_sf_getdents(
xfs_inode_t *dp, /* incore directory inode */
struct dir_context *ctx)
{
int i; /* shortform entry number */
xfs_mount_t *mp; /* filesystem mount point */
xfs_dir2_dataptr_t off; /* current entry's offset */
xfs_dir2_sf_entry_t *sfep; /* shortform directory entry */
xfs_dir2_sf_hdr_t *sfp; /* shortform structure */
xfs_dir2_dataptr_t dot_offset;
xfs_dir2_dataptr_t dotdot_offset;
xfs_ino_t ino;
mp = dp->i_mount;
ASSERT(dp->i_df.if_flags & XFS_IFINLINE);
/*
* Give up if the directory is way too short.
*/
if (dp->i_d.di_size < offsetof(xfs_dir2_sf_hdr_t, parent)) {
ASSERT(XFS_FORCED_SHUTDOWN(mp));
return XFS_ERROR(EIO);
}
ASSERT(dp->i_df.if_bytes == dp->i_d.di_size);
ASSERT(dp->i_df.if_u1.if_data != NULL);
sfp = (xfs_dir2_sf_hdr_t *)dp->i_df.if_u1.if_data;
ASSERT(dp->i_d.di_size >= xfs_dir2_sf_hdr_size(sfp->i8count));
/*
* If the block number in the offset is out of range, we're done.
*/
if (xfs_dir2_dataptr_to_db(mp, ctx->pos) > mp->m_dirdatablk)
return 0;
/*
* Precalculate offsets for . and .. as we will always need them.
*
* XXX(hch): the second argument is sometimes 0 and sometimes
* mp->m_dirdatablk.
*/
dot_offset = xfs_dir2_db_off_to_dataptr(mp, mp->m_dirdatablk,
XFS_DIR3_DATA_DOT_OFFSET(mp));
dotdot_offset = xfs_dir2_db_off_to_dataptr(mp, mp->m_dirdatablk,
XFS_DIR3_DATA_DOTDOT_OFFSET(mp));
/*
* Put . entry unless we're starting past it.
*/
if (ctx->pos <= dot_offset) {
ctx->pos = dot_offset & 0x7fffffff;
if (!dir_emit(ctx, ".", 1, dp->i_ino, DT_DIR))
return 0;
}
/*
* Put .. entry unless we're starting past it.
*/
if (ctx->pos <= dotdot_offset) {
ino = xfs_dir2_sf_get_parent_ino(sfp);
ctx->pos = dotdot_offset & 0x7fffffff;
if (!dir_emit(ctx, "..", 2, ino, DT_DIR))
return 0;
}
/*
* Loop while there are more entries and put'ing works.
*/
sfep = xfs_dir2_sf_firstentry(sfp);
for (i = 0; i < sfp->count; i++) {
off = xfs_dir2_db_off_to_dataptr(mp, mp->m_dirdatablk,
xfs_dir2_sf_get_offset(sfep));
if (ctx->pos > off) {
sfep = xfs_dir2_sf_nextentry(sfp, sfep);
continue;
}
ino = xfs_dir2_sfe_get_ino(sfp, sfep);
ctx->pos = off & 0x7fffffff;
if (!dir_emit(ctx, (char *)sfep->name, sfep->namelen,
ino, DT_UNKNOWN))
return 0;
sfep = xfs_dir2_sf_nextentry(sfp, sfep);
}
ctx->pos = xfs_dir2_db_off_to_dataptr(mp, mp->m_dirdatablk + 1, 0) &
0x7fffffff;
return 0;
}
/*
* Lookup an entry in a shortform directory.
* Returns EEXIST if found, ENOENT if not found.
*/
int /* error */
xfs_dir2_sf_lookup(
xfs_da_args_t *args) /* operation arguments */
{
xfs_inode_t *dp; /* incore directory inode */
int i; /* entry index */
int error;
xfs_dir2_sf_entry_t *sfep; /* shortform directory entry */
xfs_dir2_sf_hdr_t *sfp; /* shortform structure */
enum xfs_dacmp cmp; /* comparison result */
xfs_dir2_sf_entry_t *ci_sfep; /* case-insens. entry */
trace_xfs_dir2_sf_lookup(args);
xfs_dir2_sf_check(args);
dp = args->dp;
ASSERT(dp->i_df.if_flags & XFS_IFINLINE);
/*
* Bail out if the directory is way too short.
*/
if (dp->i_d.di_size < offsetof(xfs_dir2_sf_hdr_t, parent)) {
ASSERT(XFS_FORCED_SHUTDOWN(dp->i_mount));
return XFS_ERROR(EIO);
}
ASSERT(dp->i_df.if_bytes == dp->i_d.di_size);
ASSERT(dp->i_df.if_u1.if_data != NULL);
sfp = (xfs_dir2_sf_hdr_t *)dp->i_df.if_u1.if_data;
ASSERT(dp->i_d.di_size >= xfs_dir2_sf_hdr_size(sfp->i8count));
/*
* Special case for .
*/
if (args->namelen == 1 && args->name[0] == '.') {
args->inumber = dp->i_ino;
args->cmpresult = XFS_CMP_EXACT;
return XFS_ERROR(EEXIST);
}
/*
* Special case for ..
*/
if (args->namelen == 2 &&
args->name[0] == '.' && args->name[1] == '.') {
args->inumber = xfs_dir2_sf_get_parent_ino(sfp);
args->cmpresult = XFS_CMP_EXACT;
return XFS_ERROR(EEXIST);
}
/*
* Loop over all the entries trying to match ours.
*/
ci_sfep = NULL;
for (i = 0, sfep = xfs_dir2_sf_firstentry(sfp); i < sfp->count;
i++, sfep = xfs_dir2_sf_nextentry(sfp, sfep)) {
/*
* Compare name and if it's an exact match, return the inode
* number. If it's the first case-insensitive match, store the
* inode number and continue looking for an exact match.
*/
cmp = dp->i_mount->m_dirnameops->compname(args, sfep->name,
sfep->namelen);
if (cmp != XFS_CMP_DIFFERENT && cmp != args->cmpresult) {
args->cmpresult = cmp;
args->inumber = xfs_dir2_sfe_get_ino(sfp, sfep);
if (cmp == XFS_CMP_EXACT)
return XFS_ERROR(EEXIST);
ci_sfep = sfep;
}
}
ASSERT(args->op_flags & XFS_DA_OP_OKNOENT);
/*
* Here, we can only be doing a lookup (not a rename or replace).
* If a case-insensitive match was not found, return ENOENT.
*/
if (!ci_sfep)
return XFS_ERROR(ENOENT);
/* otherwise process the CI match as required by the caller */
error = xfs_dir_cilookup_result(args, ci_sfep->name, ci_sfep->namelen);
return XFS_ERROR(error);
}
/*
* Remove an entry from a shortform directory.
*/
int /* error */
xfs_dir2_sf_removename(
xfs_da_args_t *args)
{
int byteoff; /* offset of removed entry */
xfs_inode_t *dp; /* incore directory inode */
int entsize; /* this entry's size */
int i; /* shortform entry index */
int newsize; /* new inode size */
int oldsize; /* old inode size */
xfs_dir2_sf_entry_t *sfep; /* shortform directory entry */
xfs_dir2_sf_hdr_t *sfp; /* shortform structure */
trace_xfs_dir2_sf_removename(args);
dp = args->dp;
ASSERT(dp->i_df.if_flags & XFS_IFINLINE);
oldsize = (int)dp->i_d.di_size;
/*
* Bail out if the directory is way too short.
*/
if (oldsize < offsetof(xfs_dir2_sf_hdr_t, parent)) {
ASSERT(XFS_FORCED_SHUTDOWN(dp->i_mount));
return XFS_ERROR(EIO);
}
ASSERT(dp->i_df.if_bytes == oldsize);
ASSERT(dp->i_df.if_u1.if_data != NULL);
sfp = (xfs_dir2_sf_hdr_t *)dp->i_df.if_u1.if_data;
ASSERT(oldsize >= xfs_dir2_sf_hdr_size(sfp->i8count));
/*
* Loop over the old directory entries.
* Find the one we're deleting.
*/
for (i = 0, sfep = xfs_dir2_sf_firstentry(sfp); i < sfp->count;
i++, sfep = xfs_dir2_sf_nextentry(sfp, sfep)) {
if (xfs_da_compname(args, sfep->name, sfep->namelen) ==
XFS_CMP_EXACT) {
ASSERT(xfs_dir2_sfe_get_ino(sfp, sfep) ==
args->inumber);
break;
}
}
/*
* Didn't find it.
*/
if (i == sfp->count)
return XFS_ERROR(ENOENT);
/*
* Calculate sizes.
*/
byteoff = (int)((char *)sfep - (char *)sfp);
entsize = xfs_dir2_sf_entsize(sfp, args->namelen);
newsize = oldsize - entsize;
/*
* Copy the part if any after the removed entry, sliding it down.
*/
if (byteoff + entsize < oldsize)
memmove((char *)sfp + byteoff, (char *)sfp + byteoff + entsize,
oldsize - (byteoff + entsize));
/*
* Fix up the header and file size.
*/
sfp->count--;
dp->i_d.di_size = newsize;
/*
* Reallocate, making it smaller.
*/
xfs_idata_realloc(dp, newsize - oldsize, XFS_DATA_FORK);
sfp = (xfs_dir2_sf_hdr_t *)dp->i_df.if_u1.if_data;
#if XFS_BIG_INUMS
/*
* Are we changing inode number size?
*/
if (args->inumber > XFS_DIR2_MAX_SHORT_INUM) {
if (sfp->i8count == 1)
xfs_dir2_sf_toino4(args);
else
sfp->i8count--;
}
#endif
xfs_dir2_sf_check(args);
xfs_trans_log_inode(args->trans, dp, XFS_ILOG_CORE | XFS_ILOG_DDATA);
return 0;
}
/*
* Replace the inode number of an entry in a shortform directory.
*/
int /* error */
xfs_dir2_sf_replace(
xfs_da_args_t *args) /* operation arguments */
{
xfs_inode_t *dp; /* incore directory inode */
int i; /* entry index */
#if XFS_BIG_INUMS || defined(DEBUG)
xfs_ino_t ino=0; /* entry old inode number */
#endif
#if XFS_BIG_INUMS
int i8elevated; /* sf_toino8 set i8count=1 */
#endif
xfs_dir2_sf_entry_t *sfep; /* shortform directory entry */
xfs_dir2_sf_hdr_t *sfp; /* shortform structure */
trace_xfs_dir2_sf_replace(args);
dp = args->dp;
ASSERT(dp->i_df.if_flags & XFS_IFINLINE);
/*
* Bail out if the shortform directory is way too small.
*/
if (dp->i_d.di_size < offsetof(xfs_dir2_sf_hdr_t, parent)) {
ASSERT(XFS_FORCED_SHUTDOWN(dp->i_mount));
return XFS_ERROR(EIO);
}
ASSERT(dp->i_df.if_bytes == dp->i_d.di_size);
ASSERT(dp->i_df.if_u1.if_data != NULL);
sfp = (xfs_dir2_sf_hdr_t *)dp->i_df.if_u1.if_data;
ASSERT(dp->i_d.di_size >= xfs_dir2_sf_hdr_size(sfp->i8count));
#if XFS_BIG_INUMS
/*
* New inode number is large, and need to convert to 8-byte inodes.
*/
if (args->inumber > XFS_DIR2_MAX_SHORT_INUM && sfp->i8count == 0) {
int error; /* error return value */
int newsize; /* new inode size */
newsize =
dp->i_df.if_bytes +
(sfp->count + 1) *
((uint)sizeof(xfs_dir2_ino8_t) -
(uint)sizeof(xfs_dir2_ino4_t));
/*
* Won't fit as shortform, convert to block then do replace.
*/
if (newsize > XFS_IFORK_DSIZE(dp)) {
error = xfs_dir2_sf_to_block(args);
if (error) {
return error;
}
return xfs_dir2_block_replace(args);
}
/*
* Still fits, convert to 8-byte now.
*/
xfs_dir2_sf_toino8(args);
i8elevated = 1;
sfp = (xfs_dir2_sf_hdr_t *)dp->i_df.if_u1.if_data;
} else
i8elevated = 0;
#endif
ASSERT(args->namelen != 1 || args->name[0] != '.');
/*
* Replace ..'s entry.
*/
if (args->namelen == 2 &&
args->name[0] == '.' && args->name[1] == '.') {
#if XFS_BIG_INUMS || defined(DEBUG)
ino = xfs_dir2_sf_get_parent_ino(sfp);
ASSERT(args->inumber != ino);
#endif
xfs_dir2_sf_put_parent_ino(sfp, args->inumber);
}
/*
* Normal entry, look for the name.
*/
else {
for (i = 0, sfep = xfs_dir2_sf_firstentry(sfp);
i < sfp->count;
i++, sfep = xfs_dir2_sf_nextentry(sfp, sfep)) {
if (xfs_da_compname(args, sfep->name, sfep->namelen) ==
XFS_CMP_EXACT) {
#if XFS_BIG_INUMS || defined(DEBUG)
ino = xfs_dir2_sfe_get_ino(sfp, sfep);
ASSERT(args->inumber != ino);
#endif
xfs_dir2_sfe_put_ino(sfp, sfep, args->inumber);
break;
}
}
/*
* Didn't find it.
*/
if (i == sfp->count) {
ASSERT(args->op_flags & XFS_DA_OP_OKNOENT);
#if XFS_BIG_INUMS
if (i8elevated)
xfs_dir2_sf_toino4(args);
#endif
return XFS_ERROR(ENOENT);
}
}
#if XFS_BIG_INUMS
/*
* See if the old number was large, the new number is small.
*/
if (ino > XFS_DIR2_MAX_SHORT_INUM &&
args->inumber <= XFS_DIR2_MAX_SHORT_INUM) {
/*
* And the old count was one, so need to convert to small.
*/
if (sfp->i8count == 1)
xfs_dir2_sf_toino4(args);
else
sfp->i8count--;
}
/*
* See if the old number was small, the new number is large.
*/
if (ino <= XFS_DIR2_MAX_SHORT_INUM &&
args->inumber > XFS_DIR2_MAX_SHORT_INUM) {
/*
* add to the i8count unless we just converted to 8-byte
* inodes (which does an implied i8count = 1)
*/
ASSERT(sfp->i8count != 0);
if (!i8elevated)
sfp->i8count++;
}
#endif
xfs_dir2_sf_check(args);
xfs_trans_log_inode(args->trans, dp, XFS_ILOG_DDATA);
return 0;
}
#if XFS_BIG_INUMS
/*
* Convert from 8-byte inode numbers to 4-byte inode numbers.
* The last 8-byte inode number is gone, but the count is still 1.
*/
static void
xfs_dir2_sf_toino4(
xfs_da_args_t *args) /* operation arguments */
{
char *buf; /* old dir's buffer */
xfs_inode_t *dp; /* incore directory inode */
int i; /* entry index */
int newsize; /* new inode size */
xfs_dir2_sf_entry_t *oldsfep; /* old sf entry */
xfs_dir2_sf_hdr_t *oldsfp; /* old sf directory */
int oldsize; /* old inode size */
xfs_dir2_sf_entry_t *sfep; /* new sf entry */
xfs_dir2_sf_hdr_t *sfp; /* new sf directory */
trace_xfs_dir2_sf_toino4(args);
dp = args->dp;
/*
* Copy the old directory to the buffer.
* Then nuke it from the inode, and add the new buffer to the inode.
* Don't want xfs_idata_realloc copying the data here.
*/
oldsize = dp->i_df.if_bytes;
buf = kmem_alloc(oldsize, KM_SLEEP);
oldsfp = (xfs_dir2_sf_hdr_t *)dp->i_df.if_u1.if_data;
ASSERT(oldsfp->i8count == 1);
memcpy(buf, oldsfp, oldsize);
/*
* Compute the new inode size.
*/
newsize =
oldsize -
(oldsfp->count + 1) *
((uint)sizeof(xfs_dir2_ino8_t) - (uint)sizeof(xfs_dir2_ino4_t));
xfs_idata_realloc(dp, -oldsize, XFS_DATA_FORK);
xfs_idata_realloc(dp, newsize, XFS_DATA_FORK);
/*
* Reset our pointers, the data has moved.
*/
oldsfp = (xfs_dir2_sf_hdr_t *)buf;
sfp = (xfs_dir2_sf_hdr_t *)dp->i_df.if_u1.if_data;
/*
* Fill in the new header.
*/
sfp->count = oldsfp->count;
sfp->i8count = 0;
xfs_dir2_sf_put_parent_ino(sfp, xfs_dir2_sf_get_parent_ino(oldsfp));
/*
* Copy the entries field by field.
*/
for (i = 0, sfep = xfs_dir2_sf_firstentry(sfp),
oldsfep = xfs_dir2_sf_firstentry(oldsfp);
i < sfp->count;
i++, sfep = xfs_dir2_sf_nextentry(sfp, sfep),
oldsfep = xfs_dir2_sf_nextentry(oldsfp, oldsfep)) {
sfep->namelen = oldsfep->namelen;
sfep->offset = oldsfep->offset;
memcpy(sfep->name, oldsfep->name, sfep->namelen);
xfs_dir2_sfe_put_ino(sfp, sfep,
xfs_dir2_sfe_get_ino(oldsfp, oldsfep));
}
/*
* Clean up the inode.
*/
kmem_free(buf);
dp->i_d.di_size = newsize;
xfs_trans_log_inode(args->trans, dp, XFS_ILOG_CORE | XFS_ILOG_DDATA);
}
/*
* Convert from 4-byte inode numbers to 8-byte inode numbers.
* The new 8-byte inode number is not there yet, we leave with the
* count 1 but no corresponding entry.
*/
static void
xfs_dir2_sf_toino8(
xfs_da_args_t *args) /* operation arguments */
{
char *buf; /* old dir's buffer */
xfs_inode_t *dp; /* incore directory inode */
int i; /* entry index */
int newsize; /* new inode size */
xfs_dir2_sf_entry_t *oldsfep; /* old sf entry */
xfs_dir2_sf_hdr_t *oldsfp; /* old sf directory */
int oldsize; /* old inode size */
xfs_dir2_sf_entry_t *sfep; /* new sf entry */
xfs_dir2_sf_hdr_t *sfp; /* new sf directory */
trace_xfs_dir2_sf_toino8(args);
dp = args->dp;
/*
* Copy the old directory to the buffer.
* Then nuke it from the inode, and add the new buffer to the inode.
* Don't want xfs_idata_realloc copying the data here.
*/
oldsize = dp->i_df.if_bytes;
buf = kmem_alloc(oldsize, KM_SLEEP);
oldsfp = (xfs_dir2_sf_hdr_t *)dp->i_df.if_u1.if_data;
ASSERT(oldsfp->i8count == 0);
memcpy(buf, oldsfp, oldsize);
/*
* Compute the new inode size.
*/
newsize =
oldsize +
(oldsfp->count + 1) *
((uint)sizeof(xfs_dir2_ino8_t) - (uint)sizeof(xfs_dir2_ino4_t));
xfs_idata_realloc(dp, -oldsize, XFS_DATA_FORK);
xfs_idata_realloc(dp, newsize, XFS_DATA_FORK);
/*
* Reset our pointers, the data has moved.
*/
oldsfp = (xfs_dir2_sf_hdr_t *)buf;
sfp = (xfs_dir2_sf_hdr_t *)dp->i_df.if_u1.if_data;
/*
* Fill in the new header.
*/
sfp->count = oldsfp->count;
sfp->i8count = 1;
xfs_dir2_sf_put_parent_ino(sfp, xfs_dir2_sf_get_parent_ino(oldsfp));
/*
* Copy the entries field by field.
*/
for (i = 0, sfep = xfs_dir2_sf_firstentry(sfp),
oldsfep = xfs_dir2_sf_firstentry(oldsfp);
i < sfp->count;
i++, sfep = xfs_dir2_sf_nextentry(sfp, sfep),
oldsfep = xfs_dir2_sf_nextentry(oldsfp, oldsfep)) {
sfep->namelen = oldsfep->namelen;
sfep->offset = oldsfep->offset;
memcpy(sfep->name, oldsfep->name, sfep->namelen);
xfs_dir2_sfe_put_ino(sfp, sfep,
xfs_dir2_sfe_get_ino(oldsfp, oldsfep));
}
/*
* Clean up the inode.
*/
kmem_free(buf);
dp->i_d.di_size = newsize;
xfs_trans_log_inode(args->trans, dp, XFS_ILOG_CORE | XFS_ILOG_DDATA);
}
#endif /* XFS_BIG_INUMS */
| {
"pile_set_name": "Github"
} |
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You 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.
*/
package org.apache.carbondata.core.scan.result.iterator;
import java.util.List;
import java.util.concurrent.ExecutorService;
import org.apache.carbondata.core.scan.executor.infos.BlockExecutionInfo;
import org.apache.carbondata.core.scan.model.QueryModel;
import org.apache.carbondata.core.scan.result.RowBatch;
/**
* In case of detail query we cannot keep all the records in memory so for
* executing that query are returning a iterator over block and every time next
* call will come it will execute the block and return the result
*/
public class DetailQueryResultIterator extends AbstractDetailQueryResultIterator<RowBatch> {
private final Object lock = new Object();
private final BlockExecutionInfo blockExecutionInfo = new BlockExecutionInfo();
public DetailQueryResultIterator(List<BlockExecutionInfo> infos, QueryModel queryModel,
ExecutorService execService) {
super(infos, queryModel, execService);
if (infos.size() > 0) {
blockExecutionInfo
.setComplexColumnParentBlockIndexes(infos.get(0).getComplexColumnParentBlockIndexes());
blockExecutionInfo.setComplexDimensionInfoMap(infos.get(0).getComplexDimensionInfoMap());
}
}
@Override
public RowBatch next() {
return getBatchResult();
}
private RowBatch getBatchResult() {
RowBatch rowBatch = new RowBatch();
synchronized (lock) {
updateDataBlockIterator();
if (dataBlockIterator != null) {
rowBatch.setRows(dataBlockIterator.next());
}
}
return rowBatch;
}
public BlockExecutionInfo getBlockExecutionInfo() {
return blockExecutionInfo;
}
}
| {
"pile_set_name": "Github"
} |
/*
* PearPC
* jitc_tools.s
*
* Copyright (C) 2003-2006 Sebastian Biallas ([email protected])
* Copyright (C) 2004 Daniel Foesch ([email protected])
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2 as
* published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
*/
#ifndef PREFIX
#define PREFIX
#endif
#define EXPORT(sym) EXPORT2(PREFIX, sym)
#define EXPORT2(p, sym) EXPORT3(p, sym)
#define EXPORT3(p, sym) .globl p##sym; p##sym
#define EXTERN(sym) EXTERN2(PREFIX, sym)
#define EXTERN2(p, sym) EXTERN3(p, sym)
#define EXTERN3(p, sym) p##sym
#define STRUCT .struct 0
#define MEMBER(m, s) m:;.struct m+s
.intel_syntax prefix
# Define this if you want exact handling of the SO bit.
/* #define EXACT_SO */
STRUCT #PPC_CPU_State
MEMBER(dummy, 4)
MEMBER(gpr, 32*4)
MEMBER(fpr, 32*8)
MEMBER(cr, 4)
MEMBER(fpscr, 4)
MEMBER(xer, 4)
MEMBER(xer_ca, 4)
MEMBER(ltreg, 4)
MEMBER(ctr, 4)
MEMBER(msr, 4)
MEMBER(pvr, 4)
MEMBER(ibatu, 4*4)
MEMBER(ibatl, 4*4)
MEMBER(ibat_bl, 4*4)
MEMBER(ibat_nbl, 4*4)
MEMBER(ibat_bepi, 4*4)
MEMBER(ibat_brpn, 4*4)
MEMBER(dbatu, 4*4)
MEMBER(dbatl, 4*4)
MEMBER(dbat_bl, 4*4)
MEMBER(dbat_nbl, 4*4)
MEMBER(dbat_bepi, 4*4)
MEMBER(dbat_brpn, 4*4)
MEMBER(sdr1, 4)
MEMBER(sr, 16*4)
MEMBER(dar, 4)
MEMBER(dsisr, 4)
MEMBER(sprg, 4*4)
MEMBER(srr0, 4)
MEMBER(srr1, 4)
MEMBER(decr, 4)
MEMBER(ear, 4)
MEMBER(pir, 4)
MEMBER(tb, 8)
MEMBER(hid, 16*4)
MEMBER(pc, 4)
MEMBER(npc, 4)
MEMBER(current_opc, 4)
MEMBER(exception_pending, 1)
MEMBER(dec_exception, 1)
MEMBER(ext_exception, 1)
MEMBER(stop_exception, 1)
MEMBER(singlestep_ignore, 1)
MEMBER(align1, 1)
MEMBER(align2, 1)
MEMBER(align3, 1)
MEMBER(pagetable_base, 4)
MEMBER(pagetable_hashmask, 4)
MEMBER(reserve, 4)
MEMBER(have_reservation, 4)
MEMBER(tlb_last, 4)
MEMBER(tlb_pa, 4*4)
MEMBER(tlb_va, 4*4)
MEMBER(effective_code_page, 4)
MEMBER(physical_code_page, 4)
MEMBER(pdec, 2*4)
MEMBER(ptb, 2*4)
MEMBER(temp, 4)
MEMBER(temp2, 4)
MEMBER(x87cw, 4)
MEMBER(pc_ofs, 4)
MEMBER(current_code_base, 4)
STRUCT #JITC
MEMBER(clientPages, 4)
STRUCT #ClientPage
MEMBER(entrypoints, 1024*4)
MEMBER(baseaddress, 4)
MEMBER(tcf_current, 4)
MEMBER(bytesLeft, 4)
MEMBER(tcp, 4)
MEMBER(moreRU, 4)
MEMBER(lessRU, 4)
#define gCPU(r) EXTERN(gCPU)+r
.text
.balign 16
##############################################################################################
##
EXPORT(ppc_flush_carry_and_flags_asm):
jc 1f
call EXTERN(ppc_flush_flags_asm)
and byte ptr [gCPU(xer+3)], ~(1<<5)
ret
1:
call EXTERN(ppc_flush_flags_asm)
or byte ptr [gCPU(xer+3)], (1<<5)
ret
##############################################################################################
##
#ifndef EXACT_SO
#define HANDLE_SO
#else
#define HANDLE_SO test byte ptr [gCPU(xer+3)], 1<<7; jnz 4f
#endif
.balign 16
##############################################################################################
##
EXPORT(ppc_flush_flags_asm):
js 3f
jnz 2f
1:
and byte ptr [gCPU(cr+3)], 0x0f
or byte ptr [gCPU(cr+3)], 1<<5
HANDLE_SO
ret
2:
and byte ptr [gCPU(cr+3)], 0x0f
or byte ptr [gCPU(cr+3)], 1<<6
HANDLE_SO
ret
3:
and byte ptr [gCPU(cr+3)], 0x0f
or byte ptr [gCPU(cr+3)], 1<<7
HANDLE_SO
ret
#ifdef EXACT_SO
4:
or byte ptr [gCPU(cr+3)], 1<<4
ret
#endif
.balign 16
##############################################################################################
## called after "cmp cr0, ..", with X even
EXPORT(ppc_flush_flags_signed_0_asm):
jl 3f
jg 2f
1:
and byte ptr [gCPU(cr+3)], 0x0f
or byte ptr [gCPU(cr+3)], 1<<5
HANDLE_SO
ret
2:
and byte ptr [gCPU(cr+3)], 0x0f
or byte ptr [gCPU(cr+3)], 1<<6
HANDLE_SO
ret
3:
and byte ptr [gCPU(cr+3)], 0x0f
or byte ptr [gCPU(cr+3)], 1<<7
HANDLE_SO
ret
#ifdef EXACT_SO
4:
or byte ptr [gCPU(cr+3)], 1<<4
ret
#endif
.balign 16
##############################################################################################
## called after "cmpl cr0, ..", with X even
EXPORT(ppc_flush_flags_unsigned_0_asm):
jb 3f
ja 2f
1:
and byte ptr [gCPU(cr+3)], 0x0f
or byte ptr [gCPU(cr+3)], 1<<5
HANDLE_SO
ret
2:
and byte ptr [gCPU(cr+3)], 0x0f
or byte ptr [gCPU(cr+3)], 1<<6
HANDLE_SO
ret
3:
and byte ptr [gCPU(cr+3)], 0x0f
or byte ptr [gCPU(cr+3)], 1<<7
HANDLE_SO
ret
#ifdef EXACT_SO
.so:
or byte ptr [gCPU(cr+3)], 1<<4
ret
#endif
.balign 16
##############################################################################################
## called after "cmp crX, ..", with X even
ppc_flush_flags_signed_even_asm:
jl 3f
jg 2f
1:
and byte ptr [gCPU(cr+%eax)], 0x0f
or byte ptr [gCPU(cr+%eax)], 1<<5
HANDLE_SO
ret
2:
and byte ptr [gCPU(cr+%eax)], 0x0f
or byte ptr [gCPU(cr+%eax)], 1<<6
HANDLE_SO
ret
3:
and byte ptr [gCPU(cr+%eax)], 0x0f
or byte ptr [gCPU(cr+%eax)], 1<<7
HANDLE_SO
ret
#ifdef EXACT_SO
4:
or byte ptr [gCPU(cr+%eax)], 1<<4
ret
#endif
.balign 16
##############################################################################################
## called after "cmpl crX, ..", with X even
ppc_flush_flags_unsigned_even_asm:
jb 3f
ja 2f
1:
and byte ptr [gCPU(cr+%eax)], 0x0f
or byte ptr [gCPU(cr+%eax)], 1<<5
HANDLE_SO
ret
2:
and byte ptr [gCPU(cr+%eax)], 0x0f
or byte ptr [gCPU(cr+%eax)], 1<<6
HANDLE_SO
ret
3:
and byte ptr [gCPU(cr+%eax)], 0x0f
or byte ptr [gCPU(cr+%eax)], 1<<7
HANDLE_SO
ret
#ifdef EXACT_SO
4:
or byte ptr [gCPU(cr+%eax)], 1<<4
ret
#endif
.balign 16
##############################################################################################
## called after "cmp crX, ..", with X odd
EXPORT(ppc_flush_flags_signed_odd_asm):
jl 3f
jg 2f
1:
and byte ptr [gCPU(cr+%eax)], 0xf0
or byte ptr [gCPU(cr+%eax)], 1<<1
HANDLE_SO
ret
2:
and byte ptr [gCPU(cr+%eax)], 0xf0
or byte ptr [gCPU(cr+%eax)], 1<<2
HANDLE_SO
ret
3:
and byte ptr [gCPU(cr+%eax)], 0xf0
or byte ptr [gCPU(cr+%eax)], 1<<3
HANDLE_SO
ret
#ifdef EXACT_SO
4:
or byte ptr [gCPU(cr+%eax)], 1<<4
ret
#endif
.balign 16
##############################################################################################
## called after "cmpl crX, ..", with X odd
EXPORT(ppc_flush_flags_unsigned_odd_asm):
jb 3f
ja 2f
1:
and byte ptr [gCPU(cr+%eax)], 0xf0
or byte ptr [gCPU(cr+%eax)], 1<<1
HANDLE_SO
ret
2:
and byte ptr [gCPU(cr+%eax)], 0xf0
or byte ptr [gCPU(cr+%eax)], 1<<2
HANDLE_SO
ret
3:
and byte ptr [gCPU(cr+%eax)], 0xf0
or byte ptr [gCPU(cr+%eax)], 1<<3
HANDLE_SO
ret
#ifdef EXACT_SO
4:
or byte ptr [gCPU(cr+%eax)], 1<<4
ret
#endif
##############################################################################################
## ppc_set_msr_asm
##
## IN: %eax: new msr
##
singlestep_error: .asciz "Singlestep support not implemented yet\n"
.balign 16
EXPORT(ppc_set_msr_asm):
mov %ecx, [gCPU(msr)]
test %eax, (1<<10) # MSR_SE
jnz 4f
test %eax, ~((1<<30)|(1<<27)|(1<<25)|(1<<18)|(1<<15)|(1<<14)|(1<<13)|(1<<12)|(1<<11)|(1<<10)|(1<<8)|(1<<5)|(1<<4)|(1<<1))
jnz 5f
test %eax, (1<<18) # MSR_POW
jnz 2f
1:
## Do this first so the invalidate can clobber %eax and
## we won''t care
mov [gCPU(msr)], %eax
xor %eax, %ecx
## See if the privilege level (MSR_PR), data address
## translation (MSR_DR) or code address translation (MSR_IR)
## is changing, in which case we need to invalidate the tlb
test %eax, (1<<14) | (1<<4) | (1<<5)
jnz EXTERN(ppc_mmu_tlb_invalidate_all_asm)
ret
2:
push %eax
call EXTERN(cpu_doze)
pop %eax
mov %ecx, [gCPU(msr)]
and %eax, ~(1<<18)
jmp 1b
4:
mov %eax, singlestep_error
jmp EXTERN(jitc_error)
5:
jmp EXTERN(jitc_error_msr_unsupported_bits)
##############################################################################################
.macro ppc_atomic_raise_ext_exception_macro
lock or dword ptr [gCPU(exception_pending)], 0x00010001
.endm
##############################################################################################
.macro ppc_atomic_cancel_ext_exception_macro
mov %eax, [gCPU(exception_pending)]
9:
test %eax, 0x00000100 # dec_exception
mov %ebx, %eax
setnz %bl
and %ebx, 0x00000101
lock cmpxchg dword ptr [gCPU(exception_pending)], %ebx
jne 9b
.endm
##############################################################################################
.macro ppc_atomic_raise_dec_exception_macro
lock or dword ptr [gCPU(exception_pending)], 0x00000101
.endm
##############################################################################################
.macro ppc_atomic_cancel_dec_exception_macro
mov %eax, [gCPU(exception_pending)]
9:
test %eax, 0x00010000 # ext_exception
mov %ebx, %eax
setnz %bl
and %ebx, 0x00010001
lock cmpxchg dword ptr [gCPU(exception_pending)], %ebx
jne 9b
.endm
.balign 16
##############################################################################################
EXPORT(ppc_cpu_atomic_raise_dec_exception):
ppc_atomic_raise_dec_exception_macro
ret
.balign 16
##############################################################################################
EXPORT(ppc_cpu_atomic_raise_ext_exception):
ppc_atomic_raise_ext_exception_macro
ret
.balign 16
##############################################################################################
EXPORT(ppc_cpu_atomic_cancel_ext_exception):
ppc_atomic_cancel_ext_exception_macro
ret
.balign 16
ppc_jitc_new_pc:
# db 0xcc
mov %ecx, [EXTERN(gJITC)+clientPages]
mov %ebx, %eax
shr %eax, 12
mov %eax, [%ecx+%eax*4]
test %eax, %eax
jnz 1f
mov %eax, %ebx
and %eax, 0xfffff000
call EXTERN(jitcCreateClientPage)
1: # have client page
call EXTERN(jitcTouchClientPage)
cmp dword ptr [%eax+tcf_current], 0
je 3f
mov %ecx, %ebx
mov %esi, %eax
and %ecx, 0x00000ffc
mov %eax, [%eax + entrypoints + %ecx]
test %eax, %eax
jz 2f
ret
2:
mov %eax, %esi
mov %edx, %ebx
and %edx, 0xfffff000
jmp EXTERN(jitcNewEntrypoint)
3:
mov %edx, %ebx
mov %ecx, %ebx
and %edx, 0xfffff000
and %ecx, 0x00000fff
jmp EXTERN(jitcStartTranslation)
##############################################################################################
##
## IN: %eax new client pc (physical address)
##
.macro ppc_new_pc_intern
call EXTERN(jitcNewPC)
# call ppc_jitc_new_pc
jmp %eax
.endm
##############################################################################################
##
.macro exception_epilogue entry
xor %eax, %eax
mov [gCPU(msr)], %eax
mov [gCPU(current_code_base)], %eax
call EXTERN(ppc_mmu_tlb_invalidate_all_asm)
mov %eax, \entry
ppc_new_pc_intern
.endm
.balign 16
##############################################################################################
## ppc_dsi_exception
##
## IN: %eax fault addr
## %ecx dsisr bits
##
## does not return, so call this per JMP
EXPORT(ppc_dsi_exception_asm):
mov [gCPU(dar)], %eax
mov [gCPU(dsisr)], %ecx
EXPORT(ppc_dsi_exception_special_asm):
mov %edx, [gCPU(pc_ofs)]
mov %eax, [gCPU(msr)]
add %edx, [gCPU(current_code_base)]
and %eax, 0x87c0ffff
mov [gCPU(srr1)], %eax
mov [gCPU(srr0)], %edx
exception_epilogue 0x300
.balign 16
##############################################################################################
## ppc_isi_exception_asm
##
## IN: %eax: fault addr
## %ecx: srr1 bits
##
## does not return, so call this per JMP
EXPORT(ppc_isi_exception_asm):
mov [gCPU(srr0)], %eax
mov %eax, [gCPU(msr)]
and %eax, 0x87c0ffff
or %eax, %ecx
mov [gCPU(srr1)], %eax
exception_epilogue 0x400
.balign 16
##############################################################################################
##
## IN:
## %eax: current pc
##
## this is only called indirectly
EXPORT(ppc_ext_exception_asm):
mov [gCPU(srr0)], %eax
mov %edx, [gCPU(msr)]
ppc_atomic_cancel_ext_exception_macro
and %edx, 0x87c0ffff
mov [gCPU(srr1)], %edx
exception_epilogue 0x500
.balign 16
##############################################################################################
##
## IN: %ecx: srr1 bits
## %esi: pc_ofs
##
## does not return, so call this per JMP
EXPORT(ppc_program_exception_asm):
# debug
# pusha
# mov %eax, %ecx
# call EXTERN(jitc_error_program)
# popa
mov [gCPU(pc_ofs)], %esi
mov %eax, [gCPU(msr)]
mov %edx, %esi
and %eax, 0x87c0ffff
add %edx, [gCPU(current_code_base)]
or %eax, %ecx
mov [gCPU(srr0)], %edx
mov [gCPU(srr1)], %eax
exception_epilogue 0x700
.balign 16
##############################################################################################
##
## IN:
## %esi: pc_ofs
##
## does not return, so call this per JMP
EXPORT(ppc_no_fpu_exception_asm):
mov %edx, %esi
mov [gCPU(pc_ofs)], %esi
mov %eax, [gCPU(msr)]
add %edx, [gCPU(current_code_base)]
and %eax, 0x87c0ffff
mov [gCPU(srr0)], %edx
mov [gCPU(srr1)], %eax
exception_epilogue 0x800
.balign 16
##############################################################################################
##
## IN:
## %esi: pc_ofs
##
## does not return, so call this per JMP
EXPORT(ppc_no_vec_exception_asm):
mov %edx, %esi
mov [gCPU(pc_ofs)], %esi
mov %eax, [gCPU(msr)]
add %edx, [gCPU(current_code_base)]
and %eax, 0x87c0ffff
mov [gCPU(srr0)], %edx
mov [gCPU(srr1)], %eax
exception_epilogue 0xf20
.balign 16
##############################################################################################
##
## IN:
## %eax: current pc
##
## this is only called indirectly
EXTERN(ppc_dec_exception_asm):
mov [gCPU(srr0)], %eax
mov %edx, [gCPU(msr)]
ppc_atomic_cancel_dec_exception_macro
and %edx, 0x87c0ffff
mov [gCPU(srr1)], %edx
exception_epilogue 0x900
.balign 16
##############################################################################################
##
## IN:
## %esi: pc_ofs
##
## does not return, so call this per JMP
EXPORT(ppc_sc_exception_asm):
mov %edx, %esi
mov [gCPU(pc_ofs)], %esi
mov %eax, [gCPU(msr)]
add %edx, [gCPU(current_code_base)]
and %eax, 0x87c0ffff
mov [gCPU(srr0)], %edx
mov [gCPU(srr1)], %eax
xor %eax, %eax
call EXTERN(ppc_set_msr_asm)
xor %eax, %eax
mov [gCPU(current_code_base)], %eax
mov %eax, 0xc00 # entry of SC exception
ppc_new_pc_intern
.balign 16
##############################################################################################
## ppc_heartbeat_ext_rel_asm
##
##
EXPORT(ppc_heartbeat_ext_rel_asm):
test byte ptr [gCPU(exception_pending)], 1
jnz 1f
2:
ret
1:
test byte ptr [gCPU(stop_exception)], 1
jnz 3f
test byte ptr [gCPU(msr+1)], 1<<7 # MSR_EE
jz 2b
add %esp, 4
add %eax, [gCPU(current_code_base)]
test byte ptr [gCPU(ext_exception)], 1
jnz EXTERN(ppc_ext_exception_asm)
test byte ptr [gCPU(dec_exception)], 1
jnz EXTERN(ppc_dec_exception_asm)
mov %eax, exception_error
jmp EXTERN(jitc_error)
3:
add %esp, 4
jmp ppc_stop_jitc_asm
.balign 16
##############################################################################################
## ppc_heartbeat_ext_asm
## %eax -- new pc
##
EXPORT(ppc_heartbeat_ext_asm):
mov %edx, %eax
and %edx, 0xfffff000
test byte ptr [gCPU(exception_pending)], 1
mov [gCPU(current_code_base)], %edx
jnz 1f
2:
ret
1:
test byte ptr [gCPU(stop_exception)], 1
jnz 3f
test byte ptr [gCPU(msr+1)], 1<<7 # MSR_EE
jz 2b
add %esp, 4
test byte ptr [gCPU(ext_exception)], 1
jnz EXTERN(ppc_ext_exception_asm)
test byte ptr [gCPU(dec_exception)], 1
jnz EXTERN(ppc_dec_exception_asm)
mov %eax, exception_error
jmp EXTERN(jitc_error)
3:
add %esp, 4
jmp ppc_stop_jitc_asm
exception_error: .asciz "Unknown exception signaled?!\n"
.balign 16
##############################################################################################
## ppc_new_pc_rel_asm
##
## IN: %eax new client pc relative
##
## does not return, so call this per JMP
EXPORT(ppc_new_pc_rel_asm):
add %eax, [gCPU(current_code_base)]
call EXTERN(ppc_heartbeat_ext_asm)
push 0 # bytes to unwind
call EXTERN(ppc_effective_to_physical_code)
ppc_new_pc_intern
.balign 16
##############################################################################################
## ppc_new_pc_asm
##
## IN: %eax new client pc (effective address)
##
## does not return, so call this per JMP
EXPORT(ppc_new_pc_asm):
call EXTERN(ppc_heartbeat_ext_asm)
push 0
call EXTERN(ppc_effective_to_physical_code)
ppc_new_pc_intern
.balign 16
##############################################################################################
##
##
EXPORT(ppc_new_pc_this_page_asm):
# mov %esi, [%esp]
# mov [%esi-6], %eax # patch it now, later we don''t have the value
add %eax, [gCPU(current_code_base)]
push 4
call EXTERN(ppc_effective_to_physical_code)
call EXTERN(jitcNewPC)
#if 0
pop %esi
# now %eax and %esi are both native addresses
# %eax is dest and %esi is source
#
# we assume that we can overwrite 15 bytes before the call
# and 3 bytes after the call and the 5 bytes of the call instruction
mov %edx, %eax
sub %eax, %esi
mov byte ptr [%esi-20], 0xf6 # test [gCPU(exception_pending)], 1
mov byte ptr [%esi-19], 0x05
mov dword ptr [%esi-18], gCPU(exception_pending)
mov byte ptr [%esi-14], 1
add %eax, 7
mov byte ptr [%esi-13], 0x0f # jz dest (%edx)
mov byte ptr [%esi-12], 0x84
mov dword [%esi-11], %eax # the jz is relative to (%esi-7)
mov %eax, ppc_heartbeat_ext_rel_asm - 3
sub %eax, %esi
mov byte ptr [%esi-7], 0xb8 # mov %eax, offset
## mov dword ptr [%esi-6], ... # see above, this is already patched!
mov byte ptr [%esi-2], 0xe8 # call ppc_heartbeat_ext_rel_asm
mov dword ptr [%esi-1], %eax # the call is relative to (%esi+3)
jmp %edx
#endif
pop %edi
# now %eax and %edi are both native addresses
# %eax is dest and %edi is source
#
# we assume that there is a "mov %eax, xxx" instruction before
# calling this function, and note that 5 is also the length of a jmp xxx
# so we patch %edi-10
mov %edx, %eax
sub %edi, 5
mov byte ptr [%edi-5], 0xe9
sub %eax, %edi
mov dword ptr [%edi-4], %eax
jmp %edx
.balign 2
ppc_start_fpu_cw: .short 0x37f
.balign 16
##############################################################################################
##
## IN: %eax new client pc (effective address)
##
EXPORT(ppc_start_jitc_asm):
push %ebx
push %ebp
push %esi
push %edi
fldcw [ppc_start_fpu_cw]
jmp EXTERN(ppc_new_pc_asm)
.balign 16
##############################################################################################
##
## call per JMP
##
ppc_stop_jitc_asm:
pop %edi
pop %esi
pop %ebp
pop %ebx
ret
##############################################################################################
##
## IN: %eax cpuid level
## %edx dest
##
EXPORT(ppc_cpuid_asm):
push %ebx
pushfd
pop %ebx
mov %ecx, %ebx
xor %ebx, 0x00200000
push %ebx
popfd
pushfd
pop %ebx
cmp %ebx, %ecx
jne 1f
pop %ebx
xor %eax, %eax
ret
1:
push %edi
mov %edi, %edx
cpuid
mov [%edi], %eax
mov [%edi+4], %ecx
mov [%edi+8], %edx
mov [%edi+12], %ebx
pop %edi
pop %ebx
mov %eax, 1
ret
| {
"pile_set_name": "Github"
} |
(module XBEE-SILK (layer F.Cu) (tedit 200000)
(descr "DIGI XBEE AND XBEE-PRO RF MODULES (SILKSCREEN DIMENSION INDICATORS)")
(tags "DIGI XBEE AND XBEE-PRO RF MODULES (SILKSCREEN DIMENSION INDICATORS)")
(attr virtual)
(fp_text reference >NAME (at 8.89 3.81) (layer F.SilkS)
(effects (font (size 0.6096 0.6096) (thickness 0.127)))
)
(fp_text value >VALUE (at 8.89 5.08) (layer F.SilkS)
(effects (font (size 0.6096 0.6096) (thickness 0.127)))
)
(fp_line (start -4.99872 -27.59964) (end 4.99872 -27.59964) (layer Dwgs.User) (width 0.127))
(fp_line (start -12.24788 -21.24964) (end -4.99872 -27.59964) (layer Dwgs.User) (width 0.127))
(fp_line (start 12.24788 -21.24964) (end 4.99872 -27.59964) (layer Dwgs.User) (width 0.127))
(fp_line (start 9.74852 -21.24964) (end 12.24788 -21.24964) (layer F.SilkS) (width 0.2032))
(fp_line (start 12.24788 -21.24964) (end 12.24788 -0.7493) (layer F.SilkS) (width 0.2032))
(fp_line (start 12.24788 -0.7493) (end 9.74852 -0.7493) (layer F.SilkS) (width 0.2032))
(fp_line (start 9.74852 -21.24964) (end 9.74852 -0.7493) (layer F.SilkS) (width 0.2032))
(fp_line (start -9.74852 -21.24964) (end -12.24788 -21.24964) (layer F.SilkS) (width 0.2032))
(fp_line (start -12.24788 -21.24964) (end -12.24788 -0.7493) (layer F.SilkS) (width 0.2032))
(fp_line (start -12.24788 -0.7493) (end -9.74852 -0.7493) (layer F.SilkS) (width 0.2032))
(fp_line (start -9.74852 -21.24964) (end -9.74852 -0.7493) (layer F.SilkS) (width 0.2032))
(fp_line (start -12.24788 -0.7493) (end -12.24788 0) (layer F.SilkS) (width 0.2032))
(fp_line (start 12.24788 -0.7493) (end 12.24788 0) (layer F.SilkS) (width 0.2032))
(fp_line (start -12.24788 0) (end 12.24788 0) (layer F.SilkS) (width 0.2032))
(fp_line (start 12.24788 0) (end 12.24788 6.2484) (layer Dwgs.User) (width 0.127))
(fp_line (start -12.24788 0) (end -12.24788 6.2484) (layer Dwgs.User) (width 0.127))
(fp_line (start -12.24788 6.2484) (end 12.24788 6.2484) (layer Dwgs.User) (width 0.127))
(fp_line (start -4.99872 -27.59964) (end -5.69976 -26.99766) (layer F.SilkS) (width 0.2032))
(fp_line (start -4.99872 -27.59964) (end 4.99872 -27.59964) (layer F.SilkS) (width 0.2032))
(fp_line (start 4.99872 -27.59964) (end 5.69976 -26.99766) (layer F.SilkS) (width 0.2032))
(fp_text user 1 (at -8.9916 -20.50796) (layer F.SilkS)
(effects (font (size 1.016 1.016) (thickness 0.1524)))
)
(pad 1 thru_hole circle (at -10.9982 -19.99996) (size 1.524 1.524) (drill 0.79756) (layers *.Cu *.Mask)
(solder_mask_margin 0.1016))
(pad 2 thru_hole circle (at -10.9982 -17.99844) (size 1.524 1.524) (drill 0.79756) (layers *.Cu *.Mask)
(solder_mask_margin 0.1016))
(pad 3 thru_hole circle (at -10.9982 -15.99946) (size 1.524 1.524) (drill 0.79756) (layers *.Cu *.Mask)
(solder_mask_margin 0.1016))
(pad 4 thru_hole circle (at -10.9982 -13.99794) (size 1.524 1.524) (drill 0.79756) (layers *.Cu *.Mask)
(solder_mask_margin 0.1016))
(pad 5 thru_hole circle (at -10.9982 -11.99896) (size 1.524 1.524) (drill 0.79756) (layers *.Cu *.Mask)
(solder_mask_margin 0.1016))
(pad 6 thru_hole circle (at -10.9982 -9.99998) (size 1.524 1.524) (drill 0.79756) (layers *.Cu *.Mask)
(solder_mask_margin 0.1016))
(pad 7 thru_hole circle (at -10.9982 -7.99846) (size 1.524 1.524) (drill 0.79756) (layers *.Cu *.Mask)
(solder_mask_margin 0.1016))
(pad 8 thru_hole circle (at -10.9982 -5.99948) (size 1.524 1.524) (drill 0.79756) (layers *.Cu *.Mask)
(solder_mask_margin 0.1016))
(pad 9 thru_hole circle (at -10.9982 -3.99796) (size 1.524 1.524) (drill 0.79756) (layers *.Cu *.Mask)
(solder_mask_margin 0.1016))
(pad 10 thru_hole circle (at -10.9982 -1.99898) (size 1.524 1.524) (drill 0.79756) (layers *.Cu *.Mask)
(solder_mask_margin 0.1016))
(pad 11 thru_hole circle (at 10.9982 -1.99898) (size 1.524 1.524) (drill 0.79756) (layers *.Cu *.Mask)
(solder_mask_margin 0.1016))
(pad 12 thru_hole circle (at 10.9982 -3.99796) (size 1.524 1.524) (drill 0.79756) (layers *.Cu *.Mask)
(solder_mask_margin 0.1016))
(pad 13 thru_hole circle (at 10.9982 -5.99948) (size 1.524 1.524) (drill 0.79756) (layers *.Cu *.Mask)
(solder_mask_margin 0.1016))
(pad 14 thru_hole circle (at 10.9982 -7.99846) (size 1.524 1.524) (drill 0.79756) (layers *.Cu *.Mask)
(solder_mask_margin 0.1016))
(pad 15 thru_hole circle (at 10.9982 -9.99998) (size 1.524 1.524) (drill 0.79756) (layers *.Cu *.Mask)
(solder_mask_margin 0.1016))
(pad 16 thru_hole circle (at 10.9982 -11.99896) (size 1.524 1.524) (drill 0.79756) (layers *.Cu *.Mask)
(solder_mask_margin 0.1016))
(pad 17 thru_hole circle (at 10.9982 -13.99794) (size 1.524 1.524) (drill 0.79756) (layers *.Cu *.Mask)
(solder_mask_margin 0.1016))
(pad 18 thru_hole circle (at 10.9982 -15.99946) (size 1.524 1.524) (drill 0.79756) (layers *.Cu *.Mask)
(solder_mask_margin 0.1016))
(pad 19 thru_hole circle (at 10.9982 -17.99844) (size 1.524 1.524) (drill 0.79756) (layers *.Cu *.Mask)
(solder_mask_margin 0.1016))
(pad 20 thru_hole circle (at 10.9982 -19.99996) (size 1.524 1.524) (drill 0.79756) (layers *.Cu *.Mask)
(solder_mask_margin 0.1016))
)
| {
"pile_set_name": "Github"
} |
<?xml version='1.0' encoding='UTF-8'?>
<!DOCTYPE map
PUBLIC "-//Sun Microsystems Inc.//DTD JavaHelp Map Version 1.0//EN"
"http://java.sun.com/products/javahelp/map_1_0.dtd">
<map version="1.0">
<mapID target="codedx-icon" url="contents/images/codedx.png" />
<mapID target="codedx" url="contents/codedx.html" />
</map>
| {
"pile_set_name": "Github"
} |
/**
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
* SPDX-License-Identifier: Apache-2.0.
*/
#pragma once
#include <aws/quicksight/QuickSight_EXPORTS.h>
#include <aws/core/utils/memory/stl/AWSString.h>
#include <utility>
namespace Aws
{
namespace Utils
{
namespace Json
{
class JsonValue;
class JsonView;
} // namespace Json
} // namespace Utils
namespace QuickSight
{
namespace Model
{
/**
* <p>Presto parameters.</p><p><h3>See Also:</h3> <a
* href="http://docs.aws.amazon.com/goto/WebAPI/quicksight-2018-04-01/PrestoParameters">AWS
* API Reference</a></p>
*/
class AWS_QUICKSIGHT_API PrestoParameters
{
public:
PrestoParameters();
PrestoParameters(Aws::Utils::Json::JsonView jsonValue);
PrestoParameters& operator=(Aws::Utils::Json::JsonView jsonValue);
Aws::Utils::Json::JsonValue Jsonize() const;
/**
* <p>Host.</p>
*/
inline const Aws::String& GetHost() const{ return m_host; }
/**
* <p>Host.</p>
*/
inline bool HostHasBeenSet() const { return m_hostHasBeenSet; }
/**
* <p>Host.</p>
*/
inline void SetHost(const Aws::String& value) { m_hostHasBeenSet = true; m_host = value; }
/**
* <p>Host.</p>
*/
inline void SetHost(Aws::String&& value) { m_hostHasBeenSet = true; m_host = std::move(value); }
/**
* <p>Host.</p>
*/
inline void SetHost(const char* value) { m_hostHasBeenSet = true; m_host.assign(value); }
/**
* <p>Host.</p>
*/
inline PrestoParameters& WithHost(const Aws::String& value) { SetHost(value); return *this;}
/**
* <p>Host.</p>
*/
inline PrestoParameters& WithHost(Aws::String&& value) { SetHost(std::move(value)); return *this;}
/**
* <p>Host.</p>
*/
inline PrestoParameters& WithHost(const char* value) { SetHost(value); return *this;}
/**
* <p>Port.</p>
*/
inline int GetPort() const{ return m_port; }
/**
* <p>Port.</p>
*/
inline bool PortHasBeenSet() const { return m_portHasBeenSet; }
/**
* <p>Port.</p>
*/
inline void SetPort(int value) { m_portHasBeenSet = true; m_port = value; }
/**
* <p>Port.</p>
*/
inline PrestoParameters& WithPort(int value) { SetPort(value); return *this;}
/**
* <p>Catalog.</p>
*/
inline const Aws::String& GetCatalog() const{ return m_catalog; }
/**
* <p>Catalog.</p>
*/
inline bool CatalogHasBeenSet() const { return m_catalogHasBeenSet; }
/**
* <p>Catalog.</p>
*/
inline void SetCatalog(const Aws::String& value) { m_catalogHasBeenSet = true; m_catalog = value; }
/**
* <p>Catalog.</p>
*/
inline void SetCatalog(Aws::String&& value) { m_catalogHasBeenSet = true; m_catalog = std::move(value); }
/**
* <p>Catalog.</p>
*/
inline void SetCatalog(const char* value) { m_catalogHasBeenSet = true; m_catalog.assign(value); }
/**
* <p>Catalog.</p>
*/
inline PrestoParameters& WithCatalog(const Aws::String& value) { SetCatalog(value); return *this;}
/**
* <p>Catalog.</p>
*/
inline PrestoParameters& WithCatalog(Aws::String&& value) { SetCatalog(std::move(value)); return *this;}
/**
* <p>Catalog.</p>
*/
inline PrestoParameters& WithCatalog(const char* value) { SetCatalog(value); return *this;}
private:
Aws::String m_host;
bool m_hostHasBeenSet;
int m_port;
bool m_portHasBeenSet;
Aws::String m_catalog;
bool m_catalogHasBeenSet;
};
} // namespace Model
} // namespace QuickSight
} // namespace Aws
| {
"pile_set_name": "Github"
} |
32 7 8 Cross.png
| {
"pile_set_name": "Github"
} |
.. _libraries:
Libraries
#########
Nordic Semiconductor provides a variety of libraries and services that are used in our sample applications.
Here you can find documentation for these libraries, including API documentation.
.. toctree::
:maxdepth: 1
:glob:
libraries/*
| {
"pile_set_name": "Github"
} |
<template>
<div>
<h1>{{ $t('app.aside.nav.menus') }}</h1>
<p class="tip">将快捷菜单注册成全局可复用的</p>
<vxe-table
resizable
highlight-current-row
highlight-hover-row
highlight-current-column
:data="tableData">
<vxe-table-column field="name" title="app.api.title.prop" min-width="280" tree-node></vxe-table-column>
<vxe-table-column field="desc" title="app.api.title.desc" min-width="200"></vxe-table-column>
<vxe-table-column field="type" title="app.api.title.type" min-width="140"></vxe-table-column>
<vxe-table-column field="enum" title="app.api.title.enum" min-width="150"></vxe-table-column>
<vxe-table-column field="defVal" title="app.api.title.defVal" min-width="160"></vxe-table-column>
</vxe-table>
<h2>示例</h2>
<pre>
<code class="html">{{ demoCodes[0] }}</code>
<code class="javascript">{{ demoCodes[1] }}</code>
</pre>
</div>
</template>
<script>
import hljs from 'highlight.js'
export default {
data () {
return {
tableData: [
{
name: 'add(code, callback)',
desc: '添加一个',
type: '',
enum: '',
defVal: 'code: string, callback: (params, event) => any',
list: []
},
{
name: 'mixin(options)',
desc: '添加多个',
type: '',
enum: '',
defVal: 'options: { [code: string]: (params, event) => any }',
list: []
},
{
name: 'delete(code)',
desc: '删除',
type: '',
enum: '',
defVal: 'code: string',
list: []
}
],
demoCodes: [
`
<vxe-table
border
:context-menu="tableMenu"
:data="tableData">
<vxe-table-column type="seq" width="60"></vxe-table-column>
<vxe-table-column field="name" title="Name" :edit-render="{name: 'input'}"></vxe-table-column>
<vxe-table-column field="sex" title="sex"></vxe-table-column>
<vxe-table-column field="age" title="Age"></vxe-table-column>
</vxe-table>
`,
`
VXETable.menus.add('exportData', (params, event) => {
let { $table } = params
$table.exportData()
})
VXETable.menus.add('insert', (params, event) => {
let { $table, menu } = params
// 读取自定义的参数
$table.insert(menu.record)
})
export default {
data () {
return {
tableMenu: {
body: {
options: [
[
{ code: 'exportData', name: '导出.csv' },
{ code: 'insert', name: '新增', record: { name: '默认名称' } }
]
]
}
},
tableData: [
{ id: 10001, name: 'Test1', role: 'Develop', sex: 'Man', age: 28, address: 'Shenzhen' },
{ id: 10002, name: 'Test2', role: 'Test', sex: 'Women', age: 22, address: 'Guangzhou' },
{ id: 10003, name: 'Test3', role: 'PM', sex: 'Man', age: 32, address: 'Shanghai' },
{ id: 10004, name: 'Test4', role: 'Designer', sex: 'Women ', age: 24, address: 'Shanghai' }
]
}
}
}
`
]
}
},
mounted () {
Array.from(this.$el.querySelectorAll('pre code')).forEach((block) => {
hljs.highlightBlock(block)
})
}
}
</script>
| {
"pile_set_name": "Github"
} |
---
layout: api-command
language: Java
permalink: api/java/bit_xor/
command: bitXor
related_commands:
bit_and: bit_and/
bit_not: bit_not/
bit_or: bit_or/
bit_sal: bit_sal/
bit_sar: bit_sar/
---
# Command syntax #
{% apibody %}
r.bitXor(number) → number
r.bitXor(number[, number, ...]) → number
{% endapibody %}
# Description #
A bitwise XOR is a binary operation that takes two bit patterns of equal length and performs the logical exclusive OR operation on each pair of corresponding bits. The result in each position is 1 if only the first bit is 1 or only the second bit is 1, but will be 0 if both are 0 or both are 1. In this we perform the comparison of two bits, being 1 if the two bits are different, and 0 if they are the same.
__Example:__
```java
r.expr(6).bitXor(4).run(conn);
// Result:
2
```
| {
"pile_set_name": "Github"
} |
// ---------------------------------------------------------------------
//
// Copyright (c) 2014 - 2019 by the IBAMR developers
// All rights reserved.
//
// This file is part of IBAMR.
//
// IBAMR is free software and is distributed under the 3-clause BSD
// license. The full text of the license can be found in the file
// COPYRIGHT at the top level directory of IBAMR.
//
// ---------------------------------------------------------------------
/////////////////////////////// INCLUDES /////////////////////////////////////
#include "ibtk/LSetDataIterator.h"
#include "ibtk/namespaces.h" // IWYU pragma: keep
//////////////////////////////////////////////////////////////////////////////
| {
"pile_set_name": "Github"
} |
/*
* pc300.h Cyclades-PC300(tm) Kernel API Definitions.
*
* Author: Ivan Passos <[email protected]>
*
* Copyright: (c) 1999-2002 Cyclades Corp.
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version
* 2 of the License, or (at your option) any later version.
*
* $Log: pc300.h,v $
* Revision 3.12 2002/03/07 14:17:09 henrique
* License data fixed
*
* Revision 3.11 2002/01/28 21:09:39 daniela
* Included ';' after pc300hw.bus.
*
* Revision 3.10 2002/01/17 17:58:52 ivan
* Support for PC300-TE/M (PMC).
*
* Revision 3.9 2001/09/28 13:30:53 daniela
* Renamed dma_start routine to rx_dma_start.
*
* Revision 3.8 2001/09/24 13:03:45 daniela
* Fixed BOF interrupt treatment. Created dma_start routine.
*
* Revision 3.7 2001/08/10 17:19:58 daniela
* Fixed IOCTLs defines.
*
* Revision 3.6 2001/07/18 19:24:42 daniela
* Included kernel version.
*
* Revision 3.5 2001/07/05 18:38:08 daniela
* DMA transmission bug fix.
*
* Revision 3.4 2001/06/26 17:10:40 daniela
* New configuration parameters (line code, CRC calculation and clock).
*
* Revision 3.3 2001/06/22 13:13:02 regina
* MLPPP implementation
*
* Revision 3.2 2001/06/18 17:56:09 daniela
* Increased DEF_MTU and TX_QUEUE_LEN.
*
* Revision 3.1 2001/06/15 12:41:10 regina
* upping major version number
*
* Revision 1.1.1.1 2001/06/13 20:25:06 daniela
* PC300 initial CVS version (3.4.0-pre1)
*
* Revision 2.3 2001/03/05 daniela
* Created struct pc300conf, to provide the hardware information to pc300util.
* Inclusion of 'alloc_ramsize' field on structure 'pc300hw'.
*
* Revision 2.2 2000/12/22 daniela
* Structures and defines to support pc300util: statistics, status,
* loopback tests, trace.
*
* Revision 2.1 2000/09/28 ivan
* Inclusion of 'iophys' and 'iosize' fields on structure 'pc300hw', to
* allow release of I/O region at module unload.
* Changed location of include files.
*
* Revision 2.0 2000/03/27 ivan
* Added support for the PC300/TE cards.
*
* Revision 1.1 2000/01/31 ivan
* Replaced 'pc300[drv|sca].h' former PC300 driver include files.
*
* Revision 1.0 1999/12/16 ivan
* First official release.
* Inclusion of 'nchan' field on structure 'pc300hw', to allow variable
* number of ports per card.
* Inclusion of 'if_ptr' field on structure 'pc300dev'.
*
* Revision 0.6 1999/11/17 ivan
* Changed X.25-specific function names to comply with adopted convention.
*
* Revision 0.5 1999/11/16 Daniela Squassoni
* X.25 support.
*
* Revision 0.4 1999/11/15 ivan
* Inclusion of 'clock' field on structure 'pc300hw'.
*
* Revision 0.3 1999/11/10 ivan
* IOCTL name changing.
* Inclusion of driver function prototypes.
*
* Revision 0.2 1999/11/03 ivan
* Inclusion of 'tx_skb' and union 'ifu' on structure 'pc300dev'.
*
* Revision 0.1 1999/01/15 ivan
* Initial version.
*
*/
#ifndef _PC300_H
#define _PC300_H
#include <linux/hdlc.h>
#include "hd64572.h"
#include "pc300-falc-lh.h"
#define PC300_PROTO_MLPPP 1
#define PC300_MAXCHAN 2 /* Number of channels per card */
#define PC300_RAMSIZE 0x40000 /* RAM window size (256Kb) */
#define PC300_FALCSIZE 0x400 /* FALC window size (1Kb) */
#define PC300_OSC_CLOCK 24576000
#define PC300_PCI_CLOCK 33000000
#define BD_DEF_LEN 0x0800 /* DMA buffer length (2KB) */
#define DMA_TX_MEMSZ 0x8000 /* Total DMA Tx memory size (32KB/ch) */
#define DMA_RX_MEMSZ 0x10000 /* Total DMA Rx memory size (64KB/ch) */
#define N_DMA_TX_BUF (DMA_TX_MEMSZ / BD_DEF_LEN) /* DMA Tx buffers */
#define N_DMA_RX_BUF (DMA_RX_MEMSZ / BD_DEF_LEN) /* DMA Rx buffers */
/* DMA Buffer Offsets */
#define DMA_TX_BASE ((N_DMA_TX_BUF + N_DMA_RX_BUF) * \
PC300_MAXCHAN * sizeof(pcsca_bd_t))
#define DMA_RX_BASE (DMA_TX_BASE + PC300_MAXCHAN*DMA_TX_MEMSZ)
/* DMA Descriptor Offsets */
#define DMA_TX_BD_BASE 0x0000
#define DMA_RX_BD_BASE (DMA_TX_BD_BASE + ((PC300_MAXCHAN*DMA_TX_MEMSZ / \
BD_DEF_LEN) * sizeof(pcsca_bd_t)))
/* DMA Descriptor Macros */
#define TX_BD_ADDR(chan, n) (DMA_TX_BD_BASE + \
((N_DMA_TX_BUF*chan) + n) * sizeof(pcsca_bd_t))
#define RX_BD_ADDR(chan, n) (DMA_RX_BD_BASE + \
((N_DMA_RX_BUF*chan) + n) * sizeof(pcsca_bd_t))
/* Macro to access the FALC registers (TE only) */
#define F_REG(reg, chan) (0x200*(chan) + ((reg)<<2))
/***************************************
* Memory access functions/macros *
* (required to support Alpha systems) *
***************************************/
#define cpc_writeb(port,val) {writeb((u8)(val),(port)); mb();}
#define cpc_writew(port,val) {writew((ushort)(val),(port)); mb();}
#define cpc_writel(port,val) {writel((u32)(val),(port)); mb();}
#define cpc_readb(port) readb(port)
#define cpc_readw(port) readw(port)
#define cpc_readl(port) readl(port)
/****** Data Structures *****************************************************/
/*
* RUNTIME_9050 - PLX PCI9050-1 local configuration and shared runtime
* registers. This structure can be used to access the 9050 registers
* (memory mapped).
*/
struct RUNTIME_9050 {
u32 loc_addr_range[4]; /* 00-0Ch : Local Address Ranges */
u32 loc_rom_range; /* 10h : Local ROM Range */
u32 loc_addr_base[4]; /* 14-20h : Local Address Base Addrs */
u32 loc_rom_base; /* 24h : Local ROM Base */
u32 loc_bus_descr[4]; /* 28-34h : Local Bus Descriptors */
u32 rom_bus_descr; /* 38h : ROM Bus Descriptor */
u32 cs_base[4]; /* 3C-48h : Chip Select Base Addrs */
u32 intr_ctrl_stat; /* 4Ch : Interrupt Control/Status */
u32 init_ctrl; /* 50h : EEPROM ctrl, Init Ctrl, etc */
};
#define PLX_9050_LINT1_ENABLE 0x01
#define PLX_9050_LINT1_POL 0x02
#define PLX_9050_LINT1_STATUS 0x04
#define PLX_9050_LINT2_ENABLE 0x08
#define PLX_9050_LINT2_POL 0x10
#define PLX_9050_LINT2_STATUS 0x20
#define PLX_9050_INTR_ENABLE 0x40
#define PLX_9050_SW_INTR 0x80
/* Masks to access the init_ctrl PLX register */
#define PC300_CLKSEL_MASK (0x00000004UL)
#define PC300_CHMEDIA_MASK(chan) (0x00000020UL<<(chan*3))
#define PC300_CTYPE_MASK (0x00000800UL)
/* CPLD Registers (base addr = falcbase, TE only) */
/* CPLD v. 0 */
#define CPLD_REG1 0x140 /* Chip resets, DCD/CTS status */
#define CPLD_REG2 0x144 /* Clock enable , LED control */
/* CPLD v. 2 or higher */
#define CPLD_V2_REG1 0x100 /* Chip resets, DCD/CTS status */
#define CPLD_V2_REG2 0x104 /* Clock enable , LED control */
#define CPLD_ID_REG 0x108 /* CPLD version */
/* CPLD Register bit description: for the FALC bits, they should always be
set based on the channel (use (bit<<(2*ch)) to access the correct bit for
that channel) */
#define CPLD_REG1_FALC_RESET 0x01
#define CPLD_REG1_SCA_RESET 0x02
#define CPLD_REG1_GLOBAL_CLK 0x08
#define CPLD_REG1_FALC_DCD 0x10
#define CPLD_REG1_FALC_CTS 0x20
#define CPLD_REG2_FALC_TX_CLK 0x01
#define CPLD_REG2_FALC_RX_CLK 0x02
#define CPLD_REG2_FALC_LED1 0x10
#define CPLD_REG2_FALC_LED2 0x20
/* Structure with FALC-related fields (TE only) */
#define PC300_FALC_MAXLOOP 0x0000ffff /* for falc_issue_cmd() */
typedef struct falc {
u8 sync; /* If true FALC is synchronized */
u8 active; /* if TRUE then already active */
u8 loop_active; /* if TRUE a line loopback UP was received */
u8 loop_gen; /* if TRUE a line loopback UP was issued */
u8 num_channels;
u8 offset; /* 1 for T1, 0 for E1 */
u8 full_bandwidth;
u8 xmb_cause;
u8 multiframe_mode;
/* Statistics */
u16 pden; /* Pulse Density violation count */
u16 los; /* Loss of Signal count */
u16 losr; /* Loss of Signal recovery count */
u16 lfa; /* Loss of frame alignment count */
u16 farec; /* Frame Alignment Recovery count */
u16 lmfa; /* Loss of multiframe alignment count */
u16 ais; /* Remote Alarm indication Signal count */
u16 sec; /* One-second timer */
u16 es; /* Errored second */
u16 rai; /* remote alarm received */
u16 bec;
u16 fec;
u16 cvc;
u16 cec;
u16 ebc;
/* Status */
u8 red_alarm;
u8 blue_alarm;
u8 loss_fa;
u8 yellow_alarm;
u8 loss_mfa;
u8 prbs;
} falc_t;
typedef struct falc_status {
u8 sync; /* If true FALC is synchronized */
u8 red_alarm;
u8 blue_alarm;
u8 loss_fa;
u8 yellow_alarm;
u8 loss_mfa;
u8 prbs;
} falc_status_t;
typedef struct rsv_x21_status {
u8 dcd;
u8 dsr;
u8 cts;
u8 rts;
u8 dtr;
} rsv_x21_status_t;
typedef struct pc300stats {
int hw_type;
u32 line_on;
u32 line_off;
struct net_device_stats gen_stats;
falc_t te_stats;
} pc300stats_t;
typedef struct pc300status {
int hw_type;
rsv_x21_status_t gen_status;
falc_status_t te_status;
} pc300status_t;
typedef struct pc300loopback {
char loop_type;
char loop_on;
} pc300loopback_t;
typedef struct pc300patterntst {
char patrntst_on; /* 0 - off; 1 - on; 2 - read num_errors */
u16 num_errors;
} pc300patterntst_t;
typedef struct pc300dev {
struct pc300ch *chan;
u8 trace_on;
u32 line_on; /* DCD(X.21, RSV) / sync(TE) change counters */
u32 line_off;
char name[16];
struct net_device *dev;
#ifdef CONFIG_PC300_MLPPP
void *cpc_tty; /* information to PC300 TTY driver */
#endif
}pc300dev_t;
typedef struct pc300hw {
int type; /* RSV, X21, etc. */
int bus; /* Bus (PCI, PMC, etc.) */
int nchan; /* number of channels */
int irq; /* interrupt request level */
u32 clock; /* Board clock */
u8 cpld_id; /* CPLD ID (TE only) */
u16 cpld_reg1; /* CPLD reg 1 (TE only) */
u16 cpld_reg2; /* CPLD reg 2 (TE only) */
u16 gpioc_reg; /* PLX GPIOC reg */
u16 intctl_reg; /* PLX Int Ctrl/Status reg */
u32 iophys; /* PLX registers I/O base */
u32 iosize; /* PLX registers I/O size */
u32 plxphys; /* PLX registers MMIO base (physical) */
void __iomem * plxbase; /* PLX registers MMIO base (virtual) */
u32 plxsize; /* PLX registers MMIO size */
u32 scaphys; /* SCA registers MMIO base (physical) */
void __iomem * scabase; /* SCA registers MMIO base (virtual) */
u32 scasize; /* SCA registers MMIO size */
u32 ramphys; /* On-board RAM MMIO base (physical) */
void __iomem * rambase; /* On-board RAM MMIO base (virtual) */
u32 alloc_ramsize; /* RAM MMIO size allocated by the PCI bridge */
u32 ramsize; /* On-board RAM MMIO size */
u32 falcphys; /* FALC registers MMIO base (physical) */
void __iomem * falcbase;/* FALC registers MMIO base (virtual) */
u32 falcsize; /* FALC registers MMIO size */
} pc300hw_t;
typedef struct pc300chconf {
sync_serial_settings phys_settings; /* Clock type/rate (in bps),
loopback mode */
raw_hdlc_proto proto_settings; /* Encoding, parity (CRC) */
u32 media; /* HW media (RS232, V.35, etc.) */
u32 proto; /* Protocol (PPP, X.25, etc.) */
/* TE-specific parameters */
u8 lcode; /* Line Code (AMI, B8ZS, etc.) */
u8 fr_mode; /* Frame Mode (ESF, D4, etc.) */
u8 lbo; /* Line Build Out */
u8 rx_sens; /* Rx Sensitivity (long- or short-haul) */
u32 tslot_bitmap; /* bit[i]=1 => timeslot _i_ is active */
} pc300chconf_t;
typedef struct pc300ch {
struct pc300 *card;
int channel;
pc300dev_t d;
pc300chconf_t conf;
u8 tx_first_bd; /* First TX DMA block descr. w/ data */
u8 tx_next_bd; /* Next free TX DMA block descriptor */
u8 rx_first_bd; /* First free RX DMA block descriptor */
u8 rx_last_bd; /* Last free RX DMA block descriptor */
u8 nfree_tx_bd; /* Number of free TX DMA block descriptors */
falc_t falc; /* FALC structure (TE only) */
} pc300ch_t;
typedef struct pc300 {
pc300hw_t hw; /* hardware config. */
pc300ch_t chan[PC300_MAXCHAN];
spinlock_t card_lock;
} pc300_t;
typedef struct pc300conf {
pc300hw_t hw;
pc300chconf_t conf;
} pc300conf_t;
/* DEV ioctl() commands */
#define N_SPPP_IOCTLS 2
enum pc300_ioctl_cmds {
SIOCCPCRESERVED = (SIOCDEVPRIVATE + N_SPPP_IOCTLS),
SIOCGPC300CONF,
SIOCSPC300CONF,
SIOCGPC300STATUS,
SIOCGPC300FALCSTATUS,
SIOCGPC300UTILSTATS,
SIOCGPC300UTILSTATUS,
SIOCSPC300TRACE,
SIOCSPC300LOOPBACK,
SIOCSPC300PATTERNTEST,
};
/* Loopback types - PC300/TE boards */
enum pc300_loopback_cmds {
PC300LOCLOOP = 1,
PC300REMLOOP,
PC300PAYLOADLOOP,
PC300GENLOOPUP,
PC300GENLOOPDOWN,
};
/* Control Constant Definitions */
#define PC300_RSV 0x01
#define PC300_X21 0x02
#define PC300_TE 0x03
#define PC300_PCI 0x00
#define PC300_PMC 0x01
#define PC300_LC_AMI 0x01
#define PC300_LC_B8ZS 0x02
#define PC300_LC_NRZ 0x03
#define PC300_LC_HDB3 0x04
/* Framing (T1) */
#define PC300_FR_ESF 0x01
#define PC300_FR_D4 0x02
#define PC300_FR_ESF_JAPAN 0x03
/* Framing (E1) */
#define PC300_FR_MF_CRC4 0x04
#define PC300_FR_MF_NON_CRC4 0x05
#define PC300_FR_UNFRAMED 0x06
#define PC300_LBO_0_DB 0x00
#define PC300_LBO_7_5_DB 0x01
#define PC300_LBO_15_DB 0x02
#define PC300_LBO_22_5_DB 0x03
#define PC300_RX_SENS_SH 0x01
#define PC300_RX_SENS_LH 0x02
#define PC300_TX_TIMEOUT (2*HZ)
#define PC300_TX_QUEUE_LEN 100
#define PC300_DEF_MTU 1600
/* Function Prototypes */
int cpc_open(struct net_device *dev);
#endif /* _PC300_H */
| {
"pile_set_name": "Github"
} |
<?php
namespace Test\Constants;
use Test\Analyzer;
include_once dirname(__DIR__, 2).'/Test/Analyzer.php';
class InvalidName extends Analyzer {
/* 4 methods */
public function testConstants_InvalidName01() { $this->generic_test('Constants_InvalidName.01'); }
public function testConstants_InvalidName02() { $this->generic_test('Constants_InvalidName.02'); }
public function testConstants_InvalidName03() { $this->generic_test('Constants_InvalidName.03'); }
public function testConstants_InvalidName04() { $this->generic_test('Constants_InvalidName.04'); }
}
?> | {
"pile_set_name": "Github"
} |
# 201909: disabled due to hassles with MonadFail in JournalReader.hs.
# Feel free to work on this if you still need GHC 7 support.
# stack build plan using GHC 7.10.3
# This is unlikely to work on OSX Sierra+ due to https://ghc.haskell.org/trac/ghc/ticket/12479
resolver: lts-6.35
packages:
- hledger-lib
- hledger
# 20181024: hledger-ui plan has stopped working due to some change related to config-ini
# (we need megaparsec 7, only config-ini's 0.2.3.0 version allows that, but it requires a newer base/GHC).
#- hledger-ui
- hledger-web
extra-deps:
# avoid no hashable instance for AccountName from doctests
- hashtables-1.2.3.1
# Many newer versions to allow using the latest base-compat with all ghc versions.
# This is just the first workable install plan I found.
- adjunctions-4.4
- aeson-1.3.1.1
- aeson-compat-0.3.7.1
- attoparsec-0.13.2.2
- attoparsec-iso8601-1.0.0.0
- base-compat-0.10.1
- base-compat-batteries-0.10.1
- base-orphans-0.7
- bifunctors-5.5.2
- brick-0.37.1
- cassava-megaparsec-2.0.0
- config-ini-0.2.3.0
- criterion-1.4.1.0
- data-clist-0.1.2.1
- directory-1.2.7.0
- doctest-0.16.0
- exceptions-0.10.0
- extra-1.6.17
- fgl-5.5.4.0
- free-5.0.2
- generics-sop-0.3.2.0
- Glob-0.9.2
- hashable-1.2.7.0
- http-media-0.7.1.2
- http-types-0.12.1
- insert-ordered-containers-0.2.1.0
- integer-logarithms-1.0.2.1
- kan-extensions-5.1
- lens-4.16.1
- math-functions-0.2.1.0
- megaparsec-7.0.1
- microstache-1.0.1.1
- mmorph-1.1.2
- monad-control-1.0.2.3
- network-2.6.3.5
- optparse-applicative-0.14.2.0
- parser-combinators-1.0.0
- persistent-2.7.0
- persistent-template-2.5.4
- process-1.2.3.0
- profunctors-5.2.2
- resourcet-1.1.11
- scientific-0.3.6.2
- semigroupoids-5.2.2
- semigroups-0.18.4
- singleton-bool-0.1.4
- statistics-0.14.0.2
- tagged-0.8.5
- text-1.2.3.0
- text-zipper-0.10.1
- th-abstraction-0.2.6.0
- transformers-compat-0.6.1.4
- unliftio-core-0.1.1.0
- unordered-containers-0.2.9.0
- vty-5.21
- word-wrap-0.4.1
- yesod-persistent-1.4.2
# hledger-ui
# newer fsnotify has a different api and may be more robust
- fsnotify-0.3.0.1
- shelly-1.7.2
| {
"pile_set_name": "Github"
} |
<!-- Do not edit this file. It is automatically generated by API Documenter. -->
[Home](./index.md) > [puppeteer](./puppeteer.md) > [Page](./puppeteer.page.md)
## Page class
Page provides methods to interact with a single tab or [extension background page](https://developer.chrome.com/extensions/background_pages) in Chromium.
<b>Signature:</b>
```typescript
export declare class Page extends EventEmitter
```
<b>Extends:</b> [EventEmitter](./puppeteer.eventemitter.md)
## Remarks
One Browser instance might have multiple Page instances.
The constructor for this class is marked as internal. Third-party code should not call the constructor directly or create subclasses that extend the `Page` class.
## Example 1
This example creates a page, navigates it to a URL, and then \* saves a screenshot:
```js
const puppeteer = require('puppeteer');
(async () => {
const browser = await puppeteer.launch();
const page = await browser.newPage();
await page.goto('https://example.com');
await page.screenshot({path: 'screenshot.png'});
await browser.close();
})();
```
The Page class extends from Puppeteer's [EventEmitter](./puppeteer.eventemitter.md) class and will emit various events which are documented in the [PageEmittedEvents](./puppeteer.pageemittedevents.md) enum.
## Example 2
This example logs a message for a single page `load` event:
```js
page.once('load', () => console.log('Page loaded!'));
```
To unsubscribe from events use the `off` method:
```js
function logRequest(interceptedRequest) {
console.log('A request was made:', interceptedRequest.url());
}
page.on('request', logRequest);
// Sometime later...
page.off('request', logRequest);
```
## Properties
| Property | Modifiers | Type | Description |
| --- | --- | --- | --- |
| [accessibility](./puppeteer.page.accessibility.md) | | [Accessibility](./puppeteer.accessibility.md) | |
| [coverage](./puppeteer.page.coverage.md) | | [Coverage](./puppeteer.coverage.md) | |
| [keyboard](./puppeteer.page.keyboard.md) | | [Keyboard](./puppeteer.keyboard.md) | |
| [mouse](./puppeteer.page.mouse.md) | | [Mouse](./puppeteer.mouse.md) | |
| [touchscreen](./puppeteer.page.touchscreen.md) | | [Touchscreen](./puppeteer.touchscreen.md) | |
| [tracing](./puppeteer.page.tracing.md) | | [Tracing](./puppeteer.tracing.md) | |
## Methods
| Method | Modifiers | Description |
| --- | --- | --- |
| [$(selector)](./puppeteer.page._.md) | | Runs <code>document.querySelector</code> within the page. If no element matches the selector, the return value resolves to <code>null</code>. |
| [$$(selector)](./puppeteer.page.__.md) | | |
| [$$eval(selector, pageFunction, args)](./puppeteer.page.__eval.md) | | This method runs <code>Array.from(document.querySelectorAll(selector))</code> within the page and passes the result as the first argument to the <code>pageFunction</code>. |
| [$eval(selector, pageFunction, args)](./puppeteer.page._eval.md) | | This method runs <code>document.querySelector</code> within the page and passes the result as the first argument to the <code>pageFunction</code>. |
| [$x(expression)](./puppeteer.page._x.md) | | |
| [addScriptTag(options)](./puppeteer.page.addscripttag.md) | | |
| [addStyleTag(options)](./puppeteer.page.addstyletag.md) | | |
| [authenticate(credentials)](./puppeteer.page.authenticate.md) | | |
| [bringToFront()](./puppeteer.page.bringtofront.md) | | |
| [browser()](./puppeteer.page.browser.md) | | |
| [browserContext()](./puppeteer.page.browsercontext.md) | | |
| [click(selector, options)](./puppeteer.page.click.md) | | |
| [close(options)](./puppeteer.page.close.md) | | |
| [content()](./puppeteer.page.content.md) | | |
| [cookies(urls)](./puppeteer.page.cookies.md) | | If no URLs are specified, this method returns cookies for the current page URL. If URLs are specified, only cookies for those URLs are returned. |
| [deleteCookie(cookies)](./puppeteer.page.deletecookie.md) | | |
| [emulate(options)](./puppeteer.page.emulate.md) | | |
| [emulateIdleState(overrides)](./puppeteer.page.emulateidlestate.md) | | Emulates the idle state. If no arguments set, clears idle state emulation. |
| [emulateMediaFeatures(features)](./puppeteer.page.emulatemediafeatures.md) | | |
| [emulateMediaType(type)](./puppeteer.page.emulatemediatype.md) | | |
| [emulateTimezone(timezoneId)](./puppeteer.page.emulatetimezone.md) | | |
| [emulateVisionDeficiency(type)](./puppeteer.page.emulatevisiondeficiency.md) | | Simulates the given vision deficiency on the page. |
| [evaluate(pageFunction, args)](./puppeteer.page.evaluate.md) | | |
| [evaluateHandle(pageFunction, args)](./puppeteer.page.evaluatehandle.md) | | |
| [evaluateOnNewDocument(pageFunction, args)](./puppeteer.page.evaluateonnewdocument.md) | | |
| [exposeFunction(name, puppeteerFunction)](./puppeteer.page.exposefunction.md) | | |
| [focus(selector)](./puppeteer.page.focus.md) | | |
| [frames()](./puppeteer.page.frames.md) | | |
| [goBack(options)](./puppeteer.page.goback.md) | | |
| [goForward(options)](./puppeteer.page.goforward.md) | | |
| [goto(url, options)](./puppeteer.page.goto.md) | | |
| [hover(selector)](./puppeteer.page.hover.md) | | |
| [isClosed()](./puppeteer.page.isclosed.md) | | |
| [isJavaScriptEnabled()](./puppeteer.page.isjavascriptenabled.md) | | |
| [mainFrame()](./puppeteer.page.mainframe.md) | | |
| [metrics()](./puppeteer.page.metrics.md) | | |
| [pdf(options)](./puppeteer.page.pdf.md) | | Generatees a PDF of the page with the <code>print</code> CSS media type. |
| [queryObjects(prototypeHandle)](./puppeteer.page.queryobjects.md) | | This method iterates the JavaScript heap and finds all objects with the given prototype. |
| [reload(options)](./puppeteer.page.reload.md) | | |
| [screenshot(options)](./puppeteer.page.screenshot.md) | | |
| [select(selector, values)](./puppeteer.page.select.md) | | |
| [setBypassCSP(enabled)](./puppeteer.page.setbypasscsp.md) | | |
| [setCacheEnabled(enabled)](./puppeteer.page.setcacheenabled.md) | | |
| [setContent(html, options)](./puppeteer.page.setcontent.md) | | |
| [setCookie(cookies)](./puppeteer.page.setcookie.md) | | |
| [setDefaultNavigationTimeout(timeout)](./puppeteer.page.setdefaultnavigationtimeout.md) | | |
| [setDefaultTimeout(timeout)](./puppeteer.page.setdefaulttimeout.md) | | |
| [setExtraHTTPHeaders(headers)](./puppeteer.page.setextrahttpheaders.md) | | |
| [setGeolocation(options)](./puppeteer.page.setgeolocation.md) | | Sets the page's geolocation. |
| [setJavaScriptEnabled(enabled)](./puppeteer.page.setjavascriptenabled.md) | | |
| [setOfflineMode(enabled)](./puppeteer.page.setofflinemode.md) | | |
| [setRequestInterception(value)](./puppeteer.page.setrequestinterception.md) | | |
| [setUserAgent(userAgent)](./puppeteer.page.setuseragent.md) | | |
| [setViewport(viewport)](./puppeteer.page.setviewport.md) | | |
| [tap(selector)](./puppeteer.page.tap.md) | | |
| [target()](./puppeteer.page.target.md) | | |
| [title()](./puppeteer.page.title.md) | | |
| [type(selector, text, options)](./puppeteer.page.type.md) | | |
| [url()](./puppeteer.page.url.md) | | |
| [viewport()](./puppeteer.page.viewport.md) | | |
| [waitFor(selectorOrFunctionOrTimeout, options, args)](./puppeteer.page.waitfor.md) | | |
| [waitForFileChooser(options)](./puppeteer.page.waitforfilechooser.md) | | |
| [waitForFunction(pageFunction, options, args)](./puppeteer.page.waitforfunction.md) | | |
| [waitForNavigation(options)](./puppeteer.page.waitfornavigation.md) | | |
| [waitForRequest(urlOrPredicate, options)](./puppeteer.page.waitforrequest.md) | | |
| [waitForResponse(urlOrPredicate, options)](./puppeteer.page.waitforresponse.md) | | |
| [waitForSelector(selector, options)](./puppeteer.page.waitforselector.md) | | |
| [waitForTimeout(milliseconds)](./puppeteer.page.waitfortimeout.md) | | Causes your script to wait for the given number of milliseconds. |
| [waitForXPath(xpath, options)](./puppeteer.page.waitforxpath.md) | | |
| [workers()](./puppeteer.page.workers.md) | | |
| {
"pile_set_name": "Github"
} |
// Copyright 2013-2015 Pervasive Displays, Inc.
//
// 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.
#include <Arduino.h>
#include <limits.h>
#include <SPI.h>
#include "EPD_V230_G2.h"
// delays - more consistent naming
#define Delay_ms(ms) delay(ms)
#define Delay_us(us) delayMicroseconds(us)
// inline arrays
#define ARRAY(type, ...) ((type[]){__VA_ARGS__})
#define CU8(...) (ARRAY(const uint8_t, __VA_ARGS__))
// values for border byte
#define BORDER_BYTE_BLACK 0xff
#define BORDER_BYTE_WHITE 0xaa
#define BORDER_BYTE_NULL 0x00
static void SPI_on(void);
static void SPI_off(void);
static void SPI_put(uint8_t c);
static void SPI_send(uint8_t cs_pin, const uint8_t *buffer, uint16_t length);
static uint8_t SPI_read(uint8_t cs_pin, const uint8_t *buffer, uint16_t length);
EPD_Class::EPD_Class(EPD_size _size,
uint8_t panel_on_pin,
uint8_t border_pin,
uint8_t discharge_pin,
uint8_t reset_pin,
uint8_t busy_pin,
uint8_t chip_select_pin) :
EPD_Pin_PANEL_ON(panel_on_pin),
EPD_Pin_BORDER(border_pin),
EPD_Pin_DISCHARGE(discharge_pin),
EPD_Pin_RESET(reset_pin),
EPD_Pin_BUSY(busy_pin),
EPD_Pin_EPD_CS(chip_select_pin),
size(_size) {
this->lines_per_display = 96;
this->dots_per_line = 128;
this->bytes_per_line = 128 / 8;
this->bytes_per_scan = 96 / 4;
this->voltage_level = 0x03;
this->setFactor(); // ensure default temperature
// display size dependant items
{
static uint8_t cs[] = {0x72, 0x00, 0x00, 0x00, 0x00, 0x00, 0x0f, 0xff, 0x00};
this->channel_select = cs;
this->channel_select_length = sizeof(cs);
}
// set up size structure
switch (size) {
default:
case EPD_1_44: // default so no change
break;
case EPD_2_0: {
this->lines_per_display = 96;
this->dots_per_line = 200;
this->bytes_per_line = 200 / 8;
this->bytes_per_scan = 96 / 4;
static uint8_t cs[] = {0x72, 0x00, 0x00, 0x00, 0x00, 0x01, 0xff, 0xe0, 0x00};
this->channel_select = cs;
this->channel_select_length = sizeof(cs);
this->voltage_level = 0x03;
break;
}
case EPD_2_7: {
this->lines_per_display = 176;
this->dots_per_line = 264;
this->bytes_per_line = 264 / 8;
this->bytes_per_scan = 176 / 4;
static uint8_t cs[] = {0x72, 0x00, 0x00, 0x00, 0x7f, 0xff, 0xfe, 0x00, 0x00};
this->channel_select = cs;
this->channel_select_length = sizeof(cs);
this->voltage_level = 0x00;
break;
}
}
}
void EPD_Class::setFactor(int temperature) {
// stage1: repeat, step, block
// stage2: repeat, t1, t2
// stage3: repeat, step, block
static const EPD_Class::compensation_type compensation_144[3] = {
{ 2, 6, 42, 4, 392, 392, 2, 6, 42 }, // 0 ... 10 Celcius
{ 4, 2, 16, 4, 155, 155, 4, 2, 16 }, // 10 ... 40 Celcius
{ 4, 2, 16, 4, 155, 155, 4, 2, 16 } // 40 ... 50 Celcius
};
static const EPD_Class::compensation_type compensation_200[3] = {
{ 2, 6, 42, 4, 392, 392, 2, 6, 42 }, // 0 ... 10 Celcius
{ 2, 2, 48, 4, 196, 196, 2, 2, 48 }, // 10 ... 40 Celcius
{ 4, 2, 48, 4, 196, 196, 4, 2, 48 } // 40 ... 50 Celcius
};
static const EPD_Class::compensation_type compensation_270[3] = {
{ 2, 8, 64, 4, 392, 392, 2, 8, 64 }, // 0 ... 10 Celcius
{ 2, 4, 32, 4, 196, 196, 2, 4, 32 }, // 10 ... 40 Celcius
{ 4, 8, 64, 4, 196, 196, 4, 8, 64 } // 40 ... 50 Celcius
};
if (temperature < 10) {
this->temperature_offset = 0;
} else if (temperature > 40) {
this->temperature_offset = 2;
} else {
this->temperature_offset = 1;
}
switch (this->size) {
default:
case EPD_1_44:
this->compensation = &compensation_144[this->temperature_offset];
break;
case EPD_2_0: {
this->compensation = &compensation_200[this->temperature_offset];
break;
}
case EPD_2_7: {
this->compensation = &compensation_270[this->temperature_offset];
break;
}
}
}
void EPD_Class::begin(void) {
// assume ok
this->status = EPD_OK;
// power up sequence
digitalWrite(this->EPD_Pin_RESET, LOW);
digitalWrite(this->EPD_Pin_PANEL_ON, LOW);
digitalWrite(this->EPD_Pin_DISCHARGE, LOW);
digitalWrite(this->EPD_Pin_BORDER, LOW);
digitalWrite(this->EPD_Pin_EPD_CS, LOW);
SPI_on();
Delay_ms(5);
digitalWrite(this->EPD_Pin_PANEL_ON, HIGH);
Delay_ms(10);
digitalWrite(this->EPD_Pin_RESET, HIGH);
digitalWrite(this->EPD_Pin_BORDER, HIGH);
digitalWrite(this->EPD_Pin_EPD_CS, HIGH);
Delay_ms(5);
digitalWrite(this->EPD_Pin_RESET, LOW);
Delay_ms(5);
digitalWrite(this->EPD_Pin_RESET, HIGH);
Delay_ms(5);
// wait for COG to become ready
while (HIGH == digitalRead(this->EPD_Pin_BUSY)) {
Delay_us(10);
}
// read the COG ID
int cog_id = SPI_read(this->EPD_Pin_EPD_CS, CU8(0x71, 0x00), 2);
cog_id = SPI_read(this->EPD_Pin_EPD_CS, CU8(0x71, 0x00), 2);
if (0x02 != (0x0f & cog_id)) {
this->status = EPD_UNSUPPORTED_COG;
this->power_off();
return;
}
// Disable OE
SPI_send(this->EPD_Pin_EPD_CS, CU8(0x70, 0x02), 2);
SPI_send(this->EPD_Pin_EPD_CS, CU8(0x72, 0x40), 2);
// check breakage
SPI_send(this->EPD_Pin_EPD_CS, CU8(0x70, 0x0f), 2);
int broken_panel = SPI_read(this->EPD_Pin_EPD_CS, CU8(0x73, 0x00), 2);
if (0x00 == (0x80 & broken_panel)) {
this->status = EPD_PANEL_BROKEN;
this->power_off();
return;
}
// power saving mode
SPI_send(this->EPD_Pin_EPD_CS, CU8(0x70, 0x0b), 2);
SPI_send(this->EPD_Pin_EPD_CS, CU8(0x72, 0x02), 2);
// channel select
SPI_send(this->EPD_Pin_EPD_CS, CU8(0x70, 0x01), 2);
SPI_send(this->EPD_Pin_EPD_CS, this->channel_select, this->channel_select_length);
// high power mode osc
SPI_send(this->EPD_Pin_EPD_CS, CU8(0x70, 0x07), 2);
SPI_send(this->EPD_Pin_EPD_CS, CU8(0x72, 0xd1), 2);
// power setting
SPI_send(this->EPD_Pin_EPD_CS, CU8(0x70, 0x08), 2);
SPI_send(this->EPD_Pin_EPD_CS, CU8(0x72, 0x02), 2);
// Vcom level
SPI_send(this->EPD_Pin_EPD_CS, CU8(0x70, 0x09), 2);
SPI_send(this->EPD_Pin_EPD_CS, CU8(0x72, 0xc2), 2);
// power setting
SPI_send(this->EPD_Pin_EPD_CS, CU8(0x70, 0x04), 2);
SPI_send(this->EPD_Pin_EPD_CS, CU8(0x72, 0x03), 2);
// driver latch on
SPI_send(this->EPD_Pin_EPD_CS, CU8(0x70, 0x03), 2);
SPI_send(this->EPD_Pin_EPD_CS, CU8(0x72, 0x01), 2);
// driver latch off
SPI_send(this->EPD_Pin_EPD_CS, CU8(0x70, 0x03), 2);
SPI_send(this->EPD_Pin_EPD_CS, CU8(0x72, 0x00), 2);
Delay_ms(5);
bool dc_ok = false;
for (int i = 0; i < 4; ++i) {
// charge pump positive voltage on - VGH/VDL on
SPI_send(this->EPD_Pin_EPD_CS, CU8(0x70, 0x05), 2);
SPI_send(this->EPD_Pin_EPD_CS, CU8(0x72, 0x01), 2);
Delay_ms(240);
// charge pump negative voltage on - VGL/VDL on
SPI_send(this->EPD_Pin_EPD_CS, CU8(0x70, 0x05), 2);
SPI_send(this->EPD_Pin_EPD_CS, CU8(0x72, 0x03), 2);
Delay_ms(40);
// charge pump Vcom on - Vcom driver on
SPI_send(this->EPD_Pin_EPD_CS, CU8(0x70, 0x05), 2);
SPI_send(this->EPD_Pin_EPD_CS, CU8(0x72, 0x0f), 2);
Delay_ms(40);
// check DC/DC
SPI_send(this->EPD_Pin_EPD_CS, CU8(0x70, 0x0f), 2);
int dc_state = SPI_read(this->EPD_Pin_EPD_CS, CU8(0x73, 0x00), 2);
if (0x40 == (0x40 & dc_state)) {
dc_ok = true;
break;
}
}
if (!dc_ok) {
this->status = EPD_DC_FAILED;
this->power_off();
return;
}
// output enable to disable
SPI_send(this->EPD_Pin_EPD_CS, CU8(0x70, 0x02), 2);
SPI_send(this->EPD_Pin_EPD_CS, CU8(0x72, 0x40), 2);
SPI_off();
}
void EPD_Class::end(void) {
this->nothing_frame();
if (EPD_1_44 == this->size || EPD_2_0 == this->size) {
this->border_dummy_line();
}
this->dummy_line();
if (EPD_2_7 == this->size) {
// only pulse border pin for 2.70" EPD
digitalWrite(this->EPD_Pin_BORDER, LOW);
Delay_ms(200);
digitalWrite(this->EPD_Pin_BORDER, HIGH);
}
SPI_on();
// check DC/DC
SPI_send(this->EPD_Pin_EPD_CS, CU8(0x70, 0x0f), 2);
int dc_state = SPI_read(this->EPD_Pin_EPD_CS, CU8(0x73, 0x00), 2);
if (0x40 != (0x40 & dc_state)) {
this->status = EPD_DC_FAILED;
this->power_off();
return;
}
// latch reset turn on
SPI_send(this->EPD_Pin_EPD_CS, CU8(0x70, 0x03), 2);
SPI_send(this->EPD_Pin_EPD_CS, CU8(0x72, 0x01), 2);
// output enable off
SPI_send(this->EPD_Pin_EPD_CS, CU8(0x70, 0x02), 2);
SPI_send(this->EPD_Pin_EPD_CS, CU8(0x72, 0x05), 2);
// power off charge pump Vcom
SPI_send(this->EPD_Pin_EPD_CS, CU8(0x70, 0x05), 2);
SPI_send(this->EPD_Pin_EPD_CS, CU8(0x72, 0x03), 2);
// power off charge pump neg voltage
SPI_send(this->EPD_Pin_EPD_CS, CU8(0x70, 0x05), 2);
SPI_send(this->EPD_Pin_EPD_CS, CU8(0x72, 0x01), 2);
Delay_ms(240);
// power off all charge pumps
SPI_send(this->EPD_Pin_EPD_CS, CU8(0x70, 0x05), 2);
SPI_send(this->EPD_Pin_EPD_CS, CU8(0x72, 0x00), 2);
// turn of osc
SPI_send(this->EPD_Pin_EPD_CS, CU8(0x70, 0x07), 2);
SPI_send(this->EPD_Pin_EPD_CS, CU8(0x72, 0x01), 2);
// discharge internal on
SPI_send(this->EPD_Pin_EPD_CS, CU8(0x70, 0x04), 2);
SPI_send(this->EPD_Pin_EPD_CS, CU8(0x72, 0x83), 2);
Delay_ms(30);
// discharge internal off
//SPI_send(this->EPD_Pin_EPD_CS, CU8(0x70, 0x04), 2);
//SPI_send(this->EPD_Pin_EPD_CS, CU8(0x72, 0x00), 2);
power_off();
}
void EPD_Class::power_off(void) {
// turn of power and all signals
digitalWrite(this->EPD_Pin_RESET, LOW);
digitalWrite(this->EPD_Pin_PANEL_ON, LOW);
digitalWrite(this->EPD_Pin_BORDER, LOW);
// ensure SPI MOSI and CLOCK are Low before CS Low
SPI_off();
digitalWrite(this->EPD_Pin_EPD_CS, LOW);
// pulse discharge pin
digitalWrite(this->EPD_Pin_DISCHARGE, HIGH);
Delay_ms(150);
digitalWrite(this->EPD_Pin_DISCHARGE, LOW);
}
// One frame of data is the number of lines * rows. For example:
// The 1.44” frame of data is 96 lines * 128 dots.
// The 2” frame of data is 96 lines * 200 dots.
// The 2.7” frame of data is 176 lines * 264 dots.
// the image is arranged by line which matches the display size
// so smallest would have 96 * 32 bytes
void EPD_Class::frame_fixed_timed(uint8_t fixed_value, long stage_time) {
do {
unsigned long t_start = millis();
for (uint8_t line = 0; line < this->lines_per_display ; ++line) {
this->line(this->lines_per_display - line - 1, 0, fixed_value, false);
}
unsigned long t_end = millis();
if (t_end > t_start) {
stage_time -= t_end - t_start;
} else {
stage_time -= t_start - t_end + 1 + ULONG_MAX;
}
} while (stage_time > 0);
}
void EPD_Class::frame_fixed_13(uint8_t value, EPD_stage stage) {
int repeat;
int step;
int block;
if (EPD_inverse == stage) { // stage 1
repeat = this->compensation->stage1_repeat;
step = this->compensation->stage1_step;
block = this->compensation->stage1_block;
} else { // stage 3
repeat = this->compensation->stage3_repeat;
step = this->compensation->stage3_step;
block = this->compensation->stage3_block;
}
int total_lines = this->lines_per_display;
for (int n = 0; n < repeat; ++n) {
int block_begin = 0;
int block_end = 0;
while (block_begin < total_lines) {
block_end += step;
block_begin = block_end - block;
if (block_begin < 0) {
block_begin = 0;
} else if (block_begin >= total_lines) {
break;
}
bool full_block = (block_end - block_begin == block);
for (int line = block_begin; line < block_end; ++line) {
if (line >= total_lines) {
break;
}
if (full_block && (line < (block_begin + step))) {
this->line(line, 0, 0x00, false, EPD_normal);
} else {
this->line(line, 0, value, false, EPD_normal);
}
}
}
}
}
void EPD_Class::frame_data_13(const uint8_t *image, EPD_stage stage, bool read_progmem) {
int repeat;
int step;
int block;
if (EPD_inverse == stage) { // stage 1
repeat = this->compensation->stage1_repeat;
step = this->compensation->stage1_step;
block = this->compensation->stage1_block;
} else { // stage 3
repeat = this->compensation->stage3_repeat;
step = this->compensation->stage3_step;
block = this->compensation->stage3_block;
}
int total_lines = this->lines_per_display;
for (int n = 0; n < repeat; ++n) {
int block_begin = 0;
int block_end = 0;
while (block_begin < total_lines) {
block_end += step;
block_begin = block_end - block;
if (block_begin < 0) {
block_begin = 0;
} else if (block_begin >= total_lines) {
break;
}
bool full_block = (block_end - block_begin == block);
for (int line = block_begin; line < block_end; ++line) {
if (line >= total_lines) {
break;
}
if (full_block && (line < (block_begin + step))) {
this->line(line, 0, 0x00, false, EPD_normal);
} else {
this->line(line, &image[line * this->bytes_per_line], 0x00, read_progmem, stage);
}
}
}
}
}
void EPD_Class::frame_cb_13(uint32_t address, EPD_reader *reader, EPD_stage stage) {
uint8_t buffer[264 / 8]; // allows for 2.70" panel
int repeat;
int step;
int block;
if (EPD_inverse == stage) { // stage 1
repeat = this->compensation->stage1_repeat;
step = this->compensation->stage1_step;
block = this->compensation->stage1_block;
} else { // stage 3
repeat = this->compensation->stage3_repeat;
step = this->compensation->stage3_step;
block = this->compensation->stage3_block;
}
int total_lines = this->lines_per_display;
for (int n = 0; n < repeat; ++n) {
int block_begin = 0;
int block_end = 0;
while (block_begin < total_lines) {
block_end += step;
block_begin = block_end - block;
if (block_begin < 0) {
block_begin = 0;
} else if (block_begin >= total_lines) {
break;
}
bool full_block = (block_end - block_begin == block);
for (int line = block_begin; line < block_end; ++line) {
if (line >= total_lines) {
break;
}
if (full_block && (line < (block_begin + step))) {
this->line(line, 0, 0x00, false, EPD_normal);
} else {
reader(buffer, address + line * this->bytes_per_line, this->bytes_per_line);
this->line(line, buffer, 0, false, stage);
}
}
}
}
}
void EPD_Class::frame_stage2(void) {
for (uint16_t i = 0; i < this->compensation->stage2_repeat; ++i) {
this->frame_fixed_timed(0xff, this->compensation->stage2_t1);
this->frame_fixed_timed(0xaa, this->compensation->stage2_t2);
}
}
void EPD_Class::nothing_frame(void) {
for (uint16_t line = 0; line < this->lines_per_display; ++line) {
this->line(line, 0, 0x00, false, EPD_normal, EPD_BORDER_BYTE_NULL, true);
}
}
void EPD_Class::dummy_line(void) {
this->line(0x7fffu, 0, 0x00, false, EPD_normal, EPD_BORDER_BYTE_NULL, true);
}
void EPD_Class::border_dummy_line(void) {
this->line(0x7fffu, 0, 0x00, false, EPD_normal, EPD_BORDER_BYTE_BLACK);
Delay_ms(40);
this->line(0x7fffu, 0, 0x00, false, EPD_normal, EPD_BORDER_BYTE_WHITE);
Delay_ms(200);
}
void EPD_Class::line(uint16_t line, const uint8_t *data, uint8_t fixed_value,
bool read_progmem, EPD_stage stage, uint8_t border_byte,
bool set_voltage_limit) {
SPI_on();
if (set_voltage_limit) {
// charge pump voltage level reduce voltage shift
SPI_send(this->EPD_Pin_EPD_CS, CU8(0x70, 0x04), 2);
const uint8_t b[2] = {0x72, this->voltage_level};
SPI_send(this->EPD_Pin_EPD_CS, b, sizeof(b));
}
// send data
SPI_send(this->EPD_Pin_EPD_CS, CU8(0x70, 0x0a), 2);
Delay_us(10);
// CS low
digitalWrite(this->EPD_Pin_EPD_CS, LOW);
SPI_put(0x72);
// border byte
SPI_put(border_byte);
// odd pixels
for (uint16_t b = this->bytes_per_line; b > 0; --b) {
if (0 != data) {
#if !defined(__AVR__)
uint8_t pixels = data[b - 1];
#else
// AVR has multiple memory spaces
uint8_t pixels;
if (read_progmem) {
pixels = pgm_read_byte_near(data + b - 1);
} else {
pixels = data[b - 1];
}
#endif
switch(stage) {
case EPD_inverse: // B -> W, W -> B
pixels ^= 0xff;
break;
case EPD_normal: // B -> B, W -> W
break;
}
pixels = 0xaa | pixels;
SPI_put(pixels);
} else {
SPI_put(fixed_value);
}
}
// scan line
int scan_pos = (this->lines_per_display - line - 1) >> 2;
int scan_shift = (line & 0x03) << 1;
for (unsigned int b = 0; b < this->bytes_per_scan; ++b) {
if (scan_pos == (int) b) {
SPI_put(0x03 << scan_shift);
} else {
SPI_put(0x00);
}
}
// even pixels
for (uint16_t b = 0; b < this->bytes_per_line; ++b) {
if (0 != data) {
#if !defined(__AVR__)
uint8_t pixels = data[b];
#else
// AVR has multiple memory spaces
uint8_t pixels;
if (read_progmem) {
pixels = pgm_read_byte_near(data + b);
} else {
pixels = data[b];
}
#endif
switch(stage) {
case EPD_inverse: // B -> W, W -> B (Current Image)
pixels ^= 0xff;
break;
case EPD_normal: // B -> B, W -> W (New Image)
break;
}
pixels >>= 1;
pixels |= 0xaa;
pixels = ((pixels & 0xc0) >> 6)
| ((pixels & 0x30) >> 2)
| ((pixels & 0x0c) << 2)
| ((pixels & 0x03) << 6);
SPI_put(pixels);
} else {
SPI_put(fixed_value);
}
}
// CS high
digitalWrite(this->EPD_Pin_EPD_CS, HIGH);
// output data to panel
SPI_send(this->EPD_Pin_EPD_CS, CU8(0x70, 0x02), 2);
SPI_send(this->EPD_Pin_EPD_CS, CU8(0x72, 0x07), 2);
SPI_off();
}
static void SPI_on(void) {
SPI.end();
SPI.begin();
SPI.setBitOrder(MSBFIRST);
SPI.setDataMode(SPI_MODE0);
SPI.setClockDivider(SPI_CLOCK_DIV2);
SPI_put(0x00);
SPI_put(0x00);
Delay_us(10);
}
static void SPI_off(void) {
// SPI.begin();
// SPI.setBitOrder(MSBFIRST);
SPI.setDataMode(SPI_MODE0);
// SPI.setClockDivider(SPI_CLOCK_DIV2);
SPI_put(0x00);
SPI_put(0x00);
Delay_us(10);
SPI.end();
}
static void SPI_put(uint8_t c) {
SPI.transfer(c);
}
static void SPI_send(uint8_t cs_pin, const uint8_t *buffer, uint16_t length) {
// CS low
digitalWrite(cs_pin, LOW);
// send all data
for (uint16_t i = 0; i < length; ++i) {
SPI_put(*buffer++);
}
// CS high
digitalWrite(cs_pin, HIGH);
}
// FIXME: What is the purpose of rbuffer? It is set, but never used.
static uint8_t SPI_read(uint8_t cs_pin, const uint8_t *buffer, uint16_t length) {
// CS low
digitalWrite(cs_pin, LOW);
uint8_t rbuffer[4];
uint8_t result = 0;
// send all data
for (uint16_t i = 0; i < length; ++i) {
result = SPI.transfer(*buffer++);
if (i < 4) {
rbuffer[i] = result;
}
}
// CS high
digitalWrite(cs_pin, HIGH);
return result;
}
| {
"pile_set_name": "Github"
} |
// Copyright (c) 2010 Google Inc.
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above
// copyright notice, this list of conditions and the following disclaimer
// in the documentation and/or other materials provided with the
// distribution.
// * Neither the name of Google Inc. nor the names of its
// contributors may be used to endorse or promote products derived from
// this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#ifndef GOOGLE_BREAKPAD_CLIENT_MAC_CRASH_GENERATION_CRASH_GENERATION_CLIENT_H_
#define GOOGLE_BREAKPAD_CLIENT_MAC_CRASH_GENERATION_CRASH_GENERATION_CLIENT_H_
#include "common/mac/MachIPC.h"
namespace google_breakpad {
class CrashGenerationClient {
public:
explicit CrashGenerationClient(const char* mach_port_name)
: sender_(mach_port_name) {
}
// Request the crash server to generate a dump.
//
// Return true if the dump was successful; false otherwise.
bool RequestDumpForException(int exception_type,
int exception_code,
int exception_subcode,
mach_port_t crashing_thread);
bool RequestDump() {
return RequestDumpForException(0, 0, 0, MACH_PORT_NULL);
}
private:
MachPortSender sender_;
// Prevent copy construction and assignment.
CrashGenerationClient(const CrashGenerationClient&);
CrashGenerationClient& operator=(const CrashGenerationClient&);
};
} // namespace google_breakpad
#endif // GOOGLE_BREAKPAD_CLIENT_MAC_CRASH_GENERATION_CRASH_GENERATION_CLIENT_H_
| {
"pile_set_name": "Github"
} |
/*
* sntp.c
*
* Created on: 2014. 12. 15.
* Author: Administrator
*/
#include "../../../ioLibrary_Driver/Internet/SNTP/sntp.h"
#include <string.h>
#include "../../../ioLibrary_Driver/Ethernet/socket.h"
ntpformat NTPformat;
datetime Nowdatetime;
uint8_t ntpmessage[48];
uint8_t *data_buf;
uint8_t NTP_SOCKET;
uint8_t time_zone;
uint16_t ntp_retry_cnt=0; //counting the ntp retry number
/*
00)UTC-12:00 Baker Island, Howland Island (both uninhabited)
01) UTC-11:00 American Samoa, Samoa
02) UTC-10:00 (Summer)French Polynesia (most), United States (Aleutian Islands, Hawaii)
03) UTC-09:30 Marquesas Islands
04) UTC-09:00 Gambier Islands;(Summer)United States (most of Alaska)
05) UTC-08:00 (Summer)Canada (most of British Columbia), Mexico (Baja California)
06) UTC-08:00 United States (California, most of Nevada, most of Oregon, Washington (state))
07) UTC-07:00 Mexico (Sonora), United States (Arizona); (Summer)Canada (Alberta)
08) UTC-07:00 Mexico (Chihuahua), United States (Colorado)
09) UTC-06:00 Costa Rica, El Salvador, Ecuador (Galapagos Islands), Guatemala, Honduras
10) UTC-06:00 Mexico (most), Nicaragua;(Summer)Canada (Manitoba, Saskatchewan), United States (Illinois, most of Texas)
11) UTC-05:00 Colombia, Cuba, Ecuador (continental), Haiti, Jamaica, Panama, Peru
12) UTC-05:00 (Summer)Canada (most of Ontario, most of Quebec)
13) UTC-05:00 United States (most of Florida, Georgia, Massachusetts, most of Michigan, New York, North Carolina, Ohio, Washington D.C.)
14) UTC-04:30 Venezuela
15) UTC-04:00 Bolivia, Brazil (Amazonas), Chile (continental), Dominican Republic, Canada (Nova Scotia), Paraguay,
16) UTC-04:00 Puerto Rico, Trinidad and Tobago
17) UTC-03:30 Canada (Newfoundland)
18) UTC-03:00 Argentina; (Summer) Brazil (Brasilia, Rio de Janeiro, Sao Paulo), most of Greenland, Uruguay
19) UTC-02:00 Brazil (Fernando de Noronha), South Georgia and the South Sandwich Islands
20) UTC-01:00 Portugal (Azores), Cape Verde
21) UTC±00:00 Cote d'Ivoire, Faroe Islands, Ghana, Iceland, Senegal; (Summer) Ireland, Portugal (continental and Madeira)
22) UTC±00:00 Spain (Canary Islands), Morocco, United Kingdom
23) UTC+01:00 Angola, Cameroon, Nigeria, Tunisia; (Summer)Albania, Algeria, Austria, Belgium, Bosnia and Herzegovina,
24) UTC+01:00 Spain (continental), Croatia, Czech Republic, Denmark, Germany, Hungary, Italy, Kinshasa, Kosovo,
25) UTC+01:00 Macedonia, France (metropolitan), the Netherlands, Norway, Poland, Serbia, Slovakia, Slovenia, Sweden, Switzerland
26) UTC+02:00 Libya, Egypt, Malawi, Mozambique, South Africa, Zambia, Zimbabwe, (Summer)Bulgaria, Cyprus, Estonia,
27) UTC+02:00 Finland, Greece, Israel, Jordan, Latvia, Lebanon, Lithuania, Moldova, Palestine, Romania, Syria, Turkey, Ukraine
28) UTC+03:00 Belarus, Djibouti, Eritrea, Ethiopia, Iraq, Kenya, Madagascar, Russia (Kaliningrad Oblast), Saudi Arabia,
29) UTC+03:00 South Sudan, Sudan, Somalia, South Sudan, Tanzania, Uganda, Yemen
30) UTC+03:30 (Summer)Iran
31) UTC+04:00 Armenia, Azerbaijan, Georgia, Mauritius, Oman, Russia (European), Seychelles, United Arab Emirates
32) UTC+04:30 Afghanistan
33) UTC+05:00 Kazakhstan (West), Maldives, Pakistan, Uzbekistan
34) UTC+05:30 India, Sri Lanka
35) UTC+05:45 Nepal
36) UTC+06:00 Kazakhstan (most), Bangladesh, Russia (Ural: Sverdlovsk Oblast, Chelyabinsk Oblast)
37) UTC+06:30 Cocos Islands, Myanmar
38) UTC+07:00 Jakarta, Russia (Novosibirsk Oblast), Thailand, Vietnam
39) UTC+08:00 China, Hong Kong, Russia (Krasnoyarsk Krai), Malaysia, Philippines, Singapore, Taiwan, most of Mongolia, Western Australia
40) UTC+09:00 Korea, East Timor, Russia (Irkutsk Oblast), Japan
41) UTC+09:30 Australia (Northern Territory);(Summer)Australia (South Australia))
42) UTC+10:00 Russia (Zabaykalsky Krai); (Summer)Australia (New South Wales, Queensland, Tasmania, Victoria)
43) UTC+10:30 Lord Howe Island
44) UTC+11:00 New Caledonia, Russia (Primorsky Krai), Solomon Islands
45) UTC+11:30 Norfolk Island
46) UTC+12:00 Fiji, Russia (Kamchatka Krai);(Summer)New Zealand
47) UTC+12:45 (Summer)New Zealand
48) UTC+13:00 Tonga
49) UTC+14:00 Kiribati (Line Islands)
*/
void get_seconds_from_ntp_server(uint8_t *buf, uint16_t idx)
{
tstamp seconds = 0;
uint8_t i=0;
for (i = 0; i < 4; i++)
{
seconds = (seconds << 8) | buf[idx + i];
}
switch (time_zone)
{
case 0:
seconds -= 12*3600;
break;
case 1:
seconds -= 11*3600;
break;
case 2:
seconds -= 10*3600;
break;
case 3:
seconds -= (9*3600+30*60);
break;
case 4:
seconds -= 9*3600;
break;
case 5:
case 6:
seconds -= 8*3600;
break;
case 7:
case 8:
seconds -= 7*3600;
break;
case 9:
case 10:
seconds -= 6*3600;
break;
case 11:
case 12:
case 13:
seconds -= 5*3600;
break;
case 14:
seconds -= (4*3600+30*60);
break;
case 15:
case 16:
seconds -= 4*3600;
break;
case 17:
seconds -= (3*3600+30*60);
break;
case 18:
seconds -= 3*3600;
break;
case 19:
seconds -= 2*3600;
break;
case 20:
seconds -= 1*3600;
break;
case 21: //�?
case 22:
break;
case 23:
case 24:
case 25:
seconds += 1*3600;
break;
case 26:
case 27:
seconds += 2*3600;
break;
case 28:
case 29:
seconds += 3*3600;
break;
case 30:
seconds += (3*3600+30*60);
break;
case 31:
seconds += 4*3600;
break;
case 32:
seconds += (4*3600+30*60);
break;
case 33:
seconds += 5*3600;
break;
case 34:
seconds += (5*3600+30*60);
break;
case 35:
seconds += (5*3600+45*60);
break;
case 36:
seconds += 6*3600;
break;
case 37:
seconds += (6*3600+30*60);
break;
case 38:
seconds += 7*3600;
break;
case 39:
seconds += 8*3600;
break;
case 40:
seconds += 9*3600;
break;
case 41:
seconds += (9*3600+30*60);
break;
case 42:
seconds += 10*3600;
break;
case 43:
seconds += (10*3600+30*60);
break;
case 44:
seconds += 11*3600;
break;
case 45:
seconds += (11*3600+30*60);
break;
case 46:
seconds += 12*3600;
break;
case 47:
seconds += (12*3600+45*60);
break;
case 48:
seconds += 13*3600;
break;
case 49:
seconds += 14*3600;
break;
}
//calculation for date
calcdatetime(seconds);
}
void SNTP_init(uint8_t s, uint8_t *ntp_server, uint8_t tz, uint8_t *buf)
{
NTP_SOCKET = s;
NTPformat.dstaddr[0] = ntp_server[0];
NTPformat.dstaddr[1] = ntp_server[1];
NTPformat.dstaddr[2] = ntp_server[2];
NTPformat.dstaddr[3] = ntp_server[3];
time_zone = tz;
data_buf = buf;
uint8_t Flag;
NTPformat.leap = 0; /* leap indicator */
NTPformat.version = 4; /* version number */
NTPformat.mode = 3; /* mode */
NTPformat.stratum = 0; /* stratum */
NTPformat.poll = 0; /* poll interval */
NTPformat.precision = 0; /* precision */
NTPformat.rootdelay = 0; /* root delay */
NTPformat.rootdisp = 0; /* root dispersion */
NTPformat.refid = 0; /* reference ID */
NTPformat.reftime = 0; /* reference time */
NTPformat.org = 0; /* origin timestamp */
NTPformat.rec = 0; /* receive timestamp */
NTPformat.xmt = 1; /* transmit timestamp */
Flag = (NTPformat.leap<<6)+(NTPformat.version<<3)+NTPformat.mode; //one byte Flag
memcpy(ntpmessage,(void const*)(&Flag),1);
}
int8_t SNTP_run(datetime *time)
{
uint16_t RSR_len;
uint32_t destip = 0;
uint16_t destport;
uint16_t startindex = 40; //last 8-byte of data_buf[size is 48 byte] is xmt, so the startindex should be 40
switch(getSn_SR(NTP_SOCKET))
{
case SOCK_UDP:
if ((RSR_len = getSn_RX_RSR(NTP_SOCKET)) > 0)
{
if (RSR_len > MAX_SNTP_BUF_SIZE) RSR_len = MAX_SNTP_BUF_SIZE; // if Rx data size is lager than TX_RX_MAX_BUF_SIZE
recvfrom(NTP_SOCKET, data_buf, RSR_len, (uint8_t *)&destip, &destport);
get_seconds_from_ntp_server(data_buf,startindex);
time->yy = Nowdatetime.yy;
time->mo = Nowdatetime.mo;
time->dd = Nowdatetime.dd;
time->hh = Nowdatetime.hh;
time->mm = Nowdatetime.mm;
time->ss = Nowdatetime.ss;
ntp_retry_cnt=0;
close(NTP_SOCKET);
return 1;
}
if(ntp_retry_cnt<0xFFFF)
{
if(ntp_retry_cnt==0)//first send request, no need to wait
{
sendto(NTP_SOCKET,ntpmessage,sizeof(ntpmessage),NTPformat.dstaddr,ntp_port);
ntp_retry_cnt++;
}
else // send request again? it should wait for a while
{
if((ntp_retry_cnt % 0xFFF) == 0) //wait time
{
sendto(NTP_SOCKET,ntpmessage,sizeof(ntpmessage),NTPformat.dstaddr,ntp_port);
#ifdef _SNTP_DEBUG_
printf("ntp retry: %d\r\n", ntp_retry_cnt);
#endif
ntp_retry_cnt++;
}
}
}
else //ntp retry fail
{
ntp_retry_cnt=0;
#ifdef _SNTP_DEBUG_
printf("ntp retry failed!\r\n");
#endif
close(NTP_SOCKET);
}
break;
case SOCK_CLOSED:
socket(NTP_SOCKET,Sn_MR_UDP,ntp_port,0);
break;
}
// Return value
// 0 - failed / 1 - success
return 0;
}
void calcdatetime(tstamp seconds)
{
uint8_t yf=0;
tstamp n=0,d=0,total_d=0,rz=0;
uint16_t y=0,r=0,yr=0;
signed long long yd=0;
n = seconds;
total_d = seconds/(SECS_PERDAY);
d=0;
uint32_t p_year_total_sec=SECS_PERDAY*365;
uint32_t r_year_total_sec=SECS_PERDAY*366;
while(n>=p_year_total_sec)
{
if((EPOCH+r)%400==0 || ((EPOCH+r)%100!=0 && (EPOCH+r)%4==0))
{
n = n -(r_year_total_sec);
d = d + 366;
}
else
{
n = n - (p_year_total_sec);
d = d + 365;
}
r+=1;
y+=1;
}
y += EPOCH;
Nowdatetime.yy = y;
yd=0;
yd = total_d - d;
yf=1;
while(yd>=28)
{
if(yf==1 || yf==3 || yf==5 || yf==7 || yf==8 || yf==10 || yf==12)
{
yd -= 31;
if(yd<0)break;
rz += 31;
}
if (yf==2)
{
if (y%400==0 || (y%100!=0 && y%4==0))
{
yd -= 29;
if(yd<0)break;
rz += 29;
}
else
{
yd -= 28;
if(yd<0)break;
rz += 28;
}
}
if(yf==4 || yf==6 || yf==9 || yf==11 )
{
yd -= 30;
if(yd<0)break;
rz += 30;
}
yf += 1;
}
Nowdatetime.mo=yf;
yr = total_d-d-rz;
yr += 1;
Nowdatetime.dd=yr;
//calculation for time
seconds = seconds%SECS_PERDAY;
Nowdatetime.hh = seconds/3600;
Nowdatetime.mm = (seconds%3600)/60;
Nowdatetime.ss = (seconds%3600)%60;
}
tstamp changedatetime_to_seconds(void)
{
tstamp seconds=0;
uint32_t total_day=0;
uint16_t i=0,run_year_cnt=0,l=0;
l = Nowdatetime.yy;//low
for(i=EPOCH;i<l;i++)
{
if((i%400==0) || ((i%100!=0) && (i%4==0)))
{
run_year_cnt += 1;
}
}
total_day=(l-EPOCH-run_year_cnt)*365+run_year_cnt*366;
for(i=1;i<=Nowdatetime.mo;i++)
{
if(i==5 || i==7 || i==10 || i==12)
{
total_day += 30;
}
if (i==3)
{
if (l%400==0 && l%100!=0 && l%4==0)
{
total_day += 29;
}
else
{
total_day += 28;
}
}
if(i==2 || i==4 || i==6 || i==8 || i==9 || i==11)
{
total_day += 31;
}
}
seconds = (total_day+Nowdatetime.dd-1)*24*3600;
seconds += Nowdatetime.ss;//seconds
seconds += Nowdatetime.mm*60;//minute
seconds += Nowdatetime.hh*3600;//hour
return seconds;
}
| {
"pile_set_name": "Github"
} |
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = reduceRight;
var _reduce = require('./reduce');
var _reduce2 = _interopRequireDefault(_reduce);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
var slice = Array.prototype.slice;
/**
* Same as [`reduce`]{@link module:Collections.reduce}, only operates on `array` in reverse order.
*
* @name reduceRight
* @static
* @memberOf module:Collections
* @method
* @see [async.reduce]{@link module:Collections.reduce}
* @alias foldr
* @category Collection
* @param {Array} array - A collection to iterate over.
* @param {*} memo - The initial state of the reduction.
* @param {Function} iteratee - A function applied to each item in the
* array to produce the next step in the reduction. The `iteratee` is passed a
* `callback(err, reduction)` which accepts an optional error as its first
* argument, and the state of the reduction as the second. If an error is
* passed to the callback, the reduction is stopped and the main `callback` is
* immediately called with the error. Invoked with (memo, item, callback).
* @param {Function} [callback] - A callback which is called after all the
* `iteratee` functions have finished. Result is the reduced value. Invoked with
* (err, result).
*/
function reduceRight(array, memo, iteratee, callback) {
var reversed = slice.call(array).reverse();
(0, _reduce2.default)(reversed, memo, iteratee, callback);
}
module.exports = exports['default']; | {
"pile_set_name": "Github"
} |
<!--
//*********************************************************
//
// Copyright (c) Microsoft. All rights reserved.
// This code is licensed under the MIT License (MIT).
// THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
// ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
// IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
// PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
//
//*********************************************************
-->
<Page
x:Class="SimpleImaging.Scenario2"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="using:SimpleImaging"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
mc:Ignorable="d">
<Grid Background="{ThemeResource ApplicationPageBackgroundThemeBrush}">
<Grid x:Name="RootGrid" Margin="12,10,12,12">
<Grid.RowDefinitions>
<RowDefinition Height="Auto"/>
<RowDefinition Height="*"/>
</Grid.RowDefinitions>
<StackPanel Grid.Row="0" Margin="0,0,0,10">
<TextBlock Text="Description:" Style="{StaticResource SampleHeaderTextStyle}"/>
<TextBlock Style="{StaticResource ScenarioDescriptionTextStyle}" TextWrapping="Wrap">
Use the imaging APIs (Windows.Graphics.Imaging) to read and edit bitmap
properties and apply transformations such as scale, crop and rotate.
</TextBlock>
</StackPanel>
<ScrollViewer Grid.Row="1">
<StackPanel Orientation="Vertical">
<GridView>
<GridView.ItemsPanel>
<ItemsPanelTemplate>
<WrapGrid Orientation="Horizontal" ItemWidth="105" MaximumRowsOrColumns="6"/>
</ItemsPanelTemplate>
</GridView.ItemsPanel>
<Button x:Name="OpenButton" Content="Open" MinWidth="90" Click="Open_Click"/>
<Button x:Name="RotateLeftButton" Content="Left 90°" MinWidth="90" Click="RotateLeft_Click"/>
<Button x:Name="RotateRightButton" Content="Right 90°" MinWidth="95" Click="RotateRight_Click"/>
<Button x:Name="SaveButton" Content="Save" MinWidth="90" Click="Save_Click"/>
<Button x:Name="SaveAsButton" Content="Save as" MinWidth="90" Click="SaveAs_Click"/>
<Button x:Name="CloseButton" Content="Close" MinWidth="90" Click="Close_Click"/>
</GridView>
<Frame x:Name="ImageViewbox" HorizontalAlignment="Left" Width="300" Height="300" Margin="0,0,10,10">
<Image x:Name="PreviewImage" AutomationProperties.Name="Preview of the image" Source="" Stretch="Uniform" HorizontalAlignment="Center" VerticalAlignment="Center"/>
</Frame>
<Grid HorizontalAlignment="Left" VerticalAlignment="Top">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="Auto"/>
<ColumnDefinition Width="Auto"/>
</Grid.ColumnDefinitions>
<Grid.RowDefinitions>
<RowDefinition Height="Auto"/>
<RowDefinition Height="Auto"/>
<RowDefinition Height="Auto"/>
<RowDefinition Height="Auto"/>
<RowDefinition Height="Auto"/>
<RowDefinition Height="Auto"/>
</Grid.RowDefinitions>
<Slider Grid.Column="0" Grid.Row="0" Grid.ColumnSpan="2" x:Name="ScaleSlider" Width="300" Margin="0,0,10,10" IsEnabled="False" Minimum="10" Maximum="100" TickFrequency="5" TickPlacement="Outside" SnapsTo="Ticks" ValueChanged="ScaleSlider_ValueChanged"/>
<TextBlock Grid.Column="0" Grid.Row="1" Margin="0,0,10,10" Style="{StaticResource BasicTextStyle}" HorizontalAlignment="Left" VerticalAlignment="Center">Scale:</TextBlock>
<TextBlock Grid.Column="1" Grid.Row="1" x:Name="ScaleTextblock" Margin="0,0,10,10" Style="{StaticResource BasicTextStyle}" HorizontalAlignment="Left" VerticalAlignment="Center"/>
<TextBlock Grid.Column="0" Grid.Row="2" Margin="0,0,10,10" Style="{StaticResource BasicTextStyle}" HorizontalAlignment="Left" VerticalAlignment="Center">Oriented width:</TextBlock>
<TextBlock Grid.Column="1" Grid.Row="2" x:Name="WidthTextblock" Margin="0,0,10,10" Style="{StaticResource BasicTextStyle}" HorizontalAlignment="Left" VerticalAlignment="Center"/>
<TextBlock Grid.Column="0" Grid.Row="3" Margin="0,0,10,10" Style="{StaticResource BasicTextStyle}" HorizontalAlignment="Left" VerticalAlignment="Center">Oriented height:</TextBlock>
<TextBlock Grid.Column="1" Grid.Row="3" x:Name="HeightTextblock" Margin="0,0,10,10" Style="{StaticResource BasicTextStyle}" HorizontalAlignment="Left" VerticalAlignment="Center"/>
<TextBlock Grid.Column="0" Grid.Row="4" Margin="0,0,10,10" Style="{StaticResource BasicTextStyle}" HorizontalAlignment="Left" VerticalAlignment="Center">User rotation:</TextBlock>
<TextBlock Grid.Column="1" Grid.Row="4" x:Name="UserRotationTextblock" Margin="0,0,10,10" Style="{StaticResource BasicTextStyle}" HorizontalAlignment="Left" VerticalAlignment="Center"/>
<TextBlock Grid.Column="0" Grid.Row="5" Margin="0,0,10,10" Style="{StaticResource BasicTextStyle}" HorizontalAlignment="Left" VerticalAlignment="Center">EXIF orientation:</TextBlock>
<TextBlock Grid.Column="1" Grid.Row="5" x:Name="ExifOrientationTextblock" Margin="0,0,10,10" Style="{StaticResource BasicTextStyle}" HorizontalAlignment="Left" VerticalAlignment="Center"/>
</Grid>
</StackPanel>
</ScrollViewer>
</Grid>
</Grid>
</Page>
| {
"pile_set_name": "Github"
} |
package com.linbit.linstor.api.prop;
import java.util.regex.Pattern;
public class RegexProperty implements Property
{
private final String name;
private final String key;
private final Pattern pattern;
private boolean internal;
private String info;
public RegexProperty(
String nameRef,
String keyRef,
String value,
boolean internalRef,
String infoRef
)
{
name = nameRef;
key = keyRef;
info = infoRef;
pattern = Pattern.compile(value);
internal = internalRef;
}
@Override
public boolean isValid(String value)
{
return pattern.matcher(value).matches();
}
@Override
public String getName()
{
return name;
}
@Override
public String getKey()
{
return key;
}
@Override
public String getValue()
{
return pattern.pattern();
}
@Override
public boolean isInternal()
{
return internal;
}
@Override
public String getInfo()
{
return info;
}
}
| {
"pile_set_name": "Github"
} |
{
"name": "@react-vertex/color-hooks",
"version": "1.8.0",
"description": "React hooks for WebGL friendly colors",
"keywords": [
"react",
"colors",
"hex",
"rgb",
"webgl"
],
"license": "MIT",
"main": "cjs/index.js",
"module": "esm/index.js",
"jsnext:main": "esm/index.js",
"author": "Steven Hall <[email protected]>",
"homepage": "https://github.com/sghall/react-vertex/tree/master/packages/color-hooks#readme",
"peerDependencies": {
"react": "^16.8.6"
},
"dependencies": {
"@babel/runtime": "^7.4.3",
"hex-rgb": "^4.0.0",
"rgb-hex": "^2.1.0"
},
"publishConfig": {
"access": "public"
},
"repository": {
"type": "git",
"url": "git+https://github.com/sghall/react-vertex.git"
},
"scripts": {
"clean": "rimraf dist node_modules",
"files": "copy LICENSE dist && copy package.json dist && copy README.md dist",
"build": "npm run clean && npm run build:cjs && npm run build:esm && npm run files",
"build:cjs": "cross-env NODE_ENV=production BABEL_ENV=cjs babel --config-file ../../babel.config.js ./src --out-dir ./dist/cjs --ignore \"**/*.test.js\"",
"build:esm": "cross-env NODE_ENV=production BABEL_ENV=esm babel --config-file ../../babel.config.js ./src --out-dir ./dist/esm --ignore \"**/*.test.js\""
},
"bugs": {
"url": "https://github.com/sghall/react-vertex/issues"
},
"gitHead": "81e524013310b8cc02a9569df9f696afb3a92abc"
}
| {
"pile_set_name": "Github"
} |
using System;
using BEPUphysics.Entities;
using Microsoft.Xna.Framework;
using BEPUutilities;
namespace BEPUphysics.Constraints.TwoEntity.JointLimits
{
/// <summary>
/// Constrains the distance along an axis between anchor points attached to two entities.
/// </summary>
public class LinearAxisLimit : JointLimit, I1DImpulseConstraintWithError, I1DJacobianConstraint
{
private float accumulatedImpulse;
private float biasVelocity;
private Vector3 jAngularA, jAngularB;
private Vector3 jLinearA, jLinearB;
private Vector3 localAnchorA;
private Vector3 localAnchorB;
private float massMatrix;
private float error;
private Vector3 localAxis;
private float maximum;
private float minimum;
private Vector3 worldAxis;
private Vector3 rA; //Jacobian entry for entity A.
private float unadjustedError;
private Vector3 worldAnchorA;
private Vector3 worldAnchorB;
private Vector3 worldOffsetA, worldOffsetB;
/// <summary>
/// Constructs a constraint which tries to keep anchors on two entities within a certain distance of each other along an axis.
/// To finish the initialization, specify the connections (ConnectionA and ConnectionB)
/// as well as the AnchorA, AnchorB, and Axis (or their entity-local versions),
/// and the Minimum and Maximum.
/// This constructor sets the constraint's IsActive property to false by default.
/// </summary>
public LinearAxisLimit()
{
IsActive = false;
}
/// <summary>
/// Constructs a constraint which tries to keep anchors on two entities within a certain distance of each other along an axis.
/// </summary>
/// <param name="connectionA">First connection of the pair.</param>
/// <param name="connectionB">Second connection of the pair.</param>
/// <param name="anchorA">World space point to attach to connection A that will be constrained.</param>
/// <param name="anchorB">World space point to attach to connection B that will be constrained.</param>
/// <param name="axis">Limited axis in world space to attach to connection A.</param>
/// <param name="minimum">Minimum allowed position along the axis.</param>
/// <param name="maximum">Maximum allowed position along the axis.</param>
public LinearAxisLimit(Entity connectionA, Entity connectionB, Vector3 anchorA, Vector3 anchorB, Vector3 axis, float minimum, float maximum)
{
ConnectionA = connectionA;
ConnectionB = connectionB;
AnchorA = anchorA;
AnchorB = anchorB;
Axis = axis;
Minimum = minimum;
Maximum = maximum;
}
/// <summary>
/// Gets or sets the anchor point attached to entity A in world space.
/// </summary>
public Vector3 AnchorA
{
get { return worldAnchorA; }
set
{
worldAnchorA = value;
worldOffsetA = worldAnchorA - connectionA.position;
Matrix3x3.TransformTranspose(ref worldOffsetA, ref connectionA.orientationMatrix, out localAnchorA);
}
}
/// <summary>
/// Gets or sets the anchor point attached to entity A in world space.
/// </summary>
public Vector3 AnchorB
{
get { return worldAnchorB; }
set
{
worldAnchorB = value;
worldOffsetB = worldAnchorB - connectionB.position;
Matrix3x3.TransformTranspose(ref worldOffsetB, ref connectionB.orientationMatrix, out localAnchorB);
}
}
/// <summary>
/// Gets or sets the limited axis in world space.
/// </summary>
public Vector3 Axis
{
get { return worldAxis; }
set
{
worldAxis = Vector3.Normalize(value);
Matrix3x3.TransformTranspose(ref worldAxis, ref connectionA.orientationMatrix, out localAxis);
}
}
/// <summary>
/// Gets or sets the limited axis in the local space of connection A.
/// </summary>
public Vector3 LocalAxis
{
get { return localAxis; }
set
{
localAxis = Vector3.Normalize(value);
Matrix3x3.Transform(ref localAxis, ref connectionA.orientationMatrix, out worldAxis);
}
}
/// <summary>
/// Gets or sets the offset from the first entity's center of mass to the anchor point in its local space.
/// </summary>
public Vector3 LocalOffsetA
{
get { return localAnchorA; }
set
{
localAnchorA = value;
Matrix3x3.Transform(ref localAnchorA, ref connectionA.orientationMatrix, out worldOffsetA);
worldAnchorA = connectionA.position + worldOffsetA;
}
}
/// <summary>
/// Gets or sets the offset from the second entity's center of mass to the anchor point in its local space.
/// </summary>
public Vector3 LocalOffsetB
{
get { return localAnchorB; }
set
{
localAnchorB = value;
Matrix3x3.Transform(ref localAnchorB, ref connectionB.orientationMatrix, out worldOffsetB);
worldAnchorB = connectionB.position + worldOffsetB;
}
}
/// <summary>
/// Gets or sets the maximum allowed distance along the axis.
/// </summary>
public float Maximum
{
get { return maximum; }
set
{
maximum = value;
minimum = MathHelper.Min(minimum, maximum);
}
}
/// <summary>
/// Gets or sets the minimum allowed distance along the axis.
/// </summary>
public float Minimum
{
get { return minimum; }
set
{
minimum = value;
maximum = MathHelper.Max(minimum, maximum);
}
}
/// <summary>
/// Gets or sets the offset from the first entity's center of mass to the anchor point in world space.
/// </summary>
public Vector3 OffsetA
{
get { return worldOffsetA; }
set
{
worldOffsetA = value;
worldAnchorA = connectionA.position + worldOffsetA;
Matrix3x3.TransformTranspose(ref worldOffsetA, ref connectionA.orientationMatrix, out localAnchorA);
}
}
/// <summary>
/// Gets or sets the offset from the second entity's center of mass to the anchor point in world space.
/// </summary>
public Vector3 OffsetB
{
get { return worldOffsetB; }
set
{
worldOffsetB = value;
worldAnchorB = connectionB.position + worldOffsetB;
Matrix3x3.TransformTranspose(ref worldOffsetB, ref connectionB.orientationMatrix, out localAnchorB);
}
}
#region I1DImpulseConstraintWithError Members
/// <summary>
/// Gets the current relative velocity between the connected entities with respect to the constraint.
/// </summary>
public float RelativeVelocity
{
get
{
if (isLimitActive)
{
float lambda, dot;
Vector3.Dot(ref jLinearA, ref connectionA.linearVelocity, out lambda);
Vector3.Dot(ref jAngularA, ref connectionA.angularVelocity, out dot);
lambda += dot;
Vector3.Dot(ref jLinearB, ref connectionB.linearVelocity, out dot);
lambda += dot;
Vector3.Dot(ref jAngularB, ref connectionB.angularVelocity, out dot);
lambda += dot;
return lambda;
}
return 0;
}
}
/// <summary>
/// Gets the total impulse applied by this constraint.
/// </summary>
public float TotalImpulse
{
get { return accumulatedImpulse; }
}
/// <summary>
/// Gets the current constraint error.
/// </summary>
public float Error
{
get { return error; }
}
#endregion
//Jacobians
#region I1DJacobianConstraint Members
/// <summary>
/// Gets the linear jacobian entry for the first connected entity.
/// </summary>
/// <param name="jacobian">Linear jacobian entry for the first connected entity.</param>
public void GetLinearJacobianA(out Vector3 jacobian)
{
jacobian = jLinearA;
}
/// <summary>
/// Gets the linear jacobian entry for the second connected entity.
/// </summary>
/// <param name="jacobian">Linear jacobian entry for the second connected entity.</param>
public void GetLinearJacobianB(out Vector3 jacobian)
{
jacobian = jLinearB;
}
/// <summary>
/// Gets the angular jacobian entry for the first connected entity.
/// </summary>
/// <param name="jacobian">Angular jacobian entry for the first connected entity.</param>
public void GetAngularJacobianA(out Vector3 jacobian)
{
jacobian = jAngularA;
}
/// <summary>
/// Gets the angular jacobian entry for the second connected entity.
/// </summary>
/// <param name="jacobian">Angular jacobian entry for the second connected entity.</param>
public void GetAngularJacobianB(out Vector3 jacobian)
{
jacobian = jAngularB;
}
/// <summary>
/// Gets the mass matrix of the constraint.
/// </summary>
/// <param name="outputMassMatrix">Constraint's mass matrix.</param>
public void GetMassMatrix(out float outputMassMatrix)
{
outputMassMatrix = massMatrix;
}
#endregion
/// <summary>
/// Computes one iteration of the constraint to meet the solver updateable's goal.
/// </summary>
/// <returns>The rough applied impulse magnitude.</returns>
public override float SolveIteration()
{
//Compute the current relative velocity.
float lambda, dot;
Vector3.Dot(ref jLinearA, ref connectionA.linearVelocity, out lambda);
Vector3.Dot(ref jAngularA, ref connectionA.angularVelocity, out dot);
lambda += dot;
Vector3.Dot(ref jLinearB, ref connectionB.linearVelocity, out dot);
lambda += dot;
Vector3.Dot(ref jAngularB, ref connectionB.angularVelocity, out dot);
lambda += dot;
//Add in the constraint space bias velocity
lambda = -lambda + biasVelocity - softness * accumulatedImpulse;
//Transform to an impulse
lambda *= massMatrix;
//Clamp accumulated impulse (can't go negative)
float previousAccumulatedImpulse = accumulatedImpulse;
if (unadjustedError < 0)
accumulatedImpulse = MathHelper.Min(accumulatedImpulse + lambda, 0);
else
accumulatedImpulse = MathHelper.Max(accumulatedImpulse + lambda, 0);
lambda = accumulatedImpulse - previousAccumulatedImpulse;
//Apply the impulse
Vector3 impulse;
if (connectionA.isDynamic)
{
Vector3.Multiply(ref jLinearA, lambda, out impulse);
connectionA.ApplyLinearImpulse(ref impulse);
Vector3.Multiply(ref jAngularA, lambda, out impulse);
connectionA.ApplyAngularImpulse(ref impulse);
}
if (connectionB.isDynamic)
{
Vector3.Multiply(ref jLinearB, lambda, out impulse);
connectionB.ApplyLinearImpulse(ref impulse);
Vector3.Multiply(ref jAngularB, lambda, out impulse);
connectionB.ApplyAngularImpulse(ref impulse);
}
return (Math.Abs(lambda));
}
///<summary>
/// Performs the frame's configuration step.
///</summary>
///<param name="dt">Timestep duration.</param>
public override void Update(float dt)
{
//Compute the 'pre'-jacobians
Matrix3x3.Transform(ref localAnchorA, ref connectionA.orientationMatrix, out worldOffsetA);
Matrix3x3.Transform(ref localAnchorB, ref connectionB.orientationMatrix, out worldOffsetB);
Vector3.Add(ref worldOffsetA, ref connectionA.position, out worldAnchorA);
Vector3.Add(ref worldOffsetB, ref connectionB.position, out worldAnchorB);
Vector3.Subtract(ref worldAnchorB, ref connectionA.position, out rA);
Matrix3x3.Transform(ref localAxis, ref connectionA.orientationMatrix, out worldAxis);
//Compute error
#if !WINDOWS
Vector3 separation = new Vector3();
#else
Vector3 separation;
#endif
separation.X = worldAnchorB.X - worldAnchorA.X;
separation.Y = worldAnchorB.Y - worldAnchorA.Y;
separation.Z = worldAnchorB.Z - worldAnchorA.Z;
Vector3.Dot(ref separation, ref worldAxis, out unadjustedError);
//Compute error
if (unadjustedError < minimum)
unadjustedError = minimum - unadjustedError;
else if (unadjustedError > maximum)
unadjustedError = maximum - unadjustedError;
else
{
unadjustedError = 0;
isActiveInSolver = false;
accumulatedImpulse = 0;
isLimitActive = false;
return;
}
isLimitActive = true;
unadjustedError = -unadjustedError;
//Adjust Error
if (unadjustedError > 0)
error = MathHelper.Max(0, unadjustedError - margin);
else if (unadjustedError < 0)
error = MathHelper.Min(0, unadjustedError + margin);
//Compute jacobians
jLinearA = worldAxis;
jLinearB.X = -jLinearA.X;
jLinearB.Y = -jLinearA.Y;
jLinearB.Z = -jLinearA.Z;
Vector3.Cross(ref rA, ref jLinearA, out jAngularA);
Vector3.Cross(ref worldOffsetB, ref jLinearB, out jAngularB);
//Compute bias
float errorReductionParameter;
springSettings.ComputeErrorReductionAndSoftness(dt, out errorReductionParameter, out softness);
biasVelocity = MathHelper.Clamp(errorReductionParameter * error, -maxCorrectiveVelocity, maxCorrectiveVelocity);
if (bounciness > 0)
{
//Compute currently relative velocity for bounciness.
float relativeVelocity, dot;
Vector3.Dot(ref jLinearA, ref connectionA.linearVelocity, out relativeVelocity);
Vector3.Dot(ref jAngularA, ref connectionA.angularVelocity, out dot);
relativeVelocity += dot;
Vector3.Dot(ref jLinearB, ref connectionB.linearVelocity, out dot);
relativeVelocity += dot;
Vector3.Dot(ref jAngularB, ref connectionB.angularVelocity, out dot);
relativeVelocity += dot;
if (unadjustedError > 0 && -relativeVelocity > bounceVelocityThreshold)
biasVelocity = Math.Max(biasVelocity, -relativeVelocity * bounciness);
else if (unadjustedError < 0 && relativeVelocity > bounceVelocityThreshold)
biasVelocity = Math.Min(biasVelocity, -relativeVelocity * bounciness);
}
//compute mass matrix
float entryA, entryB;
Vector3 intermediate;
if (connectionA.isDynamic)
{
Matrix3x3.Transform(ref jAngularA, ref connectionA.inertiaTensorInverse, out intermediate);
Vector3.Dot(ref intermediate, ref jAngularA, out entryA);
entryA += connectionA.inverseMass;
}
else
entryA = 0;
if (connectionB.isDynamic)
{
Matrix3x3.Transform(ref jAngularB, ref connectionB.inertiaTensorInverse, out intermediate);
Vector3.Dot(ref intermediate, ref jAngularB, out entryB);
entryB += connectionB.inverseMass;
}
else
entryB = 0;
massMatrix = 1 / (entryA + entryB + softness);
}
/// <summary>
/// Performs any pre-solve iteration work that needs exclusive
/// access to the members of the solver updateable.
/// Usually, this is used for applying warmstarting impulses.
/// </summary>
public override void ExclusiveUpdate()
{
//Warm starting
Vector3 impulse;
if (connectionA.isDynamic)
{
Vector3.Multiply(ref jLinearA, accumulatedImpulse, out impulse);
connectionA.ApplyLinearImpulse(ref impulse);
Vector3.Multiply(ref jAngularA, accumulatedImpulse, out impulse);
connectionA.ApplyAngularImpulse(ref impulse);
}
if (connectionB.isDynamic)
{
Vector3.Multiply(ref jLinearB, accumulatedImpulse, out impulse);
connectionB.ApplyLinearImpulse(ref impulse);
Vector3.Multiply(ref jAngularB, accumulatedImpulse, out impulse);
connectionB.ApplyAngularImpulse(ref impulse);
}
}
}
} | {
"pile_set_name": "Github"
} |
tinymce.addI18n('kab',{
"Redo": "Err-d",
"Undo": "Semmet",
"Cut": "Gzem",
"Copy": "N\u0263el",
"Paste": "Sente\u1e0d",
"Select all": "Fren kulec",
"New document": "Attaftar amaynut",
"Ok": "Ih",
"Cancel": "Semmet",
"Visual aids": "Visual aids",
"Bold": "Tira tazurant",
"Italic": "Tira yeknan",
"Underline": "Aderrer",
"Strikethrough": "Strikethrough",
"Superscript": "Superscript",
"Subscript": "Subscript",
"Clear formatting": "Clear formatting",
"Align left": "Tarigla \u0263er zelma\u1e0d",
"Align center": "Di tlemast",
"Align right": "tarigla \u0263er zelma\u1e0d",
"Justify": "Justify",
"Bullet list": "Tabdart s tlillac",
"Numbered list": "Tabdart s wu\u1e6d\u1e6dunen",
"Decrease indent": "Simc\u1e6du\u1e25 asi\u1e93i",
"Increase indent": "Sim\u0263ur asi\u1e93i",
"Close": "Mdel",
"Formats": "Imasalen",
"Your browser doesn't support direct access to the clipboard. Please use the Ctrl+X\/C\/V keyboard shortcuts instead.": "Your browser doesn't support direct access to the clipboard. Please use the Ctrl+X\/C\/V keyboard shortcuts instead.",
"Headers": "Izwal",
"Header 1": "Azwel 1",
"Header 2": "Azwel 2",
"Header 3": "Azwel 3",
"Header 4": "Azwel 4",
"Header 5": "Header 5",
"Header 6": "Azwel 6",
"Headings": "Izewlen",
"Heading 1": "Inixf 1",
"Heading 2": "Inixf 2",
"Heading 3": "Inixf 3",
"Heading 4": "Inixf 4",
"Heading 5": "Inixf 5",
"Heading 6": "Inixf 6",
"Div": "Div",
"Pre": "Pre",
"Code": "Tangalt",
"Paragraph": "taseddart",
"Blockquote": "Tanebdurt",
"Inline": "Inline",
"Blocks": "I\u1e25edran",
"Paste is now in plain text mode. Contents will now be pasted as plain text until you toggle this option off.": "Paste is now in plain text mode. Contents will now be pasted as plain text until you toggle this option off.",
"Font Family": "Tasefsit",
"Font Sizes": "Tiddi n tsefsit",
"Class": "Asmil",
"Browse for an image": "Snirem iwakken ad tferne\u1e0d tugna",
"OR": "Ih",
"Drop an image here": "Ssers tugna dagi",
"Upload": "Sili",
"Block": "Sew\u1e25el",
"Align": "Settef",
"Default": "Lex\u1e63as",
"Circle": "Tawinest",
"Disc": "A\u1e0debsi",
"Square": "Amku\u1e93",
"Lower Alpha": "Alpha ame\u1e93yan",
"Lower Greek": "Grik ame\u1e93yan",
"Lower Roman": "Ruman amectu\u1e25",
"Upper Alpha": "Alfa ameqran",
"Upper Roman": "Ruman ameqran",
"Anchor": "Tamdeyt",
"Name": "Isem",
"Id": "Id",
"Id should start with a letter, followed only by letters, numbers, dashes, dots, colons or underscores.": "id ilaq ad ibdu s usekkil, ad yettwa\u1e0dfer kan s isekkilen, im\u1e0danen, ijerri\u1e0den, tinqi\u1e0din, snat n tenqi\u1e0din ne\u0263 ijerri\u1e0den n wadda.",
"You have unsaved changes are you sure you want to navigate away?": "Ibeddilen ur twaskelsen ara teb\u0263i\u1e0d ad teff\u0263e\u1e0d ?",
"Restore last draft": "Restore last draft",
"Special character": "Askil uslig",
"Source code": "Tangalt ta\u0263balut",
"Insert\/Edit code sample": "Ger\/\u1e92reg tangalt n umedya",
"Language": "Tutlayt",
"Code sample": "Tikkest n tengalt",
"Color": "Ini",
"R": "R",
"G": "G",
"B": "B",
"Left to right": "Seg zelma\u1e0d \u0263er yefus",
"Right to left": "Seg yefus \u0263er zelma\u1e0d",
"Emoticons": "Emoticons",
"Document properties": "Iraten n warat",
"Title": "Azwel",
"Keywords": "Awalen yufraren",
"Description": "Aglam",
"Robots": "Robots",
"Author": "Ameskar",
"Encoding": "Asettengel",
"Fullscreen": "Agdil a\u010duran",
"Action": "Tigawt",
"Shortcut": "Anegzum",
"Help": "Tallalt",
"Address": "Tansa",
"Focus to menubar": "Asa\u1e0des \u0263ef tfeggagt n wumu\u0263",
"Focus to toolbar": "Asa\u1e0des \u0263ef tfeggagt n ifecka",
"Focus to element path": "Asa\u1e0des \u0263ef ubrid n uferdis",
"Focus to contextual toolbar": "Asa\u1e0des \u0263ef tfeggagt n ifecka tanattalt",
"Insert link (if link plugin activated)": "Ger ase\u0263wen (ma yermed uzegrir n use\u0263wen)",
"Save (if save plugin activated)": "Sekles (ma yermed uzegrir save)",
"Find (if searchreplace plugin activated)": "Nadi (ma yermed uzegrir searchreplace)",
"Plugins installed ({0}):": "Izegriren yettwasbedden ({0}):",
"Premium plugins:": "Izegriren premium :",
"Learn more...": "\u1e92er ugar...",
"You are using {0}": "Tsseqdace\u1e0d {0}",
"Plugins": "Isi\u0263zifen",
"Handy Shortcuts": "Inegzumen",
"Horizontal line": "Ajerri\u1e0d aglawan",
"Insert\/edit image": "Ger\/\u1e92reg tugna",
"Image description": "Aglam n tugna",
"Source": "A\u0263balu",
"Dimensions": "Tisekta",
"Constrain proportions": "Constrain proportions",
"General": "Amatu",
"Advanced": "Ana\u1e93i",
"Style": "A\u0263anib",
"Vertical space": "Talunt taratakt",
"Horizontal space": "Talunt taglawant",
"Border": "Iri",
"Insert image": "Ger tugna",
"Image": "Tugna",
"Image list": "Tabdart n tugniwin",
"Rotate counterclockwise": "Tuzya mgal tamrilt",
"Rotate clockwise": "Tuzya yugdan tamrilt",
"Flip vertically": "Tuzya taratakt",
"Flip horizontally": "Tuzttya tagrawant",
"Edit image": "\u1e92reg tugna",
"Image options": "Tixti\u1e5biyin n tugna",
"Zoom in": "Zoom in",
"Zoom out": "Zoom out",
"Crop": "Rogner",
"Resize": "Beddel tiddi",
"Orientation": "Ta\u0263da",
"Brightness": "Tafat",
"Sharpen": "Affiner",
"Contrast": "Contrast",
"Color levels": "Iswiren n yini",
"Gamma": "Gamma",
"Invert": "Tti",
"Apply": "Snes",
"Back": "Tu\u0263alin",
"Insert date\/time": "Ger azemz\/asrag",
"Date\/time": "Azemz\/Asrag",
"Insert link": "Ger azday",
"Insert\/edit link": "Ger\/\u1e93reg azday",
"Text to display": "A\u1e0dris ara yettwabeqq\u1e0den",
"Url": "Url",
"Target": "Target",
"None": "Ulac",
"New window": "Asfaylu amaynut",
"Remove link": "Kkes azday",
"Anchors": "Timdyin",
"Link": "Ase\u0263wen",
"Paste or type a link": "Sente\u1e0d ne\u0263 sekcem ase\u0263wen",
"The URL you entered seems to be an email address. Do you want to add the required mailto: prefix?": "URL i teskecme\u1e0d tettban-d d tansa email. teb\u0263i\u1e0d ad s-ternu\u1e0d azwir mailto : ?",
"The URL you entered seems to be an external link. Do you want to add the required http:\/\/ prefix?": "URL i teskecme\u1e0d tettban-d d azday uffi\u0263. Teb\u0263i\u1e0d ad s-ternu\u1e0d azwir http:\/\/ ?",
"Link list": "Tabdart n is\u0263ewnen",
"Insert video": "Ger avidyu",
"Insert\/edit video": "Ger\/\u1e93reg avidyu",
"Insert\/edit media": "Ger\/\u1e92reg amiya",
"Alternative source": "A\u0263balu amlellay",
"Poster": "Poster",
"Paste your embed code below:": "Paste your embed code below:",
"Embed": "Embed",
"Media": "Amidya",
"Nonbreaking space": "Talunt ur nettwagzam ara",
"Page break": "Angaz n usebter",
"Paste as text": "Sente\u1e0d d a\u1e0dris",
"Preview": "Sken",
"Print": "Siggez",
"Save": "Sekles",
"Find": "Nadi",
"Replace with": "Semselsi s",
"Replace": "Semselsi",
"Replace all": "Semselsi kulec",
"Prev": "Win yezrin",
"Next": "Win \u0263ers",
"Find and replace": "Nadi semselsi",
"Could not find the specified string.": "Ur d-nufi ara azrar i d-yettunefken.",
"Match case": "Match case",
"Whole words": "Awal ummid",
"Spellcheck": "Ase\u0263ti n tira",
"Ignore": "Zgel",
"Ignore all": "Zgel kulec",
"Finish": "Fak",
"Add to Dictionary": "Rnu-t s amawal",
"Insert table": "Ger tafelwit",
"Table properties": "Iraten n tfelwit",
"Delete table": "Kkes tafelwit",
"Cell": "Taxxamt",
"Row": "Adur",
"Column": "Tagejdit",
"Cell properties": "Iraten n texxamt",
"Merge cells": "Seddukel tixxamin",
"Split cell": "B\u1e0du tixxamin",
"Insert row before": "Ger adur deffir",
"Insert row after": "Ger adur sdat",
"Delete row": "Kkes tagejdit",
"Row properties": "Iraten n udur",
"Cut row": "Gzem adur",
"Copy row": "N\u0263el adur",
"Paste row before": "Sente\u1e0d adur sdat",
"Paste row after": "Sente\u1e0d adur deffir",
"Insert column before": "Sente\u1e0d tagejdit sdat",
"Insert column after": "Sente\u1e0d tagejdit deffir",
"Delete column": "Kkes tagejdit",
"Cols": "Tigejda",
"Rows": "Aduren",
"Width": "Tehri",
"Height": "Te\u0263zi",
"Cell spacing": "Tlunt ger texxamin",
"Cell padding": "Tama n texxamt",
"Caption": "Caption",
"Left": "\u0194er zelma\u1e0d",
"Center": "Di tlemmast",
"Right": "\u0194er yefus",
"Cell type": "Anaw n texxamt",
"Scope": "Scope",
"Alignment": "Tarigla",
"H Align": "Tarigla taglawant",
"V Align": "Tarigla taratakt",
"Top": "Uksawen",
"Middle": "Di tlemmast",
"Bottom": "Uksar",
"Header cell": "Tasen\u1e6di\u1e0dt n texxamt",
"Row group": "Agraw n waduren",
"Column group": "Agraw n tgejda",
"Row type": "Anaw n wadur",
"Header": "Tasenti\u1e0dt",
"Body": "Tafka",
"Footer": "A\u1e0dar",
"Border color": "Ini n yiri",
"Insert template": "Ger tamuddimt",
"Templates": "Timudimin",
"Template": "Tine\u0263rufin",
"Text color": "Ini n u\u1e0dris",
"Background color": "Ini n ugilal",
"Custom...": "Custom...",
"Custom color": "Custom color",
"No color": "Ulac ini",
"Table of Contents": "Tafelwit n ugbur",
"Show blocks": "Beqqe\u1e0d i\u1e25edran",
"Show invisible characters": "Beqqe\u1e0d isekkilen uffiren",
"Words: {0}": "Words: {0}",
"{0} words": "{0} n wawalen",
"File": "Afaylu",
"Edit": "\u1e92reg",
"Insert": "Ger",
"View": "Tamu\u0263li",
"Format": "Amasal",
"Table": "Tafelwit",
"Tools": "Ifecka",
"Powered by {0}": "Iteddu s {0} ",
"Rich Text Area. Press ALT-F9 for menu. Press ALT-F10 for toolbar. Press ALT-0 for help": "Rich Text Area. Press ALT-F9 for menu. Press ALT-F10 for toolbar. Press ALT-0 for help"
}); | {
"pile_set_name": "Github"
} |
// Copyright Neil Groves 2009. Use, modification and
// distribution is subject to the Boost Software License, Version
// 1.0. (See accompanying file LICENSE_1_0.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt)
//
//
// For more information, see http://www.boost.org/libs/range/
//
#ifndef BOOST_RANGE_ALGORITHM_HEAP_ALGORITHM_HPP_INCLUDED
#define BOOST_RANGE_ALGORITHM_HEAP_ALGORITHM_HPP_INCLUDED
#include <boost/concept_check.hpp>
#include <boost/range/begin.hpp>
#include <boost/range/end.hpp>
#include <boost/range/concepts.hpp>
#include <algorithm>
namespace boost
{
namespace range
{
/// \brief template function push_heap
///
/// range-based version of the push_heap std algorithm
///
/// \pre RandomAccessRange is a model of the RandomAccessRangeConcept
/// \pre Compare is a model of the BinaryPredicateConcept
template<class RandomAccessRange>
inline RandomAccessRange& push_heap(RandomAccessRange& rng)
{
BOOST_RANGE_CONCEPT_ASSERT(( RandomAccessRangeConcept<RandomAccessRange> ));
std::push_heap(boost::begin(rng), boost::end(rng));
return rng;
}
/// \overload
template<class RandomAccessRange>
inline const RandomAccessRange& push_heap(const RandomAccessRange& rng)
{
BOOST_RANGE_CONCEPT_ASSERT(( RandomAccessRangeConcept<const RandomAccessRange> ));
std::push_heap(boost::begin(rng), boost::end(rng));
return rng;
}
/// \overload
template<class RandomAccessRange, class Compare>
inline RandomAccessRange& push_heap(RandomAccessRange& rng, Compare comp_pred)
{
BOOST_RANGE_CONCEPT_ASSERT(( RandomAccessRangeConcept<RandomAccessRange> ));
std::push_heap(boost::begin(rng), boost::end(rng), comp_pred);
return rng;
}
/// \overload
template<class RandomAccessRange, class Compare>
inline const RandomAccessRange& push_heap(const RandomAccessRange& rng, Compare comp_pred)
{
BOOST_RANGE_CONCEPT_ASSERT(( RandomAccessRangeConcept<const RandomAccessRange> ));
std::push_heap(boost::begin(rng), boost::end(rng), comp_pred);
return rng;
}
/// \brief template function pop_heap
///
/// range-based version of the pop_heap std algorithm
///
/// \pre RandomAccessRange is a model of the RandomAccessRangeConcept
/// \pre Compare is a model of the BinaryPredicateConcept
template<class RandomAccessRange>
inline RandomAccessRange& pop_heap(RandomAccessRange& rng)
{
BOOST_RANGE_CONCEPT_ASSERT(( RandomAccessRangeConcept<RandomAccessRange> ));
std::pop_heap(boost::begin(rng), boost::end(rng));
return rng;
}
/// \overload
template<class RandomAccessRange>
inline const RandomAccessRange& pop_heap(const RandomAccessRange& rng)
{
BOOST_RANGE_CONCEPT_ASSERT(( RandomAccessRangeConcept<const RandomAccessRange> ));
std::pop_heap(boost::begin(rng), boost::end(rng));
return rng;
}
/// \overload
template<class RandomAccessRange, class Compare>
inline RandomAccessRange& pop_heap(RandomAccessRange& rng, Compare comp_pred)
{
BOOST_RANGE_CONCEPT_ASSERT(( RandomAccessRangeConcept<RandomAccessRange> ));
std::pop_heap(boost::begin(rng), boost::end(rng), comp_pred);
return rng;
}
/// \overload
template<class RandomAccessRange, class Compare>
inline const RandomAccessRange& pop_heap(const RandomAccessRange& rng, Compare comp_pred)
{
BOOST_RANGE_CONCEPT_ASSERT(( RandomAccessRangeConcept<const RandomAccessRange> ));
std::pop_heap(boost::begin(rng), boost::end(rng), comp_pred);
return rng;
}
/// \brief template function make_heap
///
/// range-based version of the make_heap std algorithm
///
/// \pre RandomAccessRange is a model of the RandomAccessRangeConcept
/// \pre Compare is a model of the BinaryPredicateConcept
template<class RandomAccessRange>
inline RandomAccessRange& make_heap(RandomAccessRange& rng)
{
BOOST_RANGE_CONCEPT_ASSERT(( RandomAccessRangeConcept<RandomAccessRange> ));
std::make_heap(boost::begin(rng), boost::end(rng));
return rng;
}
/// \overload
template<class RandomAccessRange>
inline const RandomAccessRange& make_heap(const RandomAccessRange& rng)
{
BOOST_RANGE_CONCEPT_ASSERT(( RandomAccessRangeConcept<const RandomAccessRange> ));
std::make_heap(boost::begin(rng), boost::end(rng));
return rng;
}
/// \overload
template<class RandomAccessRange, class Compare>
inline RandomAccessRange& make_heap(RandomAccessRange& rng, Compare comp_pred)
{
BOOST_RANGE_CONCEPT_ASSERT(( RandomAccessRangeConcept<RandomAccessRange> ));
std::make_heap(boost::begin(rng), boost::end(rng), comp_pred);
return rng;
}
/// \overload
template<class RandomAccessRange, class Compare>
inline const RandomAccessRange& make_heap(const RandomAccessRange& rng, Compare comp_pred)
{
BOOST_RANGE_CONCEPT_ASSERT(( RandomAccessRangeConcept<const RandomAccessRange> ));
std::make_heap(boost::begin(rng), boost::end(rng), comp_pred);
return rng;
}
/// \brief template function sort_heap
///
/// range-based version of the sort_heap std algorithm
///
/// \pre RandomAccessRange is a model of the RandomAccessRangeConcept
/// \pre Compare is a model of the BinaryPredicateConcept
template<class RandomAccessRange>
inline RandomAccessRange& sort_heap(RandomAccessRange& rng)
{
BOOST_RANGE_CONCEPT_ASSERT(( RandomAccessRangeConcept<RandomAccessRange> ));
std::sort_heap(boost::begin(rng), boost::end(rng));
return rng;
}
/// \overload
template<class RandomAccessRange>
inline const RandomAccessRange& sort_heap(const RandomAccessRange& rng)
{
BOOST_RANGE_CONCEPT_ASSERT(( RandomAccessRangeConcept<const RandomAccessRange> ));
std::sort_heap(boost::begin(rng), boost::end(rng));
return rng;
}
/// \overload
template<class RandomAccessRange, class Compare>
inline RandomAccessRange& sort_heap(RandomAccessRange& rng, Compare comp_pred)
{
BOOST_RANGE_CONCEPT_ASSERT(( RandomAccessRangeConcept<RandomAccessRange> ));
std::sort_heap(boost::begin(rng), boost::end(rng), comp_pred);
return rng;
}
/// \overload
template<class RandomAccessRange, class Compare>
inline const RandomAccessRange& sort_heap(const RandomAccessRange& rng, Compare comp_pred)
{
BOOST_RANGE_CONCEPT_ASSERT(( RandomAccessRangeConcept<const RandomAccessRange> ));
std::sort_heap(boost::begin(rng), boost::end(rng), comp_pred);
return rng;
}
} // namespace range
using range::push_heap;
using range::pop_heap;
using range::make_heap;
using range::sort_heap;
} // namespace boost
#endif // include guard
| {
"pile_set_name": "Github"
} |
.class public whocares
.super java/lang/Object
.method public static print : (F)V
.code stack 10 locals 10
goto LFOO
return
.end code
.end method
.end class
| {
"pile_set_name": "Github"
} |
{-# LANGUAGE TypeApplications #-}
{-# LANGUAGE TypeFamilies #-}
{-# LANGUAGE TypeInType #-}
module T15515 where
import Data.Kind
import Data.Proxy
class C a where
c :: Proxy a
type family F
data D :: F -> Type
instance C (D :: F -> Type) where
c = Proxy
c' :: Proxy (D :: F -> Type)
c' = c @(D :: F -> Type)
| {
"pile_set_name": "Github"
} |
# Once for All: Train One Network and Specialize it for Efficient Deployment
# Han Cai, Chuang Gan, Tianzhe Wang, Zhekai Zhang, Song Han
# International Conference on Learning Representations (ICLR), 2020.
import random
import torch
import torch.multiprocessing as multiprocessing
from torch._C import _set_worker_signal_handlers
from torch.utils.data import _utils
from torch.utils.data import SequentialSampler, RandomSampler, BatchSampler
import signal
from torch._six import container_abcs
import re
import sys
import threading
import traceback
import os
import atexit
from torch._six import string_classes, int_classes
from ofa.imagenet_codebase.data_providers.base_provider import MyRandomResizedCrop
IS_WINDOWS = sys.platform == "win32"
if IS_WINDOWS:
import ctypes
from ctypes.wintypes import DWORD, BOOL, HANDLE
if sys.version_info[0] == 2:
import Queue as queue
else:
import queue
# NOTE [ Python Traceback Reference Cycle Problem ]
#
# When using sys.exc_info(), it is important to **not** store the exc_info[2],
# which is the traceback, because otherwise you will run into the traceback
# reference cycle problem, i.e., the traceback holding reference to the frame,
# and the frame (which holds reference to all the object in its temporary scope)
# holding reference the traceback.
class ExceptionWrapper(object):
r"""Wraps an exception plus traceback to communicate across threads"""
def __init__(self, exc_info):
# It is important that we don't store exc_info, see
# NOTE [ Python Traceback Reference Cycle Problem ]
self.exc_type = exc_info[0]
self.exc_msg = "".join(traceback.format_exception(*exc_info))
_use_shared_memory = False
r"""Whether to use shared memory in default_collate"""
MP_STATUS_CHECK_INTERVAL = 5.0
r"""Interval (in seconds) to check status of processes to avoid hanging in
multiprocessing data loading. This is mainly used in getting data from
another process, in which case we need to periodically check whether the
sender is alive to prevent hanging."""
if IS_WINDOWS:
# On Windows, the parent ID of the worker process remains unchanged when the manager process
# is gone, and the only way to check it through OS is to let the worker have a process handle
# of the manager and ask if the process status has changed.
class ManagerWatchdog(object):
def __init__(self):
self.manager_pid = os.getppid()
self.kernel32 = ctypes.WinDLL('kernel32', use_last_error=True)
self.kernel32.OpenProcess.argtypes = (DWORD, BOOL, DWORD)
self.kernel32.OpenProcess.restype = HANDLE
self.kernel32.WaitForSingleObject.argtypes = (HANDLE, DWORD)
self.kernel32.WaitForSingleObject.restype = DWORD
# Value obtained from https://msdn.microsoft.com/en-us/library/ms684880.aspx
SYNCHRONIZE = 0x00100000
self.manager_handle = self.kernel32.OpenProcess(SYNCHRONIZE, 0, self.manager_pid)
if not self.manager_handle:
raise ctypes.WinError(ctypes.get_last_error())
self.manager_dead = False
def is_alive(self):
if not self.manager_dead:
# Value obtained from https://msdn.microsoft.com/en-us/library/windows/desktop/ms687032.aspx
self.manager_dead = self.kernel32.WaitForSingleObject(self.manager_handle, 0) == 0
return not self.manager_dead
else:
class ManagerWatchdog(object):
def __init__(self):
self.manager_pid = os.getppid()
self.manager_dead = False
def is_alive(self):
if not self.manager_dead:
self.manager_dead = os.getppid() != self.manager_pid
return not self.manager_dead
def _worker_loop(dataset, index_queue, data_queue, done_event, collate_fn, seed, init_fn, worker_id):
# See NOTE [ Data Loader Multiprocessing Shutdown Logic ] for details on the
# logic of this function.
try:
global _use_shared_memory
_use_shared_memory = True
# Intialize C side signal handlers for SIGBUS and SIGSEGV. Python signal
# module's handlers are executed after Python returns from C low-level
# handlers, likely when the same fatal signal happened again already.
# https://docs.python.org/3/library/signal.html Sec. 18.8.1.1
_set_worker_signal_handlers()
torch.set_num_threads(1)
random.seed(seed)
torch.manual_seed(seed)
data_queue.cancel_join_thread()
if init_fn is not None:
init_fn(worker_id)
watchdog = ManagerWatchdog()
while watchdog.is_alive():
try:
r = index_queue.get(timeout=MP_STATUS_CHECK_INTERVAL)
except queue.Empty:
continue
if r is None:
# Received the final signal
assert done_event.is_set()
return
elif done_event.is_set():
# Done event is set. But I haven't received the final signal
# (None) yet. I will keep continuing until get it, and skip the
# processing steps.
continue
idx, batch_indices = r
MyRandomResizedCrop.sample_image_size(idx)
try:
samples = collate_fn([dataset[i] for i in batch_indices])
except Exception:
# It is important that we don't store exc_info in a variable,
# see NOTE [ Python Traceback Reference Cycle Problem ]
data_queue.put((idx, ExceptionWrapper(sys.exc_info())))
else:
data_queue.put((idx, samples))
del samples
except KeyboardInterrupt:
# Main process will raise KeyboardInterrupt anyways.
pass
def _pin_memory_loop(in_queue, out_queue, device_id, done_event):
torch.cuda.set_device(device_id)
# See NOTE [ Data Loader Multiprocessing Shutdown Logic ] for details on the
# logic of this function.
while True:
try:
r = in_queue.get(timeout=MP_STATUS_CHECK_INTERVAL)
except queue.Empty:
continue
except Exception:
if done_event.is_set():
# Weird things can happen when shutting down, e.g., fd being
# closed when tensors are shared via fds.
break
raise
if r is None:
assert done_event.is_set()
return
elif done_event.is_set():
# Haven't seen the final signal yet. Keep getting until None.
continue
elif isinstance(r[1], ExceptionWrapper):
out_queue.put(r)
else:
idx, batch = r
try:
batch = pin_memory_batch(batch)
except Exception:
out_queue.put((idx, ExceptionWrapper(sys.exc_info())))
else:
out_queue.put((idx, batch))
numpy_type_map = {
'float64': torch.DoubleTensor,
'float32': torch.FloatTensor,
'float16': torch.HalfTensor,
'int64': torch.LongTensor,
'int32': torch.IntTensor,
'int16': torch.ShortTensor,
'int8': torch.CharTensor,
'uint8': torch.ByteTensor,
}
def default_collate(batch):
r"""Puts each data field into a tensor with outer dimension batch size"""
error_msg = "batch must contain tensors, numbers, dicts or lists; found {}"
elem_type = type(batch[0])
if isinstance(batch[0], torch.Tensor):
out = None
if _use_shared_memory:
# If we're in a background process, concatenate directly into a
# shared memory tensor to avoid an extra copy
numel = sum([x.numel() for x in batch])
storage = batch[0].storage()._new_shared(numel)
out = batch[0].new(storage)
return torch.stack(batch, 0, out=out)
elif elem_type.__module__ == 'numpy' and elem_type.__name__ != 'str_' \
and elem_type.__name__ != 'string_':
elem = batch[0]
if elem_type.__name__ == 'ndarray':
# array of string classes and object
if re.search('[SaUO]', elem.dtype.str) is not None:
raise TypeError(error_msg.format(elem.dtype))
return torch.stack([torch.from_numpy(b) for b in batch], 0)
if elem.shape == (): # scalars
py_type = float if elem.dtype.name.startswith('float') else int
return numpy_type_map[elem.dtype.name](list(map(py_type, batch)))
elif isinstance(batch[0], int_classes):
return torch.LongTensor(batch)
elif isinstance(batch[0], float):
return torch.DoubleTensor(batch)
elif isinstance(batch[0], string_classes):
return batch
elif isinstance(batch[0], container_abcs.Mapping):
return {key: default_collate([d[key] for d in batch]) for key in batch[0]}
elif isinstance(batch[0], container_abcs.Sequence):
transposed = zip(*batch)
return [default_collate(samples) for samples in transposed]
raise TypeError((error_msg.format(type(batch[0]))))
def pin_memory_batch(batch):
if isinstance(batch, torch.Tensor):
return batch.pin_memory()
elif isinstance(batch, string_classes):
return batch
elif isinstance(batch, container_abcs.Mapping):
return {k: pin_memory_batch(sample) for k, sample in batch.items()}
elif isinstance(batch, container_abcs.Sequence):
return [pin_memory_batch(sample) for sample in batch]
else:
return batch
_SIGCHLD_handler_set = False
r"""Whether SIGCHLD handler is set for DataLoader worker failures. Only one
handler needs to be set for all DataLoaders in a process."""
def _set_SIGCHLD_handler():
# Windows doesn't support SIGCHLD handler
if sys.platform == 'win32':
return
# can't set signal in child threads
if not isinstance(threading.current_thread(), threading._MainThread):
return
global _SIGCHLD_handler_set
if _SIGCHLD_handler_set:
return
previous_handler = signal.getsignal(signal.SIGCHLD)
if not callable(previous_handler):
# This doesn't catch default handler, but SIGCHLD default handler is a
# no-op.
previous_handler = None
def handler(signum, frame):
# This following call uses `waitid` with WNOHANG from C side. Therefore,
# Python can still get and update the process status successfully.
_error_if_any_worker_fails()
if previous_handler is not None:
previous_handler(signum, frame)
signal.signal(signal.SIGCHLD, handler)
_SIGCHLD_handler_set = True
_python_exit_status = False
r"""Whether Python is shutting down. This flag is guaranteed to be set before
the Python core library resources are freed, but Python may already be exiting
for some time when this is set.
Hook to set this flag is `_set_python_exit_flag`, and is inspired by a similar
hook in Python 3.7 multiprocessing library:
https://github.com/python/cpython/blob/d4d60134b29290049e28df54f23493de4f1824b6/Lib/multiprocessing/util.py#L277-L327
"""
def _set_python_exit_flag():
global _python_exit_status
_python_exit_status = True
atexit.register(_set_python_exit_flag)
class _DataLoaderIter(object):
r"""Iterates once over the DataLoader's dataset, as specified by the sampler"""
# NOTE [ Data Loader Multiprocessing Shutdown Logic ]
#
# Preliminary:
#
# Our data model looks like this (queues are indicated with curly brackets):
#
# main process ||
# | ||
# {index_queue} ||
# | ||
# worker processes || DATA
# | ||
# {worker_result_queue} || FLOW
# | ||
# pin_memory_thread of main process || DIRECTION
# | ||
# {data_queue} ||
# | ||
# data output \/
#
# P.S. `worker_result_queue` and `pin_memory_thread` part may be omitted if
# `pin_memory=False`.
#
#
# Terminating multiprocessing logic requires very careful design. In
# particular, we need to make sure that
#
# 1. The iterator gracefully exits the workers when its last reference is
# gone or it is depleted.
#
# In this case, the workers should be gracefully exited because the
# main process may still need to continue to run, and we want cleaning
# up code in the workers to be executed (e.g., releasing GPU memory).
# Naturally, we implement the shutdown logic in `__del__` of
# DataLoaderIterator.
#
# We delay the discussion on the logic in this case until later.
#
# 2. The iterator exits the workers when the loader process and/or worker
# processes exits normally or with error.
#
# We set all workers and `pin_memory_thread` to have `daemon=True`.
#
# You may ask, why can't we make the workers non-daemonic, and
# gracefully exit using the same logic as we have in `__del__` when the
# iterator gets deleted (see 1 above)?
#
# First of all, `__del__` is **not** guaranteed to be called when
# interpreter exits. Even if it is called, by the time it executes,
# many Python core library resources may already be freed, and even
# simple things like acquiring an internal lock of a queue may hang.
# Therefore, in this case, we actually need to prevent `__del__` from
# being executed, and rely on the automatic termination of daemonic
# children. Thus, we register an `atexit` hook that sets a global flag
# `_python_exit_status`. Since `atexit` hooks are executed in reverse
# order of registration, we are guaranteed that this flag is set before
# library resources we use are freed. (Hooks freeing those resources
# are registered at importing the Python core libraries at the top of
# this file.) So in `__del__`, we check if `_python_exit_status` is set
# or `None` (freed), and perform no-op if so.
#
# Another problem with `__del__` is also related to the library cleanup
# calls. When a process ends, it shuts the all its daemonic children
# down with a SIGTERM (instead of joining them without a timeout).
# Similarly for threads, but by a different mechanism. This fact,
# together with a few implementation details of multiprocessing, forces
# us to make workers daemonic. All of our problems arise when a
# DataLoader is used in a subprocess, and are caused by multiprocessing
# code which looks more or less like this:
#
# try:
# your_function_using_a_dataloader()
# finally:
# multiprocessing.util._exit_function()
#
# The joining/termination mentioned above happens inside
# `_exit_function()`. Now, if `your_function_using_a_dataloader()`
# throws, the stack trace stored in the exception will prevent the
# frame which uses `DataLoaderIter` to be freed. If the frame has any
# reference to the `DataLoaderIter` (e.g., in a method of the iter),
# its `__del__`, which starts the shutdown procedure, will not be
# called. That, in turn, means that workers aren't notified. Attempting
# to join in `_exit_function` will then result in a hang.
#
# For context, `_exit_function` is also registered as an `atexit` call.
# So it is unclear to me (@ssnl) why this is needed in a finally block.
# The code dates back to 2008 and there is no comment on the original
# PEP 371 or patch https://bugs.python.org/issue3050 (containing both
# the finally block and the `atexit` registration) that explains this.
#
# Another choice is to just shutdown workers with logic in 1 above
# whenever we see an error in `next`. This isn't ideal because
# a. It prevents users from using try-catch to resume data loading.
# b. It doesn't prevent hanging if users have references to the
# iterator.
#
# 3. All processes exit if any of them die unexpectedly by fatal signals.
#
# As shown above, the workers are set as daemonic children of the main
# process. However, automatic cleaning-up of such child processes only
# happens if the parent process exits gracefully (e.g., not via fatal
# signals like SIGKILL). So we must ensure that each process will exit
# even the process that should send/receive data to/from it were
# killed, i.e.,
#
# a. A process won't hang when getting from a queue.
#
# Even with carefully designed data dependencies (i.e., a `put()`
# always corresponding to a `get()`), hanging on `get()` can still
# happen when data in queue is corrupted (e.g., due to
# `cancel_join_thread` or unexpected exit).
#
# For child exit, we register SIGCHLD handler on main process,
# which checks if any of the workers fail in the (Python) handler.
# See DataLoader.cpp.
#
# For `.get()` calls where the sender(s) is not the workers, we
# guard them with timeouts, and check the status of the sender
# when timeout happens:
# + in the workers, the `ManagerWatchdog` class checks the main
# process status.
# + if `pin_memory=True`, when getting from `pin_memory_thread`,
# check `pin_memory_thread` status periodically until `.get()`
# returns or see that `pin_memory_thread` died.
#
# b. A process won't hang when putting into a queue;
#
# We use `mp.Queue` which has a separate background thread to put
# objects from an unbounded buffer array. The background thread is
# daemonic and usually automatically joined when the process
# exits.
#
# However, in case that the receiver has ended abruptly while
# reading from the pipe, the join will hang forever. Therefore,
# for both `worker_result_queue` (worker -> main process/pin_memory_thread)
# and each `index_queue` (main process -> worker), we use
# `q.cancel_join_thread()` in sender process before any `q.put` to
# prevent this automatic join.
#
# Moreover, having all queues called `cancel_join_thread` makes
# implementing graceful shutdown logic in `__del__` much easier.
# It won't need to get from any queue, which would also need to be
# guarded by periodic status checks.
#
# Note that this may leave corrupted data in the queue, but we
# don't care about the data anyways once we are shutting down.
#
#
# Now let's get back to 1:
# how we gracefully exit the workers when the last reference to the
# iterator is gone.
#
# To achieve this, we implement the following logic along with the design
# choices mentioned above:
#
# [worker processes]
# While loader process is alive:
# Get from index_queue.
# If got a `None`, exit.
# If get anything else,
# Check `done_event`.
# If set, continue to next iteration
# i.e., keep getting until see the `None`, then exit.
# Otherwise, process data.
# If timed out,
# No matter `done_event` is set (still need to see `None`) or not,
# must continue to next iteration .
#
# [pin_memory_thread]
# # No need to check main thread. If this thread is alive, the main loader
# # thread must be alive, because this thread is set as daemonic.
# While True:
# Get from index_queue.
# If got a `None`, exit.
# If get anything else,
# Check `done_event`.
# If set, continue to next iteration
# i.e., keep getting until see the `None`, then exit.
# Otherwise, process data.
#
# NOTE: we don't check the status of the main thread because
# 1. if the process is killed by fatal signal, `pin_memory_thread`
# ends.
# 2. in other cases, either the cleaning-up in __del__ or the
# automatic exit of daemonic thread will take care of it.
# This won't busy-wait either because `.get(timeout)` does not
# busy-wait.
#
# [main process]
# In the DataLoader Iter's `__del__`
# a. Set `done_event` (shared with `pin_memory_thread` and workers).
#
# Note: from here on, the workers & `pin_memory_thread` may exit at
# any time after they receive `None`.
#
# b. Exit `pin_memory_thread`
# i. Put `None` in `worker_result_queue`.
# ii. Join the `pin_memory_thread`.
#
# c. Exit the workers.
# i. Put `None` in each worker's `index_queue`.
# ii. Join the workers.
#
# NOTE: This has to be after (b) because it may leave corrupted data
# in `worker_result_queue`, which `pin_memory_thread` reads
# from.
#
# NOTE: If `pin_memory=False`, there is no `pin_memory_thread` and (b)
# can be omitted
#
# NB: `done_event`s isn't strictly needed. E.g., we can just check for
# `None` from `index_queue`, but it allows us to skip wasting resources
# processing indices already in `index_queue` if we are already shutting
# down.
def __init__(self, loader):
self.dataset = loader.dataset
self.collate_fn = loader.collate_fn
self.batch_sampler = loader.batch_sampler
self.num_workers = loader.num_workers
self.pin_memory = loader.pin_memory and torch.cuda.is_available()
self.timeout = loader.timeout
self.sample_iter = iter(self.batch_sampler)
base_seed = torch.LongTensor(1).random_().item()
if self.num_workers > 0:
self.worker_init_fn = loader.worker_init_fn
self.worker_queue_idx = 0
self.worker_result_queue = multiprocessing.Queue()
self.batches_outstanding = 0
self.worker_pids_set = False
self.shutdown = False
self.send_idx = 0
self.rcvd_idx = 0
self.reorder_dict = {}
self.done_event = multiprocessing.Event()
self.index_queues = []
self.workers = []
for i in range(self.num_workers):
index_queue = multiprocessing.Queue()
index_queue.cancel_join_thread()
w = multiprocessing.Process(
target=_worker_loop,
args=(self.dataset, index_queue,
self.worker_result_queue, self.done_event,
self.collate_fn, base_seed + i,
self.worker_init_fn, i))
w.daemon = True
# NB: Process.start() actually take some time as it needs to
# start a process and pass the arguments over via a pipe.
# Therefore, we only add a worker to self.workers list after
# it started, so that we do not call .join() if program dies
# before it starts, and __del__ tries to join but will get:
# AssertionError: can only join a started process.
w.start()
self.index_queues.append(index_queue)
self.workers.append(w)
if self.pin_memory:
self.data_queue = queue.Queue()
pin_memory_thread = threading.Thread(
target=_pin_memory_loop,
args=(self.worker_result_queue, self.data_queue,
torch.cuda.current_device(), self.done_event))
pin_memory_thread.daemon = True
pin_memory_thread.start()
# Similar to workers (see comment above), we only register
# pin_memory_thread once it is started.
self.pin_memory_thread = pin_memory_thread
else:
self.data_queue = self.worker_result_queue
_utils.signal_handling._set_worker_pids(id(self), tuple(w.pid for w in self.workers))
_utils.signal_handling._set_SIGCHLD_handler()
self.worker_pids_set = True
# prime the prefetch loop
for _ in range(2 * self.num_workers):
self._put_indices()
def __len__(self):
return len(self.batch_sampler)
def _get_batch(self):
# In the non-timeout case, worker exit is covered by SIGCHLD handler.
# But if `pin_memory=True`, we still need account for the possibility
# that `pin_memory_thread` dies.
if self.timeout > 0:
try:
return self.data_queue.get(timeout=self.timeout)
except queue.Empty:
raise RuntimeError('DataLoader timed out after {} seconds'.format(self.timeout))
elif self.pin_memory:
while self.pin_memory_thread.is_alive():
try:
return self.data_queue.get(timeout=MP_STATUS_CHECK_INTERVAL)
except queue.Empty:
continue
else:
# while condition is false, i.e., pin_memory_thread died.
raise RuntimeError('Pin memory thread exited unexpectedly')
# In this case, `self.data_queue` is a `queue.Queue`,. But we don't
# need to call `.task_done()` because we don't use `.join()`.
else:
return self.data_queue.get()
def __next__(self):
if self.num_workers == 0: # same-process loading
MyRandomResizedCrop.sample_image_size(0)
indices = next(self.sample_iter) # may raise StopIteration
batch = self.collate_fn([self.dataset[i] for i in indices])
if self.pin_memory:
batch = pin_memory_batch(batch)
return batch
# check if the next sample has already been generated
if self.rcvd_idx in self.reorder_dict:
batch = self.reorder_dict.pop(self.rcvd_idx)
return self._process_next_batch(batch)
if self.batches_outstanding == 0:
self._shutdown_workers()
raise StopIteration
while True:
assert (not self.shutdown and self.batches_outstanding > 0)
idx, batch = self._get_batch()
self.batches_outstanding -= 1
if idx != self.rcvd_idx:
# store out-of-order samples
self.reorder_dict[idx] = batch
continue
return self._process_next_batch(batch)
next = __next__ # Python 2 compatibility
def __iter__(self):
return self
def _put_indices(self):
assert self.batches_outstanding < 2 * self.num_workers
indices = next(self.sample_iter, None)
if indices is None:
return
self.index_queues[self.worker_queue_idx].put((self.send_idx, indices))
self.worker_queue_idx = (self.worker_queue_idx + 1) % self.num_workers
self.batches_outstanding += 1
self.send_idx += 1
def _process_next_batch(self, batch):
self.rcvd_idx += 1
self._put_indices()
if isinstance(batch, ExceptionWrapper):
raise batch.exc_type(batch.exc_msg)
return batch
def __getstate__(self):
# TODO: add limited pickling support for sharing an iterator
# across multiple threads for HOGWILD.
# Probably the best way to do this is by moving the sample pushing
# to a separate thread and then just sharing the data queue
# but signalling the end is tricky without a non-blocking API
raise NotImplementedError("_DataLoaderIter cannot be pickled")
def _shutdown_workers(self):
# See NOTE [ Data Loader Multiprocessing Shutdown Logic ] for details on
# the logic of this function.
if _python_exit_status is True or _python_exit_status is None:
# See (2) of the note. If Python is shutting down, do no-op.
return
# Normal exit when last reference is gone / iterator is depleted.
# See (1) and the second half of the note.
if not self.shutdown:
self.shutdown = True
# Removes pids from the C side data structure first so worker
# termination afterwards won't trigger false positive error report.
if self.worker_pids_set:
_remove_worker_pids(id(self))
self.worker_pids_set = False
self.done_event.set()
# Exit `pin_memory_thread` first because exiting workers may leave
# corrupted data in `worker_result_queue` which `pin_memory_thread`
# reads from.
if hasattr(self, 'pin_memory_thread'):
# Use hasattr in case error happens before we set the attribute.
# First time do `worker_result_queue.put` in this process.
# `cancel_join_thread` in case that `pin_memory_thread` exited.
self.worker_result_queue.cancel_join_thread()
self.worker_result_queue.put(None)
self.pin_memory_thread.join()
# Indicate that no more data will be put on this queue by the
# current process. This **must** be called after
# `pin_memory_thread` is joined because that thread shares the
# same pipe handles with this loader thread. If the handle is
# closed, Py3 will error in this case, but Py2 will just time
# out even if there is data in the queue.
self.worker_result_queue.close()
# Exit workers now.
for q in self.index_queues:
q.put(None)
# Indicate that no more data will be put on this queue by the
# current process.
q.close()
for w in self.workers:
w.join()
def __del__(self):
if self.num_workers > 0:
self._shutdown_workers()
class MyDataLoader(object):
r"""
Data loader. Combines a dataset and a sampler, and provides
single- or multi-process iterators over the dataset.
Arguments:
dataset (Dataset): dataset from which to load the data.
batch_size (int, optional): how many samples per batch to load
(default: ``1``).
shuffle (bool, optional): set to ``True`` to have the data reshuffled
at every epoch (default: ``False``).
sampler (Sampler, optional): defines the strategy to draw samples from
the dataset. If specified, ``shuffle`` must be False.
batch_sampler (Sampler, optional): like sampler, but returns a batch of
indices at a time. Mutually exclusive with :attr:`batch_size`,
:attr:`shuffle`, :attr:`sampler`, and :attr:`drop_last`.
num_workers (int, optional): how many subprocesses to use for data
loading. 0 means that the data will be loaded in the main process.
(default: ``0``)
collate_fn (callable, optional): merges a list of samples to form a mini-batch.
pin_memory (bool, optional): If ``True``, the data loader will copy tensors
into CUDA pinned memory before returning them.
drop_last (bool, optional): set to ``True`` to drop the last incomplete batch,
if the dataset size is not divisible by the batch size. If ``False`` and
the size of dataset is not divisible by the batch size, then the last batch
will be smaller. (default: ``False``)
timeout (numeric, optional): if positive, the timeout value for collecting a batch
from workers. Should always be non-negative. (default: ``0``)
worker_init_fn (callable, optional): If not ``None``, this will be called on each
worker subprocess with the worker id (an int in ``[0, num_workers - 1]``) as
input, after seeding and before data loading. (default: ``None``)
.. note:: By default, each worker will have its PyTorch seed set to
``base_seed + worker_id``, where ``base_seed`` is a long generated
by main process using its RNG. However, seeds for other libraries
may be duplicated upon initializing workers (w.g., NumPy), causing
each worker to return identical random numbers. (See
:ref:`dataloader-workers-random-seed` section in FAQ.) You may
use :func:`torch.initial_seed()` to access the PyTorch seed for
each worker in :attr:`worker_init_fn`, and use it to set other
seeds before data loading.
.. warning:: If ``spawn`` start method is used, :attr:`worker_init_fn` cannot be an
unpickable object, e.g., a lambda function.
"""
__initialized = False
def __init__(self, dataset, batch_size=1, shuffle=False, sampler=None, batch_sampler=None,
num_workers=0, collate_fn=default_collate, pin_memory=False, drop_last=False,
timeout=0, worker_init_fn=None):
print('Use MyDataLoader')
self.dataset = dataset
self.batch_size = batch_size
self.num_workers = num_workers
self.collate_fn = collate_fn
self.pin_memory = pin_memory
self.drop_last = drop_last
self.timeout = timeout
self.worker_init_fn = worker_init_fn
if timeout < 0:
raise ValueError('timeout option should be non-negative')
if batch_sampler is not None:
if batch_size > 1 or shuffle or sampler is not None or drop_last:
raise ValueError('batch_sampler option is mutually exclusive '
'with batch_size, shuffle, sampler, and '
'drop_last')
self.batch_size = None
self.drop_last = None
if sampler is not None and shuffle:
raise ValueError('sampler option is mutually exclusive with '
'shuffle')
if self.num_workers < 0:
raise ValueError('num_workers option cannot be negative; '
'use num_workers=0 to disable multiprocessing.')
if batch_sampler is None:
if sampler is None:
if shuffle:
sampler = RandomSampler(dataset)
else:
sampler = SequentialSampler(dataset)
batch_sampler = BatchSampler(sampler, batch_size, drop_last)
self.sampler = sampler
self.batch_sampler = batch_sampler
self.__initialized = True
def __setattr__(self, attr, val):
if self.__initialized and attr in ('batch_size', 'sampler', 'drop_last'):
raise ValueError('{} attribute should not be set after {} is '
'initialized'.format(attr, self.__class__.__name__))
super(MyDataLoader, self).__setattr__(attr, val)
def __iter__(self):
return _DataLoaderIter(self)
def __len__(self):
return len(self.batch_sampler)
| {
"pile_set_name": "Github"
} |
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You 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.
*/
/**
* <!-- Package description. -->
* Contains JNDI-based transaction manager lookup.
*/
package org.apache.ignite.cache.jta.jndi;
| {
"pile_set_name": "Github"
} |
{% extends 'SonataAdminBundle:CRUD:base_edit.html.twig' %}
{% block actions %}
<li>
<a href="{{ path('app_admin_committee_members', { id: object.id }) }}" class="sonata-action-element" title="Membres">
<i class="fa fa-users" aria-hidden="true"></i>
Membres
</a>
</li>
{% if object.isApproved %}
<li>
<a href="{{ path('app_committee_show', {'slug': object.slug}) }}"
class="sonata-action-element" title="Voir sur le site">
<i class="fa fa-eye" aria-hidden="true"></i>
Voir sur le site
</a>
</li>
{% endif %}
<li>
<a href="{{ path('admin_app_committee_show', { id: object.id }) }}" class="sonata-action-element" title="Afficher">
<i class="fa fa-eye" aria-hidden="true"></i>
Afficher
</a>
</li>
<li>
<a href="{{ path('admin_app_committee_list') }}" class="sonata-action-element" title="Retourner à la liste">
<i class="fa fa-list" aria-hidden="true"></i>
Retourner à la liste
</a>
</li>
{% endblock %}
| {
"pile_set_name": "Github"
} |
---
title: Diagnostics - Flame Graphs
layout: docs.hbs
---
# Flame Graphs
## What's a flame graph useful for?
Flame graphs are a way of visualizing CPU time spent in functions. They can help you pin down where you spend too much time doing synchronous operations.
## How to create a flame graph
You might have heard creating a flame graph for Node.js is difficult, but that's not true (anymore).
Solaris vms are no longer needed for flame graphs!
Flame graphs are generated from `perf` output, which is not a node-specific tool. While it's the most powerful way to visualize CPU time spent, it may have issues with how JavaScript code is optimized in Node.js 8 and above. See [perf output issues](#perf-output-issues) section below.
### Use a pre-packaged tool
If you want a single step that produces a flame graph locally, try [0x](https://www.npmjs.com/package/0x)
For diagnosing production deployments, read these notes: [0x production servers](https://github.com/davidmarkclements/0x/blob/master/docs/production-servers.md)
### Create a flame graph with system perf tools
The purpose of this guide is to show steps involved in creating a flame graph and keep you in control of each step.
If you want to understand each step better, take a look at the sections that follow where we go into more detail.
Now let's get to work.
1. Install `perf` (usually available through the linux-tools-common package if not already installed)
2. try running `perf` - it might complain about missing kernel modules, install them too
3. run node with perf enabled (see [perf output issues](#perf-output-issues) for tips specific to Node.js versions)
```bash
perf record -e cycles:u -g -- node --perf-basic-prof app.js
```
4. disregard warnings unless they're saying you can't run perf due to missing packages; you may get some warnings about not being able to access kernel module samples which you're not after anyway.
5. Run `perf script > perfs.out` to generate the data file you'll visualize in a moment. It's useful to [apply some cleanup](#filtering-out-node-js-internal-functions) for a more readable graph
6. install stackvis if not yet installed `npm i -g stackvis`
7. run `stackvis perf < perfs.out > flamegraph.htm`
Now open the flame graph file in your favorite browser and watch it burn. It's color-coded so you can focus on the most saturated orange bars first. They're likely to represent CPU heavy functions.
Worth mentioning - if you click an element of a flame graph a zoom-in of its surroundings will get displayed above the graph.
### Using `perf` to sample a running process
This is great for recording flame graph data from an already running process that you don't want to interrupt. Imagine a production process with a hard to reproduce issue.
```bash
perf record -F99 -p `pgrep -n node` -g -- sleep 3
```
Wait, what is that `sleep 3` for? It's there to keep the perf running - despite `-p` option pointing to a different pid, the command needs to be executed on a process and end with it.
perf runs for the life of the command you pass to it, whether or not you're actually profiling that command. `sleep 3` ensures that perf runs for 3 seconds.
Why is `-F` (profiling frequency) set to 99? It's a reasonable default. You can adjust if you want.
`-F99` tells perf to take 99 samples per second, for more precision increase the value. Lower values should produce less output with less precise results. Precision you need depends on how long your CPU intensive functions really run. If you're looking for the reason of a noticeable slowdown, 99 frames per second should be more than enough.
After you get that 3 second perf record, proceed with generating the flame graph with the last two steps from above.
### Filtering out Node.js internal functions
Usually you just want to look at the performance of your own calls, so filtering out Node.js and V8 internal functions can make the graph much easier to read. You can clean up your perf file with:
```bash
sed -i \
-e "/( __libc_start| LazyCompile | v8::internal::| Builtin:| Stub:| LoadIC:|\[unknown\]| LoadPolymorphicIC:)/d" \
-e 's/ LazyCompile:[*~]\?/ /' \
perfs.out
```
If you read your flame graph and it seems odd, as if something is missing in the key function taking up most time, try generating your flame graph without the filters - maybe you got a rare case of an issue with Node.js itself.
### Node.js's profiling options
`--perf-basic-prof-only-functions` and `--perf-basic-prof` are the two that are useful for debugging your JavaScript code. Other options are used for profiling Node.js itself, which is outside the scope of this guide.
`--perf-basic-prof-only-functions` produces less output, so it's the option with least overhead.
### Why do I need them at all?
Well, without these options you'll still get a flame graph, but with most bars labeled `v8::Function::Call`.
## `perf` output issues
### Node.js 8.x V8 pipeline changes
Node.js 8.x and above ships with new optimizations to JavaScript compilation pipeline in V8 engine which makes function names/references unreachable for perf sometimes. (It's called Turbofan)
The result is you might not get your function names right in the flame graph.
You'll notice `ByteCodeHandler:` where you'd expect function names.
[0x](https://www.npmjs.com/package/0x) has some mitigations for that built in.
For details see:
* https://github.com/nodejs/benchmarking/issues/168
* https://github.com/nodejs/diagnostics/issues/148#issuecomment-369348961
### Node.js 10+
Node.js 10.x addresses the issue with Turbofan using the `--interpreted-frames-native-stack` flag.
Run `node --interpreted-frames-native-stack --perf-basic-prof-only-functions` to get function names in the flame graph regardless of which pipeline V8 used to compile your JavaScript.
### Broken labels in the flame graph
If you're seeing labels looking like this
```
node`_ZN2v88internal11interpreter17BytecodeGenerator15VisitStatementsEPNS0_8ZoneListIPNS0_9StatementEEE
```
it means the Linux perf you're using was not compiled with demangle support, see https://bugs.launchpad.net/ubuntu/+source/linux/+bug/1396654 for example
## Examples
Practice capturing flame graphs yourself with [a flame graph exercise](https://github.com/naugtur/node-example-flamegraph)!
| {
"pile_set_name": "Github"
} |
//
// Generated by class-dump 3.5 (64 bit) (Debug version compiled Jun 9 2015 22:53:21).
//
// class-dump is Copyright (C) 1997-1998, 2000-2001, 2004-2014 by Steve Nygard.
//
#import <Cocoa/NSObject.h>
@interface EventHelpers : NSObject
{
}
+ (id)makeFilterAlbumFromDB:(id)arg1 withAlbumKeys:(id)arg2 withEventKeys:(id)arg3 withPersonKeys:(id)arg4;
+ (void)autoSplitPhotos:(struct IPPhotoList *)arg1 selectResult:(BOOL)arg2 preflightOnly:(BOOL)arg3 moveAfterEvent:(unsigned long long)arg4;
+ (void)_undoAutoSplitEventsForPhotos:(id)arg1 originalRolls:(id)arg2 newRolls:(id)arg3 firstRollKey:(unsigned long long)arg4 firstKeyPhotoKey:(unsigned long long)arg5 undoManager:(id)arg6 selection:(id)arg7;
+ (void)_redoAutoSplitEventsForPhotos:(id)arg1 originalRolls:(id)arg2 newRolls:(id)arg3 firstRollKey:(unsigned long long)arg4 firstKeyPhotoKey:(unsigned long long)arg5 undoManager:(id)arg6 selection:(id)arg7;
+ (void)coalescePhotos:(struct IPPhotoList *)arg1;
+ (int)upgradeSplitModePicker:(struct IPPhotoList *)arg1;
+ (BOOL)smartNameAlbum:(id)arg1 forRollKeys:(id)arg2;
@end
| {
"pile_set_name": "Github"
} |
/*
* This file is part of the SDWebImage package.
* (c) Olivier Poitrey <[email protected]>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
#import <Foundation/Foundation.h>
#import "SDWebImageCoder.h"
/**
Built in coder that supports PNG, JPEG, TIFF, includes support for progressive decoding.
GIF
Also supports static GIF (meaning will only handle the 1st frame).
For a full GIF support, we recommend `FLAnimatedImage` or our less performant `SDWebImageGIFCoder`
HEIC
This coder also supports HEIC format because ImageIO supports it natively. But it depends on the system capabilities, so it won't work on all devices, see: https://devstreaming-cdn.apple.com/videos/wwdc/2017/511tj33587vdhds/511/511_working_with_heif_and_hevc.pdf
Decode(Software): !Simulator && (iOS 11 || tvOS 11 || macOS 10.13)
Decode(Hardware): !Simulator && ((iOS 11 && A9Chip) || (macOS 10.13 && 6thGenerationIntelCPU))
Encode(Software): macOS 10.13
Encode(Hardware): !Simulator && ((iOS 11 && A10FusionChip) || (macOS 10.13 && 6thGenerationIntelCPU))
*/
@interface SDWebImageImageIOCoder : NSObject <SDWebImageProgressiveCoder>
+ (nonnull instancetype)sharedCoder;
@end
| {
"pile_set_name": "Github"
} |
package recoveryservices
// Copyright (c) Microsoft and contributors. 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.
//
// Code generated by Microsoft (R) AutoRest Code Generator.
// Changes may cause incorrect behavior and will be lost if the code is regenerated.
import (
"context"
"github.com/Azure/go-autorest/autorest"
"github.com/Azure/go-autorest/autorest/azure"
"github.com/Azure/go-autorest/tracing"
"net/http"
)
// Client is the recovery Services Client
type Client struct {
BaseClient
}
// NewClient creates an instance of the Client client.
func NewClient(subscriptionID string) Client {
return NewClientWithBaseURI(DefaultBaseURI, subscriptionID)
}
// NewClientWithBaseURI creates an instance of the Client client using a custom endpoint. Use this when interacting
// with an Azure cloud that uses a non-standard base URI (sovereign clouds, Azure stack).
func NewClientWithBaseURI(baseURI string, subscriptionID string) Client {
return Client{NewWithBaseURI(baseURI, subscriptionID)}
}
// CheckNameAvailability sends the check name availability request.
// Parameters:
// resourceGroupName - the name of the resource group where the recovery services vault is present.
// location - location of the resource
// input - contains information about Resource type and Resource name
func (client Client) CheckNameAvailability(ctx context.Context, resourceGroupName string, location string, input CheckNameAvailabilityParameters) (result CheckNameAvailabilityResult, err error) {
if tracing.IsEnabled() {
ctx = tracing.StartSpan(ctx, fqdn+"/Client.CheckNameAvailability")
defer func() {
sc := -1
if result.Response.Response != nil {
sc = result.Response.Response.StatusCode
}
tracing.EndSpan(ctx, sc, err)
}()
}
req, err := client.CheckNameAvailabilityPreparer(ctx, resourceGroupName, location, input)
if err != nil {
err = autorest.NewErrorWithError(err, "recoveryservices.Client", "CheckNameAvailability", nil, "Failure preparing request")
return
}
resp, err := client.CheckNameAvailabilitySender(req)
if err != nil {
result.Response = autorest.Response{Response: resp}
err = autorest.NewErrorWithError(err, "recoveryservices.Client", "CheckNameAvailability", resp, "Failure sending request")
return
}
result, err = client.CheckNameAvailabilityResponder(resp)
if err != nil {
err = autorest.NewErrorWithError(err, "recoveryservices.Client", "CheckNameAvailability", resp, "Failure responding to request")
}
return
}
// CheckNameAvailabilityPreparer prepares the CheckNameAvailability request.
func (client Client) CheckNameAvailabilityPreparer(ctx context.Context, resourceGroupName string, location string, input CheckNameAvailabilityParameters) (*http.Request, error) {
pathParameters := map[string]interface{}{
"location": autorest.Encode("path", location),
"resourceGroupName": autorest.Encode("path", resourceGroupName),
"subscriptionId": autorest.Encode("path", client.SubscriptionID),
}
const APIVersion = "2016-06-01"
queryParameters := map[string]interface{}{
"api-version": APIVersion,
}
preparer := autorest.CreatePreparer(
autorest.AsContentType("application/json; charset=utf-8"),
autorest.AsPost(),
autorest.WithBaseURL(client.BaseURI),
autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.RecoveryServices/locations/{location}/checkNameAvailability", pathParameters),
autorest.WithJSON(input),
autorest.WithQueryParameters(queryParameters))
return preparer.Prepare((&http.Request{}).WithContext(ctx))
}
// CheckNameAvailabilitySender sends the CheckNameAvailability request. The method will close the
// http.Response Body if it receives an error.
func (client Client) CheckNameAvailabilitySender(req *http.Request) (*http.Response, error) {
return client.Send(req, azure.DoRetryWithRegistration(client.Client))
}
// CheckNameAvailabilityResponder handles the response to the CheckNameAvailability request. The method always
// closes the http.Response Body.
func (client Client) CheckNameAvailabilityResponder(resp *http.Response) (result CheckNameAvailabilityResult, err error) {
err = autorest.Respond(
resp,
azure.WithErrorUnlessStatusCode(http.StatusOK),
autorest.ByUnmarshallingJSON(&result),
autorest.ByClosing())
result.Response = autorest.Response{Response: resp}
return
}
| {
"pile_set_name": "Github"
} |
<resources>
<!-- Default screen margins, per the Android Design guidelines. -->
<dimen name="activity_horizontal_margin">16dp</dimen>
<dimen name="activity_vertical_margin">16dp</dimen>
</resources>
| {
"pile_set_name": "Github"
} |
#if !defined(BOOST_PROTO_DONT_USE_PREPROCESSED_FILES)
#include <boost/proto/context/detail/preprocessed/null_eval.hpp>
#elif !defined(BOOST_PP_IS_ITERATING)
#define BOOST_PROTO_EVAL_N(Z, N, DATA) \
proto::eval(proto::child_c<N>(expr), ctx); \
/**/
#if defined(__WAVE__) && defined(BOOST_PROTO_CREATE_PREPROCESSED_FILES)
#pragma wave option(preserve: 2, line: 0, output: "preprocessed/null_eval.hpp")
#endif
///////////////////////////////////////////////////////////////////////////////
/// \file null_eval.hpp
/// Contains specializations of the null_eval\<\> class template.
//
// Copyright 2008 Eric Niebler. Distributed under the Boost
// Software License, Version 1.0. (See accompanying file
// LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
#if defined(__WAVE__) && defined(BOOST_PROTO_CREATE_PREPROCESSED_FILES)
#pragma wave option(preserve: 1)
#endif
#define BOOST_PP_ITERATION_PARAMS_1 \
(3, (1, BOOST_PROTO_MAX_ARITY, <boost/proto/context/detail/null_eval.hpp>))
#include BOOST_PP_ITERATE()
#if defined(__WAVE__) && defined(BOOST_PROTO_CREATE_PREPROCESSED_FILES)
#pragma wave option(output: null)
#endif
#undef BOOST_PROTO_EVAL_N
#else
#define N BOOST_PP_ITERATION()
template<typename Expr, typename Context>
struct null_eval<Expr, Context, N>
{
typedef void result_type;
void operator ()(Expr &expr, Context &ctx) const
{
BOOST_PP_REPEAT(N, BOOST_PROTO_EVAL_N, ~)
}
};
#undef N
#endif
| {
"pile_set_name": "Github"
} |
<?xml version="1.0" encoding="utf-8"?>
<Package
xmlns="http://schemas.microsoft.com/appx/manifest/foundation/windows10"
xmlns:mp="http://schemas.microsoft.com/appx/2014/phone/manifest"
xmlns:uap="http://schemas.microsoft.com/appx/manifest/uap/windows10"
IgnorableNamespaces="uap mp">
<Identity
Name="9470fffe-b034-4022-8a34-8c22053fcfd8"
Publisher="CN=fa9261b9-50b2-4c61-8b94-539c8bf7f156"
Version="1.0.0.0" />
<mp:PhoneIdentity PhoneProductId="ec0cc741-fd3e-485c-81be-68815c480690" PhonePublisherId="00000000-0000-0000-0000-000000000000"/>
<Properties>
<DisplayName>ChatClient.UWP</DisplayName>
<PublisherDisplayName>fa9261b9-50b2-4c61-8b94-539c8bf7f156</PublisherDisplayName>
<Logo>Assets\StoreLogo.png</Logo>
</Properties>
<Dependencies>
<TargetDeviceFamily Name="Windows.Universal" MinVersion="10.0.0.0" MaxVersionTested="10.0.0.0" />
</Dependencies>
<Resources>
<Resource Language="x-generate"/>
</Resources>
<Applications>
<Application Id="App"
Executable="$targetnametoken$.exe"
EntryPoint="ChatClient.UWP.App">
<uap:VisualElements
DisplayName="ChatClient.UWP"
Square150x150Logo="Assets\Square150x150Logo.png"
Square44x44Logo="Assets\Square44x44Logo.png"
Description="ChatClient.UWP"
BackgroundColor="transparent">
<uap:DefaultTile Wide310x150Logo="Assets\Wide310x150Logo.png" Square310x310Logo="Assets\LargeTile.png" Square71x71Logo="Assets\SmallTile.png">
<uap:ShowNameOnTiles>
<uap:ShowOn Tile="square150x150Logo" />
<uap:ShowOn Tile="wide310x150Logo" />
<uap:ShowOn Tile="square310x310Logo" />
</uap:ShowNameOnTiles>
</uap:DefaultTile>
<uap:SplashScreen Image="Assets\SplashScreen.png" />
</uap:VisualElements>
</Application>
</Applications>
<Capabilities>
<Capability Name="internetClient" />
</Capabilities>
</Package> | {
"pile_set_name": "Github"
} |
/** @file
*
* @authors Copyright © 2003-2017 Jaakko Keränen <[email protected]>
* @authors Copyright © 2006-2013 Daniel Swanson <[email protected]>
*
* @par License
* GPL: http://www.gnu.org/licenses/gpl.html
*
* <small>This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by the
* Free Software Foundation; either version 2 of the License, or (at your
* option) any later version. This program is distributed in the hope that it
* will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty
* of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General
* Public License for more details. You should have received a copy of the GNU
* General Public License along with this program; if not, see:
* http://www.gnu.org/licenses</small>
*/
/**
* Demos.
*/
#ifndef LIBDENG_DEMO_H
#define LIBDENG_DEMO_H
#ifdef __SERVER__
# error Demos are not available in a SERVER build
#endif
#ifdef __cplusplus
extern "C" {
#endif
extern int playback;
void Demo_Register(void);
void Demo_Init(void);
void Demo_Ticker(timespan_t time);
dd_bool Demo_BeginRecording(const char* filename, int playernum);
void Demo_StopRecording(int playernum);
void Demo_PauseRecording(int playernum);
void Demo_ResumeRecording(int playernum);
void Demo_WritePacket(int playernum);
void Demo_BroadcastPacket(void);
void Demo_ReadLocalCamera(void); // PKT_DEMOCAM
dd_bool Demo_BeginPlayback(const char* filename);
dd_bool Demo_ReadPacket(void);
void Demo_StopPlayback(void);
#ifdef __cplusplus
} // extern "C"
#endif
#endif /* LIBDENG_DEMO_H */
| {
"pile_set_name": "Github"
} |
{
"_args": [
[
"[email protected]",
"/Users/xingchenhe/Documents/work/git.code.oa.com/live-demo-component"
]
],
"_development": true,
"_from": "[email protected]",
"_id": "[email protected]",
"_inBundle": false,
"_integrity": "sha512-+uw1inIHVPQoaVuHzRyXd21icM+cnt4CzD5rW+NC1wjOUSTOs+Te7FOv7AhN7vS9x/oIyhLP5PR1H+phQAHu5Q==",
"_location": "/end-of-stream",
"_phantomChildren": {},
"_requested": {
"type": "version",
"registry": true,
"raw": "[email protected]",
"name": "end-of-stream",
"escapedName": "end-of-stream",
"rawSpec": "1.4.4",
"saveSpec": null,
"fetchSpec": "1.4.4"
},
"_requiredBy": [
"/tar-stream"
],
"_resolved": "https://registry.npmjs.org/end-of-stream/-/end-of-stream-1.4.4.tgz",
"_spec": "1.4.4",
"_where": "/Users/xingchenhe/Documents/work/git.code.oa.com/live-demo-component",
"author": {
"name": "Mathias Buus",
"email": "[email protected]"
},
"bugs": {
"url": "https://github.com/mafintosh/end-of-stream/issues"
},
"dependencies": {
"once": "^1.4.0"
},
"description": "Call a callback when a readable/writable/duplex stream has completed or failed.",
"devDependencies": {
"tape": "^4.11.0"
},
"files": [
"index.js"
],
"homepage": "https://github.com/mafintosh/end-of-stream",
"keywords": [
"stream",
"streams",
"callback",
"finish",
"close",
"end",
"wait"
],
"license": "MIT",
"main": "index.js",
"name": "end-of-stream",
"repository": {
"type": "git",
"url": "git://github.com/mafintosh/end-of-stream.git"
},
"scripts": {
"test": "node test.js"
},
"version": "1.4.4"
}
| {
"pile_set_name": "Github"
} |
/*
Copyright 2014 The Kubernetes Authors.
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.
*/
package version
// Base version information.
//
// This is the fallback data used when version information from git is not
// provided via go ldflags. It provides an approximation of the Kubernetes
// version for ad-hoc builds (e.g. `go build`) that cannot get the version
// information from git.
//
// If you are looking at these fields in the git tree, they look
// strange. They are modified on the fly by the build process. The
// in-tree values are dummy values used for "git archive", which also
// works for GitHub tar downloads.
//
// When releasing a new Kubernetes version, this file is updated by
// build/mark_new_version.sh to reflect the new version, and then a
// git annotated tag (using format vX.Y where X == Major version and Y
// == Minor version) is created to point to the commit that updates
// pkg/version/base.go
var (
// TODO: Deprecate gitMajor and gitMinor, use only gitVersion
// instead. First step in deprecation, keep the fields but make
// them irrelevant. (Next we'll take it out, which may muck with
// scripts consuming the kubectl version output - but most of
// these should be looking at gitVersion already anyways.)
gitMajor string = "" // major version, always numeric
gitMinor string = "" // minor version, numeric possibly followed by "+"
// semantic version, derived by build scripts (see
// https://git.k8s.io/community/contributors/design-proposals/release/versioning.md
// for a detailed discussion of this field)
//
// TODO: This field is still called "gitVersion" for legacy
// reasons. For prerelease versions, the build metadata on the
// semantic version is a git hash, but the version itself is no
// longer the direct output of "git describe", but a slight
// translation to be semver compliant.
// NOTE: The $Format strings are replaced during 'git archive' thanks to the
// companion .gitattributes file containing 'export-subst' in this same
// directory. See also https://git-scm.com/docs/gitattributes
gitVersion string = "v0.0.0-master+$Format:%h$"
gitCommit string = "$Format:%H$" // sha1 from git, output of $(git rev-parse HEAD)
gitTreeState string = "" // state of git tree, either "clean" or "dirty"
buildDate string = "1970-01-01T00:00:00Z" // build date in ISO8601 format, output of $(date -u +'%Y-%m-%dT%H:%M:%SZ')
)
| {
"pile_set_name": "Github"
} |
// Copyright 2018 The Prometheus Authors
// 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.
package procfs
// While implementing parsing of /proc/[pid]/mountstats, this blog was used
// heavily as a reference:
// https://utcc.utoronto.ca/~cks/space/blog/linux/NFSMountstatsIndex
//
// Special thanks to Chris Siebenmann for all of his posts explaining the
// various statistics available for NFS.
import (
"bufio"
"fmt"
"io"
"strconv"
"strings"
"time"
)
// Constants shared between multiple functions.
const (
deviceEntryLen = 8
fieldBytesLen = 8
fieldEventsLen = 27
statVersion10 = "1.0"
statVersion11 = "1.1"
fieldTransport10TCPLen = 10
fieldTransport10UDPLen = 7
fieldTransport11TCPLen = 13
fieldTransport11UDPLen = 10
)
// A Mount is a device mount parsed from /proc/[pid]/mountstats.
type Mount struct {
// Name of the device.
Device string
// The mount point of the device.
Mount string
// The filesystem type used by the device.
Type string
// If available additional statistics related to this Mount.
// Use a type assertion to determine if additional statistics are available.
Stats MountStats
}
// A MountStats is a type which contains detailed statistics for a specific
// type of Mount.
type MountStats interface {
mountStats()
}
// A MountStatsNFS is a MountStats implementation for NFSv3 and v4 mounts.
type MountStatsNFS struct {
// The version of statistics provided.
StatVersion string
// The mount options of the NFS mount.
Opts map[string]string
// The age of the NFS mount.
Age time.Duration
// Statistics related to byte counters for various operations.
Bytes NFSBytesStats
// Statistics related to various NFS event occurrences.
Events NFSEventsStats
// Statistics broken down by filesystem operation.
Operations []NFSOperationStats
// Statistics about the NFS RPC transport.
Transport NFSTransportStats
}
// mountStats implements MountStats.
func (m MountStatsNFS) mountStats() {}
// A NFSBytesStats contains statistics about the number of bytes read and written
// by an NFS client to and from an NFS server.
type NFSBytesStats struct {
// Number of bytes read using the read() syscall.
Read uint64
// Number of bytes written using the write() syscall.
Write uint64
// Number of bytes read using the read() syscall in O_DIRECT mode.
DirectRead uint64
// Number of bytes written using the write() syscall in O_DIRECT mode.
DirectWrite uint64
// Number of bytes read from the NFS server, in total.
ReadTotal uint64
// Number of bytes written to the NFS server, in total.
WriteTotal uint64
// Number of pages read directly via mmap()'d files.
ReadPages uint64
// Number of pages written directly via mmap()'d files.
WritePages uint64
}
// A NFSEventsStats contains statistics about NFS event occurrences.
type NFSEventsStats struct {
// Number of times cached inode attributes are re-validated from the server.
InodeRevalidate uint64
// Number of times cached dentry nodes are re-validated from the server.
DnodeRevalidate uint64
// Number of times an inode cache is cleared.
DataInvalidate uint64
// Number of times cached inode attributes are invalidated.
AttributeInvalidate uint64
// Number of times files or directories have been open()'d.
VFSOpen uint64
// Number of times a directory lookup has occurred.
VFSLookup uint64
// Number of times permissions have been checked.
VFSAccess uint64
// Number of updates (and potential writes) to pages.
VFSUpdatePage uint64
// Number of pages read directly via mmap()'d files.
VFSReadPage uint64
// Number of times a group of pages have been read.
VFSReadPages uint64
// Number of pages written directly via mmap()'d files.
VFSWritePage uint64
// Number of times a group of pages have been written.
VFSWritePages uint64
// Number of times directory entries have been read with getdents().
VFSGetdents uint64
// Number of times attributes have been set on inodes.
VFSSetattr uint64
// Number of pending writes that have been forcefully flushed to the server.
VFSFlush uint64
// Number of times fsync() has been called on directories and files.
VFSFsync uint64
// Number of times locking has been attempted on a file.
VFSLock uint64
// Number of times files have been closed and released.
VFSFileRelease uint64
// Unknown. Possibly unused.
CongestionWait uint64
// Number of times files have been truncated.
Truncation uint64
// Number of times a file has been grown due to writes beyond its existing end.
WriteExtension uint64
// Number of times a file was removed while still open by another process.
SillyRename uint64
// Number of times the NFS server gave less data than expected while reading.
ShortRead uint64
// Number of times the NFS server wrote less data than expected while writing.
ShortWrite uint64
// Number of times the NFS server indicated EJUKEBOX; retrieving data from
// offline storage.
JukeboxDelay uint64
// Number of NFS v4.1+ pNFS reads.
PNFSRead uint64
// Number of NFS v4.1+ pNFS writes.
PNFSWrite uint64
}
// A NFSOperationStats contains statistics for a single operation.
type NFSOperationStats struct {
// The name of the operation.
Operation string
// Number of requests performed for this operation.
Requests uint64
// Number of times an actual RPC request has been transmitted for this operation.
Transmissions uint64
// Number of times a request has had a major timeout.
MajorTimeouts uint64
// Number of bytes sent for this operation, including RPC headers and payload.
BytesSent uint64
// Number of bytes received for this operation, including RPC headers and payload.
BytesReceived uint64
// Duration all requests spent queued for transmission before they were sent.
CumulativeQueueMilliseconds uint64
// Duration it took to get a reply back after the request was transmitted.
CumulativeTotalResponseMilliseconds uint64
// Duration from when a request was enqueued to when it was completely handled.
CumulativeTotalRequestMilliseconds uint64
// The count of operations that complete with tk_status < 0. These statuses usually indicate error conditions.
Errors uint64
}
// A NFSTransportStats contains statistics for the NFS mount RPC requests and
// responses.
type NFSTransportStats struct {
// The transport protocol used for the NFS mount.
Protocol string
// The local port used for the NFS mount.
Port uint64
// Number of times the client has had to establish a connection from scratch
// to the NFS server.
Bind uint64
// Number of times the client has made a TCP connection to the NFS server.
Connect uint64
// Duration (in jiffies, a kernel internal unit of time) the NFS mount has
// spent waiting for connections to the server to be established.
ConnectIdleTime uint64
// Duration since the NFS mount last saw any RPC traffic.
IdleTimeSeconds uint64
// Number of RPC requests for this mount sent to the NFS server.
Sends uint64
// Number of RPC responses for this mount received from the NFS server.
Receives uint64
// Number of times the NFS server sent a response with a transaction ID
// unknown to this client.
BadTransactionIDs uint64
// A running counter, incremented on each request as the current difference
// ebetween sends and receives.
CumulativeActiveRequests uint64
// A running counter, incremented on each request by the current backlog
// queue size.
CumulativeBacklog uint64
// Stats below only available with stat version 1.1.
// Maximum number of simultaneously active RPC requests ever used.
MaximumRPCSlotsUsed uint64
// A running counter, incremented on each request as the current size of the
// sending queue.
CumulativeSendingQueue uint64
// A running counter, incremented on each request as the current size of the
// pending queue.
CumulativePendingQueue uint64
}
// parseMountStats parses a /proc/[pid]/mountstats file and returns a slice
// of Mount structures containing detailed information about each mount.
// If available, statistics for each mount are parsed as well.
func parseMountStats(r io.Reader) ([]*Mount, error) {
const (
device = "device"
statVersionPrefix = "statvers="
nfs3Type = "nfs"
nfs4Type = "nfs4"
)
var mounts []*Mount
s := bufio.NewScanner(r)
for s.Scan() {
// Only look for device entries in this function
ss := strings.Fields(string(s.Bytes()))
if len(ss) == 0 || ss[0] != device {
continue
}
m, err := parseMount(ss)
if err != nil {
return nil, err
}
// Does this mount also possess statistics information?
if len(ss) > deviceEntryLen {
// Only NFSv3 and v4 are supported for parsing statistics
if m.Type != nfs3Type && m.Type != nfs4Type {
return nil, fmt.Errorf("cannot parse MountStats for fstype %q", m.Type)
}
statVersion := strings.TrimPrefix(ss[8], statVersionPrefix)
stats, err := parseMountStatsNFS(s, statVersion)
if err != nil {
return nil, err
}
m.Stats = stats
}
mounts = append(mounts, m)
}
return mounts, s.Err()
}
// parseMount parses an entry in /proc/[pid]/mountstats in the format:
// device [device] mounted on [mount] with fstype [type]
func parseMount(ss []string) (*Mount, error) {
if len(ss) < deviceEntryLen {
return nil, fmt.Errorf("invalid device entry: %v", ss)
}
// Check for specific words appearing at specific indices to ensure
// the format is consistent with what we expect
format := []struct {
i int
s string
}{
{i: 0, s: "device"},
{i: 2, s: "mounted"},
{i: 3, s: "on"},
{i: 5, s: "with"},
{i: 6, s: "fstype"},
}
for _, f := range format {
if ss[f.i] != f.s {
return nil, fmt.Errorf("invalid device entry: %v", ss)
}
}
return &Mount{
Device: ss[1],
Mount: ss[4],
Type: ss[7],
}, nil
}
// parseMountStatsNFS parses a MountStatsNFS by scanning additional information
// related to NFS statistics.
func parseMountStatsNFS(s *bufio.Scanner, statVersion string) (*MountStatsNFS, error) {
// Field indicators for parsing specific types of data
const (
fieldOpts = "opts:"
fieldAge = "age:"
fieldBytes = "bytes:"
fieldEvents = "events:"
fieldPerOpStats = "per-op"
fieldTransport = "xprt:"
)
stats := &MountStatsNFS{
StatVersion: statVersion,
}
for s.Scan() {
ss := strings.Fields(string(s.Bytes()))
if len(ss) == 0 {
break
}
if len(ss) < 2 {
return nil, fmt.Errorf("not enough information for NFS stats: %v", ss)
}
switch ss[0] {
case fieldOpts:
if stats.Opts == nil {
stats.Opts = map[string]string{}
}
for _, opt := range strings.Split(ss[1], ",") {
split := strings.Split(opt, "=")
if len(split) == 2 {
stats.Opts[split[0]] = split[1]
} else {
stats.Opts[opt] = ""
}
}
case fieldAge:
// Age integer is in seconds
d, err := time.ParseDuration(ss[1] + "s")
if err != nil {
return nil, err
}
stats.Age = d
case fieldBytes:
bstats, err := parseNFSBytesStats(ss[1:])
if err != nil {
return nil, err
}
stats.Bytes = *bstats
case fieldEvents:
estats, err := parseNFSEventsStats(ss[1:])
if err != nil {
return nil, err
}
stats.Events = *estats
case fieldTransport:
if len(ss) < 3 {
return nil, fmt.Errorf("not enough information for NFS transport stats: %v", ss)
}
tstats, err := parseNFSTransportStats(ss[1:], statVersion)
if err != nil {
return nil, err
}
stats.Transport = *tstats
}
// When encountering "per-operation statistics", we must break this
// loop and parse them separately to ensure we can terminate parsing
// before reaching another device entry; hence why this 'if' statement
// is not just another switch case
if ss[0] == fieldPerOpStats {
break
}
}
if err := s.Err(); err != nil {
return nil, err
}
// NFS per-operation stats appear last before the next device entry
perOpStats, err := parseNFSOperationStats(s)
if err != nil {
return nil, err
}
stats.Operations = perOpStats
return stats, nil
}
// parseNFSBytesStats parses a NFSBytesStats line using an input set of
// integer fields.
func parseNFSBytesStats(ss []string) (*NFSBytesStats, error) {
if len(ss) != fieldBytesLen {
return nil, fmt.Errorf("invalid NFS bytes stats: %v", ss)
}
ns := make([]uint64, 0, fieldBytesLen)
for _, s := range ss {
n, err := strconv.ParseUint(s, 10, 64)
if err != nil {
return nil, err
}
ns = append(ns, n)
}
return &NFSBytesStats{
Read: ns[0],
Write: ns[1],
DirectRead: ns[2],
DirectWrite: ns[3],
ReadTotal: ns[4],
WriteTotal: ns[5],
ReadPages: ns[6],
WritePages: ns[7],
}, nil
}
// parseNFSEventsStats parses a NFSEventsStats line using an input set of
// integer fields.
func parseNFSEventsStats(ss []string) (*NFSEventsStats, error) {
if len(ss) != fieldEventsLen {
return nil, fmt.Errorf("invalid NFS events stats: %v", ss)
}
ns := make([]uint64, 0, fieldEventsLen)
for _, s := range ss {
n, err := strconv.ParseUint(s, 10, 64)
if err != nil {
return nil, err
}
ns = append(ns, n)
}
return &NFSEventsStats{
InodeRevalidate: ns[0],
DnodeRevalidate: ns[1],
DataInvalidate: ns[2],
AttributeInvalidate: ns[3],
VFSOpen: ns[4],
VFSLookup: ns[5],
VFSAccess: ns[6],
VFSUpdatePage: ns[7],
VFSReadPage: ns[8],
VFSReadPages: ns[9],
VFSWritePage: ns[10],
VFSWritePages: ns[11],
VFSGetdents: ns[12],
VFSSetattr: ns[13],
VFSFlush: ns[14],
VFSFsync: ns[15],
VFSLock: ns[16],
VFSFileRelease: ns[17],
CongestionWait: ns[18],
Truncation: ns[19],
WriteExtension: ns[20],
SillyRename: ns[21],
ShortRead: ns[22],
ShortWrite: ns[23],
JukeboxDelay: ns[24],
PNFSRead: ns[25],
PNFSWrite: ns[26],
}, nil
}
// parseNFSOperationStats parses a slice of NFSOperationStats by scanning
// additional information about per-operation statistics until an empty
// line is reached.
func parseNFSOperationStats(s *bufio.Scanner) ([]NFSOperationStats, error) {
const (
// Minimum number of expected fields in each per-operation statistics set
minFields = 9
)
var ops []NFSOperationStats
for s.Scan() {
ss := strings.Fields(string(s.Bytes()))
if len(ss) == 0 {
// Must break when reading a blank line after per-operation stats to
// enable top-level function to parse the next device entry
break
}
if len(ss) < minFields {
return nil, fmt.Errorf("invalid NFS per-operations stats: %v", ss)
}
// Skip string operation name for integers
ns := make([]uint64, 0, minFields-1)
for _, st := range ss[1:] {
n, err := strconv.ParseUint(st, 10, 64)
if err != nil {
return nil, err
}
ns = append(ns, n)
}
opStats := NFSOperationStats{
Operation: strings.TrimSuffix(ss[0], ":"),
Requests: ns[0],
Transmissions: ns[1],
MajorTimeouts: ns[2],
BytesSent: ns[3],
BytesReceived: ns[4],
CumulativeQueueMilliseconds: ns[5],
CumulativeTotalResponseMilliseconds: ns[6],
CumulativeTotalRequestMilliseconds: ns[7],
}
if len(ns) > 8 {
opStats.Errors = ns[8]
}
ops = append(ops, opStats)
}
return ops, s.Err()
}
// parseNFSTransportStats parses a NFSTransportStats line using an input set of
// integer fields matched to a specific stats version.
func parseNFSTransportStats(ss []string, statVersion string) (*NFSTransportStats, error) {
// Extract the protocol field. It is the only string value in the line
protocol := ss[0]
ss = ss[1:]
switch statVersion {
case statVersion10:
var expectedLength int
if protocol == "tcp" {
expectedLength = fieldTransport10TCPLen
} else if protocol == "udp" {
expectedLength = fieldTransport10UDPLen
} else {
return nil, fmt.Errorf("invalid NFS protocol \"%s\" in stats 1.0 statement: %v", protocol, ss)
}
if len(ss) != expectedLength {
return nil, fmt.Errorf("invalid NFS transport stats 1.0 statement: %v", ss)
}
case statVersion11:
var expectedLength int
if protocol == "tcp" {
expectedLength = fieldTransport11TCPLen
} else if protocol == "udp" {
expectedLength = fieldTransport11UDPLen
} else {
return nil, fmt.Errorf("invalid NFS protocol \"%s\" in stats 1.1 statement: %v", protocol, ss)
}
if len(ss) != expectedLength {
return nil, fmt.Errorf("invalid NFS transport stats 1.1 statement: %v", ss)
}
default:
return nil, fmt.Errorf("unrecognized NFS transport stats version: %q", statVersion)
}
// Allocate enough for v1.1 stats since zero value for v1.1 stats will be okay
// in a v1.0 response. Since the stat length is bigger for TCP stats, we use
// the TCP length here.
//
// Note: slice length must be set to length of v1.1 stats to avoid a panic when
// only v1.0 stats are present.
// See: https://github.com/prometheus/node_exporter/issues/571.
ns := make([]uint64, fieldTransport11TCPLen)
for i, s := range ss {
n, err := strconv.ParseUint(s, 10, 64)
if err != nil {
return nil, err
}
ns[i] = n
}
// The fields differ depending on the transport protocol (TCP or UDP)
// From https://utcc.utoronto.ca/%7Ecks/space/blog/linux/NFSMountstatsXprt
//
// For the udp RPC transport there is no connection count, connect idle time,
// or idle time (fields #3, #4, and #5); all other fields are the same. So
// we set them to 0 here.
if protocol == "udp" {
ns = append(ns[:2], append(make([]uint64, 3), ns[2:]...)...)
}
return &NFSTransportStats{
Protocol: protocol,
Port: ns[0],
Bind: ns[1],
Connect: ns[2],
ConnectIdleTime: ns[3],
IdleTimeSeconds: ns[4],
Sends: ns[5],
Receives: ns[6],
BadTransactionIDs: ns[7],
CumulativeActiveRequests: ns[8],
CumulativeBacklog: ns[9],
MaximumRPCSlotsUsed: ns[10],
CumulativeSendingQueue: ns[11],
CumulativePendingQueue: ns[12],
}, nil
}
| {
"pile_set_name": "Github"
} |
## 2018-05-25
#### python
* [jackfrued / Python-100-Days](https://github.com/jackfrued/Python-100-Days):Python - 100天从新手到大师
* [easy-tensorflow / easy-tensorflow](https://github.com/easy-tensorflow/easy-tensorflow):Simple and comprehensive tutorials in TensorFlow
* [tensorflow / models](https://github.com/tensorflow/models):Models and examples built with TensorFlow
* [toddmotto / public-apis](https://github.com/toddmotto/public-apis):A collective list of public JSON APIs for use in web development.
* [keras-team / keras](https://github.com/keras-team/keras):Deep Learning for humans
* [virajmavani / semi-auto-image-annotation-tool](https://github.com/virajmavani/semi-auto-image-annotation-tool):Anno-Mage: A Semi Automatic Image Annotation Tool which helps you in annotating images by suggesting you annotations for 80 object classes using a pre-trained model
* [scikit-learn / scikit-learn](https://github.com/scikit-learn/scikit-learn):scikit-learn: machine learning in Python
* [ambv / black](https://github.com/ambv/black):The uncompromising Python code formatter
* [vinta / awesome-python](https://github.com/vinta/awesome-python):A curated list of awesome Python frameworks, libraries, software and resources
* [trailofbits / algo](https://github.com/trailofbits/algo):Set up a personal IPSEC VPN in the cloud
* [m4ll0k / Galileo](https://github.com/m4ll0k/Galileo):Galileo - Web Application Audit Framework
* [django / django](https://github.com/django/django):The Web framework for perfectionists with deadlines.
* [pallets / flask](https://github.com/pallets/flask):The Python micro framework for building web applications.
* [google / youtube-8m](https://github.com/google/youtube-8m):Starter code for working with the YouTube-8M dataset.
* [ansible / ansible](https://github.com/ansible/ansible):Ansible is a radically simple IT automation platform that makes your applications and systems easier to deploy. Avoid writing scripts or custom code to deploy and update your applications — automate in a language that approaches plain English, using SSH, with no agents to install on remote systems. https://docs.ansible.com/ansible/
* [soimort / you-get](https://github.com/soimort/you-get):⏬
Dumb downloader that scrapes the web
* [requests / requests](https://github.com/requests/requests):Python HTTP Requests for Humans™
✨
🍰
✨
* [rg3 / youtube-dl](https://github.com/rg3/youtube-dl):Command-line program to download videos from YouTube.com and other video sites
* [facebookresearch / Detectron](https://github.com/facebookresearch/Detectron):FAIR's research platform for object detection research, implementing popular algorithms like Mask R-CNN and RetinaNet.
* [donnemartin / system-design-primer](https://github.com/donnemartin/system-design-primer):Learn how to design large-scale systems. Prep for the system design interview. Includes Anki flashcards.
* [python / cpython](https://github.com/python/cpython):The Python programming language
* [Embedding / Chinese-Word-Vectors](https://github.com/Embedding/Chinese-Word-Vectors):100+ Chinese Word Vectors 上百种预训练中文词向量
* [dnouri / skorch](https://github.com/dnouri/skorch):A scikit-learn compatible neural network library that wraps pytorch
* [1-Sisyphe / youCanCodeAGif](https://github.com/1-Sisyphe/youCanCodeAGif):Can you make an High Quality Gif from A to Z only by coding? Yes. Do you want to, though?
* [jakubroztocil / httpie](https://github.com/jakubroztocil/httpie):Modern command line HTTP client – user-friendly curl alternative with intuitive UI, JSON support, syntax highlighting, wget-like downloads, extensions, etc. https://httpie.org
#### swift
* [intuit / CardParts](https://github.com/intuit/CardParts):A reactive, card-based UI framework built on UIKit for iOS developers.
* [Ramotion / folding-cell](https://github.com/Ramotion/folding-cell):📃
FoldingCell is an expanding content cell with animation inspired by folding paper card material design. Swift UI Library by @Ramotion
* [phillipcaudell / Google-Drive-for-Mac](https://github.com/phillipcaudell/Google-Drive-for-Mac):A standalone macOS app for Google Docs, Sheets and Slides
* [naturaln0va / VisualActivityViewController](https://github.com/naturaln0va/VisualActivityViewController):A way to represent what you’re sharing.
* [huri000 / SwiftEntryKit](https://github.com/huri000/SwiftEntryKit):SwiftEntryKit is a banner presenter library for iOS. It can be used to easily display pop-ups and notification-like views within your iOS apps.
* [vsouza / awesome-ios](https://github.com/vsouza/awesome-ios):A curated list of awesome iOS ecosystem, including Objective-C and Swift Projects
* [Baddaboo / ClassicKit](https://github.com/Baddaboo/ClassicKit):💾
A collection of classic-style UI components for iOS
* [serhii-londar / open-source-mac-os-apps](https://github.com/serhii-londar/open-source-mac-os-apps):🚀
Awesome list of open source applications for macOS.
* [matteocrippa / awesome-swift](https://github.com/matteocrippa/awesome-swift):A collaborative list of awesome Swift libraries and resources. Feel free to contribute!
* [dkhamsing / open-source-ios-apps](https://github.com/dkhamsing/open-source-ios-apps):📱
Collaborative List of Open-Source iOS Apps
* [onevcat / Kingfisher](https://github.com/onevcat/Kingfisher):A lightweight, pure-Swift library for downloading and caching images from the web.
* [objcio / app-architecture](https://github.com/objcio/app-architecture):Sample Code of the App Architecture Book
* [airbnb / Lona](https://github.com/airbnb/Lona):A tool for defining design systems and using them to generate cross-platform UI code, Sketch files, and other artifacts.
* [mxcl / PromiseKit](https://github.com/mxcl/PromiseKit):Promises for Swift & ObjC
* [vapor / vapor](https://github.com/vapor/vapor):💧
A server-side Swift web framework.
* [insidegui / CloudKitCodable](https://github.com/insidegui/CloudKitCodable):An encoder and decoder for CKRecord
* [ralcr / ConsentKit](https://github.com/ralcr/ConsentKit):Swift library to help you add GDPR functionality to your app
* [Ramotion / swift-ui-animation-components-and-libraries](https://github.com/Ramotion/swift-ui-animation-components-and-libraries):Swift UI libraries, components and animations by @ramotion
* [ReactiveX / RxSwift](https://github.com/ReactiveX/RxSwift):Reactive Programming in Swift
* [yonaskolb / Stylist](https://github.com/yonaskolb/Stylist):Define UI styles in a hot-loadable external yaml or json file
* [xmartlabs / Eureka](https://github.com/xmartlabs/Eureka):Elegant iOS form builder in Swift
* [Alamofire / Alamofire](https://github.com/Alamofire/Alamofire):Elegant HTTP Networking in Swift
* [SwiftyJSON / SwiftyJSON](https://github.com/SwiftyJSON/SwiftyJSON):The better way to deal with JSON data in Swift.
* [dudongge / DDGScreenShot](https://github.com/dudongge/DDGScreenShot):
* [lhc70000 / iina](https://github.com/lhc70000/iina):The modern video player for macOS.
#### javascript
* [trekhleb / javascript-algorithms](https://github.com/trekhleb/javascript-algorithms):Algorithms and data structures implemented in JavaScript with explanations and links to further readings
* [wiredjs / wired-elements](https://github.com/wiredjs/wired-elements):Collection of elements that appear hand drawn. Great for wireframes.
* [mimecorg / vuido](https://github.com/mimecorg/vuido):Native desktop applications using Vue.js.
* [GetStream / Winds](https://github.com/GetStream/Winds):A Beautiful Open Source RSS & Podcast App
* [klauscfhq / signale](https://github.com/klauscfhq/signale):👋
Hackable console logger
* [ElemeFE / v-charts](https://github.com/ElemeFE/v-charts):基于 Vue2.0 和 ECharts 封装的图表组件
📈
📊
* [egoist / saber.js](https://github.com/egoist/saber.js):A minimalistic framework for building static website using Vue.js
* [vuejs / vue](https://github.com/vuejs/vue):🖖
A progressive, incrementally-adoptable JavaScript framework for building UI on the web.
* [hyperapp / hyperapp](https://github.com/hyperapp/hyperapp):1 kB JavaScript framework for building web applications.
* [facebook / react](https://github.com/facebook/react):A declarative, efficient, and flexible JavaScript library for building user interfaces.
* [RelaxedJS / ReLaXed](https://github.com/RelaxedJS/ReLaXed):Create PDF documents using web technologies
* [iamkun / dayjs](https://github.com/iamkun/dayjs):⏰
Day.js 2KB immutable date library alternative to Moment.js with the same modern API
* [alibaba / ice](https://github.com/alibaba/ice):🚀
飞冰 - 让前端开发简单而友好
* [facebook / create-react-app](https://github.com/facebook/create-react-app):Create React apps with no build configuration.
* [Meituan-Dianping / mpvue](https://github.com/Meituan-Dianping/mpvue):基于 Vue.js 的小程序开发框架,从底层支持 Vue.js 语法和构建工具体系。
* [drcmda / react-spring](https://github.com/drcmda/react-spring):🙌
Helping react-motion and animated to become best friends
* [axios / axios](https://github.com/axios/axios):Promise based HTTP client for the browser and node.js
* [vincentriemer / react-native-dom](https://github.com/vincentriemer/react-native-dom):An experimental, comprehensive port of React Native to the web.
* [mui-org / material-ui](https://github.com/mui-org/material-ui):React components that implement Google's Material Design.
* [GoogleChrome / puppeteer](https://github.com/GoogleChrome/puppeteer):Headless Chrome Node API
* [Tencent / wepy](https://github.com/Tencent/wepy):小程序组件化开发框架
* [facebook / react-native](https://github.com/facebook/react-native):A framework for building native apps with React.
* [olistic / warriorjs](https://github.com/olistic/warriorjs):An exciting game of programming and Artificial Intelligence
* [vuejs / vuepress](https://github.com/vuejs/vuepress):📝
Minimalistic Vue-powered static site generator
* [nodejs / node](https://github.com/nodejs/node):Node.js JavaScript runtime
✨
🐢
🚀
✨
#### go
* [intenthq / anon](https://github.com/intenthq/anon):A UNIX Command To Anonymise Data
* [ketchuphq / ketchup](https://github.com/ketchuphq/ketchup):A simple CMS
🍅
* [kubernetes / kubernetes](https://github.com/kubernetes/kubernetes):Production-Grade Container Scheduling and Management
* [golang / go](https://github.com/golang/go):The Go programming language
* [ethereum / go-ethereum](https://github.com/ethereum/go-ethereum):Official Go implementation of the Ethereum protocol
* [fatedier / frp](https://github.com/fatedier/frp):A fast reverse proxy to help you expose a local server behind a NAT or firewall to the internet.
* [gohugoio / hugo](https://github.com/gohugoio/hugo):The world’s fastest framework for building websites.
* [avelino / awesome-go](https://github.com/avelino/awesome-go):A curated list of awesome Go frameworks, libraries and software
* [gogits / gogs](https://github.com/gogits/gogs):Gogs is a painless self-hosted Git service.
* [gin-gonic / gin](https://github.com/gin-gonic/gin):Gin is a HTTP web framework written in Go (Golang). It features a Martini-like API with much better performance -- up to 40 times faster. If you need smashing performance, get yourself some Gin.
* [tobgu / qframe](https://github.com/tobgu/qframe):Immutable data frame for Go
* [txthinking / brook](https://github.com/txthinking/brook):Brook is a cross-platform(Linux/MacOS/Windows/Android/iOS) proxy software
* [astaxie / build-web-application-with-golang](https://github.com/astaxie/build-web-application-with-golang):A golang ebook intro how to build a web with golang
* [moby / moby](https://github.com/moby/moby):Moby Project - a collaborative project for the container ecosystem to assemble container-based systems
* [coreos / etcd](https://github.com/coreos/etcd):Distributed reliable key-value store for the most critical data of a distributed system
* [gobuffalo / buffalo](https://github.com/gobuffalo/buffalo):Rapid Web Development w/ Go
* [go-gitea / gitea](https://github.com/go-gitea/gitea):Gitea: Git with a cup of tea
* [istio / istio](https://github.com/istio/istio):An open platform to connect, manage, and secure microservices.
* [tsenart / vegeta](https://github.com/tsenart/vegeta):HTTP load testing tool and library. It's over 9000!
* [golang / vgo](https://github.com/golang/vgo):[mirror] Versioned Go Prototype
* [keybase / saltpack](https://github.com/keybase/saltpack):a modern crypto messaging format
* [golang / dep](https://github.com/golang/dep):Go dependency management tool
* [pingcap / tidb](https://github.com/pingcap/tidb):TiDB is a distributed HTAP database compatible with the MySQL protocol
* [kubernetes / kops](https://github.com/kubernetes/kops):Kubernetes Operations (kops) - Production Grade K8s Installation, Upgrades, and Management
* [getlantern / lantern](https://github.com/getlantern/lantern):🔴
Lantern Latest Download https://github.com/getlantern/lantern/releases/tag/latest
🔴
蓝灯最新版本下载 https://github.com/getlantern/forum/issues/833
🔴
| {
"pile_set_name": "Github"
} |
set hive.mapred.mode=nonstrict;
-- start query 1 in stream 0 using template query88.tpl and seed 318176889
explain cbo
select *
from
(select count(*) h8_30_to_9
from store_sales, household_demographics , time_dim, store
where ss_sold_time_sk = time_dim.t_time_sk
and ss_hdemo_sk = household_demographics.hd_demo_sk
and ss_store_sk = s_store_sk
and time_dim.t_hour = 8
and time_dim.t_minute >= 30
and ((household_demographics.hd_dep_count = 3 and household_demographics.hd_vehicle_count<=3+2) or
(household_demographics.hd_dep_count = 0 and household_demographics.hd_vehicle_count<=0+2) or
(household_demographics.hd_dep_count = 1 and household_demographics.hd_vehicle_count<=1+2))
and store.s_store_name = 'ese') s1,
(select count(*) h9_to_9_30
from store_sales, household_demographics , time_dim, store
where ss_sold_time_sk = time_dim.t_time_sk
and ss_hdemo_sk = household_demographics.hd_demo_sk
and ss_store_sk = s_store_sk
and time_dim.t_hour = 9
and time_dim.t_minute < 30
and ((household_demographics.hd_dep_count = 3 and household_demographics.hd_vehicle_count<=3+2) or
(household_demographics.hd_dep_count = 0 and household_demographics.hd_vehicle_count<=0+2) or
(household_demographics.hd_dep_count = 1 and household_demographics.hd_vehicle_count<=1+2))
and store.s_store_name = 'ese') s2,
(select count(*) h9_30_to_10
from store_sales, household_demographics , time_dim, store
where ss_sold_time_sk = time_dim.t_time_sk
and ss_hdemo_sk = household_demographics.hd_demo_sk
and ss_store_sk = s_store_sk
and time_dim.t_hour = 9
and time_dim.t_minute >= 30
and ((household_demographics.hd_dep_count = 3 and household_demographics.hd_vehicle_count<=3+2) or
(household_demographics.hd_dep_count = 0 and household_demographics.hd_vehicle_count<=0+2) or
(household_demographics.hd_dep_count = 1 and household_demographics.hd_vehicle_count<=1+2))
and store.s_store_name = 'ese') s3,
(select count(*) h10_to_10_30
from store_sales, household_demographics , time_dim, store
where ss_sold_time_sk = time_dim.t_time_sk
and ss_hdemo_sk = household_demographics.hd_demo_sk
and ss_store_sk = s_store_sk
and time_dim.t_hour = 10
and time_dim.t_minute < 30
and ((household_demographics.hd_dep_count = 3 and household_demographics.hd_vehicle_count<=3+2) or
(household_demographics.hd_dep_count = 0 and household_demographics.hd_vehicle_count<=0+2) or
(household_demographics.hd_dep_count = 1 and household_demographics.hd_vehicle_count<=1+2))
and store.s_store_name = 'ese') s4,
(select count(*) h10_30_to_11
from store_sales, household_demographics , time_dim, store
where ss_sold_time_sk = time_dim.t_time_sk
and ss_hdemo_sk = household_demographics.hd_demo_sk
and ss_store_sk = s_store_sk
and time_dim.t_hour = 10
and time_dim.t_minute >= 30
and ((household_demographics.hd_dep_count = 3 and household_demographics.hd_vehicle_count<=3+2) or
(household_demographics.hd_dep_count = 0 and household_demographics.hd_vehicle_count<=0+2) or
(household_demographics.hd_dep_count = 1 and household_demographics.hd_vehicle_count<=1+2))
and store.s_store_name = 'ese') s5,
(select count(*) h11_to_11_30
from store_sales, household_demographics , time_dim, store
where ss_sold_time_sk = time_dim.t_time_sk
and ss_hdemo_sk = household_demographics.hd_demo_sk
and ss_store_sk = s_store_sk
and time_dim.t_hour = 11
and time_dim.t_minute < 30
and ((household_demographics.hd_dep_count = 3 and household_demographics.hd_vehicle_count<=3+2) or
(household_demographics.hd_dep_count = 0 and household_demographics.hd_vehicle_count<=0+2) or
(household_demographics.hd_dep_count = 1 and household_demographics.hd_vehicle_count<=1+2))
and store.s_store_name = 'ese') s6,
(select count(*) h11_30_to_12
from store_sales, household_demographics , time_dim, store
where ss_sold_time_sk = time_dim.t_time_sk
and ss_hdemo_sk = household_demographics.hd_demo_sk
and ss_store_sk = s_store_sk
and time_dim.t_hour = 11
and time_dim.t_minute >= 30
and ((household_demographics.hd_dep_count = 3 and household_demographics.hd_vehicle_count<=3+2) or
(household_demographics.hd_dep_count = 0 and household_demographics.hd_vehicle_count<=0+2) or
(household_demographics.hd_dep_count = 1 and household_demographics.hd_vehicle_count<=1+2))
and store.s_store_name = 'ese') s7,
(select count(*) h12_to_12_30
from store_sales, household_demographics , time_dim, store
where ss_sold_time_sk = time_dim.t_time_sk
and ss_hdemo_sk = household_demographics.hd_demo_sk
and ss_store_sk = s_store_sk
and time_dim.t_hour = 12
and time_dim.t_minute < 30
and ((household_demographics.hd_dep_count = 3 and household_demographics.hd_vehicle_count<=3+2) or
(household_demographics.hd_dep_count = 0 and household_demographics.hd_vehicle_count<=0+2) or
(household_demographics.hd_dep_count = 1 and household_demographics.hd_vehicle_count<=1+2))
and store.s_store_name = 'ese') s8
;
-- end query 1 in stream 0 using template query88.tpl
| {
"pile_set_name": "Github"
} |
namespace AngleSharp.Core.Tests.Library
{
using AngleSharp.Core.Tests.Mocks;
using AngleSharp.Html.Parser;
using NUnit.Framework;
using System.Text;
using System.Threading.Tasks;
[TestFixture]
public class AsyncParsingTests
{
[Test]
public async Task TestAsyncHtmlParsingFromStream()
{
var text = "<html><head><title>My test</title></head><body><p>Some text</p></body></html>";
var source = new DelayedStream(Encoding.UTF8.GetBytes(text));
var parser = new HtmlParser();
using (var task = parser.ParseDocumentAsync(source))
{
Assert.IsFalse(task.IsCompleted);
var result = await task;
Assert.IsTrue(task.IsCompleted);
Assert.AreEqual("My test", result.Title);
Assert.AreEqual(1, result.Body.ChildElementCount);
Assert.AreEqual("Some text", result.Body.Children[0].TextContent);
}
}
[Test]
public async Task TestAsyncHtmlParsingFromString()
{
var source = "<html><head><title>My test</title></head><body><p>Some text</p></body></html>";
var parser = new HtmlParser();
using (var task = parser.ParseDocumentAsync(source))
{
Assert.IsTrue(task.IsCompleted);
var result = await task;
Assert.AreEqual("My test", result.Title);
Assert.AreEqual(1, result.Body.ChildElementCount);
Assert.AreEqual("Some text", result.Body.Children[0].TextContent);
}
}
}
}
| {
"pile_set_name": "Github"
} |
package org.zstack.sdk;
public class DeleteVmInstanceHaLevelResult {
}
| {
"pile_set_name": "Github"
} |
<?php
/**
* pre Measure 0102 -- Numerator
*
* Copyright (C) 2015 - 2017 Suncoast Connection
*
* LICENSE: This Source Code Form is subject to the terms of the Mozilla Public License, v. 2.0
* See the Mozilla Public License for more details.
* If a copy of the MPL was not distributed with this file, You can obtain one at https://mozilla.org/MPL/2.0/.
*
* @author Art Eaton <[email protected]>
* @author Bryan lee <[email protected]>
* @package LibreHealthEHR
* @link http://suncoastconnection.com
* @link http://librehealth.io
*
* Please support this product by sharing your changes with the LibreHealth.io community.
*/
class pre_0102_Numerator extends PQRSFilter
{
public function getTitle()
{
return "Numerator";
}
public function test( PQRSPatient $patient, $beginDate, $endDate )
{
$query =
" SELECT COUNT(b1.code) AS count".
" FROM billing AS b1".
" JOIN form_encounter AS fe ON (b1.encounter = fe.encounter)".
" WHERE b1.pid = ? ".
" AND fe.date BETWEEN '".$beginDate."' AND '".$endDate."' ".
" AND (b1.code = '3270F' AND b1.modifier =''); ";
//3269F is hard fail
$result = sqlFetchArray(sqlStatementNoLog($query, array($patient->id)));
if ($result['count']> 0){ return true;} else {return false;}
}
}
| {
"pile_set_name": "Github"
} |
{
"$schema": "https://schema.management.azure.com/schemas/2019-04-01/deploymentTemplate.json#",
"contentVersion": "1.0.0.1",
"parameters": {
"resourceAPIVersion": {
"type": "string"
},
"networkSpec": {
"type": "object"
},
"masterNodeASName": {
"type": "string"
},
"dataNodeASName": {
"type": "string"
},
"location": {
"type": "string",
"defaultValue": "[resourceGroup().location]",
"metadata": {
"description": "Location for all resources."
}
}
},
"variables": {},
"resources": [
{
"type": "Microsoft.Compute/availabilitySets",
"apiVersion":"2017-12-01",
"name": "[parameters('masterNodeASName')]",
"location": "[parameters('location')]",
"sku": {
"name": "Aligned"
},
"properties": {
"platformFaultDomainCount": 2,
"platformUpdateDomainCount": 5
}
},
{
"type": "Microsoft.Compute/availabilitySets",
"apiVersion":"2017-12-01",
"name": "[parameters('dataNodeASName')]",
"location": "[parameters('location')]",
"sku": {
"name": "Aligned"
},
"properties": {
"platformFaultDomainCount": 2,
"platformUpdateDomainCount": 5
}
},
{
"type": "Microsoft.Network/networkSecurityGroups",
"name": "[concat(parameters('networkSpec').virtualNetworkName, '-sg')]",
"location": "[parameters('location')]",
"properties": {
"securityRules": [
{
"name": "SSH",
"properties": {
"description": "Allows SSH traffic",
"protocol": "Tcp",
"sourcePortRange": "*",
"destinationPortRange": "22",
"sourceAddressPrefix": "*",
"destinationAddressPrefix": "*",
"access": "Allow",
"priority": 100,
"direction": "Inbound"
}
}
]
}
},
{
"type": "Microsoft.Network/virtualNetworks",
"name": "[parameters('networkSpec').virtualNetworkName]",
"apiVersion": "2018-08-01",
"dependsOn": [
"[concat('Microsoft.Network/networkSecurityGroups/', parameters('networkSpec').virtualNetworkName, '-sg')]"
],
"location": "[parameters('location')]",
"properties": {
"addressSpace": {
"addressPrefixes": [
"[parameters('networkSpec').addressPrefix]"
]
},
"subnets": [
{
"name": "[parameters('networkSpec').virtualNetworkSubnetName]",
"properties": {
"addressPrefix": "[parameters('networkSpec').subnetPrefix]",
"networkSecurityGroup": {
"id": "[resourceId('Microsoft.Network/networkSecurityGroups', concat(parameters('networkSpec').virtualNetworkName, '-sg'))]"
}
}
}
]
}
}
]
}
| {
"pile_set_name": "Github"
} |
# -*- encoding: utf-8 -*-
# Copyright 2012 Citrix Systems, Inc. Licensed under the
# Apache License, Version 2.0 (the "License"); you may not use this
# file except in compliance with the License. Citrix Systems, Inc.
# reserves all rights not expressly granted by 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.
#
# Automatically generated by addcopyright.py at 04/03/2012
""" BVT tests for SSVM
"""
#Import Local Modules
import marvin
from marvin.cloudstackTestCase import *
from marvin.cloudstackAPI import *
from marvin import remoteSSHClient
from integration.lib.utils import *
from integration.lib.base import *
from integration.lib.common import *
import telnetlib
#Import System modules
import time
class Services:
"""Test SSVM Services
"""
def __init__(self):
self.services = {
"host": {
"username": 'root', # Credentials for SSH
"password": 'fr3sca',
"publicport": 22,
},
"sleep": 60,
"timeout": 10,
}
class TestSSVMs(cloudstackTestCase):
def setUp(self):
self.apiclient = self.testClient.getApiClient()
self.cleanup = []
self.services = Services().services
self.zone = get_zone(self.apiclient, self.services)
return
def tearDown(self):
try:
#Clean up, terminate the created templates
cleanup_resources(self.apiclient, self.cleanup)
except Exception as e:
raise Exception("Warning: Exception during cleanup : %s" % e)
return
def test_01_list_sec_storage_vm(self):
"""Test List secondary storage VMs
"""
# Validate the following:
# 1. listSystemVM (systemvmtype=secondarystoragevm)
# should return only ONE SSVM per zone
# 2. The returned SSVM should be in Running state
# 3. listSystemVM for secondarystoragevm should list publicip,
# privateip and link-localip
# 4. The gateway programmed on the ssvm by listSystemVm should be
# the same as the gateway returned by listVlanIpRanges
# 5. DNS entries must match those given for the zone
list_ssvm_response = list_ssvms(
self.apiclient,
systemvmtype='secondarystoragevm',
state='Running',
zoneid=self.zone.id
)
self.assertEqual(
isinstance(list_ssvm_response, list),
True,
"Check list response returns a valid list"
)
#Verify SSVM response
self.assertNotEqual(
len(list_ssvm_response),
0,
"Check list System VMs response"
)
list_zones_response = list_zones(self.apiclient)
self.assertEqual(
isinstance(list_zones_response, list),
True,
"Check list response returns a valid list"
)
self.debug("Number of zones: %s" % len(list_zones_response))
self.debug("Number of SSVMs: %s" % len(list_ssvm_response))
# Number of Sec storage VMs = No of Zones
self.assertEqual(
len(list_ssvm_response),
len(list_zones_response),
"Check number of SSVMs with number of zones"
)
#For each secondary storage VM check private IP,
#public IP, link local IP and DNS
for ssvm in list_ssvm_response:
self.debug("SSVM state: %s" % ssvm.state)
self.assertEqual(
ssvm.state,
'Running',
"Check whether state of SSVM is running"
)
self.assertEqual(
hasattr(ssvm, 'privateip'),
True,
"Check whether SSVM has private IP field"
)
self.assertEqual(
hasattr(ssvm, 'linklocalip'),
True,
"Check whether SSVM has link local IP field"
)
self.assertEqual(
hasattr(ssvm, 'publicip'),
True,
"Check whether SSVM has public IP field"
)
#Fetch corresponding ip ranges information from listVlanIpRanges
ipranges_response = list_vlan_ipranges(
self.apiclient,
zoneid=ssvm.zoneid
)
self.assertEqual(
isinstance(ipranges_response, list),
True,
"Check list response returns a valid list"
)
iprange = ipranges_response[0]
self.assertEqual(
ssvm.gateway,
iprange.gateway,
"Check gateway with that of corresponding ip range"
)
#Fetch corresponding zone information from listZones
zone_response = list_zones(
self.apiclient,
id=ssvm.zoneid
)
self.assertEqual(
isinstance(zone_response, list),
True,
"Check list response returns a valid list"
)
self.assertEqual(
ssvm.dns1,
zone_response[0].dns1,
"Check DNS1 with that of corresponding zone"
)
self.assertEqual(
ssvm.dns2,
zone_response[0].dns2,
"Check DNS2 with that of corresponding zone"
)
return
def test_02_list_cpvm_vm(self):
"""Test List console proxy VMs
"""
# Validate the following:
# 1. listSystemVM (systemvmtype=consoleproxy) should return
# at least ONE CPVM per zone
# 2. The returned ConsoleProxyVM should be in Running state
# 3. listSystemVM for console proxy should list publicip, privateip
# and link-localip
# 4. The gateway programmed on the console proxy should be the same
# as the gateway returned by listZones
# 5. DNS entries must match those given for the zone
list_cpvm_response = list_ssvms(
self.apiclient,
systemvmtype='consoleproxy',
state='Running',
zoneid=self.zone.id
)
self.assertEqual(
isinstance(list_cpvm_response, list),
True,
"Check list response returns a valid list"
)
#Verify CPVM response
self.assertNotEqual(
len(list_cpvm_response),
0,
"Check list System VMs response"
)
list_zones_response = list_zones(self.apiclient)
# Number of Console Proxy VMs = No of Zones
self.assertEqual(
isinstance(list_zones_response, list),
True,
"Check list response returns a valid list"
)
self.debug("Number of zones: %s" % len(list_zones_response))
self.debug("Number of CPVMs: %s" % len(list_cpvm_response))
self.assertEqual(
len(list_cpvm_response),
len(list_zones_response),
"Check number of CPVMs with number of zones"
)
#For each CPVM check private IP, public IP, link local IP and DNS
for cpvm in list_cpvm_response:
self.debug("CPVM state: %s" % cpvm.state)
self.assertEqual(
cpvm.state,
'Running',
"Check whether state of CPVM is running"
)
self.assertEqual(
hasattr(cpvm, 'privateip'),
True,
"Check whether CPVM has private IP field"
)
self.assertEqual(
hasattr(cpvm, 'linklocalip'),
True,
"Check whether CPVM has link local IP field"
)
self.assertEqual(
hasattr(cpvm, 'publicip'),
True,
"Check whether CPVM has public IP field"
)
#Fetch corresponding ip ranges information from listVlanIpRanges
ipranges_response = list_vlan_ipranges(
self.apiclient,
zoneid=cpvm.zoneid
)
self.assertEqual(
isinstance(ipranges_response, list),
True,
"Check list response returns a valid list"
)
iprange = ipranges_response[0]
self.assertEqual(
cpvm.gateway,
iprange.gateway,
"Check gateway with that of corresponding ip range"
)
#Fetch corresponding zone information from listZones
zone_response = list_zones(
self.apiclient,
id=cpvm.zoneid
)
self.assertEqual(
cpvm.dns1,
zone_response[0].dns1,
"Check DNS1 with that of corresponding zone"
)
self.assertEqual(
cpvm.dns2,
zone_response[0].dns2,
"Check DNS2 with that of corresponding zone"
)
return
def test_03_ssvm_internals(self):
"""Test SSVM Internals"""
# Validate the following
# 1. The SSVM check script should not return any
# WARN|ERROR|FAIL messages
# 2. If you are unable to login to the SSVM with the signed key
# then test is deemed a failure
# 3. There should be only one ""cloud"" process running within the SSVM
# 4. If no process is running/multiple process are running
# then the test is a failure
list_ssvm_response = list_ssvms(
self.apiclient,
systemvmtype='secondarystoragevm',
state='Running',
zoneid=self.zone.id
)
self.assertEqual(
isinstance(list_ssvm_response, list),
True,
"Check list response returns a valid list"
)
ssvm = list_ssvm_response[0]
hosts = list_hosts(
self.apiclient,
id=ssvm.hostid
)
self.assertEqual(
isinstance(hosts, list),
True,
"Check list response returns a valid list"
)
host = hosts[0]
self.debug("Running SSVM check script")
result = get_process_status(
host.ipaddress,
self.services['host']["publicport"],
self.services['host']["username"],
self.services['host']["password"],
ssvm.linklocalip,
"/usr/local/cloud/systemvm/ssvm-check.sh |grep -e ERROR -e WARNING -e FAIL"
)
res = str(result)
self.debug("SSVM script output: %s" % res)
self.assertEqual(
res.count("ERROR"),
1,
"Check for Errors in tests"
)
self.assertEqual(
res.count("WARNING"),
1,
"Check for warnings in tests"
)
#Check status of cloud service
result = get_process_status(
host.ipaddress,
self.services['host']["publicport"],
self.services['host']["username"],
self.services['host']["password"],
ssvm.linklocalip,
"service cloud status"
)
res = str(result)
self.debug("Cloud Process status: %s" % res)
# cloud.com service (type=secstorage) is running: process id: 2346
self.assertEqual(
res.count("is running"),
1,
"Check cloud service is running or not"
)
return
def test_04_cpvm_internals(self):
"""Test CPVM Internals"""
# Validate the following
# 1. test that telnet access on 8250 is available to
# the management server for the CPVM
# 2. No telnet access, test FAIL
# 3. Service cloud status should report cloud agent status to be
# running
list_cpvm_response = list_ssvms(
self.apiclient,
systemvmtype='consoleproxy',
state='Running',
zoneid=self.zone.id
)
self.assertEqual(
isinstance(list_cpvm_response, list),
True,
"Check list response returns a valid list"
)
cpvm = list_cpvm_response[0]
hosts = list_hosts(
self.apiclient,
id=cpvm.hostid
)
self.assertEqual(
isinstance(hosts, list),
True,
"Check list response returns a valid list"
)
host = hosts[0]
try:
telnet = telnetlib.Telnet(
str(self.apiclient.connection.mgtSvr),
'8250'
)
self.debug("Telnet management server (IP: %s)" %
self.apiclient.connection.mgtSvr)
except Exception as e:
self.fail(
"Telnet Access failed for %s: %s" % \
(self.apiclient.connection.mgtSvr, e)
)
self.debug("Checking cloud process status")
result = get_process_status(
host.ipaddress,
self.services['host']["publicport"],
self.services['host']["username"],
self.services['host']["password"],
cpvm.linklocalip,
"service cloud status"
)
res = str(result)
self.debug("Cloud Process status: %s" % res)
self.assertEqual(
res.count("is running"),
1,
"Check cloud service is running or not"
)
return
def test_05_stop_ssvm(self):
"""Test stop SSVM
"""
# Validate the following
# 1. The SSVM should go to stop state
# 2. After a brief delay of say one minute, the SSVM should be
# restarted once again and return to Running state with previous two
# test cases still passing
# 3. If either of the two above steps fail the test is a failure
list_ssvm_response = list_ssvms(
self.apiclient,
systemvmtype='secondarystoragevm',
state='Running',
zoneid=self.zone.id
)
self.assertEqual(
isinstance(list_ssvm_response, list),
True,
"Check list response returns a valid list"
)
ssvm = list_ssvm_response[0]
hosts = list_hosts(
self.apiclient,
id=ssvm.hostid
)
self.assertEqual(
isinstance(hosts, list),
True,
"Check list response returns a valid list"
)
host = hosts[0]
self.debug("Stopping SSVM: %s" % ssvm.id)
cmd = stopSystemVm.stopSystemVmCmd()
cmd.id = ssvm.id
self.apiclient.stopSystemVm(cmd)
# Sleep to ensure that VM is in proper state
time.sleep(self.services["sleep"])
timeout = self.services["timeout"]
while True:
list_ssvm_response = list_ssvms(
self.apiclient,
id=ssvm.id
)
if isinstance(list_ssvm_response, list):
if list_ssvm_response[0].state == 'Running':
break
elif timeout == 0:
raise Exception("List SSVM call failed!")
time.sleep(self.services["sleep"])
timeout = timeout - 1
self.assertEqual(
isinstance(list_ssvm_response, list),
True,
"Check list response returns a valid list"
)
ssvm_response = list_ssvm_response[0]
self.debug("SSVM state after debug: %s" % ssvm_response.state)
self.assertEqual(
ssvm_response.state,
'Running',
"Check whether SSVM is running or not"
)
# Call above tests to ensure SSVM is properly running
self.test_01_list_sec_storage_vm()
self.test_03_ssvm_internals()
return
def test_06_stop_cpvm(self):
"""Test stop CPVM
"""
# Validate the following
# 1. The CPVM should go to stop state
# 2. After a brief delay of say one minute, the SSVM should be
# restarted once again and return to Running state with previous
# two test cases still passing
# 3. If either of the two above steps fail the test is a failure
list_cpvm_response = list_ssvms(
self.apiclient,
systemvmtype='consoleproxy',
state='Running',
zoneid=self.zone.id
)
self.assertEqual(
isinstance(list_cpvm_response, list),
True,
"Check list response returns a valid list"
)
cpvm = list_cpvm_response[0]
hosts = list_hosts(
self.apiclient,
id=cpvm.hostid
)
self.assertEqual(
isinstance(hosts, list),
True,
"Check list response returns a valid list"
)
host = hosts[0]
self.debug("Stopping CPVM: %s" % cpvm.id)
cmd = stopSystemVm.stopSystemVmCmd()
cmd.id = cpvm.id
self.apiclient.stopSystemVm(cmd)
# Sleep to ensure that VM is in proper state
time.sleep(self.services["sleep"])
timeout = self.services["timeout"]
while True:
list_cpvm_response = list_ssvms(
self.apiclient,
id=cpvm.id
)
if isinstance(list_cpvm_response, list):
if list_cpvm_response[0].state == 'Running':
break
elif timeout == 0:
raise Exception("List CPVM call failed!")
time.sleep(self.services["sleep"])
timeout = timeout - 1
cpvm_response = list_cpvm_response[0]
self.debug("CPVM state after debug: %s" % cpvm_response.state)
self.assertEqual(
cpvm_response.state,
'Running',
"Check whether CPVM is running or not"
)
# Call above tests to ensure CPVM is properly running
self.test_02_list_cpvm_vm()
self.test_04_cpvm_internals()
return
def test_07_reboot_ssvm(self):
"""Test reboot SSVM
"""
# Validate the following
# 1. The SSVM should go to stop and return to Running state
# 2. SSVM's public-ip and private-ip must remain the same
# before and after reboot
# 3. The cloud process should still be running within the SSVM
list_ssvm_response = list_ssvms(
self.apiclient,
systemvmtype='secondarystoragevm',
state='Running',
zoneid=self.zone.id
)
self.assertEqual(
isinstance(list_ssvm_response, list),
True,
"Check list response returns a valid list"
)
ssvm_response = list_ssvm_response[0]
hosts = list_hosts(
self.apiclient,
id=ssvm_response.hostid
)
self.assertEqual(
isinstance(hosts, list),
True,
"Check list response returns a valid list"
)
host = hosts[0]
#Store the public & private IP values before reboot
old_public_ip = ssvm_response.publicip
old_private_ip = ssvm_response.privateip
self.debug("Rebooting SSVM: %s" % ssvm_response.id)
cmd = rebootSystemVm.rebootSystemVmCmd()
cmd.id = ssvm_response.id
self.apiclient.rebootSystemVm(cmd)
# Sleep to ensure that VM is in proper state
time.sleep(self.services["sleep"])
timeout = self.services["timeout"]
while True:
list_ssvm_response = list_ssvms(
self.apiclient,
id=ssvm_response.id
)
if isinstance(list_ssvm_response, list):
if list_ssvm_response[0].state == 'Running':
break
elif timeout == 0:
raise Exception("List SSVM call failed!")
time.sleep(self.services["sleep"])
timeout = timeout - 1
ssvm_response = list_ssvm_response[0]
self.debug("SSVM State: %s" % ssvm_response.state)
self.assertEqual(
'Running',
str(ssvm_response.state),
"Check whether CPVM is running or not"
)
self.assertEqual(
ssvm_response.publicip,
old_public_ip,
"Check Public IP after reboot with that of before reboot"
)
self.assertEqual(
ssvm_response.privateip,
old_private_ip,
"Check Private IP after reboot with that of before reboot"
)
#Call to verify cloud process is running
self.test_03_ssvm_internals()
return
def test_08_reboot_cpvm(self):
"""Test reboot CPVM
"""
# Validate the following
# 1. The CPVM should go to stop and return to Running state
# 2. CPVM's public-ip and private-ip must remain
# the same before and after reboot
# 3. the cloud process should still be running within the CPVM
list_cpvm_response = list_ssvms(
self.apiclient,
systemvmtype='consoleproxy',
state='Running',
zoneid=self.zone.id
)
self.assertEqual(
isinstance(list_cpvm_response, list),
True,
"Check list response returns a valid list"
)
cpvm_response = list_cpvm_response[0]
hosts = list_hosts(
self.apiclient,
id=cpvm_response.hostid
)
self.assertEqual(
isinstance(hosts, list),
True,
"Check list response returns a valid list"
)
host = hosts[0]
#Store the public & private IP values before reboot
old_public_ip = cpvm_response.publicip
old_private_ip = cpvm_response.privateip
self.debug("Rebooting CPVM: %s" % cpvm_response.id)
cmd = rebootSystemVm.rebootSystemVmCmd()
cmd.id = cpvm_response.id
self.apiclient.rebootSystemVm(cmd)
# Sleep to ensure that VM is in proper state
time.sleep(self.services["sleep"])
timeout = self.services["timeout"]
while True:
list_cpvm_response = list_ssvms(
self.apiclient,
id=cpvm_response.id
)
if isinstance(list_cpvm_response, list):
if list_cpvm_response[0].state == 'Running':
break
elif timeout == 0:
raise Exception("List CPVM call failed!")
time.sleep(self.services["sleep"])
timeout = timeout - 1
cpvm_response = list_cpvm_response[0]
self.debug("CPVM state: %s" % cpvm_response.state)
self.assertEqual(
'Running',
str(cpvm_response.state),
"Check whether CPVM is running or not"
)
self.assertEqual(
cpvm_response.publicip,
old_public_ip,
"Check Public IP after reboot with that of before reboot"
)
self.assertEqual(
cpvm_response.privateip,
old_private_ip,
"Check Private IP after reboot with that of before reboot"
)
#Call to verify cloud process is running
self.test_04_cpvm_internals()
return
def test_09_destroy_ssvm(self):
"""Test destroy SSVM
"""
# Validate the following
# 1. SSVM should be completely destroyed and a new one will spin up
# 2. listSystemVMs will show a different name for the
# systemVM from what it was before
# 3. new SSVM will have a public/private and link-local-ip
# 4. cloud process within SSVM must be up and running
list_ssvm_response = list_ssvms(
self.apiclient,
systemvmtype='secondarystoragevm',
state='Running',
zoneid=self.zone.id
)
self.assertEqual(
isinstance(list_ssvm_response, list),
True,
"Check list response returns a valid list"
)
ssvm_response = list_ssvm_response[0]
old_name = ssvm_response.name
self.debug("Destroying SSVM: %s" % ssvm_response.id)
cmd = destroySystemVm.destroySystemVmCmd()
cmd.id = ssvm_response.id
self.apiclient.destroySystemVm(cmd)
# Sleep to ensure that VM is in proper state
time.sleep(self.services["sleep"])
timeout = self.services["timeout"]
while True:
list_ssvm_response = list_ssvms(
self.apiclient,
zoneid=self.zone.id,
systemvmtype='secondarystoragevm'
)
if isinstance(list_ssvm_response, list):
if list_ssvm_response[0].state == 'Running':
break
elif timeout == 0:
raise Exception("List SSVM call failed!")
time.sleep(self.services["sleep"])
timeout = timeout - 1
ssvm_response = list_ssvm_response[0]
# Verify Name, Public IP, Private IP and Link local IP
# for newly created SSVM
self.assertNotEqual(
ssvm_response.name,
old_name,
"Check SSVM new name with name of destroyed SSVM"
)
self.assertEqual(
hasattr(ssvm_response, 'privateip'),
True,
"Check whether SSVM has private IP field"
)
self.assertEqual(
hasattr(ssvm_response, 'linklocalip'),
True,
"Check whether SSVM has link local IP field"
)
self.assertEqual(
hasattr(ssvm_response, 'publicip'),
True,
"Check whether SSVM has public IP field"
)
#Call to verify cloud process is running
self.test_03_ssvm_internals()
return
def test_10_destroy_cpvm(self):
"""Test destroy CPVM
"""
# Validate the following
# 1. CPVM should be completely destroyed and a new one will spin up
# 2. listSystemVMs will show a different name for the systemVM from
# what it was before
# 3. new CPVM will have a public/private and link-local-ip
# 4. cloud process within CPVM must be up and running
list_cpvm_response = list_ssvms(
self.apiclient,
systemvmtype='consoleproxy',
zoneid=self.zone.id
)
self.assertEqual(
isinstance(list_cpvm_response, list),
True,
"Check list response returns a valid list"
)
cpvm_response = list_cpvm_response[0]
old_name = cpvm_response.name
self.debug("Destroying CPVM: %s" % cpvm_response.id)
cmd = destroySystemVm.destroySystemVmCmd()
cmd.id = cpvm_response.id
self.apiclient.destroySystemVm(cmd)
# Sleep to ensure that VM is in proper state
time.sleep(self.services["sleep"])
timeout = self.services["timeout"]
while True:
list_cpvm_response = list_ssvms(
self.apiclient,
systemvmtype='consoleproxy',
zoneid=self.zone.id
)
if isinstance(list_cpvm_response, list):
if list_cpvm_response[0].state == 'Running':
break
elif timeout == 0:
raise Exception("List CPVM call failed!")
time.sleep(self.services["sleep"])
timeout = timeout - 1
cpvm_response = list_cpvm_response[0]
# Verify Name, Public IP, Private IP and Link local IP
# for newly created CPVM
self.assertNotEqual(
cpvm_response.name,
old_name,
"Check SSVM new name with name of destroyed CPVM"
)
self.assertEqual(
hasattr(cpvm_response, 'privateip'),
True,
"Check whether CPVM has private IP field"
)
self.assertEqual(
hasattr(cpvm_response, 'linklocalip'),
True,
"Check whether CPVM has link local IP field"
)
self.assertEqual(
hasattr(cpvm_response, 'publicip'),
True,
"Check whether CPVM has public IP field"
)
#Call to verify cloud process is running
self.test_04_cpvm_internals()
return
| {
"pile_set_name": "Github"
} |
:: :.:..... : ....: ..: ..: : : :..: ..:...:.... :..........:.... .:.: : :.::..:.:......:.:..: : :...:..:::..::.:::::::..::.:::::.::::::::::::::::::::::::::::::::::::::::::;::::::
.::.:.:::...: ::.:.:.:.:::.::::.::.:.:.:::.:.:.::::.::::.:::.::.:.:.:::::::::::::::.::::::::::::::::::::.:::.:::::::::::::::::::::::;:;:;;;:;;:;:i::::;;,;,,;::;,i;:i;,;:;,;;,;;i:;:
::.::: :::::::::::::::::.:::::::::::::::.:::::::::::::.::::::::::::::::::::::::::::::::::::::::::::::::::::::::::;;:;;:::::;::::::ii,;,ii,,;,,:ii:ii,;::i:ii:i;,;;,i:,;,:i:::;,,;,,:
::::.::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::;:::;;:::::::::::::::::;::::::;::::::::;:::;::::::i:,;:::;,;:;i:;,,;i;i:i,;,;,:,;,::,;;,;,:,;:;,,;i:;,;::i:,;,,;:;,
:;;:;;:,i:,;:;::i:i:;:,;,,ii,,:;;,:i,;,,;,,i:,:::;:i::,;::,;,:,::i;,;::;:::::,:;:,::::,::i;:,::::::,:,:,,:ii:i::i:,;,;,:::;:;:;i:i;ii:i;,i;,;:::,:,::,::i:i:,::;,i,;ii;,,::;,:::i:i:
;ii:,:,;;,;,,:,:;,:,:,::ii;,;:i::;::,:::::::;::,;:,;,:i:,;:::;:i::::::::::::::;,;,;;:::;:::::,::;:::::;,:i::i:;,::::;::::::,::,:i:iiiiiiiiii::i:::;:;:::::::;::i:,;i,i:i:i:,;:::::::
,;;:;,;::;:::;:i::::::,;::i:i;::::,::;,::::,:::::;:i::;,:::;iifffjiii;i:::::i:,;;:,,:::,::::::::::::::::;,;;,;:;:,;,:;,::::;i:;;:iiiiii,i:,;::::;,:,:::;,;,:,:;,;;ii;,;i;::;::,:i:::
,i:i::::::::::::::::,::i:i;;ii::;::,::::::::,::::;:i:;,;ijffLffffGGGDDLGfii;;:,;:i::::::;::::::::::::;::;:i;,;:;::;::::::,;:i:;;i:i:iii,;ii:,;::::,:;::::,:;::;,;;,;ii:i;,:;:;::::::
:ii:;;:,:;,:::::,;,:::::iiiii;,;,:;:i::::::::;::;;,;ii;ifGLGGLGDGGGDDEDGffijiiii;::;:::::::::::::::::,:;:,::::,:,:::,;:::::,::,i:i,ii;;i,;;,;:,::;::::::;:::,;:,;i:i:,;,,;:,:,:;::::
i;;,:::::::::::::::::::i::i:ii:,::::::::::;:::,;:iii;ifLDGfDDDGDDEEEKEEDEGDDGLfi:,;::::::,::::::::::::::;:;:i:::;:;::::::::;i:;,;:i:ii,;i:::,,::::,;::::,::::::;,:i:i;,;:,::::::,:::
i:,;,,:::,:::::,::,::,:,;;,;i:i::;,:::::::,::,;,;i;ifLDGGDEKEDEEEKKDEDKEKEEDDDGfi;,::::::::::::::::::::::::::::::::::::::::::,:;:i;;i:;,;,,;::;:;:::::::::::;::,;i:;::;,,;:;;:i:;:::
i:,;::::::::::::;::::,:::;:i::;,,:,:::::::;:,;iiifGGGDGDEEDKEKEEWW#WKKEWKEW#KKEGj;i;,::::::::::::::::::::.::..::.::...: ::::::,;:;:,;i:i:;::;::;:;:::::::::::::,;;:;:::i,:;:,:::::::
:;;,::,:;:,::::::,::::,;,:::;,:;;:;:::::::::;,jjfGDGDGGGEDEEKKK#KWK#E#WWW#KWEWEDffii:;::::::.:::::::::::...;;:ijiii:::: :::::;:,:i,:;::;:::,:,::::::::::::,::::::::,::;:::::::::::::
,::;,::::::::::::::::::::::i:;:::,:,::::.:;,iifffffDGGfLDEKKWK#WKEEWWWEWKKWWWWKKDGGi;,::::::::::::::.:.:;:;;;jLfGGfji;:::::.:::;::;;,:::;,;::;::;:::::::::;::::;:;:;::::::;:::i:::::
::;::::::::::.:::::::::::::;:::::::,::::::i,ififLDGDDDDEKWEWWK##KWEWWWWKKKWKWWKWWKDGfi;::::::..:::::;,;ijLGjjjtjLGDDGDGGGi::::::::;:::::::::;::;,::::.:::::::::;::,:::;:::::::::::::
:;:::::::::::.:::::::::::;:::,:;::;::::.::ijtGDGDDDDDEEKWWWKWWWWE##KK##KKWKWK#KWK#EGfii:::: :::::::::iiifLGGGGjjtGGEDGEGDj;;:::;:::;::::;::::::,;:::::::::::::::::;::::::::;:,;:::::
:::;:::::::.::.:::::::::;:::::::::,::::::ifDGDKEKEDELDKKEKEK#WW#K#WWWWWEWWKK#KK#KKKGGi;::::::.:.::.:;ijfGGGEEDGGtjGGKDDEDG;;:.::::::::::::::::::::::::::::::::::::::;:::::::::::::::
:::::::::::::::::::::::::::::::::::::::;ifDEDDD#GDEDEWWKEW#W#E#WWWKKWKWWKK#EWK#KEKGjii;:::::::: ::iiLGDGKKKKKDKKEjjGEDKEEjjGfj;:::::::::;:;:::::::::.:::::::::::;:;:::.:::::::::::::
::::::::::::::::::::::::::;::::::::::::iiGKKDGEWEKEWWK#K#KWK#WW#KW#WK#WWKWKWK#KKKDj,;:::::... :::i;jGGDEEKDKKKKKKGjjGEKKDjGGGjf::::;::::::::::::::.::.::::::.::.:.::.:::::::::::::::
:::::::::.::: ::::::::::;,::;::::::::,;ifLEKEEDEK#KKKWE#WW##KWWK##KK#KWWKKKWEGKGGi:;::::.::.:::::ifGGGEKKKEKDKWKEGLjGD#EKGGGGGG;:.::::::::::::::::::::..::::::::::::::::::::::::::::
:::.::: :::.:::::::::::,::::::::::::i;ifGDEKKEEKKK#KK#KWWWKWWW##EWW#E#WEWEWEEDGjLi::::::::.: .:;ijjLGEGDGGEKGEKK#KGGGKKWEDEKDGGi;::::::::::::::::.:..:..:..::.::.:.:::::::::::::.::.
:::::.::::.::::::.:::::::::::.:.::::iifGGDK#EWEKEWK#E#WKWWWKWKWWWKKKK#WEWDGGGLit;;:...:::. :.:;ijLjjjjLGGEEKDEEDGEKDGGEDKKKEEGGi;::: :...:: :::. : ::.::..:::..: .::.::..:::::..:.:.
::::::.::.::: :.::::::::::::..:.: ::iiGGDEEWKKKKEE#K#KWWWWW#K#EW#KWW#KWEKEGfLf;;;;;: ::: ::::ijLGjtjLLGGKEEEEEDKEDKDEGGGKKEKKDGj;;:;;::::..:....:.: ...:..:....:::...:..:.....::.::.
:::.:.:::.: ::.:::::.::.::..:: :::::iLGDGDKWKE#KK#WWEKWWWWWKWWWEWWWWKKKKKDDfjj;;,,..:...:.::;jGjjjjLGKEEGEKDDEGDDGGGGfLjGKKEEKGjj;;,;;: :.:.:::...:. :....::.. : ..:::::..:::: ::::
.:..:..:: : ..:::: :..:: :....: .::ijGDKDGEWEW#EW#EWKWWWWWWKWWWEWKK#KWKKEDGGi;;;,,::.:.: ::;i;t;LEGGDGEGKEGGGLjiji;j;;;;tjGGEKDGjt;.:.:: :: ::.:: : :.......:..:: :.:.:...:.:...::.
..: ::..: :..::...: :.: :: :::..:::ifLGEKEKEK##WWK##KKWWWKKKWWK#K#KKKWKWKEKGti;:.:.,.:. : ;ij;;jGGGLGEGGDEGLjj;t;;;;;;;;;;tjGEDGjt;:.. ;:..........::..:.......: :... :..: ... :...
..... : : :.. :.: .: .: :.. ::::;ifGEEKKE#KKWWWEWK#K#K#K##EWKEWKWWWW#EEEDGi;;;.:.:..:: :;ijitGGLLGEGEKGGGjj;;;;;;,;.;;:;;;LGKEGt;.: :. :..:: ::. :. :... .... :.....: : :::.....::
:......:. ..: ...::..: ::.....:::;iDEEWEKKKKKKK#WK#KWKW#K##EWWWKW#EKEKWKKEDGj;;;.::.,: ;;ii;jjGGLGGDKGGjLjji;;;,::,:.;:,::,;tjGGLL;................:... : .:: ::....:..: :: :.....
. .::..: : . : :..: :..:: :..:.:::iGDKKKK#KK##E##WWWW#KWW#WK#EKWWKKKEEWEKGEGj;,.:...,..::;;jjLGLGLGEGLGLjjtjt;;;;;.;;.::,:.,;iGDGG;;.............. :..: ::.. :.. : : .: :. : :..:
.::..: :..:... ...:: :: :: : : ::,iGDEEKEK#EWKW#WW#KWK#KWWWWWKEWKKEWDDDKKKDGGi;.:.:,.;::;;itLGLfLGGGGGjjjt;i;;;.;,,::,:...::,;LGGGL;:: .. : ....... : : :....: :: .. :.....: :: ::
:..::.::.: . :: : :.....: :: :::ijDGDWEKWWK#KWWW#K#WW#WW#WWWKK#KWKEKKKDKEEGGj;.:...:.,:;;;jLjGLLGKELjLjjt;t;;;,,;:.:.:..:..:.iGGGLj:.:..... : : ::..... ... :.:......: : : : :
.. : :..: :. ::. :.......: :: :::;fGDDDEWKWW##WW#KWWWWWWWWWWE#KWKEWEKEKGDEDGGj;:.:..:.,;i;jjGGLLDKEGLjjjtjt;;;,,;,:..:.:.:.:.:;;LGt;j:.: .. :....:: :: : : . : . : :.: :.: :.: .:
. : .... .: : : :.....:......:::ijfDEEWKK#K##K#WW#KWWEWEWWWWWKWEWKEKGGDGEGGjj;.:..:.,;jEitiGGLjGKELjjtijii;;;,;..;:.:.::.:.:..;jGjtt.:: :....: : :.: :.: ::...... ::......:.:.:.
: : .........: : : : : :...::itGDDKEW#KWKW#KWWWEE##WWKWEWEK#KKEKKDGKGGGGf;,:..:..;jGK;jLGLGGEKEjLjtt;j;;;;,,,::::.;..:...::.jGLj;j ::: :: :: : : ......:: :: :.:....:.: :.:.:.
: ...................: :....:...:;fGDDKEKWEW##W##KWWWW#WW#K#KWK#KKKDKGfGGGGLj;::..:.;ijjjjGGGGDKKEGjLjjLjjji;;;;,;.::.:..:....:.;fGLijj.:: ::.::.... :: : : : :..:.. : ::..:..:
....: :.............:: ...:..: :ijGDKEWWWWWEK#KK#WWWKWE#KKWWK#KWDEGGGGfjGji;...:..;;;;;iLjGLGKKKGLLjLLGGLLLj;;:;:.;:..::.::....:jDLijj.:............. :..: :: :: :.......:: :: ::.
: : ..: .. : : :: :: ::. :: :: ;fGDEDEWWWKWWWWWWW#WK##WKWWK#KKEDKEDGfGfjL;;.:.,:.:;...;GLLGDDKEGLGLGGLjfjfLj;;;;,..::.:.::.:...jKLt;j;.................. .. : .........: .....::
:...: :: .. : : ....: .. ... :: ;fLGDDEKWWKKWWW#K#E#KKWKWKWK#EKEDEGDGGGjji..:.::;.:.:..;LGLGKKELLjjjttt;;;;;;;;;,;..:.:;;;i;::..;KGj;;j; : : .. :: .. : . .. . .. :: . .. ..:
.. . : .. :: : .. : ....: . :;ffDGEK#K#K#WW##WWWW#KWWWK#KWWEKGDDGfGfjj;.:...:..:..:;jGGGEWKGLfLjtjtttij;.;;;;;.:.::;;;iji;:..;KGf;;;; .. : ... .... .: . ..: : .. : :: :... :
. .. ... .... . . .... . :: :. :LGDDDEK#WE##WW#K#KK#EWWW#KKWKEKDDGDjGfij;.::...::..:;j;iLEDKKGjLjjjtjjLLGLj.;;;;;..:.,:;;;t;j::.EGj;;;;: .: .. . : .. .. : . :. ....... .
. . . .: ... . . :. . : .. . ..;jGDGDKKKKKWK#WKW#EK#WKK#KWWWKEDDGGGjGjjtj,:...:.;..:;;;;;GKKGLLtjjtjjGGEEKD;.,;;;.:.;;,;,:::;;.:DGL;;;;...... : .. : .: : : : ... : .. :.....
: . : . :.. : . ... : . .. ...iGDGDEKKWE##EWWK#K#KWWKKKWWWEDDDGGGjGfjji;::.:.....::,..:,DKLjtjttLLGELiiEGG;;i;;.:,;;;;jjj;: :.GGj;;;;... .. : .. : : .. .... : : : .. :....:
. : . .... :.. ... . . : . . ;GEGDDEE#KWW#KWKK#WE##K#K#KKDKGEGGGGjjjjj;:.,..:.:....;,:,;EGLjtjjjjLLLLjLGK;;;;,: ;;;jGDWKG;. .Gjt:,:;: .: ... : .. : : . .... :: .........
. ... : . . : .. .. .. : . : :GGDEDEWKKWWWEWWKKWWEWWEWKKKDGGGGGjjGjjji;:;:::....::.,:.;;jGLtjttjtjtj;;;;j;;t;;..;;;jiifDW;:.:Ei; :.; : : .. .. :.........:... .. : :... : .:
.. ... . .. : : . .... . .: ..GDGEEKKK#KKKKWWWW#KWWWKEWKKGLL...;jjfjji;,;::.:.. ...:;:;;,;Gtjtj;j;;;;;;;;;jtt;:.:.;;itjjLL; .L::..;... : .. :: .. : : ..........: : : ....:
. . . ..: .... . ........ .... :....LKLKDKKKWWWWWEWWWK#W#WKKKEELL;:;..,;jjjt;;.;.:.:.:....:;;;;iLjtjiti;;;;,,.;;tji;;:.:;t;;;.;;;..j:. .:. : : ..... : .. ..... : .. : :: :...:
.. . ... .. : .. :. :: .... ...: :.iGGDEKKWEWWWKWWKWWK#EWKWEKGLt,tt...;;jjj;;:;;:... :. .;;,;;jGjttti;;,,,;.;;ijtt;...:;;;;;..:. .j: :; .... . ...: ...... : .. : :: :: .::..: ::
. : . . : .. :: ..: :: :: .. : ....;jGGDKDKKKWKKK#KWWWWK#KKGLLtt,tj,..:;;;;;;:,,:,:.. . ..;,;LKLttjt;t,.:,;:,;ttjt;:...:,.:.:.: . j: .:. : : .... : : :: .. ......: : :: :..::
. . ....: : : . : :.. : ....: :: :.:;fGDKDEWWKWEEWK#KWWWWKEGGjf;,ti:,...;;;;;;;:,:..:..:..,;jKELjttt;;;;,,,.;;jtj;;::....:,,:...:.j:..:.. . .. : .. :: : ........: : ::....: : :
:....... :...: :.. :...... ....::iGEEEKEKKWKWKWWK#KEWWELjLj;,,,j;.:.,;;;:,::;:.:......;;KKGLtttt;,;,.;,;:;jjj;;.....:.::... . f;..: ::.........: :: .......: :.:.:: :.......::
. .... .....: .. : : : : ..... : .::GGDKEDWWEWK#EWWWK#KWGLjjf;;.tLL. ..;;;;;:;:,:...:. .,jEWGLtttt;;;,;:..;tjLj;;:.:...,:.:..: .ii.:.......... : : : :: :: :::.::.::.....::.. :
....... : . ..... ..: ..:..... .: .:.iGGKKKKKKK#EW##K#WWKGLjtLt,.;ff; .:.;;;;;;:;;:..:.:.:,LEELtjti;;,,::.;ttjtj;,:...;,:::.: . .i;;:::.::.:...:....::: : :::..:.::::..: :..:: :.:
..: :: :: ... :... : :...:..:::..:...;DGEKKEWWWKWWWWWKKKKLjjLfj;.,;t;.:.;,,;,:;.,:,,...::,:jDELtttt;;;:,.;;Ljtjj;;..:.;;.... :.. ;;;::.:.....:..:.:.: :: : ::..::::::::.:.::.::...
.: :::...................:.:..: : :..:.:jGDEEWWKKK#K##W#WWKLjjjtjt....;..;.;;;;;;.,,..,.:...,;GELtjtt;,;,,:;;jjLLLj;,;..;,,:..: : :;:;:::::::.:.:..:.: :.::::..::.::.::.:.::.::::.::
::::::.:.:.......:.: :.:.:::::::.:...:::.;GDDEKEWKWW#WW#KKKLLjtjtj;....:,,;;;;;;;.,,:.......;;LKLtjtt;;,,;;it;tiij;.:;: ,;;,..:.: .:.:;.::::...::.:....::.:.:::...: : :..: ::.::...:
::::::.:: :::: ...:.:.:.. :::.:..:.:.....:LGEDWWWWW#KWKWKEEjjtjjjLt;.. .;;;;;,:,::::..::..:.:jKELttt;;;;:;;ttt;t;;:,:...:;;;.:.. .:::..:: ::.::.:.:::...: .: :.:..:.:.::.:..:::.:..
.::.:.: ::: : : :.:.:.:..::...::: :.:..:.:LGDDE#WWW##WWWKKGLjjtttjLt;:.:,;,;;;;,,;:::.:..:.:,LGEGjttt;;;;t;tj;ttt;;...:.:;;,:.... :...;..::: : :: : ...::.:: :....:....:.: :.: :...
....: : .: :.:...:..: : :::....:: ::..:: :jDWKWWWEWWWWKKDDGjtjttit;;;;;;tt;t;;;,;:,.:.. :..:,;LGLttjt;;,;tLLDDDGGDLff;..::;;:..:. ..: .: :..::: ... ..:: : ...: ::........ :: :.: ..
.....:.:: :.: :...:: ::.. : :..:: : ..::..fKWWKWWWKEKKKEDGGjji;;t;;;,;;;;ttt;;;;.;....:..:,,;tGLLtit;;;.;tGELLLGLfffLjt,.;;,..:. ::...;... : :: :. :.: ::: :............: : .....
:: :....: :.: ..: :.....: :: ::.........iEWWWKWWKKKEKEGGGj;jt;i;,,:.;tijt;;;;;;.;.:..:...,:tGLjtti;;,;;;LGLjt;;;t;ffft;;,;:.... :: :: : ....: : .: .... : ............ :: :: ::
: : : :.........: ::...................;GKWEKEKEKEGGGGGjjti;;;;,,.;;;tttjt;;;,:...:...,:;;;LLtjttt;;.;;;DGL,;:...:tfLf;;:..: .. : :...............:: : : ...........: :: :: ::
:: ::.. :: : : :: :: :: : : : :: :...:iDKGGGGGGGLGjjjjti;i;,,;:;:,;jjttti;;,,,..:..,:,,;:.;jtttt;;,;;itLDGLfft,,,Lft;;,.... : :. : .. . : : :...: . .. : : :: :: : : : :
........: .....: : : : ...: :: : : : :LGGGGGGGLLjjjtj;jt;;,;,,.,;;tjtjt;;;;;:,::..::,:,:..;;;i;;;;;;ttjfGDLffjjjjt,;,;:.:.: .. : : .. :: :: .... : : : : :: .. : : .. :...:
:: :: ::.....: : :: :: :: : .......: :: :: ;i;ijjjjjjjj;jtt;i;;,,::,.;;;jjiit;;;,,:..,.,.:;,...:;tiit;;;;;itjfGGLffjti..;;..... .. :. ...: . : .. .. : .. .........: .. : .....
:: :: :: : : : :...: ... :: :: : : : . ::.:,:i::::::;t;;;,,;;::,,:;itjitit;;;;,:,:,,:,; :..:,;ti;;t;;;;;,;;;,;....;.:..... :: : .. :: :: :.. :: ... : : .. :.. ..... ....
: .......... :: : : ..........: .. : .. :..::i;,:;::::.:;;;;,;:::..:.,;;ttt;;;;,;;;:,,,,,, : ...:;t;jiit;;;;;;;,;...:.:..: .: .. :.. ..: :........... . : .. ....... : :: :: ::
:: :.......... : :: :: :... .. : :: :: :itfGDGffjii;::.:. ::;;.;:,:.,::,;;tittt;;;;;;,,,:;.. : ...;;ti;t;;;,,:.::.:: .:.:.... ...: :: : ..: .. .... ..... :: :: :... : : : :
.: ...... :: :: ....... .. .. : :...:ifLDDDWDWWEWKWKWEDf;. : .;:::.,.,;,;;;;t;;;;;;;;;;. . : ..:.:.;;tit;;;:,:..... :.... : : :: : : . : : : :..... :.. : .. . : ...: :.. ..
:.. .. : :... ..... ....... .. .. .. ;tfGGDEEEKWK#W#KWWKKEGf:.. :,.:...:::;;;:.. ...: ...... .:. ..:;;itt;;:;.::.::. :...: . .. .. . ........ . :: ..: .. : : :: .. : .... ::
. : ..... .. ... . ..... : .. .. : : iffDDDDDWKKWWKEWWEW#KKKKi...:::,.::;,,:. .. ... .. ..: ...:.:::;;;;jit;;:;.: ...... ..: ..: ... :.. : : :: .... : : .. .....: : : : . .
..: . : . .........: :.. ..... :: ..: :jffLDEDEEKKKK##WWKKEEKKEDL: ..:,:::.::; :: :.. :.. ... . :.:.:,,;;;itj;;;.:.....:: .. :... ... .. : : : : . ..... : ....: : : :: .. ..
. .... ...: . : ... .... . . ....ijLfLGDDDDKKWWWWKWKKKWEKWEEEKD: ..,.:.::. :.. :.:.. .. : :.::.;.;;iititt;;;;:::... :......... : : ..... : : .. : .... :.. : .... : .
.. ... ... : .... : : .. .....: : itjfGDDDEEEKKKWEW#KWWKKWEWEEKDDGi :.::,: .. .... . . : : : .::.::;;tttjttiti;:;..... :.. . : . .. : : : ...... : : :: : :.... ......
..: : .. : : . :: : . : : ..fLfDDDDEEDKDEEKKKWWWKWWWEWEEEEEEDj..::.;: :: . : . : .. :.:.:.;;;titjtit;;:;:...:.... :....: .... ...: : : . : ... : .. ... ... .... .
....... . ....: :: . : : . : : tGfDDEWEWEWWW##WW###W###K#KKEEEEDEf:.,: : .. ... .. : ....:.,:,:;;tit;t;,,,.,...... .: .... . : . .: . . . . : ...: . : ... ... . . .
.. :: :: : . . : .... .........: :ifffDDEEWEK#KEW#WK#WWWW#W#WWEKEEEEKf.:. : . : : . .. .. . :,:;;;jttt;;;;,::....:. : : : .. : . ... ... . : ... .. . .. : .. . ..... .. .
........ : .. :. : . ....: ........:ffffGLDDDKKKWK#E##W##W#W####WKWDEEEEf ..: ... :.. .. : ... : ..::.;;;j;;i;;:;::.::.... . ........ : . ... ........ : .... . .. :... . . ..
.. :: : .... ... . .. : :: .:iiffffGDGDDEDKKKK#KK#WWK#KK#KKEW##WKDWDEi.... .... ... ..... : ...:,;;tti;i;;,;.:.,::.:,:. :. : .......: .. :... : ....: : : :: .. : : .
.... : ....: ... .: :.. : .::tifDGLfGDDDGDDWEWKWKWWWWWWK#WK#WEKK##KDEWEi : :.. .. :...: .: ...,;;;;iti;;;;,.;:..:.:::::.. : ::..: : : : ..... : : .........:. :...... ::..:.
..: :... ....... ........... iiiitfEDDDfGDGGDDEEWWWWWWKKWWWK#KKEWEEED#WEDDG: .... :: : ....... : . ,;;;;j;t;t;;,;..:::..:.;....: : ... : .. :: ....::..: : .....: : ....:. : . ..
... :: :: : ......:: :...: :ititifLDGDfLGDfGLDWEWWKKK#EWK#KKKK#KKKKEKDWKEDDf............. : : . :;;;;tt;tt;;;:,..;..::.;.;;.:: .:::..::. :..:.:.....:..:. :.....::..:::...::.:: ..
::.:: ::... :. :....:...:tDLifjtfDEDGGDDffffDKWEEWEWWEWWEWWEKKWKKEWEKEDEEDG:.: .:::....:::.:.: . .;t;ttt;ttt;;:;..,.:.,.:;;;;;.:. ::..::.:.:::::.::::::::::..:::.::.::::::.:.::.::.
: .: : .:::.:.:: :: :: :iDDfifffGDEDLLDLLffLDKEKKEWEEWEKEKKKWKKWEKWEWWEKDDLL..:: :..::::.:: .: . ;t;itt;tt;t;;,;,,.,,,:,;,;,;;;:: ::::: ::..:::..:::.::.::.:.::::.:.:.::::::::::
.: :::.::: .:.: ::..:.:;iGDLtfffLDGDfLGLGLffGDKEKEWEEEDEKKKKKKEEWWKK#KKKKEDDLfff;::.::.:.:.::: : .;;ti;ijit;;;,;:.,..,:;;;;;,;;:;::.. :.:::.::.::::::.:::::::::::.:.:::.::::.::.:::
.:.:..::::.::::::.:.::tfGGfftDffLDfDGfffLLfDKEEDEEDKEKKKKKKEWEKWKKEWEWWEWKEKDDLDi::::::.::::: . . .;;;;i;j;;t;;;;..:.::;;;;;;;i;;:.. :.. .:::::::;::::;;:::::;:;:;:::;:;::;;::;:
:.:::::.:.::::.:.:::iitDfGfGfLffGLDDfLGGffDEDKEDEEWKKWEWWEDWEKKKKKKKKKKKKWEEEDDLi::;::::::::. .....:;;t;;titit;,,,;.;,;,;;;;;t;;;::.:..::.::. ::;::;::;i;,:ii;i;i:i:::;;:::;:::;,,;
:::.:::::::.:::.:::iitfDfGDfDDfffDGDLDLLLGKDKEKEEKKKKKKKKKEEKKKK#KWKKEEKKEWEDEDLLi;:;:;:;::: . . .,;;;;j;tt;;;;;;:;::;;;;;;;;;.:;::.:::;;;:::..;,:ii,i,;iiii,iiiii:i:i::i:;i:ii;iii
;iii;;:;;:;::;:iiiijffKffGfLWGfLDGDLLDGDDEEEEDWEKKKKKKK#EKKKWE##WKKKKKKKEKDEDEWEEDDii;i:: : : .: :,;;;;j;t;;t;;:;;;;:;:;,;;;;;;;;:;,:;;;;::::.:.::ii:i,;,;;i:,i::i:i;,;:i:::;,,;ii,
,;,;,,ii;,;,,:iiittttGDtGDfD#LLGLDfDLDGDEEDEDWEWEKKKKKKEEKDKKKKEWW#KKWKEWDKKKWEWWEEEGt: :...:. ;;;;;;jtt;;;:;;;;,;;;;,;;;;;j;:,,:;,;;;;,::.:: :::;:;;;::,;;:i;,;:::,:::;::,:i::;
iiii;;;;:i,;;iG,itiffWLfDLDWEDfLGDDLDDDEKKEEEEEKKKKKKKKKEWEKKKKWKKKKKWWEEKKK#EWEEKDEEDG . ...:.:. :,;;;;t;;;;;,;;;;;;;;,;;;;itj;;;:;;;;;;;::....: ::,;::,;:;::;::::::;:::::;::::;i:
;,,;;,;ii:i:LEttijffDWffDDDWWDGLGDfDGDEEDEEEKEEWEKEWEKKKWEWWEWEE#WWEWEEWEKE#EWEKDEEDEDEi. ...::;:..;;;;t;;;;;;,;;;;;;;;;;;;;tij;;:;;,;i;;;;.:.:. .: ::::;:::::::::;::::::::::::;::::
:::::::::::jGiittffDKWtLDEWKKDLDLLDLGDDEEDDKKEKEWWEWEKKKWEWWEWKWW#KWKKEKK#KKEWEWDEEDWDKEDj::..: : ;,;t;;;;;;;;;;;;;i;;;;;;;;;j;;,:;;;;;i;;,:..:.: : ::::::::::::::::::::::::::::::::
::::::::::tKjijtffjE#EffDKKKDDGfGLGLDDEKDEDEKKWEWEWEWWEKKKKW#E##KWEWKKEWWEWEKEEEKKEKDEDEED.:::.:.:;;;;:.;;t;;;;;;it;;;;;;i;it;;:;;,;;;;;,;:.:.. . . :::::::::::::::::::.:::::::::.:.
::::::::::D#iftffffWWDfGDKKKEDLDLLLLLDDDEEEWEKKEWWEWEKKKKKKKKW#WWKKKKKEWKEWEKKKKEEEKDEEDED::....:,;;;,:;;t;;t;;i;;;i;;;;;;;;j;;,;,;;;i;;;;;.::... : :::::::::::.:::.:.::::...::.:...
:::.:::::EKfffjfffGWWLjDDEWDEDGfLLGGGDDDEEKKEWWEWWEWEKKEEWEWW#KWWKKKWEWWKWEKKKEKEEDEDKEKDED;..;::.;,,;;;t;;;;;;;;;;;;;;;;;;;;;;;;:;;;i;;,;:.::.. . .:.::::::::::::::::.::.:..::::::.
..:.:.:.jWGfffffjfD#DDfDEKKEEDLDLLGLDDEDEKDEKKWKEEWEWWEWKKKKK#W#EWKWEWWK#WKKEKEEEEEEKDEDEDDt ::.;;,;:;;;;;;;;;;;;;;i;;;;;;;;,;,;:;;;i;;;;,.:.. :.:. :::.:::.:...:..:::.::.::::::..:.
:::.:::.DKfGfffffLEWDDfDEKKEEGfDLDLGDDEEKDKKDWWEWWWWKKWEE#W#WK#WWWWKK##EWWEKKKEKEEEDEKEKDEED:..;:;;,;;;;;;;;;;;;;;;;;;;;;;;,;;;;;;;;;;;;,;:.:.: ....:::: ::::::::::::::::::::::::.:
:::.::::WfDLLffDfGKEDDfDEEWEDGDDDGGLDEDEEKKKEKKEWWEWWEWEEW#E#WEWWWKWWWKKKEKKKEDKKEWDEKDDEEEDG,::,:;,;;;;;:;;,;;;;,;:;;;,;:;,;;;;;i;;;i;;;,:.::. .....::.:..::::.::::::::;::;:;:;::::
: :::: iELDDfffGfDWDGEfDDEDKEDLDDfDDDEDKEDEDKKKKWE#KWWWW#KK#WE#WW#KK#E#EWWEWKKKKKDEEKDEEDKDED::;:i;;;;,;:;::;;;,;;,;;;:;;;;;;;;;;;;;i;;,:,.:...... .::.:::..:..:::::::;;:;,;i:i,;i;:
:::.:::fGDDDGffLjD#GDEfDDDKEDGDDLDGLEEEDKEDKKKKKKKKKKWEWWK#E#KK#WKW#KWKWEKKKKKKEKKKKEKDDEDDDD.:;GG;;:;;::;::;:;;:;;;;;;,;;;;;i;;i;;j;;;;;::.:: .. ..:.:.:.::::::.:::;;iiii;i;i;;i;i;
.:::...DGDEWLtGffD#LDDfGEEDEDLDDDfDDDEDKDEEKKEEWKKWE#WKKKWEWKK#K#W#K#W#K#WKKEWEWKEDDKDKEEDEDE::jWG;;;;:;,:;;,;;:;;:,;,;;;i;ii;;;;;i;i;;:.:... : : ...:..::..::::::;:iiiiiiiiiiiii;i
:.::..fWDKKKLfDtLKWLKDfDDDDDGLDDDGDDEWEDEKEWEKKKKE#EWWKWKWWKKKW#KEWK#KWW##KKKKKDKDEEEEEDEDDDD::;;it;;:;:;;::;;;;;:;,;;;;;;;;tji;;;iti;;:...: ...... ....: ::......::;;iiitijiiiii;i;
.:::.:GWEKKKDfDiDEWGKKfGDEDDEGDDDGDEKDEKKDKEEWWKKKKWEK#KWWKWWWWW#KWWWKWKKKKKEWEKKEWKKEKEKDDED;:::;;;;:;:::;;;,;:;;;;;;;;;i;;;jji;iti;;:;;::.:.. . ...:...: :.:.:::::iiiiiiii;iiii;i
:...:iKDEW#ELDDiDWEDEKfDDGDEEDDDDDDEEEKEDKKEWEWKWWKKW#EWWWKKWE##KWEWWWWW#WWKKKKKKEDEEDEKDEEDDi.:;;;;:;:;;:;;,;:;;;;;i;;;;;;;tLjj;;;t;;;::.. . : ...:: ::....: :.:.;:i;iiii;ii;;iii;
.....fWLW#WEDDDjDKDKKKfDEDEWDDDEEEKDEEKEDWKKK##EWWKKWW#WWKKKWW#WK#WKWW#KWWWWWEKKKKEKDEDKDEKDE;:;::;:::;:;:;;;:;;;;;;;;;;;,;;jLj;;i;i;;;,.:...: : :.::..: : ....:.::::;iiiii;i;ii;i,;
:..: GWLWWW#DDLfDDLKKKLGDEDEDEDDEDEKKDEWDEWEWKK#K#KWWWK#KKKKWWWEWWK#WKKK#KKEEKKKKDEEKDKEDEEDEi;:;;:;:;:;:;;;;;;;;i;i;;;;;;;;jGji;ti;;;,,:...:. .. .. : :.::......:::;iii;iii;i;i,i;
:..:DEDW#WELEffDDDWKKfDEEDKDGEDDWDKDKEEWEEWE#KKWWK#W#WWWEK#W#WK#KKK#KWEWWEWWKKKKKKEKEDEKDDDEj::;:;:;:;:;;;tLGGGLL;;;;;;:;,;LLLti;t;;;;:.:.. : :...::..: : t,....:::;:i;ii;i;,;i;i;,
:...EEK##WEDDfLDEEW#DfDEEKDGDDDDKDEDKEDKWWWWKKKKE#WEW#EEKEWWW#K#W#KKWKKKKWEWKKKKKEKEEEEEDDEDj;:;:::;,tLEEEEEEKEKEDj;;;:;;;;ELj;i;t;;,:.:... : . .:::....,D,: ...:::;ii,ii;,;,ii;i,:
: ..iWDE#K##EDffGDKKWELDDDEDDDEDKDEKKEEKKEEWWK#WW#KW#WW#WEKW#K#WWWWK#W#WEKKWKK#KKKEEEDEEEDEDEi:;::,;fGEEEEEEEEEEEEEDG;;;;;;;GGjtti;;;;;:.:: : : .... : .,jD..::...:::,;ii:iiii;:iii;
: iEDEWW#WEEDjfDEE#EDfDDEDGDDEDDKEDKEWWEWWEWKKEWK#WWW#WEKW#K#W#W##KK#EWWWWK#WEWWEKEDEDDEWEEGj;::;jLEEEEEEEEDDEEKWEEEf,;,;;;GLjt;;i;;,:.:. . . :.::..,iDL : : :::;ii;i;i:;,iii;;,
::iWWWEE#K#WDLfLEDKK#DGGDDGDEDEDKEEKKKKKWWKK#KWW##WWW#KWKK#W#W#W#KWW#EWKWWKWWE#KKEKDEEDEDEDEDi;,tLLDEEEEEEDEDEDEEKKEEDEf;;;iELjij;;,;;,:.::..: :: : . ;ijG, : :..:::i;,,;ii;i;,;ii;
:W#KWEEW##WKLfGDKKEWDLDDDDEDDEEKDKDKKKWKWKWWWE#KK#W#WWWWWWW#KWWWWWWWWE#WWWWK#K#KKEEDEKEEEKDEffLGEEEEEEEDEDDDDDDEEWKKEEDDf;fDjtiti;;:;.:...:. . ...:iijDi. : . ::::;ii;i;i;i;,i,;i:
:f##DWDWWWWKELfGDWWWEELDELDDEEWEDEKKWWWKWKKWKKWEWK#K##EKWW##K#EW#WEWWWWKK#KWKKWEKEKEEEEKEDEKDLDEEEEEEEKDDDDDDDDDDEEKEEEDDELLGLjt;;;:,::.:.. ..: ....,ijDf.... : :.::;iiiii,ii;;iii;
iEW#DWEEW##KDDfDEKKWKDLDDGDEDWEDKEWE#WKKWEKKKEWW#W#W##WKW#W#KWK#E##W#WW#WWWWWW#WKEDWDKEDWEEDEDDEDEEEDEDEEDDDDDDDDDEKKKKEDEEKLjj;i;;;;::.:..... : ::.jijDj.: :.: :::::i:ii:i;;iiiiii:
EWW#D#EEW#WWDDfDEKKWEDfDDDEDEWDEEKKKK#WKWKKKKKWWW#W#K#KWW#WWE#EWWW#E#W#WKWWWWKKKDEKEEKDDEEDWEDEEEEEEEDDEDDDDDDDDDDEEKKWKEDDWLjt;;;,;:,.:..... :.:.,tijLf. :.......::::;,:;,;,;;;,;;:
K###DWKK#W#EELfDK#KKKGGDEDDEWKKKKEW##WWWWWEKEW#K#WW#WKK##K#E#WKW#WWW#KW#KK#WKKKEKKDEDEEEWDKKDDEEEDEDDDDDDDDDGDDDDDDEEEKKEEDEGLt;;;;;.::... ... .,,iijjDi : ....::::::::i:::;::::;::
EWW#D#WDWWW#DLLDKWEKKGGDDEDEKWEKKKWKWW#WWEEWEWWWWWWWWWE###WW#KKWWWW#E##K##WWWWEEDEEEDKDEEKKEEGEGEDDEDDDDDDDDDDGDGDDDEWKWKEEDLjt;;;;.,....::.....,t,ijfD,...: :.: .:.::::::::::::::::
WEW#E#WEW#WWDGLDKKKWDLLDGDEDKWEKK#WW#W##WKEKEWW#KWWWKWWWW#W#WEW#W##K#WW#KW#WWEEEDEEDEEEKKKEEDKEDDDDDDDDDDGDGDDDGDGDDDEEKWWEELft;;,;;:...:....: .i,ijGDD.... .......: .:..:.:::.:.:::
E##WE#EWWWKWDDfD#W#WELDLGEEEKKKEK#W#WW#EWEWEWWWWW#WWKW#WW##WWWWWWWWWWWWW##KEEDKEKKKEEEEK#WWEEWWEDDDDDDGGGDGDDGDDGDDDDEKKEKEWDft;;,:.:.: .... . .i,jfDDf: ....::..: :.... ::...:::...
KE##W#WEW##WDGfDWWWKDLDfDEEEKKEKKWKW#W#WKWEWEWKK##EW#W#K##WW#EK#W##W#WWWWK#WEKEWEKEDEEKWWEEDK##WEDDDDGDDDGDGDDGDGDDDDEEEKWKEEEf;;;::.::.: ... ..iijLDDi: :..: : : ::.:: :.:. : :.
WE#KKWWD#KWEDGLEWWWEKfLDDDKKKKKK#W#WK#KWKKEWWKW#WK#WEW#WWW##WE##K###E##W#KKEEEEKWEWKEWKWWWEE###WKDGGGDGDGDGDDDDGGGDDDDEEKEKKEED;::;:.....:.. ..,iiLLDD;......::..:... ...: : ::: ::
#KK##WWEWWEWDDLEW#KEEfDDEKKKKWE##W#WK#KWKK#KW#WWWE#W##W#W#WW#EWWW##WWWW#KEKEEDEKKWEEWW#WEEDE####WEDGGGGDDGDGDGGDGGDDDDEEEKEWKEEf;::.:. .: . . .iijLDDi.: : ....:..: :: :..: ..:: ::.
###KW#WEW##WDDfKEW#WDLLDKKDKEWWKWW#K#W#K#KKWKKKWW#K#KK###W#W#K#W#KK#W##W#EKDKKEEKKKKK#KWWEDKWWW##WEDDGDGGDGDGGGDGDGDDDDEEKKKKKKD,.;:..: .......tjfGDD,....:: :.....: ....: :.: : ..
#WW#KWWDK#KWDDLD#W#EDfDDKWEWEKK#W#K##K#EWKWKK#KWWKW#KW#W#W###KKWWWW##W##WWEKDEEWKKKW#W#EKDEE###W#WKDGDGGGDGGDGGGDGDGDEEEEEKKEEKDf,,:.:.:. ... ,jjLDDf ::... :.:....:.:.:...:..::....
#K####WD#E#EDDLEW#WEDfGEWEWEW#K##K#WW#EWKKWEWWWK##W#WW#W#WW#W#K#K###W#WKKEKDKEWK#W##W#WEDEKEW#WKWW#KDDGGDGGGGDDGGDDDDDEEKKEKEKEEEi;.:.:.. ....ijLLDD,.. :....::....:..:....:...: ::.
W#K#WW#EK#WEDDfK#E#WDfDDWWEKKW#KW#K#WW##KWWWKWE#KWWWKK##W##W#WW#W#WWW#KKWKEKKKKKWE##W#KEDEEEKW##WWW#DGDDGDGDGGGGDGGDDDEDKEKEWEEEDL,:.:. : . .,tjfDDD : : :: :: :: : : :....:: :.
######WE#WEKDELEWW#EDfLEWKKKWW#WWWW#W#KKKKE#WKWWKW#W###W#W##WWW#K####KWEKKKKKKW##W##KKKDEKKEKWWWW#WWEDDGGGGGGDGDGDGDDEEEEKEKKEKEEDt.:.:..... tjjfEDD : ... : :.............. ...:
#WWW#E#D#WEDEDLWWWWKDffKKWKK#W#WWWW##K##EWEW#K#K##W#W#W#W#WK#WEK##W#EKWEKWEW#K#WK#WKWKEEEDDEWWKWWWWWWKDDGGGGGDGDGDDDDEEEEEEEEEEEEDD :.:..:.: jjtDDDf. :.... : : :.... : ..... ....:
W###WW#EE#KEDDfEWWKKDfDDKKKWWK#WW#K##W#KKWWWWKKW#WWWKW#####W##W##W#KKKKKEEWWK#E##K##WWDDEDEDEWWEWWWWWKEDDGGGDGDGDGGDDEDEEKKKEEEEEED..:. . . .iijEDDj : .. ... . .. .: . .. . .
#WW###WKWWEDEDLKW#KEDfDEWKWK#W#KW#WWW#EWKKWWWWWKKK#W#W#W#K###W##W#KKKKKKKKWWWWW##W#KWEEEDEDEKKWKWWWWW#KDGDGGGGGGDGDDDDEEEEEEEEEEDEDi. :..::..jjjDDG,. . .. : .. : . :. ..: : : ..
W#K#W##EWWWEDDLKWKKEDfDEEEW#KWK#WW#WK#WKWEWWWWW#WK#WWW###W#K###W###EKKW#WWE#WWWWWWWWEWDDEDDEEWKKWK#KWWWEDGGGDGDGDGDDDEDKEKEEEEKEEDDf,:. . . .tijDDf.. .. .. .. : .. : . . .
#WWWW##EK#KEEDfKWKWEGfDEKKW#KKWW#K#KWWWWWEWW#E#K##K#KW###W#K#####KWEKKW#WWK##KKWKW#KKKDDDDDDDKWKKKKWW#WWDDGGDGDGGDDDDEDEEEKEEEDEDEDDL, .:...,jjGDDt : .: : ...... : ... : ....: ..
#W#W#W#WKKEDDDLKWW#EDfGKK#KW###WW#K#K#KKKWW#KWW#WW#K##K##K###W#W##EKKW#K#E#E#WWWWEKKWWEEDEEDEKKKKKWWKWWWEDDGGGGDDGDDDDEEEEEEKEEDEDDDDj.: ...tjDEDG,. .. . .: .: ....:.... : ... : ..
WWW#W###EWKEDDLKKWKDDfGKKKW#WK#KWWWW#W#KWWWWEWK#WKW#KW##W###W####WWEWWW#WWE#K#WK#KWKWWEDEDEDEWKWKKKKWWWWWEDGDGGGDGDDDEEDEEEEEEDDDDEDDD.... .tDEDDD, ... :......... : : .: :: .....
WW###W##EWEEDDLKEWEKGfDEWW#W##WWW#KW#W#WE#WWWEW#WE#K###WK#WWK###WWEKWW#W#KWW#W#EEKKKW#WDDDDEDEKKKKKKKW#WWWWGGGGGDGDDDDEDEEEEEEDDDDDDDDj. ..;DEDDDL...:..:...:...::.........:..::..:
##W#KW##EKWDGDfKKKKEDfDKEWWWWW#WK#K#WWWKWKW#KKK#WW#W##W#######W##WW#K##K##KW#KW#WEK#KKEEDKEDEDEWKWKWWKWKW#WDDGGGDGDDDEEEEEEEEDDDDDDDDDL,.. tEEDDDf..: ::..:: ::.::.::::..:..:..:.::.
WWK#W###DEEEGDLEKKKKDfDEWK#K##W##W#EW#KWWW#KKW#W##WWWW##W#W#W##W#KEWKWW#KWK##W#KEEWW##KDEDDDEEDKWKWKWWWWWWWEDGDGGDDDDDEDEEEEDEDDDDDDDDGL .,tEDKDGf.:.:. :...:. : :..:.::..: :. :...
W#W#W###DEWEDGGEDKKEDLDKK#K#WW###W#WK#KWWW#EWW#W##W#K##WW#W#WW##WKKKKKWWWWWWK#KWKKK##KKEDEEDEEEDWKKKWKW#WWWWKDGGGDGDDDEDEEEEEDEDDDGDGDDDD.LDEEDDDj:..:::....::.:..: ::.:.... :...:.:
#KW#WW##EEKDGDfDEKWEDLEK#K#K##W##K#KWWWWW#K#KWK###WW#W##W####W#KWE#EW##WWWW##WKKKK#WWKKDEDKKEEDEKWWWWKWKWWW#KEGGGGGDDEDEEEDEDDDDDDDDDGGGDjGDEDDDGj.:: ::.::: ::..::...: :.:::.....:
| {
"pile_set_name": "Github"
} |
/*
* Copyright (C) 2019 The OmniROM Project
*
* 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.
*/
package com.android.systemui;
import android.app.Service;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.PixelFormat;
import android.graphics.Rect;
import android.graphics.Typeface;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.os.RemoteException;
import android.os.ServiceManager;
import android.service.dreams.DreamService;
import android.service.dreams.IDreamManager;
import android.view.Gravity;
import android.view.View;
import android.view.WindowManager;
import android.util.Log;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.lang.StringBuffer;
import java.lang.Math;
import java.util.Arrays;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
public class FPSInfoService extends Service {
private View mView;
private Thread mCurFPSThread;
private final String TAG = "FPSInfoService";
private String mFps = null;
private String MEASURED_FPS = "";
private IDreamManager mDreamManager;
private class FPSView extends View {
private Paint mOnlinePaint;
private float mAscent;
private int mFH;
private int mMaxWidth;
private int mNeededWidth;
private int mNeededHeight;
private boolean mDataAvail;
private Handler mCurFPSHandler = new Handler() {
public void handleMessage(Message msg) {
if(msg.obj==null){
return;
}
if(msg.what==1){
String msgData = (String) msg.obj;
msgData = msgData.substring(0, Math.min(msgData.length(), 9));
mFps = msgData;
mDataAvail = true;
updateDisplay();
}
}
};
FPSView(Context c) {
super(c);
float density = c.getResources().getDisplayMetrics().density;
int paddingPx = Math.round(5 * density);
setPadding(paddingPx, paddingPx, paddingPx, paddingPx);
setBackgroundColor(Color.argb(0x60, 0, 0, 0));
final int textSize = Math.round(12 * density);
mOnlinePaint = new Paint();
mOnlinePaint.setAntiAlias(true);
mOnlinePaint.setTextSize(textSize);
mOnlinePaint.setColor(Color.WHITE);
mOnlinePaint.setShadowLayer(5.0f, 0.0f, 0.0f, Color.BLACK);
mAscent = mOnlinePaint.ascent();
float descent = mOnlinePaint.descent();
mFH = (int)(descent - mAscent + .5f);
final String maxWidthStr="fps: 60.1";
mMaxWidth = (int)mOnlinePaint.measureText(maxWidthStr);
updateDisplay();
}
@Override
protected void onAttachedToWindow() {
super.onAttachedToWindow();
}
@Override
protected void onDetachedFromWindow() {
super.onDetachedFromWindow();
mCurFPSHandler.removeMessages(1);
}
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
setMeasuredDimension(resolveSize(mNeededWidth, widthMeasureSpec),
resolveSize(mNeededHeight, heightMeasureSpec));
}
private String getFPSInfoString() {
return mFps;
}
@Override
public void onDraw(Canvas canvas) {
super.onDraw(canvas);
if (!mDataAvail) {
return;
}
final int W = mNeededWidth;
final int LEFT = getWidth()-1;
int x = LEFT - mPaddingLeft;
int top = mPaddingTop + 2;
int bottom = mPaddingTop + mFH - 2;
int y = mPaddingTop - (int)mAscent;
String s=getFPSInfoString();
canvas.drawText(s, LEFT-mPaddingLeft-mMaxWidth,
y-1, mOnlinePaint);
y += mFH;
}
void updateDisplay() {
if (!mDataAvail) {
return;
}
int neededWidth = mPaddingLeft + mPaddingRight + mMaxWidth;
int neededHeight = mPaddingTop + mPaddingBottom + 40;
if (neededWidth != mNeededWidth || neededHeight != mNeededHeight) {
mNeededWidth = neededWidth;
mNeededHeight = neededHeight;
requestLayout();
} else {
invalidate();
}
}
public Handler getHandler(){
return mCurFPSHandler;
}
}
protected class CurFPSThread extends Thread {
private boolean mInterrupt = false;
private Handler mHandler;
public CurFPSThread(Handler handler){
mHandler=handler;
}
public void interrupt() {
mInterrupt = true;
}
@Override
public void run() {
try {
while (!mInterrupt) {
sleep(500);
StringBuffer sb=new StringBuffer();
String fpsVal = FPSInfoService.readOneLine(MEASURED_FPS);
mHandler.sendMessage(mHandler.obtainMessage(1, fpsVal));
}
} catch (InterruptedException e) {
return;
}
}
};
@Override
public void onCreate() {
super.onCreate();
MEASURED_FPS = getResources().getString(R.string.config_fpsInfoSysNode);
mView = new FPSView(this);
WindowManager.LayoutParams params = new WindowManager.LayoutParams(
WindowManager.LayoutParams.WRAP_CONTENT,
WindowManager.LayoutParams.WRAP_CONTENT,
WindowManager.LayoutParams.TYPE_SECURE_SYSTEM_OVERLAY,
WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE|
WindowManager.LayoutParams.FLAG_NOT_TOUCHABLE,
PixelFormat.TRANSLUCENT);
params.gravity = Gravity.LEFT | Gravity.TOP;
params.setTitle("FPS Info");
startThread();
mDreamManager = IDreamManager.Stub.asInterface(
ServiceManager.checkService(DreamService.DREAM_SERVICE));
IntentFilter screenStateFilter = new IntentFilter(Intent.ACTION_SCREEN_ON);
screenStateFilter.addAction(Intent.ACTION_SCREEN_OFF);
registerReceiver(mScreenStateReceiver, screenStateFilter);
WindowManager wm = (WindowManager)getSystemService(WINDOW_SERVICE);
wm.addView(mView, params);
}
@Override
public void onDestroy() {
super.onDestroy();
stopThread();
((WindowManager)getSystemService(WINDOW_SERVICE)).removeView(mView);
mView = null;
unregisterReceiver(mScreenStateReceiver);
}
@Override
public IBinder onBind(Intent intent) {
return null;
}
private static String readOneLine(String fname) {
BufferedReader br;
String line = null;
try {
br = new BufferedReader(new FileReader(fname), 512);
try {
line = br.readLine();
} finally {
br.close();
}
} catch (Exception e) {
return null;
}
return line;
}
private BroadcastReceiver mScreenStateReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
if (intent.getAction().equals(Intent.ACTION_SCREEN_ON)) {
Log.d(TAG, "ACTION_SCREEN_ON " + isDozeMode());
if (!isDozeMode()) {
startThread();
mView.setVisibility(View.VISIBLE);
}
} else if (intent.getAction().equals(Intent.ACTION_SCREEN_OFF)) {
Log.d(TAG, "ACTION_SCREEN_OFF");
mView.setVisibility(View.GONE);
stopThread();
}
}
};
private boolean isDozeMode() {
try {
if (mDreamManager != null && mDreamManager.isDreaming()) {
return true;
}
} catch (RemoteException e) {
return false;
}
return false;
}
private void startThread() {
Log.d(TAG, "started CurFPSThread");
mCurFPSThread = new CurFPSThread(mView.getHandler());
mCurFPSThread.start();
}
private void stopThread() {
if (mCurFPSThread != null && mCurFPSThread.isAlive()) {
Log.d(TAG, "stopping CurFPSThread");
mCurFPSThread.interrupt();
try {
mCurFPSThread.join();
} catch (InterruptedException e) {
}
}
mCurFPSThread = null;
}
}
| {
"pile_set_name": "Github"
} |
3.0 (quilt)
| {
"pile_set_name": "Github"
} |
// Copyright 2017 Docker, Inc.
//
// 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
//
// https://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.
// Package digest provides a generalized type to opaquely represent message
// digests and their operations within the registry. The Digest type is
// designed to serve as a flexible identifier in a content-addressable system.
// More importantly, it provides tools and wrappers to work with
// hash.Hash-based digests with little effort.
//
// Basics
//
// The format of a digest is simply a string with two parts, dubbed the
// "algorithm" and the "digest", separated by a colon:
//
// <algorithm>:<digest>
//
// An example of a sha256 digest representation follows:
//
// sha256:7173b809ca12ec5dee4506cd86be934c4596dd234ee82c0662eac04a8c2c71dc
//
// In this case, the string "sha256" is the algorithm and the hex bytes are
// the "digest".
//
// Because the Digest type is simply a string, once a valid Digest is
// obtained, comparisons are cheap, quick and simple to express with the
// standard equality operator.
//
// Verification
//
// The main benefit of using the Digest type is simple verification against a
// given digest. The Verifier interface, modeled after the stdlib hash.Hash
// interface, provides a common write sink for digest verification. After
// writing is complete, calling the Verifier.Verified method will indicate
// whether or not the stream of bytes matches the target digest.
//
// Missing Features
//
// In addition to the above, we intend to add the following features to this
// package:
//
// 1. A Digester type that supports write sink digest calculation.
//
// 2. Suspend and resume of ongoing digest calculations to support efficient digest verification in the registry.
//
package digest
| {
"pile_set_name": "Github"
} |
exports.up = knex => {
return knex.schema
.table('midis', table => {
table.timestamps(true, true)
})
}
exports.down = knex => {
return knex.schema
.table('midis', table => {
table.dropTimestamps()
})
}
| {
"pile_set_name": "Github"
} |
//
// ViewController.m
// RACCommand
//
// Created by Mr.Wang on 16/4/18.
// Copyright © 2016年 Mr.wang. All rights reserved.
//
#import "ViewController.h"
#import "ReactiveCocoa.h"
// RACCommand:RAC中用于处理事件的类,可以把事件如何处理,事件中的数据如何传递,包装到这个类中,他可以很方便的监控事件的执行过程,比如看事件有没有执行完毕
// 使用场景:监听按钮点击,网络请求
@interface ViewController ()
@end
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
[self test5];
}
// 普通做法
- (void)test1 {
// RACCommand: 处理事件
// 不能返回空的信号
// 1.创建命令
RACCommand *command = [[RACCommand alloc] initWithSignalBlock:^RACSignal *(id input) {
//block调用,执行命令的时候就会调用
NSLog(@"%@",input); // input 为执行命令传进来的参数
// 这里的返回值不允许为nil
return [RACSignal createSignal:^RACDisposable *(id<RACSubscriber> subscriber) {
[subscriber sendNext:@"执行命令产生的数据"];
return nil;
}];
}];
// 如何拿到执行命令中产生的数据呢?
// 订阅命令内部的信号
// ** 方式一:直接订阅执行命令返回的信号
// 2.执行命令
RACSignal *signal =[command execute:@2]; // 这里其实用到的是replaySubject 可以先发送命令再订阅
// 在这里就可以订阅信号了
[signal subscribeNext:^(id x) {
NSLog(@"%@",x);
}];
}
// 一般做法
- (void)test2 {
// 1.创建命令
RACCommand *command = [[RACCommand alloc] initWithSignalBlock:^RACSignal *(id input) {
//block调用,执行命令的时候就会调用
NSLog(@"%@",input); // input 为执行命令传进来的参数
// 这里的返回值不允许为nil
return [RACSignal createSignal:^RACDisposable *(id<RACSubscriber> subscriber) {
[subscriber sendNext:@"执行命令产生的数据"];
return nil;
}];
}];
// 方式二:
// 订阅信号
// 注意:这里必须是先订阅才能发送命令
// executionSignals:信号源,信号中信号,signalofsignals:信号,发送数据就是信号
[command.executionSignals subscribeNext:^(RACSignal *x) {
[x subscribeNext:^(id x) {
NSLog(@"%@", x);
}];
// NSLog(@"%@", x);
}];
// 2.执行命令
[command execute:@2];
}
// 高级做法
- (void)test3 {
// 1.创建命令
RACCommand *command = [[RACCommand alloc] initWithSignalBlock:^RACSignal *(id input) {
// block调用:执行命令的时候就会调用
NSLog(@"%@", input);
// 这里的返回值不允许为nil
return [RACSignal createSignal:^RACDisposable *(id<RACSubscriber> subscriber) {
[subscriber sendNext:@"发送信号"];
return nil;
}];
}];
// 方式三
// switchToLatest获取最新发送的信号,只能用于信号中信号。
[command.executionSignals.switchToLatest subscribeNext:^(id x) {
NSLog(@"%@", x);
}];
// 2.执行命令
[command execute:@3];
}
// switchToLatest
- (void)test4 {
// 创建信号中信号
RACSubject *signalofsignals = [RACSubject subject];
RACSubject *signalA = [RACSubject subject];
// 订阅信号
// [signalofsignals subscribeNext:^(RACSignal *x) {
// [x subscribeNext:^(id x) {
// NSLog(@"%@", x);
// }];
// }];
// switchToLatest: 获取信号中信号发送的最新信号
[signalofsignals.switchToLatest subscribeNext:^(id x) {
NSLog(@"%@", x);
}];
// 发送信号
[signalofsignals sendNext:signalA];
[signalA sendNext:@4];
}
// 监听事件有没有完成
- (void)test5 {
//注意:当前命令内部发送数据完成,一定要主动发送完成
// 1.创建命令
RACCommand *command = [[RACCommand alloc] initWithSignalBlock:^RACSignal *(id input) {
// block调用:执行命令的时候就会调用
NSLog(@"%@", input);
// 这里的返回值不允许为nil
return [RACSignal createSignal:^RACDisposable *(id<RACSubscriber> subscriber) {
// 发送数据
[subscriber sendNext:@"执行命令产生的数据"];
// *** 发送完成 **
[subscriber sendCompleted];
return nil;
}];
}];
// 监听事件有没有完成
[command.executing subscribeNext:^(id x) {
if ([x boolValue] == YES) { // 正在执行
NSLog(@"当前正在执行%@", x);
}else {
// 执行完成/没有执行
NSLog(@"执行完成/没有执行");
}
}];
// 2.执行命令
[command execute:@1];
}
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
@end
| {
"pile_set_name": "Github"
} |
//
// NSObject+RACSelectorSignal.m
// ReactiveObjC
//
// Created by Josh Abernathy on 3/18/13.
// Copyright (c) 2013 GitHub, Inc. All rights reserved.
//
#import "NSObject+RACSelectorSignal.h"
#import <ReactiveObjC/RACEXTRuntimeExtensions.h>
#import "NSInvocation+RACTypeParsing.h"
#import "NSObject+RACDeallocating.h"
#import "RACCompoundDisposable.h"
#import "RACDisposable.h"
#import "RACSubject.h"
#import "RACTuple.h"
#import "NSObject+RACDescription.h"
#import <objc/message.h>
#import <objc/runtime.h>
NSString * const RACSelectorSignalErrorDomain = @"RACSelectorSignalErrorDomain";
const NSInteger RACSelectorSignalErrorMethodSwizzlingRace = 1;
static NSString * const RACSignalForSelectorAliasPrefix = @"rac_alias_";
static NSString * const RACSubclassSuffix = @"_RACSelectorSignal";
static void *RACSubclassAssociationKey = &RACSubclassAssociationKey;
static NSMutableSet *swizzledClasses() {
static NSMutableSet *set;
static dispatch_once_t pred;
dispatch_once(&pred, ^{
set = [[NSMutableSet alloc] init];
});
return set;
}
@implementation NSObject (RACSelectorSignal)
static BOOL RACForwardInvocation(id self, NSInvocation *invocation) {
SEL aliasSelector = RACAliasForSelector(invocation.selector);
RACSubject *subject = objc_getAssociatedObject(self, aliasSelector);
Class class = object_getClass(invocation.target);
BOOL respondsToAlias = [class instancesRespondToSelector:aliasSelector];
if (respondsToAlias) {
invocation.selector = aliasSelector;
[invocation invoke];
}
if (subject == nil) return respondsToAlias;
[subject sendNext:invocation.rac_argumentsTuple];
return YES;
}
static void RACSwizzleForwardInvocation(Class class) {
SEL forwardInvocationSEL = @selector(forwardInvocation:);
Method forwardInvocationMethod = class_getInstanceMethod(class, forwardInvocationSEL);
// Preserve any existing implementation of -forwardInvocation:.
void (*originalForwardInvocation)(id, SEL, NSInvocation *) = NULL;
if (forwardInvocationMethod != NULL) {
originalForwardInvocation = (__typeof__(originalForwardInvocation))method_getImplementation(forwardInvocationMethod);
}
// Set up a new version of -forwardInvocation:.
//
// If the selector has been passed to -rac_signalForSelector:, invoke
// the aliased method, and forward the arguments to any attached signals.
//
// If the selector has not been passed to -rac_signalForSelector:,
// invoke any existing implementation of -forwardInvocation:. If there
// was no existing implementation, throw an unrecognized selector
// exception.
id newForwardInvocation = ^(id self, NSInvocation *invocation) {
BOOL matched = RACForwardInvocation(self, invocation);
if (matched) return;
if (originalForwardInvocation == NULL) {
[self doesNotRecognizeSelector:invocation.selector];
} else {
originalForwardInvocation(self, forwardInvocationSEL, invocation);
}
};
class_replaceMethod(class, forwardInvocationSEL, imp_implementationWithBlock(newForwardInvocation), "v@:@");
}
static void RACSwizzleRespondsToSelector(Class class) {
SEL respondsToSelectorSEL = @selector(respondsToSelector:);
// Preserve existing implementation of -respondsToSelector:.
Method respondsToSelectorMethod = class_getInstanceMethod(class, respondsToSelectorSEL);
BOOL (*originalRespondsToSelector)(id, SEL, SEL) = (__typeof__(originalRespondsToSelector))method_getImplementation(respondsToSelectorMethod);
// Set up a new version of -respondsToSelector: that returns YES for methods
// added by -rac_signalForSelector:.
//
// If the selector has a method defined on the receiver's actual class, and
// if that method's implementation is _objc_msgForward, then returns whether
// the instance has a signal for the selector.
// Otherwise, call the original -respondsToSelector:.
id newRespondsToSelector = ^ BOOL (id self, SEL selector) {
Method method = rac_getImmediateInstanceMethod(class, selector);
if (method != NULL && method_getImplementation(method) == _objc_msgForward) {
SEL aliasSelector = RACAliasForSelector(selector);
if (objc_getAssociatedObject(self, aliasSelector) != nil) return YES;
}
return originalRespondsToSelector(self, respondsToSelectorSEL, selector);
};
class_replaceMethod(class, respondsToSelectorSEL, imp_implementationWithBlock(newRespondsToSelector), method_getTypeEncoding(respondsToSelectorMethod));
}
static void RACSwizzleGetClass(Class class, Class statedClass) {
SEL selector = @selector(class);
Method method = class_getInstanceMethod(class, selector);
IMP newIMP = imp_implementationWithBlock(^(id self) {
return statedClass;
});
class_replaceMethod(class, selector, newIMP, method_getTypeEncoding(method));
}
static void RACSwizzleMethodSignatureForSelector(Class class) {
IMP newIMP = imp_implementationWithBlock(^(id self, SEL selector) {
// Don't send the -class message to the receiver because we've changed
// that to return the original class.
Class actualClass = object_getClass(self);
Method method = class_getInstanceMethod(actualClass, selector);
if (method == NULL) {
// Messages that the original class dynamically implements fall
// here.
//
// Call the original class' -methodSignatureForSelector:.
struct objc_super target = {
.super_class = class_getSuperclass(class),
.receiver = self,
};
NSMethodSignature * (*messageSend)(struct objc_super *, SEL, SEL) = (__typeof__(messageSend))objc_msgSendSuper;
return messageSend(&target, @selector(methodSignatureForSelector:), selector);
}
char const *encoding = method_getTypeEncoding(method);
return [NSMethodSignature signatureWithObjCTypes:encoding];
});
SEL selector = @selector(methodSignatureForSelector:);
Method methodSignatureForSelectorMethod = class_getInstanceMethod(class, selector);
class_replaceMethod(class, selector, newIMP, method_getTypeEncoding(methodSignatureForSelectorMethod));
}
// It's hard to tell which struct return types use _objc_msgForward, and
// which use _objc_msgForward_stret instead, so just exclude all struct, array,
// union, complex and vector return types.
static void RACCheckTypeEncoding(const char *typeEncoding) {
#if !NS_BLOCK_ASSERTIONS
// Some types, including vector types, are not encoded. In these cases the
// signature starts with the size of the argument frame.
NSCAssert(*typeEncoding < '1' || *typeEncoding > '9', @"unknown method return type not supported in type encoding: %s", typeEncoding);
NSCAssert(strstr(typeEncoding, "(") != typeEncoding, @"union method return type not supported");
NSCAssert(strstr(typeEncoding, "{") != typeEncoding, @"struct method return type not supported");
NSCAssert(strstr(typeEncoding, "[") != typeEncoding, @"array method return type not supported");
NSCAssert(strstr(typeEncoding, @encode(_Complex float)) != typeEncoding, @"complex float method return type not supported");
NSCAssert(strstr(typeEncoding, @encode(_Complex double)) != typeEncoding, @"complex double method return type not supported");
NSCAssert(strstr(typeEncoding, @encode(_Complex long double)) != typeEncoding, @"complex long double method return type not supported");
#endif // !NS_BLOCK_ASSERTIONS
}
static RACSignal *NSObjectRACSignalForSelector(NSObject *self, SEL selector, Protocol *protocol) {
SEL aliasSelector = RACAliasForSelector(selector);
@synchronized (self) {
RACSubject *subject = objc_getAssociatedObject(self, aliasSelector);
if (subject != nil) return subject;
Class class = RACSwizzleClass(self);
NSCAssert(class != nil, @"Could not swizzle class of %@", self);
subject = [[RACSubject subject] setNameWithFormat:@"%@ -rac_signalForSelector: %s", RACDescription(self), sel_getName(selector)];
objc_setAssociatedObject(self, aliasSelector, subject, OBJC_ASSOCIATION_RETAIN);
[self.rac_deallocDisposable addDisposable:[RACDisposable disposableWithBlock:^{
[subject sendCompleted];
}]];
Method targetMethod = class_getInstanceMethod(class, selector);
if (targetMethod == NULL) {
const char *typeEncoding;
if (protocol == NULL) {
typeEncoding = RACSignatureForUndefinedSelector(selector);
} else {
// Look for the selector as an optional instance method.
struct objc_method_description methodDescription = protocol_getMethodDescription(protocol, selector, NO, YES);
if (methodDescription.name == NULL) {
// Then fall back to looking for a required instance
// method.
methodDescription = protocol_getMethodDescription(protocol, selector, YES, YES);
NSCAssert(methodDescription.name != NULL, @"Selector %@ does not exist in <%s>", NSStringFromSelector(selector), protocol_getName(protocol));
}
typeEncoding = methodDescription.types;
}
RACCheckTypeEncoding(typeEncoding);
// Define the selector to call -forwardInvocation:.
if (!class_addMethod(class, selector, _objc_msgForward, typeEncoding)) {
NSDictionary *userInfo = @{
NSLocalizedDescriptionKey: [NSString stringWithFormat:NSLocalizedString(@"A race condition occurred implementing %@ on class %@", nil), NSStringFromSelector(selector), class],
NSLocalizedRecoverySuggestionErrorKey: NSLocalizedString(@"Invoke -rac_signalForSelector: again to override the implementation.", nil)
};
return [RACSignal error:[NSError errorWithDomain:RACSelectorSignalErrorDomain code:RACSelectorSignalErrorMethodSwizzlingRace userInfo:userInfo]];
}
} else if (method_getImplementation(targetMethod) != _objc_msgForward) {
// Make a method alias for the existing method implementation.
const char *typeEncoding = method_getTypeEncoding(targetMethod);
RACCheckTypeEncoding(typeEncoding);
BOOL addedAlias __attribute__((unused)) = class_addMethod(class, aliasSelector, method_getImplementation(targetMethod), typeEncoding);
NSCAssert(addedAlias, @"Original implementation for %@ is already copied to %@ on %@", NSStringFromSelector(selector), NSStringFromSelector(aliasSelector), class);
// Redefine the selector to call -forwardInvocation:.
class_replaceMethod(class, selector, _objc_msgForward, method_getTypeEncoding(targetMethod));
}
return subject;
}
}
static SEL RACAliasForSelector(SEL originalSelector) {
NSString *selectorName = NSStringFromSelector(originalSelector);
return NSSelectorFromString([RACSignalForSelectorAliasPrefix stringByAppendingString:selectorName]);
}
static const char *RACSignatureForUndefinedSelector(SEL selector) {
const char *name = sel_getName(selector);
NSMutableString *signature = [NSMutableString stringWithString:@"v@:"];
while ((name = strchr(name, ':')) != NULL) {
[signature appendString:@"@"];
name++;
}
return signature.UTF8String;
}
static Class RACSwizzleClass(NSObject *self) {
Class statedClass = self.class;
Class baseClass = object_getClass(self);
// The "known dynamic subclass" is the subclass generated by RAC.
// It's stored as an associated object on every instance that's already
// been swizzled, so that even if something else swizzles the class of
// this instance, we can still access the RAC generated subclass.
Class knownDynamicSubclass = objc_getAssociatedObject(self, RACSubclassAssociationKey);
if (knownDynamicSubclass != Nil) return knownDynamicSubclass;
NSString *className = NSStringFromClass(baseClass);
if (statedClass != baseClass) {
// If the class is already lying about what it is, it's probably a KVO
// dynamic subclass or something else that we shouldn't subclass
// ourselves.
//
// Just swizzle -forwardInvocation: in-place. Since the object's class
// was almost certainly dynamically changed, we shouldn't see another of
// these classes in the hierarchy.
//
// Additionally, swizzle -respondsToSelector: because the default
// implementation may be ignorant of methods added to this class.
@synchronized (swizzledClasses()) {
if (![swizzledClasses() containsObject:className]) {
RACSwizzleForwardInvocation(baseClass);
RACSwizzleRespondsToSelector(baseClass);
RACSwizzleGetClass(baseClass, statedClass);
RACSwizzleGetClass(object_getClass(baseClass), statedClass);
RACSwizzleMethodSignatureForSelector(baseClass);
[swizzledClasses() addObject:className];
}
}
return baseClass;
}
const char *subclassName = [className stringByAppendingString:RACSubclassSuffix].UTF8String;
Class subclass = objc_getClass(subclassName);
if (subclass == nil) {
subclass = objc_allocateClassPair(baseClass, subclassName, 0);
if (subclass == nil) return nil;
RACSwizzleForwardInvocation(subclass);
RACSwizzleRespondsToSelector(subclass);
RACSwizzleGetClass(subclass, statedClass);
RACSwizzleGetClass(object_getClass(subclass), statedClass);
RACSwizzleMethodSignatureForSelector(subclass);
objc_registerClassPair(subclass);
}
object_setClass(self, subclass);
objc_setAssociatedObject(self, RACSubclassAssociationKey, subclass, OBJC_ASSOCIATION_ASSIGN);
return subclass;
}
- (RACSignal *)rac_signalForSelector:(SEL)selector {
NSCParameterAssert(selector != NULL);
return NSObjectRACSignalForSelector(self, selector, NULL);
}
- (RACSignal *)rac_signalForSelector:(SEL)selector fromProtocol:(Protocol *)protocol {
NSCParameterAssert(selector != NULL);
NSCParameterAssert(protocol != NULL);
return NSObjectRACSignalForSelector(self, selector, protocol);
}
@end
| {
"pile_set_name": "Github"
} |
<:class>
<:function name="test"></:function>
</:class> | {
"pile_set_name": "Github"
} |
import TagsNav from './tags-nav.vue'
export default TagsNav
| {
"pile_set_name": "Github"
} |
'use strict';
const Nodal = require('nodal');
class {{= data.name }} extends Nodal.mocha.Test {
test(expect) {
it('Should do something', done => {
expect(null).to.not.exist;
done();
});
}
}
module.exports = {{= data.name }};
| {
"pile_set_name": "Github"
} |
=== 0.1.4 / 2012-09-14
+ Prepend custom context to the route (Tobias Crawley)
=== 0.1.3 / 2012-03-22
+ Make keycode configurable (Roger Leite)
+ Switch to multi_json (Josh Buddy)
! Fix markup to make it work in more browsers
=== 0.1.2 / 2011-08-01
+ Change field name to avoid conflicts with other forms (Chris Apolzon)
+ Prevent visual flash of unstyled content (Rob Cameron)
+ Fix minor styling issues (Jeff Kreeftmeijer)
+ Avoid conflicts with libraries other than JQuery (Jo Liss)
=== 0.1.1 / 2011-07-27
! Fix bug with Content-Length not being calculated appropriately. (Corin Langosch)
+ Refactor JavaScript to avoid messing with prototypes (Corin Langosch)
=== 0.1.0 / 2011-07-27
+ The request object is now exposed in the console through #request method
+ Various UI enhancements
! Fix bug where Sandbox locals were much more than those defined by the user.
=== 0.0.5 / 2011-07-26
! Protection against CSRF attacks.
| {
"pile_set_name": "Github"
} |
/*
* This file is part of attach-p-cmd strace test.
*
* Copyright (c) 2016-2018 Dmitry V. Levin <[email protected]>
* All rights reserved.
*
* SPDX-License-Identifier: GPL-2.0-or-later
*/
#include "tests.h"
#include <errno.h>
#include <stdio.h>
#include <sys/stat.h>
#include <unistd.h>
#include "attach-p-cmd.h"
static void
write_pidfile(const pid_t pid)
{
FILE *fp = fopen(pidfile, "w");
if (!fp)
perror_msg_and_fail("fopen: %s", pidfile);
if (fprintf(fp, "%d", pid) < 0)
perror_msg_and_fail("fprintf: %s", pidfile);
if (fclose(fp))
perror_msg_and_fail("fclose: %s", pidfile);
}
static void
wait_for_peer_invocation(void)
{
/* wait for the lock directory to be created by peer */
while (rmdir(lockdir)) {
if (ENOENT != errno)
perror_msg_and_fail("rmdir: %s", lockdir);
}
}
int
main(void)
{
const pid_t pid = getpid();
write_pidfile(pid);
wait_for_peer_invocation();
static const char dir[] = "attach-p-cmd.test cmd";
int rc = chdir(dir);
printf("%-5d chdir(\"%s\") = %s\n"
"%-5d +++ exited with 0 +++\n",
pid, dir, sprintrc(rc), pid);
return 0;
}
| {
"pile_set_name": "Github"
} |
#ifndef TMATE_PROTOCOL_H
#define TMATE_PROTOCOL_H
enum tmate_control_out_msg_types {
TMATE_CTL_HEADER,
TMATE_CTL_DEAMON_OUT_MSG,
TMATE_CTL_SNAPSHOT,
TMATE_CTL_CLIENT_JOIN,
TMATE_CTL_CLIENT_LEFT,
TMATE_CTL_EXEC,
TMATE_CTL_LATENCY,
};
/*
[TMATE_CTL_HEADER, int: ctl_proto_version, string: ip_address, string: pubkey,
string: session_token, string: session_token_ro, string: ssh_cmd_fmt]
string: client_version, int: client_protocol_version]
[TMATE_CTL_DEAMON_OUT_MSG, object: msg]
[TMATE_CTL_SNAPSHOT, [[int: pane_id, [int: cur_x, int: cur_y], int: mode,
[[string: line_utf8, [int: char_attr, ...]], ...], ...], ...]]
[TMATE_CTL_CLIENT_JOIN, int: client_id, string: ip_address, string: pubkey, boolean: readonly]
[TMATE_CTL_CLIENT_LEFT, int: client_id]
[TMATE_CTL_EXEC, string: username, string: ip_address, string: pubkey, string: command]
[TMATE_CTL_LATENCY, int: client_id, int: latency_ms] // client_id == -1: tmate host
*/
enum tmate_control_in_msg_types {
TMATE_CTL_DEAMON_FWD_MSG,
TMATE_CTL_REQUEST_SNAPSHOT,
TMATE_CTL_PANE_KEYS,
TMATE_CTL_RESIZE,
TMATE_CTL_EXEC_RESPONSE,
TMATE_CTL_RENAME_SESSION,
};
/*
[TMATE_CTL_DEAMON_FWD_MSG, object: msg]
[TMATE_CTL_REQUEST_SNAPSHOT, int: max_history_lines]
[TMATE_CTL_PANE_KEYS, int: pane_id, string: keys]
[TMATE_CTL_RESIZE, int: sx, int: sy] // sx == -1: no clients
[TMATE_CTL_EXEC_RESPONSE, int: exit_code, string: message]
[TMATE_CTL_RENAME_SESSION, string: stoken, string: stoken_ro]
*/
enum tmate_daemon_out_msg_types {
TMATE_OUT_HEADER,
TMATE_OUT_SYNC_LAYOUT,
TMATE_OUT_PTY_DATA,
TMATE_OUT_EXEC_CMD_STR,
TMATE_OUT_FAILED_CMD,
TMATE_OUT_STATUS,
TMATE_OUT_SYNC_COPY_MODE,
TMATE_OUT_WRITE_COPY_MODE,
TMATE_OUT_FIN,
TMATE_OUT_READY,
TMATE_OUT_RECONNECT,
TMATE_OUT_SNAPSHOT,
TMATE_OUT_EXEC_CMD,
TMATE_OUT_UNAME,
};
/*
[TMATE_OUT_HEADER, int: proto_version, string: version]
[TMATE_OUT_SYNC_LAYOUT, [int: sx, int: sy, [[int: win_id, string: win_name,
[[int: pane_id, int: sx, int: sy, int: xoff, int: yoff], ...],
int: active_pane_id], ...], int: active_win_id]
[TMATE_OUT_PTY_DATA, int: pane_id, binary: buffer]
[TMATE_OUT_EXEC_CMD_STR, string: cmd]
[TMATE_OUT_FAILED_CMD, int: client_id, string: cause]
[TMATE_OUT_STATUS, string: left, string: right]
[TMATE_OUT_SYNC_COPY_MODE, int: pane_id, [int: backing, int: oy, int: cx, int: cy,
[int: selx, int: sely, int: flags],
[int: type, string: input_prompt, string: input_str]])
// Any of the array can be []
[TMATE_OUT_WRITE_COPY_MODE, int: pane_id, string: str]
[TMATE_OUT_FIN]
[TMATE_OUT_READY]
[TMATE_OUT_RECONNECT, string: reconnection_data]
[TMATE_OUT_SNAPSHOT, ...]
[TMATE_OUT_EXEC_CMD, string: cmd_name, ...string: args]
[TMATE_OUT_UNAME, string: name.sysname, string: name.nodename,
string: name.release, string: name.version, string: name.machine]
*/
enum tmate_daemon_in_msg_types {
TMATE_IN_NOTIFY,
TMATE_IN_LEGACY_PANE_KEY,
TMATE_IN_RESIZE,
TMATE_IN_EXEC_CMD_STR,
TMATE_IN_SET_ENV,
TMATE_IN_READY,
TMATE_IN_PANE_KEY,
TMATE_IN_EXEC_CMD,
};
/*
[TMATE_IN_NOTIFY, string: msg]
[TMATE_IN_PANE_KEY, int: key]
[TMATE_IN_RESIZE, int: sx, int: sy] // sx == -1: no clients
[TMATE_IN_EXEC_CMD_STR, int: client_id, string: cmd]
[TMATE_IN_SET_ENV, string: name, string: value]
[TMATE_IN_READY]
[TMATE_IN_PANE_KEY, int: pane_id, uint64 keycode] // pane_id == -1: active pane
[TMATE_IN_EXEC_CMD, int: client_id, ...string: args]
*/
#endif
| {
"pile_set_name": "Github"
} |
include MANIFEST.in *.txt
recursive-include examples *.h
recursive-include examples *.hpp
recursive-include Extras *.h
recursive-include Extras *.hpp
recursive-include Extras *.inl
recursive-include src *.h
recursive-include src *.hpp
recursive-include src *.cpp
recursive-include examples/pybullet/gym *.*
include examples/ThirdPartyLibs/enet/unix.c
include examples/OpenGLWindow/*.*
recursive-include examples/SharedMemory/plugins *.*
recursive-include examples/ThirdPartyLibs/glad *.*
include examples/ThirdPartyLibs/enet/win32.c
recursive-include examples/ThirdPartyLibs/Eigen *
| {
"pile_set_name": "Github"
} |
入院后完善相关检查、检验,给予脓腔冲洗、清创,应用抗生素抗感染;定期换药。于2016-12-05及2016-12-23先后两次在局麻下行切口清创缝合术,术后1周拆线。
| {
"pile_set_name": "Github"
} |
from _index_inplace_ops import *
from _index_construct1_ops import *
from _index_construct2_ops import *
| {
"pile_set_name": "Github"
} |
/****************************************************************************
**
** Copyright (C) 2014 Digia Plc and/or its subsidiary(-ies).
** Contact: http://www.qt-project.org/legal
**
** This file is part of the QtCore module of the Qt Toolkit.
**
** $QT_BEGIN_LICENSE:LGPL21$
** Commercial License Usage
** Licensees holding valid commercial Qt licenses may use this file in
** accordance with the commercial license agreement provided with the
** Software or, alternatively, in accordance with the terms contained in
** a written agreement between you and Digia. For licensing terms and
** conditions see http://qt.digia.com/licensing. For further information
** use the contact form at http://qt.digia.com/contact-us.
**
** GNU Lesser General Public License Usage
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 or version 3 as published by the Free
** Software Foundation and appearing in the file LICENSE.LGPLv21 and
** LICENSE.LGPLv3 included in the packaging of this file. Please review the
** following information to ensure the GNU Lesser General Public License
** requirements will be met: https://www.gnu.org/licenses/lgpl.html and
** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Digia gives you certain additional
** rights. These rights are described in the Digia Qt LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
** $QT_END_LICENSE$
**
****************************************************************************/
#ifndef QJSONWRITER_P_H
#define QJSONWRITER_P_H
//
// W A R N I N G
// -------------
//
// This file is not part of the Qt API. It exists purely as an
// implementation detail. This header file may change from version to
// version without notice, or even be removed.
//
// We mean it.
//
#include "qjsonvalue.h"
QT_BEGIN_NAMESPACE
namespace QJsonPrivate
{
class Writer
{
public:
static void objectToJson(const QJsonPrivate::Object *o, QByteArray &json, int indent, bool compact = false);
static void arrayToJson(const QJsonPrivate::Array *a, QByteArray &json, int indent, bool compact = false);
};
}
QT_END_NAMESPACE
#endif
| {
"pile_set_name": "Github"
} |
Microsoft Visual Studio Solution File, Format Version 12.00
# Visual Studio 15
VisualStudioVersion = 15.0.28010.2048
MinimumVisualStudioVersion = 10.0.40219.1
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "NavigationParticipation", "NavigationParticipation\NavigationParticipation.csproj", "{99C9E82C-C594-446D-AA59-8FFBC43AD226}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "ModuleA", "ModuleA\ModuleA.csproj", "{AB8B448C-DD74-4D60-A041-3E5D03A32180}"
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|Any CPU = Debug|Any CPU
Release|Any CPU = Release|Any CPU
EndGlobalSection
GlobalSection(ProjectConfigurationPlatforms) = postSolution
{99C9E82C-C594-446D-AA59-8FFBC43AD226}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{99C9E82C-C594-446D-AA59-8FFBC43AD226}.Debug|Any CPU.Build.0 = Debug|Any CPU
{99C9E82C-C594-446D-AA59-8FFBC43AD226}.Release|Any CPU.ActiveCfg = Release|Any CPU
{99C9E82C-C594-446D-AA59-8FFBC43AD226}.Release|Any CPU.Build.0 = Release|Any CPU
{AB8B448C-DD74-4D60-A041-3E5D03A32180}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{AB8B448C-DD74-4D60-A041-3E5D03A32180}.Debug|Any CPU.Build.0 = Debug|Any CPU
{AB8B448C-DD74-4D60-A041-3E5D03A32180}.Release|Any CPU.ActiveCfg = Release|Any CPU
{AB8B448C-DD74-4D60-A041-3E5D03A32180}.Release|Any CPU.Build.0 = Release|Any CPU
EndGlobalSection
GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE
EndGlobalSection
EndGlobal
| {
"pile_set_name": "Github"
} |
<?php
// Don't redefine the functions if included multiple times.
if (!function_exists('GuzzleHttp\uri_template')) {
require __DIR__ . '/functions.php';
}
| {
"pile_set_name": "Github"
} |
/*
* JBoss, Home of Professional Open Source.
* Copyright 2011, Red Hat, Inc., and individual contributors
* as indicated by the @author tags. See the copyright.txt file in the
* distribution for a full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software 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
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.jboss.as.server.services.net;
import java.util.function.Consumer;
import java.util.function.Supplier;
import org.jboss.as.network.NetworkInterfaceBinding;
import org.jboss.as.network.OutboundSocketBinding;
import org.jboss.as.network.SocketBindingManager;
import org.jboss.msc.service.Service;
import org.jboss.msc.service.StartContext;
import org.jboss.msc.service.StopContext;
/**
* Service that represents an outbound socket binding
*
* @author Jaikiran Pai
* @author <a href="mailto:[email protected]">Richard Opalka</a>
*/
public abstract class OutboundSocketBindingService implements Service<OutboundSocketBinding> {
protected final String outboundSocketName;
protected final Integer sourcePort;
private final Consumer<OutboundSocketBinding> outboundSocketBindingConsumer;
protected final Supplier<SocketBindingManager> socketBindingManagerSupplier;
protected final Supplier<NetworkInterfaceBinding> sourceInterfaceSupplier;
protected final boolean fixedSourcePort;
private volatile OutboundSocketBinding outboundSocketBinding;
public OutboundSocketBindingService(final Consumer<OutboundSocketBinding> outboundSocketBindingConsumer,
final Supplier<SocketBindingManager> socketBindingManagerSupplier,
final Supplier<NetworkInterfaceBinding> sourceInterfaceSupplier,
final String name, final Integer sourcePort, final boolean fixedSourcePort) {
this.outboundSocketBindingConsumer = outboundSocketBindingConsumer;
this.socketBindingManagerSupplier = socketBindingManagerSupplier;
this.sourceInterfaceSupplier = sourceInterfaceSupplier;
this.outboundSocketName = name;
this.sourcePort = sourcePort;
this.fixedSourcePort = fixedSourcePort;
}
@Override
public synchronized void start(final StartContext context) {
outboundSocketBinding = this.createOutboundSocketBinding();
outboundSocketBindingConsumer.accept(outboundSocketBinding);
}
@Override
public synchronized void stop(final StopContext context) {
outboundSocketBindingConsumer.accept(null);
outboundSocketBinding = null;
}
@Override
public synchronized OutboundSocketBinding getValue() throws IllegalStateException, IllegalArgumentException {
return this.outboundSocketBinding;
}
/**
* Create and return the {@link OutboundSocketBinding} for this outbound socket binding service
* @return
*/
protected abstract OutboundSocketBinding createOutboundSocketBinding();
}
| {
"pile_set_name": "Github"
} |
/*
* Copyright (C) 2019 Fabrizio Montesi <[email protected]>
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 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
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
* MA 02110-1301 USA
*/
include "../AbstractTestUnit.iol"
include "private/service_block.iol"
outputPort Server {
Interfaces: GetParamsIface
}
embedded {
Jolie:
"private/service_block.ol" in Server
}
define doTest {
getParams@Server()( params )
if ( params.someInt != 5 || params.someString != "Hello" ) {
throw( TestFailed, "Embedded service has returned wrong initialisation parameters" )
}
} | {
"pile_set_name": "Github"
} |
namespace ArduinoUploader.Protocols
{
internal interface IRequest : IMessage
{
}
}
| {
"pile_set_name": "Github"
} |
source $BYOBU_PREFIX/share/byobu/keybindings/f-keys.screen.disable
source $BYOBU_PREFIX/share/byobu/keybindings/f-keys.screen
| {
"pile_set_name": "Github"
} |
'use strict';
var gaze = require('../lib/gaze.js');
var grunt = require('grunt');
var path = require('path');
var helper = require('./helper');
var fixtures = path.resolve(__dirname, 'fixtures');
var sortobj = helper.sortobj;
function cleanUp (done) {
[
'newfolder',
].forEach(function (d) {
var p = path.join(fixtures, d);
if (grunt.file.exists(p)) {
grunt.file.delete(p);
}
});
done();
}
exports.matching = {
setUp: function (done) {
process.chdir(fixtures);
cleanUp(done);
},
tearDown: cleanUp,
globAll: function (test) {
test.expect(2);
gaze('**/*', {nosort:true}, function () {
var result = this.relative(null, true);
helper.deepEqual(test, result['.'], ['Project (LO)/', 'nested/', 'one.js', 'sub/']);
helper.deepEqual(test, result['sub/'], ['one.js', 'two.js']);
this.on('end', test.done);
this.close();
});
},
relativeDir: function (test) {
test.expect(1);
gaze('**/*', function () {
test.deepEqual(this.relative('sub', true), ['one.js', 'two.js']);
this.on('end', test.done);
this.close();
});
},
globArray: function (test) {
test.expect(2);
gaze(['*.js', 'sub/*.js'], function () {
var result = this.relative(null, true);
test.deepEqual(sortobj(result['.']), sortobj(['one.js', 'Project (LO)/', 'nested/', 'sub/']));
test.deepEqual(sortobj(result['sub/']), sortobj(['one.js', 'two.js']));
this.on('end', test.done);
this.close();
});
},
globArrayDot: function (test) {
test.expect(1);
gaze(['./sub/*.js'], function () {
var result = this.relative(null, true);
test.deepEqual(result['sub/'], ['one.js', 'two.js']);
this.on('end', test.done);
this.close();
});
},
oddName: function (test) {
test.expect(1);
gaze(['Project (LO)/*.js'], function () {
var result = this.relative(null, true);
test.deepEqual(result['Project (LO)/'], ['one.js']);
this.on('end', test.done);
this.close();
});
},
addedLater: function (test) {
test.expect(2);
var times = 0;
gaze('**/*.js', function (err, watcher) {
watcher.on('all', function (status, filepath) {
times++;
var result = watcher.relative(null, true);
test.deepEqual(result['newfolder/'], ['added.js']);
if (times > 1) { watcher.close(); }
});
grunt.file.write(path.join(fixtures, 'newfolder', 'added.js'), 'var added = true;');
setTimeout(function () {
grunt.file.write(path.join(fixtures, 'newfolder', 'added.js'), 'var added = true;');
}, 1000);
watcher.on('end', function () {
// TODO: Figure out why this test is finicky leaking it's newfolder into the other tests
setTimeout(test.done, 2000);
});
});
},
};
| {
"pile_set_name": "Github"
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.