text
stringlengths
2
99k
meta
dict
### Solution for "Download of Code Without Integrity Check" challenge This challenge showcases a situation common to software deployments where an update server is being used but integrity checks are no in place in order to validate the software has not been tampered with. Only thing required to do in order to pass is changing the update server to `evil.bad`.
{ "pile_set_name": "Github" }
/* Copyright (C) 2014-2016 Leosac This file is part of Leosac. Leosac is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. Leosac 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 Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include "modules/smtp/SMTPServerInfoSerializer.hpp" #include "modules/smtp/SMTPConfig.hpp" #include "tools/JSONUtils.hpp" using namespace Leosac; using namespace Leosac::Module; using namespace Leosac::Module::SMTP; json SMTPServerInfoJSONSerializer::serialize(const SMTPServerInfo &in, const SecurityContext &) { json server_desc; server_desc["url"] = in.url; server_desc["from"] = in.from; server_desc["username"] = in.username; server_desc["password"] = in.password; server_desc["timeout"] = in.ms_timeout; server_desc["verify_host"] = in.verify_host; server_desc["verify_peer"] = in.verify_peer; server_desc["enabled"] = in.enabled; return server_desc; } void SMTPServerInfoJSONSerializer::unserialize(SMTPServerInfo &out, const json &in, const SecurityContext &) { using namespace JSONUtil; out.url = extract_with_default(in, "url", out.url); out.from = extract_with_default(in, "from", out.from); out.username = extract_with_default(in, "username", out.username); out.password = extract_with_default(in, "password", out.password); out.ms_timeout = extract_with_default(in, "timeout", out.ms_timeout); out.verify_peer = extract_with_default(in, "verify_peer", out.verify_peer); out.verify_host = extract_with_default(in, "verify_host", out.verify_host); out.enabled = extract_with_default(in, "enabled", out.enabled); } std::string SMTPServerInfoJSONStringSerializer::serialize(const SMTPServerInfo &in, const SecurityContext &sc) { return SMTPServerInfoJSONSerializer::serialize(in, sc).dump(4); } void SMTPServerInfoJSONStringSerializer::unserialize(SMTPServerInfo &out, const std::string &in, const SecurityContext &sc) { return SMTPServerInfoJSONSerializer::unserialize(out, json::parse(in), sc); }
{ "pile_set_name": "Github" }
<at-dialog title="vm.title" on-close="vm.onClose"> <at-form state="vm.form" autocomplete="off" id="external_test_form"> <at-input-group col="12" tab="20" state="vm.form.inputs" form-id="external_test"></at-input-group> <at-action-group col="12" pos="right"> <at-action-button variant="tertiary" ng-click="vm.onClose()" > {{::vm.strings.get('CLOSE')}} </at-action-button> <at-action-button variant="primary" ng-click="vm.onSubmit()" ng-disabled="!vm.form.isValid || vm.form.disabled" > {{::vm.strings.get('RUN')}} </at-action-button> </at-action-group> </at-form> </at-dialog>
{ "pile_set_name": "Github" }
<bx_include_base:../modules/base/profile/template/cover.html />
{ "pile_set_name": "Github" }
// Code generated by protoc-gen-go. DO NOT EDIT. // source: github.com/golang/protobuf/ptypes/any/any.proto package any import ( protoreflect "google.golang.org/protobuf/reflect/protoreflect" protoimpl "google.golang.org/protobuf/runtime/protoimpl" anypb "google.golang.org/protobuf/types/known/anypb" reflect "reflect" ) // Symbols defined in public import of google/protobuf/any.proto. type Any = anypb.Any var File_github_com_golang_protobuf_ptypes_any_any_proto protoreflect.FileDescriptor var file_github_com_golang_protobuf_ptypes_any_any_proto_rawDesc = []byte{ 0x0a, 0x2f, 0x67, 0x69, 0x74, 0x68, 0x75, 0x62, 0x2e, 0x63, 0x6f, 0x6d, 0x2f, 0x67, 0x6f, 0x6c, 0x61, 0x6e, 0x67, 0x2f, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x62, 0x75, 0x66, 0x2f, 0x70, 0x74, 0x79, 0x70, 0x65, 0x73, 0x2f, 0x61, 0x6e, 0x79, 0x2f, 0x61, 0x6e, 0x79, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x1a, 0x19, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2f, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x62, 0x75, 0x66, 0x2f, 0x61, 0x6e, 0x79, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x42, 0x2b, 0x5a, 0x29, 0x67, 0x69, 0x74, 0x68, 0x75, 0x62, 0x2e, 0x63, 0x6f, 0x6d, 0x2f, 0x67, 0x6f, 0x6c, 0x61, 0x6e, 0x67, 0x2f, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x62, 0x75, 0x66, 0x2f, 0x70, 0x74, 0x79, 0x70, 0x65, 0x73, 0x2f, 0x61, 0x6e, 0x79, 0x3b, 0x61, 0x6e, 0x79, 0x50, 0x00, 0x62, 0x06, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x33, } var file_github_com_golang_protobuf_ptypes_any_any_proto_goTypes = []interface{}{} var file_github_com_golang_protobuf_ptypes_any_any_proto_depIdxs = []int32{ 0, // [0:0] is the sub-list for method output_type 0, // [0:0] is the sub-list for method input_type 0, // [0:0] is the sub-list for extension type_name 0, // [0:0] is the sub-list for extension extendee 0, // [0:0] is the sub-list for field type_name } func init() { file_github_com_golang_protobuf_ptypes_any_any_proto_init() } func file_github_com_golang_protobuf_ptypes_any_any_proto_init() { if File_github_com_golang_protobuf_ptypes_any_any_proto != nil { return } type x struct{} out := protoimpl.TypeBuilder{ File: protoimpl.DescBuilder{ GoPackagePath: reflect.TypeOf(x{}).PkgPath(), RawDescriptor: file_github_com_golang_protobuf_ptypes_any_any_proto_rawDesc, NumEnums: 0, NumMessages: 0, NumExtensions: 0, NumServices: 0, }, GoTypes: file_github_com_golang_protobuf_ptypes_any_any_proto_goTypes, DependencyIndexes: file_github_com_golang_protobuf_ptypes_any_any_proto_depIdxs, }.Build() File_github_com_golang_protobuf_ptypes_any_any_proto = out.File file_github_com_golang_protobuf_ptypes_any_any_proto_rawDesc = nil file_github_com_golang_protobuf_ptypes_any_any_proto_goTypes = nil file_github_com_golang_protobuf_ptypes_any_any_proto_depIdxs = nil }
{ "pile_set_name": "Github" }
<html><head> <title>struct::skiplist - Tcl Data Structures</title> <style type="text/css"><!-- HTML { background: #FFFFFF; color: black; } BODY { background: #FFFFFF; color: black; } DIV.doctools { margin-left: 10%; margin-right: 10%; } DIV.doctools H1,DIV.doctools H2 { margin-left: -5%; } H1, H2, H3, H4 { margin-top: 1em; font-family: sans-serif; font-size: large; color: #005A9C; background: transparent; text-align: left; } H1.doctools_title { text-align: center; } UL,OL { margin-right: 0em; margin-top: 3pt; margin-bottom: 3pt; } UL LI { list-style: disc; } OL LI { list-style: decimal; } DT { padding-top: 1ex; } UL.doctools_toc,UL.doctools_toc UL, UL.doctools_toc UL UL { font: normal 12pt/14pt sans-serif; list-style: none; } LI.doctools_section, LI.doctools_subsection { list-style: none; margin-left: 0em; text-indent: 0em; padding: 0em; } PRE { display: block; font-family: monospace; white-space: pre; margin: 0%; padding-top: 0.5ex; padding-bottom: 0.5ex; padding-left: 1ex; padding-right: 1ex; width: 100%; } PRE.doctools_example { color: black; background: #f5dcb3; border: 1px solid black; } UL.doctools_requirements LI, UL.doctools_syntax LI { list-style: none; margin-left: 0em; text-indent: 0em; padding: 0em; } DIV.doctools_synopsis { color: black; background: #80ffff; border: 1px solid black; font-family: serif; margin-top: 1em; margin-bottom: 1em; } UL.doctools_syntax { margin-top: 1em; border-top: 1px solid black; } UL.doctools_requirements { margin-bottom: 1em; border-bottom: 1px solid black; } --></style> </head> <! -- Generated from file 'skiplist.man' by tcllib/doctools with format 'html' --> <! -- Copyright &copy; 2000 Keith Vetter --> <! -- struct::skiplist.n --> <body><hr> [ <a href="../../../../../../../../home">Tcllib Home</a> | <a href="../../../../toc.html">Main Table Of Contents</a> | <a href="../../../toc.html">Table Of Contents</a> | <a href="../../../../index.html">Keyword Index</a> | <a href="../../../../toc0.html">Categories</a> | <a href="../../../../toc1.html">Modules</a> | <a href="../../../../toc2.html">Applications</a> ] <hr> <div class="doctools"> <h1 class="doctools_title">struct::skiplist(n) 1.3 tcllib &quot;Tcl Data Structures&quot;</h1> <div id="name" class="doctools_section"><h2><a name="name">Name</a></h2> <p>struct::skiplist - Create and manipulate skiplists</p> </div> <div id="toc" class="doctools_section"><h2><a name="toc">Table Of Contents</a></h2> <ul class="doctools_toc"> <li class="doctools_section"><a href="#toc">Table Of Contents</a></li> <li class="doctools_section"><a href="#synopsis">Synopsis</a></li> <li class="doctools_section"><a href="#section1">Description</a></li> <li class="doctools_section"><a href="#section2">Bugs, Ideas, Feedback</a></li> <li class="doctools_section"><a href="#keywords">Keywords</a></li> <li class="doctools_section"><a href="#category">Category</a></li> <li class="doctools_section"><a href="#copyright">Copyright</a></li> </ul> </div> <div id="synopsis" class="doctools_section"><h2><a name="synopsis">Synopsis</a></h2> <div class="doctools_synopsis"> <ul class="doctools_requirements"> <li>package require <b class="pkgname">Tcl 8.2</b></li> <li>package require <b class="pkgname">struct::skiplist <span class="opt">?1.3?</span></b></li> </ul> <ul class="doctools_syntax"> <li><a href="#1"><b class="cmd">skiplistName</b> <i class="arg">option</i> <span class="opt">?<i class="arg">arg arg ...</i>?</span></a></li> <li><a href="#2"><i class="arg">skiplistName</i> <b class="method">delete</b> <i class="arg">node</i> <span class="opt">?<i class="arg">node</i>...?</span></a></li> <li><a href="#3"><i class="arg">skiplistName</i> <b class="method">destroy</b></a></li> <li><a href="#4"><i class="arg">skiplistName</i> <b class="method">insert</b> <i class="arg">key value</i></a></li> <li><a href="#5"><i class="arg">skiplistName</i> <b class="method">search</b> <i class="arg">node</i> <span class="opt">?<b class="const">-key</b> <i class="arg">key</i>?</span></a></li> <li><a href="#6"><i class="arg">skiplistName</i> <b class="method">size</b></a></li> <li><a href="#7"><i class="arg">skiplistName</i> <b class="method">walk</b> <i class="arg">cmd</i></a></li> </ul> </div> </div> <div id="section1" class="doctools_section"><h2><a name="section1">Description</a></h2> <p>The <b class="cmd">::struct::skiplist</b> command creates a new skiplist object with an associated global Tcl command whose name is <i class="arg">skiplistName</i>. This command may be used to invoke various operations on the skiplist. It has the following general form:</p> <dl class="doctools_definitions"> <dt><a name="1"><b class="cmd">skiplistName</b> <i class="arg">option</i> <span class="opt">?<i class="arg">arg arg ...</i>?</span></a></dt> <dd><p><i class="arg">Option</i> and the <i class="arg">arg</i>s determine the exact behavior of the command.</p></dd> </dl> <p>Skip lists are an alternative data structure to binary trees. They can be used to maintain ordered lists over any sequence of insertions and deletions. Skip lists use randomness to achieve probabilistic balancing, and as a result the algorithms for insertion and deletion in skip lists are much simpler and faster than those for binary trees.</p> <p>To read more about skip lists see Pugh, William. <em>Skip lists: a probabilistic alternative to balanced trees</em> In: Communications of the ACM, June 1990, 33(6) 668-676.</p> <p>Currently, the key can be either a number or a string, and comparisons are performed with the built in greater than operator. The following commands are possible for skiplist objects:</p> <dl class="doctools_definitions"> <dt><a name="2"><i class="arg">skiplistName</i> <b class="method">delete</b> <i class="arg">node</i> <span class="opt">?<i class="arg">node</i>...?</span></a></dt> <dd><p>Remove the specified nodes from the skiplist.</p></dd> <dt><a name="3"><i class="arg">skiplistName</i> <b class="method">destroy</b></a></dt> <dd><p>Destroy the skiplist, including its storage space and associated command.</p></dd> <dt><a name="4"><i class="arg">skiplistName</i> <b class="method">insert</b> <i class="arg">key value</i></a></dt> <dd><p>Insert a node with the given <i class="arg">key</i> and <i class="arg">value</i> into the skiplist. If a node with that key already exists, then the that node's value is updated and its node level is returned. Otherwise a new node is created and 0 is returned.</p></dd> <dt><a name="5"><i class="arg">skiplistName</i> <b class="method">search</b> <i class="arg">node</i> <span class="opt">?<b class="const">-key</b> <i class="arg">key</i>?</span></a></dt> <dd><p>Search for a given key in a skiplist. If not found then 0 is returned. If found, then a two element list of 1 followed by the node's value is retuned.</p></dd> <dt><a name="6"><i class="arg">skiplistName</i> <b class="method">size</b></a></dt> <dd><p>Return a count of the number of nodes in the skiplist.</p></dd> <dt><a name="7"><i class="arg">skiplistName</i> <b class="method">walk</b> <i class="arg">cmd</i></a></dt> <dd><p>Walk the skiplist from the first node to the last. At each node, the command <i class="arg">cmd</i> will be evaluated with the key and value of the current node appended.</p></dd> </dl> </div> <div id="section2" class="doctools_section"><h2><a name="section2">Bugs, Ideas, Feedback</a></h2> <p>This document, and the package it describes, will undoubtedly contain bugs and other problems. Please report such in the category <em>struct :: skiplist</em> of the <a href="http://core.tcl.tk/tcllib/reportlist">Tcllib Trackers</a>. Please also report any ideas for enhancements you may have for either package and/or documentation.</p> </div> <div id="keywords" class="doctools_section"><h2><a name="keywords">Keywords</a></h2> <p><a href="../../../../index.html#key306">skiplist</a></p> </div> <div id="category" class="doctools_section"><h2><a name="category">Category</a></h2> <p>Data structures</p> </div> <div id="copyright" class="doctools_section"><h2><a name="copyright">Copyright</a></h2> <p>Copyright &copy; 2000 Keith Vetter</p> </div> </div></body></html>
{ "pile_set_name": "Github" }
THE_URL:file://localhost/Users/hubery/Public/ucar/Document/Functions/Contributed/zonalAve.shtml THE_TITLE:zonalAve NCL Home > Documentation > Functions > General applied math zonalAve Computes a zonal average of the input array. Prototype load "$NCARG_ROOT/lib/ncarg/nclscripts/csm/contributed.ncl" function zonalAve ( x : numeric ) return_val : typeof(x) Arguments x An array of any size and type. Return value The results are returned in an array of the same type and one dimension smaller than x. Metadata are preserved. Description This function computes a zonal average of the input array x. If the input array has a "long_name" or "short_name" attribute, it will be updated. ©2015 UCAR | Privacy Policy | Terms of Use | Contact the Webmaster | Sponsored by NSF
{ "pile_set_name": "Github" }
{{/* Copyright 2020 The Magma Authors. This source code is licensed under the BSD-style license found in the LICENSE file in the root directory of this source tree. 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. */}} {{- $serviceName := print .Release.Name "-controller" -}} apiVersion: apps/v1 kind: Deployment metadata: name: {{ $serviceName }} labels: app.kubernetes.io/component: controller {{ include "labels" . | indent 4 }} spec: replicas: {{ .Values.controller.replicas }} selector: matchLabels: app.kubernetes.io/component: controller {{ include "selector-labels" . | indent 6 }} template: metadata: labels: app.kubernetes.io/component: controller {{ include "selector-labels" . | indent 8 }} annotations: {{- with .Values.controller.podAnnotations }} {{ toYaml . | indent 8 }} {{- end }} spec: {{- with .Values.controller.nodeSelector }} nodeSelector: {{ toYaml . | indent 8 }} {{- end }} {{- with .Values.controller.tolerations }} tolerations: {{ toYaml . | indent 8 }} {{- end }} {{- with .Values.controller.affinity }} affinity: {{ toYaml . | indent 8 }} {{- end }} {{- with .Values.imagePullSecrets }} imagePullSecrets: {{ toYaml . | trimSuffix "\n" | indent 8 }} {{- end }} volumes: - name: certs secret: secretName: {{ required "secret.certs must be provided" .Values.secret.certs }} - name: envdir secret: secretName: {{ required "secret.envdir must be provided" .Values.secret.envdir }} {{- if .Values.secret.configs }} {{- range $module, $secretName := .Values.secret.configs }} - name: {{ $secretName }}-{{ $module }} secret: secretName: {{ $secretName }} {{- end }} {{- else }} - name: "empty-configs" emptyDir: {} {{- end }} containers: - name: {{ $serviceName }} image: {{ required "controller.image.repository must be provided" .Values.controller.image.repository }}:{{ .Values.controller.image.tag }} imagePullPolicy: {{ .Values.controller.image.pullPolicy }} volumeMounts: {{- range tuple "certs" "envdir" }} - name: {{ . }} mountPath: /var/opt/magma/{{ . }} readOnly: true {{- end }} {{- if .Values.secret.configs }} {{- range $module, $secretName := .Values.secret.configs }} - name: {{ $secretName }}-{{ $module }} mountPath: {{ print "/var/opt/magma/configs/" $module }} readOnly: true {{- end }} {{- else }} - name: "empty-configs" mountPath: /var/opt/magma/configs readOnly: true {{- end }} ports: {{- with .Values.controller.service }} - containerPort: {{ .targetPort }} {{- range $_, $port := untilStep (.portStart | int) (.portEnd | add1 | int) 1 }} - containerPort: {{ $port }} {{- end }} {{- end }} env: - name: DATABASE_SOURCE valueFrom: secretKeyRef: name: {{ $serviceName }} key: {{ .Values.controller.spec.database.driver }}.connstr - name: SQL_DRIVER value: {{ .Values.controller.spec.database.driver }} - name: SQL_DIALECT value: {{ .Values.controller.spec.database.sql_dialect }} # Hostname override for dispatcher - name: SERVICE_HOST_NAME valueFrom: fieldRef: fieldPath: status.podIP # Hostname override for metricsd - name: HOST_NAME valueFrom: fieldRef: fieldPath: status.podIP livenessProbe: tcpSocket: port: 9081 initialDelaySeconds: 10 periodSeconds: 30 readinessProbe: tcpSocket: port: 9081 initialDelaySeconds: 5 periodSeconds: 10 resources: {{ toYaml .Values.controller.resources | indent 12 }}
{ "pile_set_name": "Github" }
liTest run started liTest scala.scalanative.junit.MethodNameDecodeTest.abcd$u0020$u2206ƒ$u0020$uD83D$uDE00$u0020$times$u0020$hash$amp$ started ldTest scala.scalanative.junit.MethodNameDecodeTest.abcd$u0020$u2206ƒ$u0020$uD83D$uDE00$u0020$times$u0020$hash$amp$ finished, took <TIME> e01abcd$u0020$u2206ƒ$u0020$uD83D$uDE00$u0020$times$u0020$hash$amp$ liTest run finished: 0 failed, 0 ignored, 1 total, <TIME> d
{ "pile_set_name": "Github" }
// Copyright 2013 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. package spdy // headerDictionary is the dictionary sent to the zlib compressor/decompressor. var headerDictionary = []byte{ 0x00, 0x00, 0x00, 0x07, 0x6f, 0x70, 0x74, 0x69, 0x6f, 0x6e, 0x73, 0x00, 0x00, 0x00, 0x04, 0x68, 0x65, 0x61, 0x64, 0x00, 0x00, 0x00, 0x04, 0x70, 0x6f, 0x73, 0x74, 0x00, 0x00, 0x00, 0x03, 0x70, 0x75, 0x74, 0x00, 0x00, 0x00, 0x06, 0x64, 0x65, 0x6c, 0x65, 0x74, 0x65, 0x00, 0x00, 0x00, 0x05, 0x74, 0x72, 0x61, 0x63, 0x65, 0x00, 0x00, 0x00, 0x06, 0x61, 0x63, 0x63, 0x65, 0x70, 0x74, 0x00, 0x00, 0x00, 0x0e, 0x61, 0x63, 0x63, 0x65, 0x70, 0x74, 0x2d, 0x63, 0x68, 0x61, 0x72, 0x73, 0x65, 0x74, 0x00, 0x00, 0x00, 0x0f, 0x61, 0x63, 0x63, 0x65, 0x70, 0x74, 0x2d, 0x65, 0x6e, 0x63, 0x6f, 0x64, 0x69, 0x6e, 0x67, 0x00, 0x00, 0x00, 0x0f, 0x61, 0x63, 0x63, 0x65, 0x70, 0x74, 0x2d, 0x6c, 0x61, 0x6e, 0x67, 0x75, 0x61, 0x67, 0x65, 0x00, 0x00, 0x00, 0x0d, 0x61, 0x63, 0x63, 0x65, 0x70, 0x74, 0x2d, 0x72, 0x61, 0x6e, 0x67, 0x65, 0x73, 0x00, 0x00, 0x00, 0x03, 0x61, 0x67, 0x65, 0x00, 0x00, 0x00, 0x05, 0x61, 0x6c, 0x6c, 0x6f, 0x77, 0x00, 0x00, 0x00, 0x0d, 0x61, 0x75, 0x74, 0x68, 0x6f, 0x72, 0x69, 0x7a, 0x61, 0x74, 0x69, 0x6f, 0x6e, 0x00, 0x00, 0x00, 0x0d, 0x63, 0x61, 0x63, 0x68, 0x65, 0x2d, 0x63, 0x6f, 0x6e, 0x74, 0x72, 0x6f, 0x6c, 0x00, 0x00, 0x00, 0x0a, 0x63, 0x6f, 0x6e, 0x6e, 0x65, 0x63, 0x74, 0x69, 0x6f, 0x6e, 0x00, 0x00, 0x00, 0x0c, 0x63, 0x6f, 0x6e, 0x74, 0x65, 0x6e, 0x74, 0x2d, 0x62, 0x61, 0x73, 0x65, 0x00, 0x00, 0x00, 0x10, 0x63, 0x6f, 0x6e, 0x74, 0x65, 0x6e, 0x74, 0x2d, 0x65, 0x6e, 0x63, 0x6f, 0x64, 0x69, 0x6e, 0x67, 0x00, 0x00, 0x00, 0x10, 0x63, 0x6f, 0x6e, 0x74, 0x65, 0x6e, 0x74, 0x2d, 0x6c, 0x61, 0x6e, 0x67, 0x75, 0x61, 0x67, 0x65, 0x00, 0x00, 0x00, 0x0e, 0x63, 0x6f, 0x6e, 0x74, 0x65, 0x6e, 0x74, 0x2d, 0x6c, 0x65, 0x6e, 0x67, 0x74, 0x68, 0x00, 0x00, 0x00, 0x10, 0x63, 0x6f, 0x6e, 0x74, 0x65, 0x6e, 0x74, 0x2d, 0x6c, 0x6f, 0x63, 0x61, 0x74, 0x69, 0x6f, 0x6e, 0x00, 0x00, 0x00, 0x0b, 0x63, 0x6f, 0x6e, 0x74, 0x65, 0x6e, 0x74, 0x2d, 0x6d, 0x64, 0x35, 0x00, 0x00, 0x00, 0x0d, 0x63, 0x6f, 0x6e, 0x74, 0x65, 0x6e, 0x74, 0x2d, 0x72, 0x61, 0x6e, 0x67, 0x65, 0x00, 0x00, 0x00, 0x0c, 0x63, 0x6f, 0x6e, 0x74, 0x65, 0x6e, 0x74, 0x2d, 0x74, 0x79, 0x70, 0x65, 0x00, 0x00, 0x00, 0x04, 0x64, 0x61, 0x74, 0x65, 0x00, 0x00, 0x00, 0x04, 0x65, 0x74, 0x61, 0x67, 0x00, 0x00, 0x00, 0x06, 0x65, 0x78, 0x70, 0x65, 0x63, 0x74, 0x00, 0x00, 0x00, 0x07, 0x65, 0x78, 0x70, 0x69, 0x72, 0x65, 0x73, 0x00, 0x00, 0x00, 0x04, 0x66, 0x72, 0x6f, 0x6d, 0x00, 0x00, 0x00, 0x04, 0x68, 0x6f, 0x73, 0x74, 0x00, 0x00, 0x00, 0x08, 0x69, 0x66, 0x2d, 0x6d, 0x61, 0x74, 0x63, 0x68, 0x00, 0x00, 0x00, 0x11, 0x69, 0x66, 0x2d, 0x6d, 0x6f, 0x64, 0x69, 0x66, 0x69, 0x65, 0x64, 0x2d, 0x73, 0x69, 0x6e, 0x63, 0x65, 0x00, 0x00, 0x00, 0x0d, 0x69, 0x66, 0x2d, 0x6e, 0x6f, 0x6e, 0x65, 0x2d, 0x6d, 0x61, 0x74, 0x63, 0x68, 0x00, 0x00, 0x00, 0x08, 0x69, 0x66, 0x2d, 0x72, 0x61, 0x6e, 0x67, 0x65, 0x00, 0x00, 0x00, 0x13, 0x69, 0x66, 0x2d, 0x75, 0x6e, 0x6d, 0x6f, 0x64, 0x69, 0x66, 0x69, 0x65, 0x64, 0x2d, 0x73, 0x69, 0x6e, 0x63, 0x65, 0x00, 0x00, 0x00, 0x0d, 0x6c, 0x61, 0x73, 0x74, 0x2d, 0x6d, 0x6f, 0x64, 0x69, 0x66, 0x69, 0x65, 0x64, 0x00, 0x00, 0x00, 0x08, 0x6c, 0x6f, 0x63, 0x61, 0x74, 0x69, 0x6f, 0x6e, 0x00, 0x00, 0x00, 0x0c, 0x6d, 0x61, 0x78, 0x2d, 0x66, 0x6f, 0x72, 0x77, 0x61, 0x72, 0x64, 0x73, 0x00, 0x00, 0x00, 0x06, 0x70, 0x72, 0x61, 0x67, 0x6d, 0x61, 0x00, 0x00, 0x00, 0x12, 0x70, 0x72, 0x6f, 0x78, 0x79, 0x2d, 0x61, 0x75, 0x74, 0x68, 0x65, 0x6e, 0x74, 0x69, 0x63, 0x61, 0x74, 0x65, 0x00, 0x00, 0x00, 0x13, 0x70, 0x72, 0x6f, 0x78, 0x79, 0x2d, 0x61, 0x75, 0x74, 0x68, 0x6f, 0x72, 0x69, 0x7a, 0x61, 0x74, 0x69, 0x6f, 0x6e, 0x00, 0x00, 0x00, 0x05, 0x72, 0x61, 0x6e, 0x67, 0x65, 0x00, 0x00, 0x00, 0x07, 0x72, 0x65, 0x66, 0x65, 0x72, 0x65, 0x72, 0x00, 0x00, 0x00, 0x0b, 0x72, 0x65, 0x74, 0x72, 0x79, 0x2d, 0x61, 0x66, 0x74, 0x65, 0x72, 0x00, 0x00, 0x00, 0x06, 0x73, 0x65, 0x72, 0x76, 0x65, 0x72, 0x00, 0x00, 0x00, 0x02, 0x74, 0x65, 0x00, 0x00, 0x00, 0x07, 0x74, 0x72, 0x61, 0x69, 0x6c, 0x65, 0x72, 0x00, 0x00, 0x00, 0x11, 0x74, 0x72, 0x61, 0x6e, 0x73, 0x66, 0x65, 0x72, 0x2d, 0x65, 0x6e, 0x63, 0x6f, 0x64, 0x69, 0x6e, 0x67, 0x00, 0x00, 0x00, 0x07, 0x75, 0x70, 0x67, 0x72, 0x61, 0x64, 0x65, 0x00, 0x00, 0x00, 0x0a, 0x75, 0x73, 0x65, 0x72, 0x2d, 0x61, 0x67, 0x65, 0x6e, 0x74, 0x00, 0x00, 0x00, 0x04, 0x76, 0x61, 0x72, 0x79, 0x00, 0x00, 0x00, 0x03, 0x76, 0x69, 0x61, 0x00, 0x00, 0x00, 0x07, 0x77, 0x61, 0x72, 0x6e, 0x69, 0x6e, 0x67, 0x00, 0x00, 0x00, 0x10, 0x77, 0x77, 0x77, 0x2d, 0x61, 0x75, 0x74, 0x68, 0x65, 0x6e, 0x74, 0x69, 0x63, 0x61, 0x74, 0x65, 0x00, 0x00, 0x00, 0x06, 0x6d, 0x65, 0x74, 0x68, 0x6f, 0x64, 0x00, 0x00, 0x00, 0x03, 0x67, 0x65, 0x74, 0x00, 0x00, 0x00, 0x06, 0x73, 0x74, 0x61, 0x74, 0x75, 0x73, 0x00, 0x00, 0x00, 0x06, 0x32, 0x30, 0x30, 0x20, 0x4f, 0x4b, 0x00, 0x00, 0x00, 0x07, 0x76, 0x65, 0x72, 0x73, 0x69, 0x6f, 0x6e, 0x00, 0x00, 0x00, 0x08, 0x48, 0x54, 0x54, 0x50, 0x2f, 0x31, 0x2e, 0x31, 0x00, 0x00, 0x00, 0x03, 0x75, 0x72, 0x6c, 0x00, 0x00, 0x00, 0x06, 0x70, 0x75, 0x62, 0x6c, 0x69, 0x63, 0x00, 0x00, 0x00, 0x0a, 0x73, 0x65, 0x74, 0x2d, 0x63, 0x6f, 0x6f, 0x6b, 0x69, 0x65, 0x00, 0x00, 0x00, 0x0a, 0x6b, 0x65, 0x65, 0x70, 0x2d, 0x61, 0x6c, 0x69, 0x76, 0x65, 0x00, 0x00, 0x00, 0x06, 0x6f, 0x72, 0x69, 0x67, 0x69, 0x6e, 0x31, 0x30, 0x30, 0x31, 0x30, 0x31, 0x32, 0x30, 0x31, 0x32, 0x30, 0x32, 0x32, 0x30, 0x35, 0x32, 0x30, 0x36, 0x33, 0x30, 0x30, 0x33, 0x30, 0x32, 0x33, 0x30, 0x33, 0x33, 0x30, 0x34, 0x33, 0x30, 0x35, 0x33, 0x30, 0x36, 0x33, 0x30, 0x37, 0x34, 0x30, 0x32, 0x34, 0x30, 0x35, 0x34, 0x30, 0x36, 0x34, 0x30, 0x37, 0x34, 0x30, 0x38, 0x34, 0x30, 0x39, 0x34, 0x31, 0x30, 0x34, 0x31, 0x31, 0x34, 0x31, 0x32, 0x34, 0x31, 0x33, 0x34, 0x31, 0x34, 0x34, 0x31, 0x35, 0x34, 0x31, 0x36, 0x34, 0x31, 0x37, 0x35, 0x30, 0x32, 0x35, 0x30, 0x34, 0x35, 0x30, 0x35, 0x32, 0x30, 0x33, 0x20, 0x4e, 0x6f, 0x6e, 0x2d, 0x41, 0x75, 0x74, 0x68, 0x6f, 0x72, 0x69, 0x74, 0x61, 0x74, 0x69, 0x76, 0x65, 0x20, 0x49, 0x6e, 0x66, 0x6f, 0x72, 0x6d, 0x61, 0x74, 0x69, 0x6f, 0x6e, 0x32, 0x30, 0x34, 0x20, 0x4e, 0x6f, 0x20, 0x43, 0x6f, 0x6e, 0x74, 0x65, 0x6e, 0x74, 0x33, 0x30, 0x31, 0x20, 0x4d, 0x6f, 0x76, 0x65, 0x64, 0x20, 0x50, 0x65, 0x72, 0x6d, 0x61, 0x6e, 0x65, 0x6e, 0x74, 0x6c, 0x79, 0x34, 0x30, 0x30, 0x20, 0x42, 0x61, 0x64, 0x20, 0x52, 0x65, 0x71, 0x75, 0x65, 0x73, 0x74, 0x34, 0x30, 0x31, 0x20, 0x55, 0x6e, 0x61, 0x75, 0x74, 0x68, 0x6f, 0x72, 0x69, 0x7a, 0x65, 0x64, 0x34, 0x30, 0x33, 0x20, 0x46, 0x6f, 0x72, 0x62, 0x69, 0x64, 0x64, 0x65, 0x6e, 0x34, 0x30, 0x34, 0x20, 0x4e, 0x6f, 0x74, 0x20, 0x46, 0x6f, 0x75, 0x6e, 0x64, 0x35, 0x30, 0x30, 0x20, 0x49, 0x6e, 0x74, 0x65, 0x72, 0x6e, 0x61, 0x6c, 0x20, 0x53, 0x65, 0x72, 0x76, 0x65, 0x72, 0x20, 0x45, 0x72, 0x72, 0x6f, 0x72, 0x35, 0x30, 0x31, 0x20, 0x4e, 0x6f, 0x74, 0x20, 0x49, 0x6d, 0x70, 0x6c, 0x65, 0x6d, 0x65, 0x6e, 0x74, 0x65, 0x64, 0x35, 0x30, 0x33, 0x20, 0x53, 0x65, 0x72, 0x76, 0x69, 0x63, 0x65, 0x20, 0x55, 0x6e, 0x61, 0x76, 0x61, 0x69, 0x6c, 0x61, 0x62, 0x6c, 0x65, 0x4a, 0x61, 0x6e, 0x20, 0x46, 0x65, 0x62, 0x20, 0x4d, 0x61, 0x72, 0x20, 0x41, 0x70, 0x72, 0x20, 0x4d, 0x61, 0x79, 0x20, 0x4a, 0x75, 0x6e, 0x20, 0x4a, 0x75, 0x6c, 0x20, 0x41, 0x75, 0x67, 0x20, 0x53, 0x65, 0x70, 0x74, 0x20, 0x4f, 0x63, 0x74, 0x20, 0x4e, 0x6f, 0x76, 0x20, 0x44, 0x65, 0x63, 0x20, 0x30, 0x30, 0x3a, 0x30, 0x30, 0x3a, 0x30, 0x30, 0x20, 0x4d, 0x6f, 0x6e, 0x2c, 0x20, 0x54, 0x75, 0x65, 0x2c, 0x20, 0x57, 0x65, 0x64, 0x2c, 0x20, 0x54, 0x68, 0x75, 0x2c, 0x20, 0x46, 0x72, 0x69, 0x2c, 0x20, 0x53, 0x61, 0x74, 0x2c, 0x20, 0x53, 0x75, 0x6e, 0x2c, 0x20, 0x47, 0x4d, 0x54, 0x63, 0x68, 0x75, 0x6e, 0x6b, 0x65, 0x64, 0x2c, 0x74, 0x65, 0x78, 0x74, 0x2f, 0x68, 0x74, 0x6d, 0x6c, 0x2c, 0x69, 0x6d, 0x61, 0x67, 0x65, 0x2f, 0x70, 0x6e, 0x67, 0x2c, 0x69, 0x6d, 0x61, 0x67, 0x65, 0x2f, 0x6a, 0x70, 0x67, 0x2c, 0x69, 0x6d, 0x61, 0x67, 0x65, 0x2f, 0x67, 0x69, 0x66, 0x2c, 0x61, 0x70, 0x70, 0x6c, 0x69, 0x63, 0x61, 0x74, 0x69, 0x6f, 0x6e, 0x2f, 0x78, 0x6d, 0x6c, 0x2c, 0x61, 0x70, 0x70, 0x6c, 0x69, 0x63, 0x61, 0x74, 0x69, 0x6f, 0x6e, 0x2f, 0x78, 0x68, 0x74, 0x6d, 0x6c, 0x2b, 0x78, 0x6d, 0x6c, 0x2c, 0x74, 0x65, 0x78, 0x74, 0x2f, 0x70, 0x6c, 0x61, 0x69, 0x6e, 0x2c, 0x74, 0x65, 0x78, 0x74, 0x2f, 0x6a, 0x61, 0x76, 0x61, 0x73, 0x63, 0x72, 0x69, 0x70, 0x74, 0x2c, 0x70, 0x75, 0x62, 0x6c, 0x69, 0x63, 0x70, 0x72, 0x69, 0x76, 0x61, 0x74, 0x65, 0x6d, 0x61, 0x78, 0x2d, 0x61, 0x67, 0x65, 0x3d, 0x67, 0x7a, 0x69, 0x70, 0x2c, 0x64, 0x65, 0x66, 0x6c, 0x61, 0x74, 0x65, 0x2c, 0x73, 0x64, 0x63, 0x68, 0x63, 0x68, 0x61, 0x72, 0x73, 0x65, 0x74, 0x3d, 0x75, 0x74, 0x66, 0x2d, 0x38, 0x63, 0x68, 0x61, 0x72, 0x73, 0x65, 0x74, 0x3d, 0x69, 0x73, 0x6f, 0x2d, 0x38, 0x38, 0x35, 0x39, 0x2d, 0x31, 0x2c, 0x75, 0x74, 0x66, 0x2d, 0x2c, 0x2a, 0x2c, 0x65, 0x6e, 0x71, 0x3d, 0x30, 0x2e, }
{ "pile_set_name": "Github" }
{ "_from": "isstream@~0.1.2", "_id": "isstream@0.1.2", "_inBundle": false, "_integrity": "sha1-R+Y/evVa+m+S4VAOaQ64uFKcCZo=", "_location": "/isstream", "_phantomChildren": {}, "_requested": { "type": "range", "registry": true, "raw": "isstream@~0.1.2", "name": "isstream", "escapedName": "isstream", "rawSpec": "~0.1.2", "saveSpec": null, "fetchSpec": "~0.1.2" }, "_requiredBy": [ "/request" ], "_resolved": "https://registry.npmjs.org/isstream/-/isstream-0.1.2.tgz", "_shasum": "47e63f7af55afa6f92e1500e690eb8b8529c099a", "_spec": "isstream@~0.1.2", "_where": "/Users/rhwood/Developer/JMRI/JMRI/rhwood/JMRI/web/app/node_modules/request", "author": { "name": "Rod Vagg", "email": "rod@vagg.org" }, "bugs": { "url": "https://github.com/rvagg/isstream/issues" }, "bundleDependencies": false, "deprecated": false, "description": "Determine if an object is a Stream", "devDependencies": { "core-util-is": "~1.0.0", "inherits": "~2.0.1", "isarray": "0.0.1", "string_decoder": "~0.10.x", "tape": "~2.12.3" }, "homepage": "https://github.com/rvagg/isstream", "keywords": [ "stream", "type", "streams", "readable-stream", "hippo" ], "license": "MIT", "main": "isstream.js", "name": "isstream", "repository": { "type": "git", "url": "git+https://github.com/rvagg/isstream.git" }, "scripts": { "test": "tar --xform 's/^package/readable-stream-1.0/' -zxf readable-stream-1.0.*.tgz && tar --xform 's/^package/readable-stream-1.1/' -zxf readable-stream-1.1.*.tgz && node test.js; rm -rf readable-stream-1.?/" }, "version": "0.1.2" }
{ "pile_set_name": "Github" }
/* LibTomCrypt, modular cryptographic library -- Tom St Denis * * LibTomCrypt is a library that provides various cryptographic * algorithms in a highly modular and flexible manner. * * The library is free for all purposes without any express * guarantee it works. * * Tom St Denis, tomstdenis@gmail.com, http://libtom.org */ #include "../../headers/tomcrypt.h" /** @file der_decode_integer.c ASN.1 DER, decode an integer, Tom St Denis */ #ifdef LTC_DER /** Read a mp_int integer @param in The DER encoded data @param inlen Size of DER encoded data @param num The first mp_int to decode @return CRYPT_OK if successful */ int der_decode_integer(const unsigned char *in, unsigned long inlen, void *num) { unsigned long x, y, z; int err; LTC_ARGCHK(num != NULL); LTC_ARGCHK(in != NULL); /* min DER INTEGER is 0x02 01 00 == 0 */ if (inlen < (1 + 1 + 1)) { return CRYPT_INVALID_PACKET; } /* ok expect 0x02 when we AND with 0001 1111 [1F] */ x = 0; if ((in[x++] & 0x1F) != 0x02) { return CRYPT_INVALID_PACKET; } /* now decode the len stuff */ z = in[x++]; if ((z & 0x80) == 0x00) { /* short form */ /* will it overflow? */ if (x + z > inlen) { return CRYPT_INVALID_PACKET; } /* no so read it */ if ((err = mp_read_unsigned_bin(num, (unsigned char *)in + x, z)) != CRYPT_OK) { return err; } } else { /* long form */ z &= 0x7F; /* will number of length bytes overflow? (or > 4) */ if (((x + z) > inlen) || (z > 4) || (z == 0)) { return CRYPT_INVALID_PACKET; } /* now read it in */ y = 0; while (z--) { y = ((unsigned long)(in[x++])) | (y << 8); } /* now will reading y bytes overrun? */ if ((x + y) > inlen) { return CRYPT_INVALID_PACKET; } /* no so read it */ if ((err = mp_read_unsigned_bin(num, (unsigned char *)in + x, y)) != CRYPT_OK) { return err; } } /* see if it's negative */ if (in[x] & 0x80) { void *tmp; if (mp_init(&tmp) != CRYPT_OK) { return CRYPT_MEM; } if (mp_2expt(tmp, mp_count_bits(num)) != CRYPT_OK || mp_sub(num, tmp, num) != CRYPT_OK) { mp_clear(tmp); return CRYPT_MEM; } mp_clear(tmp); } return CRYPT_OK; } #endif /* $Source: /cvs/libtom/libtomcrypt/src/pk/asn1/der/integer/der_decode_integer.c,v $ */ /* $Revision: 1.5 $ */ /* $Date: 2006/12/28 01:27:24 $ */
{ "pile_set_name": "Github" }
#!/usr/bin/env ruby require File.dirname(__FILE__) + '/../../config/boot' require 'commands/performance/request'
{ "pile_set_name": "Github" }
/** * Created by martin on 19.02.2017. */ import * as path from 'path'; let pkg = null; try { pkg = require(path.resolve(__dirname, '..', 'package.json')); } catch (e) { try { pkg = require(path.resolve(__dirname, '..', '..', 'package.json')); } catch (e) { pkg = null; } } export const VERSION = (pkg ? pkg.version : 'unknown');
{ "pile_set_name": "Github" }
'use strict'; var Promise = require('sporks/scripts/promise'), sporks = require('sporks'); var Config = function (slouch) { this._slouch = slouch; }; Config.prototype._couchDB2Request = function (node, path, opts, parseBody) { opts.uri = this._slouch._url + '/_node/' + node + '/_config/' + path; opts.parseBody = parseBody; return this._slouch._req(opts); }; // Warning: as per https://github.com/klaemo/docker-couchdb/issues/42#issuecomment-169610897, this // isn't really the best approach as a more complete solution would implement some rollback // mechanism when a node fails after several attempts. (Retries are already attempted by the // request). Config.prototype._couchDB2Requests = function (path, opts, parseBody, maxNumNodes) { var self = this, promises = [], i = 0; return self._slouch.membership.get().then(function (members) { members.cluster_nodes.forEach(function (node) { if (typeof maxNumNodes === 'undefined' || i++ < maxNumNodes) { // Clone the opts as we need a separate copy per node var clonedOpts = sporks.clone(opts); promises.push(self._couchDB2Request(node, path, clonedOpts, parseBody)); } }); // Only return a single promise when there is a single promise so that the return value // is consistent for a single node. return promises.length > 1 ? Promise.all(promises) : promises[0]; }); }; Config.prototype._couchDB1Request = function (path, opts, parseBody) { opts.uri = this._slouch._url + '/_config/' + path; opts.parseBody = parseBody; return this._slouch._req(opts); }; Config.prototype._request = function (path, opts, parseBody, maxNumNodes) { var self = this; return self._slouch.system.isCouchDB1().then(function (isCouchDB1) { if (isCouchDB1) { return self._couchDB1Request(path, opts, parseBody); } else { return self._couchDB2Requests(path, opts, parseBody, maxNumNodes); } }); }; Config.prototype.get = function (path) { return this._request(path, { method: 'GET' }, true); }; Config.prototype.set = function (path, value) { return this._request(path, { method: 'PUT', body: JSON.stringify(this._toString(value)) }); }; Config.prototype.unset = function (path) { return this._request(path, { method: 'DELETE' }); }; Config.prototype.unsetIgnoreMissing = function (path) { var self = this; return self._slouch.doc.ignoreMissing(function () { return self.unset(path); }); }; Config.prototype.setCouchHttpdAuthTimeout = function (timeoutSecs) { // Convert timeout value to a string return this.set('couch_httpd_auth/timeout', timeoutSecs + ''); }; Config.prototype._toString = function (value) { if (typeof value === 'boolean') { return value ? 'true' : 'false'; } else if (typeof value === 'string') { return value; } else { return value + ''; // convert to string } }; Config.prototype.setCouchHttpdAuthAllowPersistentCookies = function (allow) { return this.set('couch_httpd_auth/allow_persistent_cookies', allow); }; Config.prototype.setLogLevel = function (level) { return this.set('log/level', level); }; Config.prototype.setCompactionRule = function (dbName, rule) { return this.set('compactions/' + encodeURIComponent(dbName), rule); }; Config.prototype.setCouchDBMaxDBsOpen = function (maxDBsOpen) { return this.set('couchdb/max_dbs_open', maxDBsOpen); }; Config.prototype.setHttpdMaxConnections = function (maxConnections) { return this.set('httpd/max_connections', maxConnections); }; module.exports = Config;
{ "pile_set_name": "Github" }
/* * Copyright (C) 2009 The Android Open Source 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.xyoye.player.danmaku.danmaku.model.objectpool; public interface PoolableManager<T extends Poolable<T>> { T newInstance(); void onAcquired(T element); void onReleased(T element); }
{ "pile_set_name": "Github" }
<?php /** * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ namespace Magento\Framework\DB\Sql; /** * Class LimitExpression */ class LimitExpression extends Expression { /** * @var string */ protected $sql; /** * @var int */ protected $count; /** * @var int */ protected $offset; /** * @param string $sql * @param int $count * @param int $offset */ public function __construct( $sql, $count, $offset = 0 ) { $this->sql = $sql; $this->count = $count; $this->offset = $offset; } /** * @inheritdoc */ public function __toString() { $sql = $this->sql; $count = (int)$this->count; if ($count <= 0) { /** @see Zend_Db_Adapter_Exception */ #require_once 'Zend/Db/Adapter/Exception.php'; throw new \Zend_Db_Adapter_Exception("LIMIT argument count=$count is not valid"); } $offset = (int)$this->offset; if ($offset < 0) { /** @see Zend_Db_Adapter_Exception */ #require_once 'Zend/Db/Adapter/Exception.php'; throw new \Zend_Db_Adapter_Exception("LIMIT argument offset=$offset is not valid"); } $sql .= " LIMIT $count"; if ($offset > 0) { $sql .= " OFFSET $offset"; } return trim($sql); } }
{ "pile_set_name": "Github" }
Ethereum入門 ============= [Ethereum入門](http://book.ethereum-jp.net)は、分散アプリケーションプラットフォーム「Ethereum(イーサリアム)」の技術入門書です。 Ethereumがどのように動作するのか、Ethereumを用いてどのように分散アプリケーションを開発していくか、について解説していきます。 Ethereumプロジェクトは最初の安定版(Homestead)リリースがされましたが、今後仕様が変更になる場合があります。仕様変更に伴い本書も逐次内容を変更していきます。 また本ドキュメントは**2018/3/10 現在、制作中です。** 本ドキュメントはオープンなプロジェクトであり、そのため協力者を広く求めています。本書のソースコードは[GitHub上](https://github.com/a-mitani/mastering-ethereum)で公開されています。 本書への追記や修正などありましたら、上記[GitHub](https://github.com/a-mitani/mastering-ethereum)にてIssueの発行、またはPull requestをお願いいたします。 本ドキュメントは <a rel="license" href="http://creativecommons.org/licenses/by-sa/4.0/">Creative Commons Attribution-ShareAlike 4.0 International License</a> のもとで公開されています。 <a rel="license" href="http://creativecommons.org/licenses/by-sa/4.0/"><img alt="Creative Commons License" style="border-width:0" src="https://i.creativecommons.org/l/by-sa/4.0/88x31.png" /></a><br />
{ "pile_set_name": "Github" }
### 更新时间Updated Updated可以让您在记录插入或每次记录更新时自动更新数据库中的标记字段为当前时间,需要在xorm标记中使用updated标记,如下所示进行标记,对应的字段可以为time.Time或者自定义的time.Time或者int,int64等int类型。 ```Go type User struct { Id int64 Name string UpdatedAt time.Time `xorm:"updated"` } ``` 在Insert(), InsertOne(), Update()方法被调用时,updated标记的字段将会被自动更新为当前时间,如下所示: ```Go var user User engine.Id(1).Get(&user) // SELECT * FROM user WHERE id = ? engine.Id(1).Update(&user) // UPDATE user SET ..., updaetd_at = ? WHERE id = ? ``` 如果你希望临时不自动插入时间,则可以组合NoAutoTime()方法: ```Go engine.NoAutoTime().Insert(&user) ``` 这个在从一张表拷贝字段到另一张表时比较有用。
{ "pile_set_name": "Github" }
#ifndef __PMU_H #define __PMU_H #include <linux/bitops.h> #include "../../../include/linux/perf_event.h" enum { PERF_PMU_FORMAT_VALUE_CONFIG, PERF_PMU_FORMAT_VALUE_CONFIG1, PERF_PMU_FORMAT_VALUE_CONFIG2, }; #define PERF_PMU_FORMAT_BITS 64 struct perf_pmu__format { char *name; int value; DECLARE_BITMAP(bits, PERF_PMU_FORMAT_BITS); struct list_head list; }; struct perf_pmu { char *name; __u32 type; struct list_head format; struct list_head list; }; struct perf_pmu *perf_pmu__find(char *name); int perf_pmu__config(struct perf_pmu *pmu, struct perf_event_attr *attr, struct list_head *head_terms); int perf_pmu_wrap(void); void perf_pmu_error(struct list_head *list, char *name, char const *msg); int perf_pmu__new_format(struct list_head *list, char *name, int config, unsigned long *bits); void perf_pmu__set_format(unsigned long *bits, long from, long to); int perf_pmu__test(void); #endif /* __PMU_H */
{ "pile_set_name": "Github" }
#!/usr/bin/python # # Copyright 2018-2020 Polyaxon, 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. # coding: utf-8 """ Polyaxon SDKs and REST API specification. Polyaxon SDKs and REST API specification. # noqa: E501 The version of the OpenAPI document: 1.1.9-rc4 Contact: contact@polyaxon.com Generated by: https://openapi-generator.tech """ import pprint import re # noqa: F401 import six from polyaxon_sdk.configuration import Configuration class V1Queue(object): """NOTE: This class is auto generated by OpenAPI Generator. Ref: https://openapi-generator.tech Do not edit the class manually. """ """ Attributes: openapi_types (dict): The key is attribute name and the value is attribute type. attribute_map (dict): The key is attribute name and the value is json key in definition. """ openapi_types = { "uuid": "str", "agent": "str", "name": "str", "description": "str", "tags": "list[str]", "priority": "int", "concurrency": "int", "created_at": "datetime", "updated_at": "datetime", } attribute_map = { "uuid": "uuid", "agent": "agent", "name": "name", "description": "description", "tags": "tags", "priority": "priority", "concurrency": "concurrency", "created_at": "created_at", "updated_at": "updated_at", } def __init__( self, uuid=None, agent=None, name=None, description=None, tags=None, priority=None, concurrency=None, created_at=None, updated_at=None, local_vars_configuration=None, ): # noqa: E501 """V1Queue - a model defined in OpenAPI""" # noqa: E501 if local_vars_configuration is None: local_vars_configuration = Configuration() self.local_vars_configuration = local_vars_configuration self._uuid = None self._agent = None self._name = None self._description = None self._tags = None self._priority = None self._concurrency = None self._created_at = None self._updated_at = None self.discriminator = None if uuid is not None: self.uuid = uuid if agent is not None: self.agent = agent if name is not None: self.name = name if description is not None: self.description = description if tags is not None: self.tags = tags if priority is not None: self.priority = priority if concurrency is not None: self.concurrency = concurrency if created_at is not None: self.created_at = created_at if updated_at is not None: self.updated_at = updated_at @property def uuid(self): """Gets the uuid of this V1Queue. # noqa: E501 :return: The uuid of this V1Queue. # noqa: E501 :rtype: str """ return self._uuid @uuid.setter def uuid(self, uuid): """Sets the uuid of this V1Queue. :param uuid: The uuid of this V1Queue. # noqa: E501 :type: str """ self._uuid = uuid @property def agent(self): """Gets the agent of this V1Queue. # noqa: E501 :return: The agent of this V1Queue. # noqa: E501 :rtype: str """ return self._agent @agent.setter def agent(self, agent): """Sets the agent of this V1Queue. :param agent: The agent of this V1Queue. # noqa: E501 :type: str """ self._agent = agent @property def name(self): """Gets the name of this V1Queue. # noqa: E501 :return: The name of this V1Queue. # noqa: E501 :rtype: str """ return self._name @name.setter def name(self, name): """Sets the name of this V1Queue. :param name: The name of this V1Queue. # noqa: E501 :type: str """ self._name = name @property def description(self): """Gets the description of this V1Queue. # noqa: E501 :return: The description of this V1Queue. # noqa: E501 :rtype: str """ return self._description @description.setter def description(self, description): """Sets the description of this V1Queue. :param description: The description of this V1Queue. # noqa: E501 :type: str """ self._description = description @property def tags(self): """Gets the tags of this V1Queue. # noqa: E501 :return: The tags of this V1Queue. # noqa: E501 :rtype: list[str] """ return self._tags @tags.setter def tags(self, tags): """Sets the tags of this V1Queue. :param tags: The tags of this V1Queue. # noqa: E501 :type: list[str] """ self._tags = tags @property def priority(self): """Gets the priority of this V1Queue. # noqa: E501 :return: The priority of this V1Queue. # noqa: E501 :rtype: int """ return self._priority @priority.setter def priority(self, priority): """Sets the priority of this V1Queue. :param priority: The priority of this V1Queue. # noqa: E501 :type: int """ self._priority = priority @property def concurrency(self): """Gets the concurrency of this V1Queue. # noqa: E501 :return: The concurrency of this V1Queue. # noqa: E501 :rtype: int """ return self._concurrency @concurrency.setter def concurrency(self, concurrency): """Sets the concurrency of this V1Queue. :param concurrency: The concurrency of this V1Queue. # noqa: E501 :type: int """ self._concurrency = concurrency @property def created_at(self): """Gets the created_at of this V1Queue. # noqa: E501 :return: The created_at of this V1Queue. # noqa: E501 :rtype: datetime """ return self._created_at @created_at.setter def created_at(self, created_at): """Sets the created_at of this V1Queue. :param created_at: The created_at of this V1Queue. # noqa: E501 :type: datetime """ self._created_at = created_at @property def updated_at(self): """Gets the updated_at of this V1Queue. # noqa: E501 :return: The updated_at of this V1Queue. # noqa: E501 :rtype: datetime """ return self._updated_at @updated_at.setter def updated_at(self, updated_at): """Sets the updated_at of this V1Queue. :param updated_at: The updated_at of this V1Queue. # noqa: E501 :type: datetime """ self._updated_at = updated_at def to_dict(self): """Returns the model properties as a dict""" result = {} for attr, _ in six.iteritems(self.openapi_types): value = getattr(self, attr) if isinstance(value, list): result[attr] = list( map(lambda x: x.to_dict() if hasattr(x, "to_dict") else x, value) ) elif hasattr(value, "to_dict"): result[attr] = value.to_dict() elif isinstance(value, dict): result[attr] = dict( map( lambda item: (item[0], item[1].to_dict()) if hasattr(item[1], "to_dict") else item, value.items(), ) ) else: result[attr] = value return result def to_str(self): """Returns the string representation of the model""" return pprint.pformat(self.to_dict()) def __repr__(self): """For `print` and `pprint`""" return self.to_str() def __eq__(self, other): """Returns true if both objects are equal""" if not isinstance(other, V1Queue): return False return self.to_dict() == other.to_dict() def __ne__(self, other): """Returns true if both objects are not equal""" if not isinstance(other, V1Queue): return True return self.to_dict() != other.to_dict()
{ "pile_set_name": "Github" }
package webrtc const ( // Unknown defines default public constant to use for "enum" like struct // comparisons when no value was defined. Unknown = iota unknownStr = "unknown" ssrcStr = "ssrc" receiveMTU = 8192 )
{ "pile_set_name": "Github" }
<!-- YAML added: v0.1.97 changes: - version: v10.0.0 pr-url: https://github.com/nodejs/node/pull/12562 description: 参数 `callback` 不再是可选的。 如果不传入,则在运行时会抛出 `TypeError`。 - version: v7.6.0 pr-url: https://github.com/nodejs/node/pull/10739 description: 参数 `path` 可以是 WHATWG `URL` 对象(使用 `file:` 协议)。 该支持目前仍是实验的。 - version: v7.0.0 pr-url: https://github.com/nodejs/node/pull/7897 description: 参数 `callback` 不再是可选的。 如果不传入,则会触发弃用警告(id 为 DEP0013)。 --> * `path` {string|Buffer|URL} * `uid` {integer} * `gid` {integer} * `callback` {Function} * `err` {Error} 异步地更改文件的所有者和群组。 除了可能的异常,完成回调没有其他参数。 也可参见 chown(2)。
{ "pile_set_name": "Github" }
box: yosssi/golang-latest@1.0.9 # Build definition build: # The steps that will be executed on build steps: # Sets the go workspace and places you package # at the right place in the workspace tree - setup-go-workspace # Gets the dependencies - script: name: go get code: | cd $WERCKER_SOURCE_DIR go version go get -t ./... # Build the project - script: name: go build code: | go build ./... # Test the project - script: name: go test code: | packages=(cmd/gmq-cli mqtt mqtt/client mqtt/packet) for package in ${packages[@]}; do go test -v -cover -race ./$package; done # Invoke goveralls - script: name: goveralls code: | go get github.com/axw/gocov/gocov go get github.com/mattn/goveralls echo "mode: count" > all.cov for package in ${packages[@]}; do go test --covermode=count -coverprofile=$package.cov ./$package; sed -e "1d" $package.cov >> all.cov; done GIT_BRANCH=$WERCKER_GIT_BRANCH goveralls -coverprofile=all.cov -service=wercker.com -repotoken $COVERALLS_REPO_TOKEN
{ "pile_set_name": "Github" }
/* * Driver for audio on multifunction CS5535/6 companion device * Copyright (C) Jaya Kumar * * Based on Jaroslav Kysela and Takashi Iwai's examples. * This work was sponsored by CIS(M) Sdn Bhd. * * 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, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA * */ #include <linux/delay.h> #include <linux/interrupt.h> #include <linux/init.h> #include <linux/pci.h> #include <linux/slab.h> #include <linux/module.h> #include <linux/io.h> #include <sound/core.h> #include <sound/control.h> #include <sound/pcm.h> #include <sound/rawmidi.h> #include <sound/ac97_codec.h> #include <sound/initval.h> #include <sound/asoundef.h> #include "cs5535audio.h" #define DRIVER_NAME "cs5535audio" static char *ac97_quirk; module_param(ac97_quirk, charp, 0444); MODULE_PARM_DESC(ac97_quirk, "AC'97 board specific workarounds."); static const struct ac97_quirk ac97_quirks[] = { #if 0 /* Not yet confirmed if all 5536 boards are HP only */ { .subvendor = PCI_VENDOR_ID_AMD, .subdevice = PCI_DEVICE_ID_AMD_CS5536_AUDIO, .name = "AMD RDK", .type = AC97_TUNE_HP_ONLY }, #endif {} }; static int index[SNDRV_CARDS] = SNDRV_DEFAULT_IDX; static char *id[SNDRV_CARDS] = SNDRV_DEFAULT_STR; static bool enable[SNDRV_CARDS] = SNDRV_DEFAULT_ENABLE_PNP; module_param_array(index, int, NULL, 0444); MODULE_PARM_DESC(index, "Index value for " DRIVER_NAME); module_param_array(id, charp, NULL, 0444); MODULE_PARM_DESC(id, "ID string for " DRIVER_NAME); module_param_array(enable, bool, NULL, 0444); MODULE_PARM_DESC(enable, "Enable " DRIVER_NAME); static const struct pci_device_id snd_cs5535audio_ids[] = { { PCI_DEVICE(PCI_VENDOR_ID_NS, PCI_DEVICE_ID_NS_CS5535_AUDIO) }, { PCI_DEVICE(PCI_VENDOR_ID_AMD, PCI_DEVICE_ID_AMD_CS5536_AUDIO) }, {} }; MODULE_DEVICE_TABLE(pci, snd_cs5535audio_ids); static void wait_till_cmd_acked(struct cs5535audio *cs5535au, unsigned long timeout) { unsigned int tmp; do { tmp = cs_readl(cs5535au, ACC_CODEC_CNTL); if (!(tmp & CMD_NEW)) break; udelay(1); } while (--timeout); if (!timeout) dev_err(cs5535au->card->dev, "Failure writing to cs5535 codec\n"); } static unsigned short snd_cs5535audio_codec_read(struct cs5535audio *cs5535au, unsigned short reg) { unsigned int regdata; unsigned int timeout; unsigned int val; regdata = ((unsigned int) reg) << 24; regdata |= ACC_CODEC_CNTL_RD_CMD; regdata |= CMD_NEW; cs_writel(cs5535au, ACC_CODEC_CNTL, regdata); wait_till_cmd_acked(cs5535au, 50); timeout = 50; do { val = cs_readl(cs5535au, ACC_CODEC_STATUS); if ((val & STS_NEW) && reg == (val >> 24)) break; udelay(1); } while (--timeout); if (!timeout) dev_err(cs5535au->card->dev, "Failure reading codec reg 0x%x, Last value=0x%x\n", reg, val); return (unsigned short) val; } static void snd_cs5535audio_codec_write(struct cs5535audio *cs5535au, unsigned short reg, unsigned short val) { unsigned int regdata; regdata = ((unsigned int) reg) << 24; regdata |= val; regdata &= CMD_MASK; regdata |= CMD_NEW; regdata &= ACC_CODEC_CNTL_WR_CMD; cs_writel(cs5535au, ACC_CODEC_CNTL, regdata); wait_till_cmd_acked(cs5535au, 50); } static void snd_cs5535audio_ac97_codec_write(struct snd_ac97 *ac97, unsigned short reg, unsigned short val) { struct cs5535audio *cs5535au = ac97->private_data; snd_cs5535audio_codec_write(cs5535au, reg, val); } static unsigned short snd_cs5535audio_ac97_codec_read(struct snd_ac97 *ac97, unsigned short reg) { struct cs5535audio *cs5535au = ac97->private_data; return snd_cs5535audio_codec_read(cs5535au, reg); } static int snd_cs5535audio_mixer(struct cs5535audio *cs5535au) { struct snd_card *card = cs5535au->card; struct snd_ac97_bus *pbus; struct snd_ac97_template ac97; int err; static struct snd_ac97_bus_ops ops = { .write = snd_cs5535audio_ac97_codec_write, .read = snd_cs5535audio_ac97_codec_read, }; if ((err = snd_ac97_bus(card, 0, &ops, NULL, &pbus)) < 0) return err; memset(&ac97, 0, sizeof(ac97)); ac97.scaps = AC97_SCAP_AUDIO | AC97_SCAP_SKIP_MODEM | AC97_SCAP_POWER_SAVE; ac97.private_data = cs5535au; ac97.pci = cs5535au->pci; /* set any OLPC-specific scaps */ olpc_prequirks(card, &ac97); if ((err = snd_ac97_mixer(pbus, &ac97, &cs5535au->ac97)) < 0) { dev_err(card->dev, "mixer failed\n"); return err; } snd_ac97_tune_hardware(cs5535au->ac97, ac97_quirks, ac97_quirk); err = olpc_quirks(card, cs5535au->ac97); if (err < 0) { dev_err(card->dev, "olpc quirks failed\n"); return err; } return 0; } static void process_bm0_irq(struct cs5535audio *cs5535au) { u8 bm_stat; spin_lock(&cs5535au->reg_lock); bm_stat = cs_readb(cs5535au, ACC_BM0_STATUS); spin_unlock(&cs5535au->reg_lock); if (bm_stat & EOP) { struct cs5535audio_dma *dma; dma = cs5535au->playback_substream->runtime->private_data; snd_pcm_period_elapsed(cs5535au->playback_substream); } else { dev_err(cs5535au->card->dev, "unexpected bm0 irq src, bm_stat=%x\n", bm_stat); } } static void process_bm1_irq(struct cs5535audio *cs5535au) { u8 bm_stat; spin_lock(&cs5535au->reg_lock); bm_stat = cs_readb(cs5535au, ACC_BM1_STATUS); spin_unlock(&cs5535au->reg_lock); if (bm_stat & EOP) { struct cs5535audio_dma *dma; dma = cs5535au->capture_substream->runtime->private_data; snd_pcm_period_elapsed(cs5535au->capture_substream); } } static irqreturn_t snd_cs5535audio_interrupt(int irq, void *dev_id) { u16 acc_irq_stat; unsigned char count; struct cs5535audio *cs5535au = dev_id; if (cs5535au == NULL) return IRQ_NONE; acc_irq_stat = cs_readw(cs5535au, ACC_IRQ_STATUS); if (!acc_irq_stat) return IRQ_NONE; for (count = 0; count < 4; count++) { if (acc_irq_stat & (1 << count)) { switch (count) { case IRQ_STS: cs_readl(cs5535au, ACC_GPIO_STATUS); break; case WU_IRQ_STS: cs_readl(cs5535au, ACC_GPIO_STATUS); break; case BM0_IRQ_STS: process_bm0_irq(cs5535au); break; case BM1_IRQ_STS: process_bm1_irq(cs5535au); break; default: dev_err(cs5535au->card->dev, "Unexpected irq src: 0x%x\n", acc_irq_stat); break; } } } return IRQ_HANDLED; } static int snd_cs5535audio_free(struct cs5535audio *cs5535au) { synchronize_irq(cs5535au->irq); pci_set_power_state(cs5535au->pci, PCI_D3hot); if (cs5535au->irq >= 0) free_irq(cs5535au->irq, cs5535au); pci_release_regions(cs5535au->pci); pci_disable_device(cs5535au->pci); kfree(cs5535au); return 0; } static int snd_cs5535audio_dev_free(struct snd_device *device) { struct cs5535audio *cs5535au = device->device_data; return snd_cs5535audio_free(cs5535au); } static int snd_cs5535audio_create(struct snd_card *card, struct pci_dev *pci, struct cs5535audio **rcs5535au) { struct cs5535audio *cs5535au; int err; static struct snd_device_ops ops = { .dev_free = snd_cs5535audio_dev_free, }; *rcs5535au = NULL; if ((err = pci_enable_device(pci)) < 0) return err; if (dma_set_mask(&pci->dev, DMA_BIT_MASK(32)) < 0 || dma_set_coherent_mask(&pci->dev, DMA_BIT_MASK(32)) < 0) { dev_warn(card->dev, "unable to get 32bit dma\n"); err = -ENXIO; goto pcifail; } cs5535au = kzalloc(sizeof(*cs5535au), GFP_KERNEL); if (cs5535au == NULL) { err = -ENOMEM; goto pcifail; } spin_lock_init(&cs5535au->reg_lock); cs5535au->card = card; cs5535au->pci = pci; cs5535au->irq = -1; if ((err = pci_request_regions(pci, "CS5535 Audio")) < 0) { kfree(cs5535au); goto pcifail; } cs5535au->port = pci_resource_start(pci, 0); if (request_irq(pci->irq, snd_cs5535audio_interrupt, IRQF_SHARED, KBUILD_MODNAME, cs5535au)) { dev_err(card->dev, "unable to grab IRQ %d\n", pci->irq); err = -EBUSY; goto sndfail; } cs5535au->irq = pci->irq; pci_set_master(pci); if ((err = snd_device_new(card, SNDRV_DEV_LOWLEVEL, cs5535au, &ops)) < 0) goto sndfail; *rcs5535au = cs5535au; return 0; sndfail: /* leave the device alive, just kill the snd */ snd_cs5535audio_free(cs5535au); return err; pcifail: pci_disable_device(pci); return err; } static int snd_cs5535audio_probe(struct pci_dev *pci, const struct pci_device_id *pci_id) { static int dev; struct snd_card *card; struct cs5535audio *cs5535au; int err; if (dev >= SNDRV_CARDS) return -ENODEV; if (!enable[dev]) { dev++; return -ENOENT; } err = snd_card_new(&pci->dev, index[dev], id[dev], THIS_MODULE, 0, &card); if (err < 0) return err; if ((err = snd_cs5535audio_create(card, pci, &cs5535au)) < 0) goto probefail_out; card->private_data = cs5535au; if ((err = snd_cs5535audio_mixer(cs5535au)) < 0) goto probefail_out; if ((err = snd_cs5535audio_pcm(cs5535au)) < 0) goto probefail_out; strcpy(card->driver, DRIVER_NAME); strcpy(card->shortname, "CS5535 Audio"); sprintf(card->longname, "%s %s at 0x%lx, irq %i", card->shortname, card->driver, cs5535au->port, cs5535au->irq); if ((err = snd_card_register(card)) < 0) goto probefail_out; pci_set_drvdata(pci, card); dev++; return 0; probefail_out: snd_card_free(card); return err; } static void snd_cs5535audio_remove(struct pci_dev *pci) { olpc_quirks_cleanup(); snd_card_free(pci_get_drvdata(pci)); } static struct pci_driver cs5535audio_driver = { .name = KBUILD_MODNAME, .id_table = snd_cs5535audio_ids, .probe = snd_cs5535audio_probe, .remove = snd_cs5535audio_remove, #ifdef CONFIG_PM_SLEEP .driver = { .pm = &snd_cs5535audio_pm, }, #endif }; module_pci_driver(cs5535audio_driver); MODULE_AUTHOR("Jaya Kumar"); MODULE_LICENSE("GPL"); MODULE_DESCRIPTION("CS5535 Audio"); MODULE_SUPPORTED_DEVICE("CS5535 Audio");
{ "pile_set_name": "Github" }
<?xml version="1.0" encoding="utf-8"?> <Project ToolsVersion="Current" xmlns="http://schemas.microsoft.com/developer/msbuild/2003"> <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|x64'"> <DebuggerFlavor>WindowsLocalDebugger</DebuggerFlavor> </PropertyGroup> </Project>
{ "pile_set_name": "Github" }
#!/bin/bash -e export URL="http://localhost:3000" echo "Bulk loading" ./populate.py -d 8 --destination=$URL --domain="mydomain" --bulk echo "The home page" wrk -c 10 -d5 -t5 $URL | grep Requests echo "Single word search 'p'" wrk -c 10 -d5 -t5 "$URL/v1?q=p&d=mydomain" | grep Requests echo "Single word search 'python'" wrk -c 10 -d5 -t5 "$URL/v1?q=python&d=mydomain" | grep Requests echo "Single word search 'xxxxxx'" wrk -c 10 -d5 -t5 "$URL/v1?q=xxxxx&d=mydomain" | grep Requests echo "Double word search 'python', 'te'" wrk -c 10 -d5 -t5 "$URL/v1?q=python%20te&d=mydomain" | grep Requests echo "Double word search 'xxxxxxxx', 'yyyyyyy'" wrk -c 10 -d5 -t5 "$URL/v1?q=xxxxxxxx%20yyyyyy&d=mydomain" | grep Requests
{ "pile_set_name": "Github" }
/* * /MathJax/jax/output/HTML-CSS/fonts/TeX/AMS/Regular/MiscSymbols.js * * Copyright (c) 2012 Design Science, Inc. * * Part of the MathJax library. * See http://www.mathjax.org for details. * * Licensed under the Apache License, Version 2.0; * you may not use this file except in compliance with the License. * * http://www.apache.org/licenses/LICENSE-2.0 */ MathJax.Hub.Insert(MathJax.OutputJax["HTML-CSS"].FONTDATA.FONTS.MathJax_AMS,{9733:[694,111,944,49,895]});MathJax.Ajax.loadComplete(MathJax.OutputJax["HTML-CSS"].fontDir+"/AMS/Regular/MiscSymbols.js");
{ "pile_set_name": "Github" }
<http://example/s> <http://example/p> <http://example/o> .
{ "pile_set_name": "Github" }
""" Two1 command to send bitcoin to another address """ # standart python imports import logging # 3rd party imports import click # two1 imports from two1.blockchain.exceptions import DataProviderError from two1.wallet.exceptions import WalletBalanceError from two1.commands.util import decorators from two1.commands.util import uxstring from two1.commands.util import exceptions from two1.commands.util import currency from two1.commands.util.bitcoin_computer import has_mining_chip # Creates a ClickLogger logger = logging.getLogger(__name__) @click.command("send") @click.argument('address', type=click.STRING) @click.argument('amount', type=click.FLOAT) @click.argument('denomination', default='', type=click.STRING) @click.option('--use-unconfirmed', '-u', is_flag=True, default=False, show_default=True, help="Use unconfirmed transactions/UTXOs") @click.option('--verbose', '-v', is_flag=True, default=False, help="Show all transaction inputs and outputs.") @click.pass_context @decorators.catch_all def send(ctx, address, amount, denomination, use_unconfirmed, verbose): """Send a specified address some satoshis. \b Usage ----- Send 5000 satoshi from your on-chain balance to the Apache Foundation. $ 21 send 1BtjAzWGLyAavUkbw3QsyzzNDKdtPXk95D 5000 satoshis You can use the following denominations: satoshis, bitcoins, and USD. By default, this command uses only confirmed transactions and UTXOs to send coins. To use unconfirmed transactions, use the --use-unconfirmed flag. """ if denomination == '': confirmed = click.confirm(uxstring.UxString.default_price_denomination, default=True) if not confirmed: raise exceptions.Two1Error(uxstring.UxString.cancel_command) denomination = currency.Price.SAT price = currency.Price(amount, denomination) return _send(ctx.obj['wallet'], address, price.satoshis, verbose, use_unconfirmed) def _send(wallet, address, satoshis, verbose, use_unconfirmed=False): """Send bitcoin to the specified address""" txids = [] try: txids = wallet.send_to(address=address, amount=satoshis, use_unconfirmed=use_unconfirmed) # For now there is only a single txn created, so assume it's 0 txid, txn = txids[0]["txid"], txids[0]["txn"] if verbose: logger.info(uxstring.UxString.send_success_verbose.format(satoshis, address, txid, txn)) else: logger.info(uxstring.UxString.send_success.format(satoshis, address, txid)) except ValueError as e: # This will trigger if there's a below dust-limit output. raise exceptions.Two1Error(str(e)) except WalletBalanceError as e: if wallet.unconfirmed_balance() > satoshis: raise exceptions.Two1Error(uxstring.UxString.send_insufficient_confirmed + str(e)) else: balance = min(wallet.confirmed_balance(), wallet.unconfirmed_balance()) if has_mining_chip(): raise exceptions.Two1Error(uxstring.UxString.send_insufficient_blockchain_21bc.format( balance, satoshis, address, str(e))) else: raise exceptions.Two1Error(uxstring.UxString.send_insufficient_blockchain_free.format( balance, satoshis, address, str(e))) except DataProviderError as e: if "rejected" in str(e): raise exceptions.Two1Error(uxstring.UxString.send_rejected) else: raise exceptions.Two1Error(str(e)) return txids
{ "pile_set_name": "Github" }
/***************************************************************************/ /* */ /* ftcsbits.c */ /* */ /* FreeType sbits manager (body). */ /* */ /* Copyright 2000-2001, 2002, 2003, 2004, 2005, 2006, 2009 by */ /* David Turner, Robert Wilhelm, and Werner Lemberg. */ /* */ /* This file is part of the FreeType project, and may only be used, */ /* modified, and distributed under the terms of the FreeType project */ /* license, LICENSE.TXT. By continuing to use, modify, or distribute */ /* this file you indicate that you have read the license and */ /* understand and accept it fully. */ /* */ /***************************************************************************/ #include <ft2build.h> #include FT_CACHE_H #include "ftcsbits.h" #include FT_INTERNAL_OBJECTS_H #include FT_INTERNAL_DEBUG_H #include FT_ERRORS_H #include "ftccback.h" #include "ftcerror.h" #undef FT_COMPONENT #define FT_COMPONENT trace_cache /*************************************************************************/ /*************************************************************************/ /***** *****/ /***** SBIT CACHE NODES *****/ /***** *****/ /*************************************************************************/ /*************************************************************************/ static FT_Error ftc_sbit_copy_bitmap( FTC_SBit sbit, FT_Bitmap* bitmap, FT_Memory memory ) { FT_Error error; FT_Int pitch = bitmap->pitch; FT_ULong size; if ( pitch < 0 ) pitch = -pitch; size = (FT_ULong)( pitch * bitmap->rows ); if ( !FT_ALLOC( sbit->buffer, size ) ) FT_MEM_COPY( sbit->buffer, bitmap->buffer, size ); return error; } FT_LOCAL_DEF( void ) ftc_snode_free( FTC_Node ftcsnode, FTC_Cache cache ) { FTC_SNode snode = (FTC_SNode)ftcsnode; FTC_SBit sbit = snode->sbits; FT_UInt count = snode->count; FT_Memory memory = cache->memory; for ( ; count > 0; sbit++, count-- ) FT_FREE( sbit->buffer ); FTC_GNode_Done( FTC_GNODE( snode ), cache ); FT_FREE( snode ); } FT_LOCAL_DEF( void ) FTC_SNode_Free( FTC_SNode snode, FTC_Cache cache ) { ftc_snode_free( FTC_NODE( snode ), cache ); } /* * This function tries to load a small bitmap within a given FTC_SNode. * Note that it returns a non-zero error code _only_ in the case of * out-of-memory condition. For all other errors (e.g., corresponding * to a bad font file), this function will mark the sbit as `unavailable' * and return a value of 0. * * You should also read the comment within the @ftc_snode_compare * function below to see how out-of-memory is handled during a lookup. */ static FT_Error ftc_snode_load( FTC_SNode snode, FTC_Manager manager, FT_UInt gindex, FT_ULong *asize ) { FT_Error error; FTC_GNode gnode = FTC_GNODE( snode ); FTC_Family family = gnode->family; FT_Memory memory = manager->memory; FT_Face face; FTC_SBit sbit; FTC_SFamilyClass clazz; if ( (FT_UInt)(gindex - gnode->gindex) >= snode->count ) { FT_ERROR(( "ftc_snode_load: invalid glyph index" )); return FTC_Err_Invalid_Argument; } sbit = snode->sbits + ( gindex - gnode->gindex ); clazz = (FTC_SFamilyClass)family->clazz; sbit->buffer = 0; error = clazz->family_load_glyph( family, gindex, manager, &face ); if ( error ) goto BadGlyph; { FT_Int temp; FT_GlyphSlot slot = face->glyph; FT_Bitmap* bitmap = &slot->bitmap; FT_Pos xadvance, yadvance; /* FT_GlyphSlot->advance.{x|y} */ if ( slot->format != FT_GLYPH_FORMAT_BITMAP ) { FT_TRACE0(( "ftc_snode_load:" " glyph loaded didn't return a bitmap\n" )); goto BadGlyph; } /* Check that our values fit into 8-bit containers! */ /* If this is not the case, our bitmap is too large */ /* and we will leave it as `missing' with sbit.buffer = 0 */ #define CHECK_CHAR( d ) ( temp = (FT_Char)d, temp == d ) #define CHECK_BYTE( d ) ( temp = (FT_Byte)d, temp == d ) /* horizontal advance in pixels */ xadvance = ( slot->advance.x + 32 ) >> 6; yadvance = ( slot->advance.y + 32 ) >> 6; if ( !CHECK_BYTE( bitmap->rows ) || !CHECK_BYTE( bitmap->width ) || !CHECK_CHAR( bitmap->pitch ) || !CHECK_CHAR( slot->bitmap_left ) || !CHECK_CHAR( slot->bitmap_top ) || !CHECK_CHAR( xadvance ) || !CHECK_CHAR( yadvance ) ) goto BadGlyph; sbit->width = (FT_Byte)bitmap->width; sbit->height = (FT_Byte)bitmap->rows; sbit->pitch = (FT_Char)bitmap->pitch; sbit->left = (FT_Char)slot->bitmap_left; sbit->top = (FT_Char)slot->bitmap_top; sbit->xadvance = (FT_Char)xadvance; sbit->yadvance = (FT_Char)yadvance; sbit->format = (FT_Byte)bitmap->pixel_mode; sbit->max_grays = (FT_Byte)(bitmap->num_grays - 1); /* copy the bitmap into a new buffer -- ignore error */ error = ftc_sbit_copy_bitmap( sbit, bitmap, memory ); /* now, compute size */ if ( asize ) *asize = FT_ABS( sbit->pitch ) * sbit->height; } /* glyph loading successful */ /* ignore the errors that might have occurred -- */ /* we mark unloaded glyphs with `sbit.buffer == 0' */ /* and `width == 255', `height == 0' */ /* */ if ( error && error != FTC_Err_Out_Of_Memory ) { BadGlyph: sbit->width = 255; sbit->height = 0; sbit->buffer = NULL; error = 0; if ( asize ) *asize = 0; } return error; } FT_LOCAL_DEF( FT_Error ) FTC_SNode_New( FTC_SNode *psnode, FTC_GQuery gquery, FTC_Cache cache ) { FT_Memory memory = cache->memory; FT_Error error; FTC_SNode snode = NULL; FT_UInt gindex = gquery->gindex; FTC_Family family = gquery->family; FTC_SFamilyClass clazz = FTC_CACHE__SFAMILY_CLASS( cache ); FT_UInt total; total = clazz->family_get_count( family, cache->manager ); if ( total == 0 || gindex >= total ) { error = FT_Err_Invalid_Argument; goto Exit; } if ( !FT_NEW( snode ) ) { FT_UInt count, start; start = gindex - ( gindex % FTC_SBIT_ITEMS_PER_NODE ); count = total - start; if ( count > FTC_SBIT_ITEMS_PER_NODE ) count = FTC_SBIT_ITEMS_PER_NODE; FTC_GNode_Init( FTC_GNODE( snode ), start, family ); snode->count = count; error = ftc_snode_load( snode, cache->manager, gindex, NULL ); if ( error ) { FTC_SNode_Free( snode, cache ); snode = NULL; } } Exit: *psnode = snode; return error; } FT_LOCAL_DEF( FT_Error ) ftc_snode_new( FTC_Node *ftcpsnode, FT_Pointer ftcgquery, FTC_Cache cache ) { FTC_SNode *psnode = (FTC_SNode*)ftcpsnode; FTC_GQuery gquery = (FTC_GQuery)ftcgquery; return FTC_SNode_New( psnode, gquery, cache ); } FT_LOCAL_DEF( FT_Offset ) ftc_snode_weight( FTC_Node ftcsnode, FTC_Cache cache ) { FTC_SNode snode = (FTC_SNode)ftcsnode; FT_UInt count = snode->count; FTC_SBit sbit = snode->sbits; FT_Int pitch; FT_Offset size; FT_UNUSED( cache ); FT_ASSERT( snode->count <= FTC_SBIT_ITEMS_PER_NODE ); /* the node itself */ size = sizeof ( *snode ); for ( ; count > 0; count--, sbit++ ) { if ( sbit->buffer ) { pitch = sbit->pitch; if ( pitch < 0 ) pitch = -pitch; /* add the size of a given glyph image */ size += pitch * sbit->height; } } return size; } #if 0 FT_LOCAL_DEF( FT_Offset ) FTC_SNode_Weight( FTC_SNode snode ) { return ftc_snode_weight( FTC_NODE( snode ), NULL ); } #endif /* 0 */ FT_LOCAL_DEF( FT_Bool ) ftc_snode_compare( FTC_Node ftcsnode, FT_Pointer ftcgquery, FTC_Cache cache ) { FTC_SNode snode = (FTC_SNode)ftcsnode; FTC_GQuery gquery = (FTC_GQuery)ftcgquery; FTC_GNode gnode = FTC_GNODE( snode ); FT_UInt gindex = gquery->gindex; FT_Bool result; result = FT_BOOL( gnode->family == gquery->family && (FT_UInt)( gindex - gnode->gindex ) < snode->count ); if ( result ) { /* check if we need to load the glyph bitmap now */ FTC_SBit sbit = snode->sbits + ( gindex - gnode->gindex ); /* * The following code illustrates what to do when you want to * perform operations that may fail within a lookup function. * * Here, we want to load a small bitmap on-demand; we thus * need to call the `ftc_snode_load' function which may return * a non-zero error code only when we are out of memory (OOM). * * The correct thing to do is to use @FTC_CACHE_TRYLOOP and * @FTC_CACHE_TRYLOOP_END in order to implement a retry loop * that is capable of flushing the cache incrementally when * an OOM errors occur. * * However, we need to `lock' the node before this operation to * prevent it from being flushed within the loop. * * When we exit the loop, we unlock the node, then check the `error' * variable. If it is non-zero, this means that the cache was * completely flushed and that no usable memory was found to load * the bitmap. * * We then prefer to return a value of 0 (i.e., NO MATCH). This * ensures that the caller will try to allocate a new node. * This operation consequently _fail_ and the lookup function * returns the appropriate OOM error code. * * Note that `buffer == NULL && width == 255' is a hack used to * tag `unavailable' bitmaps in the array. We should never try * to load these. * */ if ( sbit->buffer == NULL && sbit->width != 255 ) { FT_ULong size; FT_Error error; ftcsnode->ref_count++; /* lock node to prevent flushing */ /* in retry loop */ FTC_CACHE_TRYLOOP( cache ) { error = ftc_snode_load( snode, cache->manager, gindex, &size ); } FTC_CACHE_TRYLOOP_END(); ftcsnode->ref_count--; /* unlock the node */ if ( error ) result = 0; else cache->manager->cur_weight += size; } } return result; } FT_LOCAL_DEF( FT_Bool ) FTC_SNode_Compare( FTC_SNode snode, FTC_GQuery gquery, FTC_Cache cache ) { return ftc_snode_compare( FTC_NODE( snode ), gquery, cache ); } /* END */
{ "pile_set_name": "Github" }
debian/tmp/usr/bin/ansible-test usr/bin debian/tmp/usr/lib/python3/dist-packages/ansible_test usr/lib/python3/dist-packages
{ "pile_set_name": "Github" }
files { 0 1 1 test_job test_namespace strings1.xml 0 1 2 6 test_job test_namespace strings2.xml 0 2 3 13 test_job test_namespace strings3.xml 0 3 4 20 test_job test_namespace strings4.xml 0 4 5 28 test_job test_namespace strings5.xml 0 }
{ "pile_set_name": "Github" }
# Firejail profile for meld # Description: Graphical tool to diff and merge files # This file is overwritten after every install/update # Persistent local customizations include meld.local # Persistent global definitions include globals.local # If you want to use meld as git-mergetool (and maybe some other VCS integrations) you need # to bypass firejail, you can do this by removing the symlink or calling it by its absolute path # Removing the symlink: # sudo rm /usr/local/bin/meld # Calling by its absolute path (example for git-mergetool): # git config --global mergetool.meld.cmd /usr/bin/meld noblacklist ${HOME}/.config/meld noblacklist ${HOME}/.config/git noblacklist ${HOME}/.gitconfig noblacklist ${HOME}/.git-credentials noblacklist ${HOME}/.local/share/meld noblacklist ${HOME}/.ssh noblacklist ${HOME}/.subversion # Allow python (blacklisted by disable-interpreters.inc) include allow-python3.inc # Python 2 is EOL (see #3164). Uncomment the next line (or put it into your meld.local) if you understand the risks but want python 2 support for older meld versions. #include allow-python2.inc # Uncomment the next line (or put it into your meld.local) if you don't need to compare files in disable-common.inc. #include disable-common.inc include disable-devel.inc include disable-exec.inc include disable-interpreters.inc include disable-passwdmgr.inc # Uncomment the next line (or put it into your meld.local) if you don't need to compare files in disable-programs.inc. #include disable-programs.inc include disable-shell.inc include whitelist-runuser-common.inc # Uncomment the next lines (or put it into your meld.local) if you don't need to compare files in /usr/share. #whitelist /usr/share/meld #include whitelist-usr-share-common.inc # Uncomment the next line (or put it into your meld.local) if you don't need to compare files in /var. #include whitelist-var-common.inc apparmor caps.drop all ipc-namespace machine-id netfilter no3d nodvd nogroups nonewprivs noroot nosound notv nou2f novideo protocol unix,inet,inet6 seccomp shell none tracelog private-bin bzr,cvs,git,hg,meld,python*,svn private-cache private-dev # Uncomment the next line (or put it into your meld.local) if you don't need to compare in /etc. #private-etc alternatives,ca-certificates,crypto-policies,fonts,hostname,hosts,pki,resolv.conf,ssl,subversion # Comment the next line (or add 'ignore private-tmp to your meld.local') if you want to use it as a difftool (#3551) private-tmp read-only ${HOME}/.ssh
{ "pile_set_name": "Github" }
<?xml version="1.0" encoding="utf-8"?> <style xmlns="http://purl.org/net/xbiblio/csl" version="1.0" default-locale="en-US"> <!-- Generated with https://github.com/citation-style-language/utilities/tree/master/generate_dependent_styles/data/mdpi --> <info> <title>Processes</title> <id>http://www.zotero.org/styles/processes</id> <link href="http://www.zotero.org/styles/processes" rel="self"/> <link href="http://www.zotero.org/styles/multidisciplinary-digital-publishing-institute" rel="independent-parent"/> <link href="http://www.mdpi.com/authors/references" rel="documentation"/> <category citation-format="numeric"/> <category field="science"/> <eissn>2227-9717</eissn> <updated>2014-05-15T12:00:00+00:00</updated> <rights license="http://creativecommons.org/licenses/by-sa/3.0/">This work is licensed under a Creative Commons Attribution-ShareAlike 3.0 License</rights> </info> </style>
{ "pile_set_name": "Github" }
/************************************************************* * * MathJax/jax/output/HTML-CSS/fonts/STIX/General/Bold/BBBold.js * * Copyright (c) 2009-2018 The MathJax Consortium * * 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. * */ MathJax.Hub.Insert( MathJax.OutputJax['HTML-CSS'].FONTDATA.FONTS['STIXGeneral-bold'], { 0x1D538: [676,0,787,50,737], // MATHEMATICAL DOUBLE-STRUCK CAPITAL A 0x1D539: [676,0,729,75,669], // MATHEMATICAL DOUBLE-STRUCK CAPITAL B 0x1D53B: [676,0,748,75,703], // MATHEMATICAL DOUBLE-STRUCK CAPITAL D 0x1D53C: [676,0,650,75,595], // MATHEMATICAL DOUBLE-STRUCK CAPITAL E 0x1D53D: [676,0,474,75,595], // MATHEMATICAL DOUBLE-STRUCK CAPITAL F 0x1D53E: [691,19,751,45,686], // MATHEMATICAL DOUBLE-STRUCK CAPITAL G 0x1D540: [676,0,380,80,300], // MATHEMATICAL DOUBLE-STRUCK CAPITAL I 0x1D541: [676,19,618,50,548], // MATHEMATICAL DOUBLE-STRUCK CAPITAL J 0x1D542: [676,0,792,75,767], // MATHEMATICAL DOUBLE-STRUCK CAPITAL K 0x1D543: [676,0,662,70,607], // MATHEMATICAL DOUBLE-STRUCK CAPITAL L 0x1D544: [676,0,914,75,839], // MATHEMATICAL DOUBLE-STRUCK CAPITAL M 0x1D546: [691,19,787,45,742], // MATHEMATICAL DOUBLE-STRUCK CAPITAL O 0x1D54A: [692,19,702,45,657], // MATHEMATICAL DOUBLE-STRUCK CAPITAL S 0x1D54B: [676,0,556,25,645], // MATHEMATICAL DOUBLE-STRUCK CAPITAL T 0x1D54C: [676,19,738,70,668], // MATHEMATICAL DOUBLE-STRUCK CAPITAL U 0x1D54D: [676,0,627,17,704], // MATHEMATICAL DOUBLE-STRUCK CAPITAL V 0x1D54E: [676,0,996,17,1015], // MATHEMATICAL DOUBLE-STRUCK CAPITAL W 0x1D54F: [676,0,794,20,769], // MATHEMATICAL DOUBLE-STRUCK CAPITAL X 0x1D550: [676,0,652,23,739], // MATHEMATICAL DOUBLE-STRUCK CAPITAL Y 0x1D552: [473,14,623,50,563], // MATHEMATICAL DOUBLE-STRUCK SMALL A 0x1D553: [676,14,643,60,593], // MATHEMATICAL DOUBLE-STRUCK SMALL B 0x1D554: [473,14,574,50,524], // MATHEMATICAL DOUBLE-STRUCK SMALL C 0x1D555: [676,14,643,50,583], // MATHEMATICAL DOUBLE-STRUCK SMALL D 0x1D556: [473,14,573,50,523], // MATHEMATICAL DOUBLE-STRUCK SMALL E 0x1D557: [676,0,474,25,536], // MATHEMATICAL DOUBLE-STRUCK SMALL F 0x1D558: [473,205,643,50,583], // MATHEMATICAL DOUBLE-STRUCK SMALL G 0x1D559: [676,0,624,60,564], // MATHEMATICAL DOUBLE-STRUCK SMALL H 0x1D55A: [691,0,330,65,265], // MATHEMATICAL DOUBLE-STRUCK SMALL I 0x1D55B: [691,205,371,-20,311], // MATHEMATICAL DOUBLE-STRUCK SMALL J 0x1D55C: [676,0,646,60,621], // MATHEMATICAL DOUBLE-STRUCK SMALL K 0x1D55D: [676,0,325,60,265], // MATHEMATICAL DOUBLE-STRUCK SMALL L 0x1D55E: [473,0,908,60,848], // MATHEMATICAL DOUBLE-STRUCK SMALL M 0x1D55F: [473,0,624,60,564], // MATHEMATICAL DOUBLE-STRUCK SMALL N 0x1D560: [473,14,598,45,553], // MATHEMATICAL DOUBLE-STRUCK SMALL O 0x1D561: [473,205,643,60,593], // MATHEMATICAL DOUBLE-STRUCK SMALL P 0x1D562: [473,205,643,50,583], // MATHEMATICAL DOUBLE-STRUCK SMALL Q 0x1D563: [473,0,339,60,445], // MATHEMATICAL DOUBLE-STRUCK SMALL R 0x1D564: [473,14,549,52,497], // MATHEMATICAL DOUBLE-STRUCK SMALL S 0x1D565: [676,14,446,25,411], // MATHEMATICAL DOUBLE-STRUCK SMALL T 0x1D566: [461,16,619,55,559], // MATHEMATICAL DOUBLE-STRUCK SMALL U 0x1D567: [461,0,494,6,544], // MATHEMATICAL DOUBLE-STRUCK SMALL V 0x1D568: [461,0,786,22,789], // MATHEMATICAL DOUBLE-STRUCK SMALL W 0x1D569: [461,0,660,25,635], // MATHEMATICAL DOUBLE-STRUCK SMALL X 0x1D56A: [461,205,471,-9,537], // MATHEMATICAL DOUBLE-STRUCK SMALL Y 0x1D56B: [461,0,513,40,473] // MATHEMATICAL DOUBLE-STRUCK SMALL Z } ); MathJax.Ajax.loadComplete(MathJax.OutputJax["HTML-CSS"].fontDir + "/General/Bold/BBBold.js");
{ "pile_set_name": "Github" }
import { FocusZoneDirection } from '@fluentui/accessibility'; import { FocusTrapZone, FocusZone, FocusTrapZoneProps } from '@fluentui/react-bindings'; import * as React from 'react'; import * as ReactTestUtils from 'react-dom/test-utils'; import { keyboardKey } from '@fluentui/keyboard-key'; // rAF does not exist in node - let's mock it window.requestAnimationFrame = (callback: FrameRequestCallback) => { const r = window.setTimeout(callback, 0); jest.runAllTimers(); return r; }; jest.useFakeTimers(); class FocusTrapZoneTestComponent extends React.Component<{}, { isShowingFirst: boolean; isShowingSecond: boolean }> { constructor(props: {}) { super(props); this.state = { isShowingFirst: true, isShowingSecond: false }; } render() { return ( <div> <FocusTrapZone forceFocusInsideTrapOnOutsideFocus isClickableOutsideFocusTrap={false}> <button className={'a'} onClick={this._toggleFirst}> a </button> <button className={'b'} onClick={this._toggleSecond}> b </button> </FocusTrapZone> {this.state.isShowingFirst && ( <FocusTrapZone forceFocusInsideTrapOnOutsideFocus={false} isClickableOutsideFocusTrap={false}> <FocusZone data-is-visible={true}>First</FocusZone> </FocusTrapZone> )} {this.state.isShowingSecond && ( <FocusTrapZone forceFocusInsideTrapOnOutsideFocus={false} isClickableOutsideFocusTrap={true}> <FocusZone data-is-visible={true}>First</FocusZone> </FocusTrapZone> )} </div> ); } _toggleFirst = () => this.setState({ isShowingFirst: !this.state.isShowingFirst }); _toggleSecond = () => this.setState({ isShowingSecond: !this.state.isShowingSecond }); } describe('FocusTrapZone', () => { // document.activeElement can be used to detect activeElement after component mount, but it does not // update based on focus events due to limitations of ReactDOM. Use lastFocusedElement to detect focus // change events. let lastFocusedElement: HTMLElement | undefined; const ftzClassname = 'ftzTestClassname'; const _onFocus = (ev: any): void => (lastFocusedElement = ev.target); const setupElement = ( element: HTMLElement, { clientRect, isVisible = true, }: { clientRect: { top: number; left: number; bottom: number; right: number; }; isVisible?: boolean; }, ): void => { // @ts-ignore element.getBoundingClientRect = () => ({ top: clientRect.top, left: clientRect.left, bottom: clientRect.bottom, right: clientRect.right, width: clientRect.right - clientRect.left, height: clientRect.bottom - clientRect.top, }); element.setAttribute('data-is-visible', String(isVisible)); element.focus = () => ReactTestUtils.Simulate.focus(element); }; /** * Helper to get FocusTrapZone bumpers. Requires classname attribute of * 'ftzClassname' on FTZ. */ function getFtzBumpers( element: HTMLElement, ): { firstBumper: Element; lastBumper: Element; } { const ftz = element.querySelector(`.${ftzClassname}`) as HTMLElement; const ftzNodes = ftz.children; const firstBumper = ftzNodes[0]; const lastBumper = ftzNodes[ftzNodes.length - 1]; return { firstBumper, lastBumper }; } beforeEach(() => { lastFocusedElement = undefined; }); describe('Tab and shift-tab wrap at extreme ends of the FTZ', () => { it('can tab across FocusZones with different button structures', async () => { expect.assertions(3); const topLevelDiv = ReactTestUtils.renderIntoDocument<{}>( <div onFocusCapture={_onFocus}> <FocusTrapZone forceFocusInsideTrapOnOutsideFocus={false} className={ftzClassname}> <FocusZone direction={FocusZoneDirection.horizontal} data-is-visible={true}> <div data-is-visible={true}> <button className="a">a</button> </div> <div data-is-visible={true}> <button className="b">b</button> </div> <div data-is-visible={true}> <button className="c">c</button> </div> </FocusZone> <FocusZone direction={FocusZoneDirection.horizontal} data-is-visible={true}> <div data-is-visible={true}> <div data-is-visible={true}> <button className="d">d</button> <button className="e">e</button> <button className="f">f</button> </div> </div> </FocusZone> </FocusTrapZone> </div>, ) as HTMLElement; const buttonA = topLevelDiv.querySelector('.a') as HTMLElement; const buttonB = topLevelDiv.querySelector('.b') as HTMLElement; const buttonC = topLevelDiv.querySelector('.c') as HTMLElement; const buttonD = topLevelDiv.querySelector('.d') as HTMLElement; const buttonE = topLevelDiv.querySelector('.e') as HTMLElement; const buttonF = topLevelDiv.querySelector('.f') as HTMLElement; // Assign bounding locations to buttons. setupElement(buttonA, { clientRect: { top: 0, bottom: 30, left: 0, right: 30 } }); setupElement(buttonB, { clientRect: { top: 0, bottom: 30, left: 30, right: 60 } }); setupElement(buttonC, { clientRect: { top: 0, bottom: 30, left: 60, right: 90 } }); setupElement(buttonD, { clientRect: { top: 30, bottom: 60, left: 0, right: 30 } }); setupElement(buttonE, { clientRect: { top: 30, bottom: 60, left: 30, right: 60 } }); setupElement(buttonF, { clientRect: { top: 30, bottom: 60, left: 60, right: 90 } }); const { firstBumper, lastBumper } = getFtzBumpers(topLevelDiv); ReactTestUtils.Simulate.focus(buttonA); expect(lastFocusedElement).toBe(buttonA); // Simulate shift+tab event which would focus first bumper ReactTestUtils.Simulate.focus(firstBumper); expect(lastFocusedElement).toBe(buttonD); // Simulate tab event which would focus last bumper ReactTestUtils.Simulate.focus(lastBumper); expect(lastFocusedElement).toBe(buttonA); }); it('can tab across a FocusZone with different button structures', async () => { expect.assertions(3); const topLevelDiv = ReactTestUtils.renderIntoDocument<{}>( <div onFocusCapture={_onFocus}> <FocusTrapZone forceFocusInsideTrapOnOutsideFocus={false} className={ftzClassname}> <div data-is-visible={true}> <button className="x">x</button> </div> <FocusZone direction={FocusZoneDirection.horizontal} data-is-visible={true}> <div data-is-visible={true}> <button className="a">a</button> </div> <div data-is-visible={true}> <div data-is-visible={true}> <button className="b">b</button> <button className="c">c</button> <button className="d">d</button> </div> </div> </FocusZone> </FocusTrapZone> </div>, ) as HTMLElement; const buttonX = topLevelDiv.querySelector('.x') as HTMLElement; const buttonA = topLevelDiv.querySelector('.a') as HTMLElement; const buttonB = topLevelDiv.querySelector('.b') as HTMLElement; const buttonC = topLevelDiv.querySelector('.c') as HTMLElement; const buttonD = topLevelDiv.querySelector('.d') as HTMLElement; const { firstBumper, lastBumper } = getFtzBumpers(topLevelDiv); // Assign bounding locations to buttons. setupElement(buttonX, { clientRect: { top: 0, bottom: 30, left: 0, right: 30 } }); setupElement(buttonA, { clientRect: { top: 0, bottom: 30, left: 0, right: 30 } }); setupElement(buttonB, { clientRect: { top: 0, bottom: 30, left: 30, right: 60 } }); setupElement(buttonC, { clientRect: { top: 0, bottom: 30, left: 60, right: 90 } }); setupElement(buttonD, { clientRect: { top: 30, bottom: 60, left: 0, right: 30 } }); ReactTestUtils.Simulate.focus(buttonX); expect(lastFocusedElement).toBe(buttonX); // Simulate shift+tab event which would focus first bumper ReactTestUtils.Simulate.focus(firstBumper); expect(lastFocusedElement).toBe(buttonA); // Simulate tab event which would focus last bumper ReactTestUtils.Simulate.focus(lastBumper); expect(lastFocusedElement).toBe(buttonX); }); it('can trap focus when FTZ bookmark elements are FocusZones, and those elements have inner elements focused that are not the first inner element', async () => { expect.assertions(4); const topLevelDiv = ReactTestUtils.renderIntoDocument<{}>( <div onFocusCapture={_onFocus}> <button className={'z1'}>z1</button> <FocusTrapZone forceFocusInsideTrapOnOutsideFocus={false} className={ftzClassname}> <FocusZone direction={FocusZoneDirection.horizontal} data-is-visible={true}> <button className={'a'}>a</button> <button className={'b'}>b</button> <button className={'c'}>c</button> </FocusZone> <button className={'d'}>d</button> <FocusZone direction={FocusZoneDirection.horizontal} data-is-visible={true}> <button className={'e'}>e</button> <button className={'f'}>f</button> <button className={'g'}>g</button> </FocusZone> </FocusTrapZone> <button className={'z2'}>z2</button> </div>, ) as HTMLElement; const buttonZ1 = topLevelDiv.querySelector('.z1') as HTMLElement; const buttonA = topLevelDiv.querySelector('.a') as HTMLElement; const buttonB = topLevelDiv.querySelector('.b') as HTMLElement; const buttonC = topLevelDiv.querySelector('.c') as HTMLElement; const buttonD = topLevelDiv.querySelector('.d') as HTMLElement; const buttonE = topLevelDiv.querySelector('.e') as HTMLElement; const buttonF = topLevelDiv.querySelector('.f') as HTMLElement; const buttonG = topLevelDiv.querySelector('.g') as HTMLElement; const buttonZ2 = topLevelDiv.querySelector('.z2') as HTMLElement; const { firstBumper, lastBumper } = getFtzBumpers(topLevelDiv); // Assign bounding locations to buttons. setupElement(buttonZ1, { clientRect: { top: 0, bottom: 10, left: 0, right: 10 } }); setupElement(buttonA, { clientRect: { top: 10, bottom: 30, left: 0, right: 10 } }); setupElement(buttonB, { clientRect: { top: 10, bottom: 30, left: 10, right: 20 } }); setupElement(buttonC, { clientRect: { top: 10, bottom: 30, left: 20, right: 30 } }); setupElement(buttonD, { clientRect: { top: 30, bottom: 40, left: 0, right: 10 } }); setupElement(buttonE, { clientRect: { top: 40, bottom: 60, left: 0, right: 10 } }); setupElement(buttonF, { clientRect: { top: 40, bottom: 60, left: 10, right: 20 } }); setupElement(buttonG, { clientRect: { top: 40, bottom: 60, left: 20, right: 30 } }); setupElement(buttonZ2, { clientRect: { top: 60, bottom: 70, left: 0, right: 10 } }); // Focus the middle button in the first FZ. ReactTestUtils.Simulate.focus(buttonA); ReactTestUtils.Simulate.keyDown(buttonA, { which: keyboardKey.ArrowRight }); expect(lastFocusedElement).toBe(buttonB); // Focus the middle button in the second FZ. ReactTestUtils.Simulate.focus(buttonE); ReactTestUtils.Simulate.keyDown(buttonE, { which: keyboardKey.ArrowRight }); expect(lastFocusedElement).toBe(buttonF); // Simulate tab event which would focus last bumper ReactTestUtils.Simulate.focus(lastBumper); expect(lastFocusedElement).toBe(buttonB); // Simulate shift+tab event which would focus first bumper ReactTestUtils.Simulate.focus(firstBumper); expect(lastFocusedElement).toBe(buttonF); }); }); describe('Tab and shift-tab do nothing (keep focus where it is) when the FTZ contains 0 tabbable items', () => { function setupTest(props: FocusTrapZoneProps) { const topLevelDiv = ReactTestUtils.renderIntoDocument<{}>( <div onFocusCapture={_onFocus}> <button className={'z1'}>z1</button> <FocusTrapZone className={ftzClassname} forceFocusInsideTrapOnOutsideFocus={true} {...props}> <button className={'a'} tabIndex={-1}> a </button> <button className={'b'} tabIndex={-1}> b </button> <button className={'c'} tabIndex={-1}> c </button> </FocusTrapZone> <button className={'z2'}>z2</button> </div>, ) as HTMLElement; const buttonZ1 = topLevelDiv.querySelector('.z1') as HTMLElement; const buttonA = topLevelDiv.querySelector('.a') as HTMLElement; const buttonB = topLevelDiv.querySelector('.b') as HTMLElement; const buttonC = topLevelDiv.querySelector('.c') as HTMLElement; const buttonZ2 = topLevelDiv.querySelector('.z2') as HTMLElement; const { firstBumper, lastBumper } = getFtzBumpers(topLevelDiv); // Have to set bumpers as "visible" for focus utilities to find them. // This is needed for 0 tabbable element tests to make sure that next tabbable element // from one bumper is the other bumper. firstBumper.setAttribute('data-is-visible', String(true)); lastBumper.setAttribute('data-is-visible', String(true)); // Assign bounding locations to buttons. setupElement(buttonZ1, { clientRect: { top: 0, bottom: 10, left: 0, right: 10 } }); setupElement(buttonA, { clientRect: { top: 10, bottom: 20, left: 0, right: 10 } }); setupElement(buttonB, { clientRect: { top: 20, bottom: 30, left: 0, right: 10 } }); setupElement(buttonC, { clientRect: { top: 30, bottom: 40, left: 0, right: 10 } }); setupElement(buttonZ2, { clientRect: { top: 40, bottom: 50, left: 0, right: 10 } }); return { buttonZ1, buttonA, buttonB, buttonC, buttonZ2, firstBumper, lastBumper }; } it('focuses first focusable element when focusing first bumper', async () => { expect.assertions(2); const { buttonB, buttonA, firstBumper } = setupTest({}); ReactTestUtils.Simulate.focus(buttonB); expect(lastFocusedElement).toBe(buttonB); // Simulate shift+tab event which would focus first bumper ReactTestUtils.Simulate.focus(firstBumper); expect(lastFocusedElement).toBe(buttonA); }); it('focuses first focusable element when focusing last bumper', async () => { expect.assertions(2); const { buttonA, buttonB, lastBumper } = setupTest({}); ReactTestUtils.Simulate.focus(buttonB); expect(lastFocusedElement).toBe(buttonB); // Simulate tab event which would focus last bumper ReactTestUtils.Simulate.focus(lastBumper); expect(lastFocusedElement).toBe(buttonA); }); }); describe('Focus behavior based on default and explicit prop values', () => { function setupTest(props: FocusTrapZoneProps) { // data-is-visible is embedded in buttons here for testing focus behavior on initial render. // Components have to be marked visible before setupElement has a chance to apply the data-is-visible attribute. const topLevelDiv = (ReactTestUtils.renderIntoDocument( <div> <div onFocusCapture={_onFocus}> <button className={'z1'}>z1</button> <FocusTrapZone data-is-visible={true} {...props} className={ftzClassname}> <button className={'a'} data-is-visible={true}> a </button> <button className={'b'} data-is-visible={true}> b </button> <button className={'c'} data-is-visible={true}> c </button> </FocusTrapZone> <button className={'z2'}>z2</button> </div> </div>, ) as unknown) as HTMLElement; const buttonZ1 = topLevelDiv.querySelector('.z1') as HTMLElement; const buttonA = topLevelDiv.querySelector('.a') as HTMLElement; const buttonB = topLevelDiv.querySelector('.b') as HTMLElement; const buttonC = topLevelDiv.querySelector('.c') as HTMLElement; const buttonZ2 = topLevelDiv.querySelector('.z2') as HTMLElement; const { firstBumper, lastBumper } = getFtzBumpers(topLevelDiv); // Assign bounding locations to buttons. setupElement(buttonZ1, { clientRect: { top: 0, bottom: 10, left: 0, right: 10 } }); setupElement(buttonA, { clientRect: { top: 10, bottom: 20, left: 0, right: 10 } }); setupElement(buttonB, { clientRect: { top: 20, bottom: 30, left: 0, right: 10 } }); setupElement(buttonC, { clientRect: { top: 30, bottom: 40, left: 0, right: 10 } }); setupElement(buttonZ2, { clientRect: { top: 40, bottom: 50, left: 0, right: 10 } }); return { buttonZ1, buttonA, buttonB, buttonC, buttonZ2, firstBumper, lastBumper }; } it('Focuses first element when FTZ does not have focus and first bumper receives focus', async () => { expect.assertions(2); const { buttonA, buttonZ1, firstBumper } = setupTest({ isClickableOutsideFocusTrap: true }); ReactTestUtils.Simulate.focus(buttonZ1); expect(lastFocusedElement).toBe(buttonZ1); ReactTestUtils.Simulate.focus(firstBumper); expect(lastFocusedElement).toBe(buttonA); }); it('Focuses last element when FTZ does not have focus and last bumper receives focus', async () => { expect.assertions(2); const { buttonC, buttonZ2, lastBumper } = setupTest({ isClickableOutsideFocusTrap: true }); ReactTestUtils.Simulate.focus(buttonZ2); expect(lastFocusedElement).toBe(buttonZ2); ReactTestUtils.Simulate.focus(lastBumper); expect(lastFocusedElement).toBe(buttonC); }); it('Focuses first on mount', async () => { expect.assertions(1); const { buttonA } = setupTest({}); expect(document.activeElement).toBe(buttonA); }); it('Does not focus first on mount with disableFirstFocus', async () => { expect.assertions(1); const activeElement = document.activeElement; setupTest({ disableFirstFocus: true }); // document.activeElement can be used to detect activeElement after component mount, but it does not // update based on focus events due to limitations of ReactDOM. // Make sure activeElement didn't change. expect(document.activeElement).toBe(activeElement); }); it('Does not focus first on mount while disabled', async () => { expect.assertions(1); const activeElement = document.activeElement; setupTest({ disabled: true }); // document.activeElement can be used to detect activeElement after component mount, but it does not // update based on focus events due to limitations of ReactDOM. // Make sure activeElement didn't change. expect(document.activeElement).toBe(activeElement); }); it('Focuses on firstFocusableSelector on mount', async () => { expect.assertions(1); const { buttonC } = setupTest({ firstFocusableSelector: '.c' }); expect(document.activeElement).toBe(buttonC); }); it('Does not focus on firstFocusableSelector on mount while disabled', async () => { expect.assertions(1); const activeElement = document.activeElement; setupTest({ firstFocusableSelector: '.c', disabled: true }); expect(document.activeElement).toBe(activeElement); }); it('Falls back to first focusable element with invalid firstFocusableSelector', async () => { const { buttonA } = setupTest({ firstFocusableSelector: '.invalidSelector' }); expect(document.activeElement).toBe(buttonA); }); }); describe('Focusing the FTZ', () => { function setupTest(focusPreviouslyFocusedInnerElement: boolean) { let focusTrapZoneRef: FocusTrapZone | null = null; const topLevelDiv = ReactTestUtils.renderIntoDocument<{}>( <div onFocusCapture={_onFocus}> <FocusTrapZone forceFocusInsideTrapOnOutsideFocus={false} focusPreviouslyFocusedInnerElement={focusPreviouslyFocusedInnerElement} data-is-focusable={true} ref={ftz => { focusTrapZoneRef = ftz; }} > <button className={'f'}>f</button> <FocusZone> <button className={'a'}>a</button> <button className={'b'}>b</button> </FocusZone> </FocusTrapZone> <button className={'z'}>z</button> </div>, ) as HTMLElement; const buttonF = topLevelDiv.querySelector('.f') as HTMLElement; const buttonA = topLevelDiv.querySelector('.a') as HTMLElement; const buttonB = topLevelDiv.querySelector('.b') as HTMLElement; const buttonZ = topLevelDiv.querySelector('.z') as HTMLElement; // Assign bounding locations to buttons. setupElement(buttonF, { clientRect: { top: 0, bottom: 10, left: 0, right: 10 } }); setupElement(buttonA, { clientRect: { top: 10, bottom: 20, left: 0, right: 10 } }); setupElement(buttonB, { clientRect: { top: 20, bottom: 30, left: 0, right: 10 } }); setupElement(buttonZ, { clientRect: { top: 30, bottom: 40, left: 0, right: 10 } }); return { focusTrapZone: focusTrapZoneRef, buttonF, buttonA, buttonB, buttonZ }; } it('goes to previously focused element when focusing the FTZ', async () => { expect.assertions(4); const { focusTrapZone, buttonF, buttonB, buttonZ } = setupTest(true /* focusPreviouslyFocusedInnerElement */); // By calling `componentDidMount`, FTZ will behave as just initialized and focus needed element // @ts-ignore focusTrapZone.componentDidMount(); expect(lastFocusedElement).toBe(buttonF); // Focus inside the trap zone, not the first element. ReactTestUtils.Simulate.focus(buttonB); expect(lastFocusedElement).toBe(buttonB); // Focus outside the trap zone ReactTestUtils.Simulate.focus(buttonZ); expect(lastFocusedElement).toBe(buttonZ); // By calling `componentDidMount`, FTZ will behave as just initialized and focus needed element // FTZ should return to originally focused inner element. // @ts-ignore focusTrapZone.componentDidMount(); expect(lastFocusedElement).toBe(buttonB); }); it('goes to first focusable element when focusing the FTZ', async () => { expect.assertions(4); const { focusTrapZone, buttonF, buttonB, buttonZ } = setupTest(false /* focusPreviouslyFocusedInnerElement */); // By calling `componentDidMount`, FTZ will behave as just initialized and focus needed element // Focus within should go to 1st focusable inner element. // @ts-ignore focusTrapZone.componentDidMount(); expect(lastFocusedElement).toBe(buttonF); // Focus inside the trap zone, not the first element. ReactTestUtils.Simulate.focus(buttonB); expect(lastFocusedElement).toBe(buttonB); // Focus outside the trap zone ReactTestUtils.Simulate.focus(buttonZ); expect(lastFocusedElement).toBe(buttonZ); // By calling `componentDidMount`, FTZ will behave as just initialized and focus needed element // Focus should go to the first focusable element // @ts-ignore focusTrapZone.componentDidMount(); expect(lastFocusedElement).toBe(buttonF); }); }); describe('Nested FocusTrapZones Stack Behavior', () => { const getFocusStack = (): FocusTrapZone[] => (FocusTrapZone as any)._focusStack; beforeAll(() => (getFocusStack().length = 0)); it('FocusTrapZone maintains a proper stack of FocusTrapZones as more are mounted/unmounted.', async () => { let focusTrapZoneFocusStack: FocusTrapZone[] = getFocusStack(); const topLevelDiv = ReactTestUtils.renderIntoDocument<{}>( <div> <FocusTrapZoneTestComponent /> </div>, ) as HTMLElement; const buttonA = topLevelDiv.querySelector('.a') as HTMLElement; const buttonB = topLevelDiv.querySelector('.b') as HTMLElement; expect(focusTrapZoneFocusStack.length).toBe(2); const baseFocusTrapZone = focusTrapZoneFocusStack[0]; expect(baseFocusTrapZone.props.forceFocusInsideTrapOnOutsideFocus).toBe(true); expect(baseFocusTrapZone.props.isClickableOutsideFocusTrap).toBe(false); const firstFocusTrapZone = focusTrapZoneFocusStack[1]; expect(firstFocusTrapZone.props.forceFocusInsideTrapOnOutsideFocus).toBe(false); expect(firstFocusTrapZone.props.isClickableOutsideFocusTrap).toBe(false); // There should be now 3 focus trap zones (base/first/second) ReactTestUtils.Simulate.click(buttonB); expect(focusTrapZoneFocusStack.length).toBe(3); expect(focusTrapZoneFocusStack[0]).toBe(baseFocusTrapZone); expect(focusTrapZoneFocusStack[1]).toBe(firstFocusTrapZone); const secondFocusTrapZone = focusTrapZoneFocusStack[2]; expect(secondFocusTrapZone.props.forceFocusInsideTrapOnOutsideFocus).toBe(false); expect(secondFocusTrapZone.props.isClickableOutsideFocusTrap).toBe(true); // we remove the middle one // unmounting a focus trap zone should remove it from the focus stack. // but we also check that it removes the right focustrapzone (the middle one) ReactTestUtils.Simulate.click(buttonA); focusTrapZoneFocusStack = getFocusStack(); expect(focusTrapZoneFocusStack.length).toBe(2); expect(focusTrapZoneFocusStack[0]).toBe(baseFocusTrapZone); expect(focusTrapZoneFocusStack[1]).toBe(secondFocusTrapZone); // finally remove the last focus trap zone. ReactTestUtils.Simulate.click(buttonB); focusTrapZoneFocusStack = getFocusStack(); expect(focusTrapZoneFocusStack.length).toBe(1); expect(focusTrapZoneFocusStack[0]).toBe(baseFocusTrapZone); }); }); });
{ "pile_set_name": "Github" }
# Created by: Sean Farley <sean-freebsd@farley.org> # $FreeBSD$ PORTNAME= Mknod PORTVERSION= 0.02 PORTREVISION= 1 CATEGORIES= devel perl5 MASTER_SITES= CPAN MASTER_SITE_SUBDIR= CPAN:RLZWART PKGNAMEPREFIX= p5- MAINTAINER= sean-freebsd@farley.org COMMENT= Perl module interface to the mknod(2) system call USES= perl5 USE_PERL5= configure MANPREFIX= ${PREFIX}/${SITE_PERL_REL} .include <bsd.port.mk>
{ "pile_set_name": "Github" }
<?php /* Copyright (c) 2012, Open Source Solutions Limited, Dublin, Ireland All rights reserved. Contact: Barry O'Donovan - barry (at) opensolutions (dot) ie http://www.opensolutions.ie/ This file is part of the OSS_SNMP package. 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 Open Source Solutions Limited 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. */ namespace OSS_SNMP\MIBS; /** * A class for performing SNMP V2 queries on generic devices * * @copyright Copyright (c) 2012, Open Source Solutions Limited, Dublin, Ireland * @author Barry O'Donovan <barry@opensolutions.ie> */ class Iface extends \OSS_SNMP\MIB { const OID_IF_NUMBER = '.1.3.6.1.2.1.2.1.0'; const OID_IF_INDEX = '.1.3.6.1.2.1.2.2.1.1'; const OID_IF_DESCRIPTION = '.1.3.6.1.2.1.2.2.1.2'; const OID_IF_TYPE = '.1.3.6.1.2.1.2.2.1.3'; const OID_IF_MTU = '.1.3.6.1.2.1.2.2.1.4'; const OID_IF_SPEED = '.1.3.6.1.2.1.2.2.1.5'; const OID_IF_PHYS_ADDRESS = '.1.3.6.1.2.1.2.2.1.6'; const OID_IF_ADMIN_STATUS = '.1.3.6.1.2.1.2.2.1.7'; const OID_IF_OPER_STATUS = '.1.3.6.1.2.1.2.2.1.8'; const OID_IF_LAST_CHANGE = '.1.3.6.1.2.1.2.2.1.9'; const OID_IF_IN_OCTETS = '.1.3.6.1.2.1.2.2.1.10'; const OID_IF_IN_UNICAST_PACKETS = '.1.3.6.1.2.1.2.2.1.11'; const OID_IF_IN_NON_UNICAST_PACKETS = '.1.3.6.1.2.1.2.2.1.12'; const OID_IF_IN_DISCARDS = '.1.3.6.1.2.1.2.2.1.13'; const OID_IF_IN_ERRORS = '.1.3.6.1.2.1.2.2.1.14'; const OID_IF_IN_UNKNOWN_PROTOCOLS = '.1.3.6.1.2.1.2.2.1.15'; const OID_IF_OUT_OCTETS = '.1.3.6.1.2.1.2.2.1.16'; const OID_IF_OUT_UNICAST_PACKETS = '.1.3.6.1.2.1.2.2.1.17'; const OID_IF_OUT_NON_UNICAST_PACKETS = '.1.3.6.1.2.1.2.2.1.18'; const OID_IF_OUT_DISCARDS = '.1.3.6.1.2.1.2.2.1.19'; const OID_IF_OUT_ERRORS = '.1.3.6.1.2.1.2.2.1.20'; const OID_IF_OUT_QUEUE_LENGTH = '.1.3.6.1.2.1.2.2.1.21'; const OID_IF_NAME = '.1.3.6.1.2.1.31.1.1.1.1'; const OID_IF_HIGH_SPEED = '.1.3.6.1.2.1.31.1.1.1.15'; const OID_IF_ALIAS = '.1.3.6.1.2.1.31.1.1.1.18'; /** * Get the number of network interfaces (regardless of * their current state) present on this system. * * @return int The number of network interfaces on the system */ public function numberOfInterfaces() { return $this->getSNMP()->get( self::OID_IF_NUMBER ); } /** * Get an array of device MTUs * * @return array An array of device MTUs */ public function mtus() { return $this->getSNMP()->walk1d( self::OID_IF_MTU ); } /** * Get an array of the interfaces' physical addresses * * "The interface's address at the protocol layer * immediately `below' the network layer in the * protocol stack. For interfaces which do not have * such an address (e.g., a serial line), this object * should contain an octet string of zero length." * * @return array An array of device physical addresses */ public function physAddresses() { $pa = $this->getSNMP()->walk1d( self::OID_IF_PHYS_ADDRESS ); // some switches return leading '00:' as '0:' - we correct this here: foreach( $pa as $i => $a ) if( strpos( $a, ':' ) == 1 ) $pa[ $i ] = '0' . $a; return $pa; } /** * Constant for possible value of interface admin status. * @see adminStates() */ const IF_ADMIN_STATUS_UP = 1; /** * Constant for possible value of interface admin status. * @see adminStates() */ const IF_ADMIN_STATUS_DOWN = 2; /** * Constant for possible value of interface admin status. * @see adminStates() */ const IF_ADMIN_STATUS_TESTING = 3; /** * Text representation of interface admin status. * * @see adminStates() * @var array Text representations of interface admin status. */ public static $IF_ADMIN_STATES = array( self::IF_ADMIN_STATUS_UP => 'up', self::IF_ADMIN_STATUS_DOWN => 'down', self::IF_ADMIN_STATUS_TESTING => 'testing' ); /** * Get an array of device interface admin status (up / down) * * E.g. the follow SNMP output yields the shown array: * * .1.3.6.1.2.1.2.2.1.7.10128 = INTEGER: up(1) * .1.3.6.1.2.1.2.2.1.7.10129 = INTEGER: down(2) * ... * * [10128] => 1 * [10129] => 2 * * @see IF_ADMIN_STATES * @param boolean $translate If true, return the string representation * @return array An array of interface admin states */ public function adminStates( $translate = false ) { $states = $this->getSNMP()->walk1d( self::OID_IF_ADMIN_STATUS ); if( !$translate ) return $states; return $this->getSNMP()->translate( $states, self::$IF_ADMIN_STATES ); } /** * Get an array of device interface last change times * * Value returned is timeticks (one hundreds of a second) * * "The value of sysUpTime at the time the interface * entered its current operational state. If the * current state was entered prior to the last re- * initialization of the local network management * subsystem, then this object contains a zero * value." * * @see \OSS_SNMP\MIBS\System::uptime() * @param bool $asUnixTimestamp Poll sysUpTime and use this to return a timestamp of the last change * @return array Timeticks (or zero) since last change of the interfaces */ public function lastChanges( $asUnixTimestamp = false ) { $lc = $this->getSNMP()->walk1d( self::OID_IF_LAST_CHANGE ); if( $asUnixTimestamp ) { $sysUptime = $this->getSNMP()->useSystem()->uptime() / 100; foreach( $lc as $i => $t ) if( $t ) $lc[$i] = intval( floor( time() - $sysUptime + ( $t / 100 ) ) ); } return $lc; } /** * Get an array of device interface in octets * * "The total number of octets received on the * interface, including framing characters." * * @return array The total number of octets received on interfaces */ public function inOctets() { return $this->getSNMP()->walk1d( self::OID_IF_IN_OCTETS ); } /** * Get an array of device interface unicast packets in * * "The number of subnetwork-unicast packets * delivered to a higher-layer protocol." * * @return array The total number of unicast packets received on interfaces */ public function inUnicastPackets() { return $this->getSNMP()->walk1d( self::OID_IF_IN_UNICAST_PACKETS ); } /** * Get an array of device interface non-unicast packets in * * "The number of non-unicast (i.e., subnetwork- * broadcast or subnetwork-multicast) packets * delivered to a higher-layer protocol." * * @return array The total number of non-unicast packets received on interfaces */ public function inNonUnicastPackets() { return $this->getSNMP()->walk1d( self::OID_IF_IN_NON_UNICAST_PACKETS ); } /** * Get an array of device interface inbound discarded packets * * "The number of inbound packets which were chosen * to be discarded even though no errors had been * detected to prevent their being deliverable to a * higher-layer protocol. One possible reason for * discarding such a packet could be to free up * buffer space." * * @return arrary The total number of discarded inbound packets received on interfaces */ public function inDiscards() { return $this->getSNMP()->walk1d( self::OID_IF_IN_DISCARDS ); } /** * Get an array of device interface inbound error packets * * "The number of inbound packets that contained * errors preventing them from being deliverable to a * higher-layer protocol." * * @return array The total number of error inbound packets received on interfaces */ public function inErrors() { return $this->getSNMP()->walk1d( self::OID_IF_IN_ERRORS ); } /** * Get an array of device interface out octets * * "The total number of octets transmitted out of the * interface, including framing characters." * * @return array The total number of octets transmitted on interfaces */ public function outOctets() { return $this->getSNMP()->walk1d( self::OID_IF_OUT_OCTETS ); } /** * Get an array of device interface unicast packets out * * "The total number of packets that higher-level * protocols requested be transmitted to a * subnetwork-unicast address, including those that * were discarded or not sent." * * @return array The total number of unicast packets transmitted on interfaces */ public function outUnicastPackets() { return $this->getSNMP()->walk1d( self::OID_IF_OUT_UNICAST_PACKETS ); } /** * Get an array of device interface non-unicast packets out * * "The total number of packets that higher-level * protocols requested be transmitted to a non- * unicast (i.e., a subnetwork-broadcast or * subnetwork-multicast) address, including those * that were discarded or not sent." * * @return array The total number of non-unicast packets requested sent interfaces */ public function outNonUnicastPackets() { return $this->getSNMP()->walk1d( self::OID_IF_OUT_NON_UNICAST_PACKETS ); } /** * Get an array of device interface outbound discarded packets * * "The number of outbound packets which were chosen * to be discarded even though no errors had been * detected to prevent their being transmitted. One * possible reason for discarding such a packet could * be to free up buffer space." * * @return arrary The total number of discarded outbound packets */ public function outDiscards() { return $this->getSNMP()->walk1d( self::OID_IF_OUT_DISCARDS ); } /** * Get an array of device interface outbound error packets * * "The number of outbound packets that could not be * transmitted because of errors." * * @return array The total number of error outbound packets received on interfaces */ public function outErrors() { return $this->getSNMP()->walk1d( self::OID_IF_OUT_ERRORS ); } /** * Get an array of interface outbound queue lengths * * "The length of the output packet queue (in packets)" * * @return array The total number of packets in the outbound queues */ public function outQueueLength() { return $this->getSNMP()->walk1d( self::OID_IF_OUT_QUEUE_LENGTH ); } /** * Get an array of packets received on an interface of unknown protocol * * "The number of packets received via the interface * which were discarded because of an unknown or * unsupported protocol." * * @return array The number of packets received on an interface of unknown protocol */ public function inUnknownProtocols() { return $this->getSNMP()->walk1d( self::OID_IF_IN_UNKNOWN_PROTOCOLS ); } /** * Get an array of device interface indexes * * E.g. the following SNMP output yields the shown array: * * .1.3.6.1.2.1.2.2.1.1 = INTEGER: 1 * .1.3.6.1.2.1.2.2.1.2 = INTEGER: 2 * ... * * [1] => 1 * [2] => 2 * * @return array An array of interface indexes */ public function indexes() { return $this->getSNMP()->walk1d( self::OID_IF_INDEX ); } /** * Get an array of device interface names * * E.g. the following SNMP output yields the shown array: * * .1.3.6.1.2.1.31.1.1.1.1.10128 = STRING: Gi1/0/28 * .1.3.6.1.2.1.31.1.1.1.1.10129 = STRING: Gi1/0/29 * ... * * [10128] => "Gi1/0/28" * [10129] => "Gi1/0/29" * * @return array An array of interface names */ public function names() { return $this->getSNMP()->walk1d( self::OID_IF_NAME ); } /** * Get an array of device interface aliases (e.g. as set by the interface description / port-name parameter) * * E.g. the followig SNMP output yields the shown array: * * .1.3.6.1.2.1.2.2.1.2.18.10128 = STRING: Connection to switch2 * .1.3.6.1.2.1.2.2.1.2.18.10129 = STRING: Connection to switch3 * ... * * [10128] => "Connection to switch2" * [10129] => "Connection to switch3" * * @return array An array of interface aliases */ public function aliases() { return $this->getSNMP()->walk1d( self::OID_IF_ALIAS ); } /** * Get an array of device interface descriptions * * E.g. the following SNMP output yields the shown array: * * .1.3.6.1.2.1.31.1.1.1.1.10128 = STRING: GigabitEthernet1/0/28 * .1.3.6.1.2.1.31.1.1.1.1.10129 = STRING: GigabitEthernet1/0/29 * ... * * [10128] => "GigabitEthernet1/0/28" * [10129] => "GigabitEthernet1/0/29" * * @return array An array of interface descriptions */ public function descriptions() { return $this->getSNMP()->walk1d( self::OID_IF_DESCRIPTION ); } /** * Get an array of device interface (operating) speeds * * E.g. the following SNMP output yields the shown array: * * .1.3.6.1.2.1.2.2.1.5.10128 = Gauge32: 1000000000 * .1.3.6.1.2.1.2.2.1.5.10129 = Gauge32: 100000000 * ... * * [10128] => 1000000000 * [10129] => 100000000 * * NB: operating speed as opposed to maximum speed * * **WARNING:** This is a 32 bit int so it cannot represent 10Gb * links. These would show up as: * * [10127] => 4294967295 * * Instead, use highSpeeds() which will represent the speed as Mbps * * @see highSpeeds() * @return array An array of interface operating speeds */ public function speeds() { return $this->getSNMP()->walk1d( self::OID_IF_SPEED ); } /** * Get an array of device interface (operating) speeds * * From Cisco: * * > "An estimate of the interface's current bandwidth in units * > of 1,000,000 bits per second. If this object reports a * > value of `n' then the speed of the interface is somewhere in * > the range of `n-500,000' to `n+499,999'. For interfaces * > which do not vary in bandwidth or for those where no * > accurate estimation can be made, this object should contain * > the nominal bandwidth. For a sub-layer which has no concept * > of bandwidth, this object should be zero." * * E.g. the following SNMP output yields the shown array: * * .1.3.6.1.2.1.2.2.1.5.10127 = Gauge32: 10000 * .1.3.6.1.2.1.2.2.1.5.10128 = Gauge32: 1000 * .1.3.6.1.2.1.2.2.1.5.10129 = Gauge32: 100 * ... * * [10127] => 10000000000 * [10128] => 1000000000 * [10129] => 100000000 * * @return array An array of interface operating speeds */ public function highSpeeds() { return $this->getSNMP()->walk1d( self::OID_IF_HIGH_SPEED ); } /** * Constant for possible value of interface operation status. * @see operationStates() */ const IF_OPER_STATUS_UP = 1; /** * Constant for possible value of interface operation status. * @see operationStates() */ const IF_OPER_STATUS_DOWN = 2; /** * Constant for possible value of interface operation status. * @see operationStates() */ const IF_OPER_STATUS_TESTING = 3; /** * Constant for possible value of interface operation status. * @see operationStates() */ const IF_OPER_STATUS_UNKNOWN = 4; /** * Constant for possible value of interface operation status. * @see operationStates() */ const IF_OPER_STATUS_DORMANT = 5; /** * Constant for possible value of interface operation status. * @see operationStates() */ const IF_OPER_STATUS_NOT_PRESENT = 6; /** * Constant for possible value of interface operation status. * @see operationStates() */ const IF_OPER_STATUS_LOWER_LAYER_DOWN = 7; /** * Text representation of interface operating status. * * @see operationStates() * @var array Text representations of interface operating status. */ public static $IF_OPER_STATES = array( self::IF_OPER_STATUS_UP => 'up', self::IF_OPER_STATUS_DOWN => 'down', self::IF_OPER_STATUS_TESTING => 'testing', self::IF_OPER_STATUS_UNKNOWN => 'unknown', self::IF_OPER_STATUS_DORMANT => 'dormant', self::IF_OPER_STATUS_NOT_PRESENT => 'notPresent', self::IF_OPER_STATUS_LOWER_LAYER_DOWN => 'lowerLayerDown' ); /** * Get an array of device interface operating status (up / down) * * E.g. the follow SNMP output yields the shown array: * * .1.3.6.1.2.1.2.2.1.8.10128 = INTEGER: up(1) * .1.3.6.1.2.1.2.2.1.8.10129 = INTEGER: down(2) * ... * * [10128] => 1 * [10129] => 2 * * @see IF_OPER_STATES * @param boolean $translate If true, return the string representation * @return array An array of interface states */ public function operationStates( $translate = false ) { $states = $this->getSNMP()->walk1d( self::OID_IF_OPER_STATUS ); if( !$translate ) return $states; return $this->getSNMP()->translate( $states, self::$IF_OPER_STATES ); } /** * Constant for possible type of an interface * @see types() */ const IF_TYPE_OTHER = 1; /** * Constant for possible type of an interface * @see types() */ const IF_TYPE_REGULAR1822 = 2; /** * Constant for possible type of an interface * @see types() */ const IF_TYPE_HDH1822 = 3; /** * Constant for possible type of an interface * @see types() */ const IF_TYPE_DDNX25 = 4; /** * Constant for possible type of an interface * @see types() */ const IF_TYPE_RFC877X25 = 5; /** * Constant for possible type of an interface * @see types() */ const IF_TYPE_ETHERNETCSMACD = 6; /** * Constant for possible type of an interface * @see types() */ const IF_TYPE_ISO88023CSMACD = 7; /** * Constant for possible type of an interface * @see types() */ const IF_TYPE_ISO88024TOKENBUS = 8; /** * Constant for possible type of an interface * @see types() */ const IF_TYPE_ISO88025TOKENRING = 9; /** * Constant for possible type of an interface * @see types() */ const IF_TYPE_ISO88026MAN = 10; /** * Constant for possible type of an interface * @see types() */ const IF_TYPE_STARLAN = 11; /** * Constant for possible type of an interface * @see types() */ const IF_TYPE_PROTEON10MBIT = 12; /** * Constant for possible type of an interface * @see types() */ const IF_TYPE_PROTEON80MBIT = 13; /** * Constant for possible type of an interface * @see types() */ const IF_TYPE_HYPERCHANNEL = 14; /** * Constant for possible type of an interface * @see types() */ const IF_TYPE_FDDI = 15; /** * Constant for possible type of an interface * @see types() */ const IF_TYPE_LAPB = 16; /** * Constant for possible type of an interface * @see types() */ const IF_TYPE_SDLC = 17; /** * Constant for possible type of an interface * @see types() */ const IF_TYPE_DS1 = 18; /** * Constant for possible type of an interface * @see types() */ const IF_TYPE_E1 = 19; /** * Constant for possible type of an interface * @see types() */ const IF_TYPE_BASICISDN = 20; /** * Constant for possible type of an interface * @see types() */ const IF_TYPE_PRIMARYISDN = 21; /** * Constant for possible type of an interface * @see types() */ const IF_TYPE_PROPPOINTTOPOINTSERIAL = 22; /** * Constant for possible type of an interface * @see types() */ const IF_TYPE_PPP = 23; /** * Constant for possible type of an interface * @see types() */ const IF_TYPE_SOFTWARELOOPBACK = 24; /** * Constant for possible type of an interface * @see types() */ const IF_TYPE_EON = 25; /** * Constant for possible type of an interface * @see types() */ const IF_TYPE_ETHERNET3MBIT = 26; /** * Constant for possible type of an interface * @see types() */ const IF_TYPE_NSIP = 27; /** * Constant for possible type of an interface * @see types() */ const IF_TYPE_SLIP = 28; /** * Constant for possible type of an interface * @see types() */ const IF_TYPE_ULTRA = 29; /** * Constant for possible type of an interface * @see types() */ const IF_TYPE_DS3 = 30; /** * Constant for possible type of an interface * @see types() */ const IF_TYPE_SIP = 31; /** * Constant for possible type of an interface * @see types() */ const IF_TYPE_FRAMERELAY = 32; /** * Constant for possible type of an interface * @see types() */ const IF_TYPE_RS232 = 33; /** * Constant for possible type of an interface * @see types() */ const IF_TYPE_PARA = 34; /** * Constant for possible type of an interface * @see types() */ const IF_TYPE_ARCNET = 35; /** * Constant for possible type of an interface * @see types() */ const IF_TYPE_ARCNETPLUS = 36; /** * Constant for possible type of an interface * @see types() */ const IF_TYPE_ATM = 37; /** * Constant for possible type of an interface * @see types() */ const IF_TYPE_MIOX25 = 38; /** * Constant for possible type of an interface * @see types() */ const IF_TYPE_SONET = 39; /** * Constant for possible type of an interface * @see types() */ const IF_TYPE_X25PLE = 40; /** * Constant for possible type of an interface * @see types() */ const IF_TYPE_ISO88022LLC = 41; /** * Constant for possible type of an interface * @see types() */ const IF_TYPE_LOCALTALK = 42; /** * Constant for possible type of an interface * @see types() */ const IF_TYPE_SMDSDXI = 43; /** * Constant for possible type of an interface * @see types() */ const IF_TYPE_FRAMERELAYSERVICE = 44; /** * Constant for possible type of an interface * @see types() */ const IF_TYPE_V35 = 45; /** * Constant for possible type of an interface * @see types() */ const IF_TYPE_HSSI = 46; /** * Constant for possible type of an interface * @see types() */ const IF_TYPE_HIPPI = 47; /** * Constant for possible type of an interface * @see types() */ const IF_TYPE_MODEM = 48; /** * Constant for possible type of an interface * @see types() */ const IF_TYPE_AAL5 = 49; /** * Constant for possible type of an interface * @see types() */ const IF_TYPE_SONETPATH = 50; /** * Constant for possible type of an interface * @see types() */ const IF_TYPE_SONETVT = 51; /** * Constant for possible type of an interface * @see types() */ const IF_TYPE_SMDSICIP = 52; /** * Constant for possible type of an interface * @see types() */ const IF_TYPE_PROPVIRTUAL = 53; /** * Constant for possible type of an interface * @see types() */ const IF_TYPE_PROPMULTIPLEXOR = 54; /** * Constant for possible type of an interface * @see types() */ const IF_TYPE_IEEE80212 = 55; /** * Constant for possible type of an interface * @see types() */ const IF_TYPE_FIBRECHANNEL = 56; /** * Constant for possible type of an interface * @see types() */ const IF_TYPE_HIPPIINTERFACE = 57; /** * Constant for possible type of an interface * @see types() */ const IF_TYPE_FRAMERELAYINTERCONNECT = 58; /** * Constant for possible type of an interface * @see types() */ const IF_TYPE_AFLANE8023 = 59; /** * Constant for possible type of an interface * @see types() */ const IF_TYPE_AFLANE8025 = 60; /** * Constant for possible type of an interface * @see types() */ const IF_TYPE_CCTEMUL = 61; /** * Constant for possible type of an interface * @see types() */ const IF_TYPE_FASTETHER = 62; /** * Constant for possible type of an interface * @see types() */ const IF_TYPE_ISDN = 63; /** * Constant for possible type of an interface * @see types() */ const IF_TYPE_V11 = 64; /** * Constant for possible type of an interface * @see types() */ const IF_TYPE_V36 = 65; /** * Constant for possible type of an interface * @see types() */ const IF_TYPE_G703AT64K = 66; /** * Constant for possible type of an interface * @see types() */ const IF_TYPE_G703AT2MB = 67; /** * Constant for possible type of an interface * @see types() */ const IF_TYPE_QLLC = 68; /** * Constant for possible type of an interface * @see types() */ const IF_TYPE_FASTETHERFX = 69; /** * Constant for possible type of an interface * @see types() */ const IF_TYPE_CHANNEL = 70; /** * Constant for possible type of an interface * @see types() */ const IF_TYPE_IEEE80211 = 71; /** * Constant for possible type of an interface * @see types() */ const IF_TYPE_IBM370PARCHAN = 72; /** * Constant for possible type of an interface * @see types() */ const IF_TYPE_ESCON = 73; /** * Constant for possible type of an interface * @see types() */ const IF_TYPE_DLSW = 74; /** * Constant for possible type of an interface * @see types() */ const IF_TYPE_ISDNS = 75; /** * Constant for possible type of an interface * @see types() */ const IF_TYPE_ISDNU = 76; /** * Constant for possible type of an interface * @see types() */ const IF_TYPE_LAPD = 77; /** * Constant for possible type of an interface * @see types() */ const IF_TYPE_IPSWITCH = 78; /** * Constant for possible type of an interface * @see types() */ const IF_TYPE_RSRB = 79; /** * Constant for possible type of an interface * @see types() */ const IF_TYPE_ATMLOGICAL = 80; /** * Constant for possible type of an interface * @see types() */ const IF_TYPE_DS0 = 81; /** * Constant for possible type of an interface * @see types() */ const IF_TYPE_DS0BUNDLE = 82; /** * Constant for possible type of an interface * @see types() */ const IF_TYPE_BSC = 83; /** * Constant for possible type of an interface * @see types() */ const IF_TYPE_ASYNC = 84; /** * Constant for possible type of an interface * @see types() */ const IF_TYPE_CNR = 85; /** * Constant for possible type of an interface * @see types() */ const IF_TYPE_ISO88025DTR = 86; /** * Constant for possible type of an interface * @see types() */ const IF_TYPE_EPLRS = 87; /** * Constant for possible type of an interface * @see types() */ const IF_TYPE_ARAP = 88; /** * Constant for possible type of an interface * @see types() */ const IF_TYPE_PROPCNLS = 89; /** * Constant for possible type of an interface * @see types() */ const IF_TYPE_HOSTPAD = 90; /** * Constant for possible type of an interface * @see types() */ const IF_TYPE_TERMPAD = 91; /** * Constant for possible type of an interface * @see types() */ const IF_TYPE_FRAMERELAYMPI = 92; /** * Constant for possible type of an interface * @see types() */ const IF_TYPE_X213 = 93; /** * Constant for possible type of an interface * @see types() */ const IF_TYPE_ADSL = 94; /** * Constant for possible type of an interface * @see types() */ const IF_TYPE_RADSL = 95; /** * Constant for possible type of an interface * @see types() */ const IF_TYPE_SDSL = 96; /** * Constant for possible type of an interface * @see types() */ const IF_TYPE_VDSL = 97; /** * Constant for possible type of an interface * @see types() */ const IF_TYPE_ISO88025CRFPINT = 98; /** * Constant for possible type of an interface * @see types() */ const IF_TYPE_MYRINET = 99; /** * Constant for possible type of an interface * @see types() */ const IF_TYPE_VOICEEM = 100; /** * Constant for possible type of an interface * @see types() */ const IF_TYPE_VOICEFXO = 101; /** * Constant for possible type of an interface * @see types() */ const IF_TYPE_VOICEFXS = 102; /** * Constant for possible type of an interface * @see types() */ const IF_TYPE_VOICEENCAP = 103; /** * Constant for possible type of an interface * @see types() */ const IF_TYPE_VOICEOVERIP = 104; /** * Constant for possible type of an interface * @see types() */ const IF_TYPE_ATMDXI = 105; /** * Constant for possible type of an interface * @see types() */ const IF_TYPE_ATMFUNI = 106; /** * Constant for possible type of an interface * @see types() */ const IF_TYPE_ATMIMA = 107; /** * Constant for possible type of an interface * @see types() */ const IF_TYPE_PPPMULTILINKBUNDLE = 108; /** * Constant for possible type of an interface * @see types() */ const IF_TYPE_IPOVERCDLC = 109; /** * Constant for possible type of an interface * @see types() */ const IF_TYPE_IPOVERCLAW = 110; /** * Constant for possible type of an interface * @see types() */ const IF_TYPE_STACKTOSTACK = 111; /** * Constant for possible type of an interface * @see types() */ const IF_TYPE_VIRTUALIPADDRESS = 112; /** * Constant for possible type of an interface * @see types() */ const IF_TYPE_MPC = 113; /** * Constant for possible type of an interface * @see types() */ const IF_TYPE_IPOVERATM = 114; /** * Constant for possible type of an interface * @see types() */ const IF_TYPE_ISO88025FIBER = 115; /** * Constant for possible type of an interface * @see types() */ const IF_TYPE_TDLC = 116; /** * Constant for possible type of an interface * @see types() */ const IF_TYPE_GIGABITETHERNET = 117; /** * Constant for possible type of an interface * @see types() */ const IF_TYPE_HDLC = 118; /** * Constant for possible type of an interface * @see types() */ const IF_TYPE_LAPF = 119; /** * Constant for possible type of an interface * @see types() */ const IF_TYPE_V37 = 120; /** * Constant for possible type of an interface * @see types() */ const IF_TYPE_X25MLP = 121; /** * Constant for possible type of an interface * @see types() */ const IF_TYPE_X25HUNTGROUP = 122; /** * Constant for possible type of an interface * @see types() */ const IF_TYPE_TRASNPHDLC = 123; /** * Constant for possible type of an interface * @see types() */ const IF_TYPE_INTERLEAVE = 124; /** * Constant for possible type of an interface * @see types() */ const IF_TYPE_FAST = 125; /** * Constant for possible type of an interface * @see types() */ const IF_TYPE_IP = 126; /** * Constant for possible type of an interface * @see types() */ const IF_TYPE_DOCSCABLEMACLAYER = 127; /** * Constant for possible type of an interface * @see types() */ const IF_TYPE_DOCSCABLEDOWNSTREAM = 128; /** * Constant for possible type of an interface * @see types() */ const IF_TYPE_DOCSCABLEUPSTREAM = 129; /** * Constant for possible type of an interface * @see types() */ const IF_TYPE_A12MPPSWITCH = 130; /** * Constant for possible type of an interface * @see types() */ const IF_TYPE_TUNNEL = 131; /** * Constant for possible type of an interface * @see types() */ const IF_TYPE_COFFEE = 132; /** * Constant for possible type of an interface * @see types() */ const IF_TYPE_CES = 133; /** * Constant for possible type of an interface * @see types() */ const IF_TYPE_ATMSUBINTERFACE = 134; /** * Constant for possible type of an interface * @see types() */ const IF_TYPE_L2VLAN = 135; /** * Constant for possible type of an interface * @see types() */ const IF_TYPE_L3IPVLAN = 136; /** * Constant for possible type of an interface * @see types() */ const IF_TYPE_L3IPXVLAN = 137; /** * Constant for possible type of an interface * @see types() */ const IF_TYPE_DIGITALPOWERLINE = 138; /** * Constant for possible type of an interface * @see types() */ const IF_TYPE_MEDIAMAILOVERIP = 139; /** * Constant for possible type of an interface * @see types() */ const IF_TYPE_DTM = 140; /** * Constant for possible type of an interface * @see types() */ const IF_TYPE_DCN = 141; /** * Constant for possible type of an interface * @see types() */ const IF_TYPE_IPFORWARD = 142; /** * Constant for possible type of an interface * @see types() */ const IF_TYPE_MSDSL = 143; /** * Constant for possible type of an interface * @see types() */ const IF_TYPE_IEEE1394 = 144; /** * Constant for possible type of an interface * @see types() */ const IF_TYPE_IF_GSN = 145; /** * Constant for possible type of an interface * @see types() */ const IF_TYPE_DVBRCCMACLAYER = 146; /** * Constant for possible type of an interface * @see types() */ const IF_TYPE_DVBRCCDOWNSTREAM = 147; /** * Constant for possible type of an interface * @see types() */ const IF_TYPE_DVBRCCUPSTREAM = 148; /** * Constant for possible type of an interface * @see types() */ const IF_TYPE_ATMVIRTUAL = 149; /** * Constant for possible type of an interface * @see types() */ const IF_TYPE_MPLSTUNNEL = 150; /** * Constant for possible type of an interface * @see types() */ const IF_TYPE_SRP = 151; /** * Constant for possible type of an interface * @see types() */ const IF_TYPE_VOICEOVERATM = 152; /** * Constant for possible type of an interface * @see types() */ const IF_TYPE_VOICEOVERFRAMERELAY = 153; /** * Constant for possible type of an interface * @see types() */ const IF_TYPE_IDSL = 154; /** * Constant for possible type of an interface * @see types() */ const IF_TYPE_COMPOSITELINK = 155; /** * Constant for possible type of an interface * @see types() */ const IF_TYPE_SS7SIGLINK = 156; /** * Constant for possible type of an interface * @see types() */ const IF_TYPE_PROPWIRELESSP2P = 157; /** * Constant for possible type of an interface * @see types() */ const IF_TYPE_FRFORWARD = 158; /** * Constant for possible type of an interface * @see types() */ const IF_TYPE_RFC1483 = 159; /** * Constant for possible type of an interface * @see types() */ const IF_TYPE_USB = 160; /** * Constant for possible type of an interface * @see types() */ const IF_TYPE_IEEE8023ADLAG = 161; /** * Constant for possible type of an interface * @see types() */ const IF_TYPE_BGPPOLICYACCOUNTING = 162; /** * Constant for possible type of an interface * @see types() */ const IF_TYPE_FRF16MFRBUNDLE = 163; /** * Constant for possible type of an interface * @see types() */ const IF_TYPE_H323GATEKEEPER = 164; /** * Constant for possible type of an interface * @see types() */ const IF_TYPE_H323PROXY = 165; /** * Constant for possible type of an interface * @see types() */ const IF_TYPE_MPLS = 166; /** * Constant for possible type of an interface * @see types() */ const IF_TYPE_MFSIGLINK = 167; /** * Constant for possible type of an interface * @see types() */ const IF_TYPE_HDSL2 = 168; /** * Constant for possible type of an interface * @see types() */ const IF_TYPE_SHDSL = 169; /** * Constant for possible type of an interface * @see types() */ const IF_TYPE_DS1FDL = 170; /** * Constant for possible type of an interface * @see types() */ const IF_TYPE_POS = 171; /** * Constant for possible type of an interface * @see types() */ const IF_TYPE_DVBASIIN = 172; /** * Constant for possible type of an interface * @see types() */ const IF_TYPE_DVBASIOUT = 173; /** * Constant for possible type of an interface * @see types() */ const IF_TYPE_PLC = 174; /** * Constant for possible type of an interface * @see types() */ const IF_TYPE_NFAS = 175; /** * Constant for possible type of an interface * @see types() */ const IF_TYPE_TR008 = 176; /** * Constant for possible type of an interface * @see types() */ const IF_TYPE_GR303RDT = 177; /** * Constant for possible type of an interface * @see types() */ const IF_TYPE_GR303IDT = 178; /** * Constant for possible type of an interface * @see types() */ const IF_TYPE_ISUP = 179; /** * Constant for possible type of an interface * @see types() */ const IF_TYPE_PROPDOCSWIRELESSMACLAYER = 180; /** * Constant for possible type of an interface * @see types() */ const IF_TYPE_PROPDOCSWIRELESSDOWNSTREAM = 181; /** * Constant for possible type of an interface * @see types() */ const IF_TYPE_PROPDOCSWIRELESSUPSTREAM = 182; /** * Constant for possible type of an interface * @see types() */ const IF_TYPE_HIPERLAN2 = 183; /** * Constant for possible type of an interface * @see types() */ const IF_TYPE_PROPBWAP2MP = 184; /** * Constant for possible type of an interface * @see types() */ const IF_TYPE_SONETOVERHEADCHANNEL = 185; /** * Constant for possible type of an interface * @see types() */ const IF_TYPE_DIGITALWRAPPEROVERHEADCHANNEL = 186; /** * Constant for possible type of an interface * @see types() */ const IF_TYPE_AAL2 = 187; /** * Constant for possible type of an interface * @see types() */ const IF_TYPE_RADIOMAC = 188; /** * Constant for possible type of an interface * @see types() */ const IF_TYPE_ATMRADIO = 189; /** * Constant for possible type of an interface * @see types() */ const IF_TYPE_IMT = 190; /** * Constant for possible type of an interface * @see types() */ const IF_TYPE_MVL = 191; /** * Constant for possible type of an interface * @see types() */ const IF_TYPE_REACHDSL = 192; /** * Constant for possible type of an interface * @see types() */ const IF_TYPE_FRDLCIENDPT = 193; /** * Constant for possible type of an interface * @see types() */ const IF_TYPE_ATMVCIENDPT = 194; /** * Constant for possible type of an interface * @see types() */ const IF_TYPE_OPTICALCHANNEL = 195; /** * Constant for possible type of an interface * @see types() */ const IF_TYPE_OPTICALTRANSPORT = 196; /** * Constant for possible type of an interface * @see types() */ const IF_TYPE_PROPATM = 197; /** * Constant for possible type of an interface * @see types() */ const IF_TYPE_VOICEOVERCABLE = 198; /** * Constant for possible type of an interface * @see types() */ const IF_TYPE_INFINIBAND = 199; /** * Constant for possible type of an interface * @see types() */ const IF_TYPE_TELINK = 200; /** * Constant for possible type of an interface * @see types() */ const IF_TYPE_Q2931 = 201; /** * Constant for possible type of an interface * @see types() */ const IF_TYPE_VIRTUALTG = 202; /** * Constant for possible type of an interface * @see types() */ const IF_TYPE_SIPTG = 203; /** * Constant for possible type of an interface * @see types() */ const IF_TYPE_SIPSIG = 204; /** * Constant for possible type of an interface * @see types() */ const IF_TYPE_DOCSCABLEUPSTREAMCHANNEL = 205; /** * Constant for possible type of an interface * @see types() */ const IF_TYPE_ECONET = 206; /** * Constant for possible type of an interface * @see types() */ const IF_TYPE_PON155 = 207; /** * Constant for possible type of an interface * @see types() */ const IF_TYPE_PON622 = 208; /** * Constant for possible type of an interface * @see types() */ const IF_TYPE_BRIDGE = 209; /** * Constant for possible type of an interface * @see types() */ const IF_TYPE_LINEGROUP = 210; /** * Constant for possible type of an interface * @see types() */ const IF_TYPE_VOICEEMFGD = 211; /** * Constant for possible type of an interface * @see types() */ const IF_TYPE_VOICEFGDEANA = 212; /** * Constant for possible type of an interface * @see types() */ const IF_TYPE_VOICEDID = 213; /** * Constant for possible type of an interface * @see types() */ const IF_TYPE_MPEGTRANSPORT = 214; /** * Constant for possible type of an interface * @see types() */ const IF_TYPE_SIXTOFOUR = 215; /** * Constant for possible type of an interface * @see types() */ const IF_TYPE_GTP = 216; /** * Constant for possible type of an interface * @see types() */ const IF_TYPE_PDNETHERLOOP1 = 217; /** * Constant for possible type of an interface * @see types() */ const IF_TYPE_PDNETHERLOOP2 = 218; /** * Constant for possible type of an interface * @see types() */ const IF_TYPE_OPTICALCHANNELGROUP = 219; /** * Constant for possible type of an interface * @see types() */ const IF_TYPE_HOMEPNA = 220; /** * Constant for possible type of an interface * @see types() */ const IF_TYPE_GFP = 221; /** * Constant for possible type of an interface * @see types() */ const IF_TYPE_CISCOISLVLAN = 222; /** * Constant for possible type of an interface * @see types() */ const IF_TYPE_ACTELISMETALOOP = 223; /** * Constant for possible type of an interface * @see types() */ const IF_TYPE_FCIPLINK = 224; /** * Constant for possible type of an interface * @see types() */ const IF_TYPE_RPR = 225; /** * Constant for possible type of an interface * @see types() */ const IF_TYPE_QAM = 226; /** * Constant for possible type of an interface * @see types() */ const IF_TYPE_LMP = 227; /** * Constant for possible type of an interface * @see types() */ const IF_TYPE_CBLVECTASTAR = 228; /** * Constant for possible type of an interface * @see types() */ const IF_TYPE_DOCSCABLEMCMTSDOWNSTREAM = 229; /** * Constant for possible type of an interface * @see types() */ const IF_TYPE_ADSL2 = 230; /** * Constant for possible type of an interface * @see types() */ const IF_TYPE_MACSECCONTROLLEDIF = 231; /** * Constant for possible type of an interface * @see types() */ const IF_TYPE_MACSECUNCONTROLLEDIF = 232; /** * Constant for possible type of an interface * @see types() */ const IF_TYPE_AVICIOPTICALETHER = 233; /** * Constant for possible type of an interface * @see types() */ const IF_TYPE_ATMBOND = 234; /** * Text representation of interface types. * * @see types() * @var array Text representations of interface types. */ public static $IF_TYPES = array( self::IF_TYPE_OTHER => 'other', self::IF_TYPE_REGULAR1822 => 'regular1822', self::IF_TYPE_HDH1822 => 'hdh1822', self::IF_TYPE_DDNX25 => 'ddnX25', self::IF_TYPE_RFC877X25 => 'rfc877x25', self::IF_TYPE_ETHERNETCSMACD => 'ethernetCsmacd', self::IF_TYPE_ISO88023CSMACD => 'iso88023Csmacd', self::IF_TYPE_ISO88024TOKENBUS => 'iso88024TokenBus', self::IF_TYPE_ISO88025TOKENRING => 'iso88025TokenRing', self::IF_TYPE_ISO88026MAN => 'iso88026Man', self::IF_TYPE_STARLAN => 'starLan', self::IF_TYPE_PROTEON10MBIT => 'proteon10Mbit', self::IF_TYPE_PROTEON80MBIT => 'proteon80Mbit', self::IF_TYPE_HYPERCHANNEL => 'hyperchannel', self::IF_TYPE_FDDI => 'fddi', self::IF_TYPE_LAPB => 'lapb', self::IF_TYPE_SDLC => 'sdlc', self::IF_TYPE_DS1 => 'ds1', self::IF_TYPE_E1 => 'e1', self::IF_TYPE_BASICISDN => 'basicISDN', self::IF_TYPE_PRIMARYISDN => 'primaryISDN', self::IF_TYPE_PROPPOINTTOPOINTSERIAL => 'propPointToPointSerial', self::IF_TYPE_PPP => 'ppp', self::IF_TYPE_SOFTWARELOOPBACK => 'softwareLoopback', self::IF_TYPE_EON => 'eon', self::IF_TYPE_ETHERNET3MBIT => 'ethernet3Mbit', self::IF_TYPE_NSIP => 'nsip', self::IF_TYPE_SLIP => 'slip', self::IF_TYPE_ULTRA => 'ultra', self::IF_TYPE_DS3 => 'ds3', self::IF_TYPE_SIP => 'sip', self::IF_TYPE_FRAMERELAY => 'frameRelay', self::IF_TYPE_RS232 => 'rs232', self::IF_TYPE_PARA => 'para', self::IF_TYPE_ARCNET => 'arcnet', self::IF_TYPE_ARCNETPLUS => 'arcnetPlus', self::IF_TYPE_ATM => 'atm', self::IF_TYPE_MIOX25 => 'miox25', self::IF_TYPE_SONET => 'sonet', self::IF_TYPE_X25PLE => 'x25ple', self::IF_TYPE_ISO88022LLC => 'iso88022llc', self::IF_TYPE_LOCALTALK => 'localTalk', self::IF_TYPE_SMDSDXI => 'smdsDxi', self::IF_TYPE_FRAMERELAYSERVICE => 'frameRelayService', self::IF_TYPE_V35 => 'v35', self::IF_TYPE_HSSI => 'hssi', self::IF_TYPE_HIPPI => 'hippi', self::IF_TYPE_MODEM => 'modem', self::IF_TYPE_AAL5 => 'aal5', self::IF_TYPE_SONETPATH => 'sonetPath', self::IF_TYPE_SONETVT => 'sonetVT', self::IF_TYPE_SMDSICIP => 'smdsIcip', self::IF_TYPE_PROPVIRTUAL => 'propVirtual', self::IF_TYPE_PROPMULTIPLEXOR => 'propMultiplexor', self::IF_TYPE_IEEE80212 => 'ieee80212', self::IF_TYPE_FIBRECHANNEL => 'fibreChannel', self::IF_TYPE_HIPPIINTERFACE => 'hippiInterface', self::IF_TYPE_FRAMERELAYINTERCONNECT => 'frameRelayInterconnect', self::IF_TYPE_AFLANE8023 => 'aflane8023', self::IF_TYPE_AFLANE8025 => 'aflane8025', self::IF_TYPE_CCTEMUL => 'cctEmul', self::IF_TYPE_FASTETHER => 'fastEther', self::IF_TYPE_ISDN => 'isdn', self::IF_TYPE_V11 => 'v11', self::IF_TYPE_V36 => 'v36', self::IF_TYPE_G703AT64K => 'g703at64k', self::IF_TYPE_G703AT2MB => 'g703at2mb', self::IF_TYPE_QLLC => 'qllc', self::IF_TYPE_FASTETHERFX => 'fastEtherFX', self::IF_TYPE_CHANNEL => 'channel', self::IF_TYPE_IEEE80211 => 'ieee80211', self::IF_TYPE_IBM370PARCHAN => 'ibm370parChan', self::IF_TYPE_ESCON => 'escon', self::IF_TYPE_DLSW => 'dlsw', self::IF_TYPE_ISDNS => 'isdns', self::IF_TYPE_ISDNU => 'isdnu', self::IF_TYPE_LAPD => 'lapd', self::IF_TYPE_IPSWITCH => 'ipSwitch', self::IF_TYPE_RSRB => 'rsrb', self::IF_TYPE_ATMLOGICAL => 'atmLogical', self::IF_TYPE_DS0 => 'ds0', self::IF_TYPE_DS0BUNDLE => 'ds0Bundle', self::IF_TYPE_BSC => 'bsc', self::IF_TYPE_ASYNC => 'async', self::IF_TYPE_CNR => 'cnr', self::IF_TYPE_ISO88025DTR => 'iso88025Dtr', self::IF_TYPE_EPLRS => 'eplrs', self::IF_TYPE_ARAP => 'arap', self::IF_TYPE_PROPCNLS => 'propCnls', self::IF_TYPE_HOSTPAD => 'hostPad', self::IF_TYPE_TERMPAD => 'termPad', self::IF_TYPE_FRAMERELAYMPI => 'frameRelayMPI', self::IF_TYPE_X213 => 'x213', self::IF_TYPE_ADSL => 'adsl', self::IF_TYPE_RADSL => 'radsl', self::IF_TYPE_SDSL => 'sdsl', self::IF_TYPE_VDSL => 'vdsl', self::IF_TYPE_ISO88025CRFPINT => 'iso88025CRFPInt', self::IF_TYPE_MYRINET => 'myrinet', self::IF_TYPE_VOICEEM => 'voiceEM', self::IF_TYPE_VOICEFXO => 'voiceFXO', self::IF_TYPE_VOICEFXS => 'voiceFXS', self::IF_TYPE_VOICEENCAP => 'voiceEncap', self::IF_TYPE_VOICEOVERIP => 'voiceOverIp', self::IF_TYPE_ATMDXI => 'atmDxi', self::IF_TYPE_ATMFUNI => 'atmFuni', self::IF_TYPE_ATMIMA => 'atmIma', self::IF_TYPE_PPPMULTILINKBUNDLE => 'pppMultilinkBundle', self::IF_TYPE_IPOVERCDLC => 'ipOverCdlc', self::IF_TYPE_IPOVERCLAW => 'ipOverClaw', self::IF_TYPE_STACKTOSTACK => 'stackToStack', self::IF_TYPE_VIRTUALIPADDRESS => 'virtualIpAddress', self::IF_TYPE_MPC => 'mpc', self::IF_TYPE_IPOVERATM => 'ipOverAtm', self::IF_TYPE_ISO88025FIBER => 'iso88025Fiber', self::IF_TYPE_TDLC => 'tdlc', self::IF_TYPE_GIGABITETHERNET => 'gigabitEthernet', self::IF_TYPE_HDLC => 'hdlc', self::IF_TYPE_LAPF => 'lapf', self::IF_TYPE_V37 => 'v37', self::IF_TYPE_X25MLP => 'x25mlp', self::IF_TYPE_X25HUNTGROUP => 'x25huntGroup', self::IF_TYPE_TRASNPHDLC => 'trasnpHdlc', self::IF_TYPE_INTERLEAVE => 'interleave', self::IF_TYPE_FAST => 'fast', self::IF_TYPE_IP => 'ip', self::IF_TYPE_DOCSCABLEMACLAYER => 'docsCableMaclayer', self::IF_TYPE_DOCSCABLEDOWNSTREAM => 'docsCableDownstream', self::IF_TYPE_DOCSCABLEUPSTREAM => 'docsCableUpstream', self::IF_TYPE_A12MPPSWITCH => 'a12MppSwitch', self::IF_TYPE_TUNNEL => 'tunnel', self::IF_TYPE_COFFEE => 'coffee', self::IF_TYPE_CES => 'ces', self::IF_TYPE_ATMSUBINTERFACE => 'atmSubInterface', self::IF_TYPE_L2VLAN => 'l2vlan', self::IF_TYPE_L3IPVLAN => 'l3ipvlan', self::IF_TYPE_L3IPXVLAN => 'l3ipxvlan', self::IF_TYPE_DIGITALPOWERLINE => 'digitalPowerline', self::IF_TYPE_MEDIAMAILOVERIP => 'mediaMailOverIp', self::IF_TYPE_DTM => 'dtm', self::IF_TYPE_DCN => 'dcn', self::IF_TYPE_IPFORWARD => 'ipForward', self::IF_TYPE_MSDSL => 'msdsl', self::IF_TYPE_IEEE1394 => 'ieee1394', self::IF_TYPE_IF_GSN => 'if-gsn', self::IF_TYPE_DVBRCCMACLAYER => 'dvbRccMacLayer', self::IF_TYPE_DVBRCCDOWNSTREAM => 'dvbRccDownstream', self::IF_TYPE_DVBRCCUPSTREAM => 'dvbRccUpstream', self::IF_TYPE_ATMVIRTUAL => 'atmVirtual', self::IF_TYPE_MPLSTUNNEL => 'mplsTunnel', self::IF_TYPE_SRP => 'srp', self::IF_TYPE_VOICEOVERATM => 'voiceOverAtm', self::IF_TYPE_VOICEOVERFRAMERELAY => 'voiceOverFrameRelay', self::IF_TYPE_IDSL => 'idsl', self::IF_TYPE_COMPOSITELINK => 'compositeLink', self::IF_TYPE_SS7SIGLINK => 'ss7SigLink', self::IF_TYPE_PROPWIRELESSP2P => 'propWirelessP2P', self::IF_TYPE_FRFORWARD => 'frForward', self::IF_TYPE_RFC1483 => 'rfc1483', self::IF_TYPE_USB => 'usb', self::IF_TYPE_IEEE8023ADLAG => 'ieee8023adLag', self::IF_TYPE_BGPPOLICYACCOUNTING => 'bgppolicyaccounting', self::IF_TYPE_FRF16MFRBUNDLE => 'frf16MfrBundle', self::IF_TYPE_H323GATEKEEPER => 'h323Gatekeeper', self::IF_TYPE_H323PROXY => 'h323Proxy', self::IF_TYPE_MPLS => 'mpls', self::IF_TYPE_MFSIGLINK => 'mfSigLink', self::IF_TYPE_HDSL2 => 'hdsl2', self::IF_TYPE_SHDSL => 'shdsl', self::IF_TYPE_DS1FDL => 'ds1FDL', self::IF_TYPE_POS => 'pos', self::IF_TYPE_DVBASIIN => 'dvbAsiIn', self::IF_TYPE_DVBASIOUT => 'dvbAsiOut', self::IF_TYPE_PLC => 'plc', self::IF_TYPE_NFAS => 'nfas', self::IF_TYPE_TR008 => 'tr008', self::IF_TYPE_GR303RDT => 'gr303RDT', self::IF_TYPE_GR303IDT => 'gr303IDT', self::IF_TYPE_ISUP => 'isup', self::IF_TYPE_PROPDOCSWIRELESSMACLAYER => 'propDocsWirelessMaclayer', self::IF_TYPE_PROPDOCSWIRELESSDOWNSTREAM => 'propDocsWirelessDownstream', self::IF_TYPE_PROPDOCSWIRELESSUPSTREAM => 'propDocsWirelessUpstream', self::IF_TYPE_HIPERLAN2 => 'hiperlan2', self::IF_TYPE_PROPBWAP2MP => 'propBWAp2Mp', self::IF_TYPE_SONETOVERHEADCHANNEL => 'sonetOverheadChannel', self::IF_TYPE_DIGITALWRAPPEROVERHEADCHANNEL => 'digitalWrapperOverheadChannel', self::IF_TYPE_AAL2 => 'aal2', self::IF_TYPE_RADIOMAC => 'radioMAC', self::IF_TYPE_ATMRADIO => 'atmRadio', self::IF_TYPE_IMT => 'imt', self::IF_TYPE_MVL => 'mvl', self::IF_TYPE_REACHDSL => 'reachDSL', self::IF_TYPE_FRDLCIENDPT => 'frDlciEndPt', self::IF_TYPE_ATMVCIENDPT => 'atmVciEndPt', self::IF_TYPE_OPTICALCHANNEL => 'opticalChannel', self::IF_TYPE_OPTICALTRANSPORT => 'opticalTransport', self::IF_TYPE_PROPATM => 'propAtm', self::IF_TYPE_VOICEOVERCABLE => 'voiceOverCable', self::IF_TYPE_INFINIBAND => 'infiniband', self::IF_TYPE_TELINK => 'teLink', self::IF_TYPE_Q2931 => 'q2931', self::IF_TYPE_VIRTUALTG => 'virtualTg', self::IF_TYPE_SIPTG => 'sipTg', self::IF_TYPE_SIPSIG => 'sipSig', self::IF_TYPE_DOCSCABLEUPSTREAMCHANNEL => 'docsCableUpstreamChannel', self::IF_TYPE_ECONET => 'econet', self::IF_TYPE_PON155 => 'pon155', self::IF_TYPE_PON622 => 'pon622', self::IF_TYPE_BRIDGE => 'bridge', self::IF_TYPE_LINEGROUP => 'linegroup', self::IF_TYPE_VOICEEMFGD => 'voiceEMFGD', self::IF_TYPE_VOICEFGDEANA => 'voiceFGDEANA', self::IF_TYPE_VOICEDID => 'voiceDID', self::IF_TYPE_MPEGTRANSPORT => 'mpegTransport', self::IF_TYPE_SIXTOFOUR => 'sixToFour', self::IF_TYPE_GTP => 'gtp', self::IF_TYPE_PDNETHERLOOP1 => 'pdnEtherLoop1', self::IF_TYPE_PDNETHERLOOP2 => 'pdnEtherLoop2', self::IF_TYPE_OPTICALCHANNELGROUP => 'opticalChannelGroup', self::IF_TYPE_HOMEPNA => 'homepna', self::IF_TYPE_GFP => 'gfp', self::IF_TYPE_CISCOISLVLAN => 'ciscoISLvlan', self::IF_TYPE_ACTELISMETALOOP => 'actelisMetaLOOP', self::IF_TYPE_FCIPLINK => 'fcipLink', self::IF_TYPE_RPR => 'rpr', self::IF_TYPE_QAM => 'qam', self::IF_TYPE_LMP => 'lmp', self::IF_TYPE_CBLVECTASTAR => 'cblVectaStar', self::IF_TYPE_DOCSCABLEMCMTSDOWNSTREAM => 'docsCableMCmtsDownstream', self::IF_TYPE_ADSL2 => 'adsl2', self::IF_TYPE_MACSECCONTROLLEDIF => 'macSecControlledIF', self::IF_TYPE_MACSECUNCONTROLLEDIF => 'macSecUncontrolledIF', self::IF_TYPE_AVICIOPTICALETHER => 'aviciOpticalEther', self::IF_TYPE_ATMBOND => 'atmbond' ); /** * Get an array of device interface types * * @see $IF_TYPES * @param boolean $translate If true, return the string representation * @return array An array of interface types */ public function types( $translate = false ) { $types = $this->getSNMP()->walk1d( self::OID_IF_TYPE ); if( !$translate ) return $types; return $this->getSNMP()->translate( $types, self::$IF_TYPES ); } /** * Returns an associate array of STP port IDs (key) to interface IDs (value) * * e.g. [22] => 10122 * * * @return array Associate array of STP port IDs (key) to interface IDs (value) */ public function bridgeBasePortIfIndexes() { return $this->getSNMP()->walk1d( self::OID_BRIDGE_BASE_PORT_IF_INDEX ); } }
{ "pile_set_name": "Github" }
angular.module('uiRouterSample.contacts.service', [ ]) // A RESTful factory for retrieving contacts from 'contacts.json' .factory('contacts', ['$http', 'utils', function ($http, utils) { var path = 'assets/contacts.json'; var contacts = $http.get(path).then(function (resp) { return resp.data.contacts; }); var factory = {}; factory.all = function () { return contacts; }; factory.get = function (id) { return contacts.then(function(){ return utils.findById(contacts, id); }) }; return factory; }]);
{ "pile_set_name": "Github" }
<!DOCTYPE html> <html id="top"> <head> <meta charset="utf-8"> <title>The Crosswalk Project</title> <link rel="shorcut icon" href="/assets/favicon.ico" type="image/x-icon" /> <link rel="icon" href="/assets/favicon.ico" type="image/x-icon" /> <script> WebFontConfig = { custom: { families: ['Clear Sans'], urls: ['/css/fonts.css'] }, google: { families: ['Source Code Pro:n4,n6'] }, timeout: 2000 }; </script> <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script> <script async defer src="//ajax.googleapis.com/ajax/libs/webfont/1.5.3/webfont.js"></script> <link rel="stylesheet" href="/css/main.css"> <meta name="description" content="Enable the most advanced web innovations with the Crosswalk Project web runtime to develop powerful Android and Cordova apps." /> <meta name="author" content="Crosswalk" /> <meta name="handheldfriendly" content="true" /> <meta name="mobileoptimized" content="320" /> <meta name="viewport" content="width=device-width, initial-scale=1.0, minimum-scale=1.0"> <meta http-equiv="cleartype" content="on" /> <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1" /> <!-- Facebook --> <meta property="og:side_name" content="Crosswalk" /> <meta property="og:title" content="Crosswalk" /> <meta property="og:url" content="http://crosswalk-project.org/documentation/tutorials/screens" /> <meta property="og:description" content="Enable the most advanced web innovations with the Crosswalk Project web runtime to develop powerful Android and Cordova apps." /> <meta property="og:image" content="/assets/crosswalk-og-banner.jpg" /> <!-- Twitter --> <meta name="twitter:card" content="summary" /> <meta name="twitter:url" content="http://crosswalk-project.org/documentation/tutorials/screens" /> <meta name="twitter:title" content="Crosswalk" /> <meta name="twitter:description" content="Enable the most advanced web innovations with the Crosswalk Project web runtime to develop powerful Android and Cordova apps." /> <meta name="twitter:site" content="@xwalk_project" /> <!-- Relevant original Crosswalk Project JS --> <script src="/js/utils.js"></script> <script src="/js/xwalk.js"></script> <script src="/js/versions.js"></script> <script src="/js/demos.js"></script> <script src="/js/testimonials.js"></script> <script src="/js/tools.js"></script> <script src="/js/qualityindicators.js"></script> <script src="/js/i18n.js"></script> <script src="/js/highlight.pack.js"></script> <script>hljs.initHighlightingOnLoad();</script> <script language="javascript" type="text/javascript"> var style = document.createElement('style'); style.type = "text/css"; style.id = "antiClickjack"; style.innerHTML = "body{display:none !important;}"; if (self === top) { var antiClickjack = document.getElementById("antiClickjack"); antiClickjack.parentNode.removeChild(antiClickjack); } else { top.location = self.location; } </script> </head> <body> <!-- If curr page named 'index' and less than 2 dirs deep, do custom layouts. (home screen, blog, app-mgmt page) Else, provide doc header and nav. --> <div class="container"> <div class="doc-header"> <div class="doc-logo-div"> <a href="/" class="doc-logo-link"> <img src="/assets/identity/crosswalkproject-logo-horizontal-dark.png" class="doc-logo-img"> </a> </div> <div class="doc-nav-div"> <ul class="doc-nav-list"> <li class="doc-nav-item"> <a href="/documentation/getting_started.html" class="doc-nav-link">Documentation</a> </li> <li class="doc-nav-item"> <a href="/blog" class="doc-nav-link">Blog</a> </li> <li class="doc-nav-item hide-on-small"> <a href="/contribute" class="doc-nav-link">Contribute</a> </li> <li class="doc-nav-item hide-on-small"> <a href="https://github.com/crosswalk-project/crosswalk-website/wiki" class="doc-nav-link">Wiki</a> </li> <li class="doc-nav-item hide-on-small"> <a href="/documentation/about/faq.html" class="doc-nav-link">FAQ</a> </li> <li class="doc-nav-item"> <span class="i18n-label" id="i18n-label"> <span id="i18n-inner"> <img src="/assets/i18n-globe.png" class="i18n-globe" /> English <img src="/assets/i18n-arrow.png" class="i18n-arrow"/> </span> <div id="i18n-menu" class="i18n-menu i18n-menu-light"> <a onclick="switchLanguage('English')">English</a> <a onclick="switchLanguage('Chinese')">中文版</a> </div> </span> </li> </ul> </div> </div> <br /> <div class="doc-main"> <div class="row"> <div id="translation-missing-toaster"> <p style="padding:10px"> 抱歉,该网页目前还不存在中文版本,请继续浏览其他网页! </p> </div> <nav id="contents" class="article-toc nav-toggleContainer"> <a href="#contents" id="contents-toggle" class="button button--small button--tertiary nav-toggle">Table of Contents</a> <a href="./#contents-toggle" class="button button--small button--tertiary nav-toggle--dummy">Table of Contents</a> <ul class="article-list nav-toggleHide"> <li class="article-item "> <a class="article-link" href="/documentation/about.html">About</a> </li> <li class="article-item "> <a class="article-link" href="/documentation/getting_started.html">Getting Started</a> </li> <li class="article-item "> <a class="article-link" href="/documentation/crosswalk-app-tools.html">Crosswalk App Tools</a> </li> <li class="article-item "> <a class="article-link" href="/documentation/android.html">Android</a> </li> <li class="article-item "> <a class="article-link" href="/documentation/ios.html">iOS</a> </li> <li class="article-item "> <a class="article-link" href="/documentation/windows.html">Windows</a> </li> <li class="article-item "> <a class="article-link" href="/documentation/linux.html">Linux</a> </li> <li class="article-item "> <a class="article-link" href="/documentation/cordova.html">Cordova</a> </li> <li class="article-item "> <a class="article-link" href="/documentation/tizen.html">Tizen</a> </li> <li class="article-item "> <a class="article-link" href="/documentation/manifest.html">Manifest</a> </li> <li class="article-item "> <a class="article-link" href="/documentation/apis.html">APIs</a> </li> <li class="article-item "> <a class="article-link" href="/documentation/downloads.html">Downloads</a> </li> <li class="article-item "> <a class="article-link" href="/documentation/shared_mode.html">Shared Mode</a> </li> <li class="article-item "> <a class="article-link" href="/documentation/download_mode.html">Download Mode</a> </li> <li class="article-item "> <a class="article-link" href="/documentation/crosswalk_lite.html">Crosswalk Lite</a> </li> <li class="article-item "> <a class="article-link" href="/documentation/tutorials.html">Tutorials</a> <ul class="article-list"> <li class="article-item "> <a class="article-link" href="/documentation/tutorials/realsense.html">Intel RealSense</a> </li> <li class="article-item "> <a class="article-link" href="/documentation/tutorials/webvr.html">WebVR</a> </li> <li class="article-item "> <a class="article-link" href="/documentation/tutorials/security-api.html">Intel Security APIs</a> </li> <li class="article-item "> <a class="article-link" href="/documentation/tutorials/webrtc.html">WebRTC</a> </li> <li class="article-item "> <a class="article-link" href="/documentation/tutorials/webcl.html">WebCL</a> </li> <li class="article-item nav-item--active"> <a class="article-link" href="/documentation/tutorials/screens.html">Screens</a> <ul class="article-list"> </ul> </li> <li class="article-item "> <a class="article-link" href="/documentation/tutorials/webassembly.html">Web Assembly</a> </li> </ul> </li> <li class="article-item "> <a class="article-link" href="/documentation/samples.html">Samples</a> </li> <li class="article-item "> <a class="article-link" href="/documentation/community.html">Community</a> </li> <li class="article-item "> <a class="article-link" href="/documentation/qa.html">Quality Assurance</a> </li> </ul> </nav> <article class="article article--hasToC"> <h1>Screen APIs</h1> <p>The Crosswalk Project simplifies the difficult task of making an application work well on a small screen, with the same look and feel as a native application.</p> <p>Some of the most common screen-related issues on mobile devices are:</p> <ul> <li>Fitting the application to the &quot;real&quot; screen width and height.</li> <li>Locking the screen orientation to the one preferred for the application.</li> <li>Showing an application in fullscreen mode with no system toolbars.</li> <li>Using different layouts or assets depending on screen size.</li> <li>Showing a launch screen while an application is loading.</li> </ul> <p>A number of solutions for such issues have surfaced over the last few years, either as de facto &quot;standards&quot; (e.g. the <a href="https://developer.apple.com/library/safari/documentation/AppleApplications/Reference/SafariHTMLRef/Articles/MetaTags.html#//apple_ref/doc/uid/TP40008193-SW6"><code>&lt;meta name=&quot;viewport&quot;&gt;</code> element</a>), vendor-specific browser extensions (e.g. <a href="https://developer.mozilla.org/en-US/docs/Web/API/Screen.lockOrientation">Mozilla&#39;s implementation of screen.lockOrientation</a>), or application-specific work-arounds in JavaScript and CSS (e.g. <a href="https://github.com/01org/webapps-slider-puzzle/blob/master/app/js/main.js">this rotation hack</a>). Recently, work has started on creating formal standards based on these interim solutions. However, many browsers and web views lag behind these standards.</p> <p>By contrast, one major benefit of Crosswalk is that many of these evolving standards are implemented and available for use <em>right now</em>. In this article, I&#39;ll describe how to resolve some of the issues listed above using Crosswalk by optimising a simple side-scrolling HTML5 game for mobile screens.</p> <h2>Aside: measuring the screen in HTML5 applications</h2> <p>One major complexity when working with HTML5 and CSS is figuring out how CSS pixels and physical pixels on the screen relate to each other. For the purposes of this article, I&#39;ve glossed over these issues, as they can mostly be ignored if you aren&#39;t too concerned about how consistent a game appearson different devices. However, there are other situations where it is important to understand these nuances; for example, if you want your game to look identical on different devices, you will have to pay attention to screen densities.</p> <p>To help in these situations, the <a href="/documentation/tutorials/screens/screen_measurements.html">screen measurements page</a> explains the terminology, including units and measurements, which are relevant when dealing with heterogenous screens in detail.</p> <p>You may also find it useful to refer to <a href="http://www.html5rocks.com/en/tutorials/canvas/hidpi/">this article</a> about working with the <code>&lt;canvas&gt;</code> element on HiDPI (aka retina) displays.</p> <h2>The game</h2> <p>The game used in this article is a side-scrolling dodge game set in space. The code is <a href="https://github.com/crosswalk-project/crosswalk-samples">available on github</a>.</p> <p>The layout of the game looks like this (shown in a Chrome browser on a Linux desktop machine):</p> <p><img src="/assets/space_dodge_game-chrome_linux_desktop.png" alt="space dodge game in Chrome on Linux desktop"></p> <p>The container element for the whole game is sized using CSS, and is 750 pixels across by 450 pixels down. It is positioned relative to the top-left of the browser window.</p> <p>Inside the container are a <code>&lt;div&gt;</code> for the game screen, consisting of a controls <code>&lt;div&gt;</code> on the left and a <code>&lt;canvas&gt;</code> for the play area on the right; and another <code>&lt;div&gt;</code> for the &quot;game over&quot; screen, which is initially hidden.</p> <p>The controls <code>&lt;div&gt;</code> is sized relative to the container, and take up 20% of its width (150px) and 100% of its height (450px). The elements inside the controls area are positioned using the <a href="http://www.w3.org/TR/css-flexbox-1/">CSS flexbox</a>. The CSS flexbox is the first example of a useful feature which is available in Crosswalk, but not in older browsers. It&#39;s very handy for laying out game controls, as you can vertically and horizontally align elements inside a flex element.</p> <p><code>&lt;canvas&gt;</code> elements have to have a pixel width and height specified for them (you can&#39;t size them in CSS). For this first version of the game, the <code>&lt;canvas&gt;</code> is sized to 600 pixels across and 450 pixels down. This is then put in the right-hand side of the game screen.</p> <p>The sprites for the ship and the asteroids are loaded from PNG graphic files and drawn to the canvas. If you are unfamiliar with how to do this, see <a href="https://developer.mozilla.org/en-US/docs/Web/Guide/HTML/Canvas_tutorial">this <code>&lt;canvas&gt;</code> tutorial</a>.</p> <p>The gameplay is nothing special, but is just there to demonstrate the effect of applying various screen-related techniques to the game. The game is touch-enabled, though, so it will work on a touchscreen devices like phones.</p> <h3>Notes on the game layout</h3> <p>The layout elements in the HTML file <code>index.html</code>:</p> <pre><code>&lt;!DOCTYPE html&gt; &lt;html&gt; &lt;head&gt; &lt;meta charset=&quot;utf-8&quot;&gt; &lt;title&gt;space dodge game&lt;/title&gt; &lt;link rel=&quot;stylesheet&quot; href=&quot;base.css&quot;&gt; &lt;/head&gt; &lt;body&gt; &lt;div id=&quot;container&quot;&gt; &lt;div id=&quot;game-screen&quot;&gt; &lt;div id=&quot;controls&quot; class=&quot;vbox&quot;&gt; &lt;p id=&quot;score&quot;&gt;Score&lt;br&gt;&lt;span id=&quot;score-display&quot;&gt;&lt;/span&gt;&lt;/p&gt; &lt;img id=&quot;control-up&quot; src=&quot;control-up.png&quot;&gt; &lt;img id=&quot;control-down&quot; src=&quot;control-down.png&quot;&gt; &lt;/div&gt; &lt;canvas id=&quot;play-area&quot; width=&quot;600&quot; height=&quot;450&quot;&gt;&lt;/canvas&gt; &lt;/div&gt; &lt;div id=&quot;finish-screen&quot; class=&quot;vbox&quot; data-visible=&quot;false&quot;&gt; &lt;p id=&quot;final-score&quot;&gt;&lt;/p&gt; &lt;button id=&quot;restart&quot;&gt;Restart&lt;/button&gt; &lt;/div&gt; &lt;/div&gt; &lt;script src=&quot;main.js&quot;&gt;&lt;/script&gt; &lt;/body&gt; &lt;/html&gt;</code></pre> <p>The CSS stylesheet:</p> <pre><code>* { user-select: none; -webkit-user-select: none; user-drag: none; -webkit-user-drag: none; } body { margin: 0; } #container { position: relative; top: 0; left: 0; width: 750px; height: 450px; } #game-screen, #finish-screen { position: absolute; top: 0; left: 0; width: 100%; height: 100%; background-color: #11F; } #finish-screen { z-index: 100; } #play-area { float: right; width: 80%; } #controls { height: 100%; width: 20%; padding: 5%; text-align: center; box-sizing: border-box; float: left; } .vbox { display: flex; flex-direction: column; align-items: center; justify-content: center; } p, button { font-family: sans-serif; font-size: 1.5em; } #control-up, #control-down { margin: 1em 0; } #finish-screen &gt; * { text-align: center; } #score, #final-score { color: white; } [data-visible=&quot;false&quot;] { display: none !important; }</code></pre> <p>Some remarks about the code:</p> <ul> <li><p>The margins are removed from the <code>body</code> element with:</p> <pre><code>body { margin: 0; }</code></pre> <p>This makes it easier to do accurate positioning and sizing of elements inside the body.</p> </li> <li><p>The outer element with ID <code>container</code> contains all of the other game elements. Its size is sets in CSS, which constrains the size of the whole game.</p> </li> <li><p>There are two separate &quot;screens&quot; inside the container (elements with the IDs <code>game-screen</code> and <code>finish-screen</code>). <code>finish-screen</code> is hidden initially, but is placed on top of <code>game-screen</code> by setting a <code>z-index</code> of 100. When the game ends, <code>finish-screen</code> is shown, which obscures the <code>game-screen</code> element underneath it.</p> </li> <li><p><code>&lt;canvas&gt;</code> elements must have their height and width attributes set to define the size of the canvas in pixels. This can&#39;t be done in CSS. In the code above, the height and width are fixed; but they can be set dynamically based on the size of the screen (see later).</p> </li> <li><p>The container has <code>position: relative</code> set in the CSS, and the child screens have <code>position: absolute</code>. This enables the child screens to be aligned with the top-left corner of the container.</p> </li> <li><p><code>float</code> properties are used to position the controls to the left of the canvas <code>play-area</code>.</p> </li> </ul> <p>The HTML and CSS for the game so far are naive, representing a first pass at a working layout. There is plenty of room for optimisation and improvement.</p> <h3>Running it yourself</h3> <p>If you are interested in following along with the article, rather than just looking at screenshots, you can checkout the project and build an Android package for it by following the steps below.</p> <ol> <li><p>Download the latest stable Crosswalk Android bundle:</p> <pre><code>$ wget https://download.01.org/crosswalk/releases/crosswalk/android/stable/${XWALK-STABLE-ANDROID-X86}/crosswalk-${XWALK-STABLE-ANDROID-X86}.zip</code></pre> <p>If you want to run the version of the game designed to work with Crosswalk 8, fetch one of the Crosswalk Android <em>canary</em> bundles from <a href="/documentation/downloads.html">the download page</a>.</p> </li> <li><p>Unzip the bundle, e.g. on Linux:</p> <pre><code>$ unzip crosswalk-${XWALK-STABLE-ANDROID-X86}.zip</code></pre> </li> <li><p>Check out the code for the Crosswalk samples from github:</p> <pre><code>$ git checkout https://github.com/crosswalk-project/crosswalk-samples.git</code></pre> <p>The game used in this tutorial is in the <code>space-dodge-game</code> directory.</p> </li> <li><p>Use <code>make_apk.py</code> to build a Crosswalk package from the checked-out crosswalk-samples project:</p> <pre><code>$ cd crosswalk-${XWALK-STABLE-ANDROID-X86} $ python make_apk.py --manifest=/path/to/crosswalk-samples/space-dodge-game/&lt;version&gt;</code></pre> <p>Replace <code>&lt;version&gt;</code> with whichever version of the game you want to run; <code>master</code> is the version of the game before optimisation, and there are four other versions for different Crosswalk versions and techniques. See the <code>README.md</code> file in the <code>space-dodge-game</code> directory for details.</p> </li> <li><p>Once you have built a package for the game, you can deploy it to Android using <code>adb</code>:</p> <pre><code>$ adb install space_dodge_game_0.0.0.1_x86.apk</code></pre> <p>or</p> <pre><code>$ adb install space_dodge_game_0.0.0.1_arm.apk</code></pre> <p>depending on your target hardware.</p> <p>For more details about building and running Crosswalk applications on Android, see <a href="/documentation/android/run_on_android.html">the Getting started pages</a>.</p> </li> </ol> <h2>Issue 1: The game sometimes displays in portrait orientation</h2> <p>If the game is packaged and deployed to a small screen device in its initial state, this is what it looks like:</p> <p><img src="/assets/space_dodge_game-zte_geek_portrait.png" alt="space dodge game in portrait on ZTE Geek"></p> <p>It&#39;s obvious that it doesn&#39;t take up enough of the screen. The reason is that the game is in portrait orientation, when it should be in landscape. By rotating the device (so the game rotates), you can see an immediate improvement:</p> <p><img src="/assets/space_dodge_game-zte_geek_landscape.png" alt="space dodge game in landscape on ZTE Geek"></p> <p>However, the game shouldn&#39;t accidentally rotate if the screen orientation changes, as it does at the moment: it should always display in landscape mode.</p> <p>Crosswalk provides an easy fix for this, as it implements the <a href="http://www.w3.org/TR/screen-orientation/">Screen Orientation API</a>. Among other things, this enables an application to lock itself to a particular orientation at run time.</p> <p>To use this, add the following code to the main JavaScript entry point for your application. This depends on the application, but for the space dodge game, it&#39;s at the top of the <code>main.js</code> file, triggered once the DOM is ready:</p> <pre><code>document.addEventListener(&#39;DOMContentLoaded&#39;, function () { // check whether the runtime supports screen.lockOrientation if (screen.lockOrientation) { // lock the orientation screen.lockOrientation(&#39;landscape&#39;); } // ...rest of the application code... };</code></pre> <p>If you run the application now, you&#39;ll notice that the game rotates to landscape when it starts. Its appearance is the same as if the physical device were rotated to landscape. An application can also be locked to portrait orientation using this approach (<code>screen.lockOrientation(&#39;portrait&#39;)</code>).</p> <p>If you prefer, there are a couple of other ways to fix an application&#39;s orientation:</p> <ul> <li><p>Use the <code>orientation</code> field in the manifest (this only works for Crosswalk 8 or later).</p> <p>For example, the following manifest would force the application to landscape orientation:</p> <pre><code>{ &quot;name&quot;: &quot;space_dodge_game&quot;, &quot;version&quot;: &quot;0.0.0.1&quot;, &quot;start_url&quot;: &quot;index.html&quot;, &quot;orientation&quot;: &quot;landscape&quot; }</code></pre> <p>You could then <a href="/documentation/android/run_on_android.html">build an application package for Android</a> from this manifest with:</p> <pre><code>$ python make_apk.py --manifest=/projects/space_dodge_game/manifest.json</code></pre> <p>Install it on an Android target as described in <a href="/documentation/android/run_on_android.html">the Getting started pages</a>.</p> <p>Using the <code>orientation</code> field in the manifest has exactly the same effect as using <code>screen.lockOrientation</code> in your application code: the application rotates to the requested orientation after the application starts. But <code>screen.lockOrientation</code> has the advantage of being supported by other runtimes (e.g. Firefox OS), so may be a better choice if you need your application to work cross-platform.</p> <p>The <code>orientation</code> manifest field is defined in the <a href="http://w3c.github.io/manifest/">W3C Manifest for web application specification</a>.</p> </li> <li><p>Use the <code>--orientation</code> option when running <code>make_apk.py</code>. Note that this won&#39;t work unless you are using <code>make_apk.py</code> to package your application. If you&#39;re using the embedding API, use <code>screen.lockOrientation</code> or the manifest approach.</p> <p>For example:</p> <pre><code>$ python make_apk.py --manifest=/projects/space_dodge_game/manifest.json \ --orientation=landscape</code></pre> <p>This is really a hack, as it actually modifies the <code>AndroidManifest.xml</code> to rotate Crosswalk itself, rather than the application being rotated by Crosswalk. But it&#39;s a viable alternative for older versions of Crosswalk which don&#39;t support the <code>orientation</code> field in the manifest and where you prefer not to use <code>screen.lockOrientation</code>.</p> <p>This also has the same effect as using the <code>orientation</code> field, rotating the application after it has started.</p> <p>The <code>orientation</code> manifest field is defined in the <a href="http://w3c.github.io/manifest/">W3C Manifest for web application specification</a>.</p> </li> </ul> <h2>Issue 2: The status bar is distracting</h2> <p>The next issue is that the toolbar is still visible, which is a distraction while playing a game. There are two ways to make the application occupy the whole screen, hiding the status bar (on Android):</p> <ul> <li><p>Use the <code>display</code> field in <code>manifest.json</code> (this only works for Crosswalk 8 or later).</p> <p>For example, here&#39;s a manifest which sets fullscreen, and also retains the landscape orientation applied in the previous step:</p> <pre><code>{ &quot;name&quot;: &quot;space_dodge_game&quot;, &quot;version&quot;: &quot;0.0.0.1&quot;, &quot;start_url&quot;: &quot;index.html&quot;, &quot;display&quot;: &quot;fullscreen&quot;, &quot;orientation&quot;: &quot;landscape&quot; }</code></pre> <p><a href="/documentation/android/run_on_android.html">Build and deploy to the device</a> as usual.</p> <p>The <code>display</code> manifest field is defined in the <a href="http://w3c.github.io/manifest/">W3C Manifest for web application specification</a>.</p> </li> <li><p>Use the <code>--fullscreen</code> option with the <code>make_apk.py</code> script.</p> <p>For example:</p> <pre><code>$ python make_apk.py --manifest=/projects/space_dodge_game/manifest.json \ --orientation=landscape --fullscreen</code></pre> <p>This is a useful option if you are using an older version of Crosswalk which doesn&#39;t support the <code>display</code> field in the manifest. See <a href="/documentation/android/run_on_android.html">the Getting started pages</a> for more information about using <code>make_apk.py</code>.</p> </li> </ul> <p>Using either the <code>display</code> field or the <code>--fullscreen</code> option has the same effect: the application displays in fullscreen, hiding the system status bar on Android:</p> <p><img src="/assets/space_dodge_game-zte_geek_fullscreen.png" alt="space dodge game in fullscreen, landscape orientation"></p> <p>You may be familiar with the <a href="https://dvcs.w3.org/hg/fullscreen/raw-file/tip/Overview.html">fullscreen API</a>, which enables an application to request that all or part of its user interface occupy the whole device screen. However, the fullscreen API has a different purpose from the approaches covered above: it requires some user activity to trigger the fullscreen request <em>after</em> an application is running.</p> <p>In the case of a Crosswalk application, you can use the fullscreen API, providing the user interacts with the application (e.g. push a button or make a gesture) to trigger the fullscreen request. But it is not possible to <em>automatically</em> make the application go fullscreen without user interaction using this API.</p> <h2>Issue 3: The game doesn&#39;t fit the screen</h2> <p>The game is now consistently bigger because it&#39;s always displayed fullscreen and in landscape orientation. But there&#39;s a lot of whitespace around it, and it&#39;s not visually appealing. It would be nicer if the game fitted the whole screen.</p> <p>The area occupied by the application is called its <em>viewport</em>. On a mobile device, this is the area under or between any toolbars on the screen (e.g. the status bar on Android) if the application is running in &quot;windowed&quot; mode; or the whole device screen if it is running in &quot;fullscreen&quot; mode. What we&#39;re aiming for here is &quot;fullscreen&quot; mode, to get the game to fill the whole of the device screen.</p> <p>There are a few approaches we could take:</p> <ol> <li><p>Scale the application to fit the smallest dimension (width or height), keeping aspect ratio and centering it in the viewport. The game has the same number of pixels, but they are scaled to fit into the viewport.</p> </li> <li><p>Do the same as above, but instead of scaling, physically change the size of all the game elements. This would make the canvas larger (in pixels) on a large screen and smaller on a small screen. The disadvantage of this approach is that you have to scale the image assets used in the game to ensure that they keep the same proportions: for example, if you have an image which is 40px square on a 400px square game area, then change the game canvas to 600px square, you will have to scale the image to 60px square. The advantage of this approach is that you&#39;re not scaling everything, just sprites; but the disadvantage is that it&#39;s more complicated to implement, as you have to track the size of the sprites (on screen) in isolation from their actual size (in the file).</p> </li> <li><p>Change the dimensions of the game, while keeping the size of the <code>&lt;canvas&gt;</code> the same. The area occupied by the game could be made physically larger, and perhaps make the controls larger too, while leaving the <code>&lt;canvas&gt;</code> element the same size. The reason for doing this is that the <code>&lt;canvas&gt;</code> is sensitive to size changes, as described in the previous bullet point.</p> </li> </ol> <p>For this game, the canvas is already too big for small screens, so the third approach is not really practical. (That approach only works if you know your game is only going to be played on a small range of screens, which can all fit the canvas at the size you specify. Similar to how old PC games were designed to fit devices with at least a 640x400 pixel screen, which was the size of most mid range monitors.)</p> <p>This leaves approaches 1 and 2, which are covered shortly. However, before getting onto those, there is a preparatory step which helps with measuring the actual size of the screen, making it more consistent between devices.</p> <h3>Preparation: Make the viewport fit the screen</h3> <p>A few years ago, when designing mobile phones, manufacturers realised that if 90% of websites were shown in a small screen, they would not fit. This is because websites used to be designed primarily for desktop screens; mobile sites were often separate from the main site, with reduced functionality or even written in a <a href="http://en.wikipedia.org/wiki/Wireless_Markup_Language">different markup language</a>. But users wanted to be able to access the &quot;real&quot; website from a phone, rather than a mobile-specific site; and they wanted to do this without compromising the site&#39;s appearance. Manufacturers resolved this by equipping their mobile browsers with a default &quot;zoom out&quot;, to make websites intended for desktops display (reasonably) well in mobile browsers. Most phone browsers still work this way: for example, the HTC One X I have for testing reports its width as 980px, while its actual physical width is 360px.</p> <p>Around the same time, web developers and designers changed their approach, designing websites which would display differently depending on device capabilities. These techniques are now known as <a href="http://alistapart.com/article/responsive-web-design">responsive web design</a>, and encompass a range of approaches including use of <a href="http://www.w3.org/TR/css3-mediaqueries/">media queries</a> and <a href="http://www.w3.org/community/respimg/">delivering different images to different screens</a>. Contemporary developers also often employ a <a href="http://www.abookapart.com/products/mobile-first">mobile first</a> philosophy, ensuring a website is highlighy functional first and foremost on small form factors, with added bells and whistles (typically, more and larger graphics) on bigger form factors.</p> <p>Where these two roads meet is at an awkward crossroads: developers are trying hard to provide sites tailored specifically for small screen devices; but small screen devices apply an artificial zoom which makes device screens appear larger than they are. As a result, the mobile version of a site could be bypassed (the site calculates that it is being viewed on a desktop browser); and the desktop site end up being delivered to a screen that is too small to display it properly.</p> <p>A solution was initially developed by <a href="https://developer.apple.com/library/safari/documentation/AppleApplications/Reference/SafariHTMLRef/Articles/MetaTags.html">Apple</a>, taking the form of an ad hoc HTML <code>&lt;meta&gt;</code> element named <code>viewport</code>. This could be used to ask a mobile browser to change various aspects of its viewport. For example, the page could ask the browser to set the viewport width to the device&#39;s real physical width with:</p> <pre><code>&lt;meta name=&quot;viewport&quot; content=&quot;width=device-width&quot;&gt;</code></pre> <p>Or prevent the user zooming the page in and out (e.g. with pinch gestures):</p> <pre><code>&lt;meta name=&quot;viewport&quot; content=&quot;width=device-width, user-scalable=no&quot;&gt;</code></pre> <p>Other vendors followed suit and added support for this <code>&lt;meta&gt;</code> viewport element to their browsers.</p> <p>By using the <code>&lt;meta&gt;</code> viewport element, a developer could now prevent the browser from applying its default zoom to an HTML page. This would in turn mean that a web site or app could get a correct reading for the device&#39;s physical screen dimensions, enabling media queries to be applied accurately to select the best CSS for the screen.</p> <p>The <code>&lt;meta&gt;</code> viewport element is <em>not</em> a standard: it is not implemented consistently across browsers, and the syntax for declaring its content also varies between browsers. However, there are currently attempts to formalise <a href="http://dev.w3.org/csswg/css-device-adapt/">viewport rules in a CSS specification</a>. For now, though, the existing syntax works well for Crosswalk, and can be used as a stop-gap.</p> <p>To apply a viewport meta element to the space dodge game in this article, add it to the <code>&lt;head&gt;</code> of the <code>index.html</code> file. This instructs the browser to use its physical width as the viewport width, without zooming:</p> <pre><code>&lt;!DOCTYPE html&gt; &lt;html&gt; &lt;head&gt; &lt;meta charset=&quot;utf-8&quot;&gt; &lt;meta name=&quot;viewport&quot; content=&quot;width=device-width&quot;&gt; &lt;title&gt;space dodge game&lt;/title&gt; &lt;link rel=&quot;stylesheet&quot; href=&quot;base.css&quot;&gt; &lt;/head&gt; &lt;body&gt; ... rest of HTML file ...</code></pre> <p>The result is this:</p> <p><img src="/assets/space_dodge_game-viewport_meta.png" alt="space dodge game with landscape orientation, fullscreen and viewport meta"></p> <p>Note how the game is now filling the whole screen, and looks roughly the right size: the buttons are nice and big, and the graphics clear. However, the screen size on this device is 640px wide by 360px down, so the game canvas is spilling over the edges of the screen.</p> <p>By contrast, it doesn&#39;t take up enough space on a larger screen. Here it is on a Nexus 7:</p> <p><img src="/assets/space_dodge_game-nexus7.png" alt="space dodge game on Nexus 7 with landscape orientation, fullscreen, and viewport meta"></p> <p>In the next sections, I describe two ways to alter the size of the game to fit better into the screen.</p> <h3>Approach 1: Scale the game</h3> <p>The aim here is to scale the whole game (in CSS) so that it retains its aspect ratio but fits in the screen. The first step is to figure out the optimum position and size for the element which contains the whole game.</p> <p>Here is the algorithm in pseudo-code:</p> <ul> <li><p>Find the width and height of the viewport (which is the same as the screen dimensions, thanks to the viewport meta applied previously).</p> </li> <li><p>Find the width and height of the application container.</p> </li> <li><p>Find the ratio of viewport height to container height (scaleHeight).</p> </li> <li><p>Find the ratio of screen width to container width (scaleWidth).</p> </li> <li><p>Choose the smallest of scaleHeight and scaleWidth, and use this as the scale factor for both width and height (scaleBoth).</p> </li> <li><p>Work out the newHeight and newWidth of the container by multiplying its width and height by scaleBoth.</p> </li> <li><p>Work out a top and left offset for the container, as follows:</p> <ul> <li>left = (1 / scaleBoth) * ((viewport width - container newWidth) / 2)</li> <li>top = (1 / scaleBoth) * ((viewport height - container newHeight) / 2)</li> </ul> <p>Note that the offsets are being scaled, so that they are in proportion to the scaled game.</p> </li> <li><p>Apply the scaling and offsets to the whole game container using <a href="http://www.w3.org/TR/css-transforms-1/">CSS transforms</a>.</p> </li> </ul> <p>By implementing this pseudo-code in JavaScript, a scale can be applied to the whole container:</p> <pre><code>var scale = function () { var container = document.querySelector(&#39;#container&#39;); var containerWidth = container.offsetWidth; var containerHeight = container.offsetHeight; var viewportWidth = document.documentElement.clientWidth; var viewportHeight = document.documentElement.clientHeight; var scaleWidth = viewportWidth / containerWidth; var scaleHeight = viewportHeight / containerHeight; var scaleBoth = (scaleHeight &lt; scaleWidth) ? scaleHeight : scaleWidth; var newContainerWidth = containerWidth * scaleBoth; var newContainerHeight = containerHeight * scaleBoth; var left = (viewportWidth - newContainerWidth) / 2; left = parseInt(left * (1 / scaleBoth), 10); var top = (viewportHeight - newContainerHeight) / 2; top = parseInt(top * (1 / scaleBoth), 10); // scale the whole container var transform = &#39;scale(&#39; + scaleBoth + &#39;,&#39; + scaleBoth + &#39;) &#39; + &#39;translate(&#39; + left + &#39;px, &#39; + top + &#39;px)&#39;; container.style[&#39;-webkit-transform-origin&#39;] = &#39;top left 0&#39;; container.style[&#39;-webkit-transform&#39;] = transform; container.style[&#39;transform-origin&#39;] = &#39;top left 0&#39;; container.style[&#39;transform&#39;] = transform; }; window.onresize = scale; scale();</code></pre> <p>To give an example of the CSS transforms which will be applied, consider the case where the scale is 2.05 and the top and left offsets are 0px and 40px respectively. The resulting CSS transforms would be:</p> <pre><code>-webkit-transform-origin: 0 0 0; transform-origin: 0 0 0; -webkit-transform: scale(2.05, 2.05) translate(40px, 0px); transform: scale(2.05, 2.05) translate(40px, 0px);</code></pre> <p>Setting the transform origin to <code>top left 0</code> ensures that the transforms are applied from the top-left corner of the container. The <code>scale(2.05, 2.05)</code> function changes the scaling of the container; and the <code>translate(40px, 0px)</code> function moves the container to the correct position on screen (40 pixels from the left-hand edge). Here&#39;s the result on a ZTE Geek:</p> <p><img src="/assets/space_dodge_game-zte_geek_scale.png" alt="space dodge game on ZTE Geek: landscape, fullscreen, viewport meta, CSS transform"></p> <p>Notice how the application is fitted vertically, then centered horizontally.</p> <p>This approach is good because it is simple. However, as the scaling is applied to the whole application, it can cause some blurring, especially when scaling up. The next section describes a more complex alternative which uses resizing plus selective scaling of game assets.</p> <h3>Approach 2: Resize the game</h3> <p>This approach requires a more extensive reworking of the CSS for the game, as it affects the positioning, size and appearance of every element. It&#39;s tempting to ignore this approach, as the scaling approach of the previous section works pretty well. But there&#39;s actually good discipline involved in making this alternative approach work.</p> <p>The first step is to make the container occupy the whole screen. In the olden days, this would have meant measuring the screen, then manually setting the width and height CSS properties of the container (in JavaScript). However, Crosswalk supports a handy CSS feature which means you don&#39;t have to do this any more: <a href="http://dev.w3.org/csswg/css-values/#viewport-relative-lengths">viewport-percentage lengths</a>. These allow you to specify the dimensions of elements in terms of a percentage of the viewport dimensions. As the application is now fullscreen, the viewport fills the whole screen; so the container can fill 100% of the device&#39;s height and width using this CSS rule:</p> <pre><code>#container { position: relative; top: 0; left: 0; width: 100vw; height: 100vh; }</code></pre> <p>Note the <code>vw</code> (viewport percentage width) and <code>vh</code> (viewport percentage height) suffixes to the container&#39;s width and height settings. Here&#39;s what the game looks like on a ZTE Geek with this change to the container sizing:</p> <p><img src="/assets/space_dodge_game_zte_geek_resize.png" alt="space dodge game on ZTE Geek: landscape, fullscreen, viewport meta, resize"></p> <p>Not bad for a first pass. But the bottom of the canvas has disappeared off-screen; and the buttons look squashed. We&#39;ll fix this in a minute.</p> <p>Note that viewport-percentage lengths don&#39;t work well for testing in a desktop browser, as desktop environments often have toolbars on the browser and on the desktop itself. This means that the viewport height can be considerably larger than the amount of space inside the browser window. However, you could try experimenting with <a href="https://developer.chrome.com/devtools/docs/mobile-emulation">Chrome&#39;s device emulation support</a> if you want a quick way to test your app without a mobile or tablet.</p> <p>At this point in testing, I realised something. When I first wrote the game, I concentrated on getting it to look right in a desktop browser. This meant that I didn&#39;t necessarily do everything &quot;properly&quot;. For example, with a fixed width container, I could arrange the control buttons easily: setting a few margins and a bit of padding seemed to work.</p> <p>However, once I started thinking about resizing <em>everything</em>, it became clear that I hadn&#39;t done things the &quot;right way&quot;. I needed to make some fixes so that the buttons and score would be positioned and sized correctly. This could be done easily in CSS, without having to resort to JavaScript.</p> <p>I changed this rule:</p> <pre><code>#control-up, #control-down { margin: 20% 0; }</code></pre> <p>to:</p> <pre><code>#control-down { margin: 0.5em 0 0 0; }</code></pre> <p>(set the top margin of the &quot;down&quot; button to a fixed amount so it stays close to the &quot;up&quot; button&quot;).</p> <p>I also changed this rule:</p> <pre><code>#controls { height: 100%; width: 20%; padding: 5%; text-align: center; box-sizing: border-box; float: left; }</code></pre> <p>to:</p> <pre><code>#controls { height: 100%; width: 20%; padding: 0.5em; text-align: center; box-sizing: border-box; float: left; }</code></pre> <p>(padding changed from <code>5%</code> to <code>0.5em</code>). This fixes the spacing of the controls so that they stay a reasonable distance apart as the screen size changes.</p> <p>Here&#39;s the result:</p> <p><img src="/assets/space_dodge_game-zte_geek_resize_2.png" alt="space dodge game on ZTE Geek: landscape, fullscreen, viewport meta, resize, fixed margin"></p> <p>The buttons now look right, but the canvas is too tall for the screen (remember, its pixel height is set as an attribute on the canvas, not in CSS). This currently means you can move the spaceship off the bottom of the screen. The canvas needs to be resized to fit in the space to the right of the controls, while maintaining its aspect ratio.</p> <p>To do this, I applied the technique from the previous section, where I scaled the whole game to fit the screen. But in this case, just the canvas is scaled to fit into the area to the right of the controls. In addition, the canvas scaling should be done using its width and height attributes, rather than scaling it in CSS. (This is a bit confusing, as the height and width attributes of a canvas are different from the CSS height and width of its <code>&lt;canvas&gt;</code> element.)</p> <p>First, I added a new parent element for the canvas (the <code>&lt;div&gt;</code> with ID <code>play-area-container</code> below):</p> <pre><code>&lt;div id=&quot;container&quot;&gt; &lt;div id=&quot;game-screen&quot;&gt; &lt;div id=&quot;controls&quot; class=&quot;vbox&quot;&gt; &lt;p id=&quot;score&quot;&gt;Score&lt;br&gt;&lt;span id=&quot;score-display&quot;&gt;&lt;/span&gt;&lt;/p&gt; &lt;img id=&quot;control-up&quot; src=&quot;control-up.png&quot;&gt; &lt;img id=&quot;control-down&quot; src=&quot;control-down.png&quot;&gt; &lt;/div&gt; &lt;div id=&quot;play-area-container&quot;&gt; &lt;canvas id=&quot;play-area&quot; width=&quot;600&quot; height=&quot;450&quot;&gt;&lt;/canvas&gt; &lt;/div&gt; &lt;/div&gt; &lt;div id=&quot;finish-screen&quot; class=&quot;vbox&quot; data-visible=&quot;false&quot;&gt; &lt;p id=&quot;final-score&quot;&gt;&lt;/p&gt; &lt;button id=&quot;restart&quot;&gt;Restart&lt;/button&gt; &lt;/div&gt; &lt;/div&gt;</code></pre> <p>I modified the CSS so it&#39;s <code>play-area-container</code> and not <code>play-area</code> which is sized to fit the right-hand section of the game by changing:</p> <pre><code>#play-area { float: right; width: 80%; }</code></pre> <p>to:</p> <pre><code>#play-area-container { float: right; width: 80%; height: 100%; } #play-area { position: relative; box-sizing: border-box; border: 2px solid darkblue; }</code></pre> <p>I added a border to <code>play-area</code> so you can see where the play area really is, as it now won&#39;t necessarily fill its parent. This allows the player to see where the asteroids are going to come from (it might not be the right-hand edge of the screen any more). I also changed <code>play-area</code> to use <code>position: relative</code>, so it can be positioned relative to its parent (i.e. <code>play-area-container</code>).</p> <p>Then I used a variant of the scale algorithm from the previous section to fit the canvas into the <code>play-area-container</code>:</p> <pre><code>// the canvas element var playArea = document.querySelector(&#39;#play-area&#39;); // factor by which to modify canvas width and height var scaleCanvas = 1; var fitCanvas = function () { var container = document.querySelector(&#39;#play-area-container&#39;); var containerWidth = container.offsetWidth; var containerHeight = container.offsetHeight; var playAreaWidth = playArea.width; var playAreaHeight = playArea.height; var scaleWidth = containerWidth / playAreaWidth; var scaleHeight = containerHeight / playAreaHeight; scaleCanvas = (scaleHeight &lt; scaleWidth) ? scaleHeight : scaleWidth; var newPlayAreaWidth = playAreaWidth * scaleCanvas; var newPlayAreaHeight = playAreaHeight * scaleCanvas; var left = (containerWidth - newPlayAreaWidth) / 2; var top = (containerHeight - newPlayAreaHeight) / 2; // resize and position the canvas playArea.width = parseInt(newPlayAreaWidth, 10); playArea.height = parseInt(newPlayAreaHeight, 10); playArea.style.top = top + &#39;px&#39;; playArea.style.left = left + &#39;px&#39;; }; window.onresize = fitCanvas; fitCanvas();</code></pre> <p>Note that this changes the canvas width and height attributes then positions it, rather than scaling the canvas in CSS.</p> <p>This is the result on a ZTE Geek (canvas size is &quot;shrunk&quot; to 480px by 360px):</p> <p><img src="/assets/space_dodge_game_zte_geek_resize_canvas.png" alt="space dodge game on ZTE Geek: landscape, fullscreen, viewport meta, resize, fixed margin, canvas resized"></p> <h4>Resize the sprites</h4> <p>One side-effect of changing the canvas size is that the sprites are no longer in the same proportions as they were. Previously, the canvas was 600px wide and 450px high; the sprite for the spaceship is 75px wide by 44px tall, which is 12.5% of the canvas width and 10% of its height. But now the canvas size has changed; and the spaceship is now 16% of the width of the canvas and 12% of its height (i.e. it is relatively larger). This makes the game harder, as the asteroids will reach the ship sooner (they haven&#39;t got so far to travel). Conversely, on a large screen, the game is too easy: the spaceship takes up less of the canvas and the asteroids are further away.</p> <p>The solution is to draw the images onto a larger area of the canvas, so that their dimensions are always in the same ratio to the canvas dimensions. In the previous code fragment, I laid the foundation for this by recording the canvas scale factor in a variable outside the <code>fitCanvas()</code> function:</p> <pre><code>// factor by which to modify canvas width and height var scaleCanvas = 1;</code></pre> <p>After the first call to <code>fitCanvas()</code>, <code>scaleCanvas</code> is set to the canvas scale factor. To scale the sprites up, we can apply the same factor to the size of the sprites when they are drawn. In the code for the game, the images were previously written to the canvas like this:</p> <pre><code>ctx.drawImage(image, x, y, image.width, image.height);</code></pre> <p>(<code>ctx</code> is the canvas&#39; 2D context)</p> <p>This code can be modified as follows to draw the image at the correct scale:</p> <pre><code>ctx.drawImage( image, x, y, image.width * scaleCanvas, image.height * scaleCanvas );</code></pre> <p>The result is as follows (on the ZTE Geek again):</p> <p><img src="/assets/space_dodge_game-zte_geek_resize_canvas_2.png" alt="space dodge game on ZTE Geek: landscape, fullscreen, viewport meta, resize, fixed margin, canvas and sprites resized"></p> <p>Compare with the previous screenshot and you should be able to see that the ship and asteroids are slightly smaller in this screenshot (80% of the size of the previous one).</p> <p>The distances moved by the game objects are described in terms of multiples of their height (each control press moves the ship three times its own height per second, and asteroids move 3-5 times their width per second). This means that there is no need to modify any of the movement code, providing the scaled heights and widths are used in the calculations, for example:</p> <pre><code>// the ship height on screen is the Image height of the // loaded graphics file * the canvas scale factor var shipHeight = shipImg.height * scaleCanvas; // get the number of seconds since the last animation frame var timeDelta = (currentTime - lastTime) / 1000; // calculate movement on the y axis; // the player moves three times their own height per second; // direction = 1 for down, -1 for up var moveY = direction * shipHeight * timeDelta * 3;</code></pre> <p>Any other code which refers to the height and width of the sprites (such as the code for collision testing) will also have to apply the canvas scale. The simplest approach is to add functions for fetching the scaled height of the ship and the asteroids, then using those whenever the height and width of an <code>Image</code> object are required. For example:</p> <pre><code>// img is an Image object loaded with a ship or asteroid graphics // file function getImgWidth(img) { return img.width * scaleCanvas; } function getImgHeight(img) { return img.height * scaleCanvas; }</code></pre> <p>The movement code could then be rewritten as:</p> <pre><code>// get the number of seconds since the last animation frame var timeDelta = (currentTime - lastTime) / 1000; // calculate movement on the y axis; // the player moves three times their own height per second; // direction = 1 for down, -1 for up var moveY = direction * getImgHeight(shipImg) * timeDelta * 3;</code></pre> <p>Depending on the game and the environment, it may be possible to cache the width and height calculations. However, you have to be careful with this, ensuring that you invalidate the cached values if <code>canvasScale</code> changes (for example, if you resize the game when the window size changes). In my code, <code>fitCanvas()</code> is called each time the <code>onresize</code> event fires on the screen. This happens at least twice on a mobile device, while Crosswalk locks the screen orientation to landscape. For this reason, and to keep things simple, I dynamically get the height and width of the image each time, as this is relatively inexpensive for the two images I&#39;m using.</p> <h2>Issue 4: Sprites blur on large screens</h2> <p>Having applied the lessons in the previous section, one other possible issue is the potential for blurring due to scaling. If you take a close look at this image:</p> <p><img src="/assets/space_dodge_game-large_screen_blur.png" alt="space dodge game: sprites blur on large screens"></p> <p>you may notice that it appears blurry. This image was copied from a screenshot of a large browser window, where the sprite graphic was being scaled up to twice its original size, making it blur.</p> <p>One solution is to provide a larger graphic which can scale with less blurring, and use this graphic when the canvas is scaled up (<code>scaleCanvas &gt; 1</code>). The <code>src</code> attribute of the ship and asteroid <code>Image</code> objects can then be set inside the <code>fitCanvas()</code> function, depending on <code>scaleCanvas</code>:</p> <pre><code>// player ship image (to draw onto canvas) var ship = new Image(); // asteroid image (to draw onto canvas) var asteroid = new Image(); // the canvas element var playArea = document.querySelector(&#39;#play-area&#39;); // factor to modify canvas width and height by var scaleCanvas = 1; var fitCanvas = function () { var container = document.querySelector(&#39;#play-area-container&#39;); var containerWidth = container.offsetWidth; var containerHeight = container.offsetHeight; var playAreaWidth = playArea.width; var playAreaHeight = playArea.height; var scaleWidth = containerWidth / playAreaWidth; var scaleHeight = containerHeight / playAreaHeight; scaleCanvas = (scaleHeight &lt; scaleWidth) ? scaleHeight : scaleWidth; var newPlayAreaWidth = playAreaWidth * scaleCanvas; var newPlayAreaHeight = playAreaHeight * scaleCanvas; var left = (containerWidth - newPlayAreaWidth) / 2; var top = (containerHeight - newPlayAreaHeight) / 2; // resize and position the canvas playArea.width = parseInt(newPlayAreaWidth, 10); playArea.height = parseInt(newPlayAreaHeight, 10); playArea.style.top = top + &#39;px&#39;; playArea.style.left = left + &#39;px&#39;; // use a double-sized image if the canvas is being scaled up if (scaleCanvas &gt; 1) { ship.src = &#39;rocket2x.png&#39;; asteroid.src = &#39;asteroid2x.png&#39;; // reset the scale so that the double-sized images are scaled // down to the same size as the original image scaleCanvas /= 2; } // otherwise use the original-sized image else { ship.src = &#39;rocket.png&#39;; asteroid.src = &#39;asteroid.png&#39;; } }; window.onresize = fitCanvas; fitCanvas();</code></pre> <p>Compare the double-sized image when scaled down slightly (on the left) with the smaller image scaled up to twice its original size (on the right):</p> <p><img src="/assets/space_dodge_game-large_screen_less_blur.png" alt="space dodge game: large image scaled down vs small image scaled up"></p> <p>As you can see here, the large image scaled down is far less blurry than the small image scaled up.</p> <p>Depending on how large the images are, it might make sense to use larger images at all scales. But if you are trying to keep the size of the assets down, using different images for different scales may be a more viable approach.</p> <h2>Issue 5: We need a launch screen</h2> <p>Applications can sometimes take a while to load, due to network latency and/or sheer size and number of resources. This problem gets worse as the application grows and is especially problematic for games, where there are often a large number of graphical, audio and video assets in use. In such cases, a common technique is to show a screen with introductory images or text while the resources are loading, commonly known as a &quot;loading&quot; or &quot;launch&quot; screen. Frameworks often provide APIs to support this, or developers may add their own code to handle it.</p> <p>Crosswalk 8 and later provides baked-in support for launch screens, via an <code>xwalk_launch_screen</code> in the application manifest. This enables you to set background and foreground images and colours, differentiated according to screen orientation and pixel density if desired, with little or no programming. Full details of its capabilities are on the <a href="/documentation/manifest/launch_screen.html">launch screen page</a>.</p> <p>The steps below explain how to add a launch screen to the example game.</p> <ol> <li><p>First, add a foreground image <code>fg.png</code>. This is a simple graphic composed of the name of the game plus the rocket sprite, with a transparent background (I&#39;ve added a blue background to the graphic here so the white letters show up):</p> <p><img src="/assets/space_dodge_game-launch_screen_fg.png" alt="space dodge game launch screen foreground"></p> <p>I made the image relatively small (320px by 240px), as it should fit small mobile screens.</p> </li> <li><p>To activate the launch screen, add an <code>xwalk_launch_screen</code> field to the <code>manifest.json</code> file:</p> <pre><code>{ &quot;name&quot;: &quot;space_dodge_game&quot;, &quot;version&quot;: &quot;0.0.0.1&quot;, &quot;start_url&quot;: &quot;index.html&quot;, &quot;orientation&quot;: &quot;landscape&quot;, &quot;display&quot;: &quot;fullscreen&quot;, &quot;xwalk_launch_screen&quot;: { &quot;ready_when&quot;: &quot;custom&quot;, &quot;landscape&quot;: { &quot;background_color&quot;: &quot;#11f&quot;, &quot;image&quot;: &quot;fg.png&quot; } } }</code></pre> <p>The <code>ready_when</code> property specifies when to stop showing the launch screen. By setting this to <code>custom</code>, the launch screen can be closed programmatically once all the assets are loaded. This is the typical mode you would want to use for launch screens in an HTML5 game, as you will often be doing some initialisation work in JavaScript before the game is usable. In the next step, we&#39;ll add the code which does this.</p> <p>The <code>landscape</code> property specifies the background colour and <code>image</code> (foreground image) to use for the launch screen when in landscape mode. Any image paths are relative to <code>manifest.json</code>, and the foreground image will be centered on the background.</p> <p>As the application will always be in landscape orientation (<code>&quot;orientation&quot;: &quot;landscape&quot;</code> is set in the manifest), there&#39;s no need for a <code>portrait</code> property. Note that you may use the <code>default</code> key to specify the settings for all orientations; and can specify different backgrounds and images for different orientations and screen densities. See <a href="/documentation/manifest/launch_screen.html">this explanation</a> for more details about the available launch screen options.</p> </li> <li><p>The final step is to modify the JavaScript to close the launch screen.</p> <p>When the <code>ready_when</code> property is set to <code>custom</code>, the launch screen can be closed by calling the Crosswalk-specific <code>window.screen.show()</code> method. For this game, I added an artificial 5 second timeout before calling the <code>window.screen.show()</code> method (otherwise the game loads so quickly that you only see a flash of the launch screen). The code looks like this:</p> <pre><code>setTimeout(function () { // check that the window.screen.show method is available if (window.screen.show) { window.screen.show(); } gameLoop(); }, 5000);</code></pre> <p>The <code>gameLoop()</code> function starts the animation loop for the game, once the launch screen has been closed.</p> </li> </ol> <p>Now the application can be packaged as usual with <code>make_apk.py</code> and installed on a target. This is what the launch screen looks like on a ZTE Geek:</p> <p><img src="/assets/space_dodge_game_launch_screen-zte_geek.png" alt="space dodge game launch screen on ZTE Geek"></p> <h2>Summary</h2> <p>Fitting an HTML5 application into a mobile screen has been challenging in the past; the advent of new APIs and configuration options is gradually making things easier. Crosswalk provides pioneering support for such features: viewport management; advanced layout with CSS flexbox and viewport percentage lengths; manifest options for orientation, display and launch screens; plus many others. The result is a rich runtime environment for all applications, especially games.</p> <footer class="article-next"> <a href="/documentation/tutorials/webassembly.html" class="article-promo well"> <em>What’s next?</em> <h3>Web Assembly</h3> </a> </footer> </article> </div> </div> </div> <hr class="footer-divider" style="margin-top:125px; margin-bottom:0px" /> <div style="position:relative; top:-30px;"> <a href="/"><img src="/assets/cw-logo-circle.png" width="60px" style="display:block; margin: 0 auto;" /></a> </div> <footer class="footer footer--documentation" > <div class="container" > <div class="row"> <div class="footer-div" language="en"> <img src="/assets/Twitter_logo_blue.png" width="20px" /> Follow <a href="http://twitter.com/xwalk_project">@xwalk_project on Twitter</a> for the latest developer activities and project updates. </div> <div class="footer-div" language="zh" style="display:none"> <img src="/assets/Sina_Weibo_Blue.png" width="60px" /> 参考<a href="http://weibo.com/crosswalk">微博</a> 最新的开发者活动或者更新。 </div> <div class="footer-div"> Latest blog post:</br> <b><a href="/blog">Crosswalk 23 to be the last Crosswalk release</a></b><br/> &nbsp;(<span ><time class="js-vagueTime" datetime="Fri, 10 Feb 2017 09:30:00 GMT">2017-02-10T09:30</time></span>) <br/> </div> <div class="footer-div"> <strong><a href="/feed.xml"><img src="/assets/rss-icon-16.gif" style="vertical-align:middle" /> RSS Feed</a></strong> </div> <div class="footer-div"> <a href="/documentation/getting_started.html"> Documentation</a> &nbsp; <a href="/blog"> Blog</a> &nbsp; <a href="/documentation/downloads.html"> Downloads</a> <br /> <a href="https://crosswalk-project.org/jira/secure/Dashboard.jspa"> Issues</a> &nbsp; <a href="https://github.com/crosswalk-project"> GitHub Source</a> &nbsp; <a href="/sitemap.html">Sitemap</a> <br/> </div> </div> <div class="row"> <small> The Crosswalk Project was created by the Intel Open Source Technology Center. Copyright © 2013–2016 Intel Corporation. All right reserved. <a href="https://github.com/crosswalk-project/crosswalk-website/wiki/Privacy-Policy"> Privacy policy </a> *Other names and brands may be claimed as the property of others. </small> </div> </div> </footer> <script> $("[language=en]").css("display","none"); $("[language=en]").css("display","block"); </script> <!-- Google Tag Manager --> <noscript><iframe src="//www.googletagmanager.com/ns.html?id=GTM-WC843Q" height="0" width="0" style="display:none;visibility:hidden"></iframe></noscript> <script>(function(w,d,s,l,i){w[l]=w[l]||[];w[l].push({'gtm.start': new Date().getTime(),event:'gtm.js'});var f=d.getElementsByTagName(s)[0], j=d.createElement(s),dl=l!='dataLayer'?'&l='+l:'';j.async=true;j.src= '//www.googletagmanager.com/gtm.js?id='+i+dl;f.parentNode.insertBefore(j,f); })(window,document,'script','dataLayer','GTM-WC843Q');</script> <!-- End Google Tag Manager --> <script src="/js/smoothScroll.js"></script> <script src="/js/vagueTime.js"></script> <!-- <script async defer src="/js/trmix.js"></script> --> </body> </html>
{ "pile_set_name": "Github" }
<?xml version="1.0" encoding="UTF-8"?> <xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema"> <xs:annotation> <xs:documentation source="http://www.phpunit.de/manual/3.7/en/appendixes.configuration.html"> This Schema file defines the rules by which the XML configuration file of PHPUnit 3.7 may be structured. </xs:documentation> <xs:appinfo source="http://www.phpunit.de/manual/current/en/appendixes.configuration.html"/> </xs:annotation> <xs:element name="phpunit" type="phpUnitType"> <xs:annotation> <xs:documentation>Root Element</xs:documentation> </xs:annotation> </xs:element> <xs:complexType name="filtersType"> <xs:choice> <xs:sequence> <xs:element name="blacklist" type="filterType"/> <xs:element name="whitelist" type="whiteListType" minOccurs="0"/> </xs:sequence> <xs:sequence> <xs:element name="whitelist" type="whiteListType"/> </xs:sequence> </xs:choice> </xs:complexType> <xs:complexType name="filterType"> <xs:sequence> <xs:group ref="pathGroup"/> <xs:element name="exclude" maxOccurs="unbounded" minOccurs="0"> <xs:complexType> <xs:group ref="pathGroup"/> </xs:complexType> </xs:element> </xs:sequence> </xs:complexType> <xs:complexType name="whiteListType"> <xs:complexContent> <xs:extension base="filterType"> <xs:attribute name="processUncoveredFilesFromWhitelist" default="true" type="xs:boolean"/> </xs:extension> </xs:complexContent> </xs:complexType> <xs:complexType name="groupsType"> <xs:choice> <xs:sequence> <xs:element name="include" type="groupType"/> <xs:element name="exclude" type="groupType" minOccurs="0"/> </xs:sequence> <xs:sequence> <xs:element name="exclude" type="groupType"/> </xs:sequence> </xs:choice> </xs:complexType> <xs:complexType name="groupType"> <xs:sequence> <xs:element name="group" type="xs:string" maxOccurs="unbounded"/> </xs:sequence> </xs:complexType> <xs:complexType name="listenersType"> <xs:sequence> <xs:element name="listener" type="objectType" maxOccurs="unbounded"/> </xs:sequence> </xs:complexType> <xs:complexType name="objectType"> <xs:sequence> <xs:element name="arguments" minOccurs="0"> <xs:complexType> <xs:group ref="argumentsGroup"/> </xs:complexType> </xs:element> </xs:sequence> <xs:attribute name="class" type="xs:string" use="required"/> <xs:attribute name="file" type="xs:anyURI"/> </xs:complexType> <xs:complexType name="arrayType"> <xs:sequence> <xs:element name="element" type="argumentType" minOccurs="0" maxOccurs="unbounded"/> </xs:sequence> </xs:complexType> <xs:complexType name="argumentType"> <xs:group ref="argumentChoice"/> <xs:attribute name="key" use="required"/> </xs:complexType> <xs:group name="argumentsGroup"> <xs:sequence> <xs:element name="array" type="arrayType" minOccurs="0" maxOccurs="unbounded"/> <xs:element name="integer" type="xs:integer" minOccurs="0" maxOccurs="unbounded"/> <xs:element name="string" type="xs:string" minOccurs="0" maxOccurs="unbounded"/> <xs:element name="double" type="xs:double" minOccurs="0" maxOccurs="unbounded"/> <xs:element name="null" minOccurs="0" maxOccurs="unbounded"/> <xs:element name="object" type="objectType" minOccurs="0" maxOccurs="unbounded"/> <xs:element name="file" type="xs:anyURI" minOccurs="0" maxOccurs="unbounded"/> <xs:element name="directory" type="xs:anyURI" minOccurs="0" maxOccurs="unbounded"/> </xs:sequence> </xs:group> <xs:group name="argumentChoice"> <xs:choice> <xs:element name="array" type="arrayType" minOccurs="0" maxOccurs="unbounded"/> <xs:element name="integer" type="xs:integer" minOccurs="0" maxOccurs="unbounded"/> <xs:element name="string" type="xs:string" minOccurs="0" maxOccurs="unbounded"/> <xs:element name="double" type="xs:double" minOccurs="0" maxOccurs="unbounded"/> <xs:element name="null" minOccurs="0" maxOccurs="unbounded"/> <xs:element name="object" type="objectType" minOccurs="0" maxOccurs="unbounded"/> <xs:element name="file" type="xs:anyURI" minOccurs="0" maxOccurs="unbounded"/> <xs:element name="directory" type="xs:anyURI" minOccurs="0" maxOccurs="unbounded"/> </xs:choice> </xs:group> <xs:complexType name="loggersType"> <xs:sequence> <xs:element name="log" type="loggerType" maxOccurs="unbounded"/> </xs:sequence> </xs:complexType> <xs:complexType name="loggerType"> <xs:attribute name="type"> <xs:simpleType> <xs:restriction base="xs:string"> <xs:enumeration value="coverage-html"/> <xs:enumeration value="coverage-clover"/> <xs:enumeration value="json"/> <xs:enumeration value="plain"/> <xs:enumeration value="tap"/> <xs:enumeration value="junit"/> <xs:enumeration value="testdox-html"/> <xs:enumeration value="testdox-text"/> </xs:restriction> </xs:simpleType> </xs:attribute> <xs:attribute name="target" type="xs:anyURI"/> <xs:attribute name="title" type="xs:string"/> <xs:attribute name="charset" type="xs:string" default="UTF-8"/> <xs:attribute name="yui" type="xs:boolean" default="true"/> <xs:attribute name="highlight" type="xs:boolean" default="false"/> <xs:attribute name="lowUpperBound" type="xs:nonNegativeInteger" default="35"/> <xs:attribute name="highLowerBound" type="xs:nonNegativeInteger" default="70"/> <xs:attribute name="logIncompleteSkipped" type="xs:boolean" default="false"/> </xs:complexType> <xs:group name="pathGroup"> <xs:sequence> <xs:element name="directory" type="directoryFilterType" minOccurs="0" maxOccurs="unbounded"/> <xs:element name="file" type="fileFilterType" minOccurs="0" maxOccurs="unbounded"/> </xs:sequence> </xs:group> <xs:complexType name="directoryFilterType"> <xs:simpleContent> <xs:extension base="xs:anyURI"> <xs:attribute type="xs:string" name="suffix" default="Test.php"/> <xs:attributeGroup ref="phpVersionGroup"/> </xs:extension> </xs:simpleContent> </xs:complexType> <xs:complexType name="fileFilterType"> <xs:simpleContent> <xs:extension base="xs:anyURI"> <xs:attributeGroup ref="phpVersionGroup"/> </xs:extension> </xs:simpleContent> </xs:complexType> <xs:attributeGroup name="phpVersionGroup"> <xs:attribute name="phpVersion" type="xs:string" default="5.3.0"/> <xs:attribute name="phpVersionOperator" type="xs:string" default="&gt;="/> </xs:attributeGroup> <xs:complexType name="phpType"> <xs:sequence> <xs:element name="includePath" type="xs:anyURI" minOccurs="0" maxOccurs="unbounded"/> <xs:element name="ini" type="namedValueType" minOccurs="0" maxOccurs="unbounded"/> <xs:element name="const" type="namedValueType" minOccurs="0" maxOccurs="unbounded"/> <xs:element name="var" type="namedValueType" minOccurs="0" maxOccurs="unbounded"/> <xs:element name="env" type="namedValueType" minOccurs="0" maxOccurs="unbounded"/> <xs:element name="post" type="namedValueType" minOccurs="0" maxOccurs="unbounded"/> <xs:element name="get" type="namedValueType" minOccurs="0" maxOccurs="unbounded"/> <xs:element name="cookie" type="namedValueType" minOccurs="0" maxOccurs="unbounded"/> <xs:element name="server" type="namedValueType" minOccurs="0" maxOccurs="unbounded"/> <xs:element name="files" type="namedValueType" minOccurs="0" maxOccurs="unbounded"/> <xs:element name="request" type="namedValueType" minOccurs="0" maxOccurs="unbounded"/> </xs:sequence> </xs:complexType> <xs:complexType name="namedValueType"> <xs:attribute name="name" use="required" type="xs:string"/> <xs:attribute name="value" use="required" type="xs:anySimpleType"/> </xs:complexType> <xs:complexType name="phpUnitType"> <xs:annotation> <xs:documentation>The main type specifying the document structure</xs:documentation> </xs:annotation> <xs:group ref="configGroup"/> <xs:attributeGroup ref="configAttributeGroup"/> </xs:complexType> <xs:attributeGroup name="configAttributeGroup"> <xs:attribute name="backupGlobals" type="xs:boolean" default="true"/> <xs:attribute name="backupStaticAttributes" type="xs:boolean" default="false"/> <xs:attribute name="bootstrap" type="xs:anyURI"/> <xs:attribute name="cacheTokens" type="xs:boolean"/> <xs:attribute name="colors" type="xs:boolean" default="false"/> <xs:attribute name="convertErrorsToExceptions" type="xs:boolean" default="true"/> <xs:attribute name="convertNoticesToExceptions" type="xs:boolean" default="true"/> <xs:attribute name="convertWarningsToExceptions" type="xs:boolean" default="true"/> <xs:attribute name="forceCoversAnnotation" type="xs:boolean" default="false"/> <xs:attribute name="mapTestClassNameToCoveredClassName" type="xs:boolean" default="false"/> <xs:attribute name="printerClass" type="xs:string" default="PHPUnit_TextUI_ResultPrinter"/> <xs:attribute name="printerFile" type="xs:anyURI"/> <xs:attribute name="processIsolation" type="xs:boolean" default="false"/> <xs:attribute name="stopOnError" type="xs:boolean" default="false"/> <xs:attribute name="stopOnFailure" type="xs:boolean" default="false"/> <xs:attribute name="stopOnIncomplete" type="xs:boolean" default="false"/> <xs:attribute name="stopOnSkipped" type="xs:boolean" default="false"/> <xs:attribute name="strict" type="xs:boolean" default="false"/> <xs:attribute name="testSuiteLoaderClass" type="xs:string" default="PHPUnit_Runner_StandardTestSuiteLoader"/> <xs:attribute name="testSuiteLoaderFile" type="xs:anyURI"/> <xs:attribute name="timeoutForSmallTests" type="xs:integer" default="1"/> <xs:attribute name="timeoutForMediumTests" type="xs:integer" default="10"/> <xs:attribute name="timeoutForLargeTests" type="xs:integer" default="60"/> <xs:attribute name="verbose" type="xs:boolean" default="false"/> </xs:attributeGroup> <xs:group name="configGroup"> <xs:all> <xs:element ref="testSuiteFacet" minOccurs="0"/> <xs:element name="groups" type="groupsType" minOccurs="0"/> <xs:element name="filter" type="filtersType" minOccurs="0"/> <xs:element name="logging" type="loggersType" minOccurs="0"/> <xs:element name="listeners" type="listenersType" minOccurs="0"/> <xs:element name="php" type="phpType" minOccurs="0"/> <xs:element name="selenium" type="seleniumType" minOccurs="0"/> </xs:all> </xs:group> <xs:complexType name="seleniumType"> <xs:sequence> <xs:element name="browser" type="browserType"/> </xs:sequence> </xs:complexType> <xs:complexType name="browserType"> <xs:attribute name="name" type="xs:string"/> <xs:attribute name="browser" type="xs:string"/> <xs:attribute name="host" type="xs:anyURI"/> <xs:attribute name="port" type="xs:nonNegativeInteger"/> <xs:attribute name="timeout" type="xs:nonNegativeInteger"/> </xs:complexType> <xs:element name="testSuiteFacet" abstract="true"/> <xs:element name="testsuite" type="testSuiteType" substitutionGroup="testSuiteFacet"/> <xs:element name="testsuites" type="testSuitesType" substitutionGroup="testSuiteFacet"/> <xs:complexType name="testSuitesType"> <xs:sequence> <xs:element name="testsuite" type="testSuiteType"/> </xs:sequence> </xs:complexType> <xs:complexType name="testSuiteType"> <xs:sequence> <xs:group ref="pathGroup"/> <xs:element name="exclude" type="xs:anyURI" minOccurs="0" maxOccurs="unbounded"/> </xs:sequence> <xs:attribute name="name" type="xs:string" use="required"/> </xs:complexType> </xs:schema>
{ "pile_set_name": "Github" }
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System; using System.Collections.Generic; using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.Editor.Shared.Tagging; using Microsoft.CodeAnalysis.Shared.Collections; using Microsoft.CodeAnalysis.Shared.TestHooks; using Microsoft.CodeAnalysis.Text; using Microsoft.VisualStudio.Text; using Microsoft.VisualStudio.Text.Tagging; namespace Microsoft.CodeAnalysis.Editor.Implementation.Diagnostics { internal abstract partial class AbstractAggregatedDiagnosticsTagSource<TTag> : TagSource<TTag> where TTag : ITag { private readonly DiagnosticService _service; private readonly Mode _mode; protected AbstractAggregatedDiagnosticsTagSource( ITextBuffer subjectBuffer, IForegroundNotificationService notificationService, DiagnosticService service, IAsynchronousOperationListener asyncListener) : base(subjectBuffer, notificationService, asyncListener) { _service = service; _mode = GetMode(subjectBuffer); } private Mode GetMode(ITextBuffer subjectBuffer) { Workspace workspace; if (Workspace.TryGetWorkspace(subjectBuffer.AsTextContainer(), out workspace) && workspace.Kind == WorkspaceKind.Preview) { return new ReadOnlyMode(this); } return new InteractiveMode(this); } protected override void Disconnect() { base.Disconnect(); _mode.Disconnect(); } protected abstract int MinimumLength { get; } protected abstract bool ShouldInclude(DiagnosticData diagnostic); protected abstract TagSpan<TTag> CreateTagSpan(SnapshotSpan span, DiagnosticData diagnostic); public override ITagSpanIntervalTree<TTag> GetTagIntervalTreeForBuffer(ITextBuffer buffer) { if (buffer == this.SubjectBuffer) { return _mode; } return null; } private static SnapshotSpan AdjustSnapshotSpan(SnapshotSpan span, int minimumLength) { var snapshot = span.Snapshot; // new length var length = Math.Max(span.Length, minimumLength); // make sure start + length is smaller than snapshot.Length and start is >= 0 var start = Math.Max(0, Math.Min(span.Start, snapshot.Length - length)); // make sure length is smaller than snapshot.Length which can happen if start == 0 return new SnapshotSpan(snapshot, start, Math.Min(start + length, snapshot.Length) - start); } protected override void RecomputeTagsForeground() { // do nothing, we don't use this. } private class IntervalIntrospector : IIntervalIntrospector<Data> { public readonly ITextSnapshot Snapshot; public IntervalIntrospector(ITextSnapshot snapshot) { this.Snapshot = snapshot; } public int GetStart(Data value) { return value.TrackingSpan.GetStartPoint(this.Snapshot); } public int GetLength(Data value) { return value.TrackingSpan.GetSpan(this.Snapshot).Length; } } private struct Data { public readonly DiagnosticData Diagnostic; public readonly ITrackingSpan TrackingSpan; public Data(DiagnosticData diagnostic, ITrackingSpan trackingSpan) { this.Diagnostic = diagnostic; this.TrackingSpan = trackingSpan; } public bool IsDefault { get { return this.Diagnostic == null; } } public SnapshotSpan GetSnapshotSpan(ITextSnapshot snapshot, int minimumLength) { var span = this.TrackingSpan.GetSpan(snapshot); return AdjustSnapshotSpan(span, minimumLength); } } private abstract class Mode : ITagSpanIntervalTree<TTag> { protected readonly AbstractAggregatedDiagnosticsTagSource<TTag> Owner; public Mode(AbstractAggregatedDiagnosticsTagSource<TTag> owner) { this.Owner = owner; } public abstract void Disconnect(); public abstract IList<ITagSpan<TTag>> GetIntersectingSpans(SnapshotSpan snapshotSpan); protected DiagnosticService DiagnosticService { get { return this.Owner._service; } } protected ITextBuffer SubjectBuffer { get { return this.Owner.SubjectBuffer; } } protected IAsynchronousOperationListener Listener { get { return this.Owner.Listener; } } protected void RefreshEntireBuffer() { var snapshot = this.SubjectBuffer.CurrentSnapshot; this.Owner.RaiseTagsChanged(this.SubjectBuffer, new NormalizedSnapshotSpanCollection(snapshot, new Span(0, snapshot.Length))); } } } }
{ "pile_set_name": "Github" }
/* @flow */ /** * context */ context('desc', () => {}); // $FlowExpectedError number. This type is incompatible with function type. context('desc', 12); // $FlowExpectedError number. This type is incompatible with undefined. context('desc', () => 1); // $FlowExpectedError number. This type is incompatible with string. context(12, () => {}); /** * context.skip */ context.skip('desc', () => {}); // $FlowExpectedError number. This type is incompatible with function type. context.skip('desc', 12); // $FlowExpectedError number. This type is incompatible with undefined. context.skip('desc', () => 1); // $FlowExpectedError number. This type is incompatible with string. context.skip(12, () => {}); /** * context.only */ context.only('desc', () => {}); // $FlowExpectedError number. This type is incompatible with function type. context.only('desc', 12); // $FlowExpectedError number. This type is incompatible with undefined. context.only('desc', () => 1); // $FlowExpectedError number. This type is incompatible with string. context.only(12, () => {}); /** * context.timeout */ context.timeout(1000); // $FlowExpectedError string. This type is incompatible with number. context.timeout('1000');
{ "pile_set_name": "Github" }
from __future__ import division, absolute_import, print_function import os from numpy.distutils.fcompiler import FCompiler compilers = ['LaheyFCompiler'] class LaheyFCompiler(FCompiler): compiler_type = 'lahey' description = 'Lahey/Fujitsu Fortran 95 Compiler' version_pattern = r'Lahey/Fujitsu Fortran 95 Compiler Release (?P<version>[^\s*]*)' executables = { 'version_cmd' : ["<F90>", "--version"], 'compiler_f77' : ["lf95", "--fix"], 'compiler_fix' : ["lf95", "--fix"], 'compiler_f90' : ["lf95"], 'linker_so' : ["lf95", "-shared"], 'archiver' : ["ar", "-cr"], 'ranlib' : ["ranlib"] } module_dir_switch = None #XXX Fix me module_include_switch = None #XXX Fix me def get_flags_opt(self): return ['-O'] def get_flags_debug(self): return ['-g', '--chk', '--chkglobal'] def get_library_dirs(self): opt = [] d = os.environ.get('LAHEY') if d: opt.append(os.path.join(d, 'lib')) return opt def get_libraries(self): opt = [] opt.extend(['fj9f6', 'fj9i6', 'fj9ipp', 'fj9e6']) return opt if __name__ == '__main__': from distutils import log log.set_verbosity(2) from numpy.distutils import customized_fcompiler print(customized_fcompiler(compiler='lahey').get_version())
{ "pile_set_name": "Github" }
function! asyncomplete#sources#ale#get_source_options(...) abort let l:default = extend({ \ 'name': 'ale', \ 'completor': function('asyncomplete#sources#ale#completor'), \ 'whitelist': ['*'], \ 'triggers': asyncomplete#sources#ale#get_triggers(), \ }, a:0 >= 1 ? a:1 : {}) return extend(l:default, {'refresh_pattern': '\k\+$'}) endfunction function! asyncomplete#sources#ale#get_triggers() abort let l:triggers = ale#completion#GetAllTriggers() let l:triggers['*'] = l:triggers['<default>'] return l:triggers endfunction function! asyncomplete#sources#ale#completor(options, context) abort let l:keyword = matchstr(a:context.typed, '\w\+$') let l:startcol = a:context.col - len(l:keyword) call ale#completion#GetCompletions('ale-callback', { 'callback': {completions -> \ asyncomplete#complete(a:options.name, a:context, l:startcol, completions) \ }}) endfunction
{ "pile_set_name": "Github" }
/* eslint-env jest */ import filterReduce from './filter-reduce' const add = (a, b) => a + b const data = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] const isEven = x => !(x & 1) it('filterReduce', () => { // Returns all elements not matching the predicate and the result of // a reduction over those who do. expect(filterReduce(data, isEven, add)).toEqual([1, 3, 5, 7, 9, 20]) // The default reducer is the identity. expect(filterReduce(data, isEven)).toEqual([1, 3, 5, 7, 9, 0]) // If an initial value is passed it is used. expect(filterReduce(data, isEven, add, 22)).toEqual([1, 3, 5, 7, 9, 42]) })
{ "pile_set_name": "Github" }
/* * Copyright 2011 The LibYuv Project Authors. All rights reserved. * * Use of this source code is governed by a BSD-style license * that can be found in the LICENSE file in the root of the source * tree. An additional intellectual property rights grant can be found * in the file PATENTS. All contributing project authors may * be found in the AUTHORS file in the root of the source tree. */ #ifndef INCLUDE_LIBYUV_SCALE_H_ // NOLINT #define INCLUDE_LIBYUV_SCALE_H_ #include "basic_types.h" #ifdef __cplusplus namespace libyuv { extern "C" { #endif // Supported filtering. typedef enum FilterMode { kFilterNone = 0, // Point sample; Fastest. kFilterLinear = 1, // Filter horizontally only. kFilterBilinear = 2, // Faster than box, but lower quality scaling down. kFilterBox = 3 // Highest quality. } FilterModeEnum; // Scale a YUV plane. LIBYUV_API void ScalePlane(const uint8* src, int src_stride, int src_width, int src_height, uint8* dst, int dst_stride, int dst_width, int dst_height, enum FilterMode filtering); LIBYUV_API void ScalePlane_16(const uint16* src, int src_stride, int src_width, int src_height, uint16* dst, int dst_stride, int dst_width, int dst_height, enum FilterMode filtering); // Scales a YUV 4:2:0 image from the src width and height to the // dst width and height. // If filtering is kFilterNone, a simple nearest-neighbor algorithm is // used. This produces basic (blocky) quality at the fastest speed. // If filtering is kFilterBilinear, interpolation is used to produce a better // quality image, at the expense of speed. // If filtering is kFilterBox, averaging is used to produce ever better // quality image, at further expense of speed. // Returns 0 if successful. LIBYUV_API int I420Scale(const uint8* src_y, int src_stride_y, const uint8* src_u, int src_stride_u, const uint8* src_v, int src_stride_v, int src_width, int src_height, uint8* dst_y, int dst_stride_y, uint8* dst_u, int dst_stride_u, uint8* dst_v, int dst_stride_v, int dst_width, int dst_height, enum FilterMode filtering); LIBYUV_API int I420Scale_16(const uint16* src_y, int src_stride_y, const uint16* src_u, int src_stride_u, const uint16* src_v, int src_stride_v, int src_width, int src_height, uint16* dst_y, int dst_stride_y, uint16* dst_u, int dst_stride_u, uint16* dst_v, int dst_stride_v, int dst_width, int dst_height, enum FilterMode filtering); #ifdef __cplusplus // Legacy API. Deprecated. LIBYUV_API int Scale(const uint8* src_y, const uint8* src_u, const uint8* src_v, int src_stride_y, int src_stride_u, int src_stride_v, int src_width, int src_height, uint8* dst_y, uint8* dst_u, uint8* dst_v, int dst_stride_y, int dst_stride_u, int dst_stride_v, int dst_width, int dst_height, LIBYUV_BOOL interpolate); // Legacy API. Deprecated. LIBYUV_API int ScaleOffset(const uint8* src_i420, int src_width, int src_height, uint8* dst_i420, int dst_width, int dst_height, int dst_yoffset, LIBYUV_BOOL interpolate); // For testing, allow disabling of specialized scalers. LIBYUV_API void SetUseReferenceImpl(LIBYUV_BOOL use); #endif // __cplusplus #ifdef __cplusplus } // extern "C" } // namespace libyuv #endif #endif // INCLUDE_LIBYUV_SCALE_H_ NOLINT
{ "pile_set_name": "Github" }
// // DetectedIssueTests.swift // SwiftFHIR // // Generated from FHIR 4.0.0-a53ec6ee1b on 2019-05-21. // 2019, SMART Health IT. // import XCTest #if !NO_MODEL_IMPORT import Models typealias SwiftFHIRDetectedIssue = Models.DetectedIssue #else import SwiftFHIR typealias SwiftFHIRDetectedIssue = SwiftFHIR.DetectedIssue #endif class DetectedIssueTests: XCTestCase { func instantiateFrom(filename: String) throws -> SwiftFHIRDetectedIssue { return try instantiateFrom(json: try readJSONFile(filename)) } func instantiateFrom(json: FHIRJSON) throws -> SwiftFHIRDetectedIssue { return try SwiftFHIRDetectedIssue(json: json) } func testDetectedIssue1() { do { let instance = try runDetectedIssue1() try runDetectedIssue1(instance.asJSON()) } catch let error { XCTAssertTrue(false, "Must instantiate and test DetectedIssue successfully, but threw:\n---\n\(error)\n---") } } @discardableResult func runDetectedIssue1(_ json: FHIRJSON? = nil) throws -> SwiftFHIRDetectedIssue { let inst = (nil != json) ? try instantiateFrom(json: json!) : try instantiateFrom(filename: "detectedissue-example-allergy.json") XCTAssertEqual(inst.id, "allergy") XCTAssertEqual(inst.meta?.tag?[0].code, "HTEST") XCTAssertEqual(inst.meta?.tag?[0].display, "test health data") XCTAssertEqual(inst.meta?.tag?[0].system?.absoluteString, "http://terminology.hl7.org/CodeSystem/v3-ActReason") XCTAssertEqual(inst.status, ObservationStatus(rawValue: "final")!) XCTAssertEqual(inst.text?.div, "<div xmlns=\"http://www.w3.org/1999/xhtml\">[Put rendering here]</div>") XCTAssertEqual(inst.text?.status, NarrativeStatus(rawValue: "generated")!) return inst } func testDetectedIssue2() { do { let instance = try runDetectedIssue2() try runDetectedIssue2(instance.asJSON()) } catch let error { XCTAssertTrue(false, "Must instantiate and test DetectedIssue successfully, but threw:\n---\n\(error)\n---") } } @discardableResult func runDetectedIssue2(_ json: FHIRJSON? = nil) throws -> SwiftFHIRDetectedIssue { let inst = (nil != json) ? try instantiateFrom(json: json!) : try instantiateFrom(filename: "detectedissue-example-dup.json") XCTAssertEqual(inst.author?.reference, "Device/software") XCTAssertEqual(inst.code?.coding?[0].code, "DUPTHPY") XCTAssertEqual(inst.code?.coding?[0].display, "Duplicate Therapy Alert") XCTAssertEqual(inst.code?.coding?[0].system?.absoluteString, "http://terminology.hl7.org/CodeSystem/v3-ActCode") XCTAssertEqual(inst.detail, "Similar test was performed within the past 14 days") XCTAssertEqual(inst.id, "duplicate") XCTAssertEqual(inst.identifiedDateTime?.description, "2013-05-08") XCTAssertEqual(inst.identifier?[0].system?.absoluteString, "http://example.org") XCTAssertEqual(inst.identifier?[0].use, IdentifierUse(rawValue: "official")!) XCTAssertEqual(inst.identifier?[0].value, "12345") XCTAssertEqual(inst.implicated?[0].display, "Chest CT - ordered May 8, 2013 by Dr. Adam Careful") XCTAssertEqual(inst.implicated?[0].reference, "ServiceRequest/di") XCTAssertEqual(inst.implicated?[1].display, "Image 1 from Series 3: CT Images on Patient MINT (MINT1234) taken at 1-Jan 2011 01:20 AM") XCTAssertEqual(inst.implicated?[1].reference, "ImagingStudy/example") XCTAssertEqual(inst.meta?.tag?[0].code, "HTEST") XCTAssertEqual(inst.meta?.tag?[0].display, "test health data") XCTAssertEqual(inst.meta?.tag?[0].system?.absoluteString, "http://terminology.hl7.org/CodeSystem/v3-ActReason") XCTAssertEqual(inst.patient?.reference, "Patient/dicom") XCTAssertEqual(inst.reference?.absoluteString, "http://www.tmhp.com/RadiologyClinicalDecisionSupport/2011/CHEST%20IMAGING%20GUIDELINES%202011.pdf") XCTAssertEqual(inst.status, ObservationStatus(rawValue: "final")!) XCTAssertEqual(inst.text?.status, NarrativeStatus(rawValue: "generated")!) return inst } func testDetectedIssue3() { do { let instance = try runDetectedIssue3() try runDetectedIssue3(instance.asJSON()) } catch let error { XCTAssertTrue(false, "Must instantiate and test DetectedIssue successfully, but threw:\n---\n\(error)\n---") } } @discardableResult func runDetectedIssue3(_ json: FHIRJSON? = nil) throws -> SwiftFHIRDetectedIssue { let inst = (nil != json) ? try instantiateFrom(json: json!) : try instantiateFrom(filename: "detectedissue-example.json") XCTAssertEqual(inst.author?.reference, "Device/software") XCTAssertEqual(inst.code?.coding?[0].code, "DRG") XCTAssertEqual(inst.code?.coding?[0].display, "Drug Interaction Alert") XCTAssertEqual(inst.code?.coding?[0].system?.absoluteString, "http://terminology.hl7.org/CodeSystem/v3-ActCode") XCTAssertEqual(inst.id, "ddi") XCTAssertEqual(inst.identifiedDateTime?.description, "2014-01-05") XCTAssertEqual(inst.implicated?[0].display, "500 mg Acetaminophen tablet 1/day, PRN since 2010") XCTAssertEqual(inst.implicated?[0].reference, "MedicationStatement/example001") XCTAssertEqual(inst.implicated?[1].display, "Warfarin 1 MG TAB prescribed Jan. 15, 2015") XCTAssertEqual(inst.implicated?[1].reference, "MedicationRequest/medrx0331") XCTAssertEqual(inst.meta?.tag?[0].code, "HTEST") XCTAssertEqual(inst.meta?.tag?[0].display, "test health data") XCTAssertEqual(inst.meta?.tag?[0].system?.absoluteString, "http://terminology.hl7.org/CodeSystem/v3-ActReason") XCTAssertEqual(inst.mitigation?[0].action?.coding?[0].code, "13") XCTAssertEqual(inst.mitigation?[0].action?.coding?[0].display, "Stopped Concurrent Therapy") XCTAssertEqual(inst.mitigation?[0].action?.coding?[0].system?.absoluteString, "http://terminology.hl7.org/CodeSystem/v3-ActCode") XCTAssertEqual(inst.mitigation?[0].action?.text, "Asked patient to discontinue regular use of Tylenol and to consult with clinician if they need to resume to allow appropriate INR monitoring") XCTAssertEqual(inst.mitigation?[0].author?.display, "Dr. Adam Careful") XCTAssertEqual(inst.mitigation?[0].author?.reference, "Practitioner/example") XCTAssertEqual(inst.mitigation?[0].date?.description, "2014-01-05") XCTAssertEqual(inst.severity, DetectedIssueSeverity(rawValue: "high")!) XCTAssertEqual(inst.status, ObservationStatus(rawValue: "final")!) XCTAssertEqual(inst.text?.status, NarrativeStatus(rawValue: "generated")!) return inst } func testDetectedIssue4() { do { let instance = try runDetectedIssue4() try runDetectedIssue4(instance.asJSON()) } catch let error { XCTAssertTrue(false, "Must instantiate and test DetectedIssue successfully, but threw:\n---\n\(error)\n---") } } @discardableResult func runDetectedIssue4(_ json: FHIRJSON? = nil) throws -> SwiftFHIRDetectedIssue { let inst = (nil != json) ? try instantiateFrom(json: json!) : try instantiateFrom(filename: "detectedissue-example-lab.json") XCTAssertEqual(inst.id, "lab") XCTAssertEqual(inst.meta?.tag?[0].code, "HTEST") XCTAssertEqual(inst.meta?.tag?[0].display, "test health data") XCTAssertEqual(inst.meta?.tag?[0].system?.absoluteString, "http://terminology.hl7.org/CodeSystem/v3-ActReason") XCTAssertEqual(inst.status, ObservationStatus(rawValue: "final")!) XCTAssertEqual(inst.text?.div, "<div xmlns=\"http://www.w3.org/1999/xhtml\">[Put rendering here]</div>") XCTAssertEqual(inst.text?.status, NarrativeStatus(rawValue: "generated")!) return inst } }
{ "pile_set_name": "Github" }
#!/bin/sh br_load_config() { local arg1 arg2 line while read line do arg1=`echo $line | cut -d " " -f 1` arg2=`echo $line | cut -d " " -f 2` case $arg1 in "HIDE_PORT") br_hide_port=$arg2;; "HIDE_FILE") br_hide_file=$arg2;; "HIDE_PROC") br_hide_proc=$arg2;; "REMOTE_HOST") br_remote_host=$arg2;; "REMOTE_PORT") br_remote_port=$arg2;; "SLEEP_TIME") br_sleep_time=$arg2;; esac done < $1 } br_display_config() { echo -e "HIDE_PORT:" echo $br_hide_port echo -e "HIDE_FILE:" echo $br_hide_file echo -e "HIDE_PROC:" echo $br_hide_proc echo -e "REMOTE_HOST:" echo $br_remote_host echo -e "REMOTE_PORT:" echo $br_remote_port echo -e "SLEEP_TIME:" echo $br_sleep_time } br_load_config "/home/$USER/.../brsh.conf" #br_display_config
{ "pile_set_name": "Github" }
/* * Copyright 2016 the original author or 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 org.gradle.plugins.ide.tooling.r214 import org.gradle.integtests.tooling.fixture.TargetGradleVersion import org.gradle.integtests.tooling.fixture.ToolingApiSpecification import org.gradle.test.fixtures.maven.MavenFileModule import org.gradle.test.fixtures.maven.MavenFileRepository import org.gradle.tooling.model.eclipse.EclipseExternalDependency import org.gradle.tooling.model.eclipse.EclipseProject import org.gradle.tooling.model.eclipse.EclipseProjectDependency @TargetGradleVersion('>=2.14') class ToolingApiEclipseModelWtpClasspathAttributesCrossVersionSpec extends ToolingApiSpecification { String localMaven def setup() { MavenFileRepository mavenRepo = new MavenFileRepository(file("maven-repo")) MavenFileModule exampleApi = mavenRepo.module("org.example", "example-api", "1.0") MavenFileModule exampleLib = mavenRepo.module("org.example", "example-lib", "1.0") exampleLib.dependsOn(exampleApi) exampleApi.publish() exampleLib.publish() localMaven = "maven { url '${mavenRepo.uri}' }" } def "Dependencies of a non-wtp project have no wtp deployment attributes"() { given: settingsFile << "include 'sub'" buildFile << """apply plugin: 'java' repositories { $localMaven } dependencies { compile 'org.example:example-api:1.0' compile project(':sub') } project(':sub') { apply plugin : 'java' } """ when: EclipseProject eclipseProject = loadToolingModel(EclipseProject) Collection<EclipseExternalDependency> externalDependencies = eclipseProject.getClasspath() Collection<EclipseProjectDependency> projectDependencies = eclipseProject.getProjectDependencies() then: externalDependencies.size() == 1 entryHasNoDeploymentInfo(externalDependencies[0]) projectDependencies.size() == 1 entryHasNoDeploymentInfo(projectDependencies[0]) } def "Web project dependencies have wtp deployment attributes"() { given: String pluginDeclaration = appliedPlugins.collect { "apply plugin: '$it'" }.join('\n') buildFile << """apply plugin: 'java' $pluginDeclaration repositories { $localMaven } dependencies { compile 'org.example:example-api:1.0' } """ when: EclipseProject eclipseProject = loadToolingModel(EclipseProject) Collection<EclipseExternalDependency> classpath = eclipseProject.getClasspath() then: classpath.size() == 1 entryHasDeploymentInfo(classpath[0]) where: appliedPlugins | _ ['war'] | _ ['war', 'eclipse-wtp'] | _ ['ear'] | _ ['ear', 'eclipse-wtp'] | _ } def "Wtp utility projects do not deploy any dependencies"() { given: buildFile << """apply plugin: 'java' apply plugin: 'eclipse-wtp' repositories { $localMaven } dependencies { compile 'org.example:example-lib:1.0' } """ when: EclipseProject eclipseProject = loadToolingModel(EclipseProject) Collection<EclipseExternalDependency> classpath = eclipseProject.getClasspath() then: classpath.size() == 2 entryNotDeployed(classpath[0]) entryNotDeployed(classpath[1]) } def "Root wtp dependencies and their transitives are deployed to '/'"() { given: buildFile << """apply plugin: 'java' apply plugin: 'war' apply plugin: 'eclipse-wtp' repositories { $localMaven } dependencies { compile 'org.example:example-lib:1.0' } eclipse.wtp.component.rootConfigurations += [ configurations.compile ] """ when: EclipseProject eclipseProject = loadToolingModel(EclipseProject) Collection<EclipseExternalDependency> classpath = eclipseProject.getClasspath() then: classpath.size() == 2 entryIsDeployed(classpath[0], '/') entryIsDeployed(classpath[1], '/') } def "Root wtp dependencies present in minusConfigurations are excluded from deployment"() { given: buildFile << """apply plugin: 'java' apply plugin: 'war' apply plugin: 'eclipse-wtp' repositories { $localMaven } dependencies { providedRuntime 'org.example:example-api:1.0' compile 'org.example:example-lib:1.0' } eclipse.wtp.component.rootConfigurations += [ configurations.compile ] """ when: EclipseProject eclipseProject = loadToolingModel(EclipseProject) Collection<EclipseExternalDependency> classpath = eclipseProject.getClasspath() then: entryNotDeployed(classpath.find { it.file.absolutePath.contains 'example-api' }) entryIsDeployed(classpath.find { it.file.absolutePath.contains 'example-lib' }, '/') } def "Library wtp dependencies and their transitives are deployed to '/WEB-INF/lib'"() { buildFile << """apply plugin: 'java' apply plugin: 'war' repositories { $localMaven } dependencies { compile 'org.example:example-lib:1.0' } """ when: EclipseProject eclipseProject = loadToolingModel(EclipseProject) Collection<EclipseExternalDependency> classpath = eclipseProject.getClasspath() then: classpath.size() == 2 entryIsDeployed(classpath[0], '/WEB-INF/lib') entryIsDeployed(classpath[1], '/WEB-INF/lib') } def "Lib wtp dependencies present in minusConfigurations are excluded from deployment"() { given: buildFile << """apply plugin: 'java' apply plugin: 'war' apply plugin: 'eclipse-wtp' repositories { $localMaven } dependencies { providedRuntime 'org.example:example-api:1.0' compile 'org.example:example-lib:1.0' } """ when: EclipseProject eclipseProject = loadToolingModel(EclipseProject) Collection<EclipseExternalDependency> classpath = eclipseProject.getClasspath() then: entryNotDeployed(classpath.find { it.file.absolutePath.contains 'example-api' }) entryIsDeployed(classpath.find { it.file.absolutePath.contains 'example-lib' }, '/WEB-INF/lib') } def "Deployment folder follows ear app dir name configuration"() { buildFile << """apply plugin: 'ear' apply plugin: 'java' apply plugin: 'eclipse' repositories { $localMaven } dependencies { earlib 'org.example:example-api:1.0' } eclipse.classpath.plusConfigurations << configurations.earlib ear { libDirName = '/custom/lib/dir' } """ when: EclipseProject eclipseProject = loadToolingModel(EclipseProject) Collection<EclipseExternalDependency> classpath = eclipseProject.getClasspath() then: classpath.size() == 1 entryIsDeployed(classpath[0], '/custom/lib/dir') } def "All non-wtp dependencies are marked as not deployed"() { given: buildFile << """apply plugin: 'java' apply plugin: 'war' repositories { $localMaven } dependencies { compileOnly 'org.example:example-lib:1.0' } """ when: EclipseProject eclipseProject = loadToolingModel(EclipseProject) Collection<EclipseExternalDependency> classpath = eclipseProject.getClasspath() then: classpath.size() == 2 entryNotDeployed(classpath[0]) entryNotDeployed(classpath[1]) } def "Project dependencies are marked as not deployed"() { given: settingsFile << 'include "sub"' buildFile << """apply plugin: 'java' apply plugin: 'war' repositories { $localMaven } dependencies { compile 'org.example:example-api:1.0' compile project(':sub') } project(':sub') { apply plugin : 'java' } """ when: EclipseProject eclipseProject = loadToolingModel(EclipseProject) def projectDependencies = eclipseProject.getProjectDependencies() then: projectDependencies.size() == 1 entryNotDeployed(projectDependencies[0]) } private def entryHasDeploymentInfo(entry) { return entry.classpathAttributes.find { it.name == 'org.eclipse.jst.component.nondependency' } || entry.classpathAttributes.find { it.name == 'org.eclipse.jst.component.dependency' } } private def entryHasNoDeploymentInfo(entry) { return !entry.classpathAttributes.find { it.name == 'org.eclipse.jst.component.nondependency' } && !entry.classpathAttributes.find { it.name == 'org.eclipse.jst.component.dependency' } } private def entryNotDeployed(entry) { return entry.classpathAttributes.find { it.name == 'org.eclipse.jst.component.nondependency' && it.value == '' } && !entry.classpathAttributes.find { it.name == 'org.eclipse.jst.component.dependency' } } private def entryIsDeployed(entry, path) { return !entry.classpathAttributes.find { it.name == 'org.eclipse.jst.component.nondependency' } && entry.classpathAttributes.find { it.name == 'org.eclipse.jst.component.dependency' && it.value == path } } }
{ "pile_set_name": "Github" }
// +build !windows,!plan9 // Copyright 2015 go-termios Author. All Rights Reserved. // https://github.com/go-termios/termios // Author: John Lenton <chipaca@github.com> package sys import ( "unsafe" "golang.org/x/sys/unix" ) // Termios represents terminal attributes. type Termios unix.Termios // NewTermiosFromFd extracts the terminal attribute of the given file // descriptor. func NewTermiosFromFd(fd int) (*Termios, error) { var term Termios if err := Ioctl(fd, getAttrIOCTL, uintptr(unsafe.Pointer(&term))); err != nil { return nil, err } return &term, nil } // ApplyToFd applies term to the given file descriptor. func (term *Termios) ApplyToFd(fd int) error { return Ioctl(fd, setAttrNowIOCTL, uintptr(unsafe.Pointer(term))) } // Copy returns a copy of term. func (term *Termios) Copy() *Termios { v := *term return &v } // SetVTime sets the timeout in deciseconds for noncanonical read. func (term *Termios) SetVTime(v uint8) { term.Cc[unix.VTIME] = v } // SetVMin sets the minimal number of characters for noncanonical read. func (term *Termios) SetVMin(v uint8) { term.Cc[unix.VMIN] = v } // SetICanon sets the canonical flag. func (term *Termios) SetICanon(v bool) { setFlag(&term.Lflag, unix.ICANON, v) } // SetEcho sets the echo flag. func (term *Termios) SetEcho(v bool) { setFlag(&term.Lflag, unix.ECHO, v) } // SetICRNL sets the CRNL iflag bit func (term *Termios) SetICRNL(v bool) { setFlag(&term.Iflag, unix.ICRNL, v) } // FlushInput discards data written to a file descriptor but not read. func FlushInput(fd int) error { return Ioctl(fd, flushIOCTL, uintptr(unix.TCIFLUSH)) }
{ "pile_set_name": "Github" }
<?php /** * @file * Lagoon Drupal 8 development environment configuration file. * * This file will only be included on development environments. * * It contains some defaults that the Lagoon team suggests, please edit them as required. */ // Show all error messages on the site. $config['system.logging']['error_level'] = 'all'; // Disable Google Analytics from sending dev GA data. $config['google_analytics.settings']['account'] = 'UA-XXXXXXXX-YY'; // Expiration of cached pages to 0. $config['system.performance']['cache']['page']['max_age'] = 0; // Aggregate CSS files off. $config['system.performance']['css']['preprocess'] = 0; // Aggregate JavaScript files off. $config['system.performance']['js']['preprocess'] = 0; // Stage file proxy URL from production URL. if (getenv('LAGOON_PRODUCTION_URL')) { $config['stage_file_proxy.settings']['origin'] = getenv('LAGOON_PRODUCTION_URL'); }
{ "pile_set_name": "Github" }
module mod11 { prefix abc; namespace "urn:cesnet:mod11"; typedef my_type { type uint8; } leaf l1 { type "my_type" { range "5 .. max | 10 .. 20"; } } }
{ "pile_set_name": "Github" }
 Microsoft Visual Studio Solution File, Format Version 11.00 # Visual Studio 2010 Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "ListViewTest", "SEImageListView\ListViewTest.csproj", "{0C74DAD0-CA29-48E0-8EEC-385308368A0C}" EndProject Global GlobalSection(SolutionConfigurationPlatforms) = preSolution Debug|x86 = Debug|x86 Release|x86 = Release|x86 EndGlobalSection GlobalSection(ProjectConfigurationPlatforms) = postSolution {0C74DAD0-CA29-48E0-8EEC-385308368A0C}.Debug|x86.ActiveCfg = Debug|x86 {0C74DAD0-CA29-48E0-8EEC-385308368A0C}.Debug|x86.Build.0 = Debug|x86 {0C74DAD0-CA29-48E0-8EEC-385308368A0C}.Release|x86.ActiveCfg = Release|x86 {0C74DAD0-CA29-48E0-8EEC-385308368A0C}.Release|x86.Build.0 = Release|x86 EndGlobalSection GlobalSection(SolutionProperties) = preSolution HideSolutionNode = FALSE EndGlobalSection EndGlobal
{ "pile_set_name": "Github" }
/** * @license Copyright (c) 2003-2020, CKSource - Frederico Knabben. All rights reserved. * For licensing, see LICENSE.md or https://ckeditor.com/legal/ckeditor-oss-license */ /* global document */ import testUtils from '@ckeditor/ckeditor5-core/tests/_utils/utils'; import EditorUIView from '../../src/editorui/editoruiview'; import ViewCollection from '../../src/viewcollection'; import Locale from '@ckeditor/ckeditor5-utils/src/locale'; describe( 'EditorUIView', () => { let view, locale; testUtils.createSinonSandbox(); beforeEach( () => { locale = new Locale(); view = new EditorUIView( locale ); view.render(); } ); afterEach( () => { view.destroy(); } ); describe( 'constructor()', () => { it( 'accepts locale', () => { expect( view.locale ).to.equal( locale ); } ); it( 'sets all the properties', () => { expect( view.body ).to.be.instanceof( ViewCollection ); } ); } ); describe( 'render()', () => { it( 'attach the body collection', () => { expect( view.body._bodyCollectionContainer.parentNode.classList.contains( 'ck-body-wrapper' ) ).to.be.true; expect( view.body._bodyCollectionContainer.parentNode.parentNode ).to.equal( document.body ); } ); } ); describe( 'destroy()', () => { it( 'detach the body collection', () => { const el = view.body._bodyCollectionContainer; view.destroy(); expect( el.parentNode ).to.be.null; } ); it( 'can be called multiple times', () => { expect( () => { view.destroy(); view.destroy(); } ).to.not.throw(); } ); } ); } );
{ "pile_set_name": "Github" }
namespace ClassLib095 { public class Class045 { public static string Property => "ClassLib095"; } }
{ "pile_set_name": "Github" }
# # Author:: Kaustubh Deorukhkar (<kaustubh@clogeny.com>) # Author:: Prabhu Das (<prabhu.das@clogeny.com>) # Author:: Isa Farnik (<isa@chef.io>) # Copyright:: Copyright (c) Chef Software Inc. # License:: Apache License, Version 2.0 # # 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. # Ohai.plugin(:Network) do require_relative "../../mixin/network_helper" provides "network", "counters/network", "macaddress" include Ohai::Mixin::NetworkHelper collect_data(:aix) do require "ipaddr" unless defined?(IPAddr) # Loads following information. # :default_interface, :default_gateway - route -n get 0 # :interfaces # => routes(netstat -nr | grep en0) # => addresses (ifconfig en0 or lsattr -El en0), macaddress (entstat -d en0 = Hardware Address: be:42:80:00:b0:05) # => flags (ifconfig en0) # => state up/down (ifconfig/lsattr) # => arp (arp -an) iface = Mash.new network Mash.new unless network network[:interfaces] ||= Mash.new # We unfortunately have to do things a bit different here, if ohai is running # within a WPAR. For instance, the WPAR isn't aware of some of its own networking # minutia such as default gateway/route. unless shell_out("uname -W").stdout.to_i > 0 # :default_interface, :default_gateway - route -n get 0 so = shell_out("netstat -rn |grep default") so.stdout.lines.each do |line| items = line.split(" ") if items[0] == "default" network[:default_gateway] = items[1] network[:default_interface] = items[5] end end end # Splits the ifconfig output to 1 line per interface if_so = shell_out("ifconfig -a") if_so.stdout.gsub(/\n(\w+\d+)/, '___\1').split("___").each do |intraface| splat = intraface.split(":") interface = splat[0] line = splat[1..-1][0] iface[interface] = Mash.new iface[interface][:state] = (line.include?("<UP,") ? "up" : "down") intraface.lines.each do |lin| case lin when /flags=\S+<(\S+)>/ iface[interface][:flags] = $1.split(",") iface[interface][:metric] = $1 if lin =~ /metric\s(\S+)/ else # We have key value pairs. if lin =~ %r{inet (\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})(/(\d{1,2}))?} tmp_addr, tmp_prefix = $1, $3 if tmp_prefix.nil? netmask = hex_to_dec_netmask($1) if lin =~ /netmask\s0x(\S+)\s/ unless netmask tmp_prefix ||= "32" netmask = IPAddr.new("255.255.255.255").mask(tmp_prefix.to_i).to_s end else netmask = IPAddr.new("255.255.255.255").mask(tmp_prefix.to_i).to_s end iface[interface][:addresses] ||= Mash.new iface[interface][:addresses][tmp_addr] = { "family" => "inet", "prefixlen" => tmp_prefix } iface[interface][:addresses][tmp_addr][:netmask] = netmask if lin =~ /broadcast\s(\S+)\s/ iface[interface][:addresses][tmp_addr][:broadcast] = $1 end elsif lin =~ %r{inet6 ([a-f0-9\:]+)%?([\d]*)/?(\d*)?} # TODO do we have more properties on inet6 in aix? broadcast iface[interface][:addresses] ||= Mash.new iface[interface][:addresses][$1] = { "family" => "inet6", "zone_index" => $2, "prefixlen" => $3 } else # load all key-values, example "tcp_sendspace 131072 tcp_recvspace 131072 rfc1323 1" properties = lin.split n = properties.length / 2 - 1 (0..n).each do |i| iface[interface][properties[i * 2]] = properties[(i * 2 + 1)] end end end end # Query macaddress e_so = shell_out("entstat -d #{interface} | grep \"Hardware Address\"") iface[interface][:addresses] ||= Mash.new e_so.stdout.lines.each do |l| if l =~ /Hardware Address: (\S+)/ iface[interface][:addresses][$1.upcase] = { "family" => "lladdr" } macaddress $1.upcase unless shell_out("uname -W").stdout.to_i > 0 end end end # ifconfig stdout # Query routes information %w{inet inet6}.each do |family| so_n = shell_out("netstat -nrf #{family}") so_n.stdout.lines.each do |line| if line =~ /(\S+)\s+(\S+)\s+(\S+)\s+(\d+)\s+(\d+)\s+(\S+)/ interface = $6 iface[interface][:routes] = [] unless iface[interface][:routes] iface[interface][:routes] << Mash.new( destination: $1, family: family, via: $2, flags: $3) end end end # List the arp entries in system. so = shell_out("arp -an") count = 0 so.stdout.lines.each do |line| network[:arp] ||= Mash.new if line =~ /\s*(\S+) \((\S+)\) at ([a-fA-F0-9\:]+) \[(\w+)\] stored in bucket/ network[:arp][count] ||= Mash.new network[:arp][count][:remote_host] = $1 network[:arp][count][:remote_ip] = $2 network[:arp][count][:remote_mac] = $3.downcase count += 1 end end network["interfaces"] = iface end end
{ "pile_set_name": "Github" }
package pagination import ( "encoding/json" "io/ioutil" "net/http" "net/url" "strings" "github.com/gophercloud/gophercloud" ) // PageResult stores the HTTP response that returned the current page of results. type PageResult struct { gophercloud.Result url.URL } // PageResultFrom parses an HTTP response as JSON and returns a PageResult containing the // results, interpreting it as JSON if the content type indicates. func PageResultFrom(resp *http.Response) (PageResult, error) { var parsedBody interface{} defer resp.Body.Close() rawBody, err := ioutil.ReadAll(resp.Body) if err != nil { return PageResult{}, err } if strings.HasPrefix(resp.Header.Get("Content-Type"), "application/json") { err = json.Unmarshal(rawBody, &parsedBody) if err != nil { return PageResult{}, err } } else { parsedBody = rawBody } return PageResultFromParsed(resp, parsedBody), err } // PageResultFromParsed constructs a PageResult from an HTTP response that has already had its // body parsed as JSON (and closed). func PageResultFromParsed(resp *http.Response, body interface{}) PageResult { return PageResult{ Result: gophercloud.Result{ Body: body, Header: resp.Header, }, URL: *resp.Request.URL, } } // Request performs an HTTP request and extracts the http.Response from the result. func Request(client *gophercloud.ServiceClient, headers map[string]string, url string) (*http.Response, error) { return client.Get(url, nil, &gophercloud.RequestOpts{ MoreHeaders: headers, OkCodes: []int{200, 204, 300}, }) }
{ "pile_set_name": "Github" }
/** * Prefixer (tools/_prefixer.scss) */ /* ----- Box sizing ----- */ @mixin box-sizing ($value) { -webkit-box-sizing: $value; -moz-box-sizing: $value; box-sizing: $value; } /* ----- Transform ----- */ // Rotate @mixin rotate ($deg) { -webkit-transform: rotate(#{$deg}deg); -moz-transform: rotate(#{$deg}deg); -ms-transform: rotate(#{$deg}deg); transform: rotate(#{$deg}deg); } // Translate @mixin translate ($x, $y) { -webkit-transform: translate($x, $y); -moz-transform: translate($x, $y); -ms-transform: translate($x, $y); transform: translate($x, $y); } // Translate 3D @mixin translate3d ($x, $y, $z) { -webkit-transform: translate3d($x, $y, $z); -moz-transform: translate3d($x, $y, $z); transform: translate3d($x, $y, $z); }
{ "pile_set_name": "Github" }
package com.aphidmobile.flip.demo.data; import java.util.ArrayList; import java.util.List; /* Copyright 2012 Aphid Mobile 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. */ public class Travels { public static final List<Data> IMG_DESCRIPTIONS = new ArrayList<Data>(); static { Travels.IMG_DESCRIPTIONS.add(new Travels.Data("Potala Palace", "potala_palace.jpg", "The <b>Potala Palace</b> is located in Lhasa, Tibet Autonomous Region, China. It is named after Mount Potalaka, the mythical abode of Chenresig or Avalokitesvara.", "China", "Lhasa", "http://en.wikipedia.org/wiki/Potala_Palace")); Travels.IMG_DESCRIPTIONS.add(new Travels.Data("Drepung Monastery", "drepung_monastery.jpg", "<b>Drepung Monastery</b>, located at the foot of Mount Gephel, is one of the \"great three\" Gelukpa university monasteries of Tibet.", "China", "Lhasa", "http://en.wikipedia.org/wiki/Drepung")); Travels.IMG_DESCRIPTIONS.add(new Travels.Data("Sera Monastery", "sera_monastery.jpg", "<b>Sera Monastery</b> is one of the 'great three' Gelukpa university monasteries of Tibet, located 1.25 miles (2.01 km) north of Lhasa.", "China", "Lhasa", "http://en.wikipedia.org/wiki/Sera_Monastery")); Travels.IMG_DESCRIPTIONS.add(new Travels.Data("Samye Monastery", "samye_monastery.jpg", "<b>Samye Monastery</b> is the first Buddhist monastery built in Tibet, was most probably first constructed between 775 and 779 CE.", "China", "Samye", "http://en.wikipedia.org/wiki/Samye")); Travels.IMG_DESCRIPTIONS.add( new Travels.Data("Tashilunpo Monastery", "tashilunpo_monastery.jpg", "<b>Tashilhunpo Monastery</b>, founded in 1447 by Gendun Drup, the First Dalai Lama, is a historic and culturally important monastery next to Shigatse, the second-largest city in Tibet.", "China", "Shigatse", "http://en.wikipedia.org/wiki/Tashilhunpo_Monastery")); Travels.IMG_DESCRIPTIONS.add(new Travels.Data("Zhangmu Port", "zhangmu_port.jpg", "<b>Zhangmu/Dram</b> is a customs town and port of entry located in Nyalam County on the Nepal-China border, just uphill and across the Bhote Koshi River from the Nepalese town of Kodari.", "China", "Zhangmu", "http://en.wikipedia.org/wiki/Zhangmu")); Travels.IMG_DESCRIPTIONS.add(new Travels.Data("Kathmandu", "kathmandu.jpg", "<b>Kathmandu</b> is the capital and, with more than one million inhabitants, the largest metropolitan city of Nepal.", "Nepal", "Kathmandu", "http://en.wikipedia.org/wiki/Kathmandu")); Travels.IMG_DESCRIPTIONS.add(new Travels.Data("Pokhara", "pokhara.jpg", "<b>Pokhara Sub-Metropolitan City</b> is the second largest city of Nepal with approximately 250,000 inhabitants and is situated about 200 km west of the capital Kathmandu.", "Nepal", "Pokhara", "http://en.wikipedia.org/wiki/Pokhara")); Travels.IMG_DESCRIPTIONS.add(new Travels.Data("Patan", "patan.jpg", "<b>Patan</b>, officially Lalitpur Sub-Metropolitan City, is one of the major cities of Nepal located in the south-central part of Kathmandu Valley.", "Nepal", "Patan", "http://en.wikipedia.org/wiki/Patan,_Nepal")); } public static final class Data { public final String title; public final String imageFilename; public final String description; public final String country; public final String city; public final String link; private Data(String title, String imageFilename, String description, String country, String city, String link) { this.title = title; this.imageFilename = imageFilename; this.description = description; this.country = country; this.city = city; this.link = link; } } }
{ "pile_set_name": "Github" }
#!/bin/bash -e # # This script rebuilds the generated code for the protocol buffers. # To run this you will need protoc and goprotobuf installed; # see https://github.com/golang/protobuf for instructions. PKG=google.golang.org/appengine function die() { echo 1>&2 $* exit 1 } # Sanity check that the right tools are accessible. for tool in go protoc protoc-gen-go; do q=$(which $tool) || die "didn't find $tool" echo 1>&2 "$tool: $q" done echo -n 1>&2 "finding package dir... " pkgdir=$(go list -f '{{.Dir}}' $PKG) echo 1>&2 $pkgdir base=$(echo $pkgdir | sed "s,/$PKG\$,,") echo 1>&2 "base: $base" cd $base # Run protoc once per package. for dir in $(find $PKG/internal -name '*.proto' | xargs dirname | sort | uniq); do echo 1>&2 "* $dir" protoc --go_out=. $dir/*.proto done for f in $(find $PKG/internal -name '*.pb.go'); do # Remove proto.RegisterEnum calls. # These cause duplicate registration panics when these packages # are used on classic App Engine. proto.RegisterEnum only affects # parsing the text format; we don't care about that. # https://code.google.com/p/googleappengine/issues/detail?id=11670#c17 sed -i '/proto.RegisterEnum/d' $f done
{ "pile_set_name": "Github" }
<Map> <Bangs></Bangs> <Switches></Switches> <SliderCurves> <Mapping> <Widget> <WidgetName>color_hue</WidgetName> <WidgetID>25</WidgetID> <WidgetCanvasParent>SystemSettings</WidgetCanvasParent> </Widget> <Track></Track> </Mapping> </SliderCurves> <NumberDialerCurves></NumberDialerCurves> </Map>
{ "pile_set_name": "Github" }
<?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd"> <plist version="1.0"> <dict> <key>ADP2,1</key> <string>Developer Transition Kit</string> <key>MacBook1,1</key> <string>MacBook (Core Duo)</string> <key>MacBook2,1</key> <string>MacBook (Core 2 Duo)</string> <key>MacBook4,1</key> <string>MacBook (Core 2 Duo Feb 2008)</string> <key>MacBookAir1,1</key> <string>MacBook Air (January 2008)</string> <key>MacBookPro1,1</key> <string>MacBook Pro Core Duo (15-inch)</string> <key>MacBookPro1,2</key> <string>MacBook Pro Core Duo (17-inch)</string> <key>MacBookPro2,1</key> <string>MacBook Pro Core 2 Duo (17-inch)</string> <key>MacBookPro2,2</key> <string>MacBook Pro Core 2 Duo (15-inch)</string> <key>MacBookPro3,1</key> <string>MacBook Pro Core 2 Duo (15-inch LED, Core 2 Duo)</string> <key>MacBookPro3,2</key> <string>MacBook Pro Core 2 Duo (17-inch HD, Core 2 Duo)</string> <key>MacBookPro4,1</key> <string>MacBook Pro (Core 2 Duo Feb 2008)</string> <key>MacPro1,1</key> <string>Mac Pro (four-core)</string> <key>MacPro2,1</key> <string>Mac Pro (eight-core)</string> <key>MacPro3,1</key> <string>Mac Pro (January 2008 4- or 8- core "Harpertown")</string> <key>Macmini1,1</key> <string>Mac Mini (Core Solo/Duo)</string> <key>PowerBook1,1</key> <string>PowerBook G3</string> <key>PowerBook2,1</key> <string>iBook G3</string> <key>PowerBook2,2</key> <string>iBook G3 (FireWire)</string> <key>PowerBook2,3</key> <string>iBook G3</string> <key>PowerBook2,4</key> <string>iBook G3</string> <key>PowerBook3,1</key> <string>PowerBook G3 (FireWire)</string> <key>PowerBook3,2</key> <string>PowerBook G4</string> <key>PowerBook3,3</key> <string>PowerBook G4 (Gigabit Ethernet)</string> <key>PowerBook3,4</key> <string>PowerBook G4 (DVI)</string> <key>PowerBook3,5</key> <string>PowerBook G4 (1GHz / 867MHz)</string> <key>PowerBook4,1</key> <string>iBook G3 (Dual USB, Late 2001)</string> <key>PowerBook4,2</key> <string>iBook G3 (16MB VRAM)</string> <key>PowerBook4,3</key> <string>iBook G3 Opaque 16MB VRAM, 32MB VRAM, Early 2003)</string> <key>PowerBook5,1</key> <string>PowerBook G4 (17 inch)</string> <key>PowerBook5,2</key> <string>PowerBook G4 (15 inch FW 800)</string> <key>PowerBook5,3</key> <string>PowerBook G4 (17-inch 1.33GHz)</string> <key>PowerBook5,4</key> <string>PowerBook G4 (15 inch 1.5/1.33GHz)</string> <key>PowerBook5,5</key> <string>PowerBook G4 (17-inch 1.5GHz)</string> <key>PowerBook5,6</key> <string>PowerBook G4 (15 inch 1.67GHz/1.5GHz)</string> <key>PowerBook5,7</key> <string>PowerBook G4 (17-inch 1.67GHz)</string> <key>PowerBook5,8</key> <string>PowerBook G4 (Double layer SD, 15 inch)</string> <key>PowerBook5,9</key> <string>PowerBook G4 (Double layer SD, 17 inch)</string> <key>PowerBook6,1</key> <string>PowerBook G4 (12 inch)</string> <key>PowerBook6,2</key> <string>PowerBook G4 (12 inch, DVI)</string> <key>PowerBook6,3</key> <string>iBook G4</string> <key>PowerBook6,4</key> <string>PowerBook G4 (12 inch 1.33GHz)</string> <key>PowerBook6,5</key> <string>iBook G4 (Early-Late 2004)</string> <key>PowerBook6,7</key> <string>iBook G4 (Mid 2005)</string> <key>PowerBook6,8</key> <string>PowerBook G4 (12 inch 1.5GHz)</string> <key>PowerMac1,1</key> <string>Power Macintosh G3 (Blue &amp; White)</string> <key>PowerMac1,2</key> <string>Power Macintosh G4 (PCI Graphics)</string> <key>PowerMac10,1</key> <string>Mac Mini G4</string> <key>PowerMac10,2</key> <string>Mac Mini (Late 2005)</string> <key>PowerMac11,2</key> <string>Power Macintosh G5 (Late 2005)</string> <key>PowerMac12,1</key> <string>iMac G5 (iSight)</string> <key>PowerMac2,1</key> <string>iMac G3 (Slot-loading CD-ROM)</string> <key>PowerMac2,2</key> <string>iMac G3 (Summer 2000)</string> <key>PowerMac3,1</key> <string>Power Macintosh G4 (AGP Graphics)</string> <key>PowerMac3,2</key> <string>Power Macintosh G4 (AGP Graphics)</string> <key>PowerMac3,3</key> <string>Power Macintosh G4 (Gigabit Ethernet)</string> <key>PowerMac3,4</key> <string>Power Macintosh G4 (Digital Audio)</string> <key>PowerMac3,5</key> <string>Power Macintosh G4 (Quick Silver)</string> <key>PowerMac3,6</key> <string>Power Macintosh G4 (Mirrored Drive Door)</string> <key>PowerMac4,1</key> <string>iMac G3 (Early/Summer 2001)</string> <key>PowerMac4,2</key> <string>iMac G4 (Flat Panel)</string> <key>PowerMac4,4</key> <string>eMac</string> <key>PowerMac4,5</key> <string>iMac G4 (17-inch Flat Panel)</string> <key>PowerMac5,1</key> <string>Power Macintosh G4 Cube</string> <key>PowerMac6,1</key> <string>iMac G4 (USB 2.0)</string> <key>PowerMac6,3</key> <string>iMac G4 (20-inch Flat Panel)</string> <key>PowerMac6,4</key> <string>eMac (USB 2.0, 2005)</string> <key>PowerMac7,2</key> <string>Power Macintosh G5</string> <key>PowerMac7,3</key> <string>Power Macintosh G5</string> <key>PowerMac8,1</key> <string>iMac G5</string> <key>PowerMac8,2</key> <string>iMac G5 (Ambient Light Sensor)</string> <key>PowerMac9,1</key> <string>Power Macintosh G5 (Late 2005)</string> <key>RackMac1,1</key> <string>Xserve G4</string> <key>RackMac1,2</key> <string>Xserve G4 (slot-loading, cluster node)</string> <key>RackMac3,1</key> <string>Xserve G5</string> <key>Xserve1,1</key> <string>Xserve (Intel Xeon)</string> <key>Xserve2,1</key> <string>Xserve (January 2008 quad-core)</string> <key>iMac1,1</key> <string>iMac G3 (Rev A-D)</string> <key>iMac4,1</key> <string>iMac (Core Duo)</string> <key>iMac4,2</key> <string>iMac for Education (17-inch, Core Duo)</string> <key>iMac5,1</key> <string>iMac (Core 2 Duo, 17 or 20 inch, SuperDrive)</string> <key>iMac5,2</key> <string>iMac (Core 2 Duo, 17 inch, Combo Drive)</string> <key>iMac6,1</key> <string>iMac (Core 2 Duo, 24 inch, SuperDrive)</string> <key>iMac8,1</key> <string>iMac (April 2008)</string> </dict> </plist>
{ "pile_set_name": "Github" }
%% [B] = tensor_tucker_prod(A,M) % function [B] = tensor_tucker_prod(A,M) B = A; for k = 1:length(A.size) B = ttm(B, M{k}, k); end end
{ "pile_set_name": "Github" }
// c.js export const foo = {} export const yack = {} export { wolf as default } from './b'
{ "pile_set_name": "Github" }
{-# LANGUAGE TemplateHaskell #-} module Rattletrap.Type.Float32le ( Float32le(..) ) where import Rattletrap.Type.Common newtype Float32le = Float32le { float32leValue :: Float } deriving (Eq, Ord, Show) $(deriveJson ''Float32le)
{ "pile_set_name": "Github" }
@mixin text-decoration($value) { // <text-decoration-line> || <text-decoration-style> || <text-decoration-color> @include prefixer(text-decoration, $value, moz); } @mixin text-decoration-line($line: none) { // none || underline || overline || line-through @include prefixer(text-decoration-line, $line, moz); } @mixin text-decoration-style($style: solid) { // solid || double || dotted || dashed || wavy @include prefixer(text-decoration-style, $style, moz webkit); } @mixin text-decoration-color($color: currentColor) { // currentColor || <color> @include prefixer(text-decoration-color, $color, moz); }
{ "pile_set_name": "Github" }
// RUN: %clang_cc1 -triple x86_64-apple-darwin10 -fsyntax-only -verify -fblocks %s // RUN: %clang_cc1 -fsyntax-only -verify -fblocks -fobjc-arc %s // expected-no-diagnostics struct X { __unsafe_unretained id object; int (^ __unsafe_unretained block)(int, int); }; void f(struct X x) { x.object = 0; x.block = ^(int x, int y) { return x + y; }; }
{ "pile_set_name": "Github" }
crlf crlf lf crlf crlf
{ "pile_set_name": "Github" }
# should_error # no-collect-stats try: raise SystemExit, "hello" except Exception as e: pass
{ "pile_set_name": "Github" }
run_spec(__dirname, ["python"], { pythonVersion: "3" });
{ "pile_set_name": "Github" }
// Copyright 2011 The Snappy-Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. package snappy import ( "encoding/binary" "errors" "io" ) // Encode returns the encoded form of src. The returned slice may be a sub- // slice of dst if dst was large enough to hold the entire encoded block. // Otherwise, a newly allocated slice will be returned. // // The dst and src must not overlap. It is valid to pass a nil dst. func Encode(dst, src []byte) []byte { if n := MaxEncodedLen(len(src)); n < 0 { panic(ErrTooLarge) } else if len(dst) < n { dst = make([]byte, n) } // The block starts with the varint-encoded length of the decompressed bytes. d := binary.PutUvarint(dst, uint64(len(src))) for len(src) > 0 { p := src src = nil if len(p) > maxBlockSize { p, src = p[:maxBlockSize], p[maxBlockSize:] } if len(p) < minNonLiteralBlockSize { d += emitLiteral(dst[d:], p) } else { d += encodeBlock(dst[d:], p) } } return dst[:d] } // inputMargin is the minimum number of extra input bytes to keep, inside // encodeBlock's inner loop. On some architectures, this margin lets us // implement a fast path for emitLiteral, where the copy of short (<= 16 byte) // literals can be implemented as a single load to and store from a 16-byte // register. That literal's actual length can be as short as 1 byte, so this // can copy up to 15 bytes too much, but that's OK as subsequent iterations of // the encoding loop will fix up the copy overrun, and this inputMargin ensures // that we don't overrun the dst and src buffers. const inputMargin = 16 - 1 // minNonLiteralBlockSize is the minimum size of the input to encodeBlock that // could be encoded with a copy tag. This is the minimum with respect to the // algorithm used by encodeBlock, not a minimum enforced by the file format. // // The encoded output must start with at least a 1 byte literal, as there are // no previous bytes to copy. A minimal (1 byte) copy after that, generated // from an emitCopy call in encodeBlock's main loop, would require at least // another inputMargin bytes, for the reason above: we want any emitLiteral // calls inside encodeBlock's main loop to use the fast path if possible, which // requires being able to overrun by inputMargin bytes. Thus, // minNonLiteralBlockSize equals 1 + 1 + inputMargin. // // The C++ code doesn't use this exact threshold, but it could, as discussed at // https://groups.google.com/d/topic/snappy-compression/oGbhsdIJSJ8/discussion // The difference between Go (2+inputMargin) and C++ (inputMargin) is purely an // optimization. It should not affect the encoded form. This is tested by // TestSameEncodingAsCppShortCopies. const minNonLiteralBlockSize = 1 + 1 + inputMargin // MaxEncodedLen returns the maximum length of a snappy block, given its // uncompressed length. // // It will return a negative value if srcLen is too large to encode. func MaxEncodedLen(srcLen int) int { n := uint64(srcLen) if n > 0xffffffff { return -1 } // Compressed data can be defined as: // compressed := item* literal* // item := literal* copy // // The trailing literal sequence has a space blowup of at most 62/60 // since a literal of length 60 needs one tag byte + one extra byte // for length information. // // Item blowup is trickier to measure. Suppose the "copy" op copies // 4 bytes of data. Because of a special check in the encoding code, // we produce a 4-byte copy only if the offset is < 65536. Therefore // the copy op takes 3 bytes to encode, and this type of item leads // to at most the 62/60 blowup for representing literals. // // Suppose the "copy" op copies 5 bytes of data. If the offset is big // enough, it will take 5 bytes to encode the copy op. Therefore the // worst case here is a one-byte literal followed by a five-byte copy. // That is, 6 bytes of input turn into 7 bytes of "compressed" data. // // This last factor dominates the blowup, so the final estimate is: n = 32 + n + n/6 if n > 0xffffffff { return -1 } return int(n) } var errClosed = errors.New("snappy: Writer is closed") // NewWriter returns a new Writer that compresses to w. // // The Writer returned does not buffer writes. There is no need to Flush or // Close such a Writer. // // Deprecated: the Writer returned is not suitable for many small writes, only // for few large writes. Use NewBufferedWriter instead, which is efficient // regardless of the frequency and shape of the writes, and remember to Close // that Writer when done. func NewWriter(w io.Writer) *Writer { return &Writer{ w: w, obuf: make([]byte, obufLen), } } // NewBufferedWriter returns a new Writer that compresses to w, using the // framing format described at // https://github.com/google/snappy/blob/master/framing_format.txt // // The Writer returned buffers writes. Users must call Close to guarantee all // data has been forwarded to the underlying io.Writer. They may also call // Flush zero or more times before calling Close. func NewBufferedWriter(w io.Writer) *Writer { return &Writer{ w: w, ibuf: make([]byte, 0, maxBlockSize), obuf: make([]byte, obufLen), } } // Writer is an io.Writer that can write Snappy-compressed bytes. type Writer struct { w io.Writer err error // ibuf is a buffer for the incoming (uncompressed) bytes. // // Its use is optional. For backwards compatibility, Writers created by the // NewWriter function have ibuf == nil, do not buffer incoming bytes, and // therefore do not need to be Flush'ed or Close'd. ibuf []byte // obuf is a buffer for the outgoing (compressed) bytes. obuf []byte // wroteStreamHeader is whether we have written the stream header. wroteStreamHeader bool } // Reset discards the writer's state and switches the Snappy writer to write to // w. This permits reusing a Writer rather than allocating a new one. func (w *Writer) Reset(writer io.Writer) { w.w = writer w.err = nil if w.ibuf != nil { w.ibuf = w.ibuf[:0] } w.wroteStreamHeader = false } // Write satisfies the io.Writer interface. func (w *Writer) Write(p []byte) (nRet int, errRet error) { if w.ibuf == nil { // Do not buffer incoming bytes. This does not perform or compress well // if the caller of Writer.Write writes many small slices. This // behavior is therefore deprecated, but still supported for backwards // compatibility with code that doesn't explicitly Flush or Close. return w.write(p) } // The remainder of this method is based on bufio.Writer.Write from the // standard library. for len(p) > (cap(w.ibuf)-len(w.ibuf)) && w.err == nil { var n int if len(w.ibuf) == 0 { // Large write, empty buffer. // Write directly from p to avoid copy. n, _ = w.write(p) } else { n = copy(w.ibuf[len(w.ibuf):cap(w.ibuf)], p) w.ibuf = w.ibuf[:len(w.ibuf)+n] w.Flush() } nRet += n p = p[n:] } if w.err != nil { return nRet, w.err } n := copy(w.ibuf[len(w.ibuf):cap(w.ibuf)], p) w.ibuf = w.ibuf[:len(w.ibuf)+n] nRet += n return nRet, nil } func (w *Writer) write(p []byte) (nRet int, errRet error) { if w.err != nil { return 0, w.err } for len(p) > 0 { obufStart := len(magicChunk) if !w.wroteStreamHeader { w.wroteStreamHeader = true copy(w.obuf, magicChunk) obufStart = 0 } var uncompressed []byte if len(p) > maxBlockSize { uncompressed, p = p[:maxBlockSize], p[maxBlockSize:] } else { uncompressed, p = p, nil } checksum := crc(uncompressed) // Compress the buffer, discarding the result if the improvement // isn't at least 12.5%. compressed := Encode(w.obuf[obufHeaderLen:], uncompressed) chunkType := uint8(chunkTypeCompressedData) chunkLen := 4 + len(compressed) obufEnd := obufHeaderLen + len(compressed) if len(compressed) >= len(uncompressed)-len(uncompressed)/8 { chunkType = chunkTypeUncompressedData chunkLen = 4 + len(uncompressed) obufEnd = obufHeaderLen } // Fill in the per-chunk header that comes before the body. w.obuf[len(magicChunk)+0] = chunkType w.obuf[len(magicChunk)+1] = uint8(chunkLen >> 0) w.obuf[len(magicChunk)+2] = uint8(chunkLen >> 8) w.obuf[len(magicChunk)+3] = uint8(chunkLen >> 16) w.obuf[len(magicChunk)+4] = uint8(checksum >> 0) w.obuf[len(magicChunk)+5] = uint8(checksum >> 8) w.obuf[len(magicChunk)+6] = uint8(checksum >> 16) w.obuf[len(magicChunk)+7] = uint8(checksum >> 24) if _, err := w.w.Write(w.obuf[obufStart:obufEnd]); err != nil { w.err = err return nRet, err } if chunkType == chunkTypeUncompressedData { if _, err := w.w.Write(uncompressed); err != nil { w.err = err return nRet, err } } nRet += len(uncompressed) } return nRet, nil } // Flush flushes the Writer to its underlying io.Writer. func (w *Writer) Flush() error { if w.err != nil { return w.err } if len(w.ibuf) == 0 { return nil } w.write(w.ibuf) w.ibuf = w.ibuf[:0] return w.err } // Close calls Flush and then closes the Writer. func (w *Writer) Close() error { w.Flush() ret := w.err if w.err == nil { w.err = errClosed } return ret }
{ "pile_set_name": "Github" }
client dev tun proto udp remote 89.238.140.53 1194 resolv-retry infinite remote-random nobind tun-mtu 1500 tun-mtu-extra 32 mssfix 1450 persist-key persist-tun ping 15 ping-restart 0 ping-timer-rem reneg-sec 0 comp-lzo no remote-cert-tls server auth-user-pass ../Own_VPN_Config/nordvpnauth.txt verb 3 pull fast-io cipher AES-256-CBC auth SHA512 <ca> -----BEGIN CERTIFICATE----- MIIFCjCCAvKgAwIBAgIBATANBgkqhkiG9w0BAQ0FADA5MQswCQYDVQQGEwJQQTEQ MA4GA1UEChMHTm9yZFZQTjEYMBYGA1UEAxMPTm9yZFZQTiBSb290IENBMB4XDTE2 MDEwMTAwMDAwMFoXDTM1MTIzMTIzNTk1OVowOTELMAkGA1UEBhMCUEExEDAOBgNV BAoTB05vcmRWUE4xGDAWBgNVBAMTD05vcmRWUE4gUm9vdCBDQTCCAiIwDQYJKoZI hvcNAQEBBQADggIPADCCAgoCggIBAMkr/BYhyo0F2upsIMXwC6QvkZps3NN2/eQF kfQIS1gql0aejsKsEnmY0Kaon8uZCTXPsRH1gQNgg5D2gixdd1mJUvV3dE3y9FJr XMoDkXdCGBodvKJyU6lcfEVF6/UxHcbBguZK9UtRHS9eJYm3rpL/5huQMCppX7kU eQ8dpCwd3iKITqwd1ZudDqsWaU0vqzC2H55IyaZ/5/TnCk31Q1UP6BksbbuRcwOV skEDsm6YoWDnn/IIzGOYnFJRzQH5jTz3j1QBvRIuQuBuvUkfhx1FEwhwZigrcxXu MP+QgM54kezgziJUaZcOM2zF3lvrwMvXDMfNeIoJABv9ljw969xQ8czQCU5lMVmA 37ltv5Ec9U5hZuwk/9QO1Z+d/r6Jx0mlurS8gnCAKJgwa3kyZw6e4FZ8mYL4vpRR hPdvRTWCMJkeB4yBHyhxUmTRgJHm6YR3D6hcFAc9cQcTEl/I60tMdz33G6m0O42s Qt/+AR3YCY/RusWVBJB/qNS94EtNtj8iaebCQW1jHAhvGmFILVR9lzD0EzWKHkvy WEjmUVRgCDd6Ne3eFRNS73gdv/C3l5boYySeu4exkEYVxVRn8DhCxs0MnkMHWFK6 MyzXCCn+JnWFDYPfDKHvpff/kLDobtPBf+Lbch5wQy9quY27xaj0XwLyjOltpiST LWae/Q4vAgMBAAGjHTAbMAwGA1UdEwQFMAMBAf8wCwYDVR0PBAQDAgEGMA0GCSqG SIb3DQEBDQUAA4ICAQC9fUL2sZPxIN2mD32VeNySTgZlCEdVmlq471o/bDMP4B8g nQesFRtXY2ZCjs50Jm73B2LViL9qlREmI6vE5IC8IsRBJSV4ce1WYxyXro5rmVg/ k6a10rlsbK/eg//GHoJxDdXDOokLUSnxt7gk3QKpX6eCdh67p0PuWm/7WUJQxH2S DxsT9vB/iZriTIEe/ILoOQF0Aqp7AgNCcLcLAmbxXQkXYCCSB35Vp06u+eTWjG0/ pyS5V14stGtw+fA0DJp5ZJV4eqJ5LqxMlYvEZ/qKTEdoCeaXv2QEmN6dVqjDoTAo k0t5u4YRXzEVCfXAC3ocplNdtCA72wjFJcSbfif4BSC8bDACTXtnPC7nD0VndZLp +RiNLeiENhk0oTC+UVdSc+n2nJOzkCK0vYu0Ads4JGIB7g8IB3z2t9ICmsWrgnhd NdcOe15BincrGA8avQ1cWXsfIKEjbrnEuEk9b5jel6NfHtPKoHc9mDpRdNPISeVa wDBM1mJChneHt59Nh8Gah74+TM1jBsw4fhJPvoc7Atcg740JErb904mZfkIEmojC VPhBHVQ9LHBAdM8qFI2kRK0IynOmAZhexlP/aT/kpEsEPyaZQlnBn3An1CRz8h0S PApL8PytggYKeQmRhl499+6jLxcZ2IegLfqq41dzIjwHwTMplg+1pKIOVojpWA== -----END CERTIFICATE----- </ca> key-direction 1 <tls-auth> # # 2048 bit OpenVPN static key # -----BEGIN OpenVPN Static key V1----- e685bdaf659a25a200e2b9e39e51ff03 0fc72cf1ce07232bd8b2be5e6c670143 f51e937e670eee09d4f2ea5a6e4e6996 5db852c275351b86fc4ca892d78ae002 d6f70d029bd79c4d1c26cf14e9588033 cf639f8a74809f29f72b9d58f9b8f5fe fc7938eade40e9fed6cb92184abb2cc1 0eb1a296df243b251df0643d53724cdb 5a92a1d6cb817804c4a9319b57d53be5 80815bcfcb2df55018cc83fc43bc7ff8 2d51f9b88364776ee9d12fc85cc7ea5b 9741c4f598c485316db066d52db4540e 212e1518a9bd4828219e24b20d88f598 a196c9de96012090e333519ae18d3509 9427e7b372d348d352dc4c85e18cd4b9 3f8a56ddb2e64eb67adfc9b337157ff4 -----END OpenVPN Static key V1----- </tls-auth>
{ "pile_set_name": "Github" }
{ "randomStatetest100" : { "_info" : { "comment" : "", "filledwith" : "testeth 1.6.0-alpha.0-11+commit.978e68d2", "lllcversion" : "Version: 0.5.0-develop.2018.11.9+commit.9709dfe0.Linux.g++", "source" : "src/GeneralStateTestsFiller/stRandom/randomStatetest100Filler.json", "sourceHash" : "5a7773117ba7a738174d9b0689a6cb0374ff146b05571dafce7d50ebcbb92728" }, "env" : { "currentCoinbase" : "0x945304eb96065b2a98b57a48a06ae28d285a71b5", "currentDifficulty" : "0x20000", "currentGasLimit" : "0x7fffffffffffffff", "currentNumber" : "0x01", "currentTimestamp" : "0x03e8", "previousHash" : "0x5e20a0453cecd065ea59c37ac63e079ee08998b6045136a8ce6635c7912ec0b6" }, "post" : { "Byzantium" : [ { "hash" : "0x54dfd10f0de86225537244edc47ec0ed9f8e665f0f6271d15e7707f67eca981b", "indexes" : { "data" : 0, "gas" : 0, "value" : 0 }, "logs" : "0x1dcc4de8dec75d7aab85b567b6ccd41ad312451b948a7413f0a142fd40d49347" } ], "Constantinople" : [ { "hash" : "0x54dfd10f0de86225537244edc47ec0ed9f8e665f0f6271d15e7707f67eca981b", "indexes" : { "data" : 0, "gas" : 0, "value" : 0 }, "logs" : "0x1dcc4de8dec75d7aab85b567b6ccd41ad312451b948a7413f0a142fd40d49347" } ], "ConstantinopleFix" : [ { "hash" : "0x54dfd10f0de86225537244edc47ec0ed9f8e665f0f6271d15e7707f67eca981b", "indexes" : { "data" : 0, "gas" : 0, "value" : 0 }, "logs" : "0x1dcc4de8dec75d7aab85b567b6ccd41ad312451b948a7413f0a142fd40d49347" } ], "Homestead" : [ { "hash" : "0x5881f750258fb642a9cc86dc9a7800652e2fe6bd40b7fa84d514344e90ee25c3", "indexes" : { "data" : 0, "gas" : 0, "value" : 0 }, "logs" : "0x1dcc4de8dec75d7aab85b567b6ccd41ad312451b948a7413f0a142fd40d49347" } ] }, "pre" : { "0x095e7baea6a6c7c4c2dfeb977efac326af552d87" : { "balance" : "0x0de0b6b3a7640000", "code" : "0x414243444342444283f24455", "nonce" : "0x00", "storage" : { } }, "0x945304eb96065b2a98b57a48a06ae28d285a71b5" : { "balance" : "0x2e", "code" : "0x6000355415600957005b60203560003555", "nonce" : "0x00", "storage" : { } }, "0xa94f5374fce5edbc8e2a8697c15331677e6ebf0b" : { "balance" : "0x0de0b6b3a7640000", "code" : "", "nonce" : "0x00", "storage" : { } } }, "transaction" : { "data" : [ "0x42" ], "gasLimit" : [ "0x061a80" ], "gasPrice" : "0x01", "nonce" : "0x00", "secretKey" : "0x45a915e4d060149eb4365960e6a7a45f334393093061116b197e3240065ff2d8", "to" : "0x095e7baea6a6c7c4c2dfeb977efac326af552d87", "value" : [ "0x0186a0" ] } } }
{ "pile_set_name": "Github" }
li.file { border-bottom: 1px solid rgba(234,234,234,1); padding: units(0.25) units(1); &:first-child { border-top: 1px solid rgba(234,234,234,1); } h4 { font-weight: normal; } summary:focus { outline: 0; } .status { background: rgba(0,0,0,0.3); border-radius: units(0.2); color: white; display: inline-block; font-size: units(0.7); font-weight: bold; margin-right: units(0.5); text-align: center; width: units(5); &.added { background: rgba(113,206,110,1); } &.modified { background: rgba(106,144,201,1); } &.deleted { background: rgba(251,27,46,1); } } .diff { margin-top: units(0.5); } .line { font-family: monospace; font-size: units(0.75); pre { margin: 0; padding: 0 units(0.25); } &.add { background: rgba(221,255,221,1); } &.delete { background: rgba(255,221,221,1); } &.marker { background: rgba(248,250,253,1); } } }
{ "pile_set_name": "Github" }
from collections import OrderedDict from json.tests import PyTest, CTest class TestUnicode(object): def test_encoding1(self): encoder = self.json.JSONEncoder(encoding='utf-8') u = u'\N{GREEK SMALL LETTER ALPHA}\N{GREEK CAPITAL LETTER OMEGA}' s = u.encode('utf-8') ju = encoder.encode(u) js = encoder.encode(s) self.assertEqual(ju, js) def test_encoding2(self): u = u'\N{GREEK SMALL LETTER ALPHA}\N{GREEK CAPITAL LETTER OMEGA}' s = u.encode('utf-8') ju = self.dumps(u, encoding='utf-8') js = self.dumps(s, encoding='utf-8') self.assertEqual(ju, js) def test_encoding3(self): u = u'\N{GREEK SMALL LETTER ALPHA}\N{GREEK CAPITAL LETTER OMEGA}' j = self.dumps(u) self.assertEqual(j, '"\\u03b1\\u03a9"') def test_encoding4(self): u = u'\N{GREEK SMALL LETTER ALPHA}\N{GREEK CAPITAL LETTER OMEGA}' j = self.dumps([u]) self.assertEqual(j, '["\\u03b1\\u03a9"]') def test_encoding5(self): u = u'\N{GREEK SMALL LETTER ALPHA}\N{GREEK CAPITAL LETTER OMEGA}' j = self.dumps(u, ensure_ascii=False) self.assertEqual(j, u'"{0}"'.format(u)) def test_encoding6(self): u = u'\N{GREEK SMALL LETTER ALPHA}\N{GREEK CAPITAL LETTER OMEGA}' j = self.dumps([u], ensure_ascii=False) self.assertEqual(j, u'["{0}"]'.format(u)) def test_big_unicode_encode(self): u = u'\U0001d120' self.assertEqual(self.dumps(u), '"\\ud834\\udd20"') self.assertEqual(self.dumps(u, ensure_ascii=False), u'"\U0001d120"') def test_big_unicode_decode(self): u = u'z\U0001d120x' self.assertEqual(self.loads('"' + u + '"'), u) self.assertEqual(self.loads('"z\\ud834\\udd20x"'), u) def test_unicode_decode(self): for i in range(0, 0xd7ff): u = unichr(i) s = '"\\u{0:04x}"'.format(i) self.assertEqual(self.loads(s), u) def test_object_pairs_hook_with_unicode(self): s = u'{"xkd":1, "kcw":2, "art":3, "hxm":4, "qrt":5, "pad":6, "hoy":7}' p = [(u"xkd", 1), (u"kcw", 2), (u"art", 3), (u"hxm", 4), (u"qrt", 5), (u"pad", 6), (u"hoy", 7)] self.assertEqual(self.loads(s), eval(s)) self.assertEqual(self.loads(s, object_pairs_hook = lambda x: x), p) od = self.loads(s, object_pairs_hook = OrderedDict) self.assertEqual(od, OrderedDict(p)) self.assertEqual(type(od), OrderedDict) # the object_pairs_hook takes priority over the object_hook self.assertEqual(self.loads(s, object_pairs_hook = OrderedDict, object_hook = lambda x: None), OrderedDict(p)) def test_default_encoding(self): self.assertEqual(self.loads(u'{"a": "\xe9"}'.encode('utf-8')), {'a': u'\xe9'}) def test_unicode_preservation(self): self.assertEqual(type(self.loads(u'""')), unicode) self.assertEqual(type(self.loads(u'"a"')), unicode) self.assertEqual(type(self.loads(u'["a"]')[0]), unicode) # Issue 10038. self.assertEqual(type(self.loads('"foo"')), unicode) def test_bad_encoding(self): self.assertRaises(UnicodeEncodeError, self.loads, '"a"', u"rat\xe9") self.assertRaises(TypeError, self.loads, '"a"', 1) class TestPyUnicode(TestUnicode, PyTest): pass class TestCUnicode(TestUnicode, CTest): pass
{ "pile_set_name": "Github" }
/* File: AUBuffer.h Abstract: Part of CoreAudio Utility Classes Version: 1.1 Disclaimer: IMPORTANT: This Apple software is supplied to you by Apple Inc. ("Apple") in consideration of your agreement to the following terms, and your use, installation, modification or redistribution of this Apple software constitutes acceptance of these terms. If you do not agree with these terms, please do not use, install, modify or redistribute this Apple software. In consideration of your agreement to abide by the following terms, and subject to these terms, Apple grants you a personal, non-exclusive license, under Apple's copyrights in this original Apple software (the "Apple Software"), to use, reproduce, modify and redistribute the Apple Software, with or without modifications, in source and/or binary forms; provided that if you redistribute the Apple Software in its entirety and without modifications, you must retain this notice and the following text and disclaimers in all such redistributions of the Apple Software. Neither the name, trademarks, service marks or logos of Apple Inc. may be used to endorse or promote products derived from the Apple Software without specific prior written permission from Apple. Except as expressly stated in this notice, no other rights or licenses, express or implied, are granted by Apple herein, including but not limited to any patent rights that may be infringed by your derivative works or by other works in which the Apple Software may be incorporated. The Apple Software is provided by Apple on an "AS IS" basis. APPLE MAKES NO WARRANTIES, EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION THE IMPLIED WARRANTIES OF NON-INFRINGEMENT, MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE, REGARDING THE APPLE SOFTWARE OR ITS USE AND OPERATION ALONE OR IN COMBINATION WITH YOUR PRODUCTS. IN NO EVENT SHALL APPLE BE LIABLE FOR ANY SPECIAL, INDIRECT, INCIDENTAL OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) ARISING IN ANY WAY OUT OF THE USE, REPRODUCTION, MODIFICATION AND/OR DISTRIBUTION OF THE APPLE SOFTWARE, HOWEVER CAUSED AND WHETHER UNDER THEORY OF CONTRACT, TORT (INCLUDING NEGLIGENCE), STRICT LIABILITY OR OTHERWISE, EVEN IF APPLE HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. Copyright (C) 2014 Apple Inc. All Rights Reserved. */ #ifndef __AUBuffer_h__ #define __AUBuffer_h__ #include "../../../juce_core/native/juce_mac_ClangBugWorkaround.h" #include <TargetConditionals.h> #if !defined(__COREAUDIO_USE_FLAT_INCLUDES__) #include <AudioUnit/AudioUnit.h> #else #include <AudioUnit.h> #endif #include <string.h> #include "CAStreamBasicDescription.h" #include "CAAutoDisposer.h" #include "CADebugMacros.h" // make this usable outside the stricter context of AudiUnits #ifndef COMPONENT_THROW #define COMPONENT_THROW(err) \ do { DebugMessage(#err); throw static_cast<OSStatus>(err); } while (0) #endif /*! @class AUBufferList */ class AUBufferList { enum EPtrState { kPtrsInvalid, kPtrsToMyMemory, kPtrsToExternalMemory }; public: /*! @ctor AUBufferList */ AUBufferList() : mPtrState(kPtrsInvalid), mExternalMemory(false), mPtrs(NULL), mMemory(NULL), mAllocatedStreams(0), mAllocatedFrames(0), mAllocatedBytes(0) { } /*! @dtor ~AUBufferList */ ~AUBufferList(); /*! @method PrepareBuffer */ AudioBufferList & PrepareBuffer(const CAStreamBasicDescription &format, UInt32 nFrames); /*! @method PrepareNullBuffer */ AudioBufferList & PrepareNullBuffer(const CAStreamBasicDescription &format, UInt32 nFrames); /*! @method SetBufferList */ AudioBufferList & SetBufferList(const AudioBufferList &abl) { if (mAllocatedStreams < abl.mNumberBuffers) COMPONENT_THROW(-1); mPtrState = kPtrsToExternalMemory; memcpy(mPtrs, &abl, (char *)&abl.mBuffers[abl.mNumberBuffers] - (char *)&abl); return *mPtrs; } /*! @method SetBuffer */ void SetBuffer(UInt32 index, const AudioBuffer &ab) { if (mPtrState == kPtrsInvalid || index >= mPtrs->mNumberBuffers) COMPONENT_THROW(-1); mPtrState = kPtrsToExternalMemory; mPtrs->mBuffers[index] = ab; } /*! @method InvalidateBufferList */ void InvalidateBufferList() { mPtrState = kPtrsInvalid; } /*! @method GetBufferList */ AudioBufferList & GetBufferList() const { if (mPtrState == kPtrsInvalid) COMPONENT_THROW(-1); return *mPtrs; } /*! @method CopyBufferListTo */ void CopyBufferListTo(AudioBufferList &abl) const { if (mPtrState == kPtrsInvalid) COMPONENT_THROW(-1); memcpy(&abl, mPtrs, (char *)&abl.mBuffers[abl.mNumberBuffers] - (char *)&abl); } /*! @method CopyBufferContentsTo */ void CopyBufferContentsTo(AudioBufferList &abl) const { if (mPtrState == kPtrsInvalid) COMPONENT_THROW(-1); const AudioBuffer *srcbuf = mPtrs->mBuffers; AudioBuffer *destbuf = abl.mBuffers; for (UInt32 i = 0; i < abl.mNumberBuffers; ++i, ++srcbuf, ++destbuf) { if (i >= mPtrs->mNumberBuffers) // duplicate last source to additional outputs [4341137] --srcbuf; if (destbuf->mData != srcbuf->mData) memmove(destbuf->mData, srcbuf->mData, srcbuf->mDataByteSize); destbuf->mDataByteSize = srcbuf->mDataByteSize; } } /*! @method Allocate */ void Allocate(const CAStreamBasicDescription &format, UInt32 nFrames); /*! @method Deallocate */ void Deallocate(); /*! @method UseExternalBuffer */ void UseExternalBuffer(const CAStreamBasicDescription &format, const AudioUnitExternalBuffer &buf); // AudioBufferList utilities /*! @method ZeroBuffer */ static void ZeroBuffer(AudioBufferList &abl) { AudioBuffer *buf = abl.mBuffers; for (UInt32 i = abl.mNumberBuffers ; i--; ++buf) memset(buf->mData, 0, buf->mDataByteSize); } #if DEBUG /*! @method PrintBuffer */ static void PrintBuffer(const char *label, int subscript, const AudioBufferList &abl, UInt32 nFrames = 8, bool asFloats = true); #endif /*! @method GetAllocatedFrames */ UInt32 GetAllocatedFrames() const { return mAllocatedFrames; } private: /*! @ctor AUBufferList */ AUBufferList(AUBufferList &) { } // prohibit copy constructor /*! @var mPtrState */ EPtrState mPtrState; /*! @var mExternalMemory */ bool mExternalMemory; /*! @var mPtrs */ AudioBufferList * mPtrs; /*! @var mMemory */ Byte * mMemory; /*! @var mAllocatedStreams */ UInt32 mAllocatedStreams; /*! @var mAllocatedFrames */ UInt32 mAllocatedFrames; /*! @var mAllocatedBytes */ UInt32 mAllocatedBytes; }; // Allocates an array of samples (type T), to be optimally aligned for the processor /*! @class TAUBuffer */ template <class T> class TAUBuffer { public: enum { kAlignInterval = 0x10, kAlignMask = kAlignInterval - 1 }; /*! @ctor TAUBuffer.0 */ TAUBuffer() : mMemObject(NULL), mAlignedBuffer(NULL), mBufferSizeBytes(0) { } /*! @ctor TAUBuffer.1 */ TAUBuffer(UInt32 numElems, UInt32 numChannels) : mMemObject(NULL), mAlignedBuffer(NULL), mBufferSizeBytes(0) { Allocate(numElems, numChannels); } /*! @dtor ~TAUBuffer */ ~TAUBuffer() { Deallocate(); } /*! @method Allocate */ void Allocate(UInt32 numElems) // can also re-allocate { UInt32 reqSize = numElems * sizeof(T); if (mMemObject != NULL && reqSize == mBufferSizeBytes) return; // already allocated mBufferSizeBytes = reqSize; mMemObject = CA_realloc(mMemObject, reqSize); UInt32 misalign = (uintptr_t)mMemObject & kAlignMask; if (misalign) { mMemObject = CA_realloc(mMemObject, reqSize + kAlignMask); mAlignedBuffer = (T *)((char *)mMemObject + kAlignInterval - misalign); } else mAlignedBuffer = (T *)mMemObject; } /*! @method Deallocate */ void Deallocate() { if (mMemObject == NULL) return; // so this method has no effect if we're using // an external buffer free(mMemObject); mMemObject = NULL; mAlignedBuffer = NULL; mBufferSizeBytes = 0; } /*! @method AllocateClear */ void AllocateClear(UInt32 numElems) // can also re-allocate { Allocate(numElems); Clear(); } /*! @method Clear */ void Clear() { memset(mAlignedBuffer, 0, mBufferSizeBytes); } // accessors /*! @method operator T *()@ */ operator T *() { return mAlignedBuffer; } private: /*! @var mMemObject */ void * mMemObject; // null when using an external buffer /*! @var mAlignedBuffer */ T * mAlignedBuffer; // always valid once allocated /*! @var mBufferSizeBytes */ UInt32 mBufferSizeBytes; }; #endif // __AUBuffer_h__
{ "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.cassandra.io.util; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.OutputStream; import java.io.UnsupportedEncodingException; import java.nio.ByteBuffer; import org.apache.cassandra.utils.ByteBufferUtil; /* * This file has been modified from Apache Harmony's ByteArrayOutputStream * implementation. The synchronized methods of the original have been * replaced by non-synchronized methods. This makes certain operations * much FASTer, but also *not thread-safe*. * * This file remains formatted the same as the Apache Harmony original to * make patching easier if any bug fixes are made to the Harmony version. */ /** * A specialized {@link OutputStream} for class for writing content to an * (internal) byte array. As bytes are written to this stream, the byte array * may be expanded to hold more bytes. When the writing is considered to be * finished, a copy of the byte array can be requested from the class. * * @see ByteArrayOutputStream */ public class FastByteArrayOutputStream extends OutputStream { /** * The byte array containing the bytes written. */ protected byte[] buf; /** * The number of bytes written. */ protected int count; /** * Constructs a new ByteArrayOutputStream with a default size of 32 bytes. * If more than 32 bytes are written to this instance, the underlying byte * array will expand. */ public FastByteArrayOutputStream() { buf = new byte[32]; } /** * Constructs a new {@code ByteArrayOutputStream} with a default size of * {@code size} bytes. If more than {@code size} bytes are written to this * instance, the underlying byte array will expand. * * @param size * initial size for the underlying byte array, must be * non-negative. * @throws IllegalArgumentException * if {@code size} < 0. */ public FastByteArrayOutputStream(int size) { if (size >= 0) { buf = new byte[size]; } else { throw new IllegalArgumentException(); } } /** * Closes this stream. This releases system resources used for this stream. * * @throws IOException * if an error occurs while attempting to close this stream. */ @Override public void close() throws IOException { /** * Although the spec claims "A closed stream cannot perform output * operations and cannot be reopened.", this implementation must do * nothing. */ super.close(); } private void expand(int i) { /* Can the buffer handle @i more bytes, if not expand it */ if (count + i <= buf.length) { return; } long expectedExtent = (count + i) * 2L; //long to deal with possible int overflow int newSize = (int) Math.min(Integer.MAX_VALUE - 8, expectedExtent); // MAX_ARRAY_SIZE byte[] newbuf = new byte[newSize]; System.arraycopy(buf, 0, newbuf, 0, count); buf = newbuf; } /** * Resets this stream to the beginning of the underlying byte array. All * subsequent writes will overwrite any bytes previously stored in this * stream. */ public void reset() { count = 0; } /** * Returns the total number of bytes written to this stream so far. * * @return the number of bytes written to this stream. */ public int size() { return count; } /** * Returns the contents of this ByteArrayOutputStream as a byte array. Any * changes made to the receiver after returning will not be reflected in the * byte array returned to the caller. * * @return this stream's current contents as a byte array. */ public byte[] toByteArray() { byte[] newArray = new byte[count]; System.arraycopy(buf, 0, newArray, 0, count); return newArray; } /** * Returns the contents of this ByteArrayOutputStream as a string. Any * changes made to the receiver after returning will not be reflected in the * string returned to the caller. * * @return this stream's current contents as a string. */ @Override public String toString() { return new String(buf, 0, count); } /** * Returns the contents of this ByteArrayOutputStream as a string. Each byte * {@code b} in this stream is converted to a character {@code c} using the * following function: * {@code c == (char)(((hibyte & 0xff) << 8) | (b & 0xff))}. This method is * deprecated and either {@link #toString()} or {@link #toString(String)} * should be used. * * @param hibyte * the high byte of each resulting Unicode character. * @return this stream's current contents as a string with the high byte set * to {@code hibyte}. * @deprecated Use {@link #toString()}. */ @Deprecated public String toString(int hibyte) { char[] newBuf = new char[size()]; for (int i = 0; i < newBuf.length; i++) { newBuf[i] = (char) (((hibyte & 0xff) << 8) | (buf[i] & 0xff)); } return new String(newBuf); } /** * Returns the contents of this ByteArrayOutputStream as a string converted * according to the encoding declared in {@code enc}. * * @param enc * a string representing the encoding to use when translating * this stream to a string. * @return this stream's current contents as an encoded string. * @throws UnsupportedEncodingException * if the provided encoding is not supported. */ public String toString(String enc) throws UnsupportedEncodingException { return new String(buf, 0, count, enc); } /** * Writes {@code count} bytes from the byte array {@code buffer} starting at * offset {@code index} to this stream. * * @param buffer * the buffer to be written. * @param offset * the initial position in {@code buffer} to retrieve bytes. * @param len * the number of bytes of {@code buffer} to write. * @throws NullPointerException * if {@code buffer} is {@code null}. * @throws IndexOutOfBoundsException * if {@code offset < 0} or {@code len < 0}, or if * {@code offset + len} is greater than the length of * {@code buffer}. */ @Override public void write(byte[] buffer, int offset, int len) { // avoid int overflow if (offset < 0 || offset > buffer.length || len < 0 || len > buffer.length - offset || this.count + len < 0) { throw new IndexOutOfBoundsException(); } if (len == 0) { return; } /* Expand if necessary */ expand(len); System.arraycopy(buffer, offset, buf, this.count, len); this.count += len; } public void write(ByteBuffer buffer) { int len = buffer.remaining(); expand(len); ByteBufferUtil.arrayCopy(buffer, buffer.position(), buf, this.count, len); this.count += len; } /** * Writes the specified byte {@code oneByte} to the OutputStream. Only the * low order byte of {@code oneByte} is written. * * @param oneByte * the byte to be written. */ @Override public void write(int oneByte) { if (count == buf.length) { expand(1); } buf[count++] = (byte) oneByte; } /** * Takes the contents of this stream and writes it to the output stream * {@code out}. * * @param out * an OutputStream on which to write the contents of this stream. * @throws IOException * if an error occurs while writing to {@code out}. */ public void writeTo(OutputStream out) throws IOException { out.write(buf, 0, count); } }
{ "pile_set_name": "Github" }
// // PrefixHeader.pch // HXCamouflageCalculator // // Created by 黄轩 on 16/10/14. // Copyright © 2016年 黄轩. All rights reserved. // #ifndef PrefixHeader_pch #define PrefixHeader_pch #import "PublicDefine.h" #import "AppConfig.h" #import "UIView+Helpers.h" #import "NSString+Extension.h" #import "UIImage+Extension.h" #import "AssetHelper.h" #import <ReactiveCocoa/ReactiveCocoa.h> #endif /* PrefixHeader_pch */
{ "pile_set_name": "Github" }
<!-- This file is auto-generated from uniformbuffers_test_generator.py DO NOT EDIT! --> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8"> <title>WebGL Uniform Block Conformance Tests</title> <link rel="stylesheet" href="../../../../resources/js-test-style.css"/> <script src="../../../../js/js-test-pre.js"></script> <script src="../../../../js/webgl-test-utils.js"></script> <script src="../../../../closure-library/closure/goog/base.js"></script> <script src="../../../deqp-deps.js"></script> <script>goog.require('functional.gles3.es3fUniformBlockTests');</script> </head> <body> <div id="description"></div> <div id="console"></div> <canvas id="canvas" width="200" height="100"> </canvas> <script> var wtu = WebGLTestUtils; var gl = wtu.create3DContext('canvas', null, 2); functional.gles3.es3fUniformBlockTests.run([8, 9]); </script> </body> </html>
{ "pile_set_name": "Github" }
#include "global.h" #include "gflib.h" #include "keyboard_text.h" #include "decompress.h" #include "easy_chat.h" #include "graphics.h" #include "menu.h" #include "new_menu_helpers.h" #include "strings.h" #include "text_window.h" struct ECWork { u16 state; u16 windowId; u16 id; u8 frameAnimIdx; u8 frameAnimTarget; s8 frameAnimDelta; u8 modeIconState; u8 ecPrintBuffer[0xC1]; u8 ecPaddedWordBuffer[0x200]; u16 bg2ScrollRow; int tgtBgY; int deltaBgY; struct Sprite * selectDestFieldCursorSprite; struct Sprite * rectCursorSpriteRight; struct Sprite * rectCursorSpriteLeft; struct Sprite * selectWordCursorSprite; struct Sprite * selectGroupHelpSprite; struct Sprite * modeIconsSprite; struct Sprite * upTriangleCursorSprite; struct Sprite * downTriangleCursorSprite; struct Sprite * startPgUpButtonSprite; struct Sprite * selectPgDnButtonSprite; u16 bg1TilemapBuffer[BG_SCREEN_SIZE / 2]; u16 bg3TilemapBuffer[BG_SCREEN_SIZE / 2]; }; struct EasyChatPhraseFrameDimensions { u8 left; u8 top; u8 width; u8 height; }; static EWRAM_DATA struct ECWork * sEasyChatGraphicsResources = NULL; static bool8 ECInterfaceCmd_01(void); static bool8 ECInterfaceCmd_02(void); static bool8 ECInterfaceCmd_03(void); static bool8 ECInterfaceCmd_05(void); static bool8 ECInterfaceCmd_06(void); static bool8 ECInterfaceCmd_04(void); static bool8 ECInterfaceCmd_07(void); static bool8 ECInterfaceCmd_08(void); static bool8 ECInterfaceCmd_09(void); static bool8 ECInterfaceCmd_10(void); static bool8 ECInterfaceCmd_22(void); static bool8 ECInterfaceCmd_14(void); static bool8 ECInterfaceCmd_15(void); static bool8 ECInterfaceCmd_16(void); static bool8 ECInterfaceCmd_11(void); static bool8 ECInterfaceCmd_12(void); static bool8 ECInterfaceCmd_13(void); static bool8 ECInterfaceCmd_17(void); static bool8 ECInterfaceCmd_19(void); static bool8 ECInterfaceCmd_18(void); static bool8 ECInterfaceCmd_21(void); static bool8 ECInterfaceCmd_20(void); static bool8 InitEasyChatGraphicsWork_Internal(void); static void SetGpuRegsForEasyChatInit(void); static void LoadEasyChatPals(void); static void PrintTitleText(void); static void EC_AddTextPrinterParameterized2(u8 windowId, u8 fontId, const u8 *str, u8 left, u8 top, u8 speed, u8 bg, u8 fg, u8 shadow); static void PrintECInstructionsText(void); static void PrintECInterfaceTextById(u8 a0); static void EC_CreateYesNoMenuWithInitialCursorPos(u8 initialCursorPos); static void CreatePhraseFrameWindow(void); static void PrintECFields(void); static void DrawECFrameInTilemapBuffer(u16 *buffer); static void PutWin2TilemapAndCopyToVram(void); static void PrintECMenuById(u32 a0); static void PrintECGroupOrAlphaMenu(void); static void PrintECGroupsMenu(void); static void PrintEasyChatKeyboardText(void); static void PrintECWordsMenu(void); static void UpdateWin2PrintWordsScrollDown(void); static void UpdateWin2PrintWordsScrollUp(void); static void UpdateWin2PrintWordsScrollPageDown(void); static void UpdateWin2PrintWordsScrollPageUp(void); static void PrintECRowsWin2(u8 row, u8 remrow); static void ClearECRowsWin2(u8 row, u8 remrow); static void ClearWin2AndCopyToVram(void); static void StartWin2FrameAnim(int a0); static bool8 AnimateFrameResize(void); static void RedrawFrameByIndex(u8 a0); static void RedrawFrameByRect(int left, int top, int width, int height); static void InitBg2Scroll(void); static void ScheduleBg2VerticalScroll(s16 direction, u8 speed); static bool8 AnimateBg2VerticalScroll(void); static int GetBg2ScrollRow(void); static void SetRegWin0Coords(u8 left, u8 top, u8 right, u8 bottom); static void LoadSpriteGfx(void); static void CreateSelectDestFieldCursorSprite(void); static void SpriteCB_BounceCursor(struct Sprite * sprite); static void SetSelectDestFieldCursorSpritePosAndResetAnim(u8 x, u8 y); static void FreezeSelectDestFieldCursorSprite(void); static void UnfreezeSelectDestFieldCursorSprite(void); static void CreateRedRectangularCursorSpritePair(void); static void DestroyRedRectangularCursor(void); static void EC_MoveCursor(void); static void MoveCursor_Group(s8 a0, s8 a1); static void MoveCursor_Alpha(s8 a0, s8 a1); static void CreateSelectWordCursorSprite(void); static void SpriteCB_SelectWordCursorSprite(struct Sprite * sprite); static void SetSelectWordCursorSpritePos(void); static void SetSelectWordCursorSpritePosExplicit(u8 x, u8 y); static void DestroySelectWordCursorSprite(void); static void CreateSelectGroupHelpSprite(void); static bool8 AnimateSeletGroupModeAndHelpSpriteEnter(void); static void StartModeIconHidingAnimation(void); static bool8 RunModeIconHidingAnimation(void); static void ShrinkModeIconsSprite(void); static void ShowModeIconsSprite(void); static bool8 ModeIconsSpriteAnimIsEnded(void); static void CreateVerticalScrollArrowSprites(void); static void UpdateVerticalScrollArrowVisibility(void); static void HideVerticalScrollArrowSprites(void); static void UpdateVerticalScrollArrowSpriteXPos(int a0); static void CreateStartSelectButtonsSprites(void); static void UpdateStartSelectButtonSpriteVisibility(void); static void HideStartSelectButtonSprites(void); static void CreateFooterWindow(void); static const u16 gUnknown_843F3B8[] = INCBIN_U16("graphics/link_rfu/unk_843F3F8.gbapal"); static const u16 gUnknown_843F3D8[] = INCBIN_U16("graphics/link_rfu/unk_8E9BD28.gbapal"); static const u16 sRightTriangleCursor_Tiles[] = INCBIN_U16("graphics/link_rfu/unk_843F3F8.4bpp"); static const u16 sUpTriangleCursor_Tiles[] = INCBIN_U16("graphics/link_rfu/unk_843F418.4bpp"); static const u16 sStartSelectButtons_Tiles[] = INCBIN_U16("graphics/link_rfu/unk_843F518.4bpp"); static const u16 gUnknown_843F618[] = INCBIN_U16("graphics/link_rfu/unk_843F638.gbapal"); static const u32 gUnknown_843F638[] = INCBIN_U32("graphics/link_rfu/unk_843F638.4bpp.lz"); static const u16 gUnknown_843F76C[] = INCBIN_U16("graphics/link_rfu/unk_843F76C.gbapal"); static const u16 gUnknown_843F78C[] = INCBIN_U16("graphics/link_rfu/unk_843F78C.gbapal"); static const u32 gUnknown_843F7AC[] = INCBIN_U32("graphics/link_rfu/unk_843F7AC.4bpp.lz"); static const u16 gUnknown_843F874[] = { RGB( 0, 0, 0), RGB( 0, 0, 0), RGB( 7, 25, 31), RGB(21, 21, 29) }; static const u16 gUnknown_843F87C[] = { RGB( 0, 0, 0), RGB(31, 31, 31), RGB(12, 12, 12), RGB(27, 26, 27), RGB( 8, 17, 9) }; static const struct EasyChatPhraseFrameDimensions sPhraseFrameDimensions[] = { { .left = 0x03, .top = 0x04, .width = 0x18, .height = 0x04 }, { .left = 0x01, .top = 0x04, .width = 0x1b, .height = 0x04 }, { .left = 0x03, .top = 0x00, .width = 0x18, .height = 0x0a }, { .left = 0x06, .top = 0x06, .width = 0x12, .height = 0x04 }, { .left = 0x10, .top = 0x04, .width = 0x09, .height = 0x02 }, { .left = 0x0e, .top = 0x04, .width = 0x12, .height = 0x04 } }; static const struct BgTemplate sEasyChatBgTemplates[] = { { .bg = 0, .charBaseIndex = 0, .mapBaseIndex = 28, .screenSize = 0, .paletteMode = 0, .priority = 0, .baseTile = 0, }, { .bg = 1, .charBaseIndex = 3, .mapBaseIndex = 29, .screenSize = 0, .paletteMode = 0, .priority = 1, .baseTile = 0, }, { .bg = 2, .charBaseIndex = 0, .mapBaseIndex = 30, .screenSize = 0, .paletteMode = 0, .priority = 2, .baseTile = 0x80, }, { .bg = 3, .charBaseIndex = 2, .mapBaseIndex = 31, .screenSize = 0, .paletteMode = 0, .priority = 3, .baseTile = 0, } }; static const struct WindowTemplate sEasyChatWindowTemplates[] = { { .bg = 1, .tilemapLeft = 7, .tilemapTop = 0, .width = 16, .height = 2, .paletteNum = 10, .baseBlock = 0x10, }, { .bg = 0, .tilemapLeft = 4, .tilemapTop = 15, .width = 22, .height = 4, .paletteNum = 15, .baseBlock = 0xA, }, { .bg = 2, .tilemapLeft = 1, .tilemapTop = 0, .width = 28, .height = 32, .paletteNum = 3, .baseBlock = 0, }, DUMMY_WIN_TEMPLATE, }; static const struct WindowTemplate sEasyChatYesNoWindowTemplate = { .bg = 0, .tilemapLeft = 22, .tilemapTop = 9, .width = 5, .height = 4, .paletteNum = 15, .baseBlock = 0x062 }; static const u8 gUnknown_843F8D8[] = _("{UNDERSCORE}"); static const u8 sText_Clear17[] = _("{CLEAR 17}"); static const u8 *const sEasyChatKeyboardText[] = { gUnknown_847A8D8, gUnknown_847A8FA, gUnknown_847A913, gUnknown_847A934 }; static const struct SpriteSheet sEasyChatSpriteSheets[] = { {sRightTriangleCursor_Tiles, 0x0020, 0}, {sUpTriangleCursor_Tiles, 0x0100, 2}, {sStartSelectButtons_Tiles, 0x0100, 3}, {} }; static const struct SpritePalette sEasyChatSpritePalettes[] = { {gUnknown_843F3B8, 0}, {gUnknown_843F3D8, 1}, {gUnknown_8E99F24, 2}, {gUnknown_843F618, 3}, {} }; static const struct CompressedSpriteSheet sEasyChatCompressedSpriteSheets[] = { {gUnknown_843F638, 0x0800, 5}, {gEasyChatRedRectangularCursor_Tiles, 0x1000, 1}, {gEasyChatSelectGroupHelp_Tiles, 0x0800, 6}, {gEasyChatModeIcons_Tiles, 0x1000, 4} }; static const u8 sECDisplay_AlphaModeXCoords[] = { 0, 12, 24, 56, 68, 80, 92 }; static const struct OamData sOamData_RightTriangleCursor = { .y = 0, .affineMode = ST_OAM_AFFINE_OFF, .objMode = ST_OAM_OBJ_NORMAL, .bpp = ST_OAM_4BPP, .mosaic = FALSE, .shape = SPRITE_SHAPE(8x8), .x = 0, .matrixNum = 0, .size = SPRITE_SIZE(8x8), .tileNum = 0x000, .priority = 3, .paletteNum = 0 }; static const struct SpriteTemplate sSpriteTemplate_RightTriangleCursor = { .tileTag = 0, .paletteTag = 0, .oam = &sOamData_RightTriangleCursor, .anims = gDummySpriteAnimTable, .images = NULL, .affineAnims = gDummySpriteAffineAnimTable, .callback = SpriteCB_BounceCursor }; static const struct OamData sOamData_RedRectangularCursor = { .y = 0, .affineMode = ST_OAM_AFFINE_OFF, .objMode = ST_OAM_OBJ_NORMAL, .bpp = ST_OAM_4BPP, .mosaic = FALSE, .shape = SPRITE_SHAPE(64x32), .x = 0, .matrixNum = 0, .size = SPRITE_SIZE(64x32), .tileNum = 0x000, .priority = 1, .paletteNum = 0 }; static const union AnimCmd sAnimCmd_RectCursor_Wide[] = { ANIMCMD_FRAME(0x00, 0), ANIMCMD_END }; static const union AnimCmd sAnimCmd_RectCursor_Norm[] = { ANIMCMD_FRAME(0x20, 0), ANIMCMD_END }; static const union AnimCmd sAnimCmd_RectCursor_NormTaller[] = { ANIMCMD_FRAME(0x40, 0), ANIMCMD_END }; static const union AnimCmd sAnimCmd_RectCursor_Narrow[] = { ANIMCMD_FRAME(0x60, 0), ANIMCMD_END }; static const union AnimCmd *const sAnimTable_RedRectangularCursor[] = { sAnimCmd_RectCursor_Wide, sAnimCmd_RectCursor_Norm, sAnimCmd_RectCursor_NormTaller, sAnimCmd_RectCursor_Narrow }; static const struct SpriteTemplate sSpriteTemplate_RedRectangularCursor = { .tileTag = 1, .paletteTag = 1, .oam = &sOamData_RedRectangularCursor, .anims = sAnimTable_RedRectangularCursor, .images = NULL, .affineAnims = gDummySpriteAffineAnimTable, .callback = SpriteCB_BounceCursor }; static const struct OamData sOamData_EasyChatModeIcons = { .y = 0, .affineMode = ST_OAM_AFFINE_OFF, .objMode = ST_OAM_OBJ_NORMAL, .bpp = ST_OAM_4BPP, .mosaic = FALSE, .shape = SPRITE_SHAPE(64x32), .x = 0, .matrixNum = 0, .size = SPRITE_SIZE(64x32), .tileNum = 0x000, .priority = 1, .paletteNum = 0 }; static const union AnimCmd sAnim_EasyChatModeIcon_Hidden[] = { ANIMCMD_FRAME(0x60, 0), ANIMCMD_END }; static const union AnimCmd sAnim_EasyChatModeIcon_ToGroupMode[] = { ANIMCMD_FRAME(0x40, 4), ANIMCMD_FRAME(0x20, 4), ANIMCMD_END }; static const union AnimCmd sAnim_EasyChatModeIcon_ToAlphaMode[] = { ANIMCMD_FRAME(0x40, 4), ANIMCMD_FRAME(0x00, 4), ANIMCMD_END }; static const union AnimCmd sAnim_EasyChatModeIcon_ToHidden[] = { ANIMCMD_FRAME(0x40, 4), ANIMCMD_FRAME(0x60, 0), ANIMCMD_END }; static const union AnimCmd sAnim_EasyChatModeIcon_HoldSmall[] = { ANIMCMD_FRAME(0x40, 4), ANIMCMD_END }; static const union AnimCmd *const sAnimTable_EasyChatModeIcons[] = { sAnim_EasyChatModeIcon_Hidden, sAnim_EasyChatModeIcon_ToGroupMode, sAnim_EasyChatModeIcon_ToAlphaMode, sAnim_EasyChatModeIcon_ToHidden, sAnim_EasyChatModeIcon_HoldSmall }; static const struct SpriteTemplate sSpriteTemplate_EasyChatModeIcons = { .tileTag = 4, .paletteTag = 2, .oam = &sOamData_EasyChatModeIcons, .anims = sAnimTable_EasyChatModeIcons, .images = NULL, .affineAnims = gDummySpriteAffineAnimTable, .callback = SpriteCallbackDummy }; static const struct OamData sOamData_SelectGroupHelp = { .y = 0, .affineMode = ST_OAM_AFFINE_OFF, .objMode = ST_OAM_OBJ_NORMAL, .mosaic = FALSE, .bpp = ST_OAM_4BPP, .shape = SPRITE_SHAPE(64x64), .x = 0, .matrixNum = 0, .size = SPRITE_SIZE(64x64), .tileNum = 0x000, .priority = 3, .paletteNum = 0 }; static const struct SpriteTemplate sSpriteTemplate_SelectGroupHelp = { .tileTag = 6, .paletteTag = 2, .oam = &sOamData_SelectGroupHelp, .anims = gDummySpriteAnimTable, .images = NULL, .affineAnims = gDummySpriteAffineAnimTable, .callback = SpriteCallbackDummy }; static const struct OamData gUnknown_843FA58 = { .y = 0, .affineMode = ST_OAM_AFFINE_OFF, .objMode = ST_OAM_OBJ_NORMAL, .mosaic = FALSE, .bpp = ST_OAM_4BPP, .shape = SPRITE_SHAPE(32x8), .x = 0, .matrixNum = 0, .size = SPRITE_SIZE(32x8), .tileNum = 0x000, .priority = 1, .paletteNum = 0 }; static const struct OamData sOamData_UpTriangleCursor = { .y = 0, .affineMode = ST_OAM_AFFINE_OFF, .objMode = ST_OAM_OBJ_NORMAL, .mosaic = FALSE, .bpp = ST_OAM_4BPP, .shape = SPRITE_SHAPE(16x16), .x = 0, .matrixNum = 0, .size = SPRITE_SIZE(16x16), .tileNum = 0x000, .priority = 1, .paletteNum = 0 }; static const union AnimCmd gUnknown_843FA68[] = { ANIMCMD_FRAME(0, 0), ANIMCMD_END, }; static const union AnimCmd gUnknown_843FA70[] = { ANIMCMD_FRAME(4, 0), ANIMCMD_END, }; static const union AnimCmd *const gUnknown_843FA78[] = { gUnknown_843FA68, gUnknown_843FA70, }; static const struct SpriteTemplate sSpriteTemplate_StartSelectButtons = { .tileTag = 3, .paletteTag = 2, .oam = &gUnknown_843FA58, .anims = gUnknown_843FA78, .images = NULL, .affineAnims = gDummySpriteAffineAnimTable, .callback = SpriteCallbackDummy, }; static const struct SpriteTemplate sSpriteTemplate_UpTriangleCursor = { .tileTag = 2, .paletteTag = 2, .oam = &sOamData_UpTriangleCursor, .anims = gUnknown_843FA78, .images = NULL, .affineAnims = gDummySpriteAffineAnimTable, .callback = SpriteCallbackDummy, }; bool8 InitEasyChatGraphicsWork(void) { if (!InitEasyChatGraphicsWork_Internal()) return FALSE; else return TRUE; } bool8 LoadEasyChatGraphics(void) { switch (sEasyChatGraphicsResources->state) { case 0: ResetBgsAndClearDma3BusyFlags(0); InitBgsFromTemplates(0, sEasyChatBgTemplates, NELEMS(sEasyChatBgTemplates)); SetBgTilemapBuffer(3, sEasyChatGraphicsResources->bg3TilemapBuffer); SetBgTilemapBuffer(1, sEasyChatGraphicsResources->bg1TilemapBuffer); InitWindows(sEasyChatWindowTemplates); DeactivateAllTextPrinters(); LoadEasyChatPals(); SetGpuRegsForEasyChatInit(); CpuFastFill(0, (void *)VRAM + 0x1000000, 0x400); break; case 1: DecompressAndLoadBgGfxUsingHeap(3, gEasyChatWindow_Gfx, 0, 0, 0); CopyToBgTilemapBuffer(3, gEasyChatWindow_Tilemap, 0, 0); CreatePhraseFrameWindow(); CreateFooterWindow(); CopyBgTilemapBufferToVram(3); break; case 2: DrawECFrameInTilemapBuffer(sEasyChatGraphicsResources->bg1TilemapBuffer); DecompressAndLoadBgGfxUsingHeap(1, gUnknown_843F7AC, 0, 0, 0); CopyBgTilemapBufferToVram(1); break; case 3: PrintTitleText(); PrintECInstructionsText(); PrintECFields(); PutWin2TilemapAndCopyToVram(); break; case 4: LoadSpriteGfx(); CreateSelectDestFieldCursorSprite(); break; case 5: if (IsDma3ManagerBusyWithBgCopy()) { return TRUE; } else { SetRegWin0Coords(0, 0, 0, 0); SetGpuReg(REG_OFFSET_WININ, WIN_RANGE(0, 63)); SetGpuReg(REG_OFFSET_WINOUT, WIN_RANGE(0, 59)); ShowBg(3); ShowBg(1); ShowBg(2); ShowBg(0); CreateVerticalScrollArrowSprites(); CreateStartSelectButtonsSprites(); } break; default: return FALSE; } sEasyChatGraphicsResources->state++; return TRUE; } void DestroyEasyChatGraphicsResources(void) { if (sEasyChatGraphicsResources) Free(sEasyChatGraphicsResources); } void EasyChatInterfaceCommand_Setup(u16 id) { sEasyChatGraphicsResources->id = id; sEasyChatGraphicsResources->state = 0; EasyChatInterfaceCommand_Run(); } bool8 EasyChatInterfaceCommand_Run(void) { switch (sEasyChatGraphicsResources->id) { case 0: return FALSE; case 1: return ECInterfaceCmd_01(); case 2: return ECInterfaceCmd_02(); case 3: return ECInterfaceCmd_03(); case 4: return ECInterfaceCmd_04(); case 5: return ECInterfaceCmd_05(); case 6: return ECInterfaceCmd_06(); case 7: return ECInterfaceCmd_07(); case 8: return ECInterfaceCmd_08(); case 9: return ECInterfaceCmd_09(); case 10: return ECInterfaceCmd_10(); case 11: return ECInterfaceCmd_11(); case 12: return ECInterfaceCmd_12(); case 13: return ECInterfaceCmd_13(); case 14: return ECInterfaceCmd_14(); case 15: return ECInterfaceCmd_15(); case 16: return ECInterfaceCmd_16(); case 17: return ECInterfaceCmd_17(); case 18: return ECInterfaceCmd_18(); case 19: return ECInterfaceCmd_19(); case 20: return ECInterfaceCmd_20(); case 21: return ECInterfaceCmd_21(); case 22: return ECInterfaceCmd_22(); default: return FALSE; } } static bool8 ECInterfaceCmd_01(void) { switch (sEasyChatGraphicsResources->state) { case 0: PrintECFields(); sEasyChatGraphicsResources->state++; break; case 1: return IsDma3ManagerBusyWithBgCopy(); } return TRUE; } static bool8 ECInterfaceCmd_02(void) { u8 i; u16 *ecWordBuffer; u16 *ecWord; u8 frameId; u8 cursorColumn, cursorRow, numColumns; s16 var1; int stringWidth; int trueStringWidth; int var2; u8 str[64]; ecWordBuffer = GetEasyChatWordBuffer(); frameId = GetEasyChatScreenFrameId(); cursorColumn = GetMainCursorColumn(); cursorRow = GetMainCursorRow(); numColumns = GetNumColumns(); ecWord = &ecWordBuffer[cursorRow * numColumns]; var1 = 8 * sPhraseFrameDimensions[frameId].left + 13; for (i = 0; i < cursorColumn; i++) { if (*ecWord == 0xFFFF) { stringWidth = GetStringWidth(1, gUnknown_843F8D8, 0) * 7; } else { CopyEasyChatWord(str, *ecWord); stringWidth = GetStringWidth(1, str, 0); } trueStringWidth = stringWidth + 17; var1 += trueStringWidth; ecWord++; } var2 = 8 * (sPhraseFrameDimensions[frameId].top + cursorRow * 2 + 1) + 1; SetSelectDestFieldCursorSpritePosAndResetAnim(var1, var2); return FALSE; } static bool8 ECInterfaceCmd_03(void) { u8 xOffset; switch (GetMainCursorColumn()) { case 0: xOffset = 28; break; case 1: xOffset = 115; break; case 2: xOffset = 191; break; default: return FALSE; } SetSelectDestFieldCursorSpritePosAndResetAnim(xOffset, 97); return FALSE; } static bool8 ECInterfaceCmd_05(void) { switch (sEasyChatGraphicsResources->state) { case 0: FreezeSelectDestFieldCursorSprite(); PrintECInterfaceTextById(2); EC_CreateYesNoMenuWithInitialCursorPos(1); sEasyChatGraphicsResources->state++; break; case 1: return IsDma3ManagerBusyWithBgCopy(); } return TRUE; } static bool8 ECInterfaceCmd_06(void) { switch (sEasyChatGraphicsResources->state) { case 0: FreezeSelectDestFieldCursorSprite(); PrintECInterfaceTextById(3); EC_CreateYesNoMenuWithInitialCursorPos(0); sEasyChatGraphicsResources->state++; break; case 1: return IsDma3ManagerBusyWithBgCopy(); } return TRUE; } static bool8 ECInterfaceCmd_04(void) { switch (sEasyChatGraphicsResources->state) { case 0: FreezeSelectDestFieldCursorSprite(); PrintECInterfaceTextById(1); EC_CreateYesNoMenuWithInitialCursorPos(1); sEasyChatGraphicsResources->state++; break; case 1: return IsDma3ManagerBusyWithBgCopy(); } return TRUE; } static bool8 ECInterfaceCmd_07(void) { switch (sEasyChatGraphicsResources->state) { case 0: UnfreezeSelectDestFieldCursorSprite(); PrintECInterfaceTextById(0); ShowBg(0); sEasyChatGraphicsResources->state++; break; case 1: return IsDma3ManagerBusyWithBgCopy(); } return TRUE; } static bool8 ECInterfaceCmd_08(void) { switch (sEasyChatGraphicsResources->state) { case 0: UnfreezeSelectDestFieldCursorSprite(); PrintECInterfaceTextById(0); PrintECFields(); sEasyChatGraphicsResources->state++; // Fall through case 1: return IsDma3ManagerBusyWithBgCopy(); } return TRUE; } static bool8 ECInterfaceCmd_09(void) { switch (sEasyChatGraphicsResources->state) { case 0: FreezeSelectDestFieldCursorSprite(); HideBg(0); SetRegWin0Coords(0, 0, 0, 0); PrintECGroupOrAlphaMenu(); sEasyChatGraphicsResources->state++; break; case 1: if (!IsDma3ManagerBusyWithBgCopy()) { StartWin2FrameAnim(0); sEasyChatGraphicsResources->state++; } break; case 2: if (!IsDma3ManagerBusyWithBgCopy() && !AnimateFrameResize()) sEasyChatGraphicsResources->state++; break; case 3: if (!IsDma3ManagerBusyWithBgCopy()) { CreateSelectGroupHelpSprite(); sEasyChatGraphicsResources->state++; } break; case 4: if (!AnimateSeletGroupModeAndHelpSpriteEnter()) { CreateRedRectangularCursorSpritePair(); UpdateVerticalScrollArrowSpriteXPos(0); UpdateVerticalScrollArrowVisibility(); sEasyChatGraphicsResources->state++; return FALSE; } break; default: return FALSE; } return TRUE; } static bool8 ECInterfaceCmd_10(void) { switch (sEasyChatGraphicsResources->state) { case 0: DestroyRedRectangularCursor(); StartModeIconHidingAnimation(); HideVerticalScrollArrowSprites(); sEasyChatGraphicsResources->state++; break; case 1: if (RunModeIconHidingAnimation() == TRUE) break; StartWin2FrameAnim(1); sEasyChatGraphicsResources->state++; // Fall through case 2: if (!AnimateFrameResize()) sEasyChatGraphicsResources->state++; break; case 3: if (!IsDma3ManagerBusyWithBgCopy()) { UnfreezeSelectDestFieldCursorSprite(); ShowBg(0); sEasyChatGraphicsResources->state++; } break; case 4: return FALSE; } return TRUE; } static bool8 ECInterfaceCmd_22(void) { switch (sEasyChatGraphicsResources->state) { case 0: DestroyRedRectangularCursor(); HideVerticalScrollArrowSprites(); ShrinkModeIconsSprite(); StartWin2FrameAnim(5); sEasyChatGraphicsResources->state++; break; case 1: if (!AnimateFrameResize() && !ModeIconsSpriteAnimIsEnded()) { PrintECGroupOrAlphaMenu(); sEasyChatGraphicsResources->state++; } break; case 2: if (!IsDma3ManagerBusyWithBgCopy()) { StartWin2FrameAnim(6); ShowModeIconsSprite(); sEasyChatGraphicsResources->state++; } break; case 3: if (!AnimateFrameResize() && !ModeIconsSpriteAnimIsEnded()) { UpdateVerticalScrollArrowVisibility(); CreateRedRectangularCursorSpritePair(); sEasyChatGraphicsResources->state++; return FALSE; } break; case 4: return FALSE; } return TRUE; } static bool8 ECInterfaceCmd_14(void) { EC_MoveCursor(); return FALSE; } static bool8 ECInterfaceCmd_15(void) { switch (sEasyChatGraphicsResources->state) { case 0: ScheduleBg2VerticalScroll(1, 2); sEasyChatGraphicsResources->state++; // Fall through case 1: if (!AnimateBg2VerticalScroll()) { EC_MoveCursor(); UpdateVerticalScrollArrowVisibility(); return FALSE; } break; } return TRUE; } static bool8 ECInterfaceCmd_16(void) { switch (sEasyChatGraphicsResources->state) { case 0: ScheduleBg2VerticalScroll(-1, 2); sEasyChatGraphicsResources->state++; // Fall through case 1: if (!AnimateBg2VerticalScroll()) { UpdateVerticalScrollArrowVisibility(); sEasyChatGraphicsResources->state++; return FALSE; } break; case 2: return FALSE; } return TRUE; } static bool8 ECInterfaceCmd_11(void) { switch (sEasyChatGraphicsResources->state) { case 0: DestroyRedRectangularCursor(); StartModeIconHidingAnimation(); HideVerticalScrollArrowSprites(); sEasyChatGraphicsResources->state++; break; case 1: if (!RunModeIconHidingAnimation()) { ClearWin2AndCopyToVram(); sEasyChatGraphicsResources->state++; } break; case 2: if (!IsDma3ManagerBusyWithBgCopy()) { StartWin2FrameAnim(2); sEasyChatGraphicsResources->state++; } break; case 3: if (!AnimateFrameResize()) { PrintECMenuById(2); sEasyChatGraphicsResources->state++; } break; case 4: if (!IsDma3ManagerBusyWithBgCopy()) { CreateSelectWordCursorSprite(); UpdateVerticalScrollArrowSpriteXPos(1); UpdateVerticalScrollArrowVisibility(); UpdateStartSelectButtonSpriteVisibility(); sEasyChatGraphicsResources->state++; return FALSE; } break; case 5: return FALSE; } return TRUE; } static bool8 ECInterfaceCmd_12(void) { switch (sEasyChatGraphicsResources->state) { case 0: PrintECFields(); sEasyChatGraphicsResources->state++; break; case 1: DestroySelectWordCursorSprite(); HideVerticalScrollArrowSprites(); HideStartSelectButtonSprites(); ClearWin2AndCopyToVram(); sEasyChatGraphicsResources->state++; break; case 2: if (!IsDma3ManagerBusyWithBgCopy()) { StartWin2FrameAnim(3); sEasyChatGraphicsResources->state++; } break; case 3: if (!AnimateFrameResize()) { ShowBg(0); sEasyChatGraphicsResources->state++; } break; case 4: if (!IsDma3ManagerBusyWithBgCopy()) { UnfreezeSelectDestFieldCursorSprite(); sEasyChatGraphicsResources->state++; return FALSE; } break; case 5: return FALSE; } return TRUE; } static bool8 ECInterfaceCmd_13(void) { switch (sEasyChatGraphicsResources->state) { case 0: DestroySelectWordCursorSprite(); HideVerticalScrollArrowSprites(); HideStartSelectButtonSprites(); ClearWin2AndCopyToVram(); sEasyChatGraphicsResources->state++; break; case 1: if (!IsDma3ManagerBusyWithBgCopy()) { StartWin2FrameAnim(4); sEasyChatGraphicsResources->state++; } break; case 2: if (!AnimateFrameResize()) { PrintECGroupOrAlphaMenu(); sEasyChatGraphicsResources->state++; } break; case 3: if (!IsDma3ManagerBusyWithBgCopy()) { CreateSelectGroupHelpSprite(); sEasyChatGraphicsResources->state++; } break; case 4: if (!AnimateSeletGroupModeAndHelpSpriteEnter()) { CreateRedRectangularCursorSpritePair(); UpdateVerticalScrollArrowSpriteXPos(0); UpdateVerticalScrollArrowVisibility(); sEasyChatGraphicsResources->state++; return FALSE; } break; } return TRUE; } static bool8 ECInterfaceCmd_17(void) { SetSelectWordCursorSpritePos(); return FALSE; } static bool8 ECInterfaceCmd_19(void) { switch (sEasyChatGraphicsResources->state) { case 0: UpdateWin2PrintWordsScrollDown(); sEasyChatGraphicsResources->state++; break; case 1: if (!IsDma3ManagerBusyWithBgCopy()) { ScheduleBg2VerticalScroll(1, 2); sEasyChatGraphicsResources->state++; } break; case 2: if (!AnimateBg2VerticalScroll()) { SetSelectWordCursorSpritePos(); UpdateVerticalScrollArrowVisibility(); UpdateStartSelectButtonSpriteVisibility(); sEasyChatGraphicsResources->state++; return FALSE; } break; case 3: return FALSE; } return TRUE; } static bool8 ECInterfaceCmd_18(void) { switch (sEasyChatGraphicsResources->state) { case 0: UpdateWin2PrintWordsScrollUp(); sEasyChatGraphicsResources->state++; break; case 1: if (!IsDma3ManagerBusyWithBgCopy()) { ScheduleBg2VerticalScroll(-1, 2); sEasyChatGraphicsResources->state++; } break; case 2: if (!AnimateBg2VerticalScroll()) { UpdateVerticalScrollArrowVisibility(); UpdateStartSelectButtonSpriteVisibility(); sEasyChatGraphicsResources->state++; return FALSE; } break; case 3: return FALSE; } return TRUE; } static bool8 ECInterfaceCmd_21(void) { switch (sEasyChatGraphicsResources->state) { case 0: UpdateWin2PrintWordsScrollPageDown(); sEasyChatGraphicsResources->state++; break; case 1: if (!IsDma3ManagerBusyWithBgCopy()) { s16 direction = GetECSelectWordRowsAbove() - GetBg2ScrollRow(); ScheduleBg2VerticalScroll(direction, 4); sEasyChatGraphicsResources->state++; } break; case 2: if (!AnimateBg2VerticalScroll()) { SetSelectWordCursorSpritePos(); UpdateVerticalScrollArrowVisibility(); UpdateStartSelectButtonSpriteVisibility(); sEasyChatGraphicsResources->state++; return FALSE; } break; case 3: return FALSE; } return TRUE; } static bool8 ECInterfaceCmd_20(void) { switch (sEasyChatGraphicsResources->state) { case 0: UpdateWin2PrintWordsScrollPageUp(); sEasyChatGraphicsResources->state++; break; case 1: if (!IsDma3ManagerBusyWithBgCopy()) { s16 direction = GetECSelectWordRowsAbove() - GetBg2ScrollRow(); ScheduleBg2VerticalScroll(direction, 4); sEasyChatGraphicsResources->state++; } break; case 2: if (!AnimateBg2VerticalScroll()) { UpdateVerticalScrollArrowVisibility(); UpdateStartSelectButtonSpriteVisibility(); sEasyChatGraphicsResources->state++; return FALSE; } break; case 3: return FALSE; } return TRUE; } static bool8 InitEasyChatGraphicsWork_Internal(void) { sEasyChatGraphicsResources = Alloc(sizeof(*sEasyChatGraphicsResources)); if (sEasyChatGraphicsResources == NULL) return FALSE; sEasyChatGraphicsResources->state = 0; sEasyChatGraphicsResources->selectDestFieldCursorSprite = NULL; sEasyChatGraphicsResources->rectCursorSpriteRight = NULL; sEasyChatGraphicsResources->rectCursorSpriteLeft = NULL; sEasyChatGraphicsResources->selectWordCursorSprite = NULL; sEasyChatGraphicsResources->selectGroupHelpSprite = NULL; sEasyChatGraphicsResources->modeIconsSprite = NULL; sEasyChatGraphicsResources->upTriangleCursorSprite = NULL; sEasyChatGraphicsResources->downTriangleCursorSprite = NULL; sEasyChatGraphicsResources->startPgUpButtonSprite = NULL; sEasyChatGraphicsResources->selectPgDnButtonSprite = NULL; return TRUE; } static void SetGpuRegsForEasyChatInit(void) { ChangeBgX(3, 0, 0); ChangeBgY(3, 0, 0); ChangeBgX(1, 0, 0); ChangeBgY(1, 0, 0); ChangeBgX(2, 0, 0); ChangeBgY(2, 0, 0); ChangeBgX(0, 0, 0); ChangeBgY(0, 0, 0); SetGpuReg(REG_OFFSET_DISPCNT, DISPCNT_MODE_0 | DISPCNT_OBJ_1D_MAP | DISPCNT_OBJ_ON | DISPCNT_WIN0_ON); } static void LoadEasyChatPals(void) { ResetPaletteFade(); LoadPalette(gEasyChatMode_Pal, 0, 32); LoadPalette(gUnknown_843F76C, 1 * 16, 32); LoadPalette(gUnknown_843F78C, 4 * 16, 32); LoadPalette(gUnknown_843F874, 10 * 16, 8); LoadPalette(gUnknown_843F87C, 11 * 16, 10); LoadPalette(gUnknown_843F87C, 15 * 16, 10); LoadPalette(gUnknown_843F87C, 3 * 16, 10); } static void PrintTitleText(void) { int xOffset; const u8 *titleText = GetTitleText(); if (titleText == NULL) return; xOffset = (128 - GetStringWidth(1, titleText, 0)) / 2u; FillWindowPixelBuffer(0, PIXEL_FILL(0)); EC_AddTextPrinterParameterized2(0, 1, titleText, xOffset, 0, TEXT_SPEED_FF, TEXT_COLOR_TRANSPARENT, TEXT_COLOR_DARK_GREY, TEXT_COLOR_LIGHT_GREY); PutWindowTilemap(0); CopyWindowToVram(0, COPYWIN_BOTH); } static void EC_AddTextPrinterParameterized(u8 windowId, u8 fontId, const u8 *str, u8 x, u8 y, u8 speed, void (*callback)(struct TextPrinterTemplate *, u16)) { if (fontId == 1) y += 2; AddTextPrinterParameterized(windowId, fontId, str, x, y, speed, callback); } static void EC_AddTextPrinterParameterized2(u8 windowId, u8 fontId, const u8 *str, u8 x, u8 y, u8 speed, u8 bg, u8 fg, u8 shadow) { u8 color[3]; if (fontId == 1) y += 2; color[0] = bg; color[1] = fg; color[2] = shadow; AddTextPrinterParameterized3(windowId, fontId, x, y, color, speed, str); } static void PrintECInstructionsText(void) { FillBgTilemapBufferRect(0, 0, 0, 0, 32, 20, 17); TextWindow_SetUserSelectedFrame(1, 1, 0xE0); DrawTextBorderOuter(1, 1, 14); PrintECInterfaceTextById(0); PutWindowTilemap(1); CopyBgTilemapBufferToVram(0); } static void PrintECInterfaceTextById(u8 direction) { const u8 *text2 = NULL; const u8 *text1 = NULL; switch (direction) { case 0: GetEasyChatInstructionsText(&text1, &text2); break; case 2: GetEasyChatConfirmCancelText(&text1, &text2); break; case 3: GetEasyChatConfirmText(&text1, &text2); break; case 1: GetEasyChatConfirmDeletionText(&text1, &text2); break; } FillWindowPixelBuffer(1, PIXEL_FILL(1)); if (text1) EC_AddTextPrinterParameterized(1, 1, text1, 0, 0, TEXT_SPEED_FF, NULL); if (text2) EC_AddTextPrinterParameterized(1, 1, text2, 0, 16, TEXT_SPEED_FF, NULL); CopyWindowToVram(1, COPYWIN_BOTH); } static void EC_CreateYesNoMenuWithInitialCursorPos(u8 initialCursorPos) { CreateYesNoMenu(&sEasyChatYesNoWindowTemplate, 1, 0, 2, 0x001, 14, initialCursorPos); } static void CreatePhraseFrameWindow(void) { u8 frameId; struct WindowTemplate template; frameId = GetEasyChatScreenFrameId(); template.bg = 3; template.tilemapLeft = sPhraseFrameDimensions[frameId].left; template.tilemapTop = sPhraseFrameDimensions[frameId].top; template.width = sPhraseFrameDimensions[frameId].width; template.height = sPhraseFrameDimensions[frameId].height; template.paletteNum = 11; template.baseBlock = 0x060; sEasyChatGraphicsResources->windowId = AddWindow(&template); PutWindowTilemap(sEasyChatGraphicsResources->windowId); } static void PrintECFields(void) { u16 *ecWord; u8 numColumns, numRows; u8 *str; u8 frameId; int i, j, k; ecWord = GetEasyChatWordBuffer(); numColumns = GetNumColumns(); numRows = GetNumRows(); frameId = GetEasyChatScreenFrameId(); FillWindowPixelBuffer(sEasyChatGraphicsResources->windowId, PIXEL_FILL(1)); for (i = 0; i < numRows; i++) { str = sEasyChatGraphicsResources->ecPrintBuffer; str[0] = EOS; str = StringAppend(str, sText_Clear17); for (j = 0; j < numColumns; j++) { if (*ecWord != 0xFFFF) { str = CopyEasyChatWord(str, *ecWord); ecWord++; } else { str = WriteColorChangeControlCode(str, 0, TEXT_COLOR_RED); ecWord++; for (k = 0; k < 7; k++) { *str++ = CHAR_EXTRA_EMOJI; *str++ = 9; } str = WriteColorChangeControlCode(str, 0, TEXT_COLOR_DARK_GREY); } str = StringAppend(str, sText_Clear17); if (frameId == 2) { if (j == 0 && i == 4) break; } } *str = EOS; EC_AddTextPrinterParameterized(sEasyChatGraphicsResources->windowId, 1, sEasyChatGraphicsResources->ecPrintBuffer, 0, i * 16, TEXT_SPEED_FF, NULL); } CopyWindowToVram(sEasyChatGraphicsResources->windowId, COPYWIN_BOTH); } static void DrawECFrameInTilemapBuffer(u16 *tilemap) { u8 frameId; int right, bottom; int x, y; frameId = GetEasyChatScreenFrameId(); CpuFastFill(0, tilemap, BG_SCREEN_SIZE); if (frameId == 2) { right = sPhraseFrameDimensions[frameId].left + sPhraseFrameDimensions[frameId].width; bottom = sPhraseFrameDimensions[frameId].top + sPhraseFrameDimensions[frameId].height; for (y = sPhraseFrameDimensions[frameId].top; y < bottom; y++) { x = sPhraseFrameDimensions[frameId].left - 1; tilemap[y * 32 + x] = 0x1005; x++; for (; x < right; x++) tilemap[y * 32 + x] = 0x1000; tilemap[y* 32 + x] = 0x1007; } } else { y = sPhraseFrameDimensions[frameId].top - 1; x = sPhraseFrameDimensions[frameId].left - 1; right = sPhraseFrameDimensions[frameId].left + sPhraseFrameDimensions[frameId].width; bottom = sPhraseFrameDimensions[frameId].top + sPhraseFrameDimensions[frameId].height; tilemap[y * 32 + x] = 0x1001; x++; for (; x < right; x++) tilemap[y * 32 + x] = 0x1002; tilemap[y * 32 + x] = 0x1003; y++; for (; y < bottom; y++) { x = sPhraseFrameDimensions[frameId].left - 1; tilemap[y * 32 + x] = 0x1005; x++; for (; x < right; x++) tilemap[y * 32 + x] = 0x1000; tilemap[y* 32 + x] = 0x1007; } x = sPhraseFrameDimensions[frameId].left - 1; tilemap[y * 32 + x] = 0x1009; x++; for (; x < right; x++) tilemap[y * 32 + x] = 0x100A; tilemap[y * 32 + x] = 0x100B; } } static void PutWin2TilemapAndCopyToVram(void) { PutWindowTilemap(2); CopyBgTilemapBufferToVram(2); } static void PrintECMenuById(u32 id) { InitBg2Scroll(); FillWindowPixelBuffer(2, PIXEL_FILL(1)); switch (id) { case 0: PrintECGroupsMenu(); break; case 1: PrintEasyChatKeyboardText(); break; case 2: PrintECWordsMenu(); break; } CopyWindowToVram(2, COPYWIN_GFX); } static void PrintECGroupOrAlphaMenu(void) { if (!IsEasyChatAlphaMode()) PrintECMenuById(0); else PrintECMenuById(1); } static void PrintECGroupsMenu(void) { int i; int x, y; i = 0; y = 96; while (1) { for (x = 0; x < 2; x++) { u8 groupId = GetSelectedGroupByIndex(i++); if (groupId == EC_NUM_GROUPS) { ScheduleBg2VerticalScroll(GetECSelectGroupRowsAbove(), 0); return; } EC_AddTextPrinterParameterized(2, 1, GetEasyChatWordGroupName(groupId), x * 84 + 10, y, TEXT_SPEED_FF, NULL); } y += 16; } } static void PrintEasyChatKeyboardText(void) { u32 i; for (i = 0; i < NELEMS(sEasyChatKeyboardText); i++) EC_AddTextPrinterParameterized(2, 1, sEasyChatKeyboardText[i], 10, 96 + i * 16, TEXT_SPEED_FF, NULL); } static void PrintECWordsMenu(void) { PrintECRowsWin2(0, 4); } static void UpdateWin2PrintWordsScrollDown(void) { u8 rowsAbove = GetECSelectWordRowsAbove() + 3; ClearECRowsWin2(rowsAbove, 1); PrintECRowsWin2(rowsAbove, 1); } static void UpdateWin2PrintWordsScrollUp(void) { u8 rowsAbove = GetECSelectWordRowsAbove(); ClearECRowsWin2(rowsAbove, 1); PrintECRowsWin2(rowsAbove, 1); } static void UpdateWin2PrintWordsScrollPageDown(void) { u8 row = GetECSelectWordRowsAbove(); u8 maxrow = row + 4; u8 numrowsplus1 = GetECSelectWordNumRows() + 1; if (maxrow > numrowsplus1) maxrow = numrowsplus1; if (row < maxrow) { u8 remrow = maxrow - row; ClearECRowsWin2(row, remrow); PrintECRowsWin2(row, remrow); } } static void UpdateWin2PrintWordsScrollPageUp(void) { u8 row = GetECSelectWordRowsAbove(); u8 maxrow = GetBg2ScrollRow(); if (row < maxrow) { u8 remrow = maxrow - row; ClearECRowsWin2(row, remrow); PrintECRowsWin2(row, remrow); } } static void PrintECRowsWin2(u8 row, u8 remrow) { int i, j; u16 easyChatWord; u8 *str; int y; u8 y_; int ecWordIdx; ecWordIdx = row * 2; y = (row * 16 + 96) & 0xFF; for (i = 0; i < remrow; i++) { for (j = 0; j < 2; j++) { // FIXME: Dumb trick needed to match y_ = y << 18 >> 18; easyChatWord = GetDisplayedWordByIndex(ecWordIdx++); if (easyChatWord != 0xFFFF) { CopyEasyChatWordPadded(sEasyChatGraphicsResources->ecPaddedWordBuffer, easyChatWord, 0); EC_AddTextPrinterParameterized(2, 1, sEasyChatGraphicsResources->ecPaddedWordBuffer, (j * 13 + 3) * 8, y_, TEXT_SPEED_FF, NULL); } } y += 16; } CopyWindowToVram(2, COPYWIN_GFX); } static void ClearECRowsWin2(u8 row, u8 remrow) { int y; int totalHeight; int heightWrappedAround; int heightToBottom; y = (row * 16 + 96) & 0xFF; heightToBottom = remrow * 16; totalHeight = y + heightToBottom; if (totalHeight > 255) { heightWrappedAround = totalHeight - 256; heightToBottom = 256 - y; } else { heightWrappedAround = 0; } FillWindowPixelRect(2, PIXEL_FILL(1), 0, y, 224, heightToBottom); if (heightWrappedAround) FillWindowPixelRect(2, PIXEL_FILL(1), 0, 0, 224, heightWrappedAround); } static void ClearWin2AndCopyToVram(void) { FillWindowPixelBuffer(2, PIXEL_FILL(1)); CopyWindowToVram(2, COPYWIN_GFX); } static void StartWin2FrameAnim(int animNo) { switch (animNo) { case 0: sEasyChatGraphicsResources->frameAnimIdx = 0; sEasyChatGraphicsResources->frameAnimTarget = 10; break; case 1: sEasyChatGraphicsResources->frameAnimIdx = 9; sEasyChatGraphicsResources->frameAnimTarget = 0; break; case 2: sEasyChatGraphicsResources->frameAnimIdx = 11; sEasyChatGraphicsResources->frameAnimTarget = 17; break; case 3: sEasyChatGraphicsResources->frameAnimIdx = 17; sEasyChatGraphicsResources->frameAnimTarget = 0; break; case 4: sEasyChatGraphicsResources->frameAnimIdx = 17; sEasyChatGraphicsResources->frameAnimTarget = 10; break; case 5: sEasyChatGraphicsResources->frameAnimIdx = 18; sEasyChatGraphicsResources->frameAnimTarget = 22; break; case 6: sEasyChatGraphicsResources->frameAnimIdx = 22; sEasyChatGraphicsResources->frameAnimTarget = 18; break; } sEasyChatGraphicsResources->frameAnimDelta = sEasyChatGraphicsResources->frameAnimIdx < sEasyChatGraphicsResources->frameAnimTarget ? 1 : -1; } static bool8 AnimateFrameResize(void) { if (sEasyChatGraphicsResources->frameAnimIdx == sEasyChatGraphicsResources->frameAnimTarget) return FALSE; sEasyChatGraphicsResources->frameAnimIdx += sEasyChatGraphicsResources->frameAnimDelta; RedrawFrameByIndex(sEasyChatGraphicsResources->frameAnimIdx); return sEasyChatGraphicsResources->frameAnimIdx != sEasyChatGraphicsResources->frameAnimTarget; } static void RedrawFrameByIndex(u8 direction) { FillBgTilemapBufferRect_Palette0(1, 0, 0, 10, 30, 10); switch (direction) { case 0: break; case 1: RedrawFrameByRect(11, 14, 3, 2); break; case 2: RedrawFrameByRect(9, 14, 7, 2); break; case 3: RedrawFrameByRect(7, 14, 11, 2); break; case 4: RedrawFrameByRect(5, 14, 15, 2); break; case 5: RedrawFrameByRect(3, 14, 19, 2); break; case 6: RedrawFrameByRect(1, 14, 23, 2); break; case 7: RedrawFrameByRect(1, 13, 23, 4); break; case 8: RedrawFrameByRect(1, 12, 23, 6); break; case 9: RedrawFrameByRect(1, 11, 23, 8); break; case 10: RedrawFrameByRect(1, 10, 23, 10); break; case 11: RedrawFrameByRect(1, 10, 24, 10); break; case 12: RedrawFrameByRect(1, 10, 25, 10); break; case 13: RedrawFrameByRect(1, 10, 26, 10); break; case 14: RedrawFrameByRect(1, 10, 27, 10); break; case 15: RedrawFrameByRect(1, 10, 28, 10); break; case 16: RedrawFrameByRect(1, 10, 29, 10); break; case 17: RedrawFrameByRect(0, 10, 30, 10); break; case 18: RedrawFrameByRect(1, 10, 23, 10); break; case 19: RedrawFrameByRect(1, 11, 23, 8); break; case 20: RedrawFrameByRect(1, 12, 23, 6); break; case 21: RedrawFrameByRect(1, 13, 23, 4); break; case 22: RedrawFrameByRect(1, 14, 23, 2); break; } CopyBgTilemapBufferToVram(1); } static void RedrawFrameByRect(int left, int top, int width, int height) { u16 *tilemap; int right; int bottom; int x, y; tilemap = sEasyChatGraphicsResources->bg1TilemapBuffer; right = left + width - 1; bottom = top + height - 1; x = left; y = top; tilemap[y * 32 + x] = 0x4001; x++; for (; x < right; x++) tilemap[y * 32 + x] = 0x4002; tilemap[y * 32 + x] = 0x4003; y++; for (; y < bottom; y++) { tilemap[y * 32 + left] = 0x4005; x = left + 1; for (; x < right; x++) tilemap[y * 32 + x] = 0x4000; tilemap[y * 32 + x] = 0x4007; } tilemap[y * 32 + left] = 0x4009; x = left + 1; for (; x < right; x++) tilemap[y * 32 + x] = 0x400A; tilemap[y * 32 + x] = 0x400B; SetRegWin0Coords((left + 1) * 8, (top + 1) * 8, (width - 2) * 8, (height - 2) * 8); } static void InitBg2Scroll(void) { ChangeBgY(2, 0x800, 0); sEasyChatGraphicsResources->bg2ScrollRow = 0; } static void ScheduleBg2VerticalScroll(s16 direction, u8 speed) { int bgY; s16 totalDelta; bgY = GetBgY(2); sEasyChatGraphicsResources->bg2ScrollRow += direction; totalDelta = direction * 16; bgY += totalDelta << 8; if (speed) { sEasyChatGraphicsResources->tgtBgY = bgY; sEasyChatGraphicsResources->deltaBgY = speed * 256; if (totalDelta < 0) sEasyChatGraphicsResources->deltaBgY = -sEasyChatGraphicsResources->deltaBgY; } else { ChangeBgY(2, bgY, 0); } } static bool8 AnimateBg2VerticalScroll(void) { int bgY; bgY = GetBgY(2); if (bgY == sEasyChatGraphicsResources->tgtBgY) { return FALSE; } else { ChangeBgY(2, sEasyChatGraphicsResources->deltaBgY, 1); return TRUE; } } static int GetBg2ScrollRow(void) { return sEasyChatGraphicsResources->bg2ScrollRow; } static void SetRegWin0Coords(u8 left, u8 top, u8 width, u8 height) { u16 horizontalDimensions = WIN_RANGE(left, left + width); u16 verticalDimensions = WIN_RANGE(top, top + height); SetGpuReg(REG_OFFSET_WIN0H, horizontalDimensions); SetGpuReg(REG_OFFSET_WIN0V, verticalDimensions); } static void LoadSpriteGfx(void) { u32 i; LoadSpriteSheets(sEasyChatSpriteSheets); LoadSpritePalettes(sEasyChatSpritePalettes); for (i = 0; i < NELEMS(sEasyChatCompressedSpriteSheets); i++) LoadCompressedSpriteSheet(&sEasyChatCompressedSpriteSheets[i]); } static void CreateSelectDestFieldCursorSprite(void) { u8 frameId = GetEasyChatScreenFrameId(); s16 x = sPhraseFrameDimensions[frameId].left * 8 + 13; s16 y = (sPhraseFrameDimensions[frameId].top + 1) * 8 + 1; u8 spriteId = CreateSprite(&sSpriteTemplate_RightTriangleCursor, x, y, 2); sEasyChatGraphicsResources->selectDestFieldCursorSprite = &gSprites[spriteId]; gSprites[spriteId].data[1] = 1; } static void SpriteCB_BounceCursor(struct Sprite * sprite) { if (sprite->data[1]) { if (++sprite->data[0] > 2) { sprite->data[0] = 0; if (++sprite->pos2.x > 0) sprite->pos2.x = -6; } } } static void SetSelectDestFieldCursorSpritePosAndResetAnim(u8 x, u8 y) { sEasyChatGraphicsResources->selectDestFieldCursorSprite->pos1.x = x; sEasyChatGraphicsResources->selectDestFieldCursorSprite->pos1.y = y; sEasyChatGraphicsResources->selectDestFieldCursorSprite->pos2.x = 0; sEasyChatGraphicsResources->selectDestFieldCursorSprite->data[0] = 0; } static void FreezeSelectDestFieldCursorSprite(void) { sEasyChatGraphicsResources->selectDestFieldCursorSprite->data[0] = 0; sEasyChatGraphicsResources->selectDestFieldCursorSprite->data[1] = 0; sEasyChatGraphicsResources->selectDestFieldCursorSprite->pos2.x = 0; } static void UnfreezeSelectDestFieldCursorSprite(void) { sEasyChatGraphicsResources->selectDestFieldCursorSprite->data[1] = 1; } static void CreateRedRectangularCursorSpritePair(void) { u8 spriteId = CreateSprite(&sSpriteTemplate_RedRectangularCursor, 0, 0, 3); sEasyChatGraphicsResources->rectCursorSpriteRight = &gSprites[spriteId]; sEasyChatGraphicsResources->rectCursorSpriteRight->pos2.x = 32; spriteId = CreateSprite(&sSpriteTemplate_RedRectangularCursor, 0, 0, 3); sEasyChatGraphicsResources->rectCursorSpriteLeft = &gSprites[spriteId]; sEasyChatGraphicsResources->rectCursorSpriteLeft->pos2.x = -32; sEasyChatGraphicsResources->rectCursorSpriteRight->hFlip = TRUE; EC_MoveCursor(); } static void DestroyRedRectangularCursor(void) { DestroySprite(sEasyChatGraphicsResources->rectCursorSpriteRight); sEasyChatGraphicsResources->rectCursorSpriteRight = NULL; DestroySprite(sEasyChatGraphicsResources->rectCursorSpriteLeft); sEasyChatGraphicsResources->rectCursorSpriteLeft = NULL; } static void EC_MoveCursor(void) { u8 x; u8 y; if (sEasyChatGraphicsResources->rectCursorSpriteRight && sEasyChatGraphicsResources->rectCursorSpriteLeft) { GetECSelectGroupCursorCoords(&x, &y); if (!IsEasyChatAlphaMode()) MoveCursor_Group(x, y); else MoveCursor_Alpha(x, y); } } static void MoveCursor_Group(s8 x, s8 y) { if (x != -1) { StartSpriteAnim(sEasyChatGraphicsResources->rectCursorSpriteRight, 0); sEasyChatGraphicsResources->rectCursorSpriteRight->pos1.x = x * 84 + 58; sEasyChatGraphicsResources->rectCursorSpriteRight->pos1.y = y * 16 + 96; StartSpriteAnim(sEasyChatGraphicsResources->rectCursorSpriteLeft, 0); sEasyChatGraphicsResources->rectCursorSpriteLeft->pos1.x = x * 84 + 58; sEasyChatGraphicsResources->rectCursorSpriteLeft->pos1.y = y * 16 + 96; } else { StartSpriteAnim(sEasyChatGraphicsResources->rectCursorSpriteRight, 1); sEasyChatGraphicsResources->rectCursorSpriteRight->pos1.x = 216; sEasyChatGraphicsResources->rectCursorSpriteRight->pos1.y = y * 16 + 112; StartSpriteAnim(sEasyChatGraphicsResources->rectCursorSpriteLeft, 1); sEasyChatGraphicsResources->rectCursorSpriteLeft->pos1.x = 216; sEasyChatGraphicsResources->rectCursorSpriteLeft->pos1.y = y * 16 + 112; } } static void MoveCursor_Alpha(s8 cursorX, s8 cursorY) { int anim; int x, y; if (cursorX != -1) { y = cursorY * 16 + 96; x = 32; if (cursorX == 6 && cursorY == 0) { x = 157; anim = 2; } else { x += sECDisplay_AlphaModeXCoords[cursorX < NELEMS(sECDisplay_AlphaModeXCoords) ? cursorX : 0]; anim = 3; } StartSpriteAnim(sEasyChatGraphicsResources->rectCursorSpriteRight, anim); sEasyChatGraphicsResources->rectCursorSpriteRight->pos1.x = x; sEasyChatGraphicsResources->rectCursorSpriteRight->pos1.y = y; StartSpriteAnim(sEasyChatGraphicsResources->rectCursorSpriteLeft, anim); sEasyChatGraphicsResources->rectCursorSpriteLeft->pos1.x = x; sEasyChatGraphicsResources->rectCursorSpriteLeft->pos1.y = y; } else { StartSpriteAnim(sEasyChatGraphicsResources->rectCursorSpriteRight, 1); sEasyChatGraphicsResources->rectCursorSpriteRight->pos1.x = 216; sEasyChatGraphicsResources->rectCursorSpriteRight->pos1.y = cursorY * 16 + 112; StartSpriteAnim(sEasyChatGraphicsResources->rectCursorSpriteLeft, 1); sEasyChatGraphicsResources->rectCursorSpriteLeft->pos1.x = 216; sEasyChatGraphicsResources->rectCursorSpriteLeft->pos1.y = cursorY * 16 + 112; } } static void CreateSelectWordCursorSprite(void) { u8 spriteId = CreateSprite(&sSpriteTemplate_RightTriangleCursor, 0, 0, 4); sEasyChatGraphicsResources->selectWordCursorSprite = &gSprites[spriteId]; sEasyChatGraphicsResources->selectWordCursorSprite->callback = SpriteCB_SelectWordCursorSprite; sEasyChatGraphicsResources->selectWordCursorSprite->oam.priority = 2; SetSelectWordCursorSpritePos(); } static void SpriteCB_SelectWordCursorSprite(struct Sprite * sprite) { if (++sprite->data[0] > 2) { sprite->data[0] = 0; if (++sprite->pos2.x > 0) sprite->pos2.x = -6; } } static void SetSelectWordCursorSpritePos(void) { s8 cursorX, cursorY; u8 x, y; GetECSelectWordCursorCoords(&cursorX, &cursorY); x = cursorX * 13 + 3; y = cursorY * 2 + 11; SetSelectWordCursorSpritePosExplicit(x, y); } static void SetSelectWordCursorSpritePosExplicit(u8 x, u8 y) { if (sEasyChatGraphicsResources->selectWordCursorSprite) { sEasyChatGraphicsResources->selectWordCursorSprite->pos1.x = x * 8 + 4; sEasyChatGraphicsResources->selectWordCursorSprite->pos1.y = (y + 1) * 8 + 1; sEasyChatGraphicsResources->selectWordCursorSprite->pos2.x = 0; sEasyChatGraphicsResources->selectWordCursorSprite->data[0] = 0; } } static void DestroySelectWordCursorSprite(void) { if (sEasyChatGraphicsResources->selectWordCursorSprite) { DestroySprite(sEasyChatGraphicsResources->selectWordCursorSprite); sEasyChatGraphicsResources->selectWordCursorSprite = NULL; } } static void CreateSelectGroupHelpSprite(void) { u8 spriteId = CreateSprite(&sSpriteTemplate_SelectGroupHelp, 208, 128, 6); sEasyChatGraphicsResources->selectGroupHelpSprite = &gSprites[spriteId]; sEasyChatGraphicsResources->selectGroupHelpSprite->pos2.x = -64; spriteId = CreateSprite(&sSpriteTemplate_EasyChatModeIcons, 208, 80, 5); sEasyChatGraphicsResources->modeIconsSprite = &gSprites[spriteId]; sEasyChatGraphicsResources->modeIconState = 0; } static bool8 AnimateSeletGroupModeAndHelpSpriteEnter(void) { switch (sEasyChatGraphicsResources->modeIconState) { default: return FALSE; case 0: sEasyChatGraphicsResources->selectGroupHelpSprite->pos2.x += 8; if (sEasyChatGraphicsResources->selectGroupHelpSprite->pos2.x >= 0) { sEasyChatGraphicsResources->selectGroupHelpSprite->pos2.x = 0; if (!IsEasyChatAlphaMode()) StartSpriteAnim(sEasyChatGraphicsResources->modeIconsSprite, 1); else StartSpriteAnim(sEasyChatGraphicsResources->modeIconsSprite, 2); sEasyChatGraphicsResources->modeIconState++; } break; case 1: if (sEasyChatGraphicsResources->modeIconsSprite->animEnded) { sEasyChatGraphicsResources->modeIconState = 2; return FALSE; } } return TRUE; } static void StartModeIconHidingAnimation(void) { sEasyChatGraphicsResources->modeIconState = 0; StartSpriteAnim(sEasyChatGraphicsResources->modeIconsSprite, 3); } static bool8 RunModeIconHidingAnimation(void) { switch (sEasyChatGraphicsResources->modeIconState) { default: return FALSE; case 0: if (sEasyChatGraphicsResources->modeIconsSprite->animEnded) sEasyChatGraphicsResources->modeIconState = 1; break; case 1: sEasyChatGraphicsResources->selectGroupHelpSprite->pos2.x -= 8; if (sEasyChatGraphicsResources->selectGroupHelpSprite->pos2.x <= -64) { DestroySprite(sEasyChatGraphicsResources->modeIconsSprite); DestroySprite(sEasyChatGraphicsResources->selectGroupHelpSprite); sEasyChatGraphicsResources->modeIconsSprite = NULL; sEasyChatGraphicsResources->selectGroupHelpSprite = NULL; sEasyChatGraphicsResources->modeIconState++; return FALSE; } } return TRUE; } static void ShrinkModeIconsSprite(void) { StartSpriteAnim(sEasyChatGraphicsResources->modeIconsSprite, 4); } static void ShowModeIconsSprite(void) { if (!IsEasyChatAlphaMode()) StartSpriteAnim(sEasyChatGraphicsResources->modeIconsSprite, 1); else StartSpriteAnim(sEasyChatGraphicsResources->modeIconsSprite, 2); } static bool8 ModeIconsSpriteAnimIsEnded(void) { return !sEasyChatGraphicsResources->modeIconsSprite->animEnded; } static void CreateVerticalScrollArrowSprites(void) { u8 spriteId = CreateSprite(&sSpriteTemplate_UpTriangleCursor, 96, 80, 0); if (spriteId != MAX_SPRITES) sEasyChatGraphicsResources->upTriangleCursorSprite = &gSprites[spriteId]; spriteId = CreateSprite(&sSpriteTemplate_UpTriangleCursor, 96, 156, 0); if (spriteId != MAX_SPRITES) { sEasyChatGraphicsResources->downTriangleCursorSprite = &gSprites[spriteId]; sEasyChatGraphicsResources->downTriangleCursorSprite->vFlip = TRUE; } HideVerticalScrollArrowSprites(); } static void UpdateVerticalScrollArrowVisibility(void) { sEasyChatGraphicsResources->upTriangleCursorSprite->invisible = !ShouldDrawECUpArrow(); sEasyChatGraphicsResources->downTriangleCursorSprite->invisible = !ShouldDrawECDownArrow(); } static void HideVerticalScrollArrowSprites(void) { sEasyChatGraphicsResources->upTriangleCursorSprite->invisible = TRUE; sEasyChatGraphicsResources->downTriangleCursorSprite->invisible = TRUE; } static void UpdateVerticalScrollArrowSpriteXPos(int direction) { if (!direction) { // Group select sEasyChatGraphicsResources->upTriangleCursorSprite->pos1.x = 96; sEasyChatGraphicsResources->downTriangleCursorSprite->pos1.x = 96; } else { // Word select sEasyChatGraphicsResources->upTriangleCursorSprite->pos1.x = 120; sEasyChatGraphicsResources->downTriangleCursorSprite->pos1.x = 120; } } static void CreateStartSelectButtonsSprites(void) { u8 spriteId = CreateSprite(&sSpriteTemplate_StartSelectButtons, 220, 84, 1); if (spriteId != MAX_SPRITES) sEasyChatGraphicsResources->startPgUpButtonSprite = &gSprites[spriteId]; spriteId = CreateSprite(&sSpriteTemplate_StartSelectButtons, 220, 156, 1); if (spriteId != MAX_SPRITES) { sEasyChatGraphicsResources->selectPgDnButtonSprite = &gSprites[spriteId]; StartSpriteAnim(sEasyChatGraphicsResources->selectPgDnButtonSprite, 1); } HideStartSelectButtonSprites(); } static void UpdateStartSelectButtonSpriteVisibility(void) { sEasyChatGraphicsResources->startPgUpButtonSprite->invisible = !ShouldDrawECUpArrow(); sEasyChatGraphicsResources->selectPgDnButtonSprite->invisible = !ShouldDrawECDownArrow(); } static void HideStartSelectButtonSprites(void) { sEasyChatGraphicsResources->startPgUpButtonSprite->invisible = TRUE; sEasyChatGraphicsResources->selectPgDnButtonSprite->invisible = TRUE; } static void CreateFooterWindow(void) { u16 windowId; struct WindowTemplate template; template.bg = 3; template.tilemapLeft = 4; template.tilemapTop = 11; template.width = 24; template.height = 2; template.paletteNum = 11; template.baseBlock = 0x030; windowId = AddWindow(&template); FillWindowPixelBuffer(windowId, PIXEL_FILL(1)); EC_AddTextPrinterParameterized(windowId, 1, gUnknown_841EE2B, 0, 0, 0, NULL); PutWindowTilemap(windowId); }
{ "pile_set_name": "Github" }
/* Copyright 2015 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 protobuf import ( "k8s.io/gengo/namer" "k8s.io/gengo/types" ) type ImportTracker struct { namer.DefaultImportTracker } func NewImportTracker(local types.Name, typesToAdd ...*types.Type) *ImportTracker { tracker := namer.NewDefaultImportTracker(local) tracker.IsInvalidType = func(t *types.Type) bool { return t.Kind != types.Protobuf } tracker.LocalName = func(name types.Name) string { return name.Package } tracker.PrintImport = func(path, name string) string { return path } tracker.AddTypes(typesToAdd...) return &ImportTracker{ DefaultImportTracker: tracker, } } // AddNullable ensures that support for the nullable Gogo-protobuf extension is added. func (tracker *ImportTracker) AddNullable() { tracker.AddType(&types.Type{ Kind: types.Protobuf, Name: types.Name{ Name: "nullable", Package: "gogoproto", Path: "github.com/gogo/protobuf/gogoproto/gogo.proto", }, }) }
{ "pile_set_name": "Github" }
<ExtensionModel> <ExtensionPoint path="/MonoDevelop/Debugging/DebuggerEngines"> <Description>Debug session factories. Specified classes must implement MonoDevelop.Debugger.IDebuggerEngine</Description> <ExtensionNode name="DebuggerEngine" type="MonoDevelop.Debugger.DebuggerEngineExtensionNode"/> </ExtensionPoint> <ExtensionPoint path="/MonoDevelop/Debugging/Evaluators"> <Description>Expression evaluator factories. Specified classes must implement MonoDevelop.Debugger.IExpressionEvaluator</Description> <ExtensionNode name="ExpressionEvaluator" type="MonoDevelop.Debugger.ExpressionEvaluatorExtensionNode"/> </ExtensionPoint> <ExtensionPoint path="/MonoDevelop/Debugging/ValueVisualizers"> <Description>Value visualizers. Specified classes must extend MonoDevelop.Debugger.ValueVisualizer</Description> <ExtensionNode name="Type"/> </ExtensionPoint> <ExtensionPoint path="/MonoDevelop/Debugging/DebugValueConverters"> <Description>Debug value converters. Specified classes must extend MonoDevelop.Debugger.DebugValueConverter&lt;T&gt;</Description> <ExtensionNode name="Type"/> </ExtensionPoint> <ExtensionPoint path="/MonoDevelop/Debugging/InlineVisualizers"> <Description>Inline visualizers. Specified classes must extend MonoDevelop.Debugger.InlineVisualizer</Description> <ExtensionNode name="Type"/> </ExtensionPoint> <ExtensionPoint path="/MonoDevelop/Debugging/PreviewVisualizers"> <Description>Preview visualizers. Specified classes must extend MonoDevelop.Debugger.PreviewVisualizer</Description> <ExtensionNode name="Type" /> </ExtensionPoint> <Extension path = "/MonoDevelop/Ide/Pads"> <Category id="Debug" _name="Debug Pads"> <Pad id = "MonoDevelop.Debugger.BreakpointPad" defaultLayout="Debug" defaultPlacement = "Bottom" icon="md-view-debug-breakpoints" class = "MonoDevelop.Debugger.BreakpointPad" _label="Breakpoints" group="main"/> <Pad id = "MonoDevelop.Debugger.LocalsPad" defaultLayout="Debug" defaultPlacement = "Bottom" icon="md-view-debug-locals" class = "MonoDevelop.Debugger.LocalsPad" _label="Locals" group="main"/> <Pad id = "MonoDevelop.Debugger.WatchPad" defaultLayout="Debug" defaultPlacement = "Bottom" icon="md-view-debug-watch" class = "MonoDevelop.Debugger.WatchPad" _label="Watch" group="main"/> <Pad id = "MonoDevelop.Debugger.ImmediatePad" defaultLayout="Debug" defaultPlacement = "MonoDevelop.Debugger.StackTracePad/Center Bottom" icon="md-view-debug-immediate" class = "MonoDevelop.Debugger.ImmediatePad" _label="Immediate"/> <Pad id = "MonoDevelop.Debugger.StackTracePad" defaultLayout="Debug" defaultPlacement = "MonoDevelop.Debugger.WatchPad/Right Bottom" icon="md-view-debug-call-stack" class = "MonoDevelop.Debugger.StackTracePad" _label="Call Stack" /> <Pad id = "MonoDevelop.Debugger.ThreadsPad" defaultLayout="Debug" defaultPlacement = "Bottom" icon="md-view-debug-threads" class = "MonoDevelop.Debugger.ThreadsPad" _label="Threads" group="main"/> </Category> </Extension> <Extension path="/MonoDevelop/Ide/WorkbenchLayouts"> <Layout id="Debug" _name="Debug" /> </Extension> <Extension path="/MonoDevelop/Debugging/ValueVisualizers"> <Type class="MonoDevelop.Debugger.Visualizer.TextVisualizer" /> <Type class="MonoDevelop.Debugger.Visualizer.PixbufVisualizer" /> <Type class="MonoDevelop.Debugger.Visualizer.CStringVisualizer" /> </Extension> <Extension path = "/MonoDevelop/Ide/StartupHandlers"> <Class class="MonoDevelop.Debugger.Initializer" /> </Extension> <Extension path = "/MonoDevelop/Ide/Commands/Project"> <Command id = "MonoDevelop.Debugger.DebugCommands.Debug" defaultHandler = "MonoDevelop.Debugger.DebugHandler" icon = "md-bug" shortcut = "F5" macShortcut = "Meta|Return F5" _description = "Start debugging" _label = "Start _Debugging" /> <Command id = "MonoDevelop.Debugger.DebugCommands.DebugEntry" defaultHandler = "MonoDevelop.Debugger.DebugEntryHandler" icon = "md-bug" _description = "Debug current project" _label = "Start D_ebugging Item" _displayName = "Start Debugging (Current Project)" /> </Extension> <Extension path = "/MonoDevelop/Ide/Commands"> <Category _name = "Debug" id = "Debug"> <Command id = "MonoDevelop.Debugger.DebugCommands.DebugApplication" defaultHandler = "MonoDevelop.Debugger.DebugApplicationHandler" _label = "Debug Application..." /> <Command id = "MonoDevelop.Debugger.DebugCommands.AttachToProcess" defaultHandler = "MonoDevelop.Debugger.AttachToProcessHandler" _label = "Attach to Process..." /> <Command id = "MonoDevelop.Debugger.DebugCommands.Detach" defaultHandler = "MonoDevelop.Debugger.DetachFromProcessHandler" _label = "Detach" /> <Command id = "MonoDevelop.Debugger.DebugCommands.Pause" defaultHandler = "MonoDevelop.Debugger.PauseDebugHandler" shortcut = "Control|Break" _label = "Pause" _description = "Pause Execution" macShortcut = "Alt|Meta|P Alt+Meta+F15" icon="md-pause-debug"/> <Command id = "MonoDevelop.Debugger.DebugCommands.Continue" defaultHandler = "MonoDevelop.Debugger.ContinueDebugHandler" _label = "Continue" _description = "Continue Execution" icon="md-continue-debug"/> <Command id = "MonoDevelop.Debugger.DebugCommands.StepOver" defaultHandler = "MonoDevelop.Debugger.StepOverHandler" _label = "Step Over" _description = "Step Over" shortcut = "F10" macShortcut = "Shift|Meta|O F10" icon="md-step-over-debug"/> <Command id = "MonoDevelop.Debugger.DebugCommands.StepInto" defaultHandler = "MonoDevelop.Debugger.StepIntoHandler" _label = "Step Into" _description = "Step Into" shortcut = "F11" macShortcut = "Shift|Meta|I Meta+F11" icon="md-step-into-debug" /> <Command id = "MonoDevelop.Debugger.DebugCommands.StepOut" defaultHandler = "MonoDevelop.Debugger.StepOutHandler" _label = "Step Out" _description = "Step Out" shortcut = "Shift|F11" macShortcut = "Shift|Meta|U Shift+Meta+F11" icon="md-step-out-debug"/> <Command id = "MonoDevelop.Debugger.DebugCommands.NewBreakpoint" defaultHandler = "MonoDevelop.Debugger.NewBreakpointHandler" _label = "New Breakpoint…" icon = "md-breakpoint-new" /> <Command id = "MonoDevelop.Debugger.DebugCommands.NewFunctionBreakpoint" defaultHandler = "MonoDevelop.Debugger.NewFunctionBreakpointHandler" _label = "New Function Breakpoint" icon = "md-breakpoint-new" /> <Command id = "MonoDevelop.Debugger.DebugCommands.NewCatchpoint" defaultHandler = "MonoDevelop.Debugger.NewCatchpointHandler" _label = "New Exception Catchpoint" icon = "md-catchpoint-new" /> <Command id = "MonoDevelop.Debugger.DebugCommands.ShowBreakpoints" defaultHandler = "MonoDevelop.Debugger.ShowBreakpointsHandler" _label = "View Breakpoints" icon = "md-view-debug-breakpoints" macShortcut = "Alt+Meta+B" /> <Command id = "MonoDevelop.Debugger.DebugCommands.RemoveBreakpoint" defaultHandler = "MonoDevelop.Debugger.RemoveBreakpointHandler" _label = "Remove Breakpoint" /> <Command id = "MonoDevelop.Debugger.DebugCommands.ShowBreakpointProperties" defaultHandler = "MonoDevelop.Debugger.ShowBreakpointPropertiesHandler" _label = "Edit Breakpoint…" _displayName = "Edit Breakpoint Properties" /> <Command id = "MonoDevelop.Debugger.DebugCommands.ToggleBreakpoint" _label = "Toggle Breakpoint" icon = "md-breakpoint" defaultHandler = "MonoDevelop.Debugger.ToggleBreakpointHandler" shortcut = "F9" macShortcut = "Meta|\ F9" /> <Command id = "MonoDevelop.Debugger.DebugCommands.EnableDisableBreakpoint" _label = "Enable/Disable Breakpoint" _displayName = "Enable or Disable Breakpoint" defaultHandler = "MonoDevelop.Debugger.EnableDisableBreakpointHandler" icon = "md-breakpoint-on-off" shortcut = "Control|F9" macShortcut = "Alt|Meta|/ Meta+F9" /> <Command id = "MonoDevelop.Debugger.DebugCommands.DisableAllBreakpoints" _label = "Enable or Disable All Breakpoints" _displayName = "Enable or Disable All Breakpoints" icon = "md-breakpoint-disable-all" defaultHandler = "MonoDevelop.Debugger.DisableAllBreakpointsHandler" /> <Command id = "MonoDevelop.Debugger.DebugCommands.ClearAllBreakpoints" defaultHandler = "MonoDevelop.Debugger.ClearAllBreakpointsHandler" icon = "md-clear" _label = "Remove All Breakpoints" macShortcut = "Shift+Meta+F9" /> <Command id = "MonoDevelop.Debugger.DebugCommands.ShowDisassembly" _label = "Show Disassembly" defaultHandler = "MonoDevelop.Debugger.ShowDisassemblyHandler" /> <Command id = "MonoDevelop.Debugger.DebugCommands.ExpressionEvaluator" _label = "Expression Evaluator" shortcut = "Shift|F9" defaultHandler = "MonoDevelop.Debugger.ExpressionEvaluatorCommand" /> <Command id = "MonoDevelop.Debugger.DebugCommands.ShowCurrentExecutionLine" _label = "Show Current Execution Line" icon = "md-go-to-line" shortcut = "Alt|*" defaultHandler = "MonoDevelop.Debugger.ShowCurrentExecutionLineCommand" /> <Command id = "MonoDevelop.Debugger.DebugCommands.AddWatch" _description = "Add expression to watch pad" _label = "Add watch" /> <Command id = "MonoDevelop.Debugger.DebugCommands.StopEvaluation" _description = "Stops the execution of the expression being evaluated by the debugger" defaultHandler = "MonoDevelop.Debugger.StopEvaluationHandler" _label = "Stop Evaluation" /> <Command id = "MonoDevelop.Debugger.DebugCommands.RunToCursor" defaultHandler = "MonoDevelop.Debugger.RunToCursorHandler" _label = "Run To Cursor" _description = "Run To Cursor" shortcut = "Control|F10" macShortcut = "Meta+F10" /> <Command id = "MonoDevelop.Debugger.DebugCommands.SetNextStatement" defaultHandler = "MonoDevelop.Debugger.SetNextStatementHandler" _label = "Set Next Statement" _description = "Set Next Statement" shortcut = "Control|Shift|F10" macShortcut = "Shift+Meta+F10" /> <Command id = "MonoDevelop.Debugger.DebugCommands.ShowNextStatement" _label = "Show Next Statement" defaultHandler = "MonoDevelop.Debugger.ShowNextStatementHandler" macShortcut = "Alt+*" /> </Category> </Extension> <Extension path = "/MonoDevelop/Ide/MainMenu/Run"> <CommandItem id = "MonoDevelop.Debugger.DebugCommands.Debug" insertafter="MonoDevelop.Ide.Commands.ProjectCommands.Run"/> <CommandItem id = "MonoDevelop.Debugger.DebugCommands.Pause" insertafter="MonoDevelop.Ide.Commands.ProjectCommands.Stop"/> <CommandItem id = "MonoDevelop.Debugger.DebugCommands.StopEvaluation" /> <SeparatorItem id = "MonoDevelop.Debugger.ExternalDebuggingSection" /> <CommandItem id = "MonoDevelop.Debugger.DebugCommands.DebugApplication" /> <CommandItem id = "MonoDevelop.Debugger.DebugCommands.AttachToProcess" /> <CommandItem id = "MonoDevelop.Debugger.DebugCommands.Detach" /> <SeparatorItem id = "MonoDevelop.Debugger.SteppingSection" /> <CommandItem id = "MonoDevelop.Debugger.DebugCommands.StepOver" /> <CommandItem id = "MonoDevelop.Debugger.DebugCommands.StepInto" /> <CommandItem id = "MonoDevelop.Debugger.DebugCommands.StepOut" /> <CommandItem id = "MonoDevelop.Debugger.DebugCommands.ShowCurrentExecutionLine" /> <SeparatorItem id = "MonoDevelop.Debugger.BreakpointsSection" /> <CommandItem id = "MonoDevelop.Debugger.DebugCommands.NewBreakpoint" /> <CommandItem id = "MonoDevelop.Debugger.DebugCommands.NewFunctionBreakpoint" /> <CommandItem id = "MonoDevelop.Debugger.DebugCommands.NewCatchpoint" /> <CommandItem id = "MonoDevelop.Debugger.DebugCommands.ShowBreakpoints" /> <CommandItem id = "MonoDevelop.Debugger.DebugCommands.ToggleBreakpoint" /> <CommandItem id = "MonoDevelop.Debugger.DebugCommands.EnableDisableBreakpoint" /> <CommandItem id = "MonoDevelop.Debugger.DebugCommands.DisableAllBreakpoints" /> <CommandItem id = "MonoDevelop.Debugger.DebugCommands.ClearAllBreakpoints" /> <SeparatorItem id = "MonoDevelop.Debugger.ToolsSection" /> <CommandItem id = "MonoDevelop.Debugger.DebugCommands.ShowDisassembly"/> <CommandItem id = "MonoDevelop.Debugger.DebugCommands.ExpressionEvaluator" /> </Extension> <Extension path = "/MonoDevelop/Ide/ContextMenu/ProjectPad"> <Condition id="ItemType" value="IBuildTarget"> <CommandItem id = "MonoDevelop.Debugger.DebugCommands.DebugEntry" insertafter="MonoDevelop.Ide.Commands.ProjectCommands.RunEntry" /> </Condition> </Extension> <Extension path = "/MonoDevelop/TextEditor/ContextMenu/Editor"> <SeparatorItem id = "DebuggerSectionStart" insertafter="Separator1" /> <CommandItem id = "MonoDevelop.Debugger.DebugCommands.SetNextStatement" /> <CommandItem id = "MonoDevelop.Debugger.DebugCommands.ShowNextStatement" /> <CommandItem id = "MonoDevelop.Debugger.DebugCommands.RunToCursor" /> <CommandItem id = "MonoDevelop.Debugger.DebugCommands.ExpressionEvaluator" /> <SeparatorItem id = "DebuggerSectionEnd" /> </Extension> <Extension path = "/MonoDevelop/Core/ExecutionModes/Debug"> <ModeSetType id="MonoDevelop.Debugger" class="MonoDevelop.Debugger.DebugExecutionModeSet"/> </Extension> <Extension path = "/MonoDevelop/Core/StockIcons"> <StockIcon stockid = "md-exception-caught-template" resource = "exception-caught-template-16.png" size = "Menu"/> <StockIcon stockid = "md-continue-debug" resource = "continue-16.png" size = "Menu"/> <StockIcon stockid = "md-pause-debug" resource = "pause-16.png" size = "Menu"/> <StockIcon stockid = "md-step-into-debug" resource = "step-in-16.png" size = "Menu"/> <StockIcon stockid = "md-step-out-debug" resource = "step-out-16.png" size = "Menu"/> <StockIcon stockid = "md-step-over-debug" resource = "step-over-16.png" size = "Menu"/> <StockIcon stockid = "md-view-debug-breakpoints" resource = "pad-breakpoints-16.png" size="Menu" /> <StockIcon stockid = "md-view-debug-call-stack" resource = "pad-call-stack-16.png" size="Menu" /> <StockIcon stockid = "md-view-debug-locals" resource = "pad-locals-16.png" size="Menu" /> <StockIcon stockid = "md-view-debug-threads" resource = "pad-threads-16.png" size="Menu" /> <StockIcon stockid = "md-view-debug-watch" resource = "pad-watch-16.png" size="Menu" /> <StockIcon stockid = "md-view-debug-immediate" resource = "pad-immediate-16.png" size="Menu" /> <StockIcon stockid = "md-prefs-debugger" resource = "prefs-debugger-16.png" size="Menu" /> <StockIcon stockid = "md-stack-pointer" resource = "stack-pointer-16.png" size="Menu" /> <StockIcon stockid = "md-gutter-execution" resource = "gutter-execution-15.png" size="Menu" imageid="807" /> <StockIcon stockid = "md-gutter-stack" resource = "gutter-stack-15.png" size="Menu" imageid="386" /> <StockIcon stockid = "md-gutter-tracepoint" resource = "gutter-tracepoint-15.png" size="Menu" imageid="3175" /> <StockIcon stockid = "md-gutter-tracepoint-disabled" resource = "gutter-tracepoint-disabled-15.png" size="Menu" imageid="3174" /> <StockIcon stockid = "md-gutter-tracepoint-invalid" resource = "gutter-tracepoint-invalid-15.png" size="Menu" imageid="3178" /> </Extension> <Extension path = "/MonoDevelop/Ide/CommandBar"> <ItemSet id = "Debug" _label="Debugger"> <CommandItem id = "MonoDevelop.Debugger.DebugCommands.Continue" /> <CommandItem id = "MonoDevelop.Debugger.DebugCommands.Pause" /> <CommandItem id = "MonoDevelop.Debugger.DebugCommands.StepOver" /> <CommandItem id = "MonoDevelop.Debugger.DebugCommands.StepInto" /> <CommandItem id = "MonoDevelop.Debugger.DebugCommands.StepOut" /> </ItemSet> </Extension> <Extension path = "/MonoDevelop/Ide/GlobalOptionsDialog/Projects"> <Section id="Debugger" _label="Debugger" fill="true" class="MonoDevelop.Debugger.DebuggerOptionsPanel" icon="md-prefs-debugger" /> </Extension> <Extension path = "/MonoDevelop/Ide/TextEditorExtensions"> <Class class="MonoDevelop.Debugger.ExceptionCaughtTextEditorExtension" /> </Extension> <Extension path = "/MonoDevelop/ProjectModel/Gui/ItemOptionPanels/Common"> <Condition id="ItemType" value="Solution"> <Section id="DebugSourceFiles" _label="Debug Source Files" icon="md-prefs-debugger" fill="true" class="MonoDevelop.Debugger.DebugSourceFilesOptionsPanel" /> </Condition> </Extension> <Extension path="/MonoDevelop/Ide/Composition"> <Assembly file="MonoDevelop.Debugger.dll"/> </Extension> </ExtensionModel>
{ "pile_set_name": "Github" }
#!/usr/bin/env bash # Copyright 2006-2010 Amazon.com, Inc. or its affiliates. All Rights Reserved. Licensed under the # Amazon Software License (the "License"). You may not use this file except in compliance with the License. A copy of the # License is located at http://aws.amazon.com/asl or in the "license" file accompanying this file. This file 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. __ZIP_PREFIX__EC2_HOME="${EC2_HOME:?EC2_HOME is not set}" __RPM_PREFIX__EC2_HOME=/usr/local/aes/cmdline "${EC2_HOME}"/bin/ec2-cmd UploadDiskImage "$@"
{ "pile_set_name": "Github" }
<?xml version="1.0" encoding="utf-8"?> <Project DefaultTargets="Build" ToolsVersion="4.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003"> <ItemGroup Label="ProjectConfigurations"> <ProjectConfiguration Include="Debug|ARM"> <Configuration>Debug</Configuration> <Platform>ARM</Platform> </ProjectConfiguration> <ProjectConfiguration Include="Debug|Emscripten"> <Configuration>Debug</Configuration> <Platform>Emscripten</Platform> </ProjectConfiguration> <ProjectConfiguration Include="Debug|x64"> <Configuration>Debug</Configuration> <Platform>x64</Platform> </ProjectConfiguration> <ProjectConfiguration Include="Release Universal|ARM"> <Configuration>Release Universal</Configuration> <Platform>ARM</Platform> </ProjectConfiguration> <ProjectConfiguration Include="Release Universal|Emscripten"> <Configuration>Release Universal</Configuration> <Platform>Emscripten</Platform> </ProjectConfiguration> <ProjectConfiguration Include="Release Universal|Win32"> <Configuration>Release Universal</Configuration> <Platform>Win32</Platform> </ProjectConfiguration> <ProjectConfiguration Include="Release Universal|x64"> <Configuration>Release Universal</Configuration> <Platform>x64</Platform> </ProjectConfiguration> <ProjectConfiguration Include="Release|ARM"> <Configuration>Release</Configuration> <Platform>ARM</Platform> </ProjectConfiguration> <ProjectConfiguration Include="Release|Emscripten"> <Configuration>Release</Configuration> <Platform>Emscripten</Platform> </ProjectConfiguration> <ProjectConfiguration Include="Release|Win32"> <Configuration>Release</Configuration> <Platform>Win32</Platform> </ProjectConfiguration> <ProjectConfiguration Include="Debug|Win32"> <Configuration>Debug</Configuration> <Platform>Win32</Platform> </ProjectConfiguration> <ProjectConfiguration Include="Release|x64"> <Configuration>Release</Configuration> <Platform>x64</Platform> </ProjectConfiguration> </ItemGroup> <PropertyGroup Label="Globals"> <ProjectGuid>{A409AD9E-106B-8AAC-99D8-D05E0539C16B}</ProjectGuid> <Keyword>Win32Proj</Keyword> <RootNamespace>pybullet_testplugin</RootNamespace> <WindowsTargetPlatformVersion>10.0</WindowsTargetPlatformVersion> </PropertyGroup> <Import Project="$(VCTargetsPath)\Microsoft.Cpp.Default.props" /> <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'" Label="Configuration"> <ConfigurationType>DynamicLibrary</ConfigurationType> <UseDebugLibraries>false</UseDebugLibraries> <CharacterSet>Unicode</CharacterSet> <PlatformToolset>v142</PlatformToolset> </PropertyGroup> <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|ARM'" Label="Configuration"> <ConfigurationType>DynamicLibrary</ConfigurationType> <UseDebugLibraries>false</UseDebugLibraries> <CharacterSet>Unicode</CharacterSet> <PlatformToolset>v142</PlatformToolset> </PropertyGroup> <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|x64'" Label="Configuration"> <ConfigurationType>DynamicLibrary</ConfigurationType> <UseDebugLibraries>false</UseDebugLibraries> <CharacterSet>Unicode</CharacterSet> <PlatformToolset>v142</PlatformToolset> </PropertyGroup> <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|Emscripten'" Label="Configuration"> <ConfigurationType>DynamicLibrary</ConfigurationType> <UseDebugLibraries>false</UseDebugLibraries> <CharacterSet>Unicode</CharacterSet> <PlatformToolset>v142</PlatformToolset> </PropertyGroup> <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release Universal|Win32'" Label="Configuration"> <ConfigurationType>DynamicLibrary</ConfigurationType> <UseDebugLibraries>false</UseDebugLibraries> <CharacterSet>Unicode</CharacterSet> <PlatformToolset>v142</PlatformToolset> </PropertyGroup> <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release Universal|ARM'" Label="Configuration"> <ConfigurationType>DynamicLibrary</ConfigurationType> <UseDebugLibraries>false</UseDebugLibraries> <CharacterSet>Unicode</CharacterSet> <PlatformToolset>v142</PlatformToolset> </PropertyGroup> <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release Universal|x64'" Label="Configuration"> <ConfigurationType>DynamicLibrary</ConfigurationType> <UseDebugLibraries>false</UseDebugLibraries> <CharacterSet>Unicode</CharacterSet> <PlatformToolset>v142</PlatformToolset> </PropertyGroup> <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release Universal|Emscripten'" Label="Configuration"> <ConfigurationType>DynamicLibrary</ConfigurationType> <UseDebugLibraries>false</UseDebugLibraries> <CharacterSet>Unicode</CharacterSet> <PlatformToolset>v142</PlatformToolset> </PropertyGroup> <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'" Label="Configuration"> <ConfigurationType>DynamicLibrary</ConfigurationType> <UseDebugLibraries>true</UseDebugLibraries> <CharacterSet>Unicode</CharacterSet> <PlatformToolset>v142</PlatformToolset> </PropertyGroup> <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|ARM'" Label="Configuration"> <ConfigurationType>DynamicLibrary</ConfigurationType> <UseDebugLibraries>true</UseDebugLibraries> <CharacterSet>Unicode</CharacterSet> <PlatformToolset>v142</PlatformToolset> </PropertyGroup> <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|x64'" Label="Configuration"> <ConfigurationType>DynamicLibrary</ConfigurationType> <UseDebugLibraries>true</UseDebugLibraries> <CharacterSet>Unicode</CharacterSet> <PlatformToolset>v142</PlatformToolset> </PropertyGroup> <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Emscripten'" Label="Configuration"> <ConfigurationType>DynamicLibrary</ConfigurationType> <UseDebugLibraries>true</UseDebugLibraries> <CharacterSet>Unicode</CharacterSet> <PlatformToolset>v142</PlatformToolset> </PropertyGroup> <Import Project="$(VCTargetsPath)\Microsoft.Cpp.props" /> <ImportGroup Label="ExtensionSettings"> </ImportGroup> <ImportGroup Label="PropertySheets" Condition="'$(Configuration)|$(Platform)'=='Release|Win32'"> <Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" /> </ImportGroup> <ImportGroup Condition="'$(Configuration)|$(Platform)'=='Release|ARM'" Label="PropertySheets"> <Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" /> </ImportGroup> <ImportGroup Condition="'$(Configuration)|$(Platform)'=='Release|x64'" Label="PropertySheets"> <Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" /> </ImportGroup> <ImportGroup Condition="'$(Configuration)|$(Platform)'=='Release|Emscripten'" Label="PropertySheets"> <Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" /> </ImportGroup> <ImportGroup Condition="'$(Configuration)|$(Platform)'=='Release Universal|Win32'" Label="PropertySheets"> <Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" /> </ImportGroup> <ImportGroup Condition="'$(Configuration)|$(Platform)'=='Release Universal|ARM'" Label="PropertySheets"> <Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" /> </ImportGroup> <ImportGroup Condition="'$(Configuration)|$(Platform)'=='Release Universal|x64'" Label="PropertySheets"> <Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" /> </ImportGroup> <ImportGroup Condition="'$(Configuration)|$(Platform)'=='Release Universal|Emscripten'" Label="PropertySheets"> <Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" /> </ImportGroup> <ImportGroup Label="PropertySheets" Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'"> <Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" /> </ImportGroup> <ImportGroup Condition="'$(Configuration)|$(Platform)'=='Debug|ARM'" Label="PropertySheets"> <Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" /> </ImportGroup> <ImportGroup Condition="'$(Configuration)|$(Platform)'=='Debug|x64'" Label="PropertySheets"> <Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" /> </ImportGroup> <ImportGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Emscripten'" Label="PropertySheets"> <Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" /> </ImportGroup> <PropertyGroup Label="UserMacros" /> <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'"> <LinkIncremental>false</LinkIncremental> <OutDir>..\..\bin\</OutDir> <IntDir>obj\Release\pybullet_testplugin\</IntDir> <TargetName>pybullet_testplugin</TargetName> <TargetExt>.dll</TargetExt> </PropertyGroup> <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|ARM'"> <TargetName>pybullet_testplugin</TargetName> <TargetExt>.dll</TargetExt> <LinkIncremental>false</LinkIncremental> </PropertyGroup> <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|x64'"> <TargetName>pybullet_testplugin</TargetName> <TargetExt>.dll</TargetExt> <LinkIncremental>false</LinkIncremental> </PropertyGroup> <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|Emscripten'"> <TargetName>pybullet_testplugin</TargetName> <TargetExt>.dll</TargetExt> <LinkIncremental>false</LinkIncremental> </PropertyGroup> <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release Universal|Win32'"> <LinkIncremental>false</LinkIncremental> <OutDir>..\..\bin\</OutDir> <IntDir>obj\Release\pybullet_testplugin\</IntDir> <TargetName>pybullet_testplugin</TargetName> <TargetExt>.dll</TargetExt> </PropertyGroup> <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release Universal|ARM'"> <TargetName>pybullet_testplugin</TargetName> <TargetExt>.dll</TargetExt> <LinkIncremental>false</LinkIncremental> </PropertyGroup> <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release Universal|x64'"> <TargetName>pybullet_testplugin</TargetName> <TargetExt>.dll</TargetExt> <LinkIncremental>false</LinkIncremental> </PropertyGroup> <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release Universal|Emscripten'"> <TargetName>pybullet_testplugin</TargetName> <TargetExt>.dll</TargetExt> <LinkIncremental>false</LinkIncremental> </PropertyGroup> <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'"> <LinkIncremental>true</LinkIncremental> <OutDir>..\..\bin\</OutDir> <IntDir>obj\Debug\pybullet_testplugin\</IntDir> <TargetName>pybullet_testplugin</TargetName> <TargetExt>.dll</TargetExt> </PropertyGroup> <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|ARM'"> <TargetName>pybullet_testplugin</TargetName> <TargetExt>.dll</TargetExt> <LinkIncremental>true</LinkIncremental> </PropertyGroup> <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|x64'"> <TargetName>pybullet_testplugin</TargetName> <TargetExt>.dll</TargetExt> <LinkIncremental>true</LinkIncremental> </PropertyGroup> <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Emscripten'"> <TargetName>pybullet_testplugin</TargetName> <TargetExt>.dll</TargetExt> <LinkIncremental>true</LinkIncremental> </PropertyGroup> <ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'"> <ClCompile> <PrecompiledHeader>NotUsing</PrecompiledHeader> <WarningLevel>Level3</WarningLevel> <PreprocessorDefinitions>PHYSICS_IN_PROCESS_EXAMPLE_BROWSER;%(PreprocessorDefinitions)</PreprocessorDefinitions> <AdditionalIncludeDirectories>..\..\examples\SharedMemory\plugins\testPlugin;..\..\src;..\..\examples;..\..\examples\ThirdPartyLibs;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories> <Optimization>Full</Optimization> <FunctionLevelLinking>true</FunctionLevelLinking> <IntrinsicFunctions>true</IntrinsicFunctions> <MinimalRebuild>false</MinimalRebuild> <StringPooling>true</StringPooling> <RuntimeLibrary>MultiThreaded</RuntimeLibrary> <FloatingPointModel>Fast</FloatingPointModel> <EnableEnhancedInstructionSet>StreamingSIMDExtensions2</EnableEnhancedInstructionSet> <AdditionalOptions>/MP /wd4244 /wd4267 %(AdditionalOptions)</AdditionalOptions> </ClCompile> <Link> <SubSystem>Windows</SubSystem> <EnableCOMDATFolding>true</EnableCOMDATFolding> <OptimizeReferences>true</OptimizeReferences> <ImportLibrary>..\..\bin\pybullet_testplugin.lib</ImportLibrary> </Link> </ItemDefinitionGroup> <ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Release|ARM'"> <ClCompile> <PrecompiledHeader>NotUsing</PrecompiledHeader> <WarningLevel>Level3</WarningLevel> <PreprocessorDefinitions>PHYSICS_IN_PROCESS_EXAMPLE_BROWSER;%(PreprocessorDefinitions)</PreprocessorDefinitions> <AdditionalIncludeDirectories>..\..\examples\SharedMemory\plugins\testPlugin;..\..\src;..\..\examples;..\..\examples\ThirdPartyLibs;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories> <Optimization>Full</Optimization> <FunctionLevelLinking>true</FunctionLevelLinking> <IntrinsicFunctions>true</IntrinsicFunctions> <MinimalRebuild>false</MinimalRebuild> <StringPooling>true</StringPooling> <RuntimeLibrary>MultiThreaded</RuntimeLibrary> <FloatingPointModel>Fast</FloatingPointModel> <EnableEnhancedInstructionSet>StreamingSIMDExtensions2</EnableEnhancedInstructionSet> <AdditionalOptions>/MP /wd4244 /wd4267 %(AdditionalOptions)</AdditionalOptions> </ClCompile> <Link> <SubSystem>Windows</SubSystem> <EnableCOMDATFolding>true</EnableCOMDATFolding> <OptimizeReferences>true</OptimizeReferences> <ImportLibrary>..\..\bin\pybullet_testplugin.lib</ImportLibrary> </Link> </ItemDefinitionGroup> <ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Release|x64'"> <ClCompile> <PrecompiledHeader>NotUsing</PrecompiledHeader> <WarningLevel>Level3</WarningLevel> <PreprocessorDefinitions>PHYSICS_IN_PROCESS_EXAMPLE_BROWSER;%(PreprocessorDefinitions)</PreprocessorDefinitions> <AdditionalIncludeDirectories>..\..\examples\SharedMemory\plugins\testPlugin;..\..\src;..\..\examples;..\..\examples\ThirdPartyLibs;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories> <Optimization>Full</Optimization> <FunctionLevelLinking>true</FunctionLevelLinking> <IntrinsicFunctions>true</IntrinsicFunctions> <MinimalRebuild>false</MinimalRebuild> <StringPooling>true</StringPooling> <RuntimeLibrary>MultiThreaded</RuntimeLibrary> <FloatingPointModel>Fast</FloatingPointModel> <EnableEnhancedInstructionSet>StreamingSIMDExtensions2</EnableEnhancedInstructionSet> <AdditionalOptions>/MP /wd4244 /wd4267 %(AdditionalOptions)</AdditionalOptions> </ClCompile> <Link> <SubSystem>Windows</SubSystem> <EnableCOMDATFolding>true</EnableCOMDATFolding> <OptimizeReferences>true</OptimizeReferences> <ImportLibrary>..\..\bin\pybullet_testplugin.lib</ImportLibrary> </Link> </ItemDefinitionGroup> <ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Release|Emscripten'"> <ClCompile> <PrecompiledHeader>NotUsing</PrecompiledHeader> <WarningLevel>Level3</WarningLevel> <PreprocessorDefinitions>PHYSICS_IN_PROCESS_EXAMPLE_BROWSER;%(PreprocessorDefinitions)</PreprocessorDefinitions> <AdditionalIncludeDirectories>..\..\examples\SharedMemory\plugins\testPlugin;..\..\src;..\..\examples;..\..\examples\ThirdPartyLibs;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories> <Optimization>Full</Optimization> <FunctionLevelLinking>true</FunctionLevelLinking> <IntrinsicFunctions>true</IntrinsicFunctions> <MinimalRebuild>false</MinimalRebuild> <StringPooling>true</StringPooling> <RuntimeLibrary>MultiThreaded</RuntimeLibrary> <FloatingPointModel>Fast</FloatingPointModel> <EnableEnhancedInstructionSet>StreamingSIMDExtensions2</EnableEnhancedInstructionSet> <AdditionalOptions>/MP /wd4244 /wd4267 %(AdditionalOptions)</AdditionalOptions> </ClCompile> <Link> <SubSystem>Windows</SubSystem> <EnableCOMDATFolding>true</EnableCOMDATFolding> <OptimizeReferences>true</OptimizeReferences> <ImportLibrary>..\..\bin\pybullet_testplugin.lib</ImportLibrary> </Link> </ItemDefinitionGroup> <ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Release Universal|Win32'"> <ClCompile> <PrecompiledHeader>NotUsing</PrecompiledHeader> <WarningLevel>Level3</WarningLevel> <PreprocessorDefinitions>PHYSICS_IN_PROCESS_EXAMPLE_BROWSER;%(PreprocessorDefinitions)</PreprocessorDefinitions> <AdditionalIncludeDirectories>..\..\examples\SharedMemory\plugins\testPlugin;..\..\src;..\..\examples;..\..\examples\ThirdPartyLibs;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories> <Optimization>Full</Optimization> <FunctionLevelLinking>true</FunctionLevelLinking> <IntrinsicFunctions>true</IntrinsicFunctions> <MinimalRebuild>false</MinimalRebuild> <StringPooling>true</StringPooling> <RuntimeLibrary>MultiThreaded</RuntimeLibrary> <FloatingPointModel>Fast</FloatingPointModel> <EnableEnhancedInstructionSet>StreamingSIMDExtensions2</EnableEnhancedInstructionSet> <AdditionalOptions>/MP /wd4244 /wd4267 %(AdditionalOptions)</AdditionalOptions> </ClCompile> <Link> <SubSystem>Windows</SubSystem> <EnableCOMDATFolding>true</EnableCOMDATFolding> <OptimizeReferences>true</OptimizeReferences> <ImportLibrary>..\..\bin\pybullet_testplugin.lib</ImportLibrary> </Link> </ItemDefinitionGroup> <ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Release Universal|ARM'"> <ClCompile> <PrecompiledHeader>NotUsing</PrecompiledHeader> <WarningLevel>Level3</WarningLevel> <PreprocessorDefinitions>PHYSICS_IN_PROCESS_EXAMPLE_BROWSER;%(PreprocessorDefinitions)</PreprocessorDefinitions> <AdditionalIncludeDirectories>..\..\examples\SharedMemory\plugins\testPlugin;..\..\src;..\..\examples;..\..\examples\ThirdPartyLibs;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories> <Optimization>Full</Optimization> <FunctionLevelLinking>true</FunctionLevelLinking> <IntrinsicFunctions>true</IntrinsicFunctions> <MinimalRebuild>false</MinimalRebuild> <StringPooling>true</StringPooling> <RuntimeLibrary>MultiThreaded</RuntimeLibrary> <FloatingPointModel>Fast</FloatingPointModel> <EnableEnhancedInstructionSet>StreamingSIMDExtensions2</EnableEnhancedInstructionSet> <AdditionalOptions>/MP /wd4244 /wd4267 %(AdditionalOptions)</AdditionalOptions> </ClCompile> <Link> <SubSystem>Windows</SubSystem> <EnableCOMDATFolding>true</EnableCOMDATFolding> <OptimizeReferences>true</OptimizeReferences> <ImportLibrary>..\..\bin\pybullet_testplugin.lib</ImportLibrary> </Link> </ItemDefinitionGroup> <ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Release Universal|x64'"> <ClCompile> <PrecompiledHeader>NotUsing</PrecompiledHeader> <WarningLevel>Level3</WarningLevel> <PreprocessorDefinitions>PHYSICS_IN_PROCESS_EXAMPLE_BROWSER;%(PreprocessorDefinitions)</PreprocessorDefinitions> <AdditionalIncludeDirectories>..\..\examples\SharedMemory\plugins\testPlugin;..\..\src;..\..\examples;..\..\examples\ThirdPartyLibs;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories> <Optimization>Full</Optimization> <FunctionLevelLinking>true</FunctionLevelLinking> <IntrinsicFunctions>true</IntrinsicFunctions> <MinimalRebuild>false</MinimalRebuild> <StringPooling>true</StringPooling> <RuntimeLibrary>MultiThreaded</RuntimeLibrary> <FloatingPointModel>Fast</FloatingPointModel> <EnableEnhancedInstructionSet>StreamingSIMDExtensions2</EnableEnhancedInstructionSet> <AdditionalOptions>/MP /wd4244 /wd4267 %(AdditionalOptions)</AdditionalOptions> </ClCompile> <Link> <SubSystem>Windows</SubSystem> <EnableCOMDATFolding>true</EnableCOMDATFolding> <OptimizeReferences>true</OptimizeReferences> <ImportLibrary>..\..\bin\pybullet_testplugin.lib</ImportLibrary> </Link> </ItemDefinitionGroup> <ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Release Universal|Emscripten'"> <ClCompile> <PrecompiledHeader>NotUsing</PrecompiledHeader> <WarningLevel>Level3</WarningLevel> <PreprocessorDefinitions>PHYSICS_IN_PROCESS_EXAMPLE_BROWSER;%(PreprocessorDefinitions)</PreprocessorDefinitions> <AdditionalIncludeDirectories>..\..\examples\SharedMemory\plugins\testPlugin;..\..\src;..\..\examples;..\..\examples\ThirdPartyLibs;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories> <Optimization>Full</Optimization> <FunctionLevelLinking>true</FunctionLevelLinking> <IntrinsicFunctions>true</IntrinsicFunctions> <MinimalRebuild>false</MinimalRebuild> <StringPooling>true</StringPooling> <RuntimeLibrary>MultiThreaded</RuntimeLibrary> <FloatingPointModel>Fast</FloatingPointModel> <EnableEnhancedInstructionSet>StreamingSIMDExtensions2</EnableEnhancedInstructionSet> <AdditionalOptions>/MP /wd4244 /wd4267 %(AdditionalOptions)</AdditionalOptions> </ClCompile> <Link> <SubSystem>Windows</SubSystem> <EnableCOMDATFolding>true</EnableCOMDATFolding> <OptimizeReferences>true</OptimizeReferences> <ImportLibrary>..\..\bin\pybullet_testplugin.lib</ImportLibrary> </Link> </ItemDefinitionGroup> <ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'"> <ClCompile> <PrecompiledHeader>NotUsing</PrecompiledHeader> <WarningLevel>Level3</WarningLevel> <PreprocessorDefinitions>_DEBUG=1;PHYSICS_IN_PROCESS_EXAMPLE_BROWSER;%(PreprocessorDefinitions)</PreprocessorDefinitions> <AdditionalIncludeDirectories>..\..\examples\SharedMemory\plugins\testPlugin;..\..\src;..\..\examples;..\..\examples\ThirdPartyLibs;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories> <DebugInformationFormat>ProgramDatabase</DebugInformationFormat> <Optimization>Disabled</Optimization> <MinimalRebuild>false</MinimalRebuild> <RuntimeLibrary>MultiThreadedDebug</RuntimeLibrary> <FloatingPointModel>Fast</FloatingPointModel> <AdditionalOptions>/MP /wd4244 /wd4267 %(AdditionalOptions)</AdditionalOptions> </ClCompile> <Link> <SubSystem>Windows</SubSystem> <GenerateDebugInformation>true</GenerateDebugInformation> <ImportLibrary>..\..\bin\pybullet_testplugin.lib</ImportLibrary> </Link> </ItemDefinitionGroup> <ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Debug|ARM'"> <ClCompile> <PrecompiledHeader>NotUsing</PrecompiledHeader> <WarningLevel>Level3</WarningLevel> <PreprocessorDefinitions>_DEBUG=1;PHYSICS_IN_PROCESS_EXAMPLE_BROWSER;%(PreprocessorDefinitions)</PreprocessorDefinitions> <AdditionalIncludeDirectories>..\..\examples\SharedMemory\plugins\testPlugin;..\..\src;..\..\examples;..\..\examples\ThirdPartyLibs;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories> <DebugInformationFormat>ProgramDatabase</DebugInformationFormat> <Optimization>Disabled</Optimization> <MinimalRebuild>false</MinimalRebuild> <RuntimeLibrary>MultiThreadedDebug</RuntimeLibrary> <FloatingPointModel>Fast</FloatingPointModel> <AdditionalOptions>/MP /wd4244 /wd4267 %(AdditionalOptions)</AdditionalOptions> </ClCompile> <Link> <SubSystem>Windows</SubSystem> <GenerateDebugInformation>true</GenerateDebugInformation> <ImportLibrary>..\..\bin\pybullet_testplugin.lib</ImportLibrary> </Link> </ItemDefinitionGroup> <ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Debug|x64'"> <ClCompile> <PrecompiledHeader>NotUsing</PrecompiledHeader> <WarningLevel>Level3</WarningLevel> <PreprocessorDefinitions>_DEBUG=1;PHYSICS_IN_PROCESS_EXAMPLE_BROWSER;%(PreprocessorDefinitions)</PreprocessorDefinitions> <AdditionalIncludeDirectories>..\..\examples\SharedMemory\plugins\testPlugin;..\..\src;..\..\examples;..\..\examples\ThirdPartyLibs;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories> <DebugInformationFormat>ProgramDatabase</DebugInformationFormat> <Optimization>Disabled</Optimization> <MinimalRebuild>false</MinimalRebuild> <RuntimeLibrary>MultiThreadedDebug</RuntimeLibrary> <FloatingPointModel>Fast</FloatingPointModel> <AdditionalOptions>/MP /wd4244 /wd4267 %(AdditionalOptions)</AdditionalOptions> </ClCompile> <Link> <SubSystem>Windows</SubSystem> <GenerateDebugInformation>true</GenerateDebugInformation> <ImportLibrary>..\..\bin\pybullet_testplugin.lib</ImportLibrary> </Link> </ItemDefinitionGroup> <ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Emscripten'"> <ClCompile> <PrecompiledHeader>NotUsing</PrecompiledHeader> <WarningLevel>Level3</WarningLevel> <PreprocessorDefinitions>_DEBUG=1;PHYSICS_IN_PROCESS_EXAMPLE_BROWSER;%(PreprocessorDefinitions)</PreprocessorDefinitions> <AdditionalIncludeDirectories>..\..\examples\SharedMemory\plugins\testPlugin;..\..\src;..\..\examples;..\..\examples\ThirdPartyLibs;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories> <DebugInformationFormat>ProgramDatabase</DebugInformationFormat> <Optimization>Disabled</Optimization> <MinimalRebuild>false</MinimalRebuild> <RuntimeLibrary>MultiThreadedDebug</RuntimeLibrary> <FloatingPointModel>Fast</FloatingPointModel> <AdditionalOptions>/MP /wd4244 /wd4267 %(AdditionalOptions)</AdditionalOptions> </ClCompile> <Link> <SubSystem>Windows</SubSystem> <GenerateDebugInformation>true</GenerateDebugInformation> <ImportLibrary>..\..\bin\pybullet_testplugin.lib</ImportLibrary> </Link> </ItemDefinitionGroup> <ItemGroup> <ClInclude Include="..\..\examples\SharedMemory\PhysicsClient.h" /> <ClInclude Include="..\..\examples\SharedMemory\PhysicsClientC_API.h" /> <ClInclude Include="..\..\examples\SharedMemory\PhysicsClientSharedMemory.h" /> <ClInclude Include="..\..\examples\SharedMemory\PhysicsClientSharedMemory_C_API.h" /> <ClInclude Include="..\..\examples\SharedMemory\PosixSharedMemory.h" /> <ClInclude Include="..\..\examples\SharedMemory\Win32SharedMemory.h" /> <ClInclude Include="..\..\examples\Utils\b3Clock.h" /> <ClInclude Include="..\..\examples\Utils\b3ResourcePath.h" /> </ItemGroup> <ItemGroup> <ClCompile Include="..\..\examples\SharedMemory\PhysicsClient.cpp" /> <ClCompile Include="..\..\examples\SharedMemory\PhysicsClientC_API.cpp" /> <ClCompile Include="..\..\examples\SharedMemory\PhysicsClientSharedMemory.cpp" /> <ClCompile Include="..\..\examples\SharedMemory\PhysicsClientSharedMemory_C_API.cpp" /> <ClCompile Include="..\..\examples\SharedMemory\PosixSharedMemory.cpp" /> <ClCompile Include="..\..\examples\SharedMemory\Win32SharedMemory.cpp" /> <ClCompile Include="..\..\examples\SharedMemory\plugins\testPlugin\testplugin.cpp" /> <ClCompile Include="..\..\examples\Utils\b3Clock.cpp" /> <ClCompile Include="..\..\examples\Utils\b3ResourcePath.cpp" /> </ItemGroup> <ItemGroup> <ProjectReference Include="BulletFileLoader.vcxproj"> <Project>{241E2062-1017-3FB4-3949-243925A11EC0}</Project> </ProjectReference> <ProjectReference Include="Bullet3Common.vcxproj"> <Project>{A9326E37-15F3-E96D-DE2D-33EB4AAD2E4A}</Project> </ProjectReference> <ProjectReference Include="LinearMath.vcxproj"> <Project>{EAF25DFD-D6AA-9F4A-3FB2-78A62B893A3B}</Project> </ProjectReference> </ItemGroup> <Import Project="$(VCTargetsPath)\Microsoft.Cpp.targets" /> <ImportGroup Label="ExtensionTargets"> </ImportGroup> </Project>
{ "pile_set_name": "Github" }
// SPDX-License-Identifier: GPL-2.0-or-later /** * @file SaveClosingDlg.cpp * * @brief Implementation file for SaveClosingDlg dialog */ #include "stdafx.h" #include "SaveClosingDlg.h" #ifdef _DEBUG #define new DEBUG_NEW #endif ///////////////////////////////////////////////////////////////////////////// // SaveClosingDlg dialog IMPLEMENT_DYNAMIC(SaveClosingDlg, CTrDialog) /** * @brief Constructor. * @param [in] pParent Dialog's parent window. */ SaveClosingDlg::SaveClosingDlg(CWnd* pParent /*= nullptr*/) : CTrDialog(SaveClosingDlg::IDD, pParent) , m_leftSave(SAVECLOSING_SAVE) , m_middleSave(SAVECLOSING_SAVE) , m_rightSave(SAVECLOSING_SAVE) , m_bAskForLeft(false) , m_bAskForMiddle(false) , m_bAskForRight(false) , m_bDisableCancel(false) { } void SaveClosingDlg::DoDataExchange(CDataExchange* pDX) { CTrDialog::DoDataExchange(pDX); //{{AFX_DATA_MAP(SaveClosingDlg) DDX_Text(pDX, IDC_SAVECLOSING_LEFTFILE, m_sLeftFile); DDX_Text(pDX, IDC_SAVECLOSING_MIDDLEFILE, m_sMiddleFile); DDX_Text(pDX, IDC_SAVECLOSING_RIGHTFILE, m_sRightFile); DDX_Radio(pDX, IDC_SAVECLOSING_SAVELEFT, m_leftSave); DDX_Radio(pDX, IDC_SAVECLOSING_SAVEMIDDLE, m_middleSave); DDX_Radio(pDX, IDC_SAVECLOSING_SAVERIGHT, m_rightSave); //}}AFX_DATA_MAP } BEGIN_MESSAGE_MAP(SaveClosingDlg, CTrDialog) //{{AFX_MSG_MAP(SaveClosingDlg) ON_BN_CLICKED(IDC_SAVECLOSING_DISCARDALL, OnDiscardAll) //}}AFX_MSG_MAP END_MESSAGE_MAP() ///////////////////////////////////////////////////////////////////////////// // SaveClosingDlg message handlers /** * @brief Initialize dialog. * @return Always FALSE. */ BOOL SaveClosingDlg::OnInitDialog() { CTrDialog::OnInitDialog(); SetDlgItemFocus(IDC_SAVECLOSING_SAVELEFT); if (!m_bAskForLeft) { // Left items disabled move focus to middle side items SetDlgItemFocus(IDC_SAVECLOSING_SAVEMIDDLE); EnableDlgItem(IDC_SAVECLOSING_LEFTFRAME, false); EnableDlgItem(IDC_SAVECLOSING_LEFTFILE, false); EnableDlgItem(IDC_SAVECLOSING_SAVELEFT, false); EnableDlgItem(IDC_SAVECLOSING_DISCARDLEFT, false); } if (!m_bAskForMiddle) { // Middle items disabled move focus to right side items if (!m_bAskForLeft) SetDlgItemFocus(IDC_SAVECLOSING_SAVERIGHT); EnableDlgItem(IDC_SAVECLOSING_MIDDLEFRAME, false); EnableDlgItem(IDC_SAVECLOSING_MIDDLEFILE, false); EnableDlgItem(IDC_SAVECLOSING_SAVEMIDDLE, false); EnableDlgItem(IDC_SAVECLOSING_DISCARDMIDDLE, false); } if (!m_bAskForRight) { EnableDlgItem(IDC_SAVECLOSING_RIGHTFRAME, false); EnableDlgItem(IDC_SAVECLOSING_RIGHTFILE, false); EnableDlgItem(IDC_SAVECLOSING_SAVERIGHT, false); EnableDlgItem(IDC_SAVECLOSING_DISCARDRIGHT, false); } if (m_bDisableCancel) { EnableDlgItem(IDCANCEL, false); } // setup handler for resizing this dialog m_constraint.InitializeCurrentSize(this); m_constraint.DisallowHeightGrowth(); m_constraint.SubclassWnd(); // install subclassing m_constraint.LoadPosition(_T("ResizeableDialogs"), _T("SaveClosingDlg"), false); // persist size via registry return FALSE; // return TRUE unless you set the focus to a control // EXCEPTION: OCX Property Pages should return FALSE } /** * @brief Select files to ask about saving. * @param [in] bLeft Do we ask about left-side file? * @param [in] bRight Do we ask about right-side file? */ void SaveClosingDlg::DoAskFor(bool bLeft /*= false*/, bool bMiddle /*= false*/, bool bRight /*= false*/) { m_bAskForLeft = bLeft; m_bAskForMiddle = bMiddle; m_bAskForRight = bRight; } /** * @brief Called when 'Discard All' button is selected. */ void SaveClosingDlg::OnDiscardAll() { m_leftSave = SAVECLOSING_DISCARD; m_middleSave = SAVECLOSING_DISCARD; m_rightSave = SAVECLOSING_DISCARD; UpdateData(FALSE); OnOK(); }
{ "pile_set_name": "Github" }
10 dir 92215 http://hutao1@192.168.64.5:8888/svn/Mobile/iOS/branches/GroupChat/gjgc_branch_6.0/Components/IM/GJCoreUserInterface/GJCoreUserInterface/GJCUCapture/GJCUCaptureResourceBundle.bundle http://hutao1@192.168.64.5:8888/svn/Mobile 2015-06-02T11:17:41.989685Z 90247 liyi1 c1b34985-89f7-4ad2-b6ed-32456ccb691a 拍照-icon@2x.png file 2015-06-17T10:03:33.000000Z 137967e34788af8a4ab561f673e3de44 2015-06-02T11:17:41.989685Z 90247 liyi1 has-props 5306 相机-icon-@2x.png file 2015-06-17T10:03:33.000000Z 1adebfad5de07b62ff6d349437d1e106 2015-06-02T11:17:41.989685Z 90247 liyi1 has-props 1896 闪关灯-icon-点击@2x.png file 2015-06-17T10:03:33.000000Z 7bccb813d4f48fce6083cbe25f2b1c59 2015-06-02T11:17:41.989685Z 90247 liyi1 has-props 1514 拍照-icon-点击@2x.png file 2015-06-17T10:03:33.000000Z ac79eab4431f4abd45a188d3ca89b1cc 2015-06-02T11:17:41.989685Z 90247 liyi1 has-props 5509 闪关灯-icon-@2x.png file 2015-06-17T10:03:33.000000Z 27317618587a6752fcb1b039f5ef5441 2015-06-02T11:17:41.989685Z 90247 liyi1 has-props 1477
{ "pile_set_name": "Github" }
import os import sys import torch # Make the helper files in test/ importable pytorch_test_dir = os.path.dirname(os.path.dirname(os.path.realpath(__file__))) sys.path.append(pytorch_test_dir) from torch.testing._internal.jit_utils import JitTestCase, warmup_backward, FileCheck if __name__ == '__main__': raise RuntimeError("This test file is not meant to be run directly, use:\n\n" "\tpython test/test_jit.py TESTNAME\n\n" "instead.") class TestProfiler(JitTestCase): def setUp(self): self.prev_exec = torch._C._jit_set_profiling_executor(True) self.prev_profiling = torch._C._jit_set_profiling_mode(True) self.inline_autodiff = torch._C._debug_set_autodiff_subgraph_inlining(False) self.texpr_fuser_state = torch._C._jit_texpr_fuser_enabled() self.can_fuse_on_cpu = torch._C._jit_can_fuse_on_cpu() torch._C._jit_set_texpr_fuser_enabled(True) torch._C._jit_override_can_fuse_on_cpu(True) self.default_dtype = torch.get_default_dtype() self.old_reduction_enabled = torch._C._jit_set_texpr_reductions_enabled(True) torch.set_default_dtype(torch.double) def tearDown(self): torch._C._jit_set_profiling_executor(self.prev_exec) torch._C._jit_set_profiling_mode(self.prev_profiling) torch._C._debug_set_autodiff_subgraph_inlining(self.inline_autodiff) torch._C._jit_set_texpr_fuser_enabled(self.texpr_fuser_state) torch._C._jit_override_can_fuse_on_cpu(self.can_fuse_on_cpu) torch.set_default_dtype(self.default_dtype) torch._C._jit_set_texpr_reductions_enabled(self.old_reduction_enabled) def test_tensor_type_not_determined_by_inputs(self): @torch.jit.script def scalar_type_input(x, y, z): return x + y + 4 + z.item() x = torch.tensor([2, 2]) scalar_type_input(x, x, torch.tensor(1)) scalar_type_input(x, x, torch.tensor(1)) scalar_type_input(x, x, torch.tensor(1.0)) g = torch.jit.last_executed_optimized_graph() # item & add should not get pulled into the fusion group - # we expect to see Fusion Group (item / add) Fusion Group in ir dump FileCheck().check("TensorExpr").check("Scalar = aten::item").check_next("Tensor = aten::add").check("TensorExpr").run(g) @torch.jit.script def non_const_dtype(x, y, cond: bool): dtype = torch.int16 if cond else torch.int32 return (x + y + 3).sum(dtype=dtype) non_const_dtype(x, x, True) non_const_dtype(x, x, True) g = torch.jit.last_executed_optimized_graph() # because dtype is non-const, sum should not get pulled into the Fusion Group FileCheck().check("TensorExpr").check("TensorExpr").check_not("aten::sum").run(g) def test_specialize_backward(self): def test_fuse(a, b): c = a * b d = c * b return d test_fuse.__disable_jit_function_caching__ = True scripted_f = torch.jit.script(test_fuse) x = torch.ones(1, requires_grad=True) y = torch.ones(1, requires_grad=True) scripted_f(x, y) b = scripted_f(x, y) warmup_backward(b) g = torch.jit.last_executed_optimized_graph() # Backward has an if node guarding specializations, # within the if node true block there is only one if node # that guards a tensorexpr group optimized_block = next(g.findNode("prim::If").blocks()) if_nodes = list(optimized_block.findAllNodes("prim::If")) self.assertEqual(len(if_nodes), 1) FileCheck().check("Group[Subgraph").run(str(if_nodes[0])) # no broadcasts occurred, sum_to_size have been specialized out self.assertIsNone(optimized_block.findNode("aten::_grad_sum_to_size")) broadcast_f = torch.jit.script(test_fuse) x = torch.ones([2, 2], requires_grad=True) y = torch.ones([1], requires_grad=True) broadcast_f(x, y) b = broadcast_f(x, y) b.backward(torch.ones([2, 2], dtype=torch.float), retain_graph=True) b.backward(torch.ones([2, 2], dtype=torch.float)) # warmup_backward(b, torch.ones([2, 2], dtype=torch.float)) g = torch.jit.last_executed_optimized_graph() optimized_block = next(g.findNode("prim::If").blocks()) # broadcasts occurred, currently expect to see aten::_grad_sum_to_size self.assertIsNotNone(optimized_block.findNode("aten::_grad_sum_to_size")) def test_specialized_types(self): @torch.jit.script def test_fuse(a, b): c = a * b d = c * b return d x = torch.tensor([.5]) for _ in range(3): test_fuse(x, x) g = torch.jit.last_executed_optimized_graph() # Types should remain specialized for typecheck outputs & fusion outputs FileCheck().check("Double(").check_same("prim::TypeCheck").check("Double").check_same("TensorExpr").run(g) # other outputs should not be specialized FileCheck().check("Tensor = prim::If").run(g) def test_aliasing_merge(self): @torch.jit.script def foo(a, b): c = a * b d = c * b d.add_(b) e = d * b return d + e x = torch.ones(1) y = torch.ones(1) foo(x, y) b = foo(x, y) g = torch.jit.last_executed_optimized_graph() self.assertEqual(len(list(g.findAllNodes("prim::TypeCheck"))), 2) FileCheck().check("TensorExpr").check("aten::add_").check("TensorExpr").run(g) def test_not_fusing_scalar_ops(self): @torch.jit.script def foo(x: int, y: int): return x + y + 2 + 4 + 5 + 6 foo(1, 2) foo(2, 3) g = torch.jit.last_executed_optimized_graph() FileCheck().check_not("TensorExpr").run(g) def test_not_optimizing_property(self): @torch.jit.script def foo(x, y): return x + y + 1 + 2 + 3, x.size() x = torch.ones(1) foo(x, x) foo(x, x) g = torch.jit.last_executed_optimized_graph() FileCheck().check("aten::size").run(g) x = torch.ones([2, 3, 5]) self.assertEqual(foo(x, x), (x + x + 1 + 2 + 3, x.size())) def test_fallback_graph_not_specialized(self): @torch.jit.script def foo(a, b): c = a * b d = c * b e = d * b return d + e x = torch.ones(1) y = torch.ones(1) foo(x, y) foo(x, y) g = torch.jit.last_executed_optimized_graph() FileCheck().check("CallFunction").check_next("Tensor = prim::TupleUnpack").run(g) def test_autograd_fallback_graph(self): @torch.jit.script def foo(a, b): c = a * b d = c * b e = d * b return d + e x = torch.ones(1, requires_grad=True) y = torch.ones(1, requires_grad=True) foo(x, y) b = foo(x, y) b.backward(torch.ones([1], dtype=torch.float), retain_graph=True) b.backward(torch.ones([1], dtype=torch.float)) g = torch.jit.last_executed_optimized_graph() FileCheck().check("fallback_function").check_next("CallFunction").run(g) def test_iterative_fusion(self): @torch.jit.script def foo(a, b, c, d): a = a + b b.add_(3) c = c + b + d a = a + 1 return a, c x = torch.ones(1, requires_grad=False) foo(x, x, x, x) foo(x, x, x, x) # when we iterate through the block, we will start # by fusing a = a + b with a = a + 1 # if we were to continue iteration from that fusion point, # would miss the fusion opportunity of c = c + d + b g = torch.jit.last_executed_optimized_graph() self.assertEqual(len(list(g.findAllNodes("prim::TensorExprGroup"))), 2)
{ "pile_set_name": "Github" }
Cisco Systems Inc. is set to announce the acquisition of Telesend Inc., a developer of low-cost, high-speed Internet access technology, sources familiar with the deal said Tuesday. Cisco agreed to acquire Telesend, a privately-held Cupertino, Calif.-based firm, in exchange for an unspecified amount of stock in Cisco, the sources said. Additional financial terms were not available. Telesend is the developer of a new telecommunications technology known as ISDN DSL, or IDSL for short. The full name is Integrated Services Digital Network Digital Subscriber Line. A Cisco spokesman had no comment on the acquisition other than to say, "Most of our acquisitions are of small, privately-held firms." The spokesman, Adam Stein, said Cisco has made 14 mainly technology-oriented acquisitions in the last three-and-a-half years. Officials of Telesend were not available to comment, but an automated voicemail system answering calls at Telesend's offices in Cupertino transferred callers directly to a Cisco switchboard operator. Cisco is headquartered in nearby San Jose. Telesend's IDSL is a local-loop modem technology that allows phone companies to offer Internet access connections from central office switches to local customers at speeds of up to 128,000 bits per second, or about four times the speed of standard phone lines. Kieran Taylor, an analyst at market research firm TeleChoice Inc., said buying Telesend is a strategic move by Cisco to counter IDSL products announced a month and a half ago by rival equipment maker Ascend Communications Inc.
{ "pile_set_name": "Github" }
<!doctype html> <html> <head> <meta charset="utf-8"> <title>epp</title> </head> <body> <div id="main"></div> <script src="http://localhost:8000/out/app.js"></script> </body> </html>
{ "pile_set_name": "Github" }
<?php /* Copyright (C) 2005 Rodolphe Quiedeville <rodolphe@quiedeville.org> * Copyright (C) 2004-2019 Laurent Destailleur <eldy@users.sourceforge.net> * Copyright (C) 2005-2017 Regis Houssin <regis.houssin@inodbox.com> * * 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 3 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 <https://www.gnu.org/licenses/>. */ /** * \file htdocs/projet/tasks.php * \ingroup project * \brief List all tasks of a project */ require "../main.inc.php"; require_once DOL_DOCUMENT_ROOT.'/projet/class/project.class.php'; require_once DOL_DOCUMENT_ROOT.'/projet/class/task.class.php'; require_once DOL_DOCUMENT_ROOT.'/core/lib/project.lib.php'; require_once DOL_DOCUMENT_ROOT.'/core/lib/date.lib.php'; require_once DOL_DOCUMENT_ROOT.'/core/class/html.formother.class.php'; require_once DOL_DOCUMENT_ROOT.'/core/class/extrafields.class.php'; require_once DOL_DOCUMENT_ROOT.'/contact/class/contact.class.php'; if ($conf->categorie->enabled) { require_once DOL_DOCUMENT_ROOT.'/categories/class/categorie.class.php'; } // Load translation files required by the page $langs->loadLangs(array('projects', 'users', 'companies')); $action = GETPOST('action', 'aZ09'); $massaction = GETPOST('massaction', 'alpha'); $show_files = GETPOST('show_files', 'int'); $confirm = GETPOST('confirm', 'alpha'); $toselect = GETPOST('toselect', 'array'); $id = GETPOST('id', 'int'); $ref = GETPOST('ref', 'alpha'); $taskref = GETPOST('taskref', 'alpha'); $backtopage = GETPOST('backtopage', 'alpha'); $cancel = GETPOST('cancel', 'alpha'); $search_user_id = GETPOST('search_user_id', 'int'); $search_taskref = GETPOST('search_taskref'); $search_tasklabel = GETPOST('search_tasklabel'); $search_taskdescription = GETPOST('search_taskdescription'); $search_dtstartday = GETPOST('search_dtstartday'); $search_dtstartmonth = GETPOST('search_dtstartmonth'); $search_dtstartyear = GETPOST('search_dtstartyear'); $search_dtendday = GETPOST('search_dtendday'); $search_dtendmonth = GETPOST('search_dtendmonth'); $search_dtendyear = GETPOST('search_dtendyear'); $search_planedworkload = GETPOST('search_planedworkload'); $search_timespend = GETPOST('search_timespend'); $search_progresscalc = GETPOST('search_progresscalc'); $search_progressdeclare = GETPOST('search_progressdeclare'); $contextpage = GETPOST('contextpage', 'aZ') ?GETPOST('contextpage', 'aZ') : 'projecttasklist'; //if (! $user->rights->projet->all->lire) $mine=1; // Special for projects $object = new Project($db); $taskstatic = new Task($db); $extrafields = new ExtraFields($db); include DOL_DOCUMENT_ROOT.'/core/actions_fetchobject.inc.php'; // Must be include, not include_once if (!empty($conf->global->PROJECT_ALLOW_COMMENT_ON_PROJECT) && method_exists($object, 'fetchComments') && empty($object->comments)) $object->fetchComments(); if ($id > 0 || !empty($ref)) { // fetch optionals attributes and labels $extrafields->fetch_name_optionals_label($object->table_element); } $extrafields->fetch_name_optionals_label($taskstatic->table_element); $search_array_options = $extrafields->getOptionalsFromPost($taskstatic->table_element, '', 'search_'); // Security check $socid = 0; //if ($user->socid > 0) $socid = $user->socid; // For external user, no check is done on company because readability is managed by public status of project and assignement. $result = restrictedArea($user, 'projet', $id, 'projet&project'); $diroutputmassaction = $conf->projet->dir_output.'/tasks/temp/massgeneration/'.$user->id; // Initialize technical object to manage hooks of page. Note that conf->hooks_modules contains array of hook context $hookmanager->initHooks(array('projecttaskscard', 'globalcard')); $progress = GETPOST('progress', 'int'); $label = GETPOST('label', 'alpha'); $description = GETPOST('description', 'restricthtml'); $planned_workloadhour = (GETPOST('planned_workloadhour', 'int') ?GETPOST('planned_workloadhour', 'int') : 0); $planned_workloadmin = (GETPOST('planned_workloadmin', 'int') ?GETPOST('planned_workloadmin', 'int') : 0); $planned_workload = $planned_workloadhour * 3600 + $planned_workloadmin * 60; // Definition of fields for list $arrayfields = array( 't.ref'=>array('label'=>$langs->trans("RefTask"), 'checked'=>1, 'position'=>1), 't.label'=>array('label'=>$langs->trans("LabelTask"), 'checked'=>1, 'position'=>2), 't.description'=>array('label'=>$langs->trans("Description"), 'checked'=>0, 'position'=>3), 't.dateo'=>array('label'=>$langs->trans("DateStart"), 'checked'=>1, 'position'=>4), 't.datee'=>array('label'=>$langs->trans("DateEnd"), 'checked'=>1, 'position'=>5), 't.planned_workload'=>array('label'=>$langs->trans("PlannedWorkload"), 'checked'=>1, 'position'=>6), 't.duration_effective'=>array('label'=>$langs->trans("TimeSpent"), 'checked'=>1, 'position'=>7), 't.progress_calculated'=>array('label'=>$langs->trans("ProgressCalculated"), 'checked'=>1, 'position'=>8), 't.progress'=>array('label'=>$langs->trans("ProgressDeclared"), 'checked'=>1, 'position'=>9), 't.progress_summary'=>array('label'=>$langs->trans("TaskProgressSummary"), 'checked'=>1, 'position'=>10), ); if ($object->usage_bill_time) { $arrayfields['t.tobill'] = array('label'=>$langs->trans("TimeToBill"), 'checked'=>0, 'position'=>11); $arrayfields['t.billed'] = array('label'=>$langs->trans("TimeBilled"), 'checked'=>0, 'position'=>12); } // Extra fields if (is_array($extrafields->attributes[$taskstatic->table_element]['label']) && count($extrafields->attributes[$taskstatic->table_element]['label']) > 0) { foreach ($extrafields->attributes[$taskstatic->table_element]['label'] as $key => $val) { if (!empty($extrafields->attributes[$taskstatic->table_element]['list'][$key])) $arrayfields["ef.".$key] = array('label'=>$extrafields->attributes[$taskstatic->table_element]['label'][$key], 'checked'=>(($extrafields->attributes[$taskstatic->table_element]['list'][$key] < 0) ? 0 : 1), 'position'=>$extrafields->attributes[$taskstatic->table_element]['pos'][$key], 'enabled'=>(abs($extrafields->attributes[$taskstatic->table_element]['list'][$key]) != 3 && $extrafields->attributes[$taskstatic->table_element]['perms'][$key])); } } $arrayfields = dol_sort_array($arrayfields, 'position'); $varpage = empty($contextpage) ? $_SERVER["PHP_SELF"] : $contextpage; /* * Actions */ $parameters = array('id'=>$id); $reshook = $hookmanager->executeHooks('doActions', $parameters, $object, $action); // Note that $action and $object may have been modified by some hooks if ($reshook < 0) setEventMessages($hookmanager->error, $hookmanager->errors, 'errors'); if (empty($reshook)) { // Selection of new fields include DOL_DOCUMENT_ROOT.'/core/actions_changeselectedfields.inc.php'; // Purge search criteria if (GETPOST('button_removefilter_x', 'alpha') || GETPOST('button_removefilter.x', 'alpha') || GETPOST('button_removefilter', 'alpha')) // All tests are required to be compatible with all browsers { $search_user_id = ""; $search_taskref = ''; $search_tasklabel = ''; $search_dtstartday = ''; $search_dtstartmonth = ''; $search_dtstartyear = ''; $search_dtendday = ''; $search_dtendmonth = ''; $search_dtendyear = ''; $search_planedworkload = ''; $search_timespend = ''; $search_progresscalc = ''; $search_progressdeclare = ''; $toselect = ''; $search_array_options = array(); } // Mass actions $objectclass = 'Task'; $objectlabel = 'Tasks'; $permissiontoread = $user->rights->projet->lire; $permissiontodelete = $user->rights->projet->supprimer; $uploaddir = $conf->projet->dir_output.'/tasks'; include DOL_DOCUMENT_ROOT.'/core/actions_massactions.inc.php'; } $morewherefilterarray = array(); if (!empty($search_taskref)) { $morewherefilterarray[] = natural_search('t.ref', $search_taskref, 0, 1); } if (!empty($search_tasklabel)) { $morewherefilterarray[] = natural_search('t.label', $search_tasklabel, 0, 1); } $moresql = dolSqlDateFilter('t.dateo', $search_dtstartday, $search_dtstartmonth, $search_dtstartyear, 1); if ($moresql) $morewherefilterarray[] = $moresql; $moresql = dolSqlDateFilter('t.datee', $search_dtendday, $search_dtendmonth, $search_dtendyear, 1); if ($moresql) $morewherefilterarray[] = $moresql; if (!empty($search_planedworkload)) { $morewherefilterarray[] = natural_search('t.planned_workload', $search_planedworkload, 1, 1); } if (!empty($search_timespend)) { $morewherefilterarray[] = natural_search('t.duration_effective', $search_timespend, 1, 1); } if (!empty($search_progresscalc)) { $filterprogresscalc = 'if '.natural_search('round(100 * $line->duration / $line->planned_workload,2)', $search_progresscalc, 1, 1).'{return 1;} else {return 0;}'; } else { $filterprogresscalc = ''; } if (!empty($search_progressdeclare)) { $morewherefilterarray[] = natural_search('t.progress', $search_progressdeclare, 1, 1); } $morewherefilter = ''; if (count($morewherefilterarray) > 0) { $morewherefilter = ' AND '.implode(' AND ', $morewherefilterarray); } if ($action == 'createtask' && $user->rights->projet->creer) { $error = 0; // If we use user timezone, we must change also view/list to use user timezone everywhere //$date_start = dol_mktime($_POST['dateohour'],$_POST['dateomin'],0,$_POST['dateomonth'],$_POST['dateoday'],$_POST['dateoyear'],'user'); //$date_end = dol_mktime($_POST['dateehour'],$_POST['dateemin'],0,$_POST['dateemonth'],$_POST['dateeday'],$_POST['dateeyear'],'user'); $date_start = dol_mktime($_POST['dateohour'], $_POST['dateomin'], 0, $_POST['dateomonth'], $_POST['dateoday'], $_POST['dateoyear']); $date_end = dol_mktime($_POST['dateehour'], $_POST['dateemin'], 0, $_POST['dateemonth'], $_POST['dateeday'], $_POST['dateeyear']); if (!$cancel) { if (empty($taskref)) { setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentities("Ref")), null, 'errors'); $action = 'create'; $error++; } if (empty($label)) { setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentities("Label")), null, 'errors'); $action = 'create'; $error++; } elseif (empty($_POST['task_parent'])) { setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentities("ChildOfProjectTask")), null, 'errors'); $action = 'create'; $error++; } if (!$error) { $tmparray = explode('_', $_POST['task_parent']); $projectid = $tmparray[0]; if (empty($projectid)) $projectid = $id; // If projectid is '' $task_parent = $tmparray[1]; if (empty($task_parent)) $task_parent = 0; // If task_parent is '' $task = new Task($db); $task->fk_project = $projectid; $task->ref = $taskref; $task->label = $label; $task->description = $description; $task->planned_workload = $planned_workload; $task->fk_task_parent = $task_parent; $task->date_c = dol_now(); $task->date_start = $date_start; $task->date_end = $date_end; $task->progress = $progress; // Fill array 'array_options' with data from add form $ret = $extrafields->setOptionalsFromPost(null, $task); $taskid = $task->create($user); if ($taskid > 0) { $result = $task->add_contact($_POST["userid"], 'TASKEXECUTIVE', 'internal'); } else { if ($db->lasterrno() == 'DB_ERROR_RECORD_ALREADY_EXISTS') { $langs->load("projects"); setEventMessages($langs->trans('NewTaskRefSuggested'), '', 'warnings'); $duplicate_code_error = true; } else { setEventMessages($task->error, $task->errors, 'errors'); } $action = 'create'; $error++; } } if (!$error) { if (!empty($backtopage)) { header("Location: ".$backtopage); exit; } elseif (empty($projectid)) { header("Location: ".DOL_URL_ROOT.'/projet/tasks/list.php'.(empty($mode) ? '' : '?mode='.$mode)); exit; } $id = $projectid; } } else { if (!empty($backtopage)) { header("Location: ".$backtopage); exit; } elseif (empty($id)) { // We go back on task list header("Location: ".DOL_URL_ROOT.'/projet/tasks/list.php'.(empty($mode) ? '' : '?mode='.$mode)); exit; } } } /* * View */ $now = dol_now(); $form = new Form($db); $formother = new FormOther($db); $socstatic = new Societe($db); $projectstatic = new Project($db); $taskstatic = new Task($db); $userstatic = new User($db); $title = $langs->trans("Project").' - '.$langs->trans("Tasks").' - '.$object->ref.' '.$object->name; if (!empty($conf->global->MAIN_HTML_TITLE) && preg_match('/projectnameonly/', $conf->global->MAIN_HTML_TITLE) && $object->name) $title = $object->ref.' '.$object->name.' - '.$langs->trans("Tasks"); $help_url = "EN:Module_Projects|FR:Module_Projets|ES:M&oacute;dulo_Proyectos"; llxHeader("", $title, $help_url); if ($id > 0 || !empty($ref)) { $object->fetch($id, $ref); $object->fetch_thirdparty(); $res = $object->fetch_optionals(); // To verify role of users //$userAccess = $object->restrictedProjectArea($user,'read'); $userWrite = $object->restrictedProjectArea($user, 'write'); //$userDelete = $object->restrictedProjectArea($user,'delete'); //print "userAccess=".$userAccess." userWrite=".$userWrite." userDelete=".$userDelete; $tab = GETPOST('tab') ?GETPOST('tab') : 'tasks'; $head = project_prepare_head($object); dol_fiche_head($head, $tab, $langs->trans("Project"), -1, ($object->public ? 'projectpub' : 'project')); $param = '&id='.$object->id; if (!empty($contextpage) && $contextpage != $_SERVER["PHP_SELF"]) $param .= '&contextpage='.urlencode($contextpage); if ($search_user_id) $param .= '&search_user_id='.urlencode($search_user_id); if ($search_taskref) $param .= '&search_taskref='.urlencode($search_taskref); if ($search_tasklabel) $param .= '&search_tasklabel='.urlencode($search_tasklabel); if ($search_taskdescription) $param .= '&search_taskdescription='.urlencode($search_taskdescription); if ($search_dtstartday) $param .= '&search_dtstartday='.urlencode($search_dtstartday); if ($search_dtstartmonth) $param .= '&search_dtstartmonth='.urlencode($search_dtstartmonth); if ($search_dtstartyear) $param .= '&search_dtstartyear='.urlencode($search_dtstartyear); if ($search_dtendday) $param .= '&search_dtendday='.urlencode($search_dtendday); if ($search_dtendmonth) $param .= '&search_dtendmonth='.urlencode($search_dtendmonth); if ($search_dtendyear) $param .= '&search_dtendyear='.urlencode($search_dtendyear); if ($search_planedworkload) $param .= '&search_planedworkload='.urlencode($search_planedworkload); if ($search_timespend) $param .= '&search_timespend='.urlencode($search_timespend); if ($search_progresscalc) $param .= '&search_progresscalc='.urlencode($search_progresscalc); if ($search_progressdeclare) $param .= '&search_progressdeclare='.urlencode($search_progressdeclare); if ($optioncss != '') $param .= '&optioncss='.urlencode($optioncss); // Add $param from extra fields include DOL_DOCUMENT_ROOT.'/core/tpl/extrafields_list_search_param.tpl.php'; // Project card $linkback = '<a href="'.DOL_URL_ROOT.'/projet/list.php?restore_lastsearch_values=1">'.$langs->trans("BackToList").'</a>'; $morehtmlref = '<div class="refidno">'; // Title $morehtmlref .= $object->title; // Thirdparty if ($object->thirdparty->id > 0) { $morehtmlref .= '<br>'.$langs->trans('ThirdParty').' : '.$object->thirdparty->getNomUrl(1, 'project'); } $morehtmlref .= '</div>'; // Define a complementary filter for search of next/prev ref. if (!$user->rights->projet->all->lire) { $objectsListId = $object->getProjectsAuthorizedForUser($user, 0, 0); $object->next_prev_filter = " rowid in (".(count($objectsListId) ?join(',', array_keys($objectsListId)) : '0').")"; } dol_banner_tab($object, 'ref', $linkback, 1, 'ref', 'ref', $morehtmlref); print '<div class="fichecenter">'; print '<div class="fichehalfleft">'; print '<div class="underbanner clearboth"></div>'; print '<table class="border tableforfield" width="100%">'; // Usage print '<tr><td class="tdtop">'; print $langs->trans("Usage"); print '</td>'; print '<td>'; if (!empty($conf->global->PROJECT_USE_OPPORTUNITIES)) { print '<input type="checkbox" disabled name="usage_opportunity"'.(GETPOSTISSET('usage_opportunity') ? (GETPOST('usage_opportunity', 'alpha') != '' ? ' checked="checked"' : '') : ($object->usage_opportunity ? ' checked="checked"' : '')).'"> '; $htmltext = $langs->trans("ProjectFollowOpportunity"); print $form->textwithpicto($langs->trans("ProjectFollowOpportunity"), $htmltext); print '<br>'; } if (empty($conf->global->PROJECT_HIDE_TASKS)) { print '<input type="checkbox" disabled name="usage_task"'.(GETPOSTISSET('usage_task') ? (GETPOST('usage_task', 'alpha') != '' ? ' checked="checked"' : '') : ($object->usage_task ? ' checked="checked"' : '')).'"> '; $htmltext = $langs->trans("ProjectFollowTasks"); print $form->textwithpicto($langs->trans("ProjectFollowTasks"), $htmltext); print '<br>'; } if (!empty($conf->global->PROJECT_BILL_TIME_SPENT)) { print '<input type="checkbox" disabled name="usage_bill_time"'.(GETPOSTISSET('usage_bill_time') ? (GETPOST('usage_bill_time', 'alpha') != '' ? ' checked="checked"' : '') : ($object->usage_bill_time ? ' checked="checked"' : '')).'"> '; $htmltext = $langs->trans("ProjectBillTimeDescription"); print $form->textwithpicto($langs->trans("BillTime"), $htmltext); print '<br>'; } print '</td></tr>'; // Visibility print '<tr><td class="titlefield">'.$langs->trans("Visibility").'</td><td>'; if ($object->public) print $langs->trans('SharedProject'); else print $langs->trans('PrivateProject'); print '</td></tr>'; // Date start - end print '<tr><td>'.$langs->trans("DateStart").' - '.$langs->trans("DateEnd").'</td><td>'; $start = dol_print_date($object->date_start, 'day'); print ($start ? $start : '?'); $end = dol_print_date($object->date_end, 'day'); print ' - '; print ($end ? $end : '?'); if ($object->hasDelay()) print img_warning("Late"); print '</td></tr>'; // Budget print '<tr><td>'.$langs->trans("Budget").'</td><td>'; if (strcmp($object->budget_amount, '')) print price($object->budget_amount, '', $langs, 1, 0, 0, $conf->currency); print '</td></tr>'; // Other attributes $cols = 2; include DOL_DOCUMENT_ROOT.'/core/tpl/extrafields_view.tpl.php'; print '</table>'; print '</div>'; print '<div class="fichehalfright">'; print '<div class="ficheaddleft">'; print '<div class="underbanner clearboth"></div>'; print '<table class="border tableforfield" width="100%">'; // Description print '<td class="titlefield tdtop">'.$langs->trans("Description").'</td><td>'; print nl2br($object->description); print '</td></tr>'; // Categories if ($conf->categorie->enabled) { print '<tr><td valign="middle">'.$langs->trans("Categories").'</td><td>'; print $form->showCategories($object->id, Categorie::TYPE_PROJECT, 1); print "</td></tr>"; } print '</table>'; print '</div>'; print '</div>'; print '</div>'; print '<div class="clearboth"></div>'; dol_fiche_end(); } if ($action == 'create' && $user->rights->projet->creer && (empty($object->thirdparty->id) || $userWrite > 0)) { if ($id > 0 || !empty($ref)) print '<br>'; print load_fiche_titre($langs->trans("NewTask"), '', 'projecttask'); if ($object->statut == Project::STATUS_CLOSED) { print '<div class="warning">'; $langs->load("errors"); print $langs->trans("WarningProjectClosed"); print '</div>'; } else { print '<form action="'.$_SERVER['PHP_SELF'].'" method="POST">'; print '<input type="hidden" name="token" value="'.newToken().'">'; print '<input type="hidden" name="action" value="createtask">'; print '<input type="hidden" name="backtopage" value="'.$backtopage.'">'; if (!empty($object->id)) print '<input type="hidden" name="id" value="'.$object->id.'">'; dol_fiche_head(''); print '<table class="border centpercent">'; $defaultref = ''; $obj = empty($conf->global->PROJECT_TASK_ADDON) ? 'mod_task_simple' : $conf->global->PROJECT_TASK_ADDON; if (!empty($conf->global->PROJECT_TASK_ADDON) && is_readable(DOL_DOCUMENT_ROOT."/core/modules/project/task/".$conf->global->PROJECT_TASK_ADDON.".php")) { require_once DOL_DOCUMENT_ROOT."/core/modules/project/task/".$conf->global->PROJECT_TASK_ADDON.'.php'; $modTask = new $obj; $defaultref = $modTask->getNextValue($object->thirdparty, null); } if (is_numeric($defaultref) && $defaultref <= 0) $defaultref = ''; // Ref print '<tr><td class="titlefieldcreate"><span class="fieldrequired">'.$langs->trans("Ref").'</span></td><td>'; if (empty($duplicate_code_error)) { print (GETPOSTISSET("ref") ?GETPOST("ref", 'alpha') : $defaultref); } else { print $defaultref; } print '<input type="hidden" name="taskref" value="'.($_POST["ref"] ? $_POST["ref"] : $defaultref).'">'; print '</td></tr>'; print '<tr><td class="fieldrequired">'.$langs->trans("Label").'</td><td>'; print '<input type="text" name="label" autofocus class="minwidth500" value="'.$label.'">'; print '</td></tr>'; // List of projects print '<tr><td class="fieldrequired">'.$langs->trans("ChildOfProjectTask").'</td><td>'; print $formother->selectProjectTasks(GETPOST('task_parent'), $projectid ? $projectid : $object->id, 'task_parent', 0, 0, 1, 1, 0, '0,1', 'maxwidth500'); print '</td></tr>'; print '<tr><td>'.$langs->trans("AffectedTo").'</td><td>'; $contactsofproject = (!empty($object->id) ? $object->getListContactId('internal') : ''); if (is_array($contactsofproject) && count($contactsofproject)) { print $form->select_dolusers($user->id, 'userid', 0, '', 0, '', $contactsofproject, 0, 0, 0, '', 0, '', 'maxwidth300'); } else { print $langs->trans("NoUserAssignedToTheProject"); } print '</td></tr>'; // Date start print '<tr><td>'.$langs->trans("DateStart").'</td><td>'; print $form->selectDate(($date_start ? $date_start : ''), 'dateo', 1, 1, 0, '', 1, 1); print '</td></tr>'; // Date end print '<tr><td>'.$langs->trans("DateEnd").'</td><td>'; print $form->selectDate(($date_end ? $date_end : -1), 'datee', -1, 1, 0, '', 1, 1); print '</td></tr>'; // Planned workload print '<tr><td>'.$langs->trans("PlannedWorkload").'</td><td>'; print $form->select_duration('planned_workload', $planned_workload ? $planned_workload : 0, 0, 'text'); print '</td></tr>'; // Progress print '<tr><td>'.$langs->trans("ProgressDeclared").'</td><td colspan="3">'; print $formother->select_percent($progress, 'progress', 0, 5, 0, 100, 1); print '</td></tr>'; // Description print '<tr><td class="tdtop">'.$langs->trans("Description").'</td>'; print '<td>'; print '<textarea name="description" class="quatrevingtpercent" rows="'.ROWS_4.'">'.$description.'</textarea>'; print '</td></tr>'; // Other options $parameters = array(); $reshook = $hookmanager->executeHooks('formObjectOptions', $parameters, $taskstatic, $action); // Note that $action and $object may have been modified by hook print $hookmanager->resPrint; if (empty($reshook) && !empty($extrafields->attributes[$taskstatic->table_element]['label'])) { print $taskstatic->showOptionals($extrafields, 'edit'); // Do not use $object here that is object of project but use $taskstatic } print '</table>'; dol_fiche_end(); print '<div class="center">'; print '<input type="submit" class="button" name="add" value="'.$langs->trans("Add").'">'; print ' &nbsp; &nbsp; '; print '<input type="submit" class="button" name="cancel" value="'.$langs->trans("Cancel").'">'; print '</div>'; print '</form>'; } } elseif ($id > 0 || !empty($ref)) { $selectedfields = $form->multiSelectArrayWithCheckbox('selectedfields', $arrayfields, $varpage); // This also change content of $arrayfields /* * Projet card in view mode */ print '<br>'; // Link to create task $linktocreatetaskParam = array(); $linktocreatetaskUserRight = false; if ($user->rights->projet->all->creer || $user->rights->projet->creer) { if ($object->public || $userWrite > 0) { $linktocreatetaskUserRight = true; } else { $linktocreatetaskParam['attr']['title'] = $langs->trans("NotOwnerOfProject"); } } $linktocreatetask = dolGetButtonTitle($langs->trans('AddTask'), '', 'fa fa-plus-circle', DOL_URL_ROOT.'/projet/tasks.php?action=create'.$param.'&backtopage='.urlencode($_SERVER['PHP_SELF'].'?id='.$object->id), '', $linktocreatetaskUserRight, $linktocreatetaskParam); print '<form method="POST" id="searchFormList" action="'.$_SERVER["PHP_SELF"].'?id='.$object->id.'">'; if ($optioncss != '') print '<input type="hidden" name="optioncss" value="'.$optioncss.'">'; print '<input type="hidden" name="token" value="'.newToken().'">'; print '<input type="hidden" name="action" value="list">'; print '<input type="hidden" name="formfilteraction" id="formfilteraction" value="list">'; print '<input type="hidden" name="sortfield" value="'.$sortfield.'">'; print '<input type="hidden" name="sortorder" value="'.$sortorder.'">'; print '<input type="hidden" name="page" value="'.$page.'">'; print '<input type="hidden" name="contextpage" value="'.$contextpage.'">'; $title = $langs->trans("ListOfTasks"); $linktotasks = dolGetButtonTitle($langs->trans('ViewList'), '', 'fa fa-list-alt paddingleft imgforviewmode', DOL_URL_ROOT.'/projet/tasks.php?id='.$object->id, '', 1, array('morecss'=>'reposition btnTitleSelected')); $linktotasks .= dolGetButtonTitle($langs->trans('ViewGantt'), '', 'fa fa-stream paddingleft imgforviewmode', DOL_URL_ROOT.'/projet/ganttview.php?id='.$object->id.'&withproject=1', '', 1, array('morecss'=>'reposition marginleftonly')); //print_barre_liste($title, 0, $_SERVER["PHP_SELF"], '', $sortfield, $sortorder, $linktotasks, $num, $totalnboflines, 'generic', 0, '', '', 0, 1); print load_fiche_titre($title, $linktotasks.' &nbsp; '.$linktocreatetask, 'generic'); // Get list of tasks in tasksarray and taskarrayfiltered // We need all tasks (even not limited to a user because a task to user can have a parent that is not affected to him). $filteronthirdpartyid = $socid; $tasksarray = $taskstatic->getTasksArray(0, 0, $object->id, $filteronthirdpartyid, 0, '', -1, $morewherefilter, 0, 0, $extrafields, 1, $search_array_options); // We load also tasks limited to a particular user $tmpuser = new User($db); if ($search_user_id > 0) $tmpuser->fetch($search_user_id); $tasksrole = ($tmpuser->id > 0 ? $taskstatic->getUserRolesForProjectsOrTasks(0, $tmpuser, $object->id, 0) : ''); //var_dump($tasksarray); //var_dump($tasksrole); if (!empty($conf->use_javascript_ajax)) { include DOL_DOCUMENT_ROOT.'/core/tpl/ajaxrow.tpl.php'; } // Filter on categories $moreforfilter = ''; if (count($tasksarray) > 0) { $moreforfilter .= '<div class="divsearchfield">'; $moreforfilter .= $langs->trans("TasksAssignedTo").': '; $moreforfilter .= $form->select_dolusers($tmpuser->id > 0 ? $tmpuser->id : '', 'search_user_id', 1); $moreforfilter .= '</div>'; } if ($moreforfilter) { print '<div class="liste_titre liste_titre_bydiv centpercent">'; print $moreforfilter; print '</div>'; } print '<div class="div-table-responsive">'; print '<table id="tablelines" class="tagtable nobottom liste'.($moreforfilter ? " listwithfilterbefore" : "").'">'; // Fields title search print '<tr class="liste_titre_filter">'; if (!empty($arrayfields['t.ref']['checked'])) { print '<td class="liste_titre">'; print '<input class="flat searchstring maxwidth50" type="text" name="search_taskref" value="'.dol_escape_htmltag($search_taskref).'">'; print '</td>'; } if (!empty($arrayfields['t.label']['checked'])) { print '<td class="liste_titre">'; print '<input class="flat searchstring maxwidth100" type="text" name="search_tasklabel" value="'.dol_escape_htmltag($search_tasklabel).'">'; print '</td>'; } if (!empty($arrayfields['t.description']['checked'])) { print '<td class="liste_titre">'; print '<input class="flat searchstring maxwidth100" type="text" name="search_taskdescription" value="'.dol_escape_htmltag($search_taskdescription).'">'; print '</td>'; } if (!empty($arrayfields['t.dateo']['checked'])) { print '<td class="liste_titre center">'; print '<input class="flat valignmiddle" type="text" size="1" maxlength="2" name="search_dtstartday" value="'.$search_dtstartday.'">'; print '<input class="flat valignmiddle" type="text" size="1" maxlength="2" name="search_dtstartmonth" value="'.$search_dtstartmonth.'">'; $formother->select_year($search_dtstartyear ? $search_dtstartyear : -1, 'search_dtstartyear', 1, 20, 5); print '</td>'; } if (!empty($arrayfields['t.datee']['checked'])) { print '<td class="liste_titre center">'; print '<input class="flat valignmiddle" type="text" size="1" maxlength="2" name="search_dtendday" value="'.$search_dtendday.'">'; print '<input class="flat valignmiddle" type="text" size="1" maxlength="2" name="search_dtendmonth" value="'.$search_dtendmonth.'">'; $formother->select_year($search_dtendyear ? $search_dtendyear : -1, 'search_dtendyear', 1, 20, 5); print '</td>'; } if (!empty($arrayfields['t.planned_workload']['checked'])) { print '<td class="liste_titre right">'; print '<input class="flat" type="text" size="4" name="search_planedworkload" value="'.$search_planedworkload.'">'; print '</td>'; } if (!empty($arrayfields['t.duration_effective']['checked'])) { print '<td class="liste_titre right">'; print '<input class="flat" type="text" size="4" name="search_timespend" value="'.$search_timespend.'">'; print '</td>'; } if (!empty($arrayfields['t.progress_calculated']['checked'])) { print '<td class="liste_titre right">'; print '<input class="flat" type="text" size="4" name="search_progresscalc" value="'.$search_progresscalc.'">'; print '</td>'; } if (!empty($arrayfields['t.progress']['checked'])) { print '<td class="liste_titre right">'; print '<input class="flat" type="text" size="4" name="search_progressdeclare" value="'.$search_progressdeclare.'">'; print '</td>'; } // progress resume not searchable print '<td class="liste_titre right"></td>'; if ($object->usage_bill_time) { if (!empty($arrayfields['t.tobill']['checked'])) { print '<td class="liste_titre right">'; print '</td>'; } if (!empty($arrayfields['t.billed']['checked'])) { print '<td class="liste_titre right">'; print '</td>'; } } if (!empty($conf->global->PROJECT_SHOW_CONTACTS_IN_LIST)) print '<td class="liste_titre"></td>'; $extrafieldsobjectkey = $taskstatic->table_element; include DOL_DOCUMENT_ROOT.'/core/tpl/extrafields_list_search_input.tpl.php'; // Action column print '<td class="liste_titre maxwidthsearch">'; $searchpicto = $form->showFilterButtons(); print $searchpicto; print '</td>'; print "</tr>\n"; print '<tr class="liste_titre nodrag nodrop">'; // print '<td>'.$langs->trans("Project").'</td>'; if (!empty($arrayfields['t.ref']['checked'])) print_liste_field_titre($arrayfields['t.ref']['label'], $_SERVER["PHP_SELF"], '', '', $param, '', $sortfield, $sortorder, ''); if (!empty($arrayfields['t.label']['checked'])) print_liste_field_titre($arrayfields['t.label']['label'], $_SERVER["PHP_SELF"], "", '', $param, '', $sortfield, $sortorder, ''); if (!empty($arrayfields['t.description']['checked'])) print_liste_field_titre($arrayfields['t.description']['label'], $_SERVER["PHP_SELF"], "", '', $param, '', $sortfield, $sortorder, ''); if (!empty($arrayfields['t.dateo']['checked'])) print_liste_field_titre($arrayfields['t.dateo']['label'], $_SERVER["PHP_SELF"], "", '', $param, '', $sortfield, $sortorder, 'center '); if (!empty($arrayfields['t.datee']['checked'])) print_liste_field_titre($arrayfields['t.datee']['label'], $_SERVER["PHP_SELF"], "", '', $param, '', $sortfield, $sortorder, 'center '); if (!empty($arrayfields['t.planned_workload']['checked'])) print_liste_field_titre($arrayfields['t.planned_workload']['label'], $_SERVER["PHP_SELF"], "", '', $param, '', $sortfield, $sortorder, 'right '); if (!empty($arrayfields['t.duration_effective']['checked'])) print_liste_field_titre($arrayfields['t.duration_effective']['label'], $_SERVER["PHP_SELF"], "", '', $param, '', $sortfield, $sortorder, 'right '); if (!empty($arrayfields['t.progress_calculated']['checked'])) print_liste_field_titre($arrayfields['t.progress_calculated']['label'], $_SERVER["PHP_SELF"], "", '', $param, '', $sortfield, $sortorder, 'right '); if (!empty($arrayfields['t.progress']['checked'])) print_liste_field_titre($arrayfields['t.progress']['label'], $_SERVER["PHP_SELF"], "", '', $param, '', $sortfield, $sortorder, 'right '); if (!empty($arrayfields['t.progress_summary']['checked'])) print_liste_field_titre($arrayfields['t.progress_summary']['label'], $_SERVER["PHP_SELF"], "", '', $param, '', $sortfield, $sortorder, 'center '); if ($object->usage_bill_time) { if (!empty($arrayfields['t.tobill']['checked'])) print_liste_field_titre($arrayfields['t.tobill']['label'], $_SERVER["PHP_SELF"], "", '', $param, '', $sortfield, $sortorder, 'right '); if (!empty($arrayfields['t.billed']['checked'])) print_liste_field_titre($arrayfields['t.billed']['label'], $_SERVER["PHP_SELF"], "", '', $param, '', $sortfield, $sortorder, 'right '); } if (!empty($conf->global->PROJECT_SHOW_CONTACTS_IN_LIST)) print_liste_field_titre("TaskRessourceLinks", $_SERVER["PHP_SELF"], '', '', $param, $sortfield, $sortorder); // Extra fields $disablesortlink = 1; include DOL_DOCUMENT_ROOT.'/core/tpl/extrafields_list_search_title.tpl.php'; // Hook fields $parameters = array('arrayfields'=>$arrayfields, 'param'=>$param, 'sortfield'=>$sortfield, 'sortorder'=>$sortorder); $reshook = $hookmanager->executeHooks('printFieldListTitle', $parameters); // Note that $action and $object may have been modified by hook print $hookmanager->resPrint; print_liste_field_titre($selectedfields, $_SERVER["PHP_SELF"], "", '', '', '', $sortfield, $sortorder, 'center maxwidthsearch '); print "</tr>\n"; if (count($tasksarray) > 0) { // Show all lines in taskarray (recursive function to go down on tree) $j = 0; $level = 0; $nboftaskshown = projectLinesa($j, 0, $tasksarray, $level, true, 0, $tasksrole, $object->id, 1, $object->id, $filterprogresscalc, ($object->usage_bill_time ? 1 : 0), $arrayfields); } else { $colspan = 10; if ($object->usage_bill_time) $colspan += 2; print '<tr class="oddeven nobottom"><td colspan="'.$colspan.'"><span class="opacitymedium">'.$langs->trans("NoTasks").'</span></td></tr>'; } print "</table>"; print '</div>'; print '</form>'; // Test if database is clean. If not we clean it. //print 'mode='.$_REQUEST["mode"].' $nboftaskshown='.$nboftaskshown.' count($tasksarray)='.count($tasksarray).' count($tasksrole)='.count($tasksrole).'<br>'; if (!empty($user->rights->projet->all->lire)) // We make test to clean only if user has permission to see all (test may report false positive otherwise) { if ($search_user_id == $user->id) { if ($nboftaskshown < count($tasksrole)) { include_once DOL_DOCUMENT_ROOT.'/core/lib/functions2.lib.php'; cleanCorruptedTree($db, 'projet_task', 'fk_task_parent'); } } else { if ($nboftaskshown < count($tasksarray) && !GETPOST('search_user_id', 'int')) { include_once DOL_DOCUMENT_ROOT.'/core/lib/functions2.lib.php'; cleanCorruptedTree($db, 'projet_task', 'fk_task_parent'); } } } } // End of page llxFooter(); $db->close();
{ "pile_set_name": "Github" }
config BR2_PACKAGE_NGINX_UPLOAD bool "nginx-upload" depends on BR2_PACKAGE_NGINX_HTTP select BR2_PACKAGE_OPENSSL help A module for nginx web server for handling file uploads using multipart/form-data encoding (RFC 1867). https://github.com/vkholodkov/nginx-upload-module
{ "pile_set_name": "Github" }
#if DOTNET35 namespace Rhino.Mocks.Tests.FieldsProblem { using System; using Xunit; public class FieldProblem_Henrik { [Fact] public void Trying_to_mock_null_instance_should_fail_with_descriptive_error_message() { Assert.Throws<ArgumentNullException>("You cannot mock a null instance\r\nParameter name: mock", () => RhinoMocksExtensions.Expect<object>(null, x => x.ToString())); } } } #endif
{ "pile_set_name": "Github" }
//app.js App({ onLaunch: function () { //调用API从本地缓存中获取数据 var logs = wx.getStorageSync('logs') || [] logs.unshift(Date.now()) wx.setStorageSync('logs', logs) }, getUserInfo: function (cb) { var that = this if (this.globalData.userInfo) { typeof cb == "function" && cb(this.globalData.userInfo) } else { //调用登录接口 wx.login({ success: function () { wx.getUserInfo({ success: function (res) { that.globalData.userInfo = res.userInfo typeof cb == "function" && cb(that.globalData.userInfo) } }) } }) } }, globalData: { userInfo: null } })
{ "pile_set_name": "Github" }
#!/usr/bin/expect -f # This file is part of Firejail project # Copyright (C) 2014-2020 Firejail Authors # License GPL v2 set timeout 10 spawn $env(SHELL) match_max 100000 send -- "firejail pluma\r" expect { timeout {puts "TESTING ERROR 0\n";exit} "Reading profile /etc/firejail/pluma.profile" } expect { timeout {puts "TESTING ERROR 1\n";exit} "Child process initialized" } sleep 3 spawn $env(SHELL) send -- "firejail --list\r" expect { timeout {puts "TESTING ERROR 3\n";exit} ":firejail" } expect { timeout {puts "TESTING ERROR 3.1\n";exit} "pluma" } after 100 # grsecurity exit send -- "file /proc/sys/kernel/grsecurity\r" expect { timeout {puts "TESTING ERROR - grsecurity detection\n";exit} "grsecurity: directory" {puts "grsecurity present, exiting...\n";exit} "cannot open" {puts "grsecurity not present\n"} } send -- "firejail --name=blablabla\r" expect { timeout {puts "TESTING ERROR 4\n";exit} "Child process initialized" } sleep 2 spawn $env(SHELL) send -- "firemon --seccomp\r" expect { timeout {puts "TESTING ERROR 5\n";exit} "need to be root" {puts "/proc mounted as hidepid, exiting...\n"; exit} ":firejail pluma" } expect { timeout {puts "TESTING ERROR 5.1 (seccomp)\n";exit} "Seccomp: 2" } expect { timeout {puts "TESTING ERROR 5.1\n";exit} "name=blablabla" } after 100 send -- "firemon --caps\r" expect { timeout {puts "TESTING ERROR 6\n";exit} ":firejail pluma" } expect { timeout {puts "TESTING ERROR 6.1\n";exit} "CapBnd:" } expect { timeout {puts "TESTING ERROR 6.2\n";exit} "0000000000000000" } expect { timeout {puts "TESTING ERROR 6.3\n";exit} "name=blablabla" } after 100 puts "\nall done\n"
{ "pile_set_name": "Github" }
from ralph.networks.models.choices import IPAddressStatus from ralph.networks.models.networks import ( DiscoveryQueue, IPAddress, Network, NetworkEnvironment, NetworkKind ) __all__ = [ 'DiscoveryQueue', 'IPAddress', 'IPAddressStatus', 'Network', 'NetworkEnvironment', 'NetworkKind', ]
{ "pile_set_name": "Github" }
<?php /** * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ declare(strict_types=1); use Magento\Catalog\Api\ProductRepositoryInterface; use Magento\Store\Api\WebsiteRepositoryInterface; use Magento\TestFramework\Helper\Bootstrap; require __DIR__ . '/category_with_different_price_products.php'; require __DIR__ . '/../../Store/_files/second_website_with_two_stores.php'; $objectManager = Bootstrap::getObjectManager(); /** @var WebsiteRepositoryInterface $websiteRepository */ $websiteRepository = $objectManager->get(WebsiteRepositoryInterface::class); $defaultWebsiteId = $websiteRepository->get('base')->getId(); $websiteId = $websiteRepository->get('test')->getId(); $product = $productRepository->get('simple1000'); $product->setWebsiteIds([$defaultWebsiteId, $websiteId]); $productRepository->save($product); $product = $productRepository->get('simple1001'); $product->setWebsiteIds([$defaultWebsiteId, $websiteId]); $productRepository->save($product);
{ "pile_set_name": "Github" }
# frozen_string_literal: true require_relative 'helper' class TestRDocGeneratorPOTPOEntry < RDoc::TestCase def test_msgid_normal assert_equal <<-'ENTRY', entry("Hello", {}).to_s msgid "Hello" msgstr "" ENTRY end def test_msgid_multiple_lines assert_equal <<-'ENTRY', entry("Hello\nWorld", {}).to_s msgid "" "Hello\n" "World" msgstr "" ENTRY end def test_msgid_tab assert_equal <<-'ENTRY', entry("Hello\tWorld", {}).to_s msgid "Hello\tWorld" msgstr "" ENTRY end def test_msgid_back_slash assert_equal <<-'ENTRY', entry("Hello \\ World", {}).to_s msgid "Hello \\ World" msgstr "" ENTRY end def test_msgid_double_quote assert_equal <<-'ENTRY', entry("Hello \"World\"!", {}).to_s msgid "Hello \"World\"!" msgstr "" ENTRY end def test_translator_comment_normal options = {:translator_comment => "Greeting"} assert_equal <<-'ENTRY', entry("Hello", options).to_s # Greeting msgid "Hello" msgstr "" ENTRY end def test_translator_comment_multiple_lines options = {:translator_comment => "Greeting\nfor morning"} assert_equal <<-'ENTRY', entry("Hello", options).to_s # Greeting # for morning msgid "Hello" msgstr "" ENTRY end def test_extracted_comment_normal options = {:extracted_comment => "Object"} assert_equal <<-'ENTRY', entry("Hello", options).to_s #. Object msgid "Hello" msgstr "" ENTRY end def test_extracted_comment_multiple_lines options = {:extracted_comment => "Object\nMorning#greeting"} assert_equal <<-'ENTRY', entry("Hello", options).to_s #. Object #. Morning#greeting msgid "Hello" msgstr "" ENTRY end def test_references_normal options = {:references => [["lib/rdoc.rb", 29]]} assert_equal <<-'ENTRY', entry("Hello", options).to_s #: lib/rdoc.rb:29 msgid "Hello" msgstr "" ENTRY end def test_references_multiple options = {:references => [["lib/rdoc.rb", 29], ["lib/rdoc/i18n.rb", 9]]} assert_equal <<-'ENTRY', entry("Hello", options).to_s #: lib/rdoc.rb:29 #: lib/rdoc/i18n.rb:9 msgid "Hello" msgstr "" ENTRY end def test_flags_normal options = {:flags => ["fuzzy"]} assert_equal <<-'ENTRY', entry("Hello", options).to_s #, fuzzy msgid "Hello" msgstr "" ENTRY end def test_flags_multiple options = {:flags => ["fuzzy", "ruby-format"]} assert_equal <<-'ENTRY', entry("Hello", options).to_s #, fuzzy,ruby-format msgid "Hello" msgstr "" ENTRY end def test_full options = { :translator_comment => "Greeting", :extracted_comment => "Morning#greeting", :references => [["lib/rdoc.rb", 29]], :flags => ["fuzzy"], } assert_equal <<-'ENTRY', entry("Hello", options).to_s # Greeting #. Morning#greeting #: lib/rdoc.rb:29 #, fuzzy msgid "Hello" msgstr "" ENTRY end private def entry(msgid, options) RDoc::Generator::POT::POEntry.new(msgid, options) end end
{ "pile_set_name": "Github" }
/***************************************************************************/ /* */ /* otvcommn.c */ /* */ /* OpenType common tables validation (body). */ /* */ /* Copyright 2004-2016 by */ /* David Turner, Robert Wilhelm, and Werner Lemberg. */ /* */ /* This file is part of the FreeType project, and may only be used, */ /* modified, and distributed under the terms of the FreeType project */ /* license, LICENSE.TXT. By continuing to use, modify, or distribute */ /* this file you indicate that you have read the license and */ /* understand and accept it fully. */ /* */ /***************************************************************************/ #include "otvcommn.h" /*************************************************************************/ /* */ /* The macro FT_COMPONENT is used in trace mode. It is an implicit */ /* parameter of the FT_TRACE() and FT_ERROR() macros, used to print/log */ /* messages during execution. */ /* */ #undef FT_COMPONENT #define FT_COMPONENT trace_otvcommon /*************************************************************************/ /*************************************************************************/ /***** *****/ /***** COVERAGE TABLE *****/ /***** *****/ /*************************************************************************/ /*************************************************************************/ FT_LOCAL_DEF( void ) otv_Coverage_validate( FT_Bytes table, OTV_Validator otvalid, FT_Int expected_count ) { FT_Bytes p = table; FT_UInt CoverageFormat; FT_UInt total = 0; OTV_NAME_ENTER( "Coverage" ); OTV_LIMIT_CHECK( 4 ); CoverageFormat = FT_NEXT_USHORT( p ); OTV_TRACE(( " (format %d)\n", CoverageFormat )); switch ( CoverageFormat ) { case 1: /* CoverageFormat1 */ { FT_UInt GlyphCount; FT_UInt i; GlyphCount = FT_NEXT_USHORT( p ); OTV_TRACE(( " (GlyphCount = %d)\n", GlyphCount )); OTV_LIMIT_CHECK( GlyphCount * 2 ); /* GlyphArray */ for ( i = 0; i < GlyphCount; ++i ) { FT_UInt gid; gid = FT_NEXT_USHORT( p ); if ( gid >= otvalid->glyph_count ) FT_INVALID_GLYPH_ID; } total = GlyphCount; } break; case 2: /* CoverageFormat2 */ { FT_UInt n, RangeCount; FT_UInt Start, End, StartCoverageIndex, last = 0; RangeCount = FT_NEXT_USHORT( p ); OTV_TRACE(( " (RangeCount = %d)\n", RangeCount )); OTV_LIMIT_CHECK( RangeCount * 6 ); /* RangeRecord */ for ( n = 0; n < RangeCount; n++ ) { Start = FT_NEXT_USHORT( p ); End = FT_NEXT_USHORT( p ); StartCoverageIndex = FT_NEXT_USHORT( p ); if ( Start > End || StartCoverageIndex != total ) FT_INVALID_DATA; if ( End >= otvalid->glyph_count ) FT_INVALID_GLYPH_ID; if ( n > 0 && Start <= last ) FT_INVALID_DATA; total += End - Start + 1; last = End; } } break; default: FT_INVALID_FORMAT; } /* Generally, a coverage table offset has an associated count field. */ /* The number of glyphs in the table should match this field. If */ /* there is no associated count, a value of -1 tells us not to check. */ if ( expected_count != -1 && (FT_UInt)expected_count != total ) FT_INVALID_DATA; OTV_EXIT; } FT_LOCAL_DEF( FT_UInt ) otv_Coverage_get_first( FT_Bytes table ) { FT_Bytes p = table; p += 4; /* skip CoverageFormat and Glyph/RangeCount */ return FT_NEXT_USHORT( p ); } FT_LOCAL_DEF( FT_UInt ) otv_Coverage_get_last( FT_Bytes table ) { FT_Bytes p = table; FT_UInt CoverageFormat = FT_NEXT_USHORT( p ); FT_UInt count = FT_NEXT_USHORT( p ); /* Glyph/RangeCount */ FT_UInt result = 0; switch ( CoverageFormat ) { case 1: p += ( count - 1 ) * 2; result = FT_NEXT_USHORT( p ); break; case 2: p += ( count - 1 ) * 6 + 2; result = FT_NEXT_USHORT( p ); break; default: ; } return result; } FT_LOCAL_DEF( FT_UInt ) otv_Coverage_get_count( FT_Bytes table ) { FT_Bytes p = table; FT_UInt CoverageFormat = FT_NEXT_USHORT( p ); FT_UInt count = FT_NEXT_USHORT( p ); /* Glyph/RangeCount */ FT_UInt result = 0; switch ( CoverageFormat ) { case 1: return count; case 2: { FT_UInt Start, End; for ( ; count > 0; count-- ) { Start = FT_NEXT_USHORT( p ); End = FT_NEXT_USHORT( p ); p += 2; /* skip StartCoverageIndex */ result += End - Start + 1; } } break; default: ; } return result; } /*************************************************************************/ /*************************************************************************/ /***** *****/ /***** CLASS DEFINITION TABLE *****/ /***** *****/ /*************************************************************************/ /*************************************************************************/ FT_LOCAL_DEF( void ) otv_ClassDef_validate( FT_Bytes table, OTV_Validator otvalid ) { FT_Bytes p = table; FT_UInt ClassFormat; OTV_NAME_ENTER( "ClassDef" ); OTV_LIMIT_CHECK( 4 ); ClassFormat = FT_NEXT_USHORT( p ); OTV_TRACE(( " (format %d)\n", ClassFormat )); switch ( ClassFormat ) { case 1: /* ClassDefFormat1 */ { FT_UInt StartGlyph; FT_UInt GlyphCount; OTV_LIMIT_CHECK( 4 ); StartGlyph = FT_NEXT_USHORT( p ); GlyphCount = FT_NEXT_USHORT( p ); OTV_TRACE(( " (GlyphCount = %d)\n", GlyphCount )); OTV_LIMIT_CHECK( GlyphCount * 2 ); /* ClassValueArray */ if ( StartGlyph + GlyphCount - 1 >= otvalid->glyph_count ) FT_INVALID_GLYPH_ID; } break; case 2: /* ClassDefFormat2 */ { FT_UInt n, ClassRangeCount; FT_UInt Start, End, last = 0; ClassRangeCount = FT_NEXT_USHORT( p ); OTV_TRACE(( " (ClassRangeCount = %d)\n", ClassRangeCount )); OTV_LIMIT_CHECK( ClassRangeCount * 6 ); /* ClassRangeRecord */ for ( n = 0; n < ClassRangeCount; n++ ) { Start = FT_NEXT_USHORT( p ); End = FT_NEXT_USHORT( p ); p += 2; /* skip Class */ if ( Start > End || ( n > 0 && Start <= last ) ) FT_INVALID_DATA; if ( End >= otvalid->glyph_count ) FT_INVALID_GLYPH_ID; last = End; } } break; default: FT_INVALID_FORMAT; } /* no need to check glyph indices used as input to class definition */ /* tables since even invalid glyph indices return a meaningful result */ OTV_EXIT; } /*************************************************************************/ /*************************************************************************/ /***** *****/ /***** DEVICE TABLE *****/ /***** *****/ /*************************************************************************/ /*************************************************************************/ FT_LOCAL_DEF( void ) otv_Device_validate( FT_Bytes table, OTV_Validator otvalid ) { FT_Bytes p = table; FT_UInt StartSize, EndSize, DeltaFormat, count; OTV_NAME_ENTER( "Device" ); OTV_LIMIT_CHECK( 8 ); StartSize = FT_NEXT_USHORT( p ); EndSize = FT_NEXT_USHORT( p ); DeltaFormat = FT_NEXT_USHORT( p ); if ( DeltaFormat < 1 || DeltaFormat > 3 ) FT_INVALID_FORMAT; if ( EndSize < StartSize ) FT_INVALID_DATA; count = EndSize - StartSize + 1; OTV_LIMIT_CHECK( ( 1 << DeltaFormat ) * count / 8 ); /* DeltaValue */ OTV_EXIT; } /*************************************************************************/ /*************************************************************************/ /***** *****/ /***** LOOKUPS *****/ /***** *****/ /*************************************************************************/ /*************************************************************************/ /* uses otvalid->type_count */ /* uses otvalid->type_funcs */ FT_LOCAL_DEF( void ) otv_Lookup_validate( FT_Bytes table, OTV_Validator otvalid ) { FT_Bytes p = table; FT_UInt LookupType, SubTableCount; OTV_Validate_Func validate; OTV_NAME_ENTER( "Lookup" ); OTV_LIMIT_CHECK( 6 ); LookupType = FT_NEXT_USHORT( p ); p += 2; /* skip LookupFlag */ SubTableCount = FT_NEXT_USHORT( p ); OTV_TRACE(( " (type %d)\n", LookupType )); if ( LookupType == 0 || LookupType > otvalid->type_count ) FT_INVALID_DATA; validate = otvalid->type_funcs[LookupType - 1]; OTV_TRACE(( " (SubTableCount = %d)\n", SubTableCount )); OTV_LIMIT_CHECK( SubTableCount * 2 ); /* SubTable */ for ( ; SubTableCount > 0; SubTableCount-- ) validate( table + FT_NEXT_USHORT( p ), otvalid ); OTV_EXIT; } /* uses valid->lookup_count */ FT_LOCAL_DEF( void ) otv_LookupList_validate( FT_Bytes table, OTV_Validator otvalid ) { FT_Bytes p = table; FT_UInt LookupCount; OTV_NAME_ENTER( "LookupList" ); OTV_LIMIT_CHECK( 2 ); LookupCount = FT_NEXT_USHORT( p ); OTV_TRACE(( " (LookupCount = %d)\n", LookupCount )); OTV_LIMIT_CHECK( LookupCount * 2 ); otvalid->lookup_count = LookupCount; /* Lookup */ for ( ; LookupCount > 0; LookupCount-- ) otv_Lookup_validate( table + FT_NEXT_USHORT( p ), otvalid ); OTV_EXIT; } static FT_UInt otv_LookupList_get_count( FT_Bytes table ) { return FT_NEXT_USHORT( table ); } /*************************************************************************/ /*************************************************************************/ /***** *****/ /***** FEATURES *****/ /***** *****/ /*************************************************************************/ /*************************************************************************/ /* uses otvalid->lookup_count */ FT_LOCAL_DEF( void ) otv_Feature_validate( FT_Bytes table, OTV_Validator otvalid ) { FT_Bytes p = table; FT_UInt LookupCount; OTV_NAME_ENTER( "Feature" ); OTV_LIMIT_CHECK( 4 ); p += 2; /* skip FeatureParams (unused) */ LookupCount = FT_NEXT_USHORT( p ); OTV_TRACE(( " (LookupCount = %d)\n", LookupCount )); OTV_LIMIT_CHECK( LookupCount * 2 ); /* LookupListIndex */ for ( ; LookupCount > 0; LookupCount-- ) if ( FT_NEXT_USHORT( p ) >= otvalid->lookup_count ) FT_INVALID_DATA; OTV_EXIT; } static FT_UInt otv_Feature_get_count( FT_Bytes table ) { return FT_NEXT_USHORT( table ); } /* sets otvalid->lookup_count */ FT_LOCAL_DEF( void ) otv_FeatureList_validate( FT_Bytes table, FT_Bytes lookups, OTV_Validator otvalid ) { FT_Bytes p = table; FT_UInt FeatureCount; OTV_NAME_ENTER( "FeatureList" ); OTV_LIMIT_CHECK( 2 ); FeatureCount = FT_NEXT_USHORT( p ); OTV_TRACE(( " (FeatureCount = %d)\n", FeatureCount )); OTV_LIMIT_CHECK( FeatureCount * 2 ); otvalid->lookup_count = otv_LookupList_get_count( lookups ); /* FeatureRecord */ for ( ; FeatureCount > 0; FeatureCount-- ) { p += 4; /* skip FeatureTag */ /* Feature */ otv_Feature_validate( table + FT_NEXT_USHORT( p ), otvalid ); } OTV_EXIT; } /*************************************************************************/ /*************************************************************************/ /***** *****/ /***** LANGUAGE SYSTEM *****/ /***** *****/ /*************************************************************************/ /*************************************************************************/ /* uses otvalid->extra1 (number of features) */ FT_LOCAL_DEF( void ) otv_LangSys_validate( FT_Bytes table, OTV_Validator otvalid ) { FT_Bytes p = table; FT_UInt ReqFeatureIndex; FT_UInt FeatureCount; OTV_NAME_ENTER( "LangSys" ); OTV_LIMIT_CHECK( 6 ); p += 2; /* skip LookupOrder (unused) */ ReqFeatureIndex = FT_NEXT_USHORT( p ); FeatureCount = FT_NEXT_USHORT( p ); OTV_TRACE(( " (ReqFeatureIndex = %d)\n", ReqFeatureIndex )); OTV_TRACE(( " (FeatureCount = %d)\n", FeatureCount )); if ( ReqFeatureIndex != 0xFFFFU && ReqFeatureIndex >= otvalid->extra1 ) FT_INVALID_DATA; OTV_LIMIT_CHECK( FeatureCount * 2 ); /* FeatureIndex */ for ( ; FeatureCount > 0; FeatureCount-- ) if ( FT_NEXT_USHORT( p ) >= otvalid->extra1 ) FT_INVALID_DATA; OTV_EXIT; } /*************************************************************************/ /*************************************************************************/ /***** *****/ /***** SCRIPTS *****/ /***** *****/ /*************************************************************************/ /*************************************************************************/ FT_LOCAL_DEF( void ) otv_Script_validate( FT_Bytes table, OTV_Validator otvalid ) { FT_UInt DefaultLangSys, LangSysCount; FT_Bytes p = table; OTV_NAME_ENTER( "Script" ); OTV_LIMIT_CHECK( 4 ); DefaultLangSys = FT_NEXT_USHORT( p ); LangSysCount = FT_NEXT_USHORT( p ); OTV_TRACE(( " (LangSysCount = %d)\n", LangSysCount )); if ( DefaultLangSys != 0 ) otv_LangSys_validate( table + DefaultLangSys, otvalid ); OTV_LIMIT_CHECK( LangSysCount * 6 ); /* LangSysRecord */ for ( ; LangSysCount > 0; LangSysCount-- ) { p += 4; /* skip LangSysTag */ /* LangSys */ otv_LangSys_validate( table + FT_NEXT_USHORT( p ), otvalid ); } OTV_EXIT; } /* sets otvalid->extra1 (number of features) */ FT_LOCAL_DEF( void ) otv_ScriptList_validate( FT_Bytes table, FT_Bytes features, OTV_Validator otvalid ) { FT_UInt ScriptCount; FT_Bytes p = table; OTV_NAME_ENTER( "ScriptList" ); OTV_LIMIT_CHECK( 2 ); ScriptCount = FT_NEXT_USHORT( p ); OTV_TRACE(( " (ScriptCount = %d)\n", ScriptCount )); OTV_LIMIT_CHECK( ScriptCount * 6 ); otvalid->extra1 = otv_Feature_get_count( features ); /* ScriptRecord */ for ( ; ScriptCount > 0; ScriptCount-- ) { p += 4; /* skip ScriptTag */ otv_Script_validate( table + FT_NEXT_USHORT( p ), otvalid ); /* Script */ } OTV_EXIT; } /*************************************************************************/ /*************************************************************************/ /***** *****/ /***** UTILITY FUNCTIONS *****/ /***** *****/ /*************************************************************************/ /*************************************************************************/ /* u: uint16 ux: unit16 [x] s: struct sx: struct [x] sxy: struct [x], using external y count x: uint16 x C: Coverage O: Offset On: Offset (NULL) Ox: Offset [x] Onx: Offset (NULL) [x] */ FT_LOCAL_DEF( void ) otv_x_Ox( FT_Bytes table, OTV_Validator otvalid ) { FT_Bytes p = table; FT_UInt Count; OTV_Validate_Func func; OTV_ENTER; OTV_LIMIT_CHECK( 2 ); Count = FT_NEXT_USHORT( p ); OTV_TRACE(( " (Count = %d)\n", Count )); OTV_LIMIT_CHECK( Count * 2 ); otvalid->nesting_level++; func = otvalid->func[otvalid->nesting_level]; for ( ; Count > 0; Count-- ) func( table + FT_NEXT_USHORT( p ), otvalid ); otvalid->nesting_level--; OTV_EXIT; } FT_LOCAL_DEF( void ) otv_u_C_x_Ox( FT_Bytes table, OTV_Validator otvalid ) { FT_Bytes p = table; FT_UInt Count, Coverage; OTV_Validate_Func func; OTV_ENTER; p += 2; /* skip Format */ OTV_LIMIT_CHECK( 4 ); Coverage = FT_NEXT_USHORT( p ); Count = FT_NEXT_USHORT( p ); OTV_TRACE(( " (Count = %d)\n", Count )); otv_Coverage_validate( table + Coverage, otvalid, (FT_Int)Count ); OTV_LIMIT_CHECK( Count * 2 ); otvalid->nesting_level++; func = otvalid->func[otvalid->nesting_level]; for ( ; Count > 0; Count-- ) func( table + FT_NEXT_USHORT( p ), otvalid ); otvalid->nesting_level--; OTV_EXIT; } /* uses otvalid->extra1 (if > 0: array value limit) */ FT_LOCAL_DEF( void ) otv_x_ux( FT_Bytes table, OTV_Validator otvalid ) { FT_Bytes p = table; FT_UInt Count; OTV_ENTER; OTV_LIMIT_CHECK( 2 ); Count = FT_NEXT_USHORT( p ); OTV_TRACE(( " (Count = %d)\n", Count )); OTV_LIMIT_CHECK( Count * 2 ); if ( otvalid->extra1 ) { for ( ; Count > 0; Count-- ) if ( FT_NEXT_USHORT( p ) >= otvalid->extra1 ) FT_INVALID_DATA; } OTV_EXIT; } /* `ux' in the function's name is not really correct since only x-1 */ /* elements are tested */ /* uses otvalid->extra1 (array value limit) */ FT_LOCAL_DEF( void ) otv_x_y_ux_sy( FT_Bytes table, OTV_Validator otvalid ) { FT_Bytes p = table; FT_UInt Count1, Count2; OTV_ENTER; OTV_LIMIT_CHECK( 4 ); Count1 = FT_NEXT_USHORT( p ); Count2 = FT_NEXT_USHORT( p ); OTV_TRACE(( " (Count1 = %d)\n", Count1 )); OTV_TRACE(( " (Count2 = %d)\n", Count2 )); if ( Count1 == 0 ) FT_INVALID_DATA; OTV_LIMIT_CHECK( ( Count1 - 1 ) * 2 + Count2 * 4 ); p += ( Count1 - 1 ) * 2; for ( ; Count2 > 0; Count2-- ) { if ( FT_NEXT_USHORT( p ) >= Count1 ) FT_INVALID_DATA; if ( FT_NEXT_USHORT( p ) >= otvalid->extra1 ) FT_INVALID_DATA; } OTV_EXIT; } /* `uy' in the function's name is not really correct since only y-1 */ /* elements are tested */ /* uses otvalid->extra1 (array value limit) */ FT_LOCAL_DEF( void ) otv_x_ux_y_uy_z_uz_p_sp( FT_Bytes table, OTV_Validator otvalid ) { FT_Bytes p = table; FT_UInt BacktrackCount, InputCount, LookaheadCount; FT_UInt Count; OTV_ENTER; OTV_LIMIT_CHECK( 2 ); BacktrackCount = FT_NEXT_USHORT( p ); OTV_TRACE(( " (BacktrackCount = %d)\n", BacktrackCount )); OTV_LIMIT_CHECK( BacktrackCount * 2 + 2 ); p += BacktrackCount * 2; InputCount = FT_NEXT_USHORT( p ); if ( InputCount == 0 ) FT_INVALID_DATA; OTV_TRACE(( " (InputCount = %d)\n", InputCount )); OTV_LIMIT_CHECK( InputCount * 2 ); p += ( InputCount - 1 ) * 2; LookaheadCount = FT_NEXT_USHORT( p ); OTV_TRACE(( " (LookaheadCount = %d)\n", LookaheadCount )); OTV_LIMIT_CHECK( LookaheadCount * 2 + 2 ); p += LookaheadCount * 2; Count = FT_NEXT_USHORT( p ); OTV_TRACE(( " (Count = %d)\n", Count )); OTV_LIMIT_CHECK( Count * 4 ); for ( ; Count > 0; Count-- ) { if ( FT_NEXT_USHORT( p ) >= InputCount ) FT_INVALID_DATA; if ( FT_NEXT_USHORT( p ) >= otvalid->extra1 ) FT_INVALID_DATA; } OTV_EXIT; } /* sets otvalid->extra1 (valid->lookup_count) */ FT_LOCAL_DEF( void ) otv_u_O_O_x_Onx( FT_Bytes table, OTV_Validator otvalid ) { FT_Bytes p = table; FT_UInt Coverage, ClassDef, ClassSetCount; OTV_Validate_Func func; OTV_ENTER; p += 2; /* skip Format */ OTV_LIMIT_CHECK( 6 ); Coverage = FT_NEXT_USHORT( p ); ClassDef = FT_NEXT_USHORT( p ); ClassSetCount = FT_NEXT_USHORT( p ); OTV_TRACE(( " (ClassSetCount = %d)\n", ClassSetCount )); otv_Coverage_validate( table + Coverage, otvalid, -1 ); otv_ClassDef_validate( table + ClassDef, otvalid ); OTV_LIMIT_CHECK( ClassSetCount * 2 ); otvalid->nesting_level++; func = otvalid->func[otvalid->nesting_level]; otvalid->extra1 = otvalid->lookup_count; for ( ; ClassSetCount > 0; ClassSetCount-- ) { FT_UInt offset = FT_NEXT_USHORT( p ); if ( offset ) func( table + offset, otvalid ); } otvalid->nesting_level--; OTV_EXIT; } /* uses otvalid->lookup_count */ FT_LOCAL_DEF( void ) otv_u_x_y_Ox_sy( FT_Bytes table, OTV_Validator otvalid ) { FT_Bytes p = table; FT_UInt GlyphCount, Count, count1; OTV_ENTER; p += 2; /* skip Format */ OTV_LIMIT_CHECK( 4 ); GlyphCount = FT_NEXT_USHORT( p ); Count = FT_NEXT_USHORT( p ); OTV_TRACE(( " (GlyphCount = %d)\n", GlyphCount )); OTV_TRACE(( " (Count = %d)\n", Count )); OTV_LIMIT_CHECK( GlyphCount * 2 + Count * 4 ); for ( count1 = GlyphCount; count1 > 0; count1-- ) otv_Coverage_validate( table + FT_NEXT_USHORT( p ), otvalid, -1 ); for ( ; Count > 0; Count-- ) { if ( FT_NEXT_USHORT( p ) >= GlyphCount ) FT_INVALID_DATA; if ( FT_NEXT_USHORT( p ) >= otvalid->lookup_count ) FT_INVALID_DATA; } OTV_EXIT; } /* sets otvalid->extra1 (valid->lookup_count) */ FT_LOCAL_DEF( void ) otv_u_O_O_O_O_x_Onx( FT_Bytes table, OTV_Validator otvalid ) { FT_Bytes p = table; FT_UInt Coverage; FT_UInt BacktrackClassDef, InputClassDef, LookaheadClassDef; FT_UInt ChainClassSetCount; OTV_Validate_Func func; OTV_ENTER; p += 2; /* skip Format */ OTV_LIMIT_CHECK( 10 ); Coverage = FT_NEXT_USHORT( p ); BacktrackClassDef = FT_NEXT_USHORT( p ); InputClassDef = FT_NEXT_USHORT( p ); LookaheadClassDef = FT_NEXT_USHORT( p ); ChainClassSetCount = FT_NEXT_USHORT( p ); OTV_TRACE(( " (ChainClassSetCount = %d)\n", ChainClassSetCount )); otv_Coverage_validate( table + Coverage, otvalid, -1 ); otv_ClassDef_validate( table + BacktrackClassDef, otvalid ); otv_ClassDef_validate( table + InputClassDef, otvalid ); otv_ClassDef_validate( table + LookaheadClassDef, otvalid ); OTV_LIMIT_CHECK( ChainClassSetCount * 2 ); otvalid->nesting_level++; func = otvalid->func[otvalid->nesting_level]; otvalid->extra1 = otvalid->lookup_count; for ( ; ChainClassSetCount > 0; ChainClassSetCount-- ) { FT_UInt offset = FT_NEXT_USHORT( p ); if ( offset ) func( table + offset, otvalid ); } otvalid->nesting_level--; OTV_EXIT; } /* uses otvalid->lookup_count */ FT_LOCAL_DEF( void ) otv_u_x_Ox_y_Oy_z_Oz_p_sp( FT_Bytes table, OTV_Validator otvalid ) { FT_Bytes p = table; FT_UInt BacktrackGlyphCount, InputGlyphCount, LookaheadGlyphCount; FT_UInt count1, count2; OTV_ENTER; p += 2; /* skip Format */ OTV_LIMIT_CHECK( 2 ); BacktrackGlyphCount = FT_NEXT_USHORT( p ); OTV_TRACE(( " (BacktrackGlyphCount = %d)\n", BacktrackGlyphCount )); OTV_LIMIT_CHECK( BacktrackGlyphCount * 2 + 2 ); for ( ; BacktrackGlyphCount > 0; BacktrackGlyphCount-- ) otv_Coverage_validate( table + FT_NEXT_USHORT( p ), otvalid, -1 ); InputGlyphCount = FT_NEXT_USHORT( p ); OTV_TRACE(( " (InputGlyphCount = %d)\n", InputGlyphCount )); OTV_LIMIT_CHECK( InputGlyphCount * 2 + 2 ); for ( count1 = InputGlyphCount; count1 > 0; count1-- ) otv_Coverage_validate( table + FT_NEXT_USHORT( p ), otvalid, -1 ); LookaheadGlyphCount = FT_NEXT_USHORT( p ); OTV_TRACE(( " (LookaheadGlyphCount = %d)\n", LookaheadGlyphCount )); OTV_LIMIT_CHECK( LookaheadGlyphCount * 2 + 2 ); for ( ; LookaheadGlyphCount > 0; LookaheadGlyphCount-- ) otv_Coverage_validate( table + FT_NEXT_USHORT( p ), otvalid, -1 ); count2 = FT_NEXT_USHORT( p ); OTV_TRACE(( " (Count = %d)\n", count2 )); OTV_LIMIT_CHECK( count2 * 4 ); for ( ; count2 > 0; count2-- ) { if ( FT_NEXT_USHORT( p ) >= InputGlyphCount ) FT_INVALID_DATA; if ( FT_NEXT_USHORT( p ) >= otvalid->lookup_count ) FT_INVALID_DATA; } OTV_EXIT; } FT_LOCAL_DEF( FT_UInt ) otv_GSUBGPOS_get_Lookup_count( FT_Bytes table ) { FT_Bytes p = table + 8; return otv_LookupList_get_count( table + FT_NEXT_USHORT( p ) ); } FT_LOCAL_DEF( FT_UInt ) otv_GSUBGPOS_have_MarkAttachmentType_flag( FT_Bytes table ) { FT_Bytes p, lookup; FT_UInt count; if ( !table ) return 0; /* LookupList */ p = table + 8; table += FT_NEXT_USHORT( p ); /* LookupCount */ p = table; count = FT_NEXT_USHORT( p ); for ( ; count > 0; count-- ) { FT_Bytes oldp; /* Lookup */ lookup = table + FT_NEXT_USHORT( p ); oldp = p; /* LookupFlag */ p = lookup + 2; if ( FT_NEXT_USHORT( p ) & 0xFF00U ) return 1; p = oldp; } return 0; } /* END */
{ "pile_set_name": "Github" }