text
stringlengths
2
100k
meta
dict
#!/bin/bash pushd src make -f Makefile \ CC="${CC}" \ CFLAGS="${CFLAGS} -O2 -g -Wall -D__USE_FIXED_PROTOTYPES__" \ LDFLAGS="${LDFLAGS}" mkdir -p "${PREFIX}/bin" cp \ long_seq_tm_test \ ntdpal \ oligotm \ primer3_core \ "${PREFIX}/bin/"
{ "pile_set_name": "Github" }
(* TEST * expect *) (* Implicit unpack allows the signature in (val ...) expressions to be omitted. It also adds (module M : S) and (module M) patterns, relying on implicit (val ...) for the implementation. Such patterns can only be used in function definition, match clauses, and let ... in. New: implicit pack is also supported, and you only need to be able to infer the the module type path from the context. *) (* ocaml -principal *) (* Use a module pattern *) let sort (type s) (module Set : Set.S with type elt = s) l = Set.elements (List.fold_right Set.add l Set.empty) ;; [%%expect{| val sort : (module Set.S with type elt = 's) -> 's list -> 's list = <fun> |}];; (* No real improvement here? *) let make_set (type s) cmp : (module Set.S with type elt = s) = (module Set.Make (struct type t = s let compare = cmp end)) ;; [%%expect{| val make_set : ('s -> 's -> int) -> (module Set.S with type elt = 's) = <fun> |}];; (* No type annotation here *) let sort_cmp (type s) cmp = sort (module Set.Make (struct type t = s let compare = cmp end)) ;; [%%expect{| val sort_cmp : ('s -> 's -> int) -> 's list -> 's list = <fun> |}];; module type S = sig type t val x : t end;; [%%expect{| module type S = sig type t val x : t end |}];; let f (module M : S with type t = int) = M.x;; [%%expect{| val f : (module S with type t = int) -> int = <fun> |}];; let f (module M : S with type t = 'a) = M.x;; (* Error *) [%%expect{| Line 1, characters 6-37: 1 | let f (module M : S with type t = 'a) = M.x;; (* Error *) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Error: The type of this packed module contains variables: (module S with type t = 'a) |}];; let f (type a) (module M : S with type t = a) = M.x;; f (module struct type t = int let x = 1 end);; [%%expect{| val f : (module S with type t = 'a) -> 'a = <fun> - : int = 1 |}];; (***) type 'a s = {s: (module S with type t = 'a)};; [%%expect{| type 'a s = { s : (module S with type t = 'a); } |}];; {s=(module struct type t = int let x = 1 end)};; [%%expect{| - : int s = {s = <module>} |}];; let f {s=(module M)} = M.x;; (* Error *) [%%expect{| Line 1, characters 9-19: 1 | let f {s=(module M)} = M.x;; (* Error *) ^^^^^^^^^^ Error: The type of this packed module contains variables: (module S with type t = 'a) |}];; let f (type a) ({s=(module M)} : a s) = M.x;; [%%expect{| val f : 'a s -> 'a = <fun> |}];; type s = {s: (module S with type t = int)};; let f {s=(module M)} = M.x;; let f {s=(module M)} {s=(module N)} = M.x + N.x;; [%%expect{| type s = { s : (module S with type t = int); } val f : s -> int = <fun> val f : s -> s -> int = <fun> |}];; (***) module type S = sig val x : int end;; [%%expect{| module type S = sig val x : int end |}];; let f (module M : S) y (module N : S) = M.x + y + N.x;; [%%expect{| val f : (module S) -> int -> (module S) -> int = <fun> |}];; let m = (module struct let x = 3 end);; (* Error *) [%%expect{| Line 1, characters 8-37: 1 | let m = (module struct let x = 3 end);; (* Error *) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Error: The signature for this packaged module couldn't be inferred. |}];; let m = (module struct let x = 3 end : S);; [%%expect{| val m : (module S) = <module> |}];; f m 1 m;; [%%expect{| - : int = 7 |}];; f m 1 (module struct let x = 2 end);; [%%expect{| - : int = 6 |}];; (***) let (module M) = m in M.x;; [%%expect{| - : int = 3 |}];; let (module M) = m;; (* Error: only allowed in [let .. in] *) [%%expect{| Line 1, characters 4-14: 1 | let (module M) = m;; (* Error: only allowed in [let .. in] *) ^^^^^^^^^^ Error: Modules are not allowed in this pattern. |}];; class c = let (module M) = m in object end;; (* Error again *) [%%expect{| Line 1, characters 14-24: 1 | class c = let (module M) = m in object end;; (* Error again *) ^^^^^^^^^^ Error: Modules are not allowed in this pattern. |}];; module M = (val m);; [%%expect{| module M : S |}];; (***) module type S' = sig val f : int -> int end;; [%%expect{| module type S' = sig val f : int -> int end |}];; (* Even works with recursion, but must be fully explicit *) let rec (module M : S') = (module struct let f n = if n <= 0 then 1 else n * M.f (n-1) end : S') in M.f 3;; [%%expect{| - : int = 6 |}];; (* Subtyping *) module type S = sig type t type u val x : t * u end let f (l : (module S with type t = int and type u = bool) list) = (l :> (module S with type u = bool) list) ;; [%%expect{| module type S = sig type t type u val x : t * u end val f : (module S with type t = int and type u = bool) list -> (module S with type u = bool) list = <fun> |}];; (* GADTs from the manual *) (* the only modification is in to_string *) module TypEq : sig type ('a, 'b) t val apply: ('a, 'b) t -> 'a -> 'b val refl: ('a, 'a) t val sym: ('a, 'b) t -> ('b, 'a) t end = struct type ('a, 'b) t = ('a -> 'b) * ('b -> 'a) let refl = (fun x -> x), (fun x -> x) let apply (f, _) x = f x let sym (f, g) = (g, f) end module rec Typ : sig module type PAIR = sig type t and t1 and t2 val eq: (t, t1 * t2) TypEq.t val t1: t1 Typ.typ val t2: t2 Typ.typ end type 'a typ = | Int of ('a, int) TypEq.t | String of ('a, string) TypEq.t | Pair of (module PAIR with type t = 'a) end = Typ let int = Typ.Int TypEq.refl let str = Typ.String TypEq.refl let pair (type s1) (type s2) t1 t2 = let module P = struct type t = s1 * s2 type t1 = s1 type t2 = s2 let eq = TypEq.refl let t1 = t1 let t2 = t2 end in Typ.Pair (module P) open Typ let rec to_string: 'a. 'a Typ.typ -> 'a -> string = fun (type s) t x -> match (t : s typ) with | Int eq -> Int.to_string (TypEq.apply eq x) | String eq -> Printf.sprintf "%S" (TypEq.apply eq x) | Pair (module P) -> let (x1, x2) = TypEq.apply P.eq x in Printf.sprintf "(%s,%s)" (to_string P.t1 x1) (to_string P.t2 x2) ;; [%%expect{| module TypEq : sig type ('a, 'b) t val apply : ('a, 'b) t -> 'a -> 'b val refl : ('a, 'a) t val sym : ('a, 'b) t -> ('b, 'a) t end module rec Typ : sig module type PAIR = sig type t and t1 and t2 val eq : (t, t1 * t2) TypEq.t val t1 : t1 Typ.typ val t2 : t2 Typ.typ end type 'a typ = Int of ('a, int) TypEq.t | String of ('a, string) TypEq.t | Pair of (module PAIR with type t = 'a) end val int : int Typ.typ = Typ.Int <abstr> val str : string Typ.typ = Typ.String <abstr> val pair : 's1 Typ.typ -> 's2 Typ.typ -> ('s1 * 's2) Typ.typ = <fun> val to_string : 'a Typ.typ -> 'a -> string = <fun> |}];; (* Wrapping maps *) module type MapT = sig include Map.S type data type map val of_t : data t -> map val to_t : map -> data t end type ('k,'d,'m) map = (module MapT with type key = 'k and type data = 'd and type map = 'm) let add (type k) (type d) (type m) (m:(k,d,m) map) x y s = let module M = (val m:MapT with type key = k and type data = d and type map = m) in M.of_t (M.add x y (M.to_t s)) module SSMap = struct include Map.Make(String) type data = string type map = data t let of_t x = x let to_t x = x end ;; [%%expect{| module type MapT = sig type key type +'a t val empty : 'a t val is_empty : 'a t -> bool val mem : key -> 'a t -> bool val add : key -> 'a -> 'a t -> 'a t val update : key -> ('a option -> 'a option) -> 'a t -> 'a t val singleton : key -> 'a -> 'a t val remove : key -> 'a t -> 'a t val merge : (key -> 'a option -> 'b option -> 'c option) -> 'a t -> 'b t -> 'c t val union : (key -> 'a -> 'a -> 'a option) -> 'a t -> 'a t -> 'a t val compare : ('a -> 'a -> int) -> 'a t -> 'a t -> int val equal : ('a -> 'a -> bool) -> 'a t -> 'a t -> bool val iter : (key -> 'a -> unit) -> 'a t -> unit val fold : (key -> 'a -> 'b -> 'b) -> 'a t -> 'b -> 'b val for_all : (key -> 'a -> bool) -> 'a t -> bool val exists : (key -> 'a -> bool) -> 'a t -> bool val filter : (key -> 'a -> bool) -> 'a t -> 'a t val partition : (key -> 'a -> bool) -> 'a t -> 'a t * 'a t val cardinal : 'a t -> int val bindings : 'a t -> (key * 'a) list val min_binding : 'a t -> key * 'a val min_binding_opt : 'a t -> (key * 'a) option val max_binding : 'a t -> key * 'a val max_binding_opt : 'a t -> (key * 'a) option val choose : 'a t -> key * 'a val choose_opt : 'a t -> (key * 'a) option val split : key -> 'a t -> 'a t * 'a option * 'a t val find : key -> 'a t -> 'a val find_opt : key -> 'a t -> 'a option val find_first : (key -> bool) -> 'a t -> key * 'a val find_first_opt : (key -> bool) -> 'a t -> (key * 'a) option val find_last : (key -> bool) -> 'a t -> key * 'a val find_last_opt : (key -> bool) -> 'a t -> (key * 'a) option val map : ('a -> 'b) -> 'a t -> 'b t val mapi : (key -> 'a -> 'b) -> 'a t -> 'b t val to_seq : 'a t -> (key * 'a) Seq.t val to_seq_from : key -> 'a t -> (key * 'a) Seq.t val add_seq : (key * 'a) Seq.t -> 'a t -> 'a t val of_seq : (key * 'a) Seq.t -> 'a t type data type map val of_t : data t -> map val to_t : map -> data t end type ('k, 'd, 'm) map = (module MapT with type data = 'd and type key = 'k and type map = 'm) val add : ('k, 'd, 'm) map -> 'k -> 'd -> 'm -> 'm = <fun> module SSMap : sig type key = String.t type 'a t = 'a Map.Make(String).t val empty : 'a t val is_empty : 'a t -> bool val mem : key -> 'a t -> bool val add : key -> 'a -> 'a t -> 'a t val update : key -> ('a option -> 'a option) -> 'a t -> 'a t val singleton : key -> 'a -> 'a t val remove : key -> 'a t -> 'a t val merge : (key -> 'a option -> 'b option -> 'c option) -> 'a t -> 'b t -> 'c t val union : (key -> 'a -> 'a -> 'a option) -> 'a t -> 'a t -> 'a t val compare : ('a -> 'a -> int) -> 'a t -> 'a t -> int val equal : ('a -> 'a -> bool) -> 'a t -> 'a t -> bool val iter : (key -> 'a -> unit) -> 'a t -> unit val fold : (key -> 'a -> 'b -> 'b) -> 'a t -> 'b -> 'b val for_all : (key -> 'a -> bool) -> 'a t -> bool val exists : (key -> 'a -> bool) -> 'a t -> bool val filter : (key -> 'a -> bool) -> 'a t -> 'a t val partition : (key -> 'a -> bool) -> 'a t -> 'a t * 'a t val cardinal : 'a t -> int val bindings : 'a t -> (key * 'a) list val min_binding : 'a t -> key * 'a val min_binding_opt : 'a t -> (key * 'a) option val max_binding : 'a t -> key * 'a val max_binding_opt : 'a t -> (key * 'a) option val choose : 'a t -> key * 'a val choose_opt : 'a t -> (key * 'a) option val split : key -> 'a t -> 'a t * 'a option * 'a t val find : key -> 'a t -> 'a val find_opt : key -> 'a t -> 'a option val find_first : (key -> bool) -> 'a t -> key * 'a val find_first_opt : (key -> bool) -> 'a t -> (key * 'a) option val find_last : (key -> bool) -> 'a t -> key * 'a val find_last_opt : (key -> bool) -> 'a t -> (key * 'a) option val map : ('a -> 'b) -> 'a t -> 'b t val mapi : (key -> 'a -> 'b) -> 'a t -> 'b t val to_seq : 'a t -> (key * 'a) Seq.t val to_seq_from : key -> 'a t -> (key * 'a) Seq.t val add_seq : (key * 'a) Seq.t -> 'a t -> 'a t val of_seq : (key * 'a) Seq.t -> 'a t type data = string type map = data t val of_t : 'a -> 'a val to_t : 'a -> 'a end |}];; let ssmap = (module SSMap: MapT with type key = string and type data = string and type map = SSMap.map) ;; [%%expect{| val ssmap : (module MapT with type data = string and type key = string and type map = SSMap.map) = <module> |}];; let ssmap = (module struct include SSMap end : MapT with type key = string and type data = string and type map = SSMap.map) ;; [%%expect{| val ssmap : (module MapT with type data = string and type key = string and type map = SSMap.map) = <module> |}];; let ssmap = (let module S = struct include SSMap end in (module S) : (module MapT with type key = string and type data = string and type map = SSMap.map)) ;; [%%expect{| val ssmap : (module MapT with type data = string and type key = string and type map = SSMap.map) = <module> |}];; let ssmap = (module SSMap: MapT with type key = _ and type data = _ and type map = _) ;; [%%expect{| val ssmap : (module MapT with type data = SSMap.data and type key = SSMap.key and type map = SSMap.map) = <module> |}];; let ssmap : (_,_,_) map = (module SSMap);; [%%expect{| val ssmap : (SSMap.key, SSMap.data, SSMap.map) map = <module> |}];; add ssmap;; [%%expect{| - : SSMap.key -> SSMap.data -> SSMap.map -> SSMap.map = <fun> |}];; (*****) module type S = sig type t end let x = (module struct type elt = A type t = elt list end : S with type t = _ list) ;; [%%expect{| module type S = sig type t end Line 4, characters 10-51: 4 | (module struct type elt = A type t = elt list end : S with type t = _ list) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Error: The type t in this module cannot be exported. Its type contains local dependencies: elt list |}];; type 'a s = (module S with type t = 'a);; [%%expect{| type 'a s = (module S with type t = 'a) |}];; let x : 'a s = (module struct type t = int end);; [%%expect{| val x : int s = <module> |}];; let x : 'a s = (module struct type t = A end);; [%%expect{| Line 1, characters 23-44: 1 | let x : 'a s = (module struct type t = A end);; ^^^^^^^^^^^^^^^^^^^^^ Error: The type t in this module cannot be exported. Its type contains local dependencies: t |}];; let x : 'a s = (module struct end);; [%%expect{| Line 1, characters 23-33: 1 | let x : 'a s = (module struct end);; ^^^^^^^^^^ Error: Signature mismatch: Modules do not match: sig end is not included in S The type `t' is required but not provided |}];;
{ "pile_set_name": "Github" }
// Copyright 2016 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 slack provides constants for using OAuth2 to access Slack. package slack // import "golang.org/x/oauth2/slack" import ( "golang.org/x/oauth2" ) // Endpoint is Slack's OAuth 2.0 endpoint. var Endpoint = oauth2.Endpoint{ AuthURL: "https://slack.com/oauth/authorize", TokenURL: "https://slack.com/api/oauth.access", }
{ "pile_set_name": "Github" }
/* Implement the stpcpy function. Copyright (C) 2003-2020 Free Software Foundation, Inc. Written by Kaveh R. Ghazi <[email protected]>. This file is part of the libiberty library. Libiberty is free software; you can redistribute it and/or modify it under the terms of the GNU Library General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. Libiberty is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Library General Public License for more details. You should have received a copy of the GNU Library General Public License along with libiberty; see the file COPYING.LIB. If not, write to the Free Software Foundation, Inc., 51 Franklin Street - Fifth Floor, Boston, MA 02110-1301, USA. */ /* @deftypefn Supplemental char* stpcpy (char *@var{dst}, const char *@var{src}) Copies the string @var{src} into @var{dst}. Returns a pointer to @var{dst} + strlen(@var{src}). @end deftypefn */ #include <ansidecl.h> #include <stddef.h> extern size_t strlen (const char *); extern PTR memcpy (PTR, const PTR, size_t); char * stpcpy (char *dst, const char *src) { const size_t len = strlen (src); return (char *) memcpy (dst, src, len + 1) + len; }
{ "pile_set_name": "Github" }
define(['amd-utils/array/find'], function (find) { describe('array/find', function () { it('should return first match', function () { var obj = {a : 'b'}, arr = [123, 'foo', 'bar', obj]; expect( find(arr, function(val){ return val === 123; }) ).toEqual( 123 ); expect( find(arr, function(val){ return typeof val === 'string'; }) ).toEqual( 'foo' ); expect( find(arr, function(val){ return val.a === 'b'; }) ).toEqual( obj ); }); }); });
{ "pile_set_name": "Github" }
" Vim syntax file " Language: Comshare Dimension Definition Language " Maintainer: Raul Segura Acevedo <[email protected]> " Last change: 2016 Sep 20 " quit when a syntax file was already loaded if exists("b:current_syntax") finish endif sy case ignore sy sync fromstart sy keyword cdlStatement dimension hierarchy group grouphierarchy schedule class sy keyword cdlType add update file category main altername removeall required notrequired sy keyword cdlConditional if then elseif else endif and or not cons rpt xlt sy keyword cdlFunction ChildOf IChildOf LeafChildOf DescendantOf IDescendantOf LeafDescendantOf MemberIs CountOf sy keyword cdlIdentifier contained id name desc description xlttype precision symbol curr_ name group_name rate_name sy keyword cdlIdentifier contained xcheck endbal accounttype natsign consolidate formula pctown usage periodicity sy match cdlIdentifier contained 'child\s*name' sy match cdlIdentifier contained 'parent\s*name' sy match cdlIdentifier contained 'grp\s*description' sy match cdlIdentifier contained 'grpchild\s*name' sy match cdlIdentifier contained 'grpparent\s*name' sy match cdlIdentifier contained 'preceding\s*member' sy match cdlIdentifier contained 'unit\s*name' sy match cdlIdentifier contained 'unit\s*id' sy match cdlIdentifier contained 'schedule\s*name' sy match cdlIdentifier contained 'schedule\s*id' sy match cdlString /\[[^]]*]/ contains=cdlRestricted,cdlNotSupported sy match cdlRestricted contained /[&*,_]/ " not supported sy match cdlNotSupported contained /[:"!']/ sy keyword cdlTodo contained TODO FIXME XXX sy cluster cdlCommentGroup contains=cdlTodo sy match cdlComment '//.*' contains=@cdlCommentGroup sy region cdlComment start="/\*" end="\*/" contains=@cdlCommentGroup fold sy match cdlCommentE "\*/" sy region cdlParen transparent start='(' end=')' contains=ALLBUT,cdlParenE,cdlRestricted,cdlNotSupported "sy region cdlParen transparent start='(' end=')' contains=cdlIdentifier,cdlComment,cdlParenWordE sy match cdlParenE ")" "sy match cdlParenWordE contained "\k\+" sy keyword cdlFxType allocation downfoot expr xltgain "sy keyword cdlFxType contained allocation downfoot expr xltgain "sy region cdlFx transparent start='\k\+(' end=')' contains=cdlConditional,cdlFunction,cdlString,cdlComment,cdlFxType set foldmethod=expr set foldexpr=(getline(v:lnum+1)=~'{'\|\|getline(v:lnum)=~'//\\s\\*\\{5}.*table')?'>1':1 %foldo! set foldmethod=manual let b:match_words='\<if\>:\<then\>:\<elseif\>:\<else\>:\<endif\>' " Define the default highlighting. " Only when an item doesn't have highlighting yet hi def link cdlStatement Statement hi def link cdlType Type hi def link cdlFxType Type hi def link cdlIdentifier Identifier hi def link cdlString String hi def link cdlRestricted WarningMsg hi def link cdlNotSupported ErrorMsg hi def link cdlTodo Todo hi def link cdlComment Comment hi def link cdlCommentE ErrorMsg hi def link cdlParenE ErrorMsg hi def link cdlParenWordE ErrorMsg hi def link cdlFunction Function hi def link cdlConditional Conditional let b:current_syntax = "cdl" " vim: ts=8
{ "pile_set_name": "Github" }
/* Copyright The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ // Code generated by client-gen. DO NOT EDIT. package v1alpha1 import ( v1alpha1 "k8s.io/api/settings/v1alpha1" "k8s.io/client-go/kubernetes/scheme" rest "k8s.io/client-go/rest" ) type SettingsV1alpha1Interface interface { RESTClient() rest.Interface PodPresetsGetter } // SettingsV1alpha1Client is used to interact with features provided by the settings.k8s.io group. type SettingsV1alpha1Client struct { restClient rest.Interface } func (c *SettingsV1alpha1Client) PodPresets(namespace string) PodPresetInterface { return newPodPresets(c, namespace) } // NewForConfig creates a new SettingsV1alpha1Client for the given config. func NewForConfig(c *rest.Config) (*SettingsV1alpha1Client, error) { config := *c if err := setConfigDefaults(&config); err != nil { return nil, err } client, err := rest.RESTClientFor(&config) if err != nil { return nil, err } return &SettingsV1alpha1Client{client}, nil } // NewForConfigOrDie creates a new SettingsV1alpha1Client for the given config and // panics if there is an error in the config. func NewForConfigOrDie(c *rest.Config) *SettingsV1alpha1Client { client, err := NewForConfig(c) if err != nil { panic(err) } return client } // New creates a new SettingsV1alpha1Client for the given RESTClient. func New(c rest.Interface) *SettingsV1alpha1Client { return &SettingsV1alpha1Client{c} } func setConfigDefaults(config *rest.Config) error { gv := v1alpha1.SchemeGroupVersion config.GroupVersion = &gv config.APIPath = "/apis" config.NegotiatedSerializer = scheme.Codecs.WithoutConversion() if config.UserAgent == "" { config.UserAgent = rest.DefaultKubernetesUserAgent() } return nil } // RESTClient returns a RESTClient that is used to communicate // with API server by this client implementation. func (c *SettingsV1alpha1Client) RESTClient() rest.Interface { if c == nil { return nil } return c.restClient }
{ "pile_set_name": "Github" }
# # Example of a Wasm Http Filter. # kind: Example
{ "pile_set_name": "Github" }
.\" .\" Copyright (c) 2009 by Daniel Stenberg .\" .TH libssh2_knownhost_readline 3 "28 May 2009" "libssh2 1.2" "libssh2 manual" .SH NAME libssh2_knownhost_readline - read a known host line .SH SYNOPSIS #include <libssh2.h> int libssh2_knownhost_readline(LIBSSH2_KNOWNHOSTS *hosts, const char *line, size_t len, int type): .SH DESCRIPTION Tell libssh2 to read a buffer as it if is a line from a known hosts file. \fIline\fP points to the start of the line \fIlen\fP is the length of the line in bytes \fItype\fP specifies what file type it is, and \fILIBSSH2_KNOWNHOST_FILE_OPENSSH\fP is the only currently supported format. This file is normally found named ~/.ssh/known_hosts .SH RETURN VALUE Returns a regular libssh2 error code, where negative values are error codes and 0 indicates success. .SH AVAILABILITY Added in libssh2 1.2 .SH SEE ALSO .BR libssh2_knownhost_get(3) .BR libssh2_knownhost_writeline(3) .BR libssh2_knownhost_readfile(3)
{ "pile_set_name": "Github" }
# Go App Engine packages [![Build Status](https://travis-ci.org/golang/appengine.svg)](https://travis-ci.org/golang/appengine) This repository supports the Go runtime on *App Engine standard*. It provides APIs for interacting with App Engine services. Its canonical import path is `google.golang.org/appengine`. See https://cloud.google.com/appengine/docs/go/ for more information. File issue reports and feature requests on the [GitHub's issue tracker](https://github.com/golang/appengine/issues). ## Upgrading an App Engine app to the flexible environment This package does not work on *App Engine flexible*. There are many differences between the App Engine standard environment and the flexible environment. See the [documentation on upgrading to the flexible environment](https://cloud.google.com/appengine/docs/flexible/go/upgrading). ## Directory structure The top level directory of this repository is the `appengine` package. It contains the basic APIs (e.g. `appengine.NewContext`) that apply across APIs. Specific API packages are in subdirectories (e.g. `datastore`). There is an `internal` subdirectory that contains service protocol buffers, plus packages required for connectivity to make API calls. App Engine apps should not directly import any package under `internal`. ## Updating from legacy (`import "appengine"`) packages If you're currently using the bare `appengine` packages (that is, not these ones, imported via `google.golang.org/appengine`), then you can use the `aefix` tool to help automate an upgrade to these packages. Run `go get google.golang.org/appengine/cmd/aefix` to install it. ### 1. Update import paths The import paths for App Engine packages are now fully qualified, based at `google.golang.org/appengine`. You will need to update your code to use import paths starting with that; for instance, code importing `appengine/datastore` will now need to import `google.golang.org/appengine/datastore`. ### 2. Update code using deprecated, removed or modified APIs Most App Engine services are available with exactly the same API. A few APIs were cleaned up, and there are some differences: * `appengine.Context` has been replaced with the `Context` type from `golang.org/x/net/context`. * Logging methods that were on `appengine.Context` are now functions in `google.golang.org/appengine/log`. * `appengine.Timeout` has been removed. Use `context.WithTimeout` instead. * `appengine.Datacenter` now takes a `context.Context` argument. * `datastore.PropertyLoadSaver` has been simplified to use slices in place of channels. * `delay.Call` now returns an error. * `search.FieldLoadSaver` now handles document metadata. * `urlfetch.Transport` no longer has a Deadline field; set a deadline on the `context.Context` instead. * `aetest` no longer declares its own Context type, and uses the standard one instead. * `taskqueue.QueueStats` no longer takes a maxTasks argument. That argument has been deprecated and unused for a long time. * `appengine.BackendHostname` and `appengine.BackendInstance` were for the deprecated backends feature. Use `appengine.ModuleHostname`and `appengine.ModuleName` instead. * Most of `appengine/file` and parts of `appengine/blobstore` are deprecated. Use [Google Cloud Storage](https://godoc.org/cloud.google.com/go/storage) if the feature you require is not present in the new [blobstore package](https://google.golang.org/appengine/blobstore). * `appengine/socket` is not required on App Engine flexible environment / Managed VMs. Use the standard `net` package instead.
{ "pile_set_name": "Github" }
{"name":"koibumi-socks-core","vers":"0.0.0","deps":[],"cksum":"4d749dade1fd93b35cb1de983140b7ac3a2b9cd1cde4a6ba93f10a2d2d0c52b2","features":{},"yanked":false,"links":null} {"name":"koibumi-socks-core","vers":"0.0.1","deps":[],"cksum":"fbc0c26d3ea1bd0bc18def4511a8e02e03350cea54b0bf6724f420dfbcc88b4d","features":{},"yanked":false,"links":null}
{ "pile_set_name": "Github" }
Overview -------- Build tests for drivers and sensors on all platforms. This test might now work for some of the drivers, those need to be addressed in other tests targeting those special cases. Tests ----- drivers: build all drivers sensors_a_m: build sensors with name beginning a through m. sensors_n_z: build sensors with name beginning n through z. sensors_trigger: build sensors with trigger option enabled
{ "pile_set_name": "Github" }
'use strict'; var re = /foo/; module.exports = function () { if (typeof re.match !== 'function') return false; return re.match('barfoobar') && !re.match('elo'); };
{ "pile_set_name": "Github" }
#!/usr/bin/env python ''' @ author: Kshitij Kumar @ email: [email protected], [email protected] @ purpose: A module intended to read and parse the Chrome history database for each user on disk. ''' # IMPORT FUNCTIONS FROM COMMON.FUNCTIONS from common.functions import stats2 from common.functions import chrome_time from common.functions import firefox_time from common.functions import multiglob from common.functions import finditem # IMPORT STATIC VARIABLES FROM MAIN from __main__ import inputdir from __main__ import outputdir from __main__ import forensic_mode from __main__ import no_tarball from __main__ import quiet from __main__ import archive from __main__ import startTime from __main__ import full_prefix from __main__ import data_writer import os import itertools import json import ast import glob import sqlite3 import shutil import logging import pytz import time import traceback import dateutil.parser as parser from collections import OrderedDict _modName = __name__.split('_')[-2] _modVers = '.'.join(list(__name__.split('_')[-1][1:])) log = logging.getLogger(_modName) def get_column_headers(db, column): try: col_headers = sqlite3.connect(db).cursor().execute('SELECT * from {0}'.format(column)) names = list(map(lambda x: x[0], col_headers.description)) except sqlite3.OperationalError: log.debug("Column '{0}' was not found in database.".format(column)) names = [] return names def get_chrome_version(history_db): version = sqlite3.connect(history_db).cursor().execute( 'SELECT key, value FROM meta where key="version"').fetchall() ver = OrderedDict(version)['version'] log.debug("Chrome History database meta version {0} identified.".format(ver)) return ver def connect_to_db(chrome_location): try: log.debug("Trying to connect to {0} directly...".format(chrome_location)) history_db = chrome_location ver = get_chrome_version(history_db) log.debug("Successfully connected.") except sqlite3.OperationalError: error = [x for x in traceback.format_exc().split('\n') if x.startswith("OperationalError")] log.debug("Could not connect [{0}].".format(error[0])) if "database is locked" in error[0]: tmpdb = os.path.basename(chrome_location)+'-tmp' log.debug("Trying to connect to db copied to temp location...") shutil.copyfile(history_db, os.path.join(outputdir, tmpdb)) history_db = os.path.join(outputdir, tmpdb) try: ver = get_chrome_version(history_db) log.debug("Successfully connected.") except: error = [x for x in traceback.format_exc().split('\n') if x.startswith("OperationalError")] log.debug("Could not connect [{0}].".format(error[0])) log.error("Module fatal error: cannot parse database.") history_db = None return history_db def pull_visit_history(history_db, user, prof, urls_output, urls_headers): log.debug("Executing sqlite query for visit history...") try: urls_data = sqlite3.connect(history_db).cursor().execute( 'SELECT visit_time, urls.url, title, visit_duration, visit_count, \ typed_count, urls.last_visit_time, term \ from visits left join urls on visits.url = urls.id \ left join keyword_search_terms on keyword_search_terms.url_id = urls.id' ).fetchall() log.debug("Success. Found {0} lines of data.".format(len(urls_data))) except Exception, e: log.debug('Failed to run query: {0}'.format([traceback.format_exc()])) u_cnames = get_column_headers(history_db, 'urls') log.debug('Columns available in "{0}" table: {1}'.format('urls2', str(u_cnames))) v_cnames = get_column_headers(history_db, 'visits') log.debug('Columns available in "{0}" table: {1}'.format('visits', str(v_cnames))) k_cnames = get_column_headers(history_db, 'keyword_search_terms') log.debug('Columns available in "{0}" table: {1}'.format('keyword_search_terms', str(k_cnames))) return log.debug("Parsing and writing visits data...") for item in urls_data: record = OrderedDict((h, '') for h in urls_headers) item = list(item) record['user'] = user record['profile'] = prof record['visit_time'] = chrome_time(item[0]) record['url'] = item[1] record['title'] = item[2].encode('utf-8') record['visit_duration'] = time.strftime("%H:%M:%S", time.gmtime(item[3] / 1000000)) record['visit_count'] = item[4] record['typed_count'] = item[5] record['last_visit_time'] = chrome_time(item[6]) search_term = item[7] if search_term is not None: record['search_term'] = item[7].encode('utf-8') else: record['search_term'] = '' urls_output.write_entry(record.values()) log.debug("Done.") def pull_download_history(history_db, user, prof, downloads_output, downloads_headers): log.debug("Executing sqlite query for download history...") try: downloads_data = sqlite3.connect(history_db).cursor().execute( 'SELECT current_path, target_path, start_time, end_time, danger_type, opened, \ last_modified, referrer, tab_url, tab_referrer_url, site_url, url from downloads \ left join downloads_url_chains on downloads_url_chains.id = downloads.id' ).fetchall() log.debug("Success. Found {0} lines of data.".format(len(downloads_data))) except Exception, e: log.debug('Failed to run query: {0}'.format([traceback.format_exc()])) duc_cnames = get_column_headers(history_db, 'downloads_url_chains') log.debug('Columns available: {0}'.format(str(duc_cnames))) d_cnames = get_column_headers(history_db, 'downloads') log.debug('Columns available: {0}'.format(str(d_cnames))) return log.debug("Parsing and writing downloads data...") for item in downloads_data: record = OrderedDict((h, '') for h in downloads_headers) item = list(item) record['user'] = user record['profile'] = prof record['current_path'] = item[0].encode('utf-8') record['download_path'] = item[1].encode('utf-8') record['download_started'] = chrome_time(item[2]) record['download_finished'] = chrome_time(item[3]) record['danger_type'] = item[4] record['opened'] = item[5] if item[6] != '': last_modified = parser.parse(item[6]).replace(tzinfo=pytz.UTC) record['last_modified'] = last_modified.isoformat().replace('+00:00', 'Z') else: record['last_modified'] = '' record['referrer'] = item[7] record['tab_url'] = item[8] record['tab_referrer_url'] = item[9] record['download_url'] = item[10] record['url'] = item[11] downloads_output.write_entry(record.values()) log.debug("Done.") def parse_profiles(profile_data, user, profile_output, profile_headers): log.debug("Success. Found metadata for {0} profiles.".format(len(profile_data.items()))) for k,v in profile_data.items(): record = OrderedDict((h, '') for h in profile_headers) record['user'] = user record['profile'] = k for key, val in v.items(): if key in profile_headers: record[key] = val record['active_time'] = firefox_time(record['active_time']*1000000) profile_output.write_entry(record.values()) def module(chrome_location): # for all chrome dirs on disk, parse their local state files profile_headers = ['user','profile','active_time','is_using_default_avatar','is_omitted_from_profile_list', 'name','gaia_picture_file_name','user_name','managed_user_id','gaia_name', 'avatar_icon','gaia_id','local_auth_credentials','gaia_given_name', 'is_using_default_name','background_apps','is_ephemeral'] profile_output = data_writer('browser_chrome_profiles', profile_headers) for c in chrome_location: userpath = c.split('/') userindex = len(userpath) - 1 - userpath[::-1].index('Users') + 1 user = userpath[userindex] log.debug("Parsing Chrome Local State data under {0} user.".format(user)) localstate_file = os.path.join(c, 'Local State') if os.path.exists(localstate_file): with open(localstate_file, 'r') as data: jdata = json.loads(data.read()) chrome_ver = finditem(jdata, "stats_version") log.debug("Chrome version {0} identified.".format(chrome_ver)) profile_data = finditem(jdata, "info_cache") parse_profiles(profile_data, user, profile_output, profile_headers) else: log.debug("File not found: {0}".format(localstate_file)) # make a full list of all chrome profiles under all chrome dirs full_list_raw = [multiglob(c, ['Default', 'Profile *', 'Guest Profile']) for c in chrome_location] full_list = list(itertools.chain.from_iterable(full_list_raw)) urls_headers = ['user','profile','visit_time','title','url','visit_count','last_visit_time', 'typed_count','visit_duration','search_term'] urls_output = data_writer('browser_chrome_history', urls_headers) downloads_headers = ['user','profile','download_path','current_path','download_started','download_finished', 'danger_type','opened','last_modified','referrer','tab_url','tab_referrer_url', 'download_url','url'] downloads_output = data_writer('browser_chrome_downloads', downloads_headers) for prof in full_list: userpath = prof.split('/') userindex = len(userpath) - 1 - userpath[::-1].index('Users') + 1 user = userpath[userindex] chromeindex = userpath.index('Chrome') + 1 profile = userpath[chromeindex] log.debug("Starting parsing for Chrome history under {0} user.".format(user)) history_db = connect_to_db(os.path.join(prof, 'History')) if history_db: pull_visit_history(history_db, user, profile, urls_output, urls_headers) pull_download_history(history_db, user, profile, downloads_output, downloads_headers) try: os.remove(os.path.join(outputdir, 'History-tmp')) except OSError: pass if __name__ == "__main__": print "This is an AutoMacTC module, and is not meant to be run stand-alone." print "Exiting." sys.exit(0) else: chrome_location = glob.glob( os.path.join(inputdir, 'Users/*/Library/Application Support/Google/Chrome/')) module(chrome_location)
{ "pile_set_name": "Github" }
#!/usr/bin/env python3 # -*- coding: utf-8 -*- # Copyright (C) 2019 tribe29 GmbH - License: GNU General Public License v2 # This file is part of Checkmk (https://checkmk.com). It is subject to the terms and # conditions defined in the file COPYING, which is part of this source code package. # yapf: disable # type: ignore checkname = 'lparstat_aix' info = [ [ u'System', u'configuration:', u'type=Shared', u'mode=Uncapped', u'smt=4', u'lcpu=8', u'mem=16384MB', u'psize=4', u'ent=1.00' ], [ u'%user', u'%sys', u'%wait', u'%idle', u'physc', u'%entc', u'lbusy', u'app', u'vcsw', u'phint', u'%nsp' ], [u'this line is ignored'], ['0.2', '1.2', '0.2', '98.6', '0.02', '9.3', '0.1', '519', '0', '101', '0.00'], ] discovery = {'': [(None, {})], 'cpu_util': [(None, {})]} checks = { '': [(None, None, [ (0, 'Physc: 0.02', [('physc', 0.02, None, None, None, None)]), (0, 'Entc: 9.3%', [('entc', 9.3, None, None, None, None)]), (0, 'Lbusy: 0.1', [('lbusy', 0.1, None, None, None, None)]), (0, 'App: 519.0', [('app', 519.0, None, None, None, None)]), (0, 'Vcsw: 0.0', [('vcsw', 0.0, None, None, None, None)]), (0, 'Phint: 101.0', [('phint', 101.0, None, None, None, None)]), (0, 'Nsp: 0.0%', [('nsp', 0.0, None, None, None, None)]), ]),], 'cpu_util': [ (None, None, [ (0, 'User: 0.2%', [('user', 0.2)]), (0, 'System: 1.2%', [('system', 1.2)]), (0, 'Wait: 0.2%', [('wait', 0.2)]), (0, 'Total CPU: 1.6%', [('util', 1.5999999999999999, None, None, 0, None)]), (0, "Physical CPU consumption: 0.02 CPUs", [('cpu_entitlement_util', 0.02)]), (0, 'Entitlement: 1.00 CPUs', [('cpu_entitlement', 1.0)]), ]), (None, (0.1, 0.3), [ (0, 'User: 0.2%', [('user', 0.2)]), (0, 'System: 1.2%', [('system', 1.2)]), (1, 'Wait: 0.2% (warn/crit at 0.1%/0.3%)', [('wait', 0.2, 0.1, 0.3)]), (0, 'Total CPU: 1.6%', [('util', 1.5999999999999999, None, None, 0, None)]), (0, "Physical CPU consumption: 0.02 CPUs", [('cpu_entitlement_util', 0.02)]), (0, 'Entitlement: 1.00 CPUs', [('cpu_entitlement', 1.0)]), ]), (None, { 'util': (0.5, 1.3) }, [ (0, 'User: 0.2%', [('user', 0.2)]), (0, 'System: 1.2%', [('system', 1.2)]), (0, 'Wait: 0.2%', [('wait', 0.2)]), (2, 'Total CPU: 1.6% (warn/crit at 0.5%/1.3%)', [('util', 1.5999999999999999, 0.5, 1.3, 0, None)]), (0, "Physical CPU consumption: 0.02 CPUs", [('cpu_entitlement_util', 0.02)]), (0, 'Entitlement: 1.00 CPUs', [('cpu_entitlement', 1.0)]), ]), ] }
{ "pile_set_name": "Github" }
{ "logs": [ { "outputFile": "/usr/local/google/home/benweiss/Android/pi-dev/developers/build/prebuilts/gradle/AutofillFramework/Application/build/intermediates/incremental/mergeReleaseResources/merged.dir/values-mk/values-mk.xml", "map": [ { "source": "/usr/local/google/home/benweiss/.gradle/caches/transforms-1/files-1.1/appcompat-v7-28.0.0-alpha1.aar/c05028a6d48feb825ed288e49596b8db/res/values-mk/values-mk.xml", "from": { "startLines": "2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19", "startColumns": "4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4", "startOffsets": "105,213,317,425,511,616,735,818,900,987,1093,1200,1301,1408,1519,1623,1779,1877", "endColumns": "107,103,107,85,104,118,82,81,86,105,106,100,106,110,103,155,97,83", "endOffsets": "208,312,420,506,611,730,813,895,982,1088,1195,1296,1403,1514,1618,1774,1872,1956" } }, { "source": "/usr/local/google/home/benweiss/.gradle/caches/transforms-1/files-1.1/support-compat-28.0.0-alpha1.aar/77db225a0fb1340c5ceeaf0bca144d6f/res/values-mk/values-mk.xml", "from": { "startLines": "2", "startColumns": "4", "startOffsets": "55", "endColumns": "100", "endOffsets": "151" }, "to": { "startLines": "20", "startColumns": "4", "startOffsets": "1961", "endColumns": "100", "endOffsets": "2057" } } ] } ] }
{ "pile_set_name": "Github" }
/******************************************************************************* * Copyright (c) 2000, 2006 IBM Corporation and others. * * This program and the accompanying materials * are made available under the terms of the Eclipse Public License 2.0 * which accompanies this distribution, and is available at * https://www.eclipse.org/legal/epl-2.0/ * * SPDX-License-Identifier: EPL-2.0 * * Contributors: * IBM Corporation - initial API and implementation *******************************************************************************/ package org.eclipse.jdt.core; import org.eclipse.jdt.core.compiler.IProblem; /** * Adapter of the requestor interface <code>ICompletionRequestor</code>. * <p> * This class is intended to be instantiated and subclassed by clients. * </p> * * @see ICompletionRequestor * @since 2.0 * @deprecated Subclass {@link CompletionRequestor} instead. */ public class CompletionRequestorAdapter implements ICompletionRequestor { @Override public void acceptAnonymousType( char[] superTypePackageName, char[] superTypeName, char[][] parameterPackageNames, char[][] parameterTypeNames, char[][] parameterNames, char[] completionName, int modifiers, int completionStart, int completionEnd, int relevance) { // default behavior is to ignore } @Override public void acceptClass( char[] packageName, char[] className, char[] completionName, int modifiers, int completionStart, int completionEnd, int relevance) { // default behavior is to ignore } @Override public void acceptError(IProblem error) { // default behavior is to ignore } @Override public void acceptField( char[] declaringTypePackageName, char[] declaringTypeName, char[] name, char[] typePackageName, char[] typeName, char[] completionName, int modifiers, int completionStart, int completionEnd, int relevance) { // default behavior is to ignore } @Override public void acceptInterface( char[] packageName, char[] interfaceName, char[] completionName, int modifiers, int completionStart, int completionEnd, int relevance) { // default behavior is to ignore } @Override public void acceptKeyword( char[] keywordName, int completionStart, int completionEnd, int relevance) { // default behavior is to ignore } @Override public void acceptLabel( char[] labelName, int completionStart, int completionEnd, int relevance) { // default behavior is to ignore } @Override public void acceptLocalVariable( char[] name, char[] typePackageName, char[] typeName, int modifiers, int completionStart, int completionEnd, int relevance) { // default behavior is to ignore } @Override public void acceptMethod( char[] declaringTypePackageName, char[] declaringTypeName, char[] selector, char[][] parameterPackageNames, char[][] parameterTypeNames, char[][] parameterNames, char[] returnTypePackageName, char[] returnTypeName, char[] completionName, int modifiers, int completionStart, int completionEnd, int relevance) { // default behavior is to ignore } @Override public void acceptMethodDeclaration( char[] declaringTypePackageName, char[] declaringTypeName, char[] selector, char[][] parameterPackageNames, char[][] parameterTypeNames, char[][] parameterNames, char[] returnTypePackageName, char[] returnTypeName, char[] completionName, int modifiers, int completionStart, int completionEnd, int relevance) { // default behavior is to ignore } @Override public void acceptModifier( char[] modifierName, int completionStart, int completionEnd, int relevance) { // default behavior is to ignore } @Override public void acceptPackage( char[] packageName, char[] completionName, int completionStart, int completionEnd, int relevance) { // default behavior is to ignore } @Override public void acceptType( char[] packageName, char[] typeName, char[] completionName, int completionStart, int completionEnd, int relevance) { // default behavior is to ignore } @Override public void acceptVariableName( char[] typePackageName, char[] typeName, char[] name, char[] completionName, int completionStart, int completionEnd, int relevance) { // default behavior is to ignore } }
{ "pile_set_name": "Github" }
[tower] localhost ansible_connection=local [database] [all:vars] admin_password='{{ ansible_tower.admin_password }}' pg_host="{{ ansible_tower.install.pg.host | default('') }}" pg_port="{{ ansible_tower.install.pg.port | default('') }}" pg_database="{{ ansible_tower.install.pg.database | default('awx') }}" pg_username="{{ ansible_tower.install.pg.username | default('awx') }}" pg_password="{{ ansible_tower.install.pg.password | default(ansible_tower.admin_password) }}" {% if not ansible_tower_37_later %} rabbitmq_port="{{ ansible_tower.install.rabbitmq.port | default(5672) }}" rabbitmq_vhost="{{ ansible_tower.install.rabbitmq.vhost | default('tower') }}" rabbitmq_username="{{ ansible_tower.install.rabbitmq.username | default('tower') }}" rabbitmq_password='{{ ansible_tower.install.rabbitmq.password | default(ansible_tower.admin_password) }}' rabbitmq_cookie="{{ ansible_tower.install.rabbitmq.cookie | default('cookiemonster') }}" rabbitmq_use_long_name="{{ ansible_tower.install.rabbitmq.use_long_name | default(false) }}" {% endif %}
{ "pile_set_name": "Github" }
package ne_NP import ( "math" "strconv" "time" "github.com/go-playground/locales" "github.com/go-playground/locales/currency" ) type ne_NP struct { locale string pluralsCardinal []locales.PluralRule pluralsOrdinal []locales.PluralRule pluralsRange []locales.PluralRule decimal string group string minus string percent string perMille string timeSeparator string inifinity string currencies []string // idx = enum of currency code currencyPositivePrefix string currencyNegativePrefix string monthsAbbreviated []string monthsNarrow []string monthsWide []string daysAbbreviated []string daysNarrow []string daysShort []string daysWide []string periodsAbbreviated []string periodsNarrow []string periodsShort []string periodsWide []string erasAbbreviated []string erasNarrow []string erasWide []string timezones map[string]string } // New returns a new instance of translator for the 'ne_NP' locale func New() locales.Translator { return &ne_NP{ locale: "ne_NP", pluralsCardinal: []locales.PluralRule{2, 6}, pluralsOrdinal: []locales.PluralRule{2, 6}, pluralsRange: []locales.PluralRule{2, 6}, decimal: ".", group: ",", minus: "-", percent: "%", perMille: "‰", timeSeparator: ":", inifinity: "∞", currencies: []string{"ADP", "AED", "AFA", "AFN", "ALK", "ALL", "AMD", "ANG", "AOA", "AOK", "AON", "AOR", "ARA", "ARL", "ARM", "ARP", "ARS", "ATS", "AUD", "AWG", "AZM", "AZN", "BAD", "BAM", "BAN", "BBD", "BDT", "BEC", "BEF", "BEL", "BGL", "BGM", "BGN", "BGO", "BHD", "BIF", "BMD", "BND", "BOB", "BOL", "BOP", "BOV", "BRB", "BRC", "BRE", "BRL", "BRN", "BRR", "BRZ", "BSD", "BTN", "BUK", "BWP", "BYB", "BYN", "BYR", "BZD", "CAD", "CDF", "CHE", "CHF", "CHW", "CLE", "CLF", "CLP", "CNX", "CNY", "COP", "COU", "CRC", "CSD", "CSK", "CUC", "CUP", "CVE", "CYP", "CZK", "DDM", "DEM", "DJF", "DKK", "DOP", "DZD", "ECS", "ECV", "EEK", "EGP", "ERN", "ESA", "ESB", "ESP", "ETB", "EUR", "FIM", "FJD", "FKP", "FRF", "GBP", "GEK", "GEL", "GHC", "GHS", "GIP", "GMD", "GNF", "GNS", "GQE", "GRD", "GTQ", "GWE", "GWP", "GYD", "HKD", "HNL", "HRD", "HRK", "HTG", "HUF", "IDR", "IEP", "ILP", "ILR", "ILS", "INR", "IQD", "IRR", "ISJ", "ISK", "ITL", "JMD", "JOD", "JPY", "KES", "KGS", "KHR", "KMF", "KPW", "KRH", "KRO", "KRW", "KWD", "KYD", "KZT", "LAK", "LBP", "LKR", "LRD", "LSL", "LTL", "LTT", "LUC", "LUF", "LUL", "LVL", "LVR", "LYD", "MAD", "MAF", "MCF", "MDC", "MDL", "MGA", "MGF", "MKD", "MKN", "MLF", "MMK", "MNT", "MOP", "MRO", "MTL", "MTP", "MUR", "MVP", "MVR", "MWK", "MXN", "MXP", "MXV", "MYR", "MZE", "MZM", "MZN", "NAD", "NGN", "NIC", "NIO", "NLG", "NOK", "NPR", "NZD", "OMR", "PAB", "PEI", "PEN", "PES", "PGK", "PHP", "PKR", "PLN", "PLZ", "PTE", "PYG", "QAR", "RHD", "ROL", "RON", "RSD", "RUB", "RUR", "RWF", "SAR", "SBD", "SCR", "SDD", "SDG", "SDP", "SEK", "SGD", "SHP", "SIT", "SKK", "SLL", "SOS", "SRD", "SRG", "SSP", "STD", "SUR", "SVC", "SYP", "SZL", "THB", "TJR", "TJS", "TMM", "TMT", "TND", "TOP", "TPE", "TRL", "TRY", "TTD", "TWD", "TZS", "UAH", "UAK", "UGS", "UGX", "USD", "USN", "USS", "UYI", "UYP", "UYU", "UZS", "VEB", "VEF", "VND", "VNN", "VUV", "WST", "XAF", "XAG", "XAU", "XBA", "XBB", "XBC", "XBD", "XCD", "XDR", "XEU", "XFO", "XFU", "XOF", "XPD", "XPF", "XPT", "XRE", "XSU", "XTS", "XUA", "XXX", "YDD", "YER", "YUD", "YUM", "YUN", "YUR", "ZAL", "ZAR", "ZMK", "ZMW", "ZRN", "ZRZ", "ZWD", "ZWL", "ZWR"}, currencyPositivePrefix: " ", currencyNegativePrefix: " ", monthsAbbreviated: []string{"", "जनवरी", "फेब्रुअरी", "मार्च", "अप्रिल", "मे", "जुन", "जुलाई", "अगस्ट", "सेप्टेम्बर", "अक्टोबर", "नोभेम्बर", "डिसेम्बर"}, monthsNarrow: []string{"", "१", "२", "३", "४", "५", "६", "७", "८", "९", "१०", "११", "१२"}, monthsWide: []string{"", "जनवरी", "फेब्रुअरी", "मार्च", "अप्रिल", "मई", "जुन", "जुलाई", "अगस्ट", "सेप्टेम्बर", "अक्टोबर", "नोभेम्बर", "डिसेम्बर"}, daysAbbreviated: []string{"आइत", "सोम", "मङ्गल", "बुध", "बिहि", "शुक्र", "शनि"}, daysNarrow: []string{"आ", "सो", "म", "बु", "बि", "शु", "श"}, daysShort: []string{"आइत", "सोम", "मङ्गल", "बुध", "बिहि", "शुक्र", "शनि"}, daysWide: []string{"आइतबार", "सोमबार", "मङ्गलबार", "बुधबार", "बिहिबार", "शुक्रबार", "शनिबार"}, periodsAbbreviated: []string{"पूर्वाह्न", "अपराह्न"}, periodsNarrow: []string{"पूर्वाह्न", "अपराह्न"}, periodsWide: []string{"पूर्वाह्न", "अपराह्न"}, erasAbbreviated: []string{"ईसा पूर्व", "सन्"}, erasNarrow: []string{"", ""}, erasWide: []string{"ईसा पूर्व", "सन्"}, timezones: map[string]string{"HNOG": "पश्चिमी ग्रीनल्यान्डको मानक समय", "HAT": "न्यूफाउनल्यान्डको दिवा समय", "WEZ": "पश्चिमी युरोपेली मानक समय", "HNPM": "सेन्ट पियर्रे र मिक्युलोनको मानक समय", "BT": "भुटानी समय", "HAST": "हवाई-एलुटियन मानक समय", "TMT": "तुर्कमेनिस्तान मानक समय", "HENOMX": "उत्तर पश्चिम मेक्सिकोको दिवा समय", "ADT": "एट्लान्टिक दिवा समय", "HEPMX": "मेक्सिकन प्यासिफिक दिवा समय", "MESZ": "केन्द्रीय युरोपेली ग्रीष्मकालीन समय", "JST": "जापान मानक समय", "ART": "अर्जेनटिनी मानक समय", "WAT": "पश्चिम अफ्रिकी मानक समय", "ACST": "केन्द्रीय अस्ट्रेलिया मानक समय", "∅∅∅": "∅∅∅", "HADT": "हवाई-एलुटियन दिवा समय", "MEZ": "केन्द्रीय युरोपेली मानक समय", "GMT": "ग्रीनविच मिन समय", "CHADT": "चाथाम दिवा समय", "HNCU": "क्यूबाको मानक समय", "EDT": "पूर्वी दिवा समय", "ACDT": "केन्द्रीय अस्ट्रेलिया दिवा समय", "CAT": "केन्द्रीय अफ्रिकी समय", "HNPMX": "मेक्सिकन प्यासिफिक मानक समय", "HECU": "क्यूबाको दिवा समय", "MYT": "मलेसिया समय", "SAST": "दक्षिण अफ्रिकी समय", "CLT": "चिली मानक समय", "BOT": "बोलिभिया समय", "OEZ": "पूर्वी युरोपेली मानक समय", "ARST": "अर्जेनटिनी ग्रीष्मकालीन समय", "CLST": "चिली ग्रीष्मकालीन समय", "WARST": "पश्चिमी अर्जेनटिनी ग्रीष्मकालीन समय", "SRT": "सुरिनामा समय", "CST": "केन्द्रीय मानक समय", "TMST": "तुर्कमेनिस्तान ग्रीष्मकालीन मानक समय", "IST": "भारतीय मानक समय", "PDT": "प्यासिफिक दिवा समय", "WIT": "पूर्वी इन्डोनेशिया समय", "COT": "कोलम्बियाली मानक समय", "HNT": "न्यूफाउनडल्यान्डको मानक समय", "AKDT": "अलस्काको दिवा समय", "AWST": "पश्चिमी अस्ट्रेलिया मानक समय", "WART": "पश्चिमी अर्जेनटिनी मानक समय", "HNEG": "पूर्वी ग्रीनल्यान्डको मानक समय", "WAST": "पश्चिम अफ्रिकी ग्रीष्मकालीन समय", "WIB": "पश्चिमी इन्डोनेशिया समय", "CHAST": "चाथाम मानक समय", "CDT": "केन्द्रीय दिवा समय", "UYST": "उरुग्वे ग्रीष्मकालीन समय", "WITA": "केन्द्रीय इन्डोनेशिया समय", "ECT": "ईक्वोडोर समय", "EAT": "पूर्वी अफ्रिकी समय", "HKST": "हङकङ ग्रीष्मकालीन समय", "GFT": "फ्रेन्च ग्वाना समय", "HKT": "हङकङ मानक समय", "EST": "पूर्वी मानक समय", "WESZ": "युरोपेली ग्रीष्मकालीन समय", "ChST": "चामोर्रो मानक समय", "OESZ": "पूर्वी युरोपेली ग्रीष्मकालीन समय", "HEOG": "पश्चिमी ग्रीनल्यान्डको ग्रीष्मकालीन समय", "HEEG": "पूर्वी ग्रीनल्यान्डको ग्रीष्मकालीन समय", "ACWDT": "केन्द्रीय पश्चिमी अस्ट्रेलिया दिवा समय", "NZDT": "न्यूजिल्यान्ड दिवा समय", "LHDT": "लर्ड हावे दिवा समय", "JDT": "जापान दिवा समय", "AEST": "पूर्वी अस्ट्रेलिया मानक समय", "MST": "MST", "AWDT": "पश्चिमी अस्ट्रेलिया दिवा समय", "UYT": "उरूग्वे मानक समय", "AST": "एट्लान्टिक मानक समय", "SGT": "सिंगापुर मानक समय", "ACWST": "केन्द्रीय पश्चिमी अस्ट्रेलिया मानक समय", "AEDT": "पूर्वी अस्ट्रेलिया दिवा समय", "HEPM": "सेन्ट पियर्रे र मिक्युलोनको दिवा समय", "VET": "भेनेज्युएला समय", "HNNOMX": "उत्तर पश्चिम मेक्सिकोको मानक समय", "COST": "कोलम्बियाली ग्रीष्मकालीन समय", "GYT": "गुयाना समय", "AKST": "अलस्काको मानक समय", "MDT": "MDT", "NZST": "न्यूजिल्यान्ड मानक समय", "LHST": "लर्ड हावे मानक समय", "PST": "प्यासिफिक मानक समय"}, } } // Locale returns the current translators string locale func (ne *ne_NP) Locale() string { return ne.locale } // PluralsCardinal returns the list of cardinal plural rules associated with 'ne_NP' func (ne *ne_NP) PluralsCardinal() []locales.PluralRule { return ne.pluralsCardinal } // PluralsOrdinal returns the list of ordinal plural rules associated with 'ne_NP' func (ne *ne_NP) PluralsOrdinal() []locales.PluralRule { return ne.pluralsOrdinal } // PluralsRange returns the list of range plural rules associated with 'ne_NP' func (ne *ne_NP) PluralsRange() []locales.PluralRule { return ne.pluralsRange } // CardinalPluralRule returns the cardinal PluralRule given 'num' and digits/precision of 'v' for 'ne_NP' func (ne *ne_NP) CardinalPluralRule(num float64, v uint64) locales.PluralRule { n := math.Abs(num) if n == 1 { return locales.PluralRuleOne } return locales.PluralRuleOther } // OrdinalPluralRule returns the ordinal PluralRule given 'num' and digits/precision of 'v' for 'ne_NP' func (ne *ne_NP) OrdinalPluralRule(num float64, v uint64) locales.PluralRule { n := math.Abs(num) if n >= 1 && n <= 4 { return locales.PluralRuleOne } return locales.PluralRuleOther } // RangePluralRule returns the ordinal PluralRule given 'num1', 'num2' and digits/precision of 'v1' and 'v2' for 'ne_NP' func (ne *ne_NP) RangePluralRule(num1 float64, v1 uint64, num2 float64, v2 uint64) locales.PluralRule { start := ne.CardinalPluralRule(num1, v1) end := ne.CardinalPluralRule(num2, v2) if start == locales.PluralRuleOne && end == locales.PluralRuleOther { return locales.PluralRuleOther } else if start == locales.PluralRuleOther && end == locales.PluralRuleOne { return locales.PluralRuleOne } return locales.PluralRuleOther } // MonthAbbreviated returns the locales abbreviated month given the 'month' provided func (ne *ne_NP) MonthAbbreviated(month time.Month) string { return ne.monthsAbbreviated[month] } // MonthsAbbreviated returns the locales abbreviated months func (ne *ne_NP) MonthsAbbreviated() []string { return ne.monthsAbbreviated[1:] } // MonthNarrow returns the locales narrow month given the 'month' provided func (ne *ne_NP) MonthNarrow(month time.Month) string { return ne.monthsNarrow[month] } // MonthsNarrow returns the locales narrow months func (ne *ne_NP) MonthsNarrow() []string { return ne.monthsNarrow[1:] } // MonthWide returns the locales wide month given the 'month' provided func (ne *ne_NP) MonthWide(month time.Month) string { return ne.monthsWide[month] } // MonthsWide returns the locales wide months func (ne *ne_NP) MonthsWide() []string { return ne.monthsWide[1:] } // WeekdayAbbreviated returns the locales abbreviated weekday given the 'weekday' provided func (ne *ne_NP) WeekdayAbbreviated(weekday time.Weekday) string { return ne.daysAbbreviated[weekday] } // WeekdaysAbbreviated returns the locales abbreviated weekdays func (ne *ne_NP) WeekdaysAbbreviated() []string { return ne.daysAbbreviated } // WeekdayNarrow returns the locales narrow weekday given the 'weekday' provided func (ne *ne_NP) WeekdayNarrow(weekday time.Weekday) string { return ne.daysNarrow[weekday] } // WeekdaysNarrow returns the locales narrow weekdays func (ne *ne_NP) WeekdaysNarrow() []string { return ne.daysNarrow } // WeekdayShort returns the locales short weekday given the 'weekday' provided func (ne *ne_NP) WeekdayShort(weekday time.Weekday) string { return ne.daysShort[weekday] } // WeekdaysShort returns the locales short weekdays func (ne *ne_NP) WeekdaysShort() []string { return ne.daysShort } // WeekdayWide returns the locales wide weekday given the 'weekday' provided func (ne *ne_NP) WeekdayWide(weekday time.Weekday) string { return ne.daysWide[weekday] } // WeekdaysWide returns the locales wide weekdays func (ne *ne_NP) WeekdaysWide() []string { return ne.daysWide } // Decimal returns the decimal point of number func (ne *ne_NP) Decimal() string { return ne.decimal } // Group returns the group of number func (ne *ne_NP) Group() string { return ne.group } // Group returns the minus sign of number func (ne *ne_NP) Minus() string { return ne.minus } // FmtNumber returns 'num' with digits/precision of 'v' for 'ne_NP' and handles both Whole and Real numbers based on 'v' func (ne *ne_NP) FmtNumber(num float64, v uint64) string { s := strconv.FormatFloat(math.Abs(num), 'f', int(v), 64) l := len(s) + 2 + 1*len(s[:len(s)-int(v)-1])/3 count := 0 inWhole := v == 0 b := make([]byte, 0, l) for i := len(s) - 1; i >= 0; i-- { if s[i] == '.' { b = append(b, ne.decimal[0]) inWhole = true continue } if inWhole { if count == 3 { b = append(b, ne.group[0]) count = 1 } else { count++ } } b = append(b, s[i]) } if num < 0 { b = append(b, ne.minus[0]) } // reverse for i, j := 0, len(b)-1; i < j; i, j = i+1, j-1 { b[i], b[j] = b[j], b[i] } return string(b) } // FmtPercent returns 'num' with digits/precision of 'v' for 'ne_NP' and handles both Whole and Real numbers based on 'v' // NOTE: 'num' passed into FmtPercent is assumed to be in percent already func (ne *ne_NP) FmtPercent(num float64, v uint64) string { s := strconv.FormatFloat(math.Abs(num), 'f', int(v), 64) l := len(s) + 3 b := make([]byte, 0, l) for i := len(s) - 1; i >= 0; i-- { if s[i] == '.' { b = append(b, ne.decimal[0]) continue } b = append(b, s[i]) } if num < 0 { b = append(b, ne.minus[0]) } // reverse for i, j := 0, len(b)-1; i < j; i, j = i+1, j-1 { b[i], b[j] = b[j], b[i] } b = append(b, ne.percent...) return string(b) } // FmtCurrency returns the currency representation of 'num' with digits/precision of 'v' for 'ne_NP' func (ne *ne_NP) FmtCurrency(num float64, v uint64, currency currency.Type) string { s := strconv.FormatFloat(math.Abs(num), 'f', int(v), 64) symbol := ne.currencies[currency] l := len(s) + len(symbol) + 4 + 1*len(s[:len(s)-int(v)-1])/3 count := 0 inWhole := v == 0 b := make([]byte, 0, l) for i := len(s) - 1; i >= 0; i-- { if s[i] == '.' { b = append(b, ne.decimal[0]) inWhole = true continue } if inWhole { if count == 3 { b = append(b, ne.group[0]) count = 1 } else { count++ } } b = append(b, s[i]) } for j := len(symbol) - 1; j >= 0; j-- { b = append(b, symbol[j]) } for j := len(ne.currencyPositivePrefix) - 1; j >= 0; j-- { b = append(b, ne.currencyPositivePrefix[j]) } if num < 0 { b = append(b, ne.minus[0]) } // reverse for i, j := 0, len(b)-1; i < j; i, j = i+1, j-1 { b[i], b[j] = b[j], b[i] } if int(v) < 2 { if v == 0 { b = append(b, ne.decimal...) } for i := 0; i < 2-int(v); i++ { b = append(b, '0') } } return string(b) } // FmtAccounting returns the currency representation of 'num' with digits/precision of 'v' for 'ne_NP' // in accounting notation. func (ne *ne_NP) FmtAccounting(num float64, v uint64, currency currency.Type) string { s := strconv.FormatFloat(math.Abs(num), 'f', int(v), 64) symbol := ne.currencies[currency] l := len(s) + len(symbol) + 4 + 1*len(s[:len(s)-int(v)-1])/3 count := 0 inWhole := v == 0 b := make([]byte, 0, l) for i := len(s) - 1; i >= 0; i-- { if s[i] == '.' { b = append(b, ne.decimal[0]) inWhole = true continue } if inWhole { if count == 3 { b = append(b, ne.group[0]) count = 1 } else { count++ } } b = append(b, s[i]) } if num < 0 { for j := len(symbol) - 1; j >= 0; j-- { b = append(b, symbol[j]) } for j := len(ne.currencyNegativePrefix) - 1; j >= 0; j-- { b = append(b, ne.currencyNegativePrefix[j]) } b = append(b, ne.minus[0]) } else { for j := len(symbol) - 1; j >= 0; j-- { b = append(b, symbol[j]) } for j := len(ne.currencyPositivePrefix) - 1; j >= 0; j-- { b = append(b, ne.currencyPositivePrefix[j]) } } // reverse for i, j := 0, len(b)-1; i < j; i, j = i+1, j-1 { b[i], b[j] = b[j], b[i] } if int(v) < 2 { if v == 0 { b = append(b, ne.decimal...) } for i := 0; i < 2-int(v); i++ { b = append(b, '0') } } return string(b) } // FmtDateShort returns the short date representation of 't' for 'ne_NP' func (ne *ne_NP) FmtDateShort(t time.Time) string { b := make([]byte, 0, 32) if t.Year() > 0 { b = strconv.AppendInt(b, int64(t.Year()), 10) } else { b = strconv.AppendInt(b, int64(-t.Year()), 10) } b = append(b, []byte{0x2d}...) if t.Month() < 10 { b = append(b, '0') } b = strconv.AppendInt(b, int64(t.Month()), 10) b = append(b, []byte{0x2d}...) if t.Day() < 10 { b = append(b, '0') } b = strconv.AppendInt(b, int64(t.Day()), 10) return string(b) } // FmtDateMedium returns the medium date representation of 't' for 'ne_NP' func (ne *ne_NP) FmtDateMedium(t time.Time) string { b := make([]byte, 0, 32) if t.Year() > 0 { b = strconv.AppendInt(b, int64(t.Year()), 10) } else { b = strconv.AppendInt(b, int64(-t.Year()), 10) } b = append(b, []byte{0x20}...) b = append(b, ne.monthsAbbreviated[t.Month()]...) b = append(b, []byte{0x20}...) b = strconv.AppendInt(b, int64(t.Day()), 10) return string(b) } // FmtDateLong returns the long date representation of 't' for 'ne_NP' func (ne *ne_NP) FmtDateLong(t time.Time) string { b := make([]byte, 0, 32) if t.Year() > 0 { b = strconv.AppendInt(b, int64(t.Year()), 10) } else { b = strconv.AppendInt(b, int64(-t.Year()), 10) } b = append(b, []byte{0x20}...) b = append(b, ne.monthsWide[t.Month()]...) b = append(b, []byte{0x20}...) b = strconv.AppendInt(b, int64(t.Day()), 10) return string(b) } // FmtDateFull returns the full date representation of 't' for 'ne_NP' func (ne *ne_NP) FmtDateFull(t time.Time) string { b := make([]byte, 0, 32) if t.Year() > 0 { b = strconv.AppendInt(b, int64(t.Year()), 10) } else { b = strconv.AppendInt(b, int64(-t.Year()), 10) } b = append(b, []byte{0x20}...) b = append(b, ne.monthsWide[t.Month()]...) b = append(b, []byte{0x20}...) b = strconv.AppendInt(b, int64(t.Day()), 10) b = append(b, []byte{0x2c, 0x20}...) b = append(b, ne.daysWide[t.Weekday()]...) return string(b) } // FmtTimeShort returns the short time representation of 't' for 'ne_NP' func (ne *ne_NP) FmtTimeShort(t time.Time) string { b := make([]byte, 0, 32) if t.Hour() < 10 { b = append(b, '0') } b = strconv.AppendInt(b, int64(t.Hour()), 10) b = append(b, ne.timeSeparator...) if t.Minute() < 10 { b = append(b, '0') } b = strconv.AppendInt(b, int64(t.Minute()), 10) return string(b) } // FmtTimeMedium returns the medium time representation of 't' for 'ne_NP' func (ne *ne_NP) FmtTimeMedium(t time.Time) string { b := make([]byte, 0, 32) if t.Hour() < 10 { b = append(b, '0') } b = strconv.AppendInt(b, int64(t.Hour()), 10) b = append(b, ne.timeSeparator...) if t.Minute() < 10 { b = append(b, '0') } b = strconv.AppendInt(b, int64(t.Minute()), 10) b = append(b, ne.timeSeparator...) if t.Second() < 10 { b = append(b, '0') } b = strconv.AppendInt(b, int64(t.Second()), 10) return string(b) } // FmtTimeLong returns the long time representation of 't' for 'ne_NP' func (ne *ne_NP) FmtTimeLong(t time.Time) string { b := make([]byte, 0, 32) if t.Hour() < 10 { b = append(b, '0') } b = strconv.AppendInt(b, int64(t.Hour()), 10) b = append(b, ne.timeSeparator...) if t.Minute() < 10 { b = append(b, '0') } b = strconv.AppendInt(b, int64(t.Minute()), 10) b = append(b, ne.timeSeparator...) if t.Second() < 10 { b = append(b, '0') } b = strconv.AppendInt(b, int64(t.Second()), 10) b = append(b, []byte{0x20}...) tz, _ := t.Zone() b = append(b, tz...) return string(b) } // FmtTimeFull returns the full time representation of 't' for 'ne_NP' func (ne *ne_NP) FmtTimeFull(t time.Time) string { b := make([]byte, 0, 32) if t.Hour() < 10 { b = append(b, '0') } b = strconv.AppendInt(b, int64(t.Hour()), 10) b = append(b, ne.timeSeparator...) if t.Minute() < 10 { b = append(b, '0') } b = strconv.AppendInt(b, int64(t.Minute()), 10) b = append(b, ne.timeSeparator...) if t.Second() < 10 { b = append(b, '0') } b = strconv.AppendInt(b, int64(t.Second()), 10) b = append(b, []byte{0x20}...) tz, _ := t.Zone() if btz, ok := ne.timezones[tz]; ok { b = append(b, btz...) } else { b = append(b, tz...) } return string(b) }
{ "pile_set_name": "Github" }
//------------------------------------------------------------------------------ // <auto-generated> // Ten kod został wygenerowany przez narzędzie. // Wersja wykonawcza:4.0.30319.42000 // // Zmiany w tym pliku mogą spowodować nieprawidłowe zachowanie i zostaną utracone, jeśli // kod zostanie ponownie wygenerowany. // </auto-generated> //------------------------------------------------------------------------------ namespace GameLauncher.Properties { [global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()] [global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.VisualStudio.Editors.SettingsDesigner.SettingsSingleFileGenerator", "16.6.0.0")] internal sealed partial class Settings : global::System.Configuration.ApplicationSettingsBase { private static Settings defaultInstance = ((Settings)(global::System.Configuration.ApplicationSettingsBase.Synchronized(new Settings()))); public static Settings Default { get { return defaultInstance; } } [global::System.Configuration.UserScopedSettingAttribute()] [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] [global::System.Configuration.DefaultSettingValueAttribute("")] public string PasswordDecoded { get { return ((string)(this["PasswordDecoded"])); } set { this["PasswordDecoded"] = value; } } [global::System.Configuration.UserScopedSettingAttribute()] [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] [global::System.Configuration.DefaultSettingValueAttribute("False")] public bool IsRestarting { get { return ((bool)(this["IsRestarting"])); } set { this["IsRestarting"] = value; } } } }
{ "pile_set_name": "Github" }
# # commit-circle.R, 23 Apr 20 # # Data from: # Do time of day and developer experience affect commit bugginess? # Jon Eyolfson and Lin Tan and Patrick Lam # # Example from: # Evidence-based Software Engineering: based on the publicly available data # Derek M. Jones # # TAG commit_week-day Linux_commits OpenBSD_commits faults source("ESEUR_config.r") library("circular") plot_layout(2, 1, max_height=11.0) par(mar=MAR_default-c(2.7, 3.7, 0.5, 0.7)) pal_col=rainbow(3) plot_commits=function(df, repo_str, col_str) { hrs=as.numeric(round(df$local_time, units="hours")) / (60*60) week_hr=(shift_weekend+hrs) %% hrs_per_week # Map to a 360 degree circle HoW=circular((360/hrs_per_week)*week_hr, units="degrees", rotation="clock") #plot(HoW, stack=TRUE, shrink=3, axes=FALSE, cex=0.01, col=col_str) rose.diag(HoW, bins=7*8, shrink=1.2, prop=5, col=col_str, border="grey", axes=FALSE, control.circle=circle.control(col="grey", lwd=0.5)) axis.circular(at=circular(day_angle, units="degrees", rotation="clock"), labels=c("Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun")) text(0.8, 1, repo_str, cex=1.4) arrows.circular(mean(HoW), y=rho.circular(HoW), col=pal_col[2], lwd=3) # print(c(mean(HoW)[[1]], rho.circular(HoW))) # lines(density(HoW, bw=30)) return(HoW) } # id repository_id raw_author_id sha1 merge utc_time local_time commits=read.csv(paste0(ESEUR_dir, "time-series/commits/scc_commit.tsv.xz"), sep="\t", as.is=TRUE) commits$sha1=NULL # 2011-09-09 11:30:27 commits$local_time=as.POSIXct(commits$local_time, format="%Y-%m-%d %H:%M:%S") hrs_per_day=24 hrs_per_week=hrs_per_day*7 day_angle=seq(0, 359, 360/7) # 1-Jan-1970 is a Thursday shift_weekend=3*hrs_per_day # Linux linux_circ=plot_commits(subset(commits, repository_id == 1), "Linux", pal_col[1]) # FreeBSD BSD_circ=plot_commits(subset(commits, repository_id == 5), "OpenBSD", pal_col[3])
{ "pile_set_name": "Github" }
{ "author": "Microsoft Community", "name": "App Config", "description": "Добавляет пустой файл App.config в проект.", "identity": "wts.Feat.AppDotConfig.VB" }
{ "pile_set_name": "Github" }
# frozen_string_literal: true # Creation and updates timestamps for Ansible Roles class AutomaticallySetRoleTimestamps < ActiveRecord::Migration[4.2] def up change_column :ansible_roles, :created_at, :datetime, :null => true, :default => nil change_column :ansible_roles, :updated_at, :datetime, :null => true, :default => nil end def down change_column :ansible_roles, :created_at, :datetime, :null => false, :default => Time.now.utc change_column :ansible_roles, :updated_at, :datetime, :null => false, :default => Time.now.utc end end
{ "pile_set_name": "Github" }
--- title: "TeleSign, Twilio channels agent experience in Omnichannel for Customer Service | MicrosoftDocs" description: "Learn about the TeleSign, Twilio SMS channels agent experience in Omnichannel for Customer Service." author: neeranelli ms.author: nenellim manager: shujoshi ms.date: 04/06/2020 ms.service: - "dynamics-365-customerservice" ms.topic: article --- # Use an SMS channel [!INCLUDE[cc-use-with-omnichannel](../../../includes/cc-use-with-omnichannel.md)] ## Channels overview When you sign in to Omnichannel for Customer Service, you can see your work items in the Omnichannel Agent Dashboard. To learn more, see [View agent dashboard and agent conversations (work items)](oc-agent-dashboard.md). ## Prerequisite Make sure your administrator has configured a TeleSign or Twilio channel in Omnichannel for Customer Service. ### Incoming chat notifications You'll receive a notification when a customer requests a conversation through TeleSign or Twilio. You can accept the chat request, after which a session starts and you'll see the communication panel in which you can exchange messages with the customer. > [!div class=mx-imgBorder] > ![Incoming chat notification](../../media/oceh/sms-notification-request.png "Incoming SMS notification") As an agent in Omnichannel for Customer Service, you can: - [View a customer summary](oc-customer-summary.md). - [View the communication panel](oc-conversation-control.md). - [Use call options and visual engagement in live chat](call-options-visual-engagement.md). - [Monitor real-time customer sentiment](oc-monitor-real-time-customer-sentiment-sessions.md). - [Manage sessions](oc-manage-sessions.md). - [Manage applications](oc-manage-applications.md). - Use these productivity tools: - [Use agent scripts](oc-agent-scripts.md) - [View smart-assist cards](oc-smart-assist.md) - [Use the productivity pane](oc-productivity-pane.md) - [Create a record](oc-create-record.md). - [Search, link, and unlink a record](oc-search-link-unlink-record.md). - [Search for and share knowledge articles](oc-search-knowledge-articles.md). - [Take notes specific to a conversation](oc-take-notes.md). - [Understand conversation states](oc-conversation-state.md). - [Manage presence status](oc-manage-presence-status.md). - [Search for transcripts](oc-search-transcipts.md). - [View conversation and session forms](oc-view-activity-types.md). - [View the customer summary for an incoming conversation request](oc-view-customer-summary-incoming-conversation-request.md). - [Search for transcripts](oc-search-transcipts.md). ### See also [Configure SMS channel for Twilio](../../administrator/configure-sms-channel-twilio.md)
{ "pile_set_name": "Github" }
import React, { Component } from 'react'; import { Redirect, Switch, Route } from 'react-router-dom'; import routerConfig from '../../routerConfig'; import Guide from '../../components/Guide'; class MainRoutes extends Component { /** * 渲染路由组件 */ renderNormalRoute = (item, index) => { return item.component ? ( <Route key={index} path={item.path} component={item.component} exact={item.exact} /> ) : null; }; render() { return ( <Switch> {/* 渲染路由表 */} {routerConfig.map(this.renderNormalRoute)} {/* 首页默认重定向到 /dashboard */} <Redirect exact from="/" to="/dashboard" /> {/* 未匹配到的路由重定向到 <Guide> 组件,实际情况应该重定向到 404 */} <Route component={Guide} /> </Switch> ); } } export default MainRoutes;
{ "pile_set_name": "Github" }
<!DOCTYPE html> <meta charset="utf-8"> <title>Testing Available Space in Orthogonal Flows / max-height / no scroller</title> <link rel="author" title="Florian Rivoal" href="https://florian.rivoal.net/"> <link rel="help" href="https://www.w3.org/TR/css-writing-modes-3/#orthogonal-auto"> <link rel="match" href="reference/available-size-002-ref.html"> <meta name="assert" content="When an orthogonal flow's ancestor doesn't have a definite block size but does have a fixed max-height, but isn't a scroller, do not use that size."> <meta name="flags" content=""> <style> body > div { font-family: monospace; /* to be able to reliably measure things in ch*/ font-size: 20px; max-height: 8ch; /* **max**-height does not give the element a definite block size */ color: transparent; position: relative; /* to act as a container of #green */ } div > div > div { writing-mode: vertical-rl; } span { background: white; display: inline-block; /* This should not change it's size or position, but makes the size of the background predictable*/ } #green { position: absolute; background: green; left: 0; writing-mode: vertical-rl; z-index: -1; } </style> <p>Test passes if there is a <strong>green rectangle</strong> below and <strong>no red</strong>. <div> <div> <aside id="green">0</aside> <div>0 0 0 0 <span>0</span> 0 0 0</div> <!-- If this div takes its height from the max-height of its parent (which it shouldn't, since it's not a scroller), it should wrap just right for the white 0 to overlap with the green one. --> </div> </div>
{ "pile_set_name": "Github" }
<?xml version="1.0" encoding="utf-8"?> <!-- /* ** Copyright 2011, 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. */ --> <accelerateInterpolator xmlns:android="http://schemas.android.com/apk/res/android" android:factor="2.0"/>
{ "pile_set_name": "Github" }
/* SPDX-License-Identifier: GPL-2.0 */ #ifndef __PERF_REGS_H #define __PERF_REGS_H #include <linux/types.h> #include <linux/compiler.h> struct regs_dump; struct sample_reg { const char *name; uint64_t mask; }; #define SMPL_REG(n, b) { .name = #n, .mask = 1ULL << (b) } #define SMPL_REG_END { .name = NULL } extern const struct sample_reg sample_reg_masks[]; enum { SDT_ARG_VALID = 0, SDT_ARG_SKIP, }; int arch_sdt_arg_parse_op(char *old_op, char **new_op); #ifdef HAVE_PERF_REGS_SUPPORT #include <perf_regs.h> int perf_reg_value(u64 *valp, struct regs_dump *regs, int id); #else #define PERF_REGS_MASK 0 #define PERF_REGS_MAX 0 static inline const char *perf_reg_name(int id __maybe_unused) { return "unknown"; } static inline int perf_reg_value(u64 *valp __maybe_unused, struct regs_dump *regs __maybe_unused, int id __maybe_unused) { return 0; } #endif /* HAVE_PERF_REGS_SUPPORT */ #endif /* __PERF_REGS_H */
{ "pile_set_name": "Github" }
<?php // Don't redefine the functions if included multiple times. if (!function_exists('GuzzleHttp\Psr7\str')) { require __DIR__ . '/functions.php'; }
{ "pile_set_name": "Github" }
<!DOCTYPE html> <html lang="en-us"> <head> <link href="http://gmpg.org/xfn/11" rel="profile"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta http-equiv="content-type" content="text/html; charset=utf-8"> <!-- Enable responsiveness on mobile devices--> <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1"> <title> Exercise 18.2 &middot; AIMA Exercises </title> <!-- CSS --> <link rel="stylesheet" href="/aima-exercises/public/css/poole.css"> <link rel="stylesheet" href="/aima-exercises/public/css/syntax.css"> <link rel="stylesheet" href="/aima-exercises/public/css/lanyon.css"> <link rel="stylesheet" href="/aima-exercises/public/css/style.css"> <link rel="stylesheet" href="https://fonts.googleapis.com/css?family=PT+Serif:400,400italic,700%7CPT+Sans:400"> <link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.8.1/css/all.css" integrity="sha384-50oBUHEmvpQ+1lW4y57PTFmhCaXp0ML5d60M1M7uH2+nqUivzIebhndOJK28anvf" crossorigin="anonymous"> <!-- Bootstrap CSS --> <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous"> <!-- Icons --> <link rel="apple-touch-icon-precomposed" sizes="144x144" href="/aima-exercises/public/apple-touch-icon-precomposed.png"> <link rel="shortcut icon" href="/aima-exercises/public/aima_logo.ico"> <!-- RSS --> <link rel="alternate" type="application/rss+xml" title="RSS" href="/atom.xml"> </head> <body> <!-- Target for toggling the sidebar `.sidebar-checkbox` is for regular styles, `#sidebar-checkbox` for behavior. --> <input type="checkbox" class="sidebar-checkbox" id="sidebar-checkbox"> <!-- Toggleable sidebar --> <div class="sidebar" id="sidebar"> <div class="sidebar-item"> <p>Artificial Intelligence : A Modern Approach</p> </div> <nav class="sidebar-nav"> <a class="sidebar-nav-item" href="/aima-exercises/">Home</a> <span class="sidebar-nav-item">Part - I Artificial Intelligence</span> <a class="sidebar-nav-item" href="/aima-exercises/intro-exercises/">Chapter 1 - Introduction</a> <a class="sidebar-nav-item" href="/aima-exercises/agents-exercises/">Chapter 2 - Intelligent Agents</a> <span class="sidebar-nav-item">Part - II Problem Solving</span> <a class="sidebar-nav-item" href="/aima-exercises/search-exercises/">Chapter 3 - Solving Problems By Searching</a> <a class="sidebar-nav-item" href="/aima-exercises/advanced-search-exercises">Chapter 4 - Beyond Classical Search</a> <a class="sidebar-nav-item" href="/aima-exercises/game-playing-exercises">Chapter 5 - Adversarial Search</a> <a class="sidebar-nav-item" href="/aima-exercises/csp-exercises">Chapter 6 - Constraint Satisfaction Problems</a> <span class="sidebar-nav-item">Part - III Knowledge, Reasoning and Planning</span> <a class="sidebar-nav-item" href="/aima-exercises/knowledge-logic-exercises">Chapter 7 - Logical Agents</a> <a class="sidebar-nav-item" href="/aima-exercises/fol-exercises">Chapter 8 - First Order Logic</a> <a class="sidebar-nav-item" href="/aima-exercises/logical-inference-exercises">Chapter 9 - Inference in First Order Logic</a> <a class="sidebar-nav-item" href="/aima-exercises/planning-exercises">Chapter 10 - Classical Planning</a> <a class="sidebar-nav-item" href="/aima-exercises/advanced-planning-exercises">Chapter 11 - Planning and Acting in Real Life</a> <a class="sidebar-nav-item" href="/aima-exercises/kr-exercises">Chapter 12 - Knowledge Representation</a> <span class="sidebar-nav-item">Part - IV Uncertaing Knowledge and Reasoning</span> <a class="sidebar-nav-item" href="/aima-exercises/probability-exercises">Chapter 13 - Quantifying Uncertainty</a> <a class="sidebar-nav-item" href="/aima-exercises/bayes-nets-exercises">Chapter 14 - Probabilistic Reasoning</a> <a class="sidebar-nav-item" href="/aima-exercises/dbn-exercises">Chapter 15 - Probabilistic Reasoning Over Time</a> <a class="sidebar-nav-item" href="/aima-exercises/decision-theory-exercises">Chapter 16 - Making-Simple Decisions</a> <a class="sidebar-nav-item" href="/aima-exercises/complex-decisions-exercises">Chapter 17 - Making Complex Decisions</a> <span class="sidebar-nav-item">Part - V Lerning</span> <a class="sidebar-nav-item" href="/aima-exercises/concept-learning-exercises">Chapter 18 - Learning From Examples</a> <a class="sidebar-nav-item" href="/aima-exercises/ilp-exercises">Chapter 19 - Knowledge In Learning</a> <a class="sidebar-nav-item" href="/aima-exercises/bayesian-learning-exercises">Chapter 20 - Learning Probabilistic Models</a> <a class="sidebar-nav-item" href="/aima-exercises/reinforcement-learning-exercises">Chapter 21 - Reinforcement Learning</a> <span class="sidebar-nav-item">Part - VI Communicating, Perceiving and Acting</span> <a class="sidebar-nav-item" href="/aima-exercises/nlp-communicating-exercises">Chapter 22 - Natural Language Processing</a> <a class="sidebar-nav-item" href="/aima-exercises/nlp-english-exercises">Chapter 23 - Natural Language For Communication</a> <a class="sidebar-nav-item" href="/aima-exercises/perception-exercises">Chapter 24 - Perception</a> <a class="sidebar-nav-item" href="/aima-exercises/robotics-exercises">Chapter 25 - Robotics</a> <span class="sidebar-nav-item">Part - VII Conclusions</span> <a class="sidebar-nav-item" href="/aima-exercises/philosophy-exercises">Chapter 26 - Philosophical Foundations</a> <a class="sidebar-nav-item" href="/aima-exercises/#/">Chapter 27 - AI The Present And Future</a> <span class="sidebar-nav-item">Currently v1.0.0</span> </nav> <div class="sidebar-item"> <p> &copy; 2019. All rights reserved. </p> </div> </div> <div class="wrap"> <div class="masthead"> <div class="container"> <h3 class="masthead-title"> <a href="/aima-exercises/" title="Home">Artificial Intelligence</a> <small>AIMA Exercises </small> </h3> <br> <center> <form class="form-inline active-pink-3 active-pink-4" action="/aima-exercises/search" id="site_search" autocomplete="off" method="GET"> <i class="fas fa-search" aria-hidden="true"></i> <input class="form-control form-control-sm ml-3 w-75" type="text" placeholder="Search within AIMA Exercises" aria-label="Search" name="query"> <input type="submit" value="Go!" class="search-btn"> </form> <br> </center> <ul class="breadcrumbb" id="bbreadcrumb"> <label for="toggletoc" class="toc-icon"> <span></span> <span></span> <span></span> </label> <li><a class="breadcrumb-text" href="/aima-exercises/"><i class="fa fa-home"></i></a> </li> <!-- /concept-learning-exercises --> <li><a class="breadcrumb-text" href="/aima-exercises/concept-learning-exercises">concept-learning-exercises</a> </li> </ul> </div> </div> <div class="container content"> <article class="post"> <div class="entry"> <div class="mode_btn view_question_source"> </div> <script type="text/x-mathjax-config"> MathJax.Hub.Config({ TeX: { equationNumbers: { autoNumber: "AMS" } }, tex2jax: { inlineMath: [ ['$','$'] ], displayMath: [ ['$$','$$'] ], processEscapes: true, }, "HTML-CSS": { preferredFont: "TeX", availableFonts: ["STIX","TeX"], styles: {".MathJax": {}} } }); </script> <script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/mathjax/2.7.0/MathJax.js?config=TeX-AMS-MML_HTMLorMML"> </script> <div id="hiddden"> Repeat Exercise <a class="exerciseRef" href="/aima-exercises/concept-learning-exercises/ex_1/">infant-language-exercise</a> for the case of learning to play tennis (or some other sport with which you are familiar). Is this supervised learning or reinforcement learning? </div> </div> <div class="card"> <div class="card-header p-2"> <a href='#' class="p-2">Exercise 18.2</a> <a class="bookmarkquest" id="bookmark_question"> <button type="button" class="btn btn-dark float-right" title="Bookmark Exercise" onclick="bookmark('ch18ex2');" href="#"> <i id="ch18ex2" class="fas fa-bookmark" style="color:white"></i> </button> </a> <a class="edit_question" id="editt_question" href="#"> <button type="button" class="btn btn-dark float-right" title="Edit this Question" style="margin-left:10px; margin-right:10px;" onclick="edit('ch18ex2');" href="#" id="buttonsolve"> <i id="ch18ex2" class="far fa-edit" style="color:white"></i> </button> </a> </div> <div class="card-body"> <p class="card-text"> Repeat Exercise <a class="exerciseRef" href="/aima-exercises/concept-learning-exercises/ex_1/">infant-language-exercise</a> for the case of learning to play tennis (or some other sport with which you are familiar). Is this supervised learning or reinforcement learning? </p> </div> </div> <br> <div class="card"> <div class="card-header p-2"> <a href="#" class="p-2">Community Solution</a> <a class="reqcomm" id="reqcommus" href="#"> <button type="button" class="btn btn-dark float-right" title="Request for Community Solution" href="#" id="requestcommsol"> <i class="fas fa-hands" style="color:white"></i> </button> </a> <a class="viewcommsolution" id="viewcommsolution"> <button type="button" class="btn btn-dark float-right" title="View Community solution" style="margin-left:10px; margin-right:10px;" onclick="myFunction2()" href="#" id="viewsol"> <i class="fas fa-bars" style="color:white"></i> </button> </a> </div> <div class="card-body" id="hideandviewcommunitysolution" markdown="1"> <div id="content2" markdown="1"> <div class="hideit" id="link2"></div> </div> </div> </div> <br> <div class="card" id="borderbottom"> <div class="card-header p-2"> <a href="#" class="p-2">Student Answers</a> <a class="addanswerorcomment" id="addanswerorcomment" href="#"> <button type="button" class="btn btn-dark float-right" title="Add answer/comment" id="addanswerorcomment2" href="#"> <i class="fas fa-edit" style="color:white"></i> </button> </a> <a class="viewusersolution" id="viewusersolution"> <button type="button" class="btn btn-dark float-right" title="View Answers" style="margin-left:10px; margin-right:10px;" id="viewanswers" onclick="myFunction4()" href="#" > <i class="fas fa-bars" style="color:white"></i> </button> </a> </div> <div class="card-body" id="hideandviewusersolution" markdown="1"> <div id="content" markdown="1"> <div class="hideit" id="link"></div> </div> </div> </div> <br><br> <div id="writeeanswer"></div> <div class="styling" id="styling2"> <form class="contact100-form validate-form" id="new_comment" method="post" action="https://staticmanlove.herokuapp.com/v3/entry/github/aimacode/aima-exercises/master/ch18ex2"> <span class="contact100-form-title"> <center>Submit Solution</center> </span> <br> <div class="wrap-input100 rs1-wrap-input100 validate-input" data-validate="Name is required" > <span class="label-input100">Your Display Name</span> <input class="input100" type="text" placeholder="Enter your Display name" name="fields[Name]" tabindex="3"> <span class="focus-input100"></span> </div> <div class="wrap-input100 rs1-wrap-input100 validate-input" data-validate = "Valid email is required: [email protected]"> <span class="label-input100">Email</span> <input class="input100" type="text" placeholder="Enter your email addess" name="fields[Email]" tabindex="2"> <span class="focus-input100"></span> </div> <div class="wrap-input100 validate-input" data-validate = "Message is required"> <span class="label-input100">Solution</span> <textarea class="input100" placeholder="Your solution here..." name="fields[message]" tabindex="1"></textarea> <span class="focus-input100"></span> </div> <input type="hidden" name="options[redirect]" value="https://aimacode.github.io/aima-exercises/answersubmitted/"> <div class="container-contact100-form-btn"> <button class="contact100-form-btn" tabindex="5"> <span> Submit <i class="fa fa-long-arrow-right m-l-7" aria-hidden="true"></i></center> </span> </button> </div> </form> </div> </article> <script> var baseurl="https://github.com/aimacode/aima-exercises/edit/master/markdown/"; var chapterName = String('18-Learning-From-Examples'); var fullName = String('ch18ex2'); var dot = fullName.indexOf("x"); var exerciseName = "ex_"; var subs = fullName.substring(dot+1,fullName.length); exerciseName+=subs; document.getElementById("editt_question").href = baseurl+chapterName+"/exercises/"+exerciseName+"/question.md"; document.getElementById("reqcommus").href = "https://github.com/aimacode/aima-exercises/issues/new?title=Request%20to%20get%20Community%20solution%20for%20Exercise%20%27"+exerciseName+"%27%20in%20%27"+chapterName+"%27&body=Request%20for%20Community%20Solution"; document.getElementById("solve_question").href = "#writeeanswer"; document.getElementById("addanswerorcomment").href= "#writeeanswer"; document.getElementById("link").innerHTML = "https://api.github.com/repos/aimacode/aima-exercises/contents/markdown/"+chapterName+"/exercises/"+exerciseName+"/answers"; document.getElementById("link2").innerHTML = "https://api.github.com/repos/aimacode/aima-exercises/contents/markdown/"+chapterName+"/exercises/"+exerciseName+"/answers"; </script> </div> <label for="sidebar-checkbox" class="sidebar-toggle"></label> <script> (function(document) { var toggle = document.querySelector('.sidebar-toggle'); var sidebar = document.querySelector('#sidebar'); var checkbox = document.querySelector('#sidebar-checkbox'); document.addEventListener('click', function(e) { var target = e.target; if(!checkbox.checked || sidebar.contains(target) || (target === checkbox || target === toggle)) return; checkbox.checked = false; }, false); })(document); </script> <script src="/aima-exercises/js/main.js"></script> <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script> <script src="/aima-exercises/js/answer.js"></script> <script src="/aima-exercises/js/commsol.js"></script> <script src="/aima-exercises/js/forms.js"></script> <script src="/aima-exercises/js/crossref.js"></script> <script src="/aima-exercises/js/bookmark.js"></script> <script src="https://cdn.jsdelivr.net/npm/marked/marked.min.js"></script> </body> </html>
{ "pile_set_name": "Github" }
<div class="modal fade show" id="start-install-modal" data-easein="shrinkIn" role="dialog" aria-hidden="true"> <div class="modal-dialog" style="width: 600px"> <div class="modal-content bg-primary"> <div class="modal-header"> <h4 class="modal-title">安装模块 </h4> <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">×</span></button> </div> <div class="modal-body"> <div class="row"> <div class="col-12 col-12"> <form class="form-inline" id="startInstallForm" method="post"> <div class="form-group" id="machine-select-group" > <label for="scenario-name" class="col-3 control-label">应用</label> <div class="col-8"> <input type="text" class="form-control form-control-sm" name="appName" autocomplete="off" placeholder="appName" style="width: 300px"> </div> </div> <div class="form-group" id="machine-select-group" style="margin-top: 10px"> <label for="scenario-name" class="col-3 control-label">机器</label> <div class="col-8"> <input type="text" class="form-control form-control-sm" name="ip" autocomplete="off" placeholder="ip" style="width: 300px"> </div> </div> </form> </div> </div> </div> <div class="modal-footer justify-content-between"> <button type="button" class="btn btn-outline-light pull-left" data-dismiss="modal">取消</button> <button type="button" class="btn btn-outline-light" id="start-install-btn">确定</button> </div> </div><!-- /.modal-content --> </div><!-- /.modal-dialog --> </div>
{ "pile_set_name": "Github" }
// Prepare demo data // Data is joined to map using value of 'hc-key' property by default. // See API docs for 'joinBy' for more info on linking data and map. var data = [ ['td-ma', 0], ['td-sa', 1], ['td-nj', 2], ['td-lo', 3], ['td-mw', 4], ['td-br', 5], ['td-ti', 6], ['td-en', 7], ['td-cg', 8], ['td-bg', 9], ['td-si', 10], ['td-mo', 11], ['td-hd', 12], ['td-km', 13], ['td-lc', 14], ['td-bi', 15], ['td-ba', 16], ['td-gr', 17], ['td-oa', 18], ['td-lr', 19], ['td-me', 20], ['td-ta', 21] ]; // Create the chart Highcharts.mapChart('container', { chart: { map: 'countries/td/td-all' }, title: { text: 'Highmaps basic demo' }, subtitle: { text: 'Source map: <a href="http://code.highcharts.com/mapdata/countries/td/td-all.js">Chad</a>' }, mapNavigation: { enabled: true, buttonOptions: { verticalAlign: 'bottom' } }, colorAxis: { min: 0 }, series: [{ data: data, name: 'Random data', states: { hover: { color: '#BADA55' } }, dataLabels: { enabled: true, format: '{point.name}' } }] });
{ "pile_set_name": "Github" }
/********************************************************************** ceabstracteditor.h Base class for crystal builder editor dockwidgets Copyright (C) 2011 by David C. Lonie This file is part of the Avogadro molecular editor project. For more information, see <http://avogadro.cc/> This source code is released under the New BSD License, (the "License"). Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ***********************************************************************/ #include "ceabstracteditor.h" #include <QtGui/QMainWindow> #include <QtCore/QSettings> #include "../crystallographyextension.h" namespace Avogadro { CEAbstractEditor::CEAbstractEditor(CrystallographyExtension *ext) : CEAbstractDockWidget(ext), m_isLocked(false) { connect(this, SIGNAL(invalidInput()), this, SLOT(markAsInvalid())); connect(this, SIGNAL(validInput()), this, SLOT(markAsValid())); connect(m_ext, SIGNAL(cellChanged()), this, SLOT(refreshEditor())); connect(this, SIGNAL(visibilityChanged()), m_ext, SLOT(refreshActions())); connect(this, SIGNAL(editStarted()), m_ext, SLOT(lockEditors())); connect(this, SIGNAL(editAccepted()), m_ext, SLOT(unlockEditors())); connect(this, SIGNAL(editRejected()), m_ext, SLOT(unlockEditors())); } CEAbstractEditor::~CEAbstractEditor() { } }
{ "pile_set_name": "Github" }
// Copyright © 2019 The Things Network Foundation, The Things Industries B.V. // // 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 sendgrid provides the implementation of an email sender using SendGrid. package sendgrid import ( "context" "github.com/sendgrid/sendgrid-go" "github.com/sendgrid/sendgrid-go/helpers/mail" "go.thethings.network/lorawan-stack/v3/pkg/email" "go.thethings.network/lorawan-stack/v3/pkg/errors" "go.thethings.network/lorawan-stack/v3/pkg/log" ) // SendGrid is the type that implements SendGrid as email provider. type SendGrid struct { logger log.Interface config Config client *sendgrid.Client fromEmail *mail.Email } // New creates a SendGrid email provider. func New(ctx context.Context, emailConfig email.Config, sgConfig Config) (email.Sender, error) { provider := &SendGrid{ logger: log.FromContext(ctx).WithField("email_provider", "SendGrid"), config: sgConfig, client: sendgrid.NewSendClient(sgConfig.APIKey), fromEmail: mail.NewEmail(emailConfig.SenderName, emailConfig.SenderAddress), } return provider, nil } var errEmailNotSent = errors.DefineInternal("email_not_sent", "email was not sent") // Send an email message. func (s *SendGrid) Send(message *email.Message) error { logger := s.logger.WithFields(log.Fields( "template_name", message.TemplateName, "recipient_name", message.RecipientName, "recipient_address", message.RecipientAddress, )) email, err := s.buildEmail(message) if err != nil { return err } logger.Debug("Sending email...") response, err := s.client.Send(email) if err != nil { return errEmailNotSent.WithCause(err) } if response.StatusCode >= 300 { attributes := []interface{}{ "status_code", response.StatusCode, "response", response.Body, } logger.WithFields(log.Fields(attributes...)).WithError(err).Error("Could not send email") return errEmailNotSent.WithAttributes(attributes...) } logger.Info("Sent email") return nil } func (s *SendGrid) buildEmail(email *email.Message) (*mail.SGMailV3, error) { message := mail.NewV3MailInit( s.fromEmail, email.Subject, mail.NewEmail(email.RecipientName, email.RecipientAddress), ) if email.TextBody != "" { message.AddContent(mail.NewContent("text/plain", email.TextBody)) } if email.HTMLBody != "" { message.AddContent(mail.NewContent("text/html", email.HTMLBody)) } if s.config.SandboxMode { settings := mail.NewMailSettings() settings.SetSandboxMode(mail.NewSetting(true)) message = message.SetMailSettings(settings) } return message, nil }
{ "pile_set_name": "Github" }
package tillerino.tillerinobot.predicates; import lombok.Value; import java.util.Optional; import org.tillerino.osuApiModel.Mods; import org.tillerino.osuApiModel.OsuApiBeatmap; import tillerino.tillerinobot.UserException; import tillerino.tillerinobot.lang.Language; import tillerino.tillerinobot.predicates.PredicateParser.PredicateBuilder; import tillerino.tillerinobot.recommendations.BareRecommendation; import tillerino.tillerinobot.recommendations.RecommendationRequest; @Value public class ExcludeMod implements RecommendationPredicate { Mods mod; @Override public boolean test(BareRecommendation r, OsuApiBeatmap beatmap) { return !mod.is(r.getMods()); } @Override public boolean contradicts(RecommendationPredicate otherPredicate) { return false; } @Override public String getOriginalArgument() { return "-" + mod.getShortName(); } public static class Builder implements PredicateBuilder<ExcludeMod> { @Override public ExcludeMod build(String argument, Language lang) throws UserException { if (!argument.startsWith("-")) { return null; } try { Mods mod = Mods.fromShortName(argument.substring(1).toUpperCase()); if (mod == null) { return null; } return new ExcludeMod(mod); } catch (IllegalArgumentException e) { return null; } } } @Override public Optional<String> findNonPredicateContradiction(RecommendationRequest request) { if (mod.is(request.getRequestedMods())) { return Optional.of(String.format("%s -%s", mod.getShortName(), mod.getShortName())); } return Optional.empty(); } }
{ "pile_set_name": "Github" }
<?php /** * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ declare(strict_types=1); /** * Tests for \Magento\Framework\Data\Form\Element\Reset */ namespace Magento\Framework\Data\Test\Unit\Form\Element; use Magento\Framework\Data\Form\Element\CollectionFactory; use Magento\Framework\Data\Form\Element\Factory; use Magento\Framework\Data\Form\Element\Reset; use Magento\Framework\DataObject; use Magento\Framework\Escaper; use PHPUnit\Framework\MockObject\MockObject; use PHPUnit\Framework\TestCase; class ResetTest extends TestCase { /** * @var MockObject */ protected $_objectManagerMock; /** * @var Reset */ protected $_model; protected function setUp(): void { $factoryMock = $this->createMock(Factory::class); $collectionFactoryMock = $this->createMock(CollectionFactory::class); $escaperMock = $this->createMock(Escaper::class); $this->_model = new Reset( $factoryMock, $collectionFactoryMock, $escaperMock ); $formMock = new DataObject(); $formMock->getHtmlIdPrefix('id_prefix'); $formMock->getHtmlIdPrefix('id_suffix'); $this->_model->setForm($formMock); } /** * @covers \Magento\Framework\Data\Form\Element\Reset::__construct */ public function testConstruct() { $this->assertEquals('text', $this->_model->getType()); $this->assertEquals('textfield', $this->_model->getExtType()); } }
{ "pile_set_name": "Github" }
Thanks for sending a pull request! **Please make sure that you are using `feature` branch, since all the WiFi Analyzer changes are done on the `feature` branch!** [How to submit a pull request](https://github.com/VREMSoftwareDevelopment/WiFiAnalyzer/wiki/Pull-Request) **What does this implement/fix? Please describe.** - A clear and concise description of the changes. **Does this close any currently open issues?** - Please provide issue(s) number. **Additional context** - Add any other context about the pull request. **Where has this been tested?** - Operating System: - Platform: - Target Platform: - Toolchain Version: - SDK Version:
{ "pile_set_name": "Github" }
%description: This test contains basic checks for integration. %includes: #include "inet/common/math/Functions.h" %global: using namespace inet; using namespace inet::math; using namespace inet::units::values; %activity: // 1 dimensional Ptr<const IFunction<double, Domain<simtime_t>>> c2 = makeShared<Boxcar1DFunction<double, simtime_t>>(-1, 1, 5); std::cout << "f(s) = 5: f(0) = " << c2->getValue(Point<simtime_t>(0)) << ", max(f) = " << c2->getMax(Interval<simtime_t>(Point<simtime_t>(-1), Point<simtime_t>(1), 0b1, 0b0, 0b0)) << std::endl; Ptr<const IFunction<double, Domain<>>> i2 = integrate<double, Domain<simtime_t>, 0b0, double, Domain<>>(c2); std::cout << "f(s) = 5: I(f, s)() = " << i2->getValue(Point<>()) << std::endl; // 2 dimensional Ptr<const IFunction<double, Domain<simtime_t, Hz>>> c3 = makeShared<Boxcar2DFunction<double, simtime_t, Hz>>(-1, 1, Hz(-1), Hz(1), 5); std::cout << "f(s, Hz) = 5: f(0, 0) = " << c3->getValue(Point<simtime_t, Hz>(0, Hz(0))) << ", max(f) = " << c3->getMax(Interval<simtime_t, Hz>(Point<simtime_t, Hz>(-1, Hz(-1)), Point<simtime_t, Hz>(1, Hz(1)), 0b11, 0b00, 0b00)) << std::endl; Ptr<const IFunction<double, Domain<simtime_t>>> i3 = integrate<double, Domain<simtime_t, Hz>, 0b10, double, Domain<simtime_t>>(c3); std::cout << "f(s, Hz) = 5: I(f, Hz)(0) = " << i3->getValue(Point<simtime_t>(0)) << ", max(f) = " << i3->getMax(Interval<simtime_t>(Point<simtime_t>(-1), Point<simtime_t>(1), 0b1, 0b0, 0b0)) << std::endl; Ptr<const IFunction<double, Domain<>>> i4 = integrate<double, Domain<simtime_t>, 0b0, double, Domain<>>(i3); std::cout << "f(s, Hz) = 5: I(I(f, Hz), s)() = " << i4->getValue(Point<>()) << std::endl; %contains: stdout f(s) = 5: f(0) = 5, max(f) = 5 f(s) = 5: I(f, s)() = 10 f(s, Hz) = 5: f(0, 0) = 5, max(f) = 5 f(s, Hz) = 5: I(f, Hz)(0) = 10, max(f) = 10 f(s, Hz) = 5: I(I(f, Hz), s)() = 20
{ "pile_set_name": "Github" }
## 执行上下文 可执行代码:全局代码、函数代码、eval 代码 ## 执行上下文栈 当执行一个函数的时候,就会创建一个执行上下文,并且压入执行上下文栈,当函数执行完毕的时候,就会将函数的执行上下文从栈中弹出 ```js function fun3() { console.log("fun3"); } function fun2() { fun3(); } function fun1() { fun2(); } fun1(); // 伪代码 // fun1() ECStack.push(<fun1> functionContext); // fun1中竟然调用了fun2,还要创建fun2的执行上下文 ECStack.push(<fun2> functionContext); // 擦,fun2还调用了fun3! ECStack.push(<fun3> functionContext); // fun3执行完毕 ECStack.pop(); // fun2执行完毕 ECStack.pop(); // fun1执行完毕 ECStack.pop(); // javascript接着执行下面的代码,但是ECStack底层永远有个globalContext ``` ## 执行上下文包含 变量对象(Variable object,VO) [作用域链(Scope chain)](./scope-chain.md) [this](./this.md) #### 全局上下文 函数上下文 全局上下文中的变量对象就是全局对象呐! 只有到当进入一个执行上下文中,这个执行上下文的变量对象才会被激活,所以才叫 activation object 呐, 而只有被激活的变量对象,也就是活动对象上的各种属性才能被访问。 活动对象是在进入函数上下文时刻被创建的,它通过函数的 arguments 属性初始化。arguments 属性值是 Arguments 对象。 #### 执行过程 进入执行上下文 代码执行 ## 变量对象 ##### 函数的所有形参 (如果是函数上下文) 由名称和对应值组成的一个变量对象的属性被创建 没有实参,属性值设为 undefined ##### 函数声明 由名称和对应值(函数对象(function-object))组成一个变量对象的属性被创建 如果变量对象已经存在相同名称的属性,则完全替换这个属性 ##### 变量声明 由名称和对应值(undefined)组成一个变量对象的属性被创建; 如果变量名称跟已经声明的形式参数或函数相同,则变量声明不会干扰已经存在的这类属性 ```js function foo(a) { var b = 2; function c() {} var d = function() {}; b = 3; } foo(1); AO = { arguments: { 0: 1, length: 1 }, a: 1, b: undefined, c: reference to function c(){}, d: undefined } ``` #### 代码执行 ```js AO = { arguments: { 0: 1, length: 1 }, a: 1, b: 3, c: reference to function c(){}, d: reference to FunctionExpression "d" } ``` #### 思考题 ```js function foo() { console.log(a); a = 1; } foo(); // ??? function bar() { a = 1; console.log(a); } bar(); // ??? // 第一段会报错:Uncaught ReferenceError: a is not defined。 // 这是因为函数中的 "a" 并没有通过 var 关键字声明,所有不会被存放在 AO 中。全局也没有 // 第二段会打印:1。 // 当第二段执行 console 的时候,全局对象已经被赋予了 a 属性,这时候就可以从全局找到 a 的值,所以会打印 1。 ```
{ "pile_set_name": "Github" }
#include "MinimalKeyType.h" std::atomic<int> MinimalKeyType::instances(0);
{ "pile_set_name": "Github" }
"use strict"; require("retape")(require("./index"))
{ "pile_set_name": "Github" }
# SHELL=/bin/bash TARGET_VERSION ?= latest all: docker docker: docker build --pull --no-cache -t antidotelabs/wordpress:$(TARGET_VERSION) . docker push antidotelabs/wordpress:$(TARGET_VERSION)
{ "pile_set_name": "Github" }
<?xml version="1.0" encoding="utf-8"?> <translate xmlns:android="http://schemas.android.com/apk/res/android" android:duration="@android:integer/config_mediumAnimTime" android:fromYDelta="0%p" android:toYDelta="100%p" />
{ "pile_set_name": "Github" }
export * from 'rxjs-compat/operators/min';
{ "pile_set_name": "Github" }
throw Error("Coucou")
{ "pile_set_name": "Github" }
"resource/UI/DemoPolish.res" { "DemoPolish" { "ControlName" "Frame" "fieldName" "DemoPolish" "xpos" "214" "ypos" "52" "wide" "280" "tall" "480" "autoResize" "0" "pinCorner" "0" "visible" "1" "enabled" "1" "tabPosition" "0" "settitlebarvisible" "1" "title" "Demo Polish Options" } "frame_topGrip" { "ControlName" "Panel" "fieldName" "frame_topGrip" "xpos" "5" "ypos" "0" "wide" "189" "tall" "3" "autoResize" "0" "pinCorner" "0" "visible" "1" "enabled" "1" "tabPosition" "0" } "frame_bottomGrip" { "ControlName" "Panel" "fieldName" "frame_bottomGrip" "xpos" "5" "ypos" "296" "wide" "182" "tall" "3" "autoResize" "0" "pinCorner" "0" "visible" "1" "enabled" "1" "tabPosition" "0" } "frame_leftGrip" { "ControlName" "Panel" "fieldName" "frame_leftGrip" "xpos" "0" "ypos" "5" "wide" "3" "tall" "289" "autoResize" "0" "pinCorner" "0" "visible" "1" "enabled" "1" "tabPosition" "0" } "frame_rightGrip" { "ControlName" "Panel" "fieldName" "frame_rightGrip" "xpos" "196" "ypos" "5" "wide" "3" "tall" "282" "autoResize" "0" "pinCorner" "0" "visible" "1" "enabled" "1" "tabPosition" "0" } "frame_tlGrip" { "ControlName" "Panel" "fieldName" "frame_tlGrip" "xpos" "0" "ypos" "0" "wide" "5" "tall" "5" "autoResize" "0" "pinCorner" "0" "visible" "1" "enabled" "1" "tabPosition" "0" } "frame_trGrip" { "ControlName" "Panel" "fieldName" "frame_trGrip" "xpos" "194" "ypos" "0" "wide" "5" "tall" "5" "autoResize" "0" "pinCorner" "0" "visible" "1" "enabled" "1" "tabPosition" "0" } "frame_blGrip" { "ControlName" "Panel" "fieldName" "frame_blGrip" "xpos" "0" "ypos" "294" "wide" "5" "tall" "5" "autoResize" "0" "pinCorner" "0" "visible" "1" "enabled" "1" "tabPosition" "0" } "frame_brGrip" { "ControlName" "Panel" "fieldName" "frame_brGrip" "xpos" "188" "ypos" "288" "wide" "12" "tall" "12" "autoResize" "0" "pinCorner" "0" "visible" "1" "enabled" "1" "tabPosition" "0" } "frame_caption" { "ControlName" "Panel" "fieldName" "frame_caption" "xpos" "0" "ypos" "0" "wide" "193" "tall" "15" "autoResize" "0" "pinCorner" "0" "visible" "1" "enabled" "1" "tabPosition" "0" } "frame_minimize" { "ControlName" "Button" "fieldName" "frame_minimize" "xpos" "0" "ypos" "0" "wide" "12" "tall" "12" "autoResize" "0" "pinCorner" "0" "visible" "0" "enabled" "1" "tabPosition" "0" "labelText" "0" "textAlignment" "north-west" "dulltext" "0" "brighttext" "0" "wrap" "0" "Default" "0" } "frame_maximize" { "ControlName" "Button" "fieldName" "frame_maximize" "xpos" "0" "ypos" "0" "wide" "12" "tall" "12" "autoResize" "0" "pinCorner" "0" "visible" "0" "enabled" "1" "tabPosition" "0" "labelText" "1" "textAlignment" "north-west" "dulltext" "0" "brighttext" "0" "wrap" "0" "Default" "0" } "frame_mintosystray" { "ControlName" "Button" "fieldName" "frame_mintosystray" "xpos" "0" "ypos" "0" "wide" "12" "tall" "12" "autoResize" "0" "pinCorner" "0" "visible" "0" "enabled" "1" "tabPosition" "0" "labelText" "o" "textAlignment" "north-west" "dulltext" "0" "brighttext" "0" "wrap" "0" "Command" "MinimizeToSysTray" "Default" "0" } "frame_close" { "ControlName" "Button" "fieldName" "frame_close" "xpos" "0" "ypos" "0" "wide" "12" "tall" "12" "autoResize" "0" "pinCorner" "0" "visible" "0" "enabled" "1" "tabPosition" "0" "labelText" "r" "textAlignment" "north-west" "dulltext" "0" "brighttext" "0" "wrap" "0" "Default" "0" } "frame_menu" { "ControlName" "FrameSystemButton" "fieldName" "frame_menu" "xpos" "4" "ypos" "5" "wide" "12" "tall" "12" "autoResize" "0" "pinCorner" "0" "visible" "1" "enabled" "1" "tabPosition" "0" "textAlignment" "west" "dulltext" "0" "brighttext" "0" "wrap" "0" "Default" "0" } "Button_save" { "ControlName" "Button" "fieldName" "Button_save" "xpos" "150" "ypos" "276" "wide" "40" "tall" "16" "autoResize" "0" "pinCorner" "0" "visible" "1" "enabled" "1" "tabPosition" "0" "labelText" "Save" "textAlignment" "center" "dulltext" "0" "brighttext" "0" "wrap" "0" "Default" "1" } "BuildModeDialog" { "ControlName" "BuildModeDialog" "fieldName" "BuildModeDialog" "xpos" "9" "ypos" "52" "wide" "200" "tall" "280" "autoResize" "0" "pinCorner" "0" "visible" "1" "enabled" "1" "tabPosition" "0" "settitlebarvisible" "1" "title" "#Frame_Untitled" } "Combo_selector" { "ControlName" "ComboBox" "fieldName" "Combo_selector" "xpos" "10" "ypos" "28" "wide" "260" "tall" "16" "autoResize" "0" "pinCorner" "0" "visible" "1" "enabled" "1" "tabPosition" "0" "textHidden" "0" "editable" "1" "maxchars" "-1" "NumericInputOnly" "0" "unicode" "0" } }
{ "pile_set_name": "Github" }
<?xml version="1.0" encoding="UTF-8"?> <!-- Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. This program and the accompanying materials are made available under the terms of the Eclipse Public License v. 2.0, which is available at http://www.eclipse.org/legal/epl-2.0. This Source Code may also be made available under the following Secondary Licenses when the conditions for such availability set forth in the Eclipse Public License v. 2.0 are satisfied: GNU General Public License, version 2 with the GNU Classpath Exception, which is available at https://www.gnu.org/software/classpath/license.html. SPDX-License-Identifier: EPL-2.0 OR GPL-2.0 WITH Classpath-exception-2.0 --> <!DOCTYPE sun-web-app PUBLIC "-//Sun Microsystems, Inc.//DTD Application Server 8.1 Servlet 2.4//EN" "http://www.sun.com/software/sunone/appserver/dtds/sun-web-app_2_4-1.dtd"> <sun-web-app> <session-config> <session-manager> <manager-properties> <property name="sessionFilename" value="mysessionfile" /> </manager-properties> </session-manager> </session-config> </sun-web-app>
{ "pile_set_name": "Github" }
package lib import ( "errors" "go.dedis.ch/kyber/v3" "go.dedis.ch/kyber/v3/share/dkg/rabin" "go.dedis.ch/kyber/v3/util/random" "go.dedis.ch/cothority/v3" ) // RandomKeyPair creates a random public/private Diffie-Hellman key pair. func RandomKeyPair() (x kyber.Scalar, X kyber.Point) { x = cothority.Suite.Scalar().Pick(random.New()) X = cothority.Suite.Point().Mul(x, nil) return } // SharedSecret represents the needed information to do shared encryption and decryption. type SharedSecret struct { Index int V kyber.Scalar X kyber.Point Commits []kyber.Point } // NewSharedSecret takes an initialized DistKeyGenerator and returns the // minimal set of values necessary to do shared encryption/decryption. func NewSharedSecret(dkg *dkg.DistKeyGenerator) (*SharedSecret, error) { if dkg == nil { return nil, errors.New("no valid dkg given") } if !dkg.Finished() { return nil, errors.New("dkg is not finished yet") } dks, err := dkg.DistKeyShare() if err != nil { return nil, err } return &SharedSecret{ Index: dks.Share.I, V: dks.Share.V, X: dks.Public(), Commits: dks.Commits, }, nil } // DKGSimulate runs an offline version of the DKG protocol. func DKGSimulate(nbrNodes, threshold int) (dkgs []*dkg.DistKeyGenerator, err error) { dkgs = make([]*dkg.DistKeyGenerator, nbrNodes) scalars := make([]kyber.Scalar, nbrNodes) points := make([]kyber.Point, nbrNodes) // 1a - initialisation for i := range scalars { scalars[i] = cothority.Suite.Scalar().Pick(cothority.Suite.RandomStream()) points[i] = cothority.Suite.Point().Mul(scalars[i], nil) } // 1b - key-sharing for i := range dkgs { dkgs[i], err = dkg.NewDistKeyGenerator(cothority.Suite, scalars[i], points, threshold) if err != nil { return } } // Exchange of Deals responses := make([][]*dkg.Response, nbrNodes) for i, p := range dkgs { responses[i] = make([]*dkg.Response, nbrNodes) deals, err := p.Deals() if err != nil { return nil, err } for j, d := range deals { responses[i][j], err = dkgs[j].ProcessDeal(d) if err != nil { return nil, err } } } // ProcessResponses for _, resp := range responses { for j, r := range resp { for k, p := range dkgs { if r != nil && j != k { p.ProcessResponse(r) } } } } // Secret commits for _, p := range dkgs { commit, err := p.SecretCommits() if err != nil { return nil, err } for _, p2 := range dkgs { p2.ProcessSecretCommits(commit) } } // Verify if all is OK for _, p := range dkgs { if !p.Finished() { return nil, errors.New("one of the dkgs is not finished yet") } } return }
{ "pile_set_name": "Github" }
<template> <component :is="type" v-bind="linkProps(to)"> <slot /> </component> </template> <script> import { isExternal } from '@/utils/validate' export default { props: { to: { type: String, required: true } }, computed: { isExternal() { return isExternal(this.to) }, type() { if (this.isExternal) { return 'a' } return 'router-link' } }, methods: { linkProps(to) { if (this.isExternal) { return { href: to, target: '_blank', rel: 'noopener' } } return { to: to } } } } </script>
{ "pile_set_name": "Github" }
--- title: 投影运算 ms.date: 07/20/2015 ms.assetid: b8d38e6d-21cf-4619-8dbb-94476f4badc7 ms.openlocfilehash: 4795bdaba53949b34fe380ea9c51025ce43c40db ms.sourcegitcommit: f8c270376ed905f6a8896ce0fe25b4f4b38ff498 ms.translationtype: MT ms.contentlocale: zh-CN ms.lasthandoff: 06/04/2020 ms.locfileid: "84396332" --- # <a name="projection-operations-visual-basic"></a>投影操作(Visual Basic) 投影是指将对象转换为一种新形式的操作,该形式通常只包含那些将随后使用的属性。 通过使用投影,您可以构造从每个对象生成的新类型。 可以投影属性,并对该属性执行数学函数。 还可以在不更改原始对象的情况下投影该对象。 下面一节列出了执行投影的标准查询运算符方法。 ## <a name="methods"></a>方法 |方法名|说明|Visual Basic 查询表达式语法|详细信息| |-----------------|-----------------|------------------------------------------|----------------------| |选择|投影基于转换函数的值。|`Select`|<xref:System.Linq.Enumerable.Select%2A?displayProperty=nameWithType><br /><br /> <xref:System.Linq.Queryable.Select%2A?displayProperty=nameWithType>| |SelectMany|投影基于转换函数的值序列,然后将它们展平为一个序列。|使用多个 `From` 子句|<xref:System.Linq.Enumerable.SelectMany%2A?displayProperty=nameWithType><br /><br /> <xref:System.Linq.Queryable.SelectMany%2A?displayProperty=nameWithType>| ## <a name="query-expression-syntax-examples"></a>查询表达式语法示例 ### <a name="select"></a>选择 下面的示例使用 `Select` 子句来投影字符串列表中每个字符串的第一个字母。 ```vb Dim words = New List(Of String) From {"an", "apple", "a", "day"} Dim query = From word In words Select word.Substring(0, 1) Dim sb As New System.Text.StringBuilder() For Each letter As String In query sb.AppendLine(letter) Next ' Display the output. MsgBox(sb.ToString()) ' This code produces the following output: ' a ' a ' a ' d ``` ### <a name="selectmany"></a>SelectMany 下面的示例使用多个 `From` 子句来投影字符串列表中每个字符串的每个单词。 ```vb Dim phrases = New List(Of String) From {"an apple a day", "the quick brown fox"} Dim query = From phrase In phrases From word In phrase.Split(" "c) Select word Dim sb As New System.Text.StringBuilder() For Each str As String In query sb.AppendLine(str) Next ' Display the output. MsgBox(sb.ToString()) ' This code produces the following output: ' an ' apple ' a ' day ' the ' quick ' brown ' fox ``` ## <a name="select-versus-selectmany"></a>Select 与 SelectMany `Select()` 和 `SelectMany()` 的工作都是依据源值生成一个或多个结果值。 `Select()` 为每个源值生成一个结果值。 因此,总体结果是一个与源集合具有相同元素数目的集合。 与之相反,`SelectMany()` 生成单个总体结果,其中包含来自每个源值的串联子集合。 作为参数传递到 `SelectMany()` 的转换函数必须为每个源值返回一个可枚举值序列。 然后,`SelectMany()` 串联这些可枚举序列,以创建一个大的序列。 下面两个插图演示了这两个方法的操作之间的概念性区别。 在每种情况下,假定选择器(转换)函数从每个源值中选择一个由花卉数据组成的数组。 下图描述 `Select()` 如何返回一个与源集合具有相同元素数目的集合。 ![显示 Select() 的操作的图](./media/projection-operations/select-action-graphic.png) 下图描述 `SelectMany()` 如何将中间数组序列串联为一个最终结果值,其中包含每个中间数组中的每个值。 ![显示 SelectMany() 的操作的图。](./media/projection-operations/select-many-action-graphic.png ) ### <a name="code-example"></a>代码示例 下面的示例比较 `Select()` 和 `SelectMany()` 的行为。 代码通过从源集合的每个花卉名称列表中提取前两项来创建一个“花束”。 此示例中,transform 函数 <xref:System.Linq.Enumerable.Select%60%602%28System.Collections.Generic.IEnumerable%7B%60%600%7D%2CSystem.Func%7B%60%600%2C%60%601%7D%29> 使用的“单值”本身即是值的集合。 这需要额外的 `For Each` 循环,以便枚举每个子序列中的每个字符串。 ```vb Class Bouquet Public Flowers As List(Of String) End Class Sub SelectVsSelectMany() Dim bouquets = New List(Of Bouquet) From { New Bouquet With {.Flowers = New List(Of String)(New String() {"sunflower", "daisy", "daffodil", "larkspur"})}, New Bouquet With {.Flowers = New List(Of String)(New String() {"tulip", "rose", "orchid"})}, New Bouquet With {.Flowers = New List(Of String)(New String() {"gladiolis", "lily", "snapdragon", "aster", "protea"})}, New Bouquet With {.Flowers = New List(Of String)(New String() {"larkspur", "lilac", "iris", "dahlia"})}} Dim output As New System.Text.StringBuilder ' Select() Dim query1 = bouquets.Select(Function(b) b.Flowers) output.AppendLine("Using Select():") For Each flowerList In query1 For Each str As String In flowerList output.AppendLine(str) Next Next ' SelectMany() Dim query2 = bouquets.SelectMany(Function(b) b.Flowers) output.AppendLine(vbCrLf & "Using SelectMany():") For Each str As String In query2 output.AppendLine(str) Next ' Display the output MsgBox(output.ToString()) ' This code produces the following output: ' ' Using Select(): ' sunflower ' daisy ' daffodil ' larkspur ' tulip ' rose ' orchid ' gladiolis ' lily ' snapdragon ' aster ' protea ' larkspur ' lilac ' iris ' dahlia ' Using SelectMany() ' sunflower ' daisy ' daffodil ' larkspur ' tulip ' rose ' orchid ' gladiolis ' lily ' snapdragon ' aster ' protea ' larkspur ' lilac ' iris ' dahlia End Sub ``` ## <a name="see-also"></a>另请参阅 - <xref:System.Linq> - [标准查询运算符概述 (Visual Basic)](standard-query-operators-overview.md) - [Select 子句](../../../language-reference/queries/select-clause.md) - [如何:使用联接合并数据](../../language-features/linq/how-to-combine-data-with-linq-by-using-joins.md) - [如何:从多个源填充对象集合(LINQ)(Visual Basic)](how-to-populate-object-collections-from-multiple-sources-linq.md) - [如何:以特定类型返回 LINQ 查询结果](../../language-features/linq/how-to-return-a-linq-query-result-as-a-specific-type.md) - [如何:使用组将一个文件拆分成多个文件(LINQ)(Visual Basic)](how-to-split-a-file-into-many-files-by-using-groups-linq.md)
{ "pile_set_name": "Github" }
package apimodels; import java.time.OffsetDateTime; import com.fasterxml.jackson.annotation.*; import java.util.Set; import javax.validation.*; import java.util.Objects; import javax.validation.constraints.*; /** * An order for a pets from the pet store */ @SuppressWarnings({"UnusedReturnValue", "WeakerAccess"}) public class Order { @JsonProperty("id") private Long id = null; @JsonProperty("petId") private Long petId = null; @JsonProperty("quantity") private Integer quantity = null; @JsonProperty("shipDate") private OffsetDateTime shipDate = null; /** * Order Status */ public enum StatusEnum { PLACED("placed"), APPROVED("approved"), DELIVERED("delivered"); private final String value; StatusEnum(String value) { this.value = value; } @Override @JsonValue public String toString() { return String.valueOf(value); } @JsonCreator public static StatusEnum fromValue(String text) { for (StatusEnum b : StatusEnum.values()) { if (String.valueOf(b.value).equals(text)) { return b; } } return null; } } @JsonProperty("status") private StatusEnum status = null; @JsonProperty("complete") private Boolean complete = false; public Order id(Long id) { this.id = id; return this; } /** * Get id * @return id **/ public Long getId() { return id; } public void setId(Long id) { this.id = id; } public Order petId(Long petId) { this.petId = petId; return this; } /** * Get petId * @return petId **/ public Long getPetId() { return petId; } public void setPetId(Long petId) { this.petId = petId; } public Order quantity(Integer quantity) { this.quantity = quantity; return this; } /** * Get quantity * @return quantity **/ public Integer getQuantity() { return quantity; } public void setQuantity(Integer quantity) { this.quantity = quantity; } public Order shipDate(OffsetDateTime shipDate) { this.shipDate = shipDate; return this; } /** * Get shipDate * @return shipDate **/ @Valid public OffsetDateTime getShipDate() { return shipDate; } public void setShipDate(OffsetDateTime shipDate) { this.shipDate = shipDate; } public Order status(StatusEnum status) { this.status = status; return this; } /** * Order Status * @return status **/ public StatusEnum getStatus() { return status; } public void setStatus(StatusEnum status) { this.status = status; } public Order complete(Boolean complete) { this.complete = complete; return this; } /** * Get complete * @return complete **/ public Boolean isComplete() { return complete; } public void setComplete(Boolean complete) { this.complete = complete; } @Override public boolean equals(java.lang.Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } Order order = (Order) o; return Objects.equals(id, order.id) && Objects.equals(petId, order.petId) && Objects.equals(quantity, order.quantity) && Objects.equals(shipDate, order.shipDate) && Objects.equals(status, order.status) && Objects.equals(complete, order.complete); } @Override public int hashCode() { return Objects.hash(id, petId, quantity, shipDate, status, complete); } @SuppressWarnings("StringBufferReplaceableByString") @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append("class Order {\n"); sb.append(" id: ").append(toIndentedString(id)).append("\n"); sb.append(" petId: ").append(toIndentedString(petId)).append("\n"); sb.append(" quantity: ").append(toIndentedString(quantity)).append("\n"); sb.append(" shipDate: ").append(toIndentedString(shipDate)).append("\n"); sb.append(" status: ").append(toIndentedString(status)).append("\n"); sb.append(" complete: ").append(toIndentedString(complete)).append("\n"); sb.append("}"); return sb.toString(); } /** * Convert the given object to string with each line indented by 4 spaces * (except the first line). */ private String toIndentedString(java.lang.Object o) { if (o == null) { return "null"; } return o.toString().replace("\n", "\n "); } }
{ "pile_set_name": "Github" }
args @ { fetchurl, ... }: rec { baseName = ''mt19937''; version = ''1.1.1''; description = ''Portable MT19937 Mersenne Twister random number generator''; deps = [ ]; src = fetchurl { url = ''http://beta.quicklisp.org/archive/mt19937/2011-02-19/mt19937-1.1.1.tgz''; sha256 = ''1iw636b0iw5ygkv02y8i41lh7xj0acglv0hg5agryn0zzi2nf1xv''; }; packageName = "mt19937"; asdFilesToKeep = ["mt19937.asd"]; overrides = x: x; } /* (SYSTEM mt19937 DESCRIPTION Portable MT19937 Mersenne Twister random number generator SHA256 1iw636b0iw5ygkv02y8i41lh7xj0acglv0hg5agryn0zzi2nf1xv URL http://beta.quicklisp.org/archive/mt19937/2011-02-19/mt19937-1.1.1.tgz MD5 54c63977b6d77abd66ebe0227b77c143 NAME mt19937 FILENAME mt19937 DEPS NIL DEPENDENCIES NIL VERSION 1.1.1 SIBLINGS NIL PARASITES NIL) */
{ "pile_set_name": "Github" }
/** * @directive sb-clickwrap * @author Xtraball SAS <[email protected]> * @version 4.18.12 */ angular .module('starter') .directive('sbClickwrap', function (Application) { return { restrict: 'E', replace: false, scope: { field: '=', model: '=', cardDesign: '=?' }, templateUrl: 'templates/directives/clickwrap/clickwrap.html', link: function (scope) { if (scope.cardDesign === undefined) { scope.cardDesign = false; } scope.modal = null; scope.htmlContent = scope.field.htmlContent; // Default modal title or custom! if (scope.field.modaltitle.length > 0) { scope.modalTitle = (scope.field.modaltitle.length > 0) ? scope.field.modaltitle : scope.field.label; } }, controller: function($scope, Modal) { $scope.openModal = function () { Modal .fromTemplateUrl('templates/directives/clickwrap/clickwrap-modal.html', { scope: angular.extend($scope, { close: function () { $scope.modal.remove(); } }), animation: 'slide-in-right-left' }).then(function (modal) { $scope.modal = modal; $scope.modal.show(); return modal; }); }; $scope.onClick = function () { if (!$scope.model) { return; } $scope.openModal(); }; } }; });
{ "pile_set_name": "Github" }
// Copyright 2010 The Closure Library Authors. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS-IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. goog.provide('goog.events.KeyCodesTest'); goog.setTestOnly('goog.events.KeyCodesTest'); goog.require('goog.events.BrowserEvent'); goog.require('goog.events.KeyCodes'); goog.require('goog.object'); goog.require('goog.testing.PropertyReplacer'); goog.require('goog.testing.jsunit'); goog.require('goog.userAgent'); var KeyCodes; var stubs; function setUpPage() { KeyCodes = goog.events.KeyCodes; stubs = new goog.testing.PropertyReplacer(); } function tearDown() { stubs.reset(); } function testTextModifyingKeys() { var specialTextModifiers = goog.object.createSet( KeyCodes.BACKSPACE, KeyCodes.DELETE, KeyCodes.ENTER, KeyCodes.MAC_ENTER, KeyCodes.TAB, KeyCodes.WIN_IME); if (!goog.userAgent.GECKO) { specialTextModifiers[KeyCodes.WIN_KEY_FF_LINUX] = 1; } for (var keyId in KeyCodes) { var key = KeyCodes[keyId]; if (goog.isFunction(key)) { // skip static methods continue; } var fakeEvent = createEventWithKeyCode(key); if (KeyCodes.isCharacterKey(key) || (key in specialTextModifiers)) { assertTrue( 'Expected key to modify text: ' + keyId, KeyCodes.isTextModifyingKeyEvent(fakeEvent)); } else { assertFalse( 'Expected key to not modify text: ' + keyId, KeyCodes.isTextModifyingKeyEvent(fakeEvent)); } } for (var i = KeyCodes.FIRST_MEDIA_KEY; i <= KeyCodes.LAST_MEDIA_KEY; i++) { var fakeEvent = createEventWithKeyCode(i); assertFalse( 'Expected key to not modify text: ' + i, KeyCodes.isTextModifyingKeyEvent(fakeEvent)); } } function testKeyCodeZero() { var zeroEvent = createEventWithKeyCode(0); assertEquals( !goog.userAgent.GECKO, KeyCodes.isTextModifyingKeyEvent(zeroEvent)); assertEquals( goog.userAgent.WEBKIT || goog.userAgent.EDGE, KeyCodes.isCharacterKey(0)); } function testPhantomKey() { // KeyCode 255 deserves its own test to make sure this does not regress, // because it's so weird. See the comments in the KeyCode enum. var fakeEvent = createEventWithKeyCode(goog.events.KeyCodes.PHANTOM); assertFalse( 'Expected phantom key to not modify text', KeyCodes.isTextModifyingKeyEvent(fakeEvent)); assertFalse(KeyCodes.isCharacterKey(fakeEvent)); } function testNonUsKeyboards() { var fakeEvent = createEventWithKeyCode(1092 /* Russian a */); assertTrue( 'Expected key to not modify text: 1092', KeyCodes.isTextModifyingKeyEvent(fakeEvent)); } function createEventWithKeyCode(i) { var fakeEvent = new goog.events.BrowserEvent('keydown'); fakeEvent.keyCode = i; return fakeEvent; } function testNormalizeGeckoKeyCode() { stubs.set(goog.userAgent, 'GECKO', true); // Test Gecko-specific key codes. assertEquals( goog.events.KeyCodes.normalizeGeckoKeyCode(KeyCodes.FF_EQUALS), KeyCodes.EQUALS); assertEquals( goog.events.KeyCodes.normalizeKeyCode(KeyCodes.FF_EQUALS), KeyCodes.EQUALS); assertEquals( goog.events.KeyCodes.normalizeGeckoKeyCode(KeyCodes.FF_SEMICOLON), KeyCodes.SEMICOLON); assertEquals( goog.events.KeyCodes.normalizeKeyCode(KeyCodes.FF_SEMICOLON), KeyCodes.SEMICOLON); assertEquals( goog.events.KeyCodes.normalizeGeckoKeyCode(KeyCodes.MAC_FF_META), KeyCodes.META); assertEquals( goog.events.KeyCodes.normalizeKeyCode(KeyCodes.MAC_FF_META), KeyCodes.META); assertEquals( goog.events.KeyCodes.normalizeGeckoKeyCode(KeyCodes.WIN_KEY_FF_LINUX), KeyCodes.WIN_KEY); assertEquals( goog.events.KeyCodes.normalizeKeyCode(KeyCodes.WIN_KEY_FF_LINUX), KeyCodes.WIN_KEY); // Test general key codes. assertEquals( goog.events.KeyCodes.normalizeGeckoKeyCode(KeyCodes.COMMA), KeyCodes.COMMA); assertEquals( goog.events.KeyCodes.normalizeKeyCode(KeyCodes.COMMA), KeyCodes.COMMA); } function testNormalizeMacWebKitKeyCode() { stubs.set(goog.userAgent, 'GECKO', false); stubs.set(goog.userAgent, 'MAC', true); stubs.set(goog.userAgent, 'WEBKIT', true); // Test Mac WebKit specific key codes. assertEquals( goog.events.KeyCodes.normalizeMacWebKitKeyCode(KeyCodes.MAC_WK_CMD_LEFT), KeyCodes.META); assertEquals( goog.events.KeyCodes.normalizeKeyCode(KeyCodes.MAC_WK_CMD_LEFT), KeyCodes.META); assertEquals( goog.events.KeyCodes.normalizeMacWebKitKeyCode(KeyCodes.MAC_WK_CMD_RIGHT), KeyCodes.META); assertEquals( goog.events.KeyCodes.normalizeKeyCode(KeyCodes.MAC_WK_CMD_RIGHT), KeyCodes.META); // Test general key codes. assertEquals( goog.events.KeyCodes.normalizeMacWebKitKeyCode(KeyCodes.COMMA), KeyCodes.COMMA); assertEquals( goog.events.KeyCodes.normalizeKeyCode(KeyCodes.COMMA), KeyCodes.COMMA); }
{ "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. */ /* * Description : BTree Index verification test * : This test is intended to verify that the secondary BTree index is used * : in the optimized query plan. * Expected Result : Success * Date : 11th Nov 2014 */ drop dataverse test if exists; create dataverse test; use test; write output to asterix_nc1:"rttest/btree-index_btree-secondary-63.adm"; create type test.TestTypetmp as { id : integer, fname : string, lname : string }; create type test.TestType as { nested : TestTypetmp }; create dataset testdst(TestType) primary key nested.id; create index sec_Idx on testdst (nested.fname,nested.lname) type btree; select element emp from testdst as emp where ((emp.nested.fname < 'Julio') and (emp.nested.lname = 'Xu')) ;
{ "pile_set_name": "Github" }
// https://tc39.github.io/proposal-setmap-offrom/#sec-weakmap.of require('./_set-collection-of')('WeakMap');
{ "pile_set_name": "Github" }
/* * #%L * BroadleafCommerce Integration * %% * Copyright (C) 2009 - 2016 Broadleaf Commerce * %% * Licensed under the Broadleaf Fair Use License Agreement, Version 1.0 * (the "Fair Use License" located at http://license.broadleafcommerce.org/fair_use_license-1.0.txt) * unless the restrictions on use therein are violated and require payment to Broadleaf in which case * the Broadleaf End User License Agreement (EULA), Version 1.1 * (the "Commercial License" located at http://license.broadleafcommerce.org/commercial_license-1.1.txt) * shall apply. * * Alternatively, the Commercial License may be replaced with a mutually agreed upon license (the "Custom License") * between you and Broadleaf Commerce. You may not use this file except in compliance with the applicable license. * #L% */ package org.broadleafcommerce.test; import org.broadleafcommerce.common.i18n.domain.ISOCountry; import org.broadleafcommerce.common.i18n.domain.ISOCountryImpl; import org.broadleafcommerce.common.i18n.service.ISOService; import org.broadleafcommerce.common.money.Money; import org.broadleafcommerce.core.catalog.domain.Category; import org.broadleafcommerce.core.catalog.domain.CategoryImpl; import org.broadleafcommerce.core.catalog.domain.Product; import org.broadleafcommerce.core.catalog.domain.ProductBundle; import org.broadleafcommerce.core.catalog.domain.ProductImpl; import org.broadleafcommerce.core.catalog.domain.Sku; import org.broadleafcommerce.core.catalog.domain.SkuBundleItem; import org.broadleafcommerce.core.catalog.domain.SkuBundleItemImpl; import org.broadleafcommerce.core.catalog.domain.SkuImpl; import org.broadleafcommerce.core.catalog.service.CatalogService; import org.broadleafcommerce.core.catalog.service.type.ProductType; import org.broadleafcommerce.core.order.dao.OrderDao; import org.broadleafcommerce.core.order.domain.Order; import org.broadleafcommerce.core.order.domain.OrderImpl; import org.broadleafcommerce.core.order.service.OrderService; import org.broadleafcommerce.core.order.service.type.OrderStatus; import org.broadleafcommerce.core.pricing.domain.ShippingRate; import org.broadleafcommerce.core.pricing.domain.ShippingRateImpl; import org.broadleafcommerce.core.pricing.service.ShippingRateService; import org.broadleafcommerce.profile.core.domain.Address; import org.broadleafcommerce.profile.core.domain.AddressImpl; import org.broadleafcommerce.profile.core.domain.Country; import org.broadleafcommerce.profile.core.domain.CountryImpl; import org.broadleafcommerce.profile.core.domain.Customer; import org.broadleafcommerce.profile.core.domain.CustomerAddress; import org.broadleafcommerce.profile.core.domain.CustomerAddressImpl; import org.broadleafcommerce.profile.core.domain.State; import org.broadleafcommerce.profile.core.domain.StateImpl; import org.broadleafcommerce.profile.core.service.CountryService; import org.broadleafcommerce.profile.core.service.CustomerAddressService; import org.broadleafcommerce.profile.core.service.CustomerService; import org.broadleafcommerce.profile.core.service.StateService; import java.math.BigDecimal; import java.util.Calendar; import javax.annotation.Resource; public abstract class CommonSetupBaseTest extends TestNGSiteIntegrationSetup { @Resource protected ISOService isoService; @Resource protected CountryService countryService; @Resource protected StateService stateService; @Resource protected CustomerService customerService; @Resource protected CustomerAddressService customerAddressService; @Resource protected CatalogService catalogService; @Resource(name = "blOrderService") protected OrderService orderService; @Resource protected ShippingRateService shippingRateService; @Resource private OrderDao orderDao; public void createCountry() { Country country = new CountryImpl(); country.setAbbreviation("US"); country.setName("United States"); countryService.save(country); ISOCountry isoCountry = new ISOCountryImpl(); isoCountry.setAlpha2("US"); isoCountry.setName("UNITED STATES"); isoService.save(isoCountry); } public void createState() { State state = new StateImpl(); state.setAbbreviation("KY"); state.setName("Kentucky"); state.setCountry(countryService.findCountryByAbbreviation("US")); stateService.save(state); } public Customer createCustomer() { Customer customer = customerService.createCustomerFromId(null); return customer; } /** * Creates a country, state, and customer with some CustomerAddresses * @return customer created */ public Customer createCustomerWithAddresses() { createCountry(); createState(); Customer customer = createCustomer(); customer.setUsername(String.valueOf(customer.getId())); customer = customerService.saveCustomer(customer); CustomerAddress ca1 = new CustomerAddressImpl(); Address address1 = new AddressImpl(); address1.setAddressLine1("1234 Merit Drive"); address1.setCity("Bozeman"); address1.setPostalCode("75251"); ca1.setAddress(address1); ca1.setAddressName("address1"); ca1.setCustomer(customer); CustomerAddress addResult1 = customerAddressService.saveCustomerAddress(ca1); assert addResult1 != null; CustomerAddress ca2 = new CustomerAddressImpl(); Address address2 = new AddressImpl(); address2.setAddressLine1("12 Testing Drive"); address2.setCity("Portland"); address2.setPostalCode("75251"); ca2.setAddress(address2); ca2.setAddressName("address2"); ca2.setCustomer(customer); CustomerAddress addResult2 = customerAddressService.saveCustomerAddress(ca2); assert addResult2 != null; return customer; } /** * Creates a country, state, and customer with the supplied customerAddress * @param customerAddress * @return customer created */ public CustomerAddress createCustomerWithAddress(CustomerAddress customerAddress) { createCountry(); createState(); Customer customer = createCustomer(); customer.setUsername(String.valueOf(customer.getId())); customerAddress.setCustomer(customer); return saveCustomerAddress(customerAddress); } /** * Saves a customerAddress with state KY and country US. Requires that createCountry() and createState() have been called * @param customerAddress */ public CustomerAddress saveCustomerAddress(CustomerAddress customerAddress) { State state = stateService.findStateByAbbreviation("KY"); customerAddress.getAddress().setState(state); Country country = countryService.findCountryByAbbreviation("US"); customerAddress.getAddress().setCountry(country); customerAddress.getAddress().setIsoCountrySubdivision("US-KY"); ISOCountry isoCountry = isoService.findISOCountryByAlpha2Code("US"); customerAddress.getAddress().setIsoCountryAlpha2(isoCountry); return customerAddressService.saveCustomerAddress(customerAddress); } /** * Create a state, country, and customer with a basic order and some addresses */ public Customer createCustomerWithBasicOrderAndAddresses() { Customer customer = createCustomerWithAddresses(); Order order = new OrderImpl(); order.setStatus(OrderStatus.IN_PROCESS); order.setTotal(new Money(BigDecimal.valueOf(1000))); assert order.getId() == null; order.setCustomer(customer); order = orderDao.save(order); assert order.getId() != null; return customer; } public Product addTestProduct(String productName, String categoryName) { return addTestProduct(productName, categoryName, true); } public Product addTestProduct(String productName, String categoryName, boolean active) { Calendar activeStartCal = Calendar.getInstance(); activeStartCal.add(Calendar.DAY_OF_YEAR, -2); Calendar activeEndCal = Calendar.getInstance(); activeEndCal.add(Calendar.DAY_OF_YEAR, -1); Category category = new CategoryImpl(); category.setName(categoryName); category.setActiveStartDate(activeStartCal.getTime()); category = catalogService.saveCategory(category); Sku newSku = new SkuImpl(); newSku.setName(productName); newSku.setRetailPrice(new Money(44.99)); newSku.setActiveStartDate(activeStartCal.getTime()); if (!active) { newSku.setActiveEndDate(activeEndCal.getTime()); } newSku.setDiscountable(true); newSku = catalogService.saveSku(newSku); Product newProduct = new ProductImpl(); newProduct.setDefaultCategory(category); newProduct.setDefaultSku(newSku); newProduct = catalogService.saveProduct(newProduct); return newProduct; } public ProductBundle addProductBundle() { // Create the product Product p = addTestProduct("bundleproduct1", "bundlecat1"); // Create the sku for the ProductBundle object Sku bundleSku = catalogService.createSku(); bundleSku.setName(p.getName()); bundleSku.setRetailPrice(new Money(44.99)); bundleSku.setActiveStartDate(p.getActiveStartDate()); bundleSku.setActiveEndDate(p.getActiveEndDate()); bundleSku.setDiscountable(true); // Create the ProductBundle and associate the sku ProductBundle bundle = (ProductBundle) catalogService.createProduct(ProductType.BUNDLE); bundle.setDefaultCategory(p.getDefaultCategory()); bundle.setDefaultSku(bundleSku); bundle = (ProductBundle) catalogService.saveProduct(bundle); // Reverse-associate the ProductBundle to the sku (Must be done this way because it's a // bidirectional OneToOne relationship //bundleSku.setDefaultProduct(bundle); //catalogService.saveSku(bundleSku); // Wrap the product/sku that is part of the bundle in a SkuBundleItem SkuBundleItem skuBundleItem = new SkuBundleItemImpl(); skuBundleItem.setBundle(bundle); skuBundleItem.setQuantity(1); skuBundleItem.setSku(p.getDefaultSku()); // Add the SkuBundleItem to the ProductBundle bundle.getSkuBundleItems().add(skuBundleItem); bundle = (ProductBundle) catalogService.saveProduct(bundle); return bundle; } public void createShippingRates() { ShippingRate sr = new ShippingRateImpl(); sr.setFeeType("SHIPPING"); sr.setFeeSubType("ALL"); sr.setFeeBand(1); sr.setBandUnitQuantity(BigDecimal.valueOf(29.99)); sr.setBandResultQuantity(BigDecimal.valueOf(8.5)); sr.setBandResultPercent(0); ShippingRate sr2 = new ShippingRateImpl(); sr2.setFeeType("SHIPPING"); sr2.setFeeSubType("ALL"); sr2.setFeeBand(2); sr2.setBandUnitQuantity(BigDecimal.valueOf(999999.99)); sr2.setBandResultQuantity(BigDecimal.valueOf(8.5)); sr2.setBandResultPercent(0); shippingRateService.save(sr); shippingRateService.save(sr2); } }
{ "pile_set_name": "Github" }
;- Copyright © 2008-2011 8th Light, Inc. All Rights Reserved. ;- Limelight and all included source files are distributed under terms of the MIT License. (ns limelight.clojure.production-player) (declare ^:dynamic *production*) (defn add-action-with-bindings [event-type action] (let [event-action (reify limelight.events.EventAction (invoke [this e] (action e)))] (.add (.getEventHandler (._peer *production*)) event-type event-action))) (defmacro add-action [event-type & forms] (if (vector? (first forms)) `(add-action-with-bindings ~event-type (fn ~(first forms) ~@(rest forms))) `(add-action-with-bindings ~event-type (fn [~'%] ~@forms)))) (defmacro on-production-created [& forms] `(add-action ~limelight.model.events.ProductionCreatedEvent ~@forms)) (defmacro on-production-loaded [& forms] `(add-action ~limelight.model.events.ProductionLoadedEvent ~@forms)) (defmacro on-production-opened [& forms] `(add-action ~limelight.model.events.ProductionOpenedEvent ~@forms)) (defmacro on-production-closing [& forms] `(add-action ~limelight.model.events.ProductionClosingEvent ~@forms)) (defmacro on-production-closed [& forms] `(add-action ~limelight.model.events.ProductionClosedEvent ~@forms))
{ "pile_set_name": "Github" }
# Be sure to restart your server when you modify this file. # You can add backtrace silencers for libraries that you're using but don't wish to see in your backtraces. # Rails.backtrace_cleaner.add_silencer { |line| line =~ /my_noisy_library/ } # You can also remove all the silencers if you're trying to debug a problem that might stem from framework code. # Rails.backtrace_cleaner.remove_silencers!
{ "pile_set_name": "Github" }
#浪潮之巅 近一百多年来,总有一些公司很幸运地、有意识或者无意识地站在技术革命的浪尖之上。 一旦处在了那个位置,即使不做任何事,也可以随着波浪顺顺当当地向前漂个十年甚至更长的时间。在这十几年间,它们代表着科技的浪潮,直到下一波浪潮的来临。 --- 1995年,如日中天的AT&T 公司重组,分裂成AT&T、朗讯和NCR三家公司。AT&T下属的举世闻名的科研机构贝尔实验室也被一分为二。朗讯公司获得了一半的科研机构和贝尔实验室的名称。划归AT&T的一半研究室组成了AT&T实验室(后来更名为香农实验室),从原来的茉莉山(MurrayHills)搬到了弗伦翰公园。在那里,出过十一位诺贝尔奖获得者的AT&T实验室,像一颗进入晚年的恒星,爆发出极强的,但也是最后的光辉,然后就迅速的暗淡下来。十年后AT&T和朗讯公司分别被SBC公司和法国的阿尔卡特公司并购。 --- 最值得一提的是,在二战中,贝尔实验室的天才青年科学家香农提出的信息论。信息论是整个现代通信的基础。到五十年代,AT&T发展到美国政府司法部不得不管一管的地步了。1956年,AT&T和司法部达成协议,再次限制了一下自己的行为。反垄断法逼着AT&T 靠科技进步来提升自己的实力。因此,AT&T巩固了自己在技术上的领先地位。1948年,AT&T 实现商用的微波通信,1962年,它发射了第一颗商用通信卫星。尽管有些小的竞争者存在,它们无法撼动AT&T的根基。 --- 在很长的时间里,美国国际长途电话的价钱不是由市场决定的,而是由AT&T和美国联邦通信委员会(FCC)谈判决定的,定价是三美元一分钟。AT&T计算价钱的方法听起来很合理--铺设光缆和电缆需要多少钱,购买设备需要多少钱,研发需要多少钱,雇接线员需要多少钱等等,所以只有一分钟三美元才能不亏损。但是事实上,到2002年,当国际长途电话费降到平均一分钟只有三十美分时,AT&T仍然有1/3的毛利润。 --- 到了八十年代,美国司法部不得不再次对AT&T公司提起反垄断诉讼。这次,美国政府终于打赢了旷日持久的官司,这才导致了AT&T 1984年的第一次分家。这次反垄断的官司,不过是替AT&T这棵大树剪剪枝。剪完枝后,AT&T公司反而发展得更健康。十年后,AT&T 又如日中天了。当时,AT&T不仅在传统的电话业务上,而且在兴起的网络和移动通信方面,都处于世界领先地位。 --- AT&T几个执行官们手上的股票远不如华尔街投资银行控制的多。说句不好听的,AT&T的总裁们并不真正拥有公司。他们之中不乏有远见者,但是根本左右不了董事会。更何况公司的长期利益和他们没有太大关系。如果能在任期内狠狠捞一把,何乐而不为呢?作为华尔街的投资公司,他们关心的是手中的股票何时能翻番。1995年正是一个机会,整个股市长势很好,在这时将设备制造部门和电信服务部门分开,那么前者的股票一定会飞涨。华尔街看到了这一点,公司的老总们懂得这一点,公司大量拥有股权的员工们也明白这一点。本来大家都是明白人,但是利令智昏。一场杀鸡取卵的分家就开始了。 --- AT&T将分为三个部分,从事电信业务的AT&T,从事设备制造业务的朗讯Lucent和从事计算机业务的NCR。NCR较小,我们姑且不必提它。朗讯从AT&T中分离,绝对是世界电信史上第一件大事。1996年二月朗讯公司由华尔街最有名的投资银行摩根斯坦利(Morgan Stanley)领衔上市,筹集现金三十亿美元,成为当时历史上最大的上市行动,也是迄今为止第十一大上市活动。朗讯上市时,市值达180亿元。 --- 尔实验室此时已不是过去以研究为主的地方了,它的创新能力不复存在,从1995年至今,贝尔实验室没有再搞出轰动世界的发明。本来,AT&T的电信服务和设备制造相辅相成,是个双赢的组合。分家对双方长远的发展都没有好处。AT&T和朗讯的衰落都从这时起 --- 在2000年前后,短线投资者发现最快的挣钱方法不是把一个企业搞好,而是炒作和包装上市。将公司的一部分拆了卖无疑挣钱最快。于是AT&T决定一拆四,分成长途电话,移动电话,企业服务和宽带四个公司。其中最大的手笔是将移动部门单独上市。1999年5月,AT&T 移动(AT&Twireless)在华尔街最好的投资公司高盛(GoldmanSachs)的帮助下挂牌上市,募集到现金一百亿美元。这是人类历史上迄今最大的上市行动。当时AT&T的董事和执行官们给出了一些冠冕堂皇的理由拆分后对发展如何有利,但其实,用AT&T实验室的一位主管的话说,原因只有一个--贪婪(greedy)。AT&T在一次性得到一笔横财时,也失去了立足于电信业的竞争能力,因为它所剩的只有一个收入不断下滑的传统长途电话业务。同时,香农实验室萎缩到1996年成立时的规模。2001年发生的9.11恐怖袭击,AT&T在纽约的很多设备被毁,而它几乎拿不出修复设备的钱。半年后,AT&T的香农实验室也几乎解散了。在AT&T实验室解散前,它的主管拉里?拉宾纳(Larry Rabinar)博士已经预感到情况不妙了,他很有人情味地为他的老部下们安排了出路,然后自己退离了香农实验室第一把手的岗位。身为美国工程院院士的拉宾纳,无论是学术水平还是管理水平,在世界上都是首屈一指,但是他根本无力扭转AT&T实验室的困境。这也许是命运。 --- 如果说终结AT&T帝国的内因是华尔街和AT&T自己的贪婪和短视,那么互联网的兴起从外界彻底击垮了这个帝国。在互联网兴起以前,固定电话几乎是人类唯一的交互通信手段,因此,只要在这个产业中占领一席之地,即使不做任何事,也可以由着它的波浪推着前进。 --- 互联网的崛起,对原贝尔实验室研究的影响也是巨大的。比如,语音的自动识别,曾经被认为是人类最伟大的梦想之一,现在随着电话时代的过去变得不重要了。今天,世界上主要的语音识别公司只剩下Nuance一家,美国整个语音识别市场的规模一年不到五亿美元,相当于谷歌两个星期的收入。而同时,世界上对文字处理、图像处理技术的需求随着互联网的普及不断增加 --- 回顾AT&T百年历史,几乎每个人都为这个百年老店的衰落而遗憾。它曾经是电话业的代名词,而它的贝尔实验室曾经是创新的代名词,现在这一切已成为历史。我和很多AT&T 的主管和科学家们聊过此事,大家普遍认为AT&T的每一个大的决定,在当时的情况下都很难避免,即使知道它是错的。上个世纪90年代,AT&T已经不属于一个人,一个机构,没有人对它的十年百年后的发展着想。(我们以后还会多次看到,当一个公司没有人对它有控制时,它的长期发展就会有问题)从华尔街,到它的高管和员工,大都希望从它身上快快地捞一笔。 --- IBM能成为科技界的常青树,要归功于它的二字秘诀--保守。毫无疑问,保守使得IBM 失去了无数发展机会,但是也让它能专注于最重要的事,并因此而立于不败之地。 --- 华生父子对IBM的影响是巨大的。一个公司创始者的灵魂常常会永久地留在这个公司,即使他们已经离去。 --- 我们可以将第二次世界大战作为机械时代和电子时代的分水岭。二战后,IBM显然面临着两种选择,是继续发展它的电动机械制表机,还是发展新兴的电子工业。在IBM里,这两派争执不下,而代表人物恰恰是华生父子。老华生认为电子的东西不可靠,世界上至今还有不少人持老华生的观点。而小华生则坚持电子工业是今后的发展趋势。这场争论终于以小华生的胜利而告终。1952年,小华生成为IBM的新总裁。IBM从此开始领导电子技术革命的浪潮。 --- 有一位先哲说过,社会的需求对科技进步的作用要超过十所大学。计算机就是在这个背景下被发明的。美国研制计算机的直接目的是在第二次世界大战时为军方计算弹道的轨迹 ---
{ "pile_set_name": "Github" }
########################################################################## # # pgAdmin 4 - PostgreSQL Tools # # Copyright (C) 2013 - 2020, The pgAdmin Development Team # This software is released under the PostgreSQL Licence # ########################################################################## import uuid import json from pgadmin.browser.server_groups.servers.databases.schemas.tests import \ utils as schema_utils from pgadmin.browser.server_groups.servers.databases.tests import utils as \ database_utils from pgadmin.utils.route import BaseTestGenerator from regression import parent_node_dict from regression.python_test_utils import test_utils as utils from . import utils as sequence_utils class SequenceDeleteMultipleTestCase(BaseTestGenerator): """This class will delete added sequence under schema node.""" skip_on_database = ['gpdb'] scenarios = [ # Fetching default URL for sequence node. ('Fetch sequence Node URL', dict(url='/browser/sequence/obj/')) ] def setUp(self): super(SequenceDeleteMultipleTestCase, self).setUp() self.db_name = parent_node_dict["database"][-1]["db_name"] schema_info = parent_node_dict["schema"][-1] self.server_id = schema_info["server_id"] self.db_id = schema_info["db_id"] db_con = database_utils.connect_database(self, utils.SERVER_GROUP, self.server_id, self.db_id) if not db_con['data']["connected"]: raise Exception("Could not connect to database to add sequence.") self.schema_id = schema_info["schema_id"] self.schema_name = schema_info["schema_name"] schema_response = schema_utils.verify_schemas(self.server, self.db_name, self.schema_name) if not schema_response: raise Exception("Could not find the schema to add sequence.") self.sequence_name = "test_sequence_delete_%s" % str(uuid.uuid4())[1:8] self.sequence_name_1 = "test_sequence_delete_%s" %\ str(uuid.uuid4())[1:8] self.sequence_ids = [sequence_utils.create_sequences( self.server, self.db_name, self.schema_name, self.sequence_name), sequence_utils.create_sequences( self.server, self.db_name, self.schema_name, self.sequence_name_1) ] def runTest(self): """ This function will delete added sequence under schema node. """ sequence_response = sequence_utils.verify_sequence(self.server, self.db_name, self.sequence_name) if not sequence_response: raise Exception("Could not find the sequence to delete.") sequence_response = sequence_utils.verify_sequence(self.server, self.db_name, self.sequence_name_1 ) if not sequence_response: raise Exception("Could not find the sequence to delete.") data = json.dumps({'ids': self.sequence_ids}) response = self.tester.delete( self.url + str(utils.SERVER_GROUP) + '/' + str(self.server_id) + '/' + str(self.db_id) + '/' + str(self.schema_id) + '/', follow_redirects=True, data=data, content_type='html/json' ) self.assertEqual(response.status_code, 200) def tearDown(self): # Disconnect the database database_utils.disconnect_database(self, self.server_id, self.db_id)
{ "pile_set_name": "Github" }
--- # defaults file for libmysqlclient-dev
{ "pile_set_name": "Github" }
// // ASTMethod.hpp // Emojicode // // Created by Theo Weidmann on 05/08/2017. // Copyright © 2017 Theo Weidmann. All rights reserved. // #ifndef ASTMethod_hpp #define ASTMethod_hpp #include "ASTExpr.hpp" #include "Functions/CallType.h" #include <utility> #include <map> namespace EmojicodeCompiler { class FunctionAnalyser; class Compiler; class ASTMethodable : public ASTCall { protected: explicit ASTMethodable(const SourcePosition &p) : ASTCall(p), args_(p) {} ASTMethodable(const SourcePosition &p, ASTArguments args) : ASTCall(p), args_(std::move(args)) {} Type analyseMethodCall(ExpressionAnalyser *analyser, const std::u32string &name, std::shared_ptr<ASTExpr> &callee); /// Analyses this node as method call. /// @param otype Result of analysing `callee` with TypeExpectation `TypeExpectation()`. Type analyseMethodCall(ExpressionAnalyser *analyser, const std::u32string &name, std::shared_ptr<ASTExpr> &callee, const Type &otype); enum class BuiltInType { None, DoubleMultiply, DoubleAdd, DoubleSubstract, DoubleDivide, DoubleGreater, DoubleGreaterOrEqual, DoubleLess, DoubleLessOrEqual, DoubleRemainder, DoubleEqual, DoubleInverse, Power, Log2, Log10, Ln, Ceil, Floor, Round, DoubleAbs, DoubleToInteger, IntegerMultiply, IntegerAdd, IntegerSubstract, IntegerDivide, IntegerGreater, IntegerGreaterOrEqual, IntegerLess, IntegerLessOrEqual, IntegerLeftShift, IntegerRightShift, IntegerOr, IntegerAnd, IntegerXor, IntegerRemainder, IntegerToDouble, IntegerNot, IntegerInverse, IntegerToByte, ByteToInteger, BooleanAnd, BooleanOr, BooleanNegate, Equal, Store, Load, Release, MemoryMove, MemorySet, IsNoValueLeft, IsNoValueRight, Multiprotocol, }; BuiltInType builtIn_ = BuiltInType::None; ASTArguments args_; CallType callType_ = CallType::None; Type calleeType_ = Type::noReturn(); size_t multiprotocolN_ = 0; Function *method_ = nullptr; Type castTo_ = Type::noReturn(); bool isErrorProne() const override; const Type& errorType() const override; private: static std::map<std::pair<TypeDefinition*, char32_t>, BuiltInType> kBuiltIns; static void prepareBuiltIns(Compiler *c); bool builtIn(ExpressionAnalyser *analyser, const Type &type, const std::u32string &name); Type analyseMultiProtocolCall(ExpressionAnalyser *analyser, const std::u32string &name); void checkMutation(ExpressionAnalyser *analyser, const std::shared_ptr<ASTExpr> &callee) const; void determineCallType(const ExpressionAnalyser *analyser); void determineCalleeType(ExpressionAnalyser *analyser, const std::u32string &name, std::shared_ptr<ASTExpr> &callee, const Type &otype); Type analyseTypeMethodCall(ExpressionAnalyser *analyser, const std::u32string &name, std::shared_ptr<ASTExpr> &callee); }; class ASTMethod final : public ASTMethodable { public: ASTMethod(std::u32string name, std::shared_ptr<ASTExpr> callee, const ASTArguments &args, const SourcePosition &p) : ASTMethodable(p, args), name_(std::move(name)), callee_(std::move(callee)) {} Type analyse(ExpressionAnalyser *analyser) override; void toCode(PrettyStream &pretty) const override; Value* generate(FunctionCodeGenerator *fg) const override; void analyseMemoryFlow(MFFunctionAnalyser *analyser, MFFlowCategory type) override; void mutateReference(ExpressionAnalyser *analyser) final; private: std::u32string name_; std::shared_ptr<ASTExpr> callee_; llvm::Value* buildMemoryAddress(FunctionCodeGenerator *fg, llvm::Value *memory, llvm::Value *offset, const Type &type) const; llvm::Value* buildAddOffsetAddress(FunctionCodeGenerator *fg, llvm::Value *memory, llvm::Value *offset) const; }; } // namespace EmojicodeCompiler #endif /* ASTMethod_hpp */
{ "pile_set_name": "Github" }
/*---------------------------------------------------------------------------*\ ========= | \\ / F ield | OpenFOAM: The Open Source CFD Toolbox \\ / O peration | \\ / A nd | Copyright (C) 2011-2013 OpenFOAM Foundation \\/ M anipulation | ------------------------------------------------------------------------------- License This file is part of OpenFOAM. OpenFOAM 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. OpenFOAM 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 OpenFOAM. If not, see <http://www.gnu.org/licenses/>. // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * // \mainpage OpenFOAM&reg;: open source CFD \section about About OpenFOAM OpenFOAM is a free, open source CFD software package released free and open-source under the GNU General Public License by the, <a href="http://www.openfoam.org">OpenFOAM Foundation</a>. It has a large user base across most areas of engineering and science, from both commercial and academic organisations. OpenFOAM has an extensive range of features to solve anything from complex fluid flows involving chemical reactions, turbulence and heat transfer, to solid dynamics and electromagnetics. <a href="http://www.openfoam.org/features">More ...</a> \section layout Code Layout The OpenFOAM source code comprises of four main components: - src: the core OpenFOAM source code - applications: collections of library functionality wrapped up into applications, such as solvers and utilities - tutorials: a suite of test cases that highlight a broad cross-section of OpenFOAM's capabilities - doc: supporting documentation \section usingTheCode Using the code - \subpage pagePostProcessing - \subpage pageBoundaryConditions \*---------------------------------------------------------------------------*/
{ "pile_set_name": "Github" }
<?xml version="1.0" encoding="utf-8"?> <Project ToolsVersion="4.0" DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003"> <PropertyGroup> <Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration> <Platform Condition=" '$(Platform)' == '' ">AnyCPU</Platform> <ProductVersion>8.0.30703</ProductVersion> <SchemaVersion>2.0</SchemaVersion> <ProjectGuid>{857E540C-0092-4590-A279-F98A6B77AC0A}</ProjectGuid> <OutputType>Library</OutputType> <AppDesignerFolder>Properties</AppDesignerFolder> <RootNamespace>Facebook</RootNamespace> <AssemblyName>Facebook</AssemblyName> <TargetFrameworkVersion>v3.5</TargetFrameworkVersion> <BaseIntermediateOutputPath>..\..\Working\obj\Facebook\net35-client\</BaseIntermediateOutputPath> <FileAlignment>512</FileAlignment> <SccProjectName> </SccProjectName> <SccLocalPath> </SccLocalPath> <SccAuxPath> </SccAuxPath> <SccProvider> </SccProvider> <CodeContractsAssemblyMode>0</CodeContractsAssemblyMode> <TargetFrameworkProfile>Client</TargetFrameworkProfile> <SolutionDir Condition="$(SolutionDir) == '' Or $(SolutionDir) == '*Undefined*'">..\..\Source\</SolutionDir> <RestorePackages>true</RestorePackages> </PropertyGroup> <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' "> <DebugSymbols>true</DebugSymbols> <DebugType>full</DebugType> <Optimize>false</Optimize> <OutputPath>..\..\Bin\Debug\net35-client\</OutputPath> <DefineConstants>TRACE;DEBUG;CODE_ANALYSIS;NET35;SIMPLE_JSON_INTERNAL;SIMPLE_JSON_DATACONTRACT;FLUENTHTTP_URLENCODING;FLUENTHTTP_HTMLENCODING</DefineConstants> <ErrorReport>prompt</ErrorReport> <WarningLevel>4</WarningLevel> <RunCodeAnalysis>true</RunCodeAnalysis> <CodeAnalysisRuleSet>..\CustomRules.ruleset</CodeAnalysisRuleSet> <CodeContractsEnableRuntimeChecking>False</CodeContractsEnableRuntimeChecking> <CodeContractsRuntimeOnlyPublicSurface>False</CodeContractsRuntimeOnlyPublicSurface> <CodeContractsRuntimeThrowOnFailure>True</CodeContractsRuntimeThrowOnFailure> <CodeContractsRuntimeCallSiteRequires>False</CodeContractsRuntimeCallSiteRequires> <CodeContractsRunCodeAnalysis>False</CodeContractsRunCodeAnalysis> <CodeContractsNonNullObligations>True</CodeContractsNonNullObligations> <CodeContractsBoundsObligations>True</CodeContractsBoundsObligations> <CodeContractsArithmeticObligations>True</CodeContractsArithmeticObligations> <CodeContractsRedundantAssumptions>True</CodeContractsRedundantAssumptions> <CodeContractsRunInBackground>True</CodeContractsRunInBackground> <CodeContractsShowSquigglies>True</CodeContractsShowSquigglies> <CodeContractsUseBaseLine>False</CodeContractsUseBaseLine> <CodeContractsEmitXMLDocs>True</CodeContractsEmitXMLDocs> <CodeContractsCustomRewriterAssembly /> <CodeContractsCustomRewriterClass /> <CodeContractsLibPaths /> <CodeContractsExtraRewriteOptions /> <CodeContractsExtraAnalysisOptions /> <CodeContractsBaseLineFile> </CodeContractsBaseLineFile> <CodeContractsRuntimeCheckingLevel>Full</CodeContractsRuntimeCheckingLevel> <CodeContractsReferenceAssembly>%28none%29</CodeContractsReferenceAssembly> <CodeContractsContainerAnalysis>True</CodeContractsContainerAnalysis> <DocumentationFile>..\..\Bin\Debug\net35-client\Facebook.xml</DocumentationFile> <CodeContractsCacheAnalysisResults>True</CodeContractsCacheAnalysisResults> </PropertyGroup> <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|AnyCPU' "> <DebugType>pdbonly</DebugType> <Optimize>true</Optimize> <OutputPath>..\..\Bin\Release\net35-client\</OutputPath> <DefineConstants>TRACE;NET35;SIMPLE_JSON_INTERNAL;SIMPLE_JSON_DATACONTRACT;FLUENTHTTP_URLENCODING;FLUENTHTTP_HTMLENCODING</DefineConstants> <ErrorReport>prompt</ErrorReport> <WarningLevel>4</WarningLevel> <CodeContractsEnableRuntimeChecking>False</CodeContractsEnableRuntimeChecking> <CodeContractsRuntimeOnlyPublicSurface>False</CodeContractsRuntimeOnlyPublicSurface> <CodeContractsRuntimeThrowOnFailure>True</CodeContractsRuntimeThrowOnFailure> <CodeContractsRuntimeCallSiteRequires>False</CodeContractsRuntimeCallSiteRequires> <CodeContractsRunCodeAnalysis>False</CodeContractsRunCodeAnalysis> <CodeContractsNonNullObligations>True</CodeContractsNonNullObligations> <CodeContractsBoundsObligations>True</CodeContractsBoundsObligations> <CodeContractsArithmeticObligations>True</CodeContractsArithmeticObligations> <CodeContractsRedundantAssumptions>True</CodeContractsRedundantAssumptions> <CodeContractsRunInBackground>True</CodeContractsRunInBackground> <CodeContractsShowSquigglies>True</CodeContractsShowSquigglies> <CodeContractsUseBaseLine>False</CodeContractsUseBaseLine> <CodeContractsEmitXMLDocs>True</CodeContractsEmitXMLDocs> <CodeContractsCustomRewriterAssembly /> <CodeContractsCustomRewriterClass /> <CodeContractsLibPaths /> <CodeContractsExtraRewriteOptions /> <CodeContractsExtraAnalysisOptions /> <CodeContractsBaseLineFile /> <CodeContractsRuntimeCheckingLevel>Full</CodeContractsRuntimeCheckingLevel> <CodeContractsReferenceAssembly>%28none%29</CodeContractsReferenceAssembly> <RunCodeAnalysis>false</RunCodeAnalysis> <CodeAnalysisRuleSet>..\CustomRules.ruleset</CodeAnalysisRuleSet> <CodeContractsContainerAnalysis>True</CodeContractsContainerAnalysis> <CodeContractsCacheAnalysisResults>True</CodeContractsCacheAnalysisResults> <DocumentationFile>..\..\Bin\Release\net35-client\Facebook.xml</DocumentationFile> </PropertyGroup> <PropertyGroup> <SignAssembly>true</SignAssembly> </PropertyGroup> <PropertyGroup> <AssemblyOriginatorKeyFile>..\SharedKey.snk</AssemblyOriginatorKeyFile> </PropertyGroup> <ItemGroup> <Reference Include="System" /> <Reference Include="System.Configuration" /> <Reference Include="System.Core" /> <Reference Include="System.Runtime.Serialization" /> </ItemGroup> <ItemGroup> <Compile Include="CombinationStream.cs" /> <Compile Include="DateTimeConvertor.cs" /> <Compile Include="FacebookApiEventArgs.cs" /> <Compile Include="FacebookApiException.cs" /> <Compile Include="FacebookBatchParameter.cs" /> <Compile Include="FacebookClient.cs" /> <Compile Include="FacebookClient.Async.cs"> <DependentUpon>FacebookClient.cs</DependentUpon> </Compile> <Compile Include="FacebookClient.Batch.Sync.cs"> <DependentUpon>FacebookClient.cs</DependentUpon> </Compile> <Compile Include="FacebookClient.Batch.Async.cs"> <DependentUpon>FacebookClient.cs</DependentUpon> </Compile> <Compile Include="FacebookClient.Sync.cs"> <DependentUpon>FacebookClient.cs</DependentUpon> </Compile> <Compile Include="FacebookClient.SignedRequest.cs"> <DependentUpon>FacebookClient.cs</DependentUpon> </Compile> <Compile Include="FacebookClient.Subscription.cs"> <DependentUpon>FacebookClient.cs</DependentUpon> </Compile> <Compile Include="FacebookClient.OAuthResult.cs"> <DependentUpon>FacebookClient.cs</DependentUpon> </Compile> <Compile Include="FacebookMediaObject.cs" /> <Compile Include="FacebookMediaStream.cs" /> <Compile Include="FacebookOAuthException.cs"> <DependentUpon>FacebookApiException.cs</DependentUpon> </Compile> <Compile Include="FacebookApiLimitException.cs"> <DependentUpon>FacebookApiException.cs</DependentUpon> </Compile> <Compile Include="FacebookOAuthResult.cs" /> <Compile Include="FacebookUploadProgressChangedEventArgs.cs"> <DependentUpon>FacebookApiEventArgs.cs</DependentUpon> </Compile> <Compile Include="GlobalSuppressions.cs" /> <Compile Include="HttpHelper.cs" /> <Compile Include="HttpMethod.cs" /> <Compile Include="Properties\AssemblyInfo.cs" /> <Compile Include="..\GlobalAssemblyInfo.cs"> <Link>Properties\GlobalAssemblyInfo.cs</Link> </Compile> <Compile Include="SimpleJson.cs" /> </ItemGroup> <ItemGroup> <None Include="..\SharedKey.snk"> <Link>SharedKey.snk</Link> </None> <None Include="packages.config" /> </ItemGroup> <ItemGroup> <CodeAnalysisDictionary Include="..\CustomDictionary.xml"> <Link>CustomDictionary.xml</Link> </CodeAnalysisDictionary> </ItemGroup> <Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" /> <Import Project="$(SolutionDir)\.nuget\nuget.targets" /> <!-- To modify your build process, add your task inside one of the targets below and uncomment it. Other similar extension points exist, see Microsoft.Common.targets. <Target Name="BeforeBuild"> </Target> <Target Name="AfterBuild"> </Target> --> </Project>
{ "pile_set_name": "Github" }
defmodule Hound.Helpers.ScriptExecution do @moduledoc "Functions to execute javascript" import Hound.RequestUtils @doc """ Execute javascript synchronously. * The first argument is the script to execute. * The second argument is a list of arguments that is passed. These arguments are accessible in the script via `arguments`. execute_script("return(arguments[0] + arguments[1]);", [1, 2]) execute_script("doSomething(); return(arguments[0] + arguments[1]);") """ @spec execute_script(String.t, list) :: any def execute_script(script_function, function_args \\ []) do session_id = Hound.current_session_id make_req(:post, "session/#{session_id}/execute", %{script: script_function, args: function_args} ) end @doc """ Execute javascript asynchronously. * The first argument is the script to execute. * The second argument is a list of arguments that is passed. These arguments are accessible in the script via `arguments`. Webdriver passes a callback function as the last argument to the script. When your script has completed execution, it has to call the last argument, which is a callback function, to indicate that the execute is complete. # Once we perform whatever we want, # we call the callback function with the arguments that must be returned. execute_script_async("doSomething(); arguments[arguments.length-1]('hello')", []) # We have no arguments to pass, so we'll skip the second argument. execute_script_async("console.log('hello'); doSomething(); arguments[arguments.length-1]()") Unless you call the callback function, the function is not assumed to be completed. It will error out. """ @spec execute_script_async(String.t, list) :: any def execute_script_async(script_function, function_args \\ []) do session_id = Hound.current_session_id make_req(:post, "session/#{session_id}/execute_async", %{script: script_function, args: function_args} ) end @doc """ Execute a phantomjs script to configure callbacks. This will only work with phantomjs driver. * The first argument is the script to execute. * The second argument is a list of arguments that is passed. These arguments are accessible in the script via `arguments`. execute_phantom_script("return(arguments[0] + arguments[1]);", [1, 2]) execute_phantom_script("doSomething(); return(arguments[0] + arguments[1]);") * NOTE: "this" in the context of the script function refers to the phantomjs result of require('webpage').create(). To use it, capture it in a variable at the beginning of the script. Example: page = this; page.onResourceRequested = function(requestData, request) { // Do something with the request }; """ @spec execute_phantom_script(String.t, list) :: any def execute_phantom_script(script_function, function_args \\ []) do session_id = Hound.current_session_id make_req(:post, "/session/#{session_id}/phantom/execute", %{script: script_function, args: function_args} ) end end
{ "pile_set_name": "Github" }
/* * sdh.h, export bfin_mmc_init * * Copyright (c) 2009 Analog Devices Inc. * * Licensed under the GPL-2 or later. */ #ifndef __ASM_SDH_H__ #define __ASM_SDH_H__ #include <mmc.h> #include <asm/u-boot.h> int bfin_mmc_init(bd_t *bis); #endif
{ "pile_set_name": "Github" }
#include "f2c.h" #include "blaswrap.h" /* Table of constant values */ static integer c__1 = 1; static integer c_n1 = -1; static integer c__0 = 0; static doublereal c_b17 = 1.; /* Subroutine */ int dsyev_(char *jobz, char *uplo, integer *n, doublereal *a, integer *lda, doublereal *w, doublereal *work, integer *lwork, integer *info) { /* System generated locals */ integer a_dim1, a_offset, i__1, i__2; doublereal d__1; /* Builtin functions */ double sqrt(doublereal); /* Local variables */ integer nb; doublereal eps; integer inde; doublereal anrm; integer imax; doublereal rmin, rmax; extern /* Subroutine */ int dscal_(integer *, doublereal *, doublereal *, integer *); doublereal sigma; extern logical lsame_(char *, char *); integer iinfo; logical lower, wantz; extern doublereal dlamch_(char *); integer iscale; extern /* Subroutine */ int dlascl_(char *, integer *, integer *, doublereal *, doublereal *, integer *, integer *, doublereal *, integer *, integer *); doublereal safmin; extern integer ilaenv_(integer *, char *, char *, integer *, integer *, integer *, integer *); extern /* Subroutine */ int xerbla_(char *, integer *); doublereal bignum; integer indtau; extern /* Subroutine */ int dsterf_(integer *, doublereal *, doublereal *, integer *); extern doublereal dlansy_(char *, char *, integer *, doublereal *, integer *, doublereal *); integer indwrk; extern /* Subroutine */ int dorgtr_(char *, integer *, doublereal *, integer *, doublereal *, doublereal *, integer *, integer *), dsteqr_(char *, integer *, doublereal *, doublereal *, doublereal *, integer *, doublereal *, integer *), dsytrd_(char *, integer *, doublereal *, integer *, doublereal *, doublereal *, doublereal *, doublereal *, integer *, integer *); integer llwork; doublereal smlnum; integer lwkopt; logical lquery; /* -- LAPACK driver routine (version 3.1) -- */ /* Univ. of Tennessee, Univ. of California Berkeley and NAG Ltd.. */ /* November 2006 */ /* .. Scalar Arguments .. */ /* .. */ /* .. Array Arguments .. */ /* .. */ /* Purpose */ /* ======= */ /* DSYEV computes all eigenvalues and, optionally, eigenvectors of a */ /* real symmetric matrix A. */ /* Arguments */ /* ========= */ /* JOBZ (input) CHARACTER*1 */ /* = 'N': Compute eigenvalues only; */ /* = 'V': Compute eigenvalues and eigenvectors. */ /* UPLO (input) CHARACTER*1 */ /* = 'U': Upper triangle of A is stored; */ /* = 'L': Lower triangle of A is stored. */ /* N (input) INTEGER */ /* The order of the matrix A. N >= 0. */ /* A (input/output) DOUBLE PRECISION array, dimension (LDA, N) */ /* On entry, the symmetric matrix A. If UPLO = 'U', the */ /* leading N-by-N upper triangular part of A contains the */ /* upper triangular part of the matrix A. If UPLO = 'L', */ /* the leading N-by-N lower triangular part of A contains */ /* the lower triangular part of the matrix A. */ /* On exit, if JOBZ = 'V', then if INFO = 0, A contains the */ /* orthonormal eigenvectors of the matrix A. */ /* If JOBZ = 'N', then on exit the lower triangle (if UPLO='L') */ /* or the upper triangle (if UPLO='U') of A, including the */ /* diagonal, is destroyed. */ /* LDA (input) INTEGER */ /* The leading dimension of the array A. LDA >= max(1,N). */ /* W (output) DOUBLE PRECISION array, dimension (N) */ /* If INFO = 0, the eigenvalues in ascending order. */ /* WORK (workspace/output) DOUBLE PRECISION array, dimension (MAX(1,LWORK)) */ /* On exit, if INFO = 0, WORK(1) returns the optimal LWORK. */ /* LWORK (input) INTEGER */ /* The length of the array WORK. LWORK >= max(1,3*N-1). */ /* For optimal efficiency, LWORK >= (NB+2)*N, */ /* where NB is the blocksize for DSYTRD returned by ILAENV. */ /* If LWORK = -1, then a workspace query is assumed; the routine */ /* only calculates the optimal size of the WORK array, returns */ /* this value as the first entry of the WORK array, and no error */ /* message related to LWORK is issued by XERBLA. */ /* INFO (output) INTEGER */ /* = 0: successful exit */ /* < 0: if INFO = -i, the i-th argument had an illegal value */ /* > 0: if INFO = i, the algorithm failed to converge; i */ /* off-diagonal elements of an intermediate tridiagonal */ /* form did not converge to zero. */ /* ===================================================================== */ /* .. Parameters .. */ /* .. */ /* .. Local Scalars .. */ /* .. */ /* .. External Functions .. */ /* .. */ /* .. External Subroutines .. */ /* .. */ /* .. Intrinsic Functions .. */ /* .. */ /* .. Executable Statements .. */ /* Test the input parameters. */ /* Parameter adjustments */ a_dim1 = *lda; a_offset = 1 + a_dim1; a -= a_offset; --w; --work; /* Function Body */ wantz = lsame_(jobz, "V"); lower = lsame_(uplo, "L"); lquery = *lwork == -1; *info = 0; if (! (wantz || lsame_(jobz, "N"))) { *info = -1; } else if (! (lower || lsame_(uplo, "U"))) { *info = -2; } else if (*n < 0) { *info = -3; } else if (*lda < max(1,*n)) { *info = -5; } if (*info == 0) { nb = ilaenv_(&c__1, "DSYTRD", uplo, n, &c_n1, &c_n1, &c_n1); /* Computing MAX */ i__1 = 1, i__2 = (nb + 2) * *n; lwkopt = max(i__1,i__2); work[1] = (doublereal) lwkopt; /* Computing MAX */ i__1 = 1, i__2 = *n * 3 - 1; if (*lwork < max(i__1,i__2) && ! lquery) { *info = -8; } } if (*info != 0) { i__1 = -(*info); xerbla_("DSYEV ", &i__1); return 0; } else if (lquery) { return 0; } /* Quick return if possible */ if (*n == 0) { return 0; } if (*n == 1) { w[1] = a[a_dim1 + 1]; work[1] = 2.; if (wantz) { a[a_dim1 + 1] = 1.; } return 0; } /* Get machine constants. */ safmin = dlamch_("Safe minimum"); eps = dlamch_("Precision"); smlnum = safmin / eps; bignum = 1. / smlnum; rmin = sqrt(smlnum); rmax = sqrt(bignum); /* Scale matrix to allowable range, if necessary. */ anrm = dlansy_("M", uplo, n, &a[a_offset], lda, &work[1]); iscale = 0; if (anrm > 0. && anrm < rmin) { iscale = 1; sigma = rmin / anrm; } else if (anrm > rmax) { iscale = 1; sigma = rmax / anrm; } if (iscale == 1) { dlascl_(uplo, &c__0, &c__0, &c_b17, &sigma, n, n, &a[a_offset], lda, info); } /* Call DSYTRD to reduce symmetric matrix to tridiagonal form. */ inde = 1; indtau = inde + *n; indwrk = indtau + *n; llwork = *lwork - indwrk + 1; dsytrd_(uplo, n, &a[a_offset], lda, &w[1], &work[inde], &work[indtau], & work[indwrk], &llwork, &iinfo); /* For eigenvalues only, call DSTERF. For eigenvectors, first call */ /* DORGTR to generate the orthogonal matrix, then call DSTEQR. */ if (! wantz) { dsterf_(n, &w[1], &work[inde], info); } else { dorgtr_(uplo, n, &a[a_offset], lda, &work[indtau], &work[indwrk], & llwork, &iinfo); dsteqr_(jobz, n, &w[1], &work[inde], &a[a_offset], lda, &work[indtau], info); } /* If matrix was scaled, then rescale eigenvalues appropriately. */ if (iscale == 1) { if (*info == 0) { imax = *n; } else { imax = *info - 1; } d__1 = 1. / sigma; dscal_(&imax, &d__1, &w[1], &c__1); } /* Set WORK(1) to optimal workspace size. */ work[1] = (doublereal) lwkopt; return 0; /* End of DSYEV */ } /* dsyev_ */
{ "pile_set_name": "Github" }
/* Copyright SecureKey Technologies Inc. All Rights Reserved. SPDX-License-Identifier: Apache-2.0 */ package fabsdk import ( "github.com/hyperledger/fabric-sdk-go/pkg/common/providers/msp" "github.com/pkg/errors" ) type identityOptions struct { signingIdentity msp.SigningIdentity orgName string username string } // ContextOption provides parameters for creating a session (primarily from a fabric identity/user) type ContextOption func(s *identityOptions) error // WithUser uses the named user to load the identity func WithUser(username string) ContextOption { return func(o *identityOptions) error { o.username = username return nil } } // WithIdentity uses a pre-constructed identity object as the credential for the session func WithIdentity(signingIdentity msp.SigningIdentity) ContextOption { return func(o *identityOptions) error { o.signingIdentity = signingIdentity return nil } } // WithOrg uses the named organization func WithOrg(org string) ContextOption { return func(o *identityOptions) error { o.orgName = org return nil } } // ErrAnonymousIdentity is returned when options for identity creation // don't include neither username nor identity var ErrAnonymousIdentity = errors.New("missing credentials") func (sdk *FabricSDK) newIdentity(options ...ContextOption) (msp.SigningIdentity, error) { opts := identityOptions{ orgName: sdk.provider.IdentityConfig().Client().Organization, } for _, option := range options { err1 := option(&opts) if err1 != nil { return nil, errors.WithMessage(err1, "error in option passed to create identity") } } if opts.signingIdentity == nil && opts.username == "" { return nil, ErrAnonymousIdentity } if opts.signingIdentity != nil { return opts.signingIdentity, nil } if opts.username == "" || opts.orgName == "" { return nil, errors.New("invalid options to create identity") } mgr, ok := sdk.provider.IdentityManager(opts.orgName) if !ok { return nil, errors.New("invalid options to create identity, invalid org name") } user, err := mgr.GetSigningIdentity(opts.username) if err != nil { return nil, err } return user, nil }
{ "pile_set_name": "Github" }
/* ******************************************************************************* * Copyright (C) 1997-2005, International Business Machines * Corporation and others. All Rights Reserved. ******************************************************************************* * Date Name Description * 06/21/00 aliu Creation. ******************************************************************************* */ #ifndef UTRANS_H #define UTRANS_H #include "unicode/utypes.h" #if !UCONFIG_NO_TRANSLITERATION #include "unicode/urep.h" #include "unicode/parseerr.h" #include "unicode/uenum.h" /******************************************************************** * General Notes ******************************************************************** */ /** * \file * \brief C API: Transliterator * * <h2> Transliteration </h2> * The data structures and functions described in this header provide * transliteration services. Transliteration services are implemented * as C++ classes. The comments and documentation in this header * assume the reader is familiar with the C++ headers translit.h and * associated documentation. * * A significant but incomplete subset of the C++ transliteration * services are available to C code through this header. In order to * access more complex transliteration services, refer to the C++ * headers and documentation. * * There are two sets of functions for working with transliterator IDs: * * An old, deprecated set uses char * IDs, which works for true and pure * identifiers that these APIs were designed for, * for example "Cyrillic-Latin". * It does not work when the ID contains filters ("[:Script=Cyrl:]") * or even a complete set of rules because then the ID string contains more * than just "invariant" characters (see utypes.h). * * A new set of functions replaces the old ones and uses UChar * IDs, * paralleling the UnicodeString IDs in the C++ API. (New in ICU 2.8.) */ /******************************************************************** * Data Structures ********************************************************************/ /** * An opaque transliterator for use in C. Open with utrans_openxxx() * and close with utrans_close() when done. Equivalent to the C++ class * Transliterator and its subclasses. * @see Transliterator * @stable ICU 2.0 */ typedef void* UTransliterator; /** * Direction constant indicating the direction in a transliterator, * e.g., the forward or reverse rules of a RuleBasedTransliterator. * Specified when a transliterator is opened. An "A-B" transliterator * transliterates A to B when operating in the forward direction, and * B to A when operating in the reverse direction. * @stable ICU 2.0 */ typedef enum UTransDirection { /** * UTRANS_FORWARD means from &lt;source&gt; to &lt;target&gt; for a * transliterator with ID &lt;source&gt;-&lt;target&gt;. For a transliterator * opened using a rule, it means forward direction rules, e.g., * "A > B". */ UTRANS_FORWARD, /** * UTRANS_REVERSE means from &lt;target&gt; to &lt;source&gt; for a * transliterator with ID &lt;source&gt;-&lt;target&gt;. For a transliterator * opened using a rule, it means reverse direction rules, e.g., * "A < B". */ UTRANS_REVERSE } UTransDirection; /** * Position structure for utrans_transIncremental() incremental * transliteration. This structure defines two substrings of the text * being transliterated. The first region, [contextStart, * contextLimit), defines what characters the transliterator will read * as context. The second region, [start, limit), defines what * characters will actually be transliterated. The second region * should be a subset of the first. * * <p>After a transliteration operation, some of the indices in this * structure will be modified. See the field descriptions for * details. * * <p>contextStart <= start <= limit <= contextLimit * * <p>Note: All index values in this structure must be at code point * boundaries. That is, none of them may occur between two code units * of a surrogate pair. If any index does split a surrogate pair, * results are unspecified. * * @stable ICU 2.0 */ typedef struct UTransPosition { /** * Beginning index, inclusive, of the context to be considered for * a transliteration operation. The transliterator will ignore * anything before this index. INPUT/OUTPUT parameter: This parameter * is updated by a transliteration operation to reflect the maximum * amount of antecontext needed by a transliterator. * @stable ICU 2.4 */ int32_t contextStart; /** * Ending index, exclusive, of the context to be considered for a * transliteration operation. The transliterator will ignore * anything at or after this index. INPUT/OUTPUT parameter: This * parameter is updated to reflect changes in the length of the * text, but points to the same logical position in the text. * @stable ICU 2.4 */ int32_t contextLimit; /** * Beginning index, inclusive, of the text to be transliteratd. * INPUT/OUTPUT parameter: This parameter is advanced past * characters that have already been transliterated by a * transliteration operation. * @stable ICU 2.4 */ int32_t start; /** * Ending index, exclusive, of the text to be transliteratd. * INPUT/OUTPUT parameter: This parameter is updated to reflect * changes in the length of the text, but points to the same * logical position in the text. * @stable ICU 2.4 */ int32_t limit; } UTransPosition; /******************************************************************** * General API ********************************************************************/ /** * Open a custom transliterator, given a custom rules string * OR * a system transliterator, given its ID. * Any non-NULL result from this function should later be closed with * utrans_close(). * * @param id a valid transliterator ID * @param idLength the length of the ID string, or -1 if NUL-terminated * @param dir the desired direction * @param rules the transliterator rules. See the C++ header rbt.h for * rules syntax. If NULL then a system transliterator matching * the ID is returned. * @param rulesLength the length of the rules, or -1 if the rules * are NUL-terminated. * @param parseError a pointer to a UParseError struct to receive the details * of any parsing errors. This parameter may be NULL if no * parsing error details are desired. * @param pErrorCode a pointer to the UErrorCode * @return a transliterator pointer that may be passed to other * utrans_xxx() functions, or NULL if the open call fails. * @stable ICU 2.8 */ U_STABLE UTransliterator* U_EXPORT2 utrans_openU(const UChar *id, int32_t idLength, UTransDirection dir, const UChar *rules, int32_t rulesLength, UParseError *parseError, UErrorCode *pErrorCode); /** * Open an inverse of an existing transliterator. For this to work, * the inverse must be registered with the system. For example, if * the Transliterator "A-B" is opened, and then its inverse is opened, * the result is the Transliterator "B-A", if such a transliterator is * registered with the system. Otherwise the result is NULL and a * failing UErrorCode is set. Any non-NULL result from this function * should later be closed with utrans_close(). * * @param trans the transliterator to open the inverse of. * @param status a pointer to the UErrorCode * @return a pointer to a newly-opened transliterator that is the * inverse of trans, or NULL if the open call fails. * @stable ICU 2.0 */ U_STABLE UTransliterator* U_EXPORT2 utrans_openInverse(const UTransliterator* trans, UErrorCode* status); /** * Create a copy of a transliterator. Any non-NULL result from this * function should later be closed with utrans_close(). * * @param trans the transliterator to be copied. * @param status a pointer to the UErrorCode * @return a transliterator pointer that may be passed to other * utrans_xxx() functions, or NULL if the clone call fails. * @stable ICU 2.0 */ U_STABLE UTransliterator* U_EXPORT2 utrans_clone(const UTransliterator* trans, UErrorCode* status); /** * Close a transliterator. Any non-NULL pointer returned by * utrans_openXxx() or utrans_clone() should eventually be closed. * @param trans the transliterator to be closed. * @stable ICU 2.0 */ U_STABLE void U_EXPORT2 utrans_close(UTransliterator* trans); /** * Return the programmatic identifier for this transliterator. * If this identifier is passed to utrans_openU(), it will open * a transliterator equivalent to this one, if the ID has been * registered. * * @param trans the transliterator to return the ID of. * @param resultLength pointer to an output variable receiving the length * of the ID string; can be NULL * @return the NUL-terminated ID string. This pointer remains * valid until utrans_close() is called on this transliterator. * * @stable ICU 2.8 */ U_STABLE const UChar * U_EXPORT2 utrans_getUnicodeID(const UTransliterator *trans, int32_t *resultLength); /** * Register an open transliterator with the system. When * utrans_open() is called with an ID string that is equal to that * returned by utrans_getID(adoptedTrans,...), then * utrans_clone(adoptedTrans,...) is returned. * * <p>NOTE: After this call the system owns the adoptedTrans and will * close it. The user must not call utrans_close() on adoptedTrans. * * @param adoptedTrans a transliterator, typically the result of * utrans_openRules(), to be registered with the system. * @param status a pointer to the UErrorCode * @stable ICU 2.0 */ U_STABLE void U_EXPORT2 utrans_register(UTransliterator* adoptedTrans, UErrorCode* status); /** * Unregister a transliterator from the system. After this call the * system will no longer recognize the given ID when passed to * utrans_open(). If the ID is invalid then nothing is done. * * @param id an ID to unregister * @param idLength the length of id, or -1 if id is zero-terminated * @stable ICU 2.8 */ U_STABLE void U_EXPORT2 utrans_unregisterID(const UChar* id, int32_t idLength); /** * Set the filter used by a transliterator. A filter can be used to * make the transliterator pass certain characters through untouched. * The filter is expressed using a UnicodeSet pattern. If the * filterPattern is NULL or the empty string, then the transliterator * will be reset to use no filter. * * @param trans the transliterator * @param filterPattern a pattern string, in the form accepted by * UnicodeSet, specifying which characters to apply the * transliteration to. May be NULL or the empty string to indicate no * filter. * @param filterPatternLen the length of filterPattern, or -1 if * filterPattern is zero-terminated * @param status a pointer to the UErrorCode * @see UnicodeSet * @stable ICU 2.0 */ U_STABLE void U_EXPORT2 utrans_setFilter(UTransliterator* trans, const UChar* filterPattern, int32_t filterPatternLen, UErrorCode* status); /** * Return the number of system transliterators. * It is recommended to use utrans_openIDs() instead. * * @return the number of system transliterators. * @stable ICU 2.0 */ U_STABLE int32_t U_EXPORT2 utrans_countAvailableIDs(void); /** * Return a UEnumeration for the available transliterators. * * @param pErrorCode Pointer to the UErrorCode in/out parameter. * @return UEnumeration for the available transliterators. * Close with uenum_close(). * * @stable ICU 2.8 */ U_STABLE UEnumeration * U_EXPORT2 utrans_openIDs(UErrorCode *pErrorCode); /******************************************************************** * Transliteration API ********************************************************************/ /** * Transliterate a segment of a UReplaceable string. The string is * passed in as a UReplaceable pointer rep and a UReplaceableCallbacks * function pointer struct repFunc. Functions in the repFunc struct * will be called in order to modify the rep string. * * @param trans the transliterator * @param rep a pointer to the string. This will be passed to the * repFunc functions. * @param repFunc a set of function pointers that will be used to * modify the string pointed to by rep. * @param start the beginning index, inclusive; <code>0 <= start <= * limit</code>. * @param limit pointer to the ending index, exclusive; <code>start <= * limit <= repFunc->length(rep)</code>. Upon return, *limit will * contain the new limit index. The text previously occupying * <code>[start, limit)</code> has been transliterated, possibly to a * string of a different length, at <code>[start, * </code><em>new-limit</em><code>)</code>, where <em>new-limit</em> * is the return value. * @param status a pointer to the UErrorCode * @stable ICU 2.0 */ U_STABLE void U_EXPORT2 utrans_trans(const UTransliterator* trans, UReplaceable* rep, UReplaceableCallbacks* repFunc, int32_t start, int32_t* limit, UErrorCode* status); /** * Transliterate the portion of the UReplaceable text buffer that can * be transliterated unambiguosly. This method is typically called * after new text has been inserted, e.g. as a result of a keyboard * event. The transliterator will try to transliterate characters of * <code>rep</code> between <code>index.cursor</code> and * <code>index.limit</code>. Characters before * <code>index.cursor</code> will not be changed. * * <p>Upon return, values in <code>index</code> will be updated. * <code>index.start</code> will be advanced to the first * character that future calls to this method will read. * <code>index.cursor</code> and <code>index.limit</code> will * be adjusted to delimit the range of text that future calls to * this method may change. * * <p>Typical usage of this method begins with an initial call * with <code>index.start</code> and <code>index.limit</code> * set to indicate the portion of <code>text</code> to be * transliterated, and <code>index.cursor == index.start</code>. * Thereafter, <code>index</code> can be used without * modification in future calls, provided that all changes to * <code>text</code> are made via this method. * * <p>This method assumes that future calls may be made that will * insert new text into the buffer. As a result, it only performs * unambiguous transliterations. After the last call to this method, * there may be untransliterated text that is waiting for more input * to resolve an ambiguity. In order to perform these pending * transliterations, clients should call utrans_trans() with a start * of index.start and a limit of index.end after the last call to this * method has been made. * * @param trans the transliterator * @param rep a pointer to the string. This will be passed to the * repFunc functions. * @param repFunc a set of function pointers that will be used to * modify the string pointed to by rep. * @param pos a struct containing the start and limit indices of the * text to be read and the text to be transliterated * @param status a pointer to the UErrorCode * @stable ICU 2.0 */ U_STABLE void U_EXPORT2 utrans_transIncremental(const UTransliterator* trans, UReplaceable* rep, UReplaceableCallbacks* repFunc, UTransPosition* pos, UErrorCode* status); /** * Transliterate a segment of a UChar* string. The string is passed * in in a UChar* buffer. The string is modified in place. If the * result is longer than textCapacity, it is truncated. The actual * length of the result is returned in *textLength, if textLength is * non-NULL. *textLength may be greater than textCapacity, but only * textCapacity UChars will be written to *text, including the zero * terminator. * * @param trans the transliterator * @param text a pointer to a buffer containing the text to be * transliterated on input and the result text on output. * @param textLength a pointer to the length of the string in text. * If the length is -1 then the string is assumed to be * zero-terminated. Upon return, the new length is stored in * *textLength. If textLength is NULL then the string is assumed to * be zero-terminated. * @param textCapacity a pointer to the length of the text buffer. * Upon return, * @param start the beginning index, inclusive; <code>0 <= start <= * limit</code>. * @param limit pointer to the ending index, exclusive; <code>start <= * limit <= repFunc->length(rep)</code>. Upon return, *limit will * contain the new limit index. The text previously occupying * <code>[start, limit)</code> has been transliterated, possibly to a * string of a different length, at <code>[start, * </code><em>new-limit</em><code>)</code>, where <em>new-limit</em> * is the return value. * @param status a pointer to the UErrorCode * @stable ICU 2.0 */ U_STABLE void U_EXPORT2 utrans_transUChars(const UTransliterator* trans, UChar* text, int32_t* textLength, int32_t textCapacity, int32_t start, int32_t* limit, UErrorCode* status); /** * Transliterate the portion of the UChar* text buffer that can be * transliterated unambiguosly. See utrans_transIncremental(). The * string is passed in in a UChar* buffer. The string is modified in * place. If the result is longer than textCapacity, it is truncated. * The actual length of the result is returned in *textLength, if * textLength is non-NULL. *textLength may be greater than * textCapacity, but only textCapacity UChars will be written to * *text, including the zero terminator. See utrans_transIncremental() * for usage details. * * @param trans the transliterator * @param text a pointer to a buffer containing the text to be * transliterated on input and the result text on output. * @param textLength a pointer to the length of the string in text. * If the length is -1 then the string is assumed to be * zero-terminated. Upon return, the new length is stored in * *textLength. If textLength is NULL then the string is assumed to * be zero-terminated. * @param textCapacity the length of the text buffer * @param pos a struct containing the start and limit indices of the * text to be read and the text to be transliterated * @param status a pointer to the UErrorCode * @see utrans_transIncremental * @stable ICU 2.0 */ U_STABLE void U_EXPORT2 utrans_transIncrementalUChars(const UTransliterator* trans, UChar* text, int32_t* textLength, int32_t textCapacity, UTransPosition* pos, UErrorCode* status); /* deprecated API ----------------------------------------------------------- */ /* see utrans.h documentation for why these functions are deprecated */ /** * Deprecated, use utrans_openU() instead. * Open a custom transliterator, given a custom rules string * OR * a system transliterator, given its ID. * Any non-NULL result from this function should later be closed with * utrans_close(). * * @param id a valid ID, as returned by utrans_getAvailableID() * @param dir the desired direction * @param rules the transliterator rules. See the C++ header rbt.h * for rules syntax. If NULL then a system transliterator matching * the ID is returned. * @param rulesLength the length of the rules, or -1 if the rules * are zero-terminated. * @param parseError a pointer to a UParseError struct to receive the * details of any parsing errors. This parameter may be NULL if no * parsing error details are desired. * @param status a pointer to the UErrorCode * @return a transliterator pointer that may be passed to other * utrans_xxx() functions, or NULL if the open call fails. * @deprecated ICU 2.8 Use utrans_openU() instead, see utrans.h */ U_DEPRECATED UTransliterator* U_EXPORT2 utrans_open(const char* id, UTransDirection dir, const UChar* rules, /* may be Null */ int32_t rulesLength, /* -1 if null-terminated */ UParseError* parseError, /* may be Null */ UErrorCode* status); /** * Deprecated, use utrans_getUnicodeID() instead. * Return the programmatic identifier for this transliterator. * If this identifier is passed to utrans_open(), it will open * a transliterator equivalent to this one, if the ID has been * registered. * @param trans the transliterator to return the ID of. * @param buf the buffer in which to receive the ID. This may be * NULL, in which case no characters are copied. * @param bufCapacity the capacity of the buffer. Ignored if buf is * NULL. * @return the actual length of the ID, not including * zero-termination. This may be greater than bufCapacity. * @deprecated ICU 2.8 Use utrans_getUnicodeID() instead, see utrans.h */ U_DEPRECATED int32_t U_EXPORT2 utrans_getID(const UTransliterator* trans, char* buf, int32_t bufCapacity); /** * Deprecated, use utrans_unregisterID() instead. * Unregister a transliterator from the system. After this call the * system will no longer recognize the given ID when passed to * utrans_open(). If the id is invalid then nothing is done. * * @param id a zero-terminated ID * @deprecated ICU 2.8 Use utrans_unregisterID() instead, see utrans.h */ U_DEPRECATED void U_EXPORT2 utrans_unregister(const char* id); /** * Deprecated, use utrans_openIDs() instead. * Return the ID of the index-th system transliterator. The result * is placed in the given buffer. If the given buffer is too small, * the initial substring is copied to buf. The result in buf is * always zero-terminated. * * @param index the number of the transliterator to return. Must * satisfy 0 <= index < utrans_countAvailableIDs(). If index is out * of range then it is treated as if it were 0. * @param buf the buffer in which to receive the ID. This may be * NULL, in which case no characters are copied. * @param bufCapacity the capacity of the buffer. Ignored if buf is * NULL. * @return the actual length of the index-th ID, not including * zero-termination. This may be greater than bufCapacity. * @deprecated ICU 2.8 Use utrans_openIDs() instead, see utrans.h */ U_DEPRECATED int32_t U_EXPORT2 utrans_getAvailableID(int32_t index, char* buf, int32_t bufCapacity); #endif /* #if !UCONFIG_NO_TRANSLITERATION */ #endif
{ "pile_set_name": "Github" }
define([ "require", "dojo/_base/declare", "dijit/_WidgetBase", "dijit/_TemplatedMixin", "dijit/_WidgetsInTemplateMixin", "./TestWidget" ], function(require, declare, _WidgetBase, _TemplatedMixin, _WidgetsInTemplateMixin){ // This module requires utilises a relative MID in the template. Because of the synchronous nature of the widget // lifecycle, you need to require in any modules in the template into the parent module (as auto-require will not // work) as well as require in the context require and pass it as part of the declare. return declare([_WidgetBase, _TemplatedMixin, _WidgetsInTemplateMixin], { templateString: '<div><div data-dojo-type="./TestWidget" data-dojo-attach-point="fooNode"></div></div>', contextRequire: require }); });
{ "pile_set_name": "Github" }
! Copyright (C) 2008 Slava Pestov. ! See http://factorcode.org/license.txt for BSD license. USING: backtrack shuffle math math.ranges quotations locals fry kernel words io memoize macros prettyprint sequences assocs combinators namespaces ; IN: benchmark.backtrack ! This was suggested by Dr_Ford. Compute the number of quadruples ! (a,b,c,d) with 1 <= a,b,c,d <= 10 such that we can make 24 by ! placing them on the stack, and applying the operations ! +, -, * and rot as many times as we wish. : nop ( -- ) ; : do-something ( a b -- c ) { + - * } amb-execute ; : some-rots ( a b c -- a b c ) ! Try to rot 0, 1 or 2 times. { nop rot -rot } amb-execute ; MEMO: 24-from-1 ( a -- ? ) 24 = ; MEMO: 24-from-2 ( a b -- ? ) [ do-something 24-from-1 ] [ 2drop ] if-amb ; MEMO: 24-from-3 ( a b c -- ? ) [ some-rots do-something 24-from-2 ] [ 3drop ] if-amb ; MEMO: 24-from-4 ( a b c d -- ? ) [ some-rots do-something 24-from-3 ] [ 4drop ] if-amb ; : find-impossible-24 ( -- n ) 10 [1,b] [| a | 10 [1,b] [| b | 10 [1,b] [| c | 10 [1,b] [| d | a b c d 24-from-4 ] count ] map-sum ] map-sum ] map-sum ; CONSTANT: words { 24-from-1 24-from-2 24-from-3 24-from-4 } : backtrack-benchmark ( -- ) words [ reset-memoized ] each find-impossible-24 6479 assert= words [ "memoize" word-prop assoc-size ] map { 1588 5137 4995 10000 } assert= ; MAIN: backtrack-benchmark
{ "pile_set_name": "Github" }
// Copyright 2009 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. package net import ( "bytes" "context" "fmt" "internal/testenv" "reflect" "runtime" "sort" "strings" "testing" "time" ) func lookupLocalhost(ctx context.Context, fn func(context.Context, string) ([]IPAddr, error), host string) ([]IPAddr, error) { switch host { case "localhost": return []IPAddr{ {IP: IPv4(127, 0, 0, 1)}, {IP: IPv6loopback}, }, nil default: return fn(ctx, host) } } // The Lookup APIs use various sources such as local database, DNS or // mDNS, and may use platform-dependent DNS stub resolver if possible. // The APIs accept any of forms for a query; host name in various // encodings, UTF-8 encoded net name, domain name, FQDN or absolute // FQDN, but the result would be one of the forms and it depends on // the circumstances. var lookupGoogleSRVTests = []struct { service, proto, name string cname, target string }{ { "xmpp-server", "tcp", "google.com", "google.com.", "google.com.", }, { "xmpp-server", "tcp", "google.com.", "google.com.", "google.com.", }, // non-standard back door { "", "", "_xmpp-server._tcp.google.com", "google.com.", "google.com.", }, { "", "", "_xmpp-server._tcp.google.com.", "google.com.", "google.com.", }, } func TestLookupGoogleSRV(t *testing.T) { if testenv.Builder() == "" { testenv.MustHaveExternalNetwork(t) } if !supportsIPv4() || !*testIPv4 { t.Skip("IPv4 is required") } for _, tt := range lookupGoogleSRVTests { cname, srvs, err := LookupSRV(tt.service, tt.proto, tt.name) if err != nil { testenv.SkipFlakyNet(t) t.Fatal(err) } if len(srvs) == 0 { t.Error("got no record") } if !strings.HasSuffix(cname, tt.cname) { t.Errorf("got %s; want %s", cname, tt.cname) } for _, srv := range srvs { if !strings.HasSuffix(srv.Target, tt.target) { t.Errorf("got %v; want a record containing %s", srv, tt.target) } } } } var lookupGmailMXTests = []struct { name, host string }{ {"gmail.com", "google.com."}, {"gmail.com.", "google.com."}, } func TestLookupGmailMX(t *testing.T) { if testenv.Builder() == "" { testenv.MustHaveExternalNetwork(t) } if !supportsIPv4() || !*testIPv4 { t.Skip("IPv4 is required") } defer dnsWaitGroup.Wait() for _, tt := range lookupGmailMXTests { mxs, err := LookupMX(tt.name) if err != nil { t.Fatal(err) } if len(mxs) == 0 { t.Error("got no record") } for _, mx := range mxs { if !strings.HasSuffix(mx.Host, tt.host) { t.Errorf("got %v; want a record containing %s", mx, tt.host) } } } } var lookupGmailNSTests = []struct { name, host string }{ {"gmail.com", "google.com."}, {"gmail.com.", "google.com."}, } func TestLookupGmailNS(t *testing.T) { if testenv.Builder() == "" { testenv.MustHaveExternalNetwork(t) } if !supportsIPv4() || !*testIPv4 { t.Skip("IPv4 is required") } defer dnsWaitGroup.Wait() for _, tt := range lookupGmailNSTests { nss, err := LookupNS(tt.name) if err != nil { testenv.SkipFlakyNet(t) t.Fatal(err) } if len(nss) == 0 { t.Error("got no record") } for _, ns := range nss { if !strings.HasSuffix(ns.Host, tt.host) { t.Errorf("got %v; want a record containing %s", ns, tt.host) } } } } var lookupGmailTXTTests = []struct { name, txt, host string }{ {"gmail.com", "spf", "google.com"}, {"gmail.com.", "spf", "google.com"}, } func TestLookupGmailTXT(t *testing.T) { if testenv.Builder() == "" { testenv.MustHaveExternalNetwork(t) } if !supportsIPv4() || !*testIPv4 { t.Skip("IPv4 is required") } defer dnsWaitGroup.Wait() for _, tt := range lookupGmailTXTTests { txts, err := LookupTXT(tt.name) if err != nil { t.Fatal(err) } if len(txts) == 0 { t.Error("got no record") } for _, txt := range txts { if !strings.Contains(txt, tt.txt) || (!strings.HasSuffix(txt, tt.host) && !strings.HasSuffix(txt, tt.host+".")) { t.Errorf("got %s; want a record containing %s, %s", txt, tt.txt, tt.host) } } } } var lookupGooglePublicDNSAddrTests = []struct { addr, name string }{ {"8.8.8.8", ".google.com."}, {"8.8.4.4", ".google.com."}, {"2001:4860:4860::8888", ".google.com."}, {"2001:4860:4860::8844", ".google.com."}, } func TestLookupGooglePublicDNSAddr(t *testing.T) { if testenv.Builder() == "" { testenv.MustHaveExternalNetwork(t) } if !supportsIPv4() || !supportsIPv6() || !*testIPv4 || !*testIPv6 { t.Skip("both IPv4 and IPv6 are required") } defer dnsWaitGroup.Wait() for _, tt := range lookupGooglePublicDNSAddrTests { names, err := LookupAddr(tt.addr) if err != nil { t.Fatal(err) } if len(names) == 0 { t.Error("got no record") } for _, name := range names { if !strings.HasSuffix(name, tt.name) { t.Errorf("got %s; want a record containing %s", name, tt.name) } } } } func TestLookupIPv6LinkLocalAddr(t *testing.T) { if !supportsIPv6() || !*testIPv6 { t.Skip("IPv6 is required") } defer dnsWaitGroup.Wait() addrs, err := LookupHost("localhost") if err != nil { t.Fatal(err) } found := false for _, addr := range addrs { if addr == "fe80::1%lo0" { found = true break } } if !found { t.Skipf("not supported on %s", runtime.GOOS) } if _, err := LookupAddr("fe80::1%lo0"); err != nil { t.Error(err) } } var lookupCNAMETests = []struct { name, cname string }{ {"www.iana.org", "icann.org."}, {"www.iana.org.", "icann.org."}, {"www.google.com", "google.com."}, } func TestLookupCNAME(t *testing.T) { if testenv.Builder() == "" { testenv.MustHaveExternalNetwork(t) } if !supportsIPv4() || !*testIPv4 { t.Skip("IPv4 is required") } defer dnsWaitGroup.Wait() for _, tt := range lookupCNAMETests { cname, err := LookupCNAME(tt.name) if err != nil { t.Fatal(err) } if !strings.HasSuffix(cname, tt.cname) { t.Errorf("got %s; want a record containing %s", cname, tt.cname) } } } var lookupGoogleHostTests = []struct { name string }{ {"google.com"}, {"google.com."}, } func TestLookupGoogleHost(t *testing.T) { if testenv.Builder() == "" { testenv.MustHaveExternalNetwork(t) } if !supportsIPv4() || !*testIPv4 { t.Skip("IPv4 is required") } defer dnsWaitGroup.Wait() for _, tt := range lookupGoogleHostTests { addrs, err := LookupHost(tt.name) if err != nil { t.Fatal(err) } if len(addrs) == 0 { t.Error("got no record") } for _, addr := range addrs { if ParseIP(addr) == nil { t.Errorf("got %q; want a literal IP address", addr) } } } } func TestLookupLongTXT(t *testing.T) { if runtime.GOOS == "plan9" { t.Skip("skipping on plan9; see https://golang.org/issue/22857") } if testenv.Builder() == "" { testenv.MustHaveExternalNetwork(t) } defer dnsWaitGroup.Wait() txts, err := LookupTXT("golang.rsc.io") if err != nil { t.Fatal(err) } sort.Strings(txts) want := []string{ strings.Repeat("abcdefghijklmnopqrstuvwxyABCDEFGHJIKLMNOPQRSTUVWXY", 10), "gophers rule", } if !reflect.DeepEqual(txts, want) { t.Fatalf("LookupTXT golang.rsc.io incorrect\nhave %q\nwant %q", txts, want) } } var lookupGoogleIPTests = []struct { name string }{ {"google.com"}, {"google.com."}, } func TestLookupGoogleIP(t *testing.T) { if testenv.Builder() == "" { testenv.MustHaveExternalNetwork(t) } if !supportsIPv4() || !*testIPv4 { t.Skip("IPv4 is required") } defer dnsWaitGroup.Wait() for _, tt := range lookupGoogleIPTests { ips, err := LookupIP(tt.name) if err != nil { t.Fatal(err) } if len(ips) == 0 { t.Error("got no record") } for _, ip := range ips { if ip.To4() == nil && ip.To16() == nil { t.Errorf("got %v; want an IP address", ip) } } } } var revAddrTests = []struct { Addr string Reverse string ErrPrefix string }{ {"1.2.3.4", "4.3.2.1.in-addr.arpa.", ""}, {"245.110.36.114", "114.36.110.245.in-addr.arpa.", ""}, {"::ffff:12.34.56.78", "78.56.34.12.in-addr.arpa.", ""}, {"::1", "1.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.ip6.arpa.", ""}, {"1::", "0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.1.0.0.0.ip6.arpa.", ""}, {"1234:567::89a:bcde", "e.d.c.b.a.9.8.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.7.6.5.0.4.3.2.1.ip6.arpa.", ""}, {"1234:567:fefe:bcbc:adad:9e4a:89a:bcde", "e.d.c.b.a.9.8.0.a.4.e.9.d.a.d.a.c.b.c.b.e.f.e.f.7.6.5.0.4.3.2.1.ip6.arpa.", ""}, {"1.2.3", "", "unrecognized address"}, {"1.2.3.4.5", "", "unrecognized address"}, {"1234:567:bcbca::89a:bcde", "", "unrecognized address"}, {"1234:567::bcbc:adad::89a:bcde", "", "unrecognized address"}, } func TestReverseAddress(t *testing.T) { defer dnsWaitGroup.Wait() for i, tt := range revAddrTests { a, err := reverseaddr(tt.Addr) if len(tt.ErrPrefix) > 0 && err == nil { t.Errorf("#%d: expected %q, got <nil> (error)", i, tt.ErrPrefix) continue } if len(tt.ErrPrefix) == 0 && err != nil { t.Errorf("#%d: expected <nil>, got %q (error)", i, err) } if err != nil && err.(*DNSError).Err != tt.ErrPrefix { t.Errorf("#%d: expected %q, got %q (mismatched error)", i, tt.ErrPrefix, err.(*DNSError).Err) } if a != tt.Reverse { t.Errorf("#%d: expected %q, got %q (reverse address)", i, tt.Reverse, a) } } } func TestDNSFlood(t *testing.T) { if !*testDNSFlood { t.Skip("test disabled; use -dnsflood to enable") } defer dnsWaitGroup.Wait() var N = 5000 if runtime.GOOS == "darwin" { // On Darwin this test consumes kernel threads much // than other platforms for some reason. // When we monitor the number of allocated Ms by // observing on runtime.newm calls, we can see that it // easily reaches the per process ceiling // kern.num_threads when CGO_ENABLED=1 and // GODEBUG=netdns=go. N = 500 } const timeout = 3 * time.Second ctxHalfTimeout, cancel := context.WithTimeout(context.Background(), timeout/2) defer cancel() ctxTimeout, cancel := context.WithTimeout(context.Background(), timeout) defer cancel() c := make(chan error, 2*N) for i := 0; i < N; i++ { name := fmt.Sprintf("%d.net-test.golang.org", i) go func() { _, err := DefaultResolver.LookupIPAddr(ctxHalfTimeout, name) c <- err }() go func() { _, err := DefaultResolver.LookupIPAddr(ctxTimeout, name) c <- err }() } qstats := struct { succeeded, failed int timeout, temporary, other int unknown int }{} deadline := time.After(timeout + time.Second) for i := 0; i < 2*N; i++ { select { case <-deadline: t.Fatal("deadline exceeded") case err := <-c: switch err := err.(type) { case nil: qstats.succeeded++ case Error: qstats.failed++ if err.Timeout() { qstats.timeout++ } if err.Temporary() { qstats.temporary++ } if !err.Timeout() && !err.Temporary() { qstats.other++ } default: qstats.failed++ qstats.unknown++ } } } // A high volume of DNS queries for sub-domain of golang.org // would be coordinated by authoritative or recursive server, // or stub resolver which implements query-response rate // limitation, so we can expect some query successes and more // failures including timeout, temporary and other here. // As a rule, unknown must not be shown but it might possibly // happen due to issue 4856 for now. t.Logf("%v succeeded, %v failed (%v timeout, %v temporary, %v other, %v unknown)", qstats.succeeded, qstats.failed, qstats.timeout, qstats.temporary, qstats.other, qstats.unknown) } func TestLookupDotsWithLocalSource(t *testing.T) { if !supportsIPv4() || !*testIPv4 { t.Skip("IPv4 is required") } if testenv.Builder() == "" { testenv.MustHaveExternalNetwork(t) } defer dnsWaitGroup.Wait() for i, fn := range []func() func(){forceGoDNS, forceCgoDNS} { fixup := fn() if fixup == nil { continue } names, err := LookupAddr("127.0.0.1") fixup() if err != nil { t.Logf("#%d: %v", i, err) continue } mode := "netgo" if i == 1 { mode = "netcgo" } loop: for i, name := range names { if strings.Index(name, ".") == len(name)-1 { // "localhost" not "localhost." for j := range names { if j == i { continue } if names[j] == name[:len(name)-1] { // It's OK if we find the name without the dot, // as some systems say 127.0.0.1 localhost localhost. continue loop } } t.Errorf("%s: got %s; want %s", mode, name, name[:len(name)-1]) } else if strings.Contains(name, ".") && !strings.HasSuffix(name, ".") { // "localhost.localdomain." not "localhost.localdomain" t.Errorf("%s: got %s; want name ending with trailing dot", mode, name) } } } } func TestLookupDotsWithRemoteSource(t *testing.T) { if testenv.Builder() == "" { testenv.MustHaveExternalNetwork(t) } if !supportsIPv4() || !*testIPv4 { t.Skip("IPv4 is required") } defer dnsWaitGroup.Wait() if fixup := forceGoDNS(); fixup != nil { testDots(t, "go") fixup() } if fixup := forceCgoDNS(); fixup != nil { testDots(t, "cgo") fixup() } } func testDots(t *testing.T, mode string) { names, err := LookupAddr("8.8.8.8") // Google dns server if err != nil { testenv.SkipFlakyNet(t) t.Errorf("LookupAddr(8.8.8.8): %v (mode=%v)", err, mode) } else { for _, name := range names { if !strings.HasSuffix(name, ".google.com.") { t.Errorf("LookupAddr(8.8.8.8) = %v, want names ending in .google.com. with trailing dot (mode=%v)", names, mode) break } } } cname, err := LookupCNAME("www.mit.edu") if err != nil { testenv.SkipFlakyNet(t) t.Errorf("LookupCNAME(www.mit.edu, mode=%v): %v", mode, err) } else if !strings.HasSuffix(cname, ".") { t.Errorf("LookupCNAME(www.mit.edu) = %v, want cname ending in . with trailing dot (mode=%v)", cname, mode) } mxs, err := LookupMX("google.com") if err != nil { testenv.SkipFlakyNet(t) t.Errorf("LookupMX(google.com): %v (mode=%v)", err, mode) } else { for _, mx := range mxs { if !strings.HasSuffix(mx.Host, ".google.com.") { t.Errorf("LookupMX(google.com) = %v, want names ending in .google.com. with trailing dot (mode=%v)", mxString(mxs), mode) break } } } nss, err := LookupNS("google.com") if err != nil { testenv.SkipFlakyNet(t) t.Errorf("LookupNS(google.com): %v (mode=%v)", err, mode) } else { for _, ns := range nss { if !strings.HasSuffix(ns.Host, ".google.com.") { t.Errorf("LookupNS(google.com) = %v, want names ending in .google.com. with trailing dot (mode=%v)", nsString(nss), mode) break } } } cname, srvs, err := LookupSRV("xmpp-server", "tcp", "google.com") if err != nil { testenv.SkipFlakyNet(t) t.Errorf("LookupSRV(xmpp-server, tcp, google.com): %v (mode=%v)", err, mode) } else { if !strings.HasSuffix(cname, ".google.com.") { t.Errorf("LookupSRV(xmpp-server, tcp, google.com) returned cname=%v, want name ending in .google.com. with trailing dot (mode=%v)", cname, mode) } for _, srv := range srvs { if !strings.HasSuffix(srv.Target, ".google.com.") { t.Errorf("LookupSRV(xmpp-server, tcp, google.com) returned addrs=%v, want names ending in .google.com. with trailing dot (mode=%v)", srvString(srvs), mode) break } } } } func mxString(mxs []*MX) string { var buf bytes.Buffer sep := "" fmt.Fprintf(&buf, "[") for _, mx := range mxs { fmt.Fprintf(&buf, "%s%s:%d", sep, mx.Host, mx.Pref) sep = " " } fmt.Fprintf(&buf, "]") return buf.String() } func nsString(nss []*NS) string { var buf bytes.Buffer sep := "" fmt.Fprintf(&buf, "[") for _, ns := range nss { fmt.Fprintf(&buf, "%s%s", sep, ns.Host) sep = " " } fmt.Fprintf(&buf, "]") return buf.String() } func srvString(srvs []*SRV) string { var buf bytes.Buffer sep := "" fmt.Fprintf(&buf, "[") for _, srv := range srvs { fmt.Fprintf(&buf, "%s%s:%d:%d:%d", sep, srv.Target, srv.Port, srv.Priority, srv.Weight) sep = " " } fmt.Fprintf(&buf, "]") return buf.String() } func TestLookupPort(t *testing.T) { // See http://www.iana.org/assignments/service-names-port-numbers/service-names-port-numbers.xhtml // // Please be careful about adding new test cases. // There are platforms having incomplete mappings for // restricted resource access and security reasons. type test struct { network string name string port int ok bool } var tests = []test{ {"tcp", "0", 0, true}, {"udp", "0", 0, true}, {"udp", "domain", 53, true}, {"--badnet--", "zzz", 0, false}, {"tcp", "--badport--", 0, false}, {"tcp", "-1", 0, false}, {"tcp", "65536", 0, false}, {"udp", "-1", 0, false}, {"udp", "65536", 0, false}, {"tcp", "123456789", 0, false}, // Issue 13610: LookupPort("tcp", "") {"tcp", "", 0, true}, {"tcp4", "", 0, true}, {"tcp6", "", 0, true}, {"udp", "", 0, true}, {"udp4", "", 0, true}, {"udp6", "", 0, true}, } switch runtime.GOOS { case "android": if netGo { t.Skipf("not supported on %s without cgo; see golang.org/issues/14576", runtime.GOOS) } default: tests = append(tests, test{"tcp", "http", 80, true}) } for _, tt := range tests { port, err := LookupPort(tt.network, tt.name) if port != tt.port || (err == nil) != tt.ok { t.Errorf("LookupPort(%q, %q) = %d, %v; want %d, error=%t", tt.network, tt.name, port, err, tt.port, !tt.ok) } if err != nil { if perr := parseLookupPortError(err); perr != nil { t.Error(perr) } } } } // Like TestLookupPort but with minimal tests that should always pass // because the answers are baked-in to the net package. func TestLookupPort_Minimal(t *testing.T) { type test struct { network string name string port int } var tests = []test{ {"tcp", "http", 80}, {"tcp", "HTTP", 80}, // case shouldn't matter {"tcp", "https", 443}, {"tcp", "ssh", 22}, {"tcp", "gopher", 70}, {"tcp4", "http", 80}, {"tcp6", "http", 80}, } for _, tt := range tests { port, err := LookupPort(tt.network, tt.name) if port != tt.port || err != nil { t.Errorf("LookupPort(%q, %q) = %d, %v; want %d, error=nil", tt.network, tt.name, port, err, tt.port) } } } func TestLookupProtocol_Minimal(t *testing.T) { type test struct { name string want int } var tests = []test{ {"tcp", 6}, {"TcP", 6}, // case shouldn't matter {"icmp", 1}, {"igmp", 2}, {"udp", 17}, {"ipv6-icmp", 58}, } for _, tt := range tests { got, err := lookupProtocol(context.Background(), tt.name) if got != tt.want || err != nil { t.Errorf("LookupProtocol(%q) = %d, %v; want %d, error=nil", tt.name, got, err, tt.want) } } } func TestLookupNonLDH(t *testing.T) { if runtime.GOOS == "nacl" { t.Skip("skip on nacl") } defer dnsWaitGroup.Wait() if fixup := forceGoDNS(); fixup != nil { defer fixup() } // "LDH" stands for letters, digits, and hyphens and is the usual // description of standard DNS names. // This test is checking that other kinds of names are reported // as not found, not reported as invalid names. addrs, err := LookupHost("!!!.###.bogus..domain.") if err == nil { t.Fatalf("lookup succeeded: %v", addrs) } if !strings.HasSuffix(err.Error(), errNoSuchHost.Error()) { t.Fatalf("lookup error = %v, want %v", err, errNoSuchHost) } } func TestLookupContextCancel(t *testing.T) { if testenv.Builder() == "" { testenv.MustHaveExternalNetwork(t) } if runtime.GOOS == "nacl" { t.Skip("skip on nacl") } defer dnsWaitGroup.Wait() ctx, ctxCancel := context.WithCancel(context.Background()) ctxCancel() _, err := DefaultResolver.LookupIPAddr(ctx, "google.com") if err != errCanceled { testenv.SkipFlakyNet(t) t.Fatal(err) } ctx = context.Background() _, err = DefaultResolver.LookupIPAddr(ctx, "google.com") if err != nil { testenv.SkipFlakyNet(t) t.Fatal(err) } }
{ "pile_set_name": "Github" }
# Upgrading Forseti with Terraform ## Introduction <walkthrough-tutorial-duration duration="30"></walkthrough-tutorial-duration> This guide explains how to upgrade Forseti previously installed with Terraform, to version 2.23. This is due to a breaking change introduced in this Terraform module, now version 5.0.0. The steps outlined in this guide should not be needed after Forseti has been upgraded versions 2.23 or above. If you have any questions about this process, please contact us by [email](mailto:[email protected]) or on [Slack](https://forsetisecurity.slack.com/join/shared_invite/enQtNDIyMzg4Nzg1NjcxLTM1NTUzZmM2ODVmNzE5MWEwYzAwNjUxMjVkZjhmYWZiOGZjMjY3ZjllNDlkYjk1OGU4MTVhZGM4NzgyZjZhNTE). ## Prerequisites Before you begin the migration process, you will need: - A Forseti deployment of at least v2.18.0; follow the [upgrade guide](https://forsetisecurity.org/docs/latest/setup/upgrade.html) as necessary deployed via the [terraform-google-forseti Terraform module](https://github.com/forseti-security/terraform-google-forseti). Please note that the upper bound of the upgrades possible for the Python installer is 2.22. - A version of the [Terraform command-line interface](https://www.terraform.io/downloads.html) in the 0.12 series. - The ID of the GCP project in which Forseti is deployed. - A service account in the organization with the [roles required by the Terraform module](https://registry.terraform.io/modules/terraform-google-modules/forseti/google/4.3.0#iam-roles). - A [JSON key file](https://cloud.google.com/iam/docs/creating-managing-service-account-keys#creating_service_account_keys) for the service account. - If you are an Org Admin in the organization in which you deploying Forseti, a separate Service Account and Key are recommended, but not required. - **Strongly recommended out of an overabundance of caution:** A backup of your current state. - In the Forseti Server's GCS Bucket - Scanner rules - Server config file - Scanner Violations - Inventory summary - [CloudSQL database](https://cloud.google.com/sql/docs/mysql/backup-recovery/backups) ## Configuring Terraform Terraform can assume the identity of a service account through a strategy called [Application Default Credentials](https://cloud.google.com/docs/authentication/production#providing_credentials_to_your_application) when provisioning resources. To enable this approach, set the appropriate environment variable to the path of the service account JSON key file: ```sh export GOOGLE_APPLICATION_CREDENTIALS="PATH_TO_JSON_KEY_FILE" ``` As stated in the pre-requisites, if you have Org Admin privilges, you do not need to complete this step. ## Backup the Terraform State In a shell, navigate to the folder containing your user-defined Terraform module, most likely in a **main.tf**. The following command will simultaneously backup your existing Terraform state and remove resource from the current state file. This will not affect your existing Forseti deployment. ```sh terraform state rm $(terraform state list) ``` ## Update main.tf In order to support this upgrade, we'll need to update a few input variables. ### Source The **source** will need to point to the root terraform-google-forseti module. ``` source = "terraform-google-modules/forseti/google" ``` If you have cloned the module to your local file system, you may set the **source** path to the directory containing the module. ### Version The **version** will need to be 5.0.0. ``` version = "5.0.0" ``` If you have set the **source** path to the directory containing the module, omit the **version** variable. ### Region If you have a **region**, it will need to be split into the cloudsql_region, server_region, and client_region variables. You will also need to set the location of the Forseti Client and Server storage buckets (**storage_bucket_location**) as well as the CAI storage bucket (**bucket_cai_location**). **NOTE:** In order to prevent data loss to your CloudSQL database, please double check the region where your CloudSQL instance currently exists and update the **cloudsql_region** variable, accourdingly. Before (example): ``` region = "us-central1" ``` After (example): ``` cloudsql_region = "us-central1" server_region = "us-central1" client_region = "us-central1" storage_bucket_location = "us-central1" bucket_cai_location = "us-central1" ``` ### Credentials path Remove the **credentials_path** variable if present. The `google` provider now solely relies on the _GOOGLE_APPLICATION_CREDENTIALS_ environment variable. ### Root Resource identity Add the **resource_name_suffix** variable and set it to the resource suffix. The suffix can be found appended to the Forseti Server VM, for example. ``` resource_name_suffix = "abc123efg" ``` ### Server Rules and Login Add the following clause to the bottom of your main.tf. ``` client_instance_metadata = { enable-oslogin = "TRUE" } enable_write = true manage_rules_enabled = false ``` ## Obtain and Run the Import Script ### Obtain the Import Script This [import script](https://github.com/forseti-security/terraform-google-forseti/blob/module-release-5.0.0/helpers/import.sh) will import the Forseti GCP resources into a local state file. ```sh curl --location --remote-name https://raw.githubusercontent.com/forseti-security/terraform-google-forseti/module-release-5.0.0/helpers/import.sh chmod +x import.sh ./import.sh -h ``` ### Initialize the Terraform Module ```sh terraform init ``` ### Import the Existing Terraform State Import the existing resources to the Terraform state, replacing the uppercase values with the aforementioned values: ```sh ./import.sh -m MODULE_LOCAL_NAME -o ORG_ID -p PROJECT_ID -s RESOURCE_NAME_SUFFIX -z GCE_ZONE [-n NETWORK_PROJECT_ID] ``` Observe the expected Terraform changes by execution `terraform plan`. As stated in the introduction, if you have any questions about this process, please contact us by [email](mailto:[email protected]) or on [Slack](https://forsetisecurity.slack.com/join/shared_invite/enQtNDIyMzg4Nzg1NjcxLTM1NTUzZmM2ODVmNzE5MWEwYzAwNjUxMjVkZjhmYWZiOGZjMjY3ZjllNDlkYjk1OGU4MTVhZGM4NzgyZjZhNTE). ## Terraform Plan It is strongly recommend to execute `terraform plan` before `terraform apply`. This will provide you an opportunity to review changes Terraform is planning to make to your deployment. ```sh terraform plan ``` ### Terraform Changes Because there is not an exact mapping between the deprecated Python Installer and the Terraform module, some changes will occur when Terraform assumes management of the Forseti deployment. You should carefully review this section as well as the output from `terraform plan` to ensure that all changes are expected and acceptable. Observe the expected Terraform changes. As stated in the introduction, if you have any questions about this process, please contact us by e-mail at [email protected] or on [Slack](https://forsetisecurity.slack.com/join/shared_invite/enQtNDIyMzg4Nzg1NjcxLTM1NTUzZmM2ODVmNzE5MWEwYzAwNjUxMjVkZjhmYWZiOGZjMjY3ZjllNDlkYjk1OGU4MTVhZGM4NzgyZjZhNTE). #### Created - The `forseti-client-gcp-RESOURCE_NAME_SUFFIX` service account will gain the Cloud Trace Agent (`roles/cloudtrace.agent`) role - The `forseti-client-gcp-RESOURCE_NAME_SUFFIX` service account will gain the Cloud Trace Agent (`roles/storage.objectViewer`) role - The `forseti-server-gcp-RESOURCE_NAME_SUFFIX` service account will gain the following roles. Note your server service account likely has these roles already. Terraform re-applying them is essentially a no-op. - Cloud Trace Agent (`roles/cloudtrace.agent`) - IAM Service Account Token Creator (`roles/iam.serviceAccountTokenCreator`) - App Engine Viewer (`roles/appengine.appViewer`) - BigQuery Meta-data Viewer (`roles/bigquery.metadataViewer`) - Project Reader (`roles/browser`) - Cloud Asset Viewer (`roles/cloudasset.viewer`) - CloudSQL Viewer (`roles/cloudsql.viewer`) - Network Viewer (`roles/compute.networkViewer`) - Security Reviewer (`roles/iam.securityReviewer`) - Organization Policy Viewer (`roles/orgpolicy.policyViewer`) - Sevice Management Quota Viewer (`roles/servicemanagement.quotaViewer`) - Service Usage Consumer (`roles/serviceusage.serviceUsageConsumer`) - Compute Security Admin (`roles/compute.securityAdmin`) - Storage Object Viewer (`roles/storage.objectViewer`) - Storage Object Creator (`roles/storage.objectCreator`) - CloudSQL Client (`roles/cloudsql.client`) - Stackdriver Log Writer (`roles/logging.logWriter`) - Service Account Token Creator (`roles/iam.serviceAccountTokenCreator`) #### Updated In-Place - The `forseti-client-deny-all-RESOURCE_NAME_SUFFIX` firewall rule and the `forseti-server-deny-all-RESOURCE_NAME_SUFFIX` firewall rule will both update from denying all protocols to denying ICMP, TCP, and UDP - The `forseti-server-allow-grpc-RESOURCE_NAME_SUFFIX` firewall rule will update to only allow traffic from the `forseti-client-gcp-RESOURCE_NAME_SUFFIX` service account and to allow traffic to port 50052 in addition to 50051 - The `forseti-cai-export-RESOURCE_NAME_SUFFIX`, `forseti-client-RESOURCE_NAME_SUFFIX` and `forseti-server-RESOURCE_NAME_SUFFIX` GCS bucket to set `force_destroy` to `true`. - The `forseti-client-gcp-RESOURCE_NAME_SUFFIX` and `forseti-server-gcp-RESOURCE_NAME_SUFFIX` service accounts will be updated in place to change the display name - The `forseti-server-db-RESOURCE_NAME_SUFFIX` CloudSQL database will increase in resource size. It will also gain the `net_write_timeout` flag. #### Destroyed and Replaced - The `forseti-client-allow-ssh-external-RESOURCE_NAME_SUFFIX` firewall rule and the `forseti-server-allow-ssh-external-RESOURCE_NAME_SUFFIX` firewall rule will both be replaced due to a naming change, but the new firewall rules will be equivalent - The `forseti-client-vm-RESOURCE_NAME_SUFFIX` compute instance and the `forseti-server-vm-RESOURCE_NAME_SUFFIX` compute instance will be replaced due to changes in metadata startup scripts, boot disk sizes and boot disk types; these VMs should be stateless but ensure that any customizations are captured before applying this change - The `configs/forseti_conf_client.yaml` object in the `forseti-client-RESOURCE_NAME_SUFFIX` storage bucket and the `configs/forseti_conf_server.yaml` object in the `forseti-server-RESOURCE_NAME_SUFFIX` storage bucket will be replaced due to a lack of Terraform import support ## Apply the Terraform Changes Execute the following to apply the Terraform plan. ```sh terraform apply ``` ## Client VM Endpoint It is possible that the *forseti_conf_client.yaml* did not get updated with the right **server_ip** address. This is a known issue and is being investigated. Please perform the following steps. 1. Update the **server_ip** in your `forseti-client-RESOURCE_NAME_SUFFIX/configs/forseti_config_client.yaml` file if necessary. 2. Reset your client VM. ## Upgrade Complete <walkthrough-conclusion-trophy></walkthrough-conclusion-trophy> You have completed upgrading Forseti to 2.23 with the re-architected terraform-google-forseti Terraform module!
{ "pile_set_name": "Github" }
package main
{ "pile_set_name": "Github" }
/* * R : A Computer Language for Statistical Data Analysis * Copyright (C) 2000-2016 The R Core Team. * Copyright (C) 2008-2014 Andrew R. Runnalls. * Copyright (C) 2014 and onwards the Rho Project Authors. * * Rho is not part of the R project, and bugs and other issues should * not be reported via r-bugs or other R project channels; instead refer * to the Rho website. * * 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, a copy is available at * https://www.R-project.org/Licenses/ */ /* <UTF8> the only interpretation of char is ASCII */ #ifdef HAVE_CONFIG_H #include <config.h> #endif #include <Defn.h> #include <Fileio.h> #include <Rconnections.h> #include <R_ext/R-ftp-http.h> #include <errno.h> #include <cstdarg> using namespace std; static void *in_R_HTTPOpen(const char *url, const char *headers, const int cacheOK); static int in_R_HTTPRead(void *ctx, char *dest, int len); static void in_R_HTTPClose(void *ctx); static void *in_R_FTPOpen(const char *url); static int in_R_FTPRead(void *ctx, char *dest, int len); static void in_R_FTPClose(void *ctx); extern "C" { SEXP in_do_curlVersion(SEXP call, SEXP op, SEXP args, SEXP rho); SEXP in_do_curlGetHeaders(SEXP call, SEXP op, SEXP args, SEXP rho); SEXP in_do_curlDownload(SEXP call, SEXP op, SEXP args, SEXP rho); Rconnection in_newCurlUrl(const char *description, const char * const mode, int type); #ifdef Win32 static void *in_R_HTTPOpen2(const char *url, const char *headers, const int cacheOK); static int in_R_HTTPRead2(void *ctx, char *dest, int len); static void in_R_HTTPClose2(void *ctx); static void *in_R_FTPOpen2(const char *url); #define Ri_HTTPOpen(url, headers, cacheOK) \ (meth ? in_R_HTTPOpen2(url, headers, cacheOK) : \ in_R_HTTPOpen(url, headers, cacheOK)); #define Ri_HTTPRead(ctx, dest, len) \ (meth ? in_R_HTTPRead2(ctx, dest, len) : in_R_HTTPRead(ctx, dest, len)) #define Ri_HTTPClose(ctx) \ if(meth) in_R_HTTPClose2(ctx); else in_R_HTTPClose(ctx); #define Ri_FTPOpen(url) \ (meth ? in_R_FTPOpen2(url) : in_R_FTPOpen(url)); #define Ri_FTPRead(ctx, dest, len) \ (meth ? in_R_HTTPRead2(ctx, dest, len) : in_R_FTPRead(ctx, dest, len)) #define Ri_FTPClose(ctx) \ if(meth) in_R_HTTPClose2(ctx); else in_R_FTPClose(ctx); #else #define Ri_HTTPOpen in_R_HTTPOpen #define Ri_HTTPRead in_R_HTTPRead #define Ri_HTTPClose in_R_HTTPClose #define Ri_FTPOpen in_R_FTPOpen #define Ri_FTPRead in_R_FTPRead #define Ri_FTPClose in_R_FTPClose #endif } #include <Rmodules/Rinternet.h> #ifdef HAVE_UNISTD_H # include <unistd.h> #endif #ifdef HAVE_FCNTL_H # include <fcntl.h> /* Solaris and AIX define open as open64 under some circumstances */ # undef open #endif /* ------------------- internet access functions --------------------- */ static Rboolean IDquiet = TRUE; static Rboolean url_open(Rconnection con) { void *ctxt; char *url = con->description; UrlScheme type = ((Rurlconn)(con->connprivate))->type; if(con->mode[0] != 'r') { REprintf("can only open URLs for reading"); return FALSE; } switch(type) { #ifdef Win32 case HTTPSsh: warning(_("for https:// URLs use method = \"wininet\"")); return FALSE; #endif case HTTPsh: { SEXP sheaders, agentFun; const char *headers; SEXP s_makeUserAgent = install("makeUserAgent"); agentFun = PROTECT(lang1(s_makeUserAgent)); // defaults to ,TRUE SEXP utilsNS = PROTECT(R_FindNamespace(mkString("utils"))); sheaders = eval(agentFun, utilsNS); UNPROTECT(1); /* utilsNS */ PROTECT(sheaders); if(TYPEOF(sheaders) == NILSXP) headers = NULL; else headers = CHAR(STRING_ELT(sheaders, 0)); ctxt = in_R_HTTPOpen(url, headers, 0); UNPROTECT(2); if(ctxt == NULL) { /* if we call error() we get a connection leak*/ /* so do_url has to raise the error*/ /* error("cannot open URL '%s'", url); */ return FALSE; } ((Rurlconn)(con->connprivate))->ctxt = ctxt; } break; case FTPsh: ctxt = in_R_FTPOpen(url); if(ctxt == NULL) { /* if we call error() we get a connection leak*/ /* so do_url has to raise the error*/ /* error("cannot open URL '%s'", url); */ return FALSE; } ((Rurlconn)(con->connprivate))->ctxt = ctxt; break; default: warning(_("scheme not supported in URL '%s'"), url); return FALSE; } con->isopen = TRUE; con->canwrite = (RHOCONSTRUCT(Rboolean, con->mode[0] == 'w' || con->mode[0] == 'a')); con->canread = RHOCONSTRUCT(Rboolean, !con->canwrite); if(strlen(con->mode) >= 2 && con->mode[1] == 'b') con->text = FALSE; else con->text = TRUE; con->save = -1000; set_iconv(con); return TRUE; } static void url_close(Rconnection con) { UrlScheme type = ((Rurlconn)(con->connprivate))->type; switch(type) { case HTTPsh: case HTTPSsh: in_R_HTTPClose(((Rurlconn)(con->connprivate))->ctxt); break; case FTPsh: in_R_FTPClose(((Rurlconn)(con->connprivate))->ctxt); break; default: break; } con->isopen = FALSE; } static int url_fgetc_internal(Rconnection con) { UrlScheme type = ((Rurlconn)(con->connprivate))->type; void * ctxt = ((Rurlconn)(con->connprivate))->ctxt; unsigned char c; size_t n = 0; /* -Wall */ switch(type) { case HTTPsh: case HTTPSsh: n = in_R_HTTPRead(ctxt, (char *)&c, 1); break; case FTPsh: n = in_R_FTPRead(ctxt, (char *)&c, 1); break; default: break; } return (n == 1) ? c : R_EOF; } static size_t url_read(void *ptr, size_t size, size_t nitems, Rconnection con) { UrlScheme type = ((Rurlconn)(con->connprivate))->type; void * ctxt = ((Rurlconn)(con->connprivate))->ctxt; size_t n = 0; /* -Wall */ switch(type) { case HTTPsh: case HTTPSsh: n = in_R_HTTPRead(ctxt, RHO_S_CAST(char*, ptr), size*nitems); break; case FTPsh: n = in_R_FTPRead(ctxt, RHO_S_CAST(char*, ptr), size*nitems); break; default: break; } return n/size; } #ifdef Win32 static Rboolean url_open2(Rconnection con) { void *ctxt; char *url = con->description; UrlScheme type = ((Rurlconn)(con->private))->type; if(con->mode[0] != 'r') { REprintf("can only open URLs for reading"); return FALSE; } switch(type) { case HTTPSsh: case HTTPsh: { SEXP sheaders, agentFun; const char *headers; SEXP s_makeUserAgent = install("makeUserAgent"); agentFun = PROTECT(lang2(s_makeUserAgent, ScalarLogical(0))); sheaders = PROTECT(eval(agentFun, R_FindNamespace(mkString("utils")))); if(TYPEOF(sheaders) == NILSXP) headers = NULL; else headers = CHAR(STRING_ELT(sheaders, 0)); ctxt = in_R_HTTPOpen2(url, headers, 0); UNPROTECT(2); if(ctxt == NULL) { /* if we call error() we get a connection leak*/ /* so do_url has to raise the error*/ /* error("cannot open URL '%s'", url); */ return FALSE; } ((Rurlconn)(con->private))->ctxt = ctxt; } break; case FTPsh: ctxt = in_R_FTPOpen2(url); if(ctxt == NULL) { /* if we call error() we get a connection leak*/ /* so do_url has to raise the error*/ /* error("cannot open URL '%s'", url); */ return FALSE; } ((Rurlconn)(con->private))->ctxt = ctxt; break; default: warning(_("scheme not supported in URL '%s'"), url); return FALSE; } con->isopen = TRUE; con->canwrite = (con->mode[0] == 'w' || con->mode[0] == 'a'); con->canread = !con->canwrite; if(strlen(con->mode) >= 2 && con->mode[1] == 'b') con->text = FALSE; else con->text = TRUE; con->save = -1000; set_iconv(con); return TRUE; } static void url_close2(Rconnection con) { UrlScheme type = ((Rurlconn)(con->private))->type; switch(type) { case HTTPsh: case HTTPSsh: case FTPsh: in_R_HTTPClose2(((Rurlconn)(con->private))->ctxt); break; default: break; } con->isopen = FALSE; } static int url_fgetc_internal2(Rconnection con) { UrlScheme type = ((Rurlconn)(con->private))->type; void * ctxt = ((Rurlconn)(con->private))->ctxt; unsigned char c; size_t n = 0; /* -Wall */ switch(type) { case HTTPsh: case HTTPSsh: case FTPsh: n = in_R_HTTPRead2(ctxt, (char *)&c, 1); break; default: break; } return (n == 1) ? c : R_EOF; } static size_t url_read2(void *ptr, size_t size, size_t nitems, Rconnection con) { UrlScheme type = ((Rurlconn)(con->private))->type; void * ctxt = ((Rurlconn)(con->private))->ctxt; size_t n = 0; /* -Wall */ switch(type) { case HTTPsh: case HTTPSsh: case FTPsh: n = in_R_HTTPRead2(ctxt, ptr, (int)(size*nitems)); break; default: break; } return n/size; } #endif static Rconnection in_R_newurl(const char *description, const char * const mode, int type) { Rconnection newconn; newconn = (Rconnection) malloc(sizeof(struct Rconn)); if(!newconn) error(_("allocation of url connection failed")); newconn->connclass = (char *) malloc(strlen("url-wininet") + 1); if(!newconn->connclass) { free(newconn); error(_("allocation of url connection failed")); } newconn->description = (char *) malloc(strlen(description) + 1); if(!newconn->description) { free(newconn->connclass); free(newconn); error(_("allocation of url connection failed")); } init_con(newconn, description, CE_NATIVE, mode); newconn->canwrite = FALSE; #ifdef Win32 if (type) { newconn->open = &url_open2; newconn->read = &url_read2; newconn->close = &url_close2; newconn->fgetc_internal = &url_fgetc_internal2; strcpy(newconn->connclass, "url-wininet"); } else #endif { newconn->open = &url_open; newconn->read = &url_read; newconn->close = &url_close; newconn->fgetc_internal = &url_fgetc_internal; strcpy(newconn->connclass, "url"); } newconn->fgetc = &dummy_fgetc; newconn->connprivate = (void *) malloc(sizeof(struct urlconn)); if(!newconn->connprivate) { free(newconn->description); free(newconn->connclass); free(newconn); error(_("allocation of url connection failed")); } IDquiet = TRUE; return newconn; } static void putdots(DLsize_t *pold, DLsize_t newi) { DLsize_t i, old = *pold; *pold = newi; for(i = old; i < newi; i++) { REprintf("."); if((i+1) % 50 == 0) REprintf("\n"); else if((i+1) % 10 == 0) REprintf(" "); } if(R_Consolefile) fflush(R_Consolefile); } static void putdashes(int *pold, int newi) { int i, old = *pold; *pold = newi; for(i = old; i < newi; i++) REprintf("="); if(R_Consolefile) fflush(R_Consolefile); } /* note, ALL the possible structures have the first two elements */ typedef struct { DLsize_t length; char *type; void *ctxt; } inetconn; #ifdef Win32 #include <ga.h> typedef struct { window wprog; progressbar pb; label l_url; Context cntxt; int pc; } winprogressbar; static winprogressbar pbar = {NULL, NULL, NULL}; static void doneprogressbar(void *data) { winprogressbar *pbar = data; hide(pbar->wprog); } #endif /* download(url, destfile, quiet, mode, headers, cacheOK) */ #define CPBUFSIZE 65536 #define IBUFSIZE 4096 static SEXP in_do_download(SEXP args) { SEXP scmd, sfile, smode; const char *url, *file, *mode; int quiet, status = 0, cacheOK; #ifdef Win32 char pbuf[30]; int pc; #endif scmd = CAR(args); args = CDR(args); if(!isString(scmd) || Rf_length(scmd) < 1) error(_("invalid '%s' argument"), "url"); if(Rf_length(scmd) > 1) warning(_("only first element of 'url' argument used")); url = CHAR(STRING_ELT(scmd, 0)); sfile = CAR(args); args = CDR(args); if(!isString(sfile) || Rf_length(sfile) < 1) error(_("invalid '%s' argument"), "destfile"); if(Rf_length(sfile) > 1) warning(_("only first element of 'destfile' argument used")); file = translateChar(STRING_ELT(sfile, 0)); quiet = IDquiet = RHOCONSTRUCT(Rboolean, asLogical(CAR(args))); args = CDR(args); if(quiet == NA_LOGICAL) error(_("invalid '%s' argument"), "quiet"); smode = CAR(args); args = CDR(args); if(!isString(smode) || Rf_length(smode) != 1) error(_("invalid '%s' argument"), "mode"); mode = CHAR(STRING_ELT(smode, 0)); cacheOK = asLogical(CAR(args)); if(cacheOK == NA_LOGICAL) error(_("invalid '%s' argument"), "cacheOK"); bool file_URL = (strncmp(url, "file://", 7) == 0); #ifdef Win32 int meth = asLogical(CADR(args)); if(meth == NA_LOGICAL) error(_("invalid '%s' argument"), "method"); // if(meth == 0) meth = UseInternet2; if (!file_URL && R_Interactive && !quiet && !pbar.wprog) { pbar.wprog = newwindow(_("Download progress"), rect(0, 0, 540, 100), Titlebar | Centered); setbackground(pbar.wprog, dialog_bg()); pbar.l_url = newlabel(" ", rect(10, 15, 520, 25), AlignCenter); pbar.pb = newprogressbar(rect(20, 50, 500, 20), 0, 1024, 1024, 1); pbar.pc = 0; } #endif if(file_URL) { FILE *in, *out; static char buf[CPBUFSIZE]; size_t n; int nh = 7; #ifdef Win32 /* on Windows we have file:///d:/path/to whereas on Unix it is file:///path/to */ if (strlen(url) > 9 && url[7] == '/' && url[9] == ':') nh = 8; #endif /* Use binary transfers? */ in = R_fopen(R_ExpandFileName(url+nh), (mode[2] == 'b') ? "rb" : "r"); if(!in) { error(_("cannot open URL '%s', reason '%s'"), url, strerror(errno)); } out = R_fopen(R_ExpandFileName(file), mode); if(!out) { fclose(in); error(_("cannot open destfile '%s', reason '%s'"), file, strerror(errno)); } while((n = fread(buf, 1, CPBUFSIZE, in)) > 0) { size_t res = fwrite(buf, 1, n, out); if(res != n) error(_("write failed")); } fclose(out); fclose(in); } else if (strncmp(url, "http://", 7) == 0 #ifdef Win32 || ((strncmp(url, "https://", 8) == 0) && meth) #endif ) { FILE *out; void *ctxt; DLsize_t len, total, guess, nbytes = 0; char buf[IBUFSIZE]; int ndashes = 0; DLsize_t ndots = 0; #ifdef Win32 int factor = 1; #endif out = R_fopen(R_ExpandFileName(file), mode); if(!out) { error(_("cannot open destfile '%s', reason '%s'"), file, strerror(errno)); } R_Busy(1); if(!quiet) REprintf(_("trying URL '%s'\n"), url); SEXP agentFun, sheaders; #ifdef Win32 R_FlushConsole(); if(meth) agentFun = PROTECT(lang2(install("makeUserAgent"), ScalarLogical(0))); else agentFun = PROTECT(lang1(install("makeUserAgent"))); #else agentFun = PROTECT(lang1(install("makeUserAgent"))); #endif SEXP utilsNS = PROTECT(R_FindNamespace(mkString("utils"))); sheaders = eval(agentFun, utilsNS); UNPROTECT(1); /* utilsNS */ PROTECT(sheaders); const char *headers = (TYPEOF(sheaders) == NILSXP) ? NULL : CHAR(STRING_ELT(sheaders, 0)); ctxt = Ri_HTTPOpen(url, headers, cacheOK); UNPROTECT(2); if(ctxt == NULL) status = 1; else { // if(!quiet) REprintf(_("opened URL\n"), url); guess = total = ((inetconn *)ctxt)->length; #ifdef Win32 if(R_Interactive) { if (guess <= 0) guess = 100 * 1024; if (guess > 1e9) factor = guess/1e6; R_FlushConsole(); strcpy(buf, "URL: "); if(strlen(url) > 60) { strcat(buf, "... "); strcat(buf, url + (strlen(url) - 60)); } else strcat(buf, url); if(!quiet) { settext(pbar.l_url, buf); setprogressbarrange(pbar.pb, 0, guess/factor); setprogressbar(pbar.pb, 0); settext(pbar.wprog, "Download progress"); show(pbar.wprog); begincontext(&(pbar.cntxt), Content::CCODE, R_NilValue, R_NilValue, R_NilValue, R_NilValue, R_NilValue); pbar.cntxt.cend = &doneprogressbar; pbar.cntxt.cenddata = &pbar; pbar.pc = 0; } } #endif while ((len = Ri_HTTPRead(ctxt, buf, sizeof(buf))) > 0) { size_t res = fwrite(buf, 1, len, out); if(RHOCONSTRUCT(int, res) != len) error(_("write failed")); nbytes += len; if(!quiet) { #ifdef Win32 if(R_Interactive) { if(nbytes > guess) { guess *= 2; if (guess > 1e9) factor = guess/1e6; setprogressbarrange(pbar.pb, 0, guess/factor); } setprogressbar(pbar.pb, nbytes/factor); if (total > 0) { pc = 0.499 + 100.0*nbytes/total; if (pc > pbar.pc) { snprintf(pbuf, 30, "%d%% downloaded", pc); settext(pbar.wprog, pbuf); pbar.pc = pc; } } } else #endif { if(guess <= 0) putdots(&ndots, nbytes/1024); else putdashes(&ndashes, (int)(50*nbytes/guess)); } } } Ri_HTTPClose(ctxt); if(!quiet) { #ifdef Win32 if(!R_Interactive) REprintf("\n"); #else REprintf("\n"); #endif if(nbytes > 1024*1024) REprintf("downloaded %0.1f MB\n\n", (double)nbytes/1024/1024); else if(nbytes > 10240) REprintf("downloaded %d KB\n\n", (int) nbytes/1024); else REprintf("downloaded %d bytes\n\n", (int) nbytes); } #ifdef Win32 R_FlushConsole(); if(R_Interactive && !quiet) { endcontext(&(pbar.cntxt)); doneprogressbar(&pbar); } #endif if (total > 0 && total != nbytes) warning(_("downloaded length %0.f != reported length %0.f"), (double)nbytes, (double)total); } fclose(out); R_Busy(0); if (status == 1) error(_("cannot open URL '%s'"), url); } else if (strncmp(url, "ftp://", 6) == 0) { FILE *out; void *ctxt; DLsize_t len, total, guess, nbytes = 0; char buf[IBUFSIZE]; int ndashes = 0; DLsize_t ndots = 0; #ifdef Win32 int factor = 1; #endif out = R_fopen(R_ExpandFileName(file), mode); if(!out) { error(_("cannot open destfile '%s', reason '%s'"), file, strerror(errno)); } R_Busy(1); if(!quiet) REprintf(_("trying URL '%s'\n"), url); #ifdef Win32 R_FlushConsole(); #endif ctxt = Ri_FTPOpen(url); if(ctxt == NULL) status = 1; else { // if(!quiet) REprintf(_("opened URL\n"), url); guess = total = ((inetconn *)ctxt)->length; #ifdef Win32 if(R_Interactive && !quiet) { if (guess <= 0) guess = 100 * 1024; if (guess > 1e9) factor = guess/1e6; R_FlushConsole(); strcpy(buf, "URL: "); if(strlen(url) > 60) { strcat(buf, "... "); strcat(buf, url + (strlen(url) - 60)); } else strcat(buf, url); settext(pbar.l_url, buf); setprogressbarrange(pbar.pb, 0, guess/factor); setprogressbar(pbar.pb, 0); settext(pbar.wprog, "Download progress"); show(pbar.wprog); /* set up a context which will close progressbar on error. */ begincontext(&(pbar.cntxt), Context::CCODE, R_NilValue, R_NilValue, R_NilValue, R_NilValue, R_NilValue); pbar.cntxt.cend = &doneprogressbar; pbar.cntxt.cenddata = &pbar; pbar.pc = 0; } #endif while ((len = Ri_FTPRead(ctxt, buf, sizeof(buf))) > 0) { size_t res = fwrite(buf, 1, len, out); if(RHOCONSTRUCT(int, res) != len) error(_("write failed")); nbytes += len; if(!quiet) { #ifdef Win32 if(R_Interactive) { if(nbytes > guess) { guess *= 2; if (guess > 1e9) factor = guess/1e6; setprogressbarrange(pbar.pb, 0, guess/factor); } setprogressbar(pbar.pb, nbytes/factor); if (total > 0) { pc = 0.499 + 100.0*nbytes/total; if (pc > pbar.pc) { snprintf(pbuf, 30, "%d%% downloaded", pc); settext(pbar.wprog, pbuf); pbar.pc = pc; } } } else #endif { if(guess <= 0) putdots(&ndots, nbytes/1024); else putdashes(&ndashes, (int)(50*nbytes/guess)); } } } Ri_FTPClose(ctxt); if(!quiet) { #ifdef Win32 if(!R_Interactive) REprintf("\n"); #else REprintf("\n"); #endif if(nbytes > 1024*1024) REprintf("downloaded %0.1f MB\n\n", (double)nbytes/1024/1024); else if(nbytes > 10240) REprintf("downloaded %d KB\n\n", (int) nbytes/1024); else REprintf("downloaded %d bytes\n\n", (int) nbytes); } #ifdef Win32 R_FlushConsole(); if(R_Interactive && !quiet) { endcontext(&(pbar.cntxt)); doneprogressbar(&pbar); } #endif if (total > 0 && total != nbytes) warning(_("downloaded length %0.f != reported length %0.f"), (double)nbytes, (double)total); } R_Busy(0); fclose(out); if (status == 1) error(_("cannot open URL '%s'"), url); } else error(_("scheme not supported in URL '%s'"), url); return ScalarInteger(status); } void *in_R_HTTPOpen(const char *url, const char *headers, const int cacheOK) { inetconn *con; void *ctxt; int timeout = asInteger(GetOption1(install("timeout"))); DLsize_t len = -1; char *type = NULL; if(timeout == NA_INTEGER || timeout <= 0) timeout = 60; RxmlNanoHTTPTimeout(timeout); ctxt = RxmlNanoHTTPOpen(url, NULL, headers, cacheOK); if(ctxt != NULL) { int rc = RxmlNanoHTTPReturnCode(ctxt); if(rc != 200) { warning(_("cannot open URL '%s': HTTP status was '%d %s'"), url, rc, RxmlNanoHTTPStatusMsg(ctxt)); RxmlNanoHTTPClose(ctxt); return NULL; } else { type = RxmlNanoHTTPContentType(ctxt); len = RxmlNanoHTTPContentLength(ctxt); if(!IDquiet){ REprintf("Content type '%s'", type ? type : "unknown"); if(len > 1024*1024) // might be longer than long, and is on 64-bit windows REprintf(" length %0.0f bytes (%0.1f MB)\n", (double)len, len/1024.0/1024.0); else if(len > 10240) REprintf(" length %d bytes (%d KB)\n", (int)len, (int)(len/1024)); else if(len >= 0) REprintf(" length %d bytes\n", (int)len); else REprintf(" length unknown\n", len); #ifdef Win32 R_FlushConsole(); #endif } } } else return NULL; con = (inetconn *) malloc(sizeof(inetconn)); if(con) { con->length = len; con->type = type; con->ctxt = ctxt; } return con; } static int in_R_HTTPRead(void *ctx, char *dest, int len) { return RxmlNanoHTTPRead(((inetconn *)ctx)->ctxt, dest, len); } static void in_R_HTTPClose(void *ctx) { if(ctx) { RxmlNanoHTTPClose(((inetconn *)ctx)->ctxt); free(ctx); } } static void *in_R_FTPOpen(const char *url) { inetconn *con; void *ctxt; int timeout = asInteger(GetOption1(install("timeout"))); DLsize_t len = 0; if(timeout == NA_INTEGER || timeout <= 0) timeout = 60; RxmlNanoFTPTimeout(timeout); ctxt = RxmlNanoFTPOpen(url); if(!ctxt) return NULL; if(!IDquiet) { len = RxmlNanoFTPContentLength(ctxt); if(len >= 0) REprintf("ftp data connection made, file length %ld bytes\n", len); else REprintf("ftp data connection made, file length unknown\n"); #ifdef Win32 R_FlushConsole(); #endif } con = (inetconn *) malloc(sizeof(inetconn)); if(con) { con->length = len; con->type = NULL; con->ctxt = ctxt; } return con; } static int in_R_FTPRead(void *ctx, char *dest, int len) { return RxmlNanoFTPRead(((inetconn *)ctx)->ctxt, dest, len); } static void in_R_FTPClose(void *ctx) { if(ctx) { RxmlNanoFTPClose(((inetconn *)ctx)->ctxt); free(ctx); } } #ifdef Win32 #define WIN32_LEAN_AND_MEAN 1 #include <windows.h> #include <wininet.h> typedef struct wictxt { DLsize_t length; char * type; HINTERNET hand; HINTERNET session; } wIctxt, *WIctxt; static void *in_R_HTTPOpen2(const char *url, const char *headers, const int cacheOK) { WIctxt wictxt; DWORD status, d1 = 4, d2 = 0, d3 = 100; char buf[101], *p; wictxt = (WIctxt) malloc(sizeof(wIctxt)); wictxt->length = -1; wictxt->type = NULL; wictxt->hand = InternetOpen(headers, INTERNET_OPEN_TYPE_PRECONFIG, NULL, NULL, 0); if(!wictxt->hand) { free(wictxt); /* error("cannot open Internet connection"); */ return NULL; } // use keep-alive semantics, do not use local WinINet cache. DWORD flags = INTERNET_FLAG_KEEP_CONNECTION | INTERNET_FLAG_NO_CACHE_WRITE; if(!cacheOK) flags |= INTERNET_FLAG_PRAGMA_NOCACHE; wictxt->session = InternetOpenUrl(wictxt->hand, url, NULL, 0, flags, 0); if(!wictxt->session) { DWORD err1 = GetLastError(), err2, blen = 101; InternetCloseHandle(wictxt->hand); free(wictxt); if (err1 == ERROR_INTERNET_EXTENDED_ERROR) { InternetGetLastResponseInfo(&err2, buf, &blen); /* some of these messages end in \r\n */ while(1) { p = buf + strlen(buf) - 1; if(*p == '\n' || *p == '\r') *p = '\0'; else break; } warning(_("InternetOpenUrl failed: '%s'"), buf); return NULL; } else { FormatMessage( FORMAT_MESSAGE_FROM_HMODULE, GetModuleHandle("wininet.dll"), err1, MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), buf, 101, NULL); /* some of these messages end in \r\n */ while(1) { p = buf + strlen(buf) - 1; if(*p == '\n' || *p == '\r') *p = '\0'; else break; } warning(_("InternetOpenUrl failed: '%s'"), buf); return NULL; } } HttpQueryInfo(wictxt->session, HTTP_QUERY_STATUS_CODE | HTTP_QUERY_FLAG_NUMBER, &status, &d1, &d2); if(status != 200) { d2 = 0; HttpQueryInfo(wictxt->session, HTTP_QUERY_STATUS_TEXT, &buf, &d3, &d2); InternetCloseHandle(wictxt->session); InternetCloseHandle(wictxt->hand); free(wictxt); warning(_("cannot open URL '%s': HTTP status was '%d %s'"), url, status, buf); return NULL; } HttpQueryInfo(wictxt->session, HTTP_QUERY_CONTENT_TYPE, &buf, &d3, &d2); d2 = 0; // NB: this can only retrieve in a DWORD, so up to 2GB or 4GB? HttpQueryInfo(wictxt->session, HTTP_QUERY_CONTENT_LENGTH | HTTP_QUERY_FLAG_NUMBER, &status, &d1, &d2); wictxt->length = status; wictxt->type = strdup(buf); if(!IDquiet) { if(status > 1024*1024) REprintf("Content type '%s' length %0.0f bytes (%0.1f MB)\n", buf, (double) status, status/1024.0/1024.0); else if(status > 10240) REprintf("Content type '%s' length %d bytes (%d KB)\n", buf, (int) status, (int) (status/1024)); else REprintf("Content type '%s' length %d bytes\n", buf, (int) status); R_FlushConsole(); } R_ProcessEvents(); return (void *)wictxt; } static int in_R_HTTPRead2(void *ctx, char *dest, int len) { DWORD nread; InternetReadFile(((WIctxt)ctx)->session, dest, len, &nread); R_ProcessEvents(); return (int) nread; } static void in_R_HTTPClose2(void *ctx) { InternetCloseHandle(((WIctxt)ctx)->session); InternetCloseHandle(((WIctxt)ctx)->hand); if(((WIctxt)ctx)->type) free(((WIctxt)ctx)->type); free(ctx); } static void *in_R_FTPOpen2(const char *url) { WIctxt wictxt; wictxt = (WIctxt) malloc(sizeof(wIctxt)); wictxt->length = -1; wictxt->type = NULL; wictxt->hand = InternetOpen("R", INTERNET_OPEN_TYPE_PRECONFIG, NULL, NULL, 0); if(!wictxt->hand) { free(wictxt); return NULL; } DWORD flag = INTERNET_FLAG_KEEP_CONNECTION | INTERNET_FLAG_NO_CACHE_WRITE; wictxt->session = InternetOpenUrl(wictxt->hand, url, NULL, 0, flag | INTERNET_FLAG_PASSIVE, 0); if(!wictxt->session) wictxt->session = InternetOpenUrl(wictxt->hand, url, NULL, 0, flag, 0); if(!wictxt->session) { char buf[256]; DWORD err1 = GetLastError(), err2, blen = 256; InternetCloseHandle(wictxt->hand); free(wictxt); if (err1 == ERROR_INTERNET_EXTENDED_ERROR) { InternetGetLastResponseInfo(&err2, buf, &blen); warning(_("InternetOpenUrl failed: '%s'"), buf); return NULL; } else { FormatMessage( FORMAT_MESSAGE_FROM_HMODULE, GetModuleHandle("wininet.dll"), err1, MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), buf, 101, NULL); warning(_("InternetOpenUrl failed: '%s'"), buf); return NULL; } } R_ProcessEvents(); return (void *)wictxt; } #endif // Win32 #define MBUFSIZE 8192 void RxmlMessage(int level, const char *format, ...) { int clevel; char buf[MBUFSIZE], *p; va_list(ap); clevel = asInteger(GetOption1(install("internet.info"))); if(clevel == NA_INTEGER) clevel = 2; if(level < clevel) return; va_start(ap, format); vsnprintf(buf, MBUFSIZE, format, ap); buf[MBUFSIZE-1] = '\0'; va_end(ap); p = buf + strlen(buf) - 1; if(strlen(buf) > 0 && *p == '\n') *p = '\0'; warning(buf); } #include "sock.h" #define STRICT_R_HEADERS #include <R_ext/RS.h> /* for R_Calloc */ #include <R_ext/Rdynload.h> extern "C" { void #ifdef USE_WININET R_init_internet2(DllInfo *info); #else R_init_internet(DllInfo *info); #endif } void #ifdef HAVE_VISIBILITY_ATTRIBUTE __attribute__ ((visibility ("default"))) #endif R_init_internet(DllInfo *info) { R_InternetRoutines *tmp; tmp = R_Calloc(1, R_InternetRoutines); tmp->download = in_do_download; tmp->newurl = in_R_newurl; tmp->newsock = in_R_newsock; tmp->HTTPOpen = in_R_HTTPOpen; tmp->HTTPRead = in_R_HTTPRead; tmp->HTTPClose = in_R_HTTPClose; tmp->FTPOpen = in_R_FTPOpen; tmp->FTPRead = in_R_FTPRead; tmp->FTPClose = in_R_FTPClose; tmp->sockopen = in_Rsockopen; tmp->socklisten = in_Rsocklisten; tmp->sockconnect = in_Rsockconnect; tmp->sockclose = in_Rsockclose; tmp->sockread = in_Rsockread; tmp->sockwrite = in_Rsockwrite; tmp->sockselect = in_Rsockselect; tmp->HTTPDCreate = in_R_HTTPDCreate; tmp->HTTPDStop = in_R_HTTPDStop; tmp->curlVersion = in_do_curlVersion; tmp->curlGetHeaders = in_do_curlGetHeaders; tmp->curlDownload = in_do_curlDownload; tmp->newcurlurl = in_newCurlUrl; R_setInternetRoutines(tmp); }
{ "pile_set_name": "Github" }
from Foundation import * from PyObjCTools.TestSupport import * class TestNSURLRequest (TestCase): def testConstants(self): self.assertEqual(NSURLRequestUseProtocolCachePolicy, 0) self.assertEqual(NSURLRequestReloadIgnoringLocalCacheData, 1) self.assertEqual(NSURLRequestReloadIgnoringLocalAndRemoteCacheData, 4) self.assertEqual(NSURLRequestReloadIgnoringCacheData, NSURLRequestReloadIgnoringLocalCacheData) self.assertEqual(NSURLRequestReturnCacheDataElseLoad, 2) self.assertEqual(NSURLRequestReturnCacheDataDontLoad, 3) self.assertEqual(NSURLRequestReloadRevalidatingCacheData, 5) self.assertEqual(NSURLNetworkServiceTypeDefault, 0) self.assertEqual(NSURLNetworkServiceTypeVoIP, 1) self.assertEqual(NSURLNetworkServiceTypeVideo, 2) self.assertEqual(NSURLNetworkServiceTypeBackground, 3) self.assertEqual(NSURLNetworkServiceTypeVoice, 4) def testMethods(self): self.assertResultIsBOOL(NSURLRequest.HTTPShouldHandleCookies) self.assertArgIsBOOL(NSMutableURLRequest.setHTTPShouldHandleCookies_, 0) @min_os_level('10.7') def testMethods10_7(self): self.assertResultIsBOOL(NSURLRequest.HTTPShouldUsePipelining) self.assertArgIsBOOL(NSMutableURLRequest.setHTTPShouldUsePipelining_, 0) @min_os_level('10.8') def testMethods10_8(self): self.assertResultIsBOOL(NSURLRequest.allowsCellularAccess) #self.assertArgIsBOOL(NSURLRequest.setAllowsCellularAccess_, 0) if __name__ == "__main__": main()
{ "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 arq.examples.riot; import org.apache.jena.graph.Triple ; import org.apache.jena.riot.RDFParser ; import org.apache.jena.riot.lang.CollectorStreamBase; import org.apache.jena.riot.lang.CollectorStreamTriples; /** * Example of using RIOT for streaming RDF to be stored into a Collection. * * Suitable for single-threaded parsing, for use with small data or distributed * computing frameworks (e.g. Hadoop) where the overhead of creating many threads * is significant. * * @see CollectorStreamBase */ public class ExRIOT5_StreamRDFCollect { public static void main(String... argv) { final String filename = "data.ttl"; CollectorStreamTriples inputStream = new CollectorStreamTriples(); RDFParser.source(filename).parse(inputStream); for (Triple triple : inputStream.getCollected()) { System.out.println(triple); } } }
{ "pile_set_name": "Github" }
// // Prefix header for all source files of the 'Simplenote' target in the 'Simplenote' project // #ifdef __OBJC__ #import <Cocoa/Cocoa.h> #import <SystemConfiguration/SystemConfiguration.h> #endif
{ "pile_set_name": "Github" }
<feed xmlns="http://www.w3.org/2005/Atom" xml:lang="en"> <title>nLab</title> <link rel="alternate" type="application/xhtml+xml" href="https://ncatlab.org/nlab/show/HomePage"/> <link rel="self" href="https://ncatlab.org/nlab/atom_with_headlines"/> <updated>2017-09-21T16:03:01Z</updated> <id>tag:ncatlab.org,2008-11-28:nLab</id> <subtitle>An Instiki Wiki</subtitle> <generator uri="http://golem.ph.utexas.edu/instiki/show/HomePage" version="0.19.7(MML+)">Instiki</generator> <entry> <title type="html">(0,1)-category</title> <link rel="self" type="application/xhtml+xml" href="https://ncatlab.org/nlab/show/self_link/"/> <link rel="alternate" type="application/xhtml+xml" href="https://ncatlab.org/nlab/show/%280%2C1%29-category"/> <updated>2017-09-21T16:03:01Z</updated> <published>2009-09-08T23:20:59Z</published> <id>tag:ncatlab.org,2009-09-08:nLab,%280%2C1%29-category</id> <author> <name>Mike Shulman</name> </author> <summary type="text">Updated by Mike Shulman on 2017-09-21 at 16:03:01Z.</summary> </entry> </feed>
{ "pile_set_name": "Github" }
type=item items=minecraft:experience_bottle texture=./frail.png nbt.display.Lore.*=ipattern:*Frail*
{ "pile_set_name": "Github" }
<?xml version="1.0"?> <Workbook xmlns="urn:schemas-microsoft-com:office:spreadsheet" xmlns:o="urn:schemas-microsoft-com:office:office" xmlns:x="urn:schemas-microsoft-com:office:excel" xmlns:ss="urn:schemas-microsoft-com:office:spreadsheet" xmlns:html="http://www.w3.org/TR/REC-html40"> <DocumentProperties xmlns="urn:schemas-microsoft-com:office:office"> <Author> </Author> <LastAuthor>God</LastAuthor> <Created>2008-02-17T20:34:32Z</Created> <LastSaved>2013-03-13T16:18:45Z</LastSaved> <Version>14.0</Version> </DocumentProperties> <OfficeDocumentSettings xmlns="urn:schemas-microsoft-com:office:office"> <AllowPNG/> <Colors> <Color> <Index>16</Index> <RGB>#9999FF</RGB> </Color> <Color> <Index>17</Index> <RGB>#993366</RGB> </Color> <Color> <Index>18</Index> <RGB>#FFFFCC</RGB> </Color> <Color> <Index>19</Index> <RGB>#CCFFFF</RGB> </Color> <Color> <Index>20</Index> <RGB>#660066</RGB> </Color> <Color> <Index>21</Index> <RGB>#FF8080</RGB> </Color> <Color> <Index>22</Index> <RGB>#0066CC</RGB> </Color> <Color> <Index>23</Index> <RGB>#CCCCFF</RGB> </Color> <Color> <Index>24</Index> <RGB>#000080</RGB> </Color> <Color> <Index>25</Index> <RGB>#FF00FF</RGB> </Color> <Color> <Index>26</Index> <RGB>#FFFF00</RGB> </Color> <Color> <Index>27</Index> <RGB>#00FFFF</RGB> </Color> <Color> <Index>28</Index> <RGB>#800080</RGB> </Color> <Color> <Index>29</Index> <RGB>#800000</RGB> </Color> <Color> <Index>30</Index> <RGB>#008080</RGB> </Color> <Color> <Index>31</Index> <RGB>#0000FF</RGB> </Color> </Colors> </OfficeDocumentSettings> <ExcelWorkbook xmlns="urn:schemas-microsoft-com:office:excel"> <WindowHeight>12200</WindowHeight> <WindowWidth>22820</WindowWidth> <WindowTopX>100</WindowTopX> <WindowTopY>20</WindowTopY> <TabRatio>600</TabRatio> <ActiveSheet>1</ActiveSheet> <ProtectStructure>False</ProtectStructure> <ProtectWindows>False</ProtectWindows> </ExcelWorkbook> <Styles> <Style ss:ID="Default" ss:Name="Normal"> <Alignment ss:Vertical="Bottom"/> <Borders/> <Font ss:FontName="Calibri" x:Family="Swiss" ss:Size="11" ss:Color="#000000"/> <Interior/> <NumberFormat/> <Protection/> </Style> <Style ss:ID="s63"> <Alignment ss:Vertical="Bottom" ss:WrapText="1"/> </Style> <Style ss:ID="s64"> <Alignment ss:Vertical="Bottom" ss:WrapText="1"/> <NumberFormat/> </Style> <Style ss:ID="s65"> <Font ss:FontName="Calibri" x:Family="Swiss" ss:Size="11" ss:Color="#000000" ss:Bold="1"/> </Style> <Style ss:ID="s66"> <NumberFormat ss:Format="@"/> </Style> </Styles> <Names> <NamedRange ss:Name="numberArea" ss:RefersTo="=Index!R123C10:R125C13"/> <NamedRange ss:Name="oneByOne" ss:RefersTo="=Index!R7C12"/> <NamedRange ss:Name="singleColumn" ss:RefersTo="=Index!R5C11:R9C11"/> <NamedRange ss:Name="singleRow" ss:RefersTo="=Index!R6C10:R6C14"/> <NamedRange ss:Name="threeByThree" ss:RefersTo="=Index!R6C11:R8C13"/> </Names> <Worksheet ss:Name="Read Me"> <Table ss:ExpandedColumnCount="1" ss:ExpandedRowCount="11" x:FullColumns="1" x:FullRows="1" ss:DefaultColumnWidth="53" ss:DefaultRowHeight="14"> <Column ss:Width="651"/> <Row> <Cell><Data ss:Type="String">This spreadsheet contains various test cases for lookup functions: VLOOKUP, HLOOKUP, LOOKUP and MATCH</Data></Cell> </Row> <Row> <Cell><Data ss:Type="String">Name of the main junit test class which uses this spreadsheet:</Data></Cell> </Row> <Row> <Cell><Data ss:Type="String">org.apache.poi.ss.formula.functions.TestIndexFunctionFromSpreadsheet</Data></Cell> </Row> <Row> <Cell><Data ss:Type="String">(The content of cell 'Read Me'!A3 is confirmed by the test)</Data></Cell> </Row> <Row ss:Index="6"> <Cell><Data ss:Type="String">Every sheet besides this first one contains formula evaluation test cases in a standardised format.</Data></Cell> </Row> <Row> <Cell><Data ss:Type="String">On row 4 of each sheet, in columns B,C,D there are the column headings &quot;Formula&quot;, &quot;Expected Result&quot; and &quot;Comment&quot;</Data></Cell> </Row> <Row ss:Height="28"> <Cell ss:StyleID="s63"><Data ss:Type="String">The test iterates down from row 5 onward until a the text &quot;&lt;end&gt;&quot; is found in column A. Rows with &quot;&lt;skip&gt;&quot; in column A are ignored (useful for currently unsupported behaviour). Otherwise column A can be used for commenting the group of rows below. </Data></Cell> </Row> <Row ss:Height="28"> <Cell ss:StyleID="s64"><Data ss:Type="String">If the evaluated result of column B does not match the expected result in column C, the junit test will report a failure. Test failures get annotated with the section and row comments, if any.</Data></Cell> </Row> <Row ss:Height="28"> <Cell ss:StyleID="s63"><Data ss:Type="String">Besides the first 4 columns, row 5 onwards, the junit test does not inspect any other cells in the sheet. The other cells can be used freely to set up test data.</Data></Cell> </Row> <Row ss:Height="28"> <Cell ss:StyleID="s63"><Data ss:Type="String">Care should be taken to not only make the values in column C match those in column B, but also to make sure column C contains only simple literal values. This can be achieved easily by 'pasting special' from column B to C, selecting the 'as values' option.</Data></Cell> </Row> </Table> <WorksheetOptions xmlns="urn:schemas-microsoft-com:office:excel"> <PageSetup> <Header x:Margin="0.3"/> <Footer x:Margin="0.3"/> <PageMargins x:Bottom="0.75" x:Left="0.7" x:Right="0.7" x:Top="0.75"/> </PageSetup> <PageLayoutZoom>0</PageLayoutZoom> <Panes> <Pane> <Number>3</Number> <ActiveRow>3</ActiveRow> </Pane> </Panes> <ProtectObjects>False</ProtectObjects> <ProtectScenarios>False</ProtectScenarios> </WorksheetOptions> </Worksheet> <Worksheet ss:Name="Index"> <Table ss:ExpandedColumnCount="14" ss:ExpandedRowCount="139" x:FullColumns="1" x:FullRows="1" ss:DefaultColumnWidth="53" ss:DefaultRowHeight="14"> <Column ss:Width="39"/> <Column ss:Width="96"/> <Column ss:Width="297"/> <Column ss:Width="58"/> <Column ss:Width="220"/> <Column ss:Width="16"/> <Column ss:AutoFitWidth="0" ss:Width="100"/> <Column ss:Index="9" ss:Width="13"/> <Column ss:Width="24" ss:Span="3"/> <Column ss:Index="14" ss:Width="13"/> <Row> <Cell ss:Index="2" ss:StyleID="s65"><Data ss:Type="String">Sheet Comment:</Data></Cell> <Cell><Data ss:Type="String">Simple tests of INDEX using basic argument values</Data></Cell> </Row> <Row ss:Index="3"> <Cell ss:Index="2" ss:StyleID="s65"><Data ss:Type="String">Formula</Data></Cell> <Cell ss:StyleID="s65"><Data ss:Type="String">Expected Result</Data></Cell> <Cell ss:StyleID="s65"><Data ss:Type="String">Comment</Data></Cell> </Row> <Row> <Cell ss:Index="5" ss:StyleID="s66"><Data ss:Type="String">threeByThree area with both index args</Data></Cell> </Row> <Row> <Cell ss:Index="2" ss:Formula="=INDEX(threeByThree,RC[3],RC[4])"><Data ss:Type="String">g</Data></Cell> <Cell><Data ss:Type="String">g</Data></Cell> <Cell ss:Index="5"><Data ss:Type="Number">1</Data></Cell> <Cell><Data ss:Type="Number">1</Data></Cell> <Cell ss:Index="10"><Data ss:Type="String">a</Data></Cell> <Cell><Data ss:Type="String">b</Data><NamedCell ss:Name="singleColumn"/></Cell> <Cell><Data ss:Type="String">c</Data></Cell> <Cell><Data ss:Type="String">d</Data></Cell> <Cell><Data ss:Type="String">e</Data></Cell> </Row> <Row> <Cell ss:Index="2" ss:Formula="=INDEX(threeByThree,RC[3],RC[4])"><Data ss:Type="String">l</Data></Cell> <Cell><Data ss:Type="String">l</Data></Cell> <Cell ss:Index="5"><Data ss:Type="Number">2</Data></Cell> <Cell><Data ss:Type="Number">1</Data></Cell> <Cell ss:Index="10"><Data ss:Type="String">f</Data><NamedCell ss:Name="singleRow"/></Cell> <Cell><Data ss:Type="String">g</Data><NamedCell ss:Name="singleRow"/><NamedCell ss:Name="threeByThree"/><NamedCell ss:Name="singleColumn"/></Cell> <Cell><Data ss:Type="String">h</Data><NamedCell ss:Name="singleRow"/><NamedCell ss:Name="threeByThree"/></Cell> <Cell><Data ss:Type="String">i</Data><NamedCell ss:Name="singleRow"/><NamedCell ss:Name="threeByThree"/></Cell> <Cell><Data ss:Type="String">j</Data><NamedCell ss:Name="singleRow"/></Cell> </Row> <Row> <Cell ss:Index="2" ss:Formula="=INDEX(threeByThree,RC[3],RC[4])"><Data ss:Type="String">h</Data></Cell> <Cell><Data ss:Type="String">h</Data></Cell> <Cell ss:Index="5"><Data ss:Type="Number">1</Data></Cell> <Cell><Data ss:Type="Number">2</Data></Cell> <Cell ss:Index="10"><Data ss:Type="String">k</Data></Cell> <Cell><Data ss:Type="String">l</Data><NamedCell ss:Name="threeByThree"/><NamedCell ss:Name="singleColumn"/></Cell> <Cell><Data ss:Type="String">m</Data><NamedCell ss:Name="oneByOne"/><NamedCell ss:Name="threeByThree"/></Cell> <Cell><Data ss:Type="String">n</Data><NamedCell ss:Name="threeByThree"/></Cell> <Cell><Data ss:Type="String">o</Data></Cell> </Row> <Row> <Cell ss:Index="2" ss:Formula="=INDEX(threeByThree,RC[3],RC[4])"><Data ss:Type="String">s</Data></Cell> <Cell><Data ss:Type="String">s</Data></Cell> <Cell ss:Index="5"><Data ss:Type="Number">3</Data></Cell> <Cell><Data ss:Type="Number">3</Data></Cell> <Cell ss:Index="10"><Data ss:Type="String">p</Data></Cell> <Cell><Data ss:Type="String">q</Data><NamedCell ss:Name="threeByThree"/><NamedCell ss:Name="singleColumn"/></Cell> <Cell><Data ss:Type="String">r</Data><NamedCell ss:Name="threeByThree"/></Cell> <Cell><Data ss:Type="String">s</Data><NamedCell ss:Name="threeByThree"/></Cell> <Cell><Data ss:Type="String">t</Data></Cell> </Row> <Row> <Cell ss:Index="2" ss:Formula="=INDEX(threeByThree,RC[3],RC[4])"><Data ss:Type="Error">#VALUE!</Data></Cell> <Cell><Data ss:Type="Error">#VALUE!</Data></Cell> <Cell ss:Index="5"><Data ss:Type="Number">0</Data></Cell> <Cell><Data ss:Type="Number">0</Data></Cell> <Cell ss:Index="10"><Data ss:Type="String">u</Data></Cell> <Cell><Data ss:Type="String">v</Data><NamedCell ss:Name="singleColumn"/></Cell> <Cell><Data ss:Type="String">w</Data></Cell> <Cell><Data ss:Type="String">x</Data></Cell> <Cell><Data ss:Type="String">y</Data></Cell> </Row> <Row> <Cell ss:Index="2" ss:Formula="=INDEX(threeByThree,RC[3],RC[4])"><Data ss:Type="Error">#VALUE!</Data></Cell> <Cell><Data ss:Type="Error">#VALUE!</Data></Cell> <Cell ss:Index="5"><Data ss:Type="Number">-1</Data></Cell> <Cell><Data ss:Type="Number">-1</Data></Cell> </Row> <Row> <Cell ss:Index="2" ss:Formula="=INDEX(threeByThree,RC[3],RC[4])"><Data ss:Type="Error">#REF!</Data></Cell> <Cell><Data ss:Type="Error">#REF!</Data></Cell> <Cell ss:Index="5"><Data ss:Type="Number">4</Data></Cell> <Cell><Data ss:Type="Number">1</Data></Cell> </Row> <Row> <Cell ss:Index="2" ss:Formula="=INDEX(threeByThree,RC[3],RC[4])"><Data ss:Type="Error">#VALUE!</Data></Cell> <Cell><Data ss:Type="Error">#VALUE!</Data></Cell> <Cell ss:Index="5"><Data ss:Type="Number">-1</Data></Cell> <Cell><Data ss:Type="Number">0</Data></Cell> </Row> <Row> <Cell ss:Index="2" ss:Formula="=INDEX(threeByThree,RC[3])"><Data ss:Type="Error">#REF!</Data></Cell> <Cell><Data ss:Type="Error">#REF!</Data></Cell> <Cell ss:Index="5"><Data ss:Type="Number">1</Data></Cell> <Cell><Data ss:Type="Number">0</Data></Cell> </Row> <Row ss:Index="16"> <Cell ss:Index="5"><Data ss:Type="String">threeByThree area with one index arg</Data></Cell> </Row> <Row> <Cell ss:Index="2" ss:Formula="=INDEX(threeByThree,RC[3])"><Data ss:Type="Error">#VALUE!</Data></Cell> <Cell><Data ss:Type="Error">#VALUE!</Data></Cell> <Cell ss:Index="5"><Data ss:Type="Number">-1</Data></Cell> </Row> <Row> <Cell ss:Index="2" ss:Formula="=INDEX(threeByThree,RC[3])"><Data ss:Type="Error">#REF!</Data></Cell> <Cell><Data ss:Type="Error">#REF!</Data></Cell> <Cell ss:Index="5"><Data ss:Type="Number">0</Data></Cell> </Row> <Row> <Cell ss:Index="2" ss:Formula="=INDEX(threeByThree,RC[3])"><Data ss:Type="Error">#REF!</Data></Cell> <Cell><Data ss:Type="Error">#REF!</Data></Cell> <Cell ss:Index="5"><Data ss:Type="Number">1</Data></Cell> </Row> <Row> <Cell ss:Index="2" ss:Formula="=INDEX(threeByThree,RC[3])"><Data ss:Type="Error">#REF!</Data></Cell> <Cell><Data ss:Type="Error">#REF!</Data></Cell> <Cell ss:Index="5"><Data ss:Type="Number">3</Data></Cell> </Row> <Row> <Cell ss:Index="2" ss:Formula="=INDEX(threeByThree,RC[3])"><Data ss:Type="Error">#REF!</Data></Cell> <Cell><Data ss:Type="Error">#REF!</Data></Cell> <Cell ss:Index="5"><Data ss:Type="Number">4</Data></Cell> </Row> <Row ss:Index="24"> <Cell ss:Index="5"><Data ss:Type="String">singleRow with one index arg</Data></Cell> </Row> <Row> <Cell ss:Index="2" ss:Formula="=INDEX(singleRow,RC[3])"><Data ss:Type="Error">#VALUE!</Data></Cell> <Cell><Data ss:Type="Error">#VALUE!</Data></Cell> <Cell ss:Index="5"><Data ss:Type="Number">-1</Data></Cell> </Row> <Row> <Cell ss:Index="2" ss:Formula="=INDEX(singleRow,RC[3])"><Data ss:Type="Error">#VALUE!</Data></Cell> <Cell><Data ss:Type="Error">#VALUE!</Data></Cell> <Cell ss:Index="5"><Data ss:Type="Number">0</Data></Cell> </Row> <Row> <Cell ss:Index="2" ss:Formula="=INDEX(singleRow,RC[3])"><Data ss:Type="String">f</Data></Cell> <Cell><Data ss:Type="String">f</Data></Cell> <Cell ss:Index="5"><Data ss:Type="Number">1</Data></Cell> </Row> <Row> <Cell ss:Index="2" ss:Formula="=INDEX(singleRow,RC[3])"><Data ss:Type="String">i</Data></Cell> <Cell><Data ss:Type="String">i</Data></Cell> <Cell ss:Index="5"><Data ss:Type="Number">4</Data></Cell> </Row> <Row> <Cell ss:Index="2" ss:Formula="=INDEX(singleRow,RC[3])"><Data ss:Type="String">j</Data></Cell> <Cell><Data ss:Type="String">j</Data></Cell> <Cell ss:Index="5"><Data ss:Type="Number">5</Data></Cell> </Row> <Row> <Cell ss:Index="2" ss:Formula="=INDEX(singleRow,RC[3])"><Data ss:Type="Error">#REF!</Data></Cell> <Cell><Data ss:Type="Error">#REF!</Data></Cell> <Cell ss:Index="5"><Data ss:Type="Number">6</Data></Cell> </Row> <Row ss:Index="33"> <Cell ss:Index="5"><Data ss:Type="String">singleRow with both index args</Data></Cell> </Row> <Row> <Cell ss:Index="2" ss:Formula="=INDEX(singleRow,RC[3],RC[4])"><Data ss:Type="String">f</Data></Cell> <Cell><Data ss:Type="String">f</Data></Cell> <Cell ss:Index="5"><Data ss:Type="Number">1</Data></Cell> <Cell><Data ss:Type="Number">1</Data></Cell> </Row> <Row> <Cell ss:Index="2" ss:Formula="=INDEX(singleRow,RC[3],RC[4])"><Data ss:Type="String">g</Data></Cell> <Cell><Data ss:Type="String">g</Data></Cell> <Cell ss:Index="5"><Data ss:Type="Number">1</Data></Cell> <Cell><Data ss:Type="Number">2</Data></Cell> </Row> <Row> <Cell ss:Index="2" ss:Formula="=INDEX(singleRow,RC[3],RC[4])"><Data ss:Type="String">j</Data></Cell> <Cell><Data ss:Type="String">j</Data></Cell> <Cell ss:Index="5"><Data ss:Type="Number">1</Data></Cell> <Cell><Data ss:Type="Number">5</Data></Cell> </Row> <Row> <Cell ss:Index="2" ss:Formula="=INDEX(singleRow,RC[3],RC[4])"><Data ss:Type="Error">#REF!</Data></Cell> <Cell><Data ss:Type="Error">#REF!</Data></Cell> <Cell ss:Index="5"><Data ss:Type="Number">1</Data></Cell> <Cell><Data ss:Type="Number">6</Data></Cell> </Row> <Row> <Cell ss:Index="2" ss:Formula="=INDEX(singleRow,RC[3],RC[4])"><Data ss:Type="String">f</Data></Cell> <Cell><Data ss:Type="String">f</Data></Cell> <Cell ss:Index="5"><Data ss:Type="Number">0</Data></Cell> <Cell><Data ss:Type="Number">1</Data></Cell> </Row> <Row> <Cell ss:Index="2" ss:Formula="=INDEX(singleRow,RC[3],RC[4])"><Data ss:Type="String">i</Data></Cell> <Cell><Data ss:Type="String">i</Data></Cell> <Cell ss:Index="5"><Data ss:Type="Number">0</Data></Cell> <Cell><Data ss:Type="Number">4</Data></Cell> </Row> <Row> <Cell ss:Index="2" ss:Formula="=INDEX(singleRow,RC[3],RC[4])"><Data ss:Type="String">j</Data></Cell> <Cell><Data ss:Type="String">j</Data></Cell> <Cell ss:Index="5"><Data ss:Type="Number">0</Data></Cell> <Cell><Data ss:Type="Number">5</Data></Cell> </Row> <Row> <Cell ss:Index="2" ss:Formula="=INDEX(singleRow,RC[3],RC[4])"><Data ss:Type="Error">#REF!</Data></Cell> <Cell><Data ss:Type="Error">#REF!</Data></Cell> <Cell ss:Index="5"><Data ss:Type="Number">0</Data></Cell> <Cell><Data ss:Type="Number">6</Data></Cell> </Row> <Row> <Cell ss:Index="2" ss:Formula="=INDEX(singleRow,RC[3],RC[4])"><Data ss:Type="Error">#REF!</Data></Cell> <Cell><Data ss:Type="Error">#REF!</Data></Cell> <Cell ss:Index="5"><Data ss:Type="Number">2</Data></Cell> <Cell><Data ss:Type="Number">1</Data></Cell> </Row> <Row> <Cell ss:Index="2" ss:Formula="=INDEX(singleRow,RC[3],RC[4])"><Data ss:Type="Error">#REF!</Data></Cell> <Cell><Data ss:Type="Error">#REF!</Data></Cell> <Cell ss:Index="5"><Data ss:Type="Number">2</Data></Cell> <Cell><Data ss:Type="Number">0</Data></Cell> </Row> <Row> <Cell ss:Index="2" ss:Formula="=INDEX(singleRow,RC[3],RC[4])"><Data ss:Type="Error">#VALUE!</Data></Cell> <Cell><Data ss:Type="Error">#VALUE!</Data></Cell> <Cell ss:Index="5"><Data ss:Type="Number">2</Data></Cell> <Cell><Data ss:Type="Number">-1</Data></Cell> </Row> <Row> <Cell ss:Index="2" ss:Formula="=INDEX(singleRow,RC[3],RC[4])"><Data ss:Type="Error">#VALUE!</Data></Cell> <Cell><Data ss:Type="Error">#VALUE!</Data></Cell> <Cell ss:Index="5"><Data ss:Type="Number">5</Data></Cell> <Cell><Data ss:Type="Number">-5</Data></Cell> </Row> <Row> <Cell ss:Index="2" ss:Formula="=INDEX(singleRow,RC[3],RC[4])"><Data ss:Type="Error">#VALUE!</Data></Cell> <Cell><Data ss:Type="Error">#VALUE!</Data></Cell> <Cell ss:Index="5"><Data ss:Type="Number">2</Data></Cell> <Cell><Data ss:Type="Number">-1</Data></Cell> </Row> <Row> <Cell ss:Index="2" ss:Formula="=INDEX(singleRow,RC[3],RC[4])"><Data ss:Type="Error">#VALUE!</Data></Cell> <Cell><Data ss:Type="Error">#VALUE!</Data></Cell> <Cell ss:Index="5"><Data ss:Type="Number">-1</Data></Cell> <Cell><Data ss:Type="Number">1</Data></Cell> </Row> <Row> <Cell ss:Index="2" ss:Formula="=INDEX(singleRow,RC[3],RC[4])"><Data ss:Type="Error">#VALUE!</Data></Cell> <Cell><Data ss:Type="Error">#VALUE!</Data></Cell> <Cell ss:Index="5"><Data ss:Type="Number">1</Data></Cell> <Cell><Data ss:Type="Number">-1</Data></Cell> </Row> <Row> <Cell ss:Index="2" ss:Formula="=INDEX(singleRow,RC[3],RC[4])"><Data ss:Type="Error">#VALUE!</Data></Cell> <Cell><Data ss:Type="Error">#VALUE!</Data></Cell> <Cell ss:Index="5"><Data ss:Type="Number">0</Data></Cell> <Cell><Data ss:Type="Number">-5</Data></Cell> </Row> <Row> <Cell ss:Index="2" ss:Formula="=INDEX(singleRow,RC[3],RC[4])"><Data ss:Type="Error">#VALUE!</Data></Cell> <Cell><Data ss:Type="Error">#VALUE!</Data></Cell> <Cell ss:Index="5"><Data ss:Type="Number">0</Data></Cell> <Cell><Data ss:Type="Number">0</Data></Cell> </Row> <Row ss:Index="53"> <Cell ss:Index="5"><Data ss:Type="String">singleColumn with one index arg</Data></Cell> </Row> <Row> <Cell ss:Index="2" ss:Formula="=INDEX(singleColumn,RC[3])"><Data ss:Type="String">b</Data></Cell> <Cell><Data ss:Type="String">b</Data></Cell> <Cell ss:Index="5"><Data ss:Type="Number">1</Data></Cell> </Row> <Row> <Cell ss:Index="2" ss:Formula="=INDEX(singleColumn,RC[3])"><Data ss:Type="String">g</Data></Cell> <Cell><Data ss:Type="String">g</Data></Cell> <Cell ss:Index="5"><Data ss:Type="Number">2</Data></Cell> </Row> <Row> <Cell ss:Index="2" ss:Formula="=INDEX(singleColumn,RC[3])"><Data ss:Type="String">q</Data></Cell> <Cell><Data ss:Type="String">q</Data></Cell> <Cell ss:Index="5"><Data ss:Type="Number">4</Data></Cell> </Row> <Row> <Cell ss:Index="2" ss:Formula="=INDEX(singleColumn,RC[3])"><Data ss:Type="String">v</Data></Cell> <Cell><Data ss:Type="String">v</Data></Cell> <Cell ss:Index="5"><Data ss:Type="Number">5</Data></Cell> </Row> <Row> <Cell ss:Index="2" ss:Formula="=INDEX(singleColumn,RC[3])"><Data ss:Type="Error">#REF!</Data></Cell> <Cell><Data ss:Type="Error">#REF!</Data></Cell> <Cell ss:Index="5"><Data ss:Type="Number">6</Data></Cell> </Row> <Row> <Cell ss:Index="2" ss:Formula="=INDEX(singleColumn,RC[3])"><Data ss:Type="Error">#VALUE!</Data></Cell> <Cell><Data ss:Type="Error">#VALUE!</Data></Cell> <Cell ss:Index="5"><Data ss:Type="Number">-1</Data></Cell> </Row> <Row ss:Index="62"> <Cell ss:Index="5"><Data ss:Type="String">singleColumn with both index args</Data></Cell> </Row> <Row> <Cell ss:Index="2" ss:Formula="=INDEX(singleColumn,RC[3],RC[4])"><Data ss:Type="String">b</Data></Cell> <Cell><Data ss:Type="String">b</Data></Cell> <Cell ss:Index="5"><Data ss:Type="Number">1</Data></Cell> <Cell><Data ss:Type="Number">1</Data></Cell> </Row> <Row> <Cell ss:Index="2" ss:Formula="=INDEX(singleColumn,RC[3],RC[4])"><Data ss:Type="String">g</Data></Cell> <Cell><Data ss:Type="String">g</Data></Cell> <Cell ss:Index="5"><Data ss:Type="Number">2</Data></Cell> <Cell><Data ss:Type="Number">1</Data></Cell> </Row> <Row> <Cell ss:Index="2" ss:Formula="=INDEX(singleColumn,RC[3],RC[4])"><Data ss:Type="String">v</Data></Cell> <Cell><Data ss:Type="String">v</Data></Cell> <Cell ss:Index="5"><Data ss:Type="Number">5</Data></Cell> <Cell><Data ss:Type="Number">1</Data></Cell> </Row> <Row> <Cell ss:Index="2" ss:Formula="=INDEX(singleColumn,RC[3],RC[4])"><Data ss:Type="Error">#REF!</Data></Cell> <Cell><Data ss:Type="Error">#REF!</Data></Cell> <Cell ss:Index="5"><Data ss:Type="Number">6</Data></Cell> <Cell><Data ss:Type="Number">1</Data></Cell> </Row> <Row> <Cell ss:Index="2" ss:Formula="=INDEX(singleColumn,RC[3],RC[4])"><Data ss:Type="String">b</Data></Cell> <Cell><Data ss:Type="String">b</Data></Cell> <Cell ss:Index="5"><Data ss:Type="Number">1</Data></Cell> <Cell><Data ss:Type="Number">0</Data></Cell> </Row> <Row> <Cell ss:Index="2" ss:Formula="=INDEX(singleColumn,RC[3],RC[4])"><Data ss:Type="String">q</Data></Cell> <Cell><Data ss:Type="String">q</Data></Cell> <Cell ss:Index="5"><Data ss:Type="Number">4</Data></Cell> <Cell><Data ss:Type="Number">0</Data></Cell> </Row> <Row> <Cell ss:Index="2" ss:Formula="=INDEX(singleColumn,RC[3],RC[4])"><Data ss:Type="String">v</Data></Cell> <Cell><Data ss:Type="String">v</Data></Cell> <Cell ss:Index="5"><Data ss:Type="Number">5</Data></Cell> <Cell><Data ss:Type="Number">0</Data></Cell> </Row> <Row> <Cell ss:Index="2" ss:Formula="=INDEX(singleColumn,RC[3],RC[4])"><Data ss:Type="Error">#REF!</Data></Cell> <Cell><Data ss:Type="Error">#REF!</Data></Cell> <Cell ss:Index="5"><Data ss:Type="Number">6</Data></Cell> <Cell><Data ss:Type="Number">0</Data></Cell> </Row> <Row> <Cell ss:Index="2" ss:Formula="=INDEX(singleColumn,RC[3],RC[4])"><Data ss:Type="Error">#VALUE!</Data></Cell> <Cell><Data ss:Type="Error">#VALUE!</Data></Cell> <Cell ss:Index="5"><Data ss:Type="Number">0</Data></Cell> <Cell><Data ss:Type="Number">1</Data></Cell> </Row> <Row> <Cell ss:Index="2" ss:Formula="=INDEX(singleColumn,RC[3],RC[4])"><Data ss:Type="Error">#REF!</Data></Cell> <Cell><Data ss:Type="Error">#REF!</Data></Cell> <Cell ss:Index="5"><Data ss:Type="Number">0</Data></Cell> <Cell><Data ss:Type="Number">2</Data></Cell> </Row> <Row> <Cell ss:Index="2" ss:Formula="=INDEX(singleColumn,RC[3],RC[4])"><Data ss:Type="Error">#VALUE!</Data></Cell> <Cell><Data ss:Type="Error">#VALUE!</Data></Cell> <Cell ss:Index="5"><Data ss:Type="Number">-1</Data></Cell> <Cell><Data ss:Type="Number">2</Data></Cell> </Row> <Row> <Cell ss:Index="2" ss:Formula="=INDEX(singleColumn,RC[3],RC[4])"><Data ss:Type="Error">#VALUE!</Data></Cell> <Cell><Data ss:Type="Error">#VALUE!</Data></Cell> <Cell ss:Index="5"><Data ss:Type="Number">-1</Data></Cell> <Cell><Data ss:Type="Number">3</Data></Cell> </Row> <Row> <Cell ss:Index="2" ss:Formula="=INDEX(singleColumn,RC[3],RC[4])"><Data ss:Type="Error">#VALUE!</Data></Cell> <Cell><Data ss:Type="Error">#VALUE!</Data></Cell> <Cell ss:Index="5"><Data ss:Type="Number">-1</Data></Cell> <Cell><Data ss:Type="Number">0</Data></Cell> </Row> <Row> <Cell ss:Index="2" ss:Formula="=INDEX(singleColumn,RC[3],RC[4])"><Data ss:Type="Error">#REF!</Data></Cell> <Cell><Data ss:Type="Error">#REF!</Data></Cell> <Cell ss:Index="5"><Data ss:Type="Number">6</Data></Cell> <Cell><Data ss:Type="Number">0</Data></Cell> </Row> <Row> <Cell ss:Index="2" ss:Formula="=INDEX(singleColumn,RC[3],RC[4])"><Data ss:Type="Error">#VALUE!</Data></Cell> <Cell><Data ss:Type="Error">#VALUE!</Data></Cell> <Cell ss:Index="5"><Data ss:Type="Number">6</Data></Cell> <Cell><Data ss:Type="Number">-1</Data></Cell> </Row> <Row ss:Index="80"> <Cell ss:Index="5"><Data ss:Type="String">oneByOne with both index args</Data></Cell> </Row> <Row> <Cell ss:Index="2" ss:Formula="=INDEX(oneByOne,RC[3],RC[4])"><Data ss:Type="String">m</Data></Cell> <Cell><Data ss:Type="String">m</Data></Cell> <Cell ss:Index="5"><Data ss:Type="Number">0</Data></Cell> <Cell><Data ss:Type="Number">0</Data></Cell> </Row> <Row> <Cell ss:Index="2" ss:Formula="=INDEX(oneByOne,RC[3],RC[4])"><Data ss:Type="String">m</Data></Cell> <Cell><Data ss:Type="String">m</Data></Cell> <Cell ss:Index="5"><Data ss:Type="Number">0</Data></Cell> <Cell><Data ss:Type="Number">1</Data></Cell> </Row> <Row> <Cell ss:Index="2" ss:Formula="=INDEX(oneByOne,RC[3],RC[4])"><Data ss:Type="String">m</Data></Cell> <Cell><Data ss:Type="String">m</Data></Cell> <Cell ss:Index="5"><Data ss:Type="Number">1</Data></Cell> <Cell><Data ss:Type="Number">0</Data></Cell> </Row> <Row> <Cell ss:Index="2" ss:Formula="=INDEX(oneByOne,RC[3],RC[4])"><Data ss:Type="String">m</Data></Cell> <Cell><Data ss:Type="String">m</Data></Cell> <Cell ss:Index="5"><Data ss:Type="Number">1</Data></Cell> <Cell><Data ss:Type="Number">1</Data></Cell> </Row> <Row> <Cell ss:Index="2" ss:Formula="=INDEX(oneByOne,RC[3],RC[4])"><Data ss:Type="Error">#REF!</Data></Cell> <Cell><Data ss:Type="Error">#REF!</Data></Cell> <Cell ss:Index="5"><Data ss:Type="Number">1</Data></Cell> <Cell><Data ss:Type="Number">2</Data></Cell> </Row> <Row> <Cell ss:Index="2" ss:Formula="=INDEX(oneByOne,RC[3],RC[4])"><Data ss:Type="Error">#REF!</Data></Cell> <Cell><Data ss:Type="Error">#REF!</Data></Cell> <Cell ss:Index="5"><Data ss:Type="Number">0</Data></Cell> <Cell><Data ss:Type="Number">2</Data></Cell> </Row> <Row> <Cell ss:Index="2" ss:Formula="=INDEX(oneByOne,RC[3],RC[4])"><Data ss:Type="Error">#VALUE!</Data></Cell> <Cell><Data ss:Type="Error">#VALUE!</Data></Cell> <Cell ss:Index="5"><Data ss:Type="Number">-1</Data></Cell> <Cell><Data ss:Type="Number">1</Data></Cell> </Row> <Row> <Cell ss:Index="2" ss:Formula="=INDEX(oneByOne,RC[3],RC[4])"><Data ss:Type="Error">#VALUE!</Data></Cell> <Cell><Data ss:Type="Error">#VALUE!</Data></Cell> <Cell ss:Index="5"><Data ss:Type="Number">0</Data></Cell> <Cell><Data ss:Type="Number">-1</Data></Cell> </Row> <Row> <Cell ss:Index="2" ss:Formula="=INDEX(oneByOne,RC[3],RC[4])"><Data ss:Type="Error">#VALUE!</Data></Cell> <Cell><Data ss:Type="Error">#VALUE!</Data></Cell> <Cell ss:Index="5"><Data ss:Type="Number">2</Data></Cell> <Cell><Data ss:Type="Number">-1</Data></Cell> </Row> <Row> <Cell ss:Index="2" ss:Formula="=INDEX(oneByOne,RC[3],RC[4])"><Data ss:Type="Error">#REF!</Data></Cell> <Cell><Data ss:Type="Error">#REF!</Data></Cell> <Cell ss:Index="5"><Data ss:Type="Number">2</Data></Cell> <Cell><Data ss:Type="Number">0</Data></Cell> </Row> <Row> <Cell ss:Index="2" ss:Formula="=INDEX(oneByOne,RC[3],RC[4])"><Data ss:Type="Error">#VALUE!</Data></Cell> <Cell><Data ss:Type="Error">#VALUE!</Data></Cell> <Cell ss:Index="5"><Data ss:Type="Number">5</Data></Cell> <Cell><Data ss:Type="Number">-5</Data></Cell> </Row> <Row ss:Index="94"> <Cell ss:Index="5"><Data ss:Type="String">oneByOne with one index arg</Data></Cell> </Row> <Row> <Cell ss:Index="2" ss:Formula="=INDEX(oneByOne,RC[3])"><Data ss:Type="String">m</Data></Cell> <Cell><Data ss:Type="String">m</Data></Cell> <Cell ss:Index="5"><Data ss:Type="Number">0</Data></Cell> </Row> <Row> <Cell ss:Index="2" ss:Formula="=INDEX(oneByOne,RC[3])"><Data ss:Type="String">m</Data></Cell> <Cell><Data ss:Type="String">m</Data></Cell> <Cell ss:Index="5"><Data ss:Type="Number">1</Data></Cell> </Row> <Row> <Cell ss:Index="2" ss:Formula="=INDEX(oneByOne,RC[3])"><Data ss:Type="Error">#REF!</Data></Cell> <Cell><Data ss:Type="Error">#REF!</Data></Cell> <Cell ss:Index="5"><Data ss:Type="Number">2</Data></Cell> </Row> <Row> <Cell ss:Index="2" ss:Formula="=INDEX(oneByOne,RC[3])"><Data ss:Type="Error">#VALUE!</Data></Cell> <Cell><Data ss:Type="Error">#VALUE!</Data></Cell> <Cell ss:Index="5"><Data ss:Type="Number">-1</Data></Cell> </Row> <Row ss:Index="101"> <Cell ss:Index="5"><Data ss:Type="String">missing second arg - area</Data></Cell> </Row> <Row ss:Index="103"> <Cell ss:Index="2" ss:Formula="=INDEX(R104C9:R105C10,,RC[4])"><Data ss:Type="Error">#VALUE!</Data></Cell> <Cell><Data ss:Type="Error">#VALUE!</Data></Cell> <Cell ss:Index="6"><Data ss:Type="Number">1</Data></Cell> </Row> <Row> <Cell ss:Index="2" ss:Formula="=INDEX(R104C9:R105C10,,RC[4])"><Data ss:Type="String">a</Data></Cell> <Cell><Data ss:Type="String">a</Data></Cell> <Cell ss:Index="6"><Data ss:Type="Number">1</Data></Cell> <Cell ss:Index="9"><Data ss:Type="String">a</Data></Cell> <Cell><Data ss:Type="String">b</Data></Cell> </Row> <Row> <Cell ss:Index="2" ss:Formula="=INDEX(R104C9:R105C10,,RC[4])"><Data ss:Type="String">c</Data></Cell> <Cell><Data ss:Type="String">c</Data></Cell> <Cell ss:Index="6"><Data ss:Type="Number">1</Data></Cell> <Cell ss:Index="9"><Data ss:Type="String">c</Data></Cell> <Cell><Data ss:Type="String">d</Data></Cell> </Row> <Row> <Cell ss:Index="2" ss:Formula="=INDEX(R104C9:R105C10,,RC[4])"><Data ss:Type="Error">#VALUE!</Data></Cell> <Cell><Data ss:Type="Error">#VALUE!</Data></Cell> <Cell ss:Index="6"><Data ss:Type="Number">1</Data></Cell> </Row> <Row> <Cell ss:Index="2" ss:Formula="=INDEX(R108C9:R109C10,RC[3],RC[4])"><Data ss:Type="Error">#VALUE!</Data></Cell> <Cell><Data ss:Type="Error">#VALUE!</Data></Cell> <Cell ss:Index="6"><Data ss:Type="Number">1</Data></Cell> </Row> <Row> <Cell ss:Index="2" ss:Formula="=INDEX(R108C9:R109C10,RC[3],RC[4])"><Data ss:Type="String">a</Data></Cell> <Cell><Data ss:Type="String">a</Data></Cell> <Cell ss:Index="6"><Data ss:Type="Number">1</Data></Cell> <Cell ss:Index="9"><Data ss:Type="String">a</Data></Cell> <Cell><Data ss:Type="String">b</Data></Cell> </Row> <Row> <Cell ss:Index="2" ss:Formula="=INDEX(R108C9:R109C10,RC[3],RC[4])"><Data ss:Type="String">c</Data></Cell> <Cell><Data ss:Type="String">c</Data></Cell> <Cell ss:Index="6"><Data ss:Type="Number">1</Data></Cell> <Cell ss:Index="9"><Data ss:Type="String">c</Data></Cell> <Cell><Data ss:Type="String">d</Data></Cell> </Row> <Row> <Cell ss:Index="2" ss:Formula="=INDEX(R108C9:R109C10,RC[3],RC[4])"><Data ss:Type="Error">#VALUE!</Data></Cell> <Cell><Data ss:Type="Error">#VALUE!</Data></Cell> <Cell ss:Index="6"><Data ss:Type="Number">1</Data></Cell> </Row> <Row ss:Index="112"> <Cell ss:Index="5"><Data ss:Type="String">missing second arg - row</Data></Cell> </Row> <Row> <Cell ss:Index="2" ss:Formula="=INDEX(R114C9:R114C10,,RC[4])"><Data ss:Type="String">a</Data></Cell> <Cell><Data ss:Type="String">a</Data></Cell> <Cell ss:Index="6"><Data ss:Type="Number">1</Data></Cell> </Row> <Row> <Cell ss:Index="2" ss:Formula="=INDEX(R114C9:R114C10,,RC[4])"><Data ss:Type="String">b</Data></Cell> <Cell><Data ss:Type="String">b</Data></Cell> <Cell ss:Index="6"><Data ss:Type="Number">2</Data></Cell> <Cell ss:Index="9"><Data ss:Type="String">a</Data></Cell> <Cell><Data ss:Type="String">b</Data></Cell> </Row> <Row ss:Index="116"> <Cell ss:Index="5"><Data ss:Type="String">missing second arg - column</Data></Cell> </Row> <Row> <Cell ss:Index="2" ss:Formula="=INDEX(R118C9:R119C9,,RC[4])"><Data ss:Type="Error">#VALUE!</Data></Cell> <Cell><Data ss:Type="Error">#VALUE!</Data></Cell> <Cell ss:Index="6"><Data ss:Type="Number">1</Data></Cell> </Row> <Row> <Cell ss:Index="2" ss:Formula="=INDEX(R118C9:R119C9,,RC[4])"><Data ss:Type="String">a</Data></Cell> <Cell><Data ss:Type="String">a</Data></Cell> <Cell ss:Index="6"><Data ss:Type="Number">1</Data></Cell> <Cell ss:Index="9"><Data ss:Type="String">a</Data></Cell> </Row> <Row> <Cell ss:Index="2" ss:Formula="=INDEX(R118C9:R119C9,,RC[4])"><Data ss:Type="String">b</Data></Cell> <Cell><Data ss:Type="String">b</Data></Cell> <Cell ss:Index="6"><Data ss:Type="Number">0</Data></Cell> <Cell ss:Index="9"><Data ss:Type="String">b</Data></Cell> </Row> <Row> <Cell ss:Index="2" ss:Formula="=INDEX(R118C9:R119C9,,RC[4])"><Data ss:Type="Error">#VALUE!</Data></Cell> <Cell><Data ss:Type="Error">#VALUE!</Data></Cell> <Cell ss:Index="6"><Data ss:Type="Number">1</Data></Cell> </Row> <Row ss:Index="123"> <Cell ss:Index="10"><Data ss:Type="Number">4</Data><NamedCell ss:Name="numberArea"/></Cell> <Cell><Data ss:Type="Number">2</Data><NamedCell ss:Name="numberArea"/></Cell> <Cell><Data ss:Type="Number">3</Data><NamedCell ss:Name="numberArea"/></Cell> <Cell><Data ss:Type="Number">5</Data><NamedCell ss:Name="numberArea"/></Cell> </Row> <Row> <Cell ss:Index="10"><Data ss:Type="Number">0.1</Data><NamedCell ss:Name="numberArea"/></Cell> <Cell><Data ss:Type="Number">0.3</Data><NamedCell ss:Name="numberArea"/></Cell> <Cell><Data ss:Type="Number">0.2</Data><NamedCell ss:Name="numberArea"/></Cell> <Cell><Data ss:Type="Number">0.5</Data><NamedCell ss:Name="numberArea"/></Cell> </Row> <Row> <Cell ss:Index="10"><Data ss:Type="Number">10</Data><NamedCell ss:Name="numberArea"/></Cell> <Cell><Data ss:Type="Number">20</Data><NamedCell ss:Name="numberArea"/></Cell> <Cell><Data ss:Type="Number">50</Data><NamedCell ss:Name="numberArea"/></Cell> <Cell><Data ss:Type="Number">40</Data><NamedCell ss:Name="numberArea"/></Cell> </Row> <Row ss:Index="127"> <Cell ss:Index="5"><Data ss:Type="String">whole row, whole column results</Data></Cell> </Row> <Row> <Cell ss:Index="2" ss:Formula="=SUM(INDEX(numberArea,RC[3],RC[4]))"><Data ss:Type="Number">135.1</Data></Cell> <Cell><Data ss:Type="Number">135.1</Data></Cell> </Row> <Row> <Cell ss:Index="2" ss:Formula="=SUM(INDEX(numberArea,RC[3],RC[4]))"><Data ss:Type="Number">135.1</Data></Cell> <Cell><Data ss:Type="Number">135.1</Data></Cell> <Cell ss:Index="5"><Data ss:Type="Number">0</Data></Cell> <Cell><Data ss:Type="Number">0</Data></Cell> </Row> <Row> <Cell ss:Index="2" ss:Formula="=SUM(INDEX(numberArea,RC[3],RC[4]))"><Data ss:Type="Number">14</Data></Cell> <Cell><Data ss:Type="Number">14</Data></Cell> <Cell ss:Index="5"><Data ss:Type="Number">1</Data></Cell> </Row> <Row> <Cell ss:Index="2" ss:Formula="=SUM(INDEX(numberArea,RC[3],RC[4]))"><Data ss:Type="Number">1.1000000000000001</Data></Cell> <Cell><Data ss:Type="Number">1.1000000000000001</Data></Cell> <Cell ss:Index="5"><Data ss:Type="Number">2</Data></Cell> </Row> <Row> <Cell ss:Index="2" ss:Formula="=SUM(INDEX(numberArea,RC[3],RC[4]))"><Data ss:Type="Number">120</Data></Cell> <Cell><Data ss:Type="Number">120</Data></Cell> <Cell ss:Index="5"><Data ss:Type="Number">3</Data></Cell> </Row> <Row> <Cell ss:Index="2" ss:Formula="=SUM(INDEX(numberArea,RC[3],RC[4]))"><Data ss:Type="Error">#REF!</Data></Cell> <Cell><Data ss:Type="Error">#REF!</Data></Cell> <Cell ss:Index="5"><Data ss:Type="Number">4</Data></Cell> </Row> <Row> <Cell ss:Index="2" ss:Formula="=SUM(INDEX(numberArea,RC[3],RC[4]))"><Data ss:Type="Number">14.1</Data></Cell> <Cell><Data ss:Type="Number">14.1</Data></Cell> <Cell ss:Index="6"><Data ss:Type="Number">1</Data></Cell> </Row> <Row> <Cell ss:Index="2" ss:Formula="=SUM(INDEX(numberArea,RC[3],RC[4]))"><Data ss:Type="Number">22.3</Data></Cell> <Cell><Data ss:Type="Number">22.3</Data></Cell> <Cell ss:Index="6"><Data ss:Type="Number">2</Data></Cell> </Row> <Row> <Cell ss:Index="2" ss:Formula="=SUM(INDEX(numberArea,RC[3],RC[4]))"><Data ss:Type="Number">53.2</Data></Cell> <Cell><Data ss:Type="Number">53.2</Data></Cell> <Cell ss:Index="6"><Data ss:Type="Number">3</Data></Cell> </Row> <Row> <Cell ss:Index="2" ss:Formula="=SUM(INDEX(numberArea,RC[3],RC[4]))"><Data ss:Type="Number">45.5</Data></Cell> <Cell><Data ss:Type="Number">45.5</Data></Cell> <Cell ss:Index="6"><Data ss:Type="Number">4</Data></Cell> </Row> <Row> <Cell ss:Index="2" ss:Formula="=SUM(INDEX(numberArea,RC[3],RC[4]))"><Data ss:Type="Error">#REF!</Data></Cell> <Cell><Data ss:Type="Error">#REF!</Data></Cell> <Cell ss:Index="6"><Data ss:Type="Number">5</Data></Cell> </Row> <Row> <Cell><Data ss:Type="String">&lt;end&gt;</Data></Cell> </Row> </Table> <WorksheetOptions xmlns="urn:schemas-microsoft-com:office:excel"> <PageSetup> <Header x:Margin="0.3"/> <Footer x:Margin="0.3"/> <PageMargins x:Bottom="0.75" x:Left="0.7" x:Right="0.7" x:Top="0.75"/> </PageSetup> <Print> <ValidPrinterInfo/> <PaperSizeIndex>9</PaperSizeIndex> <HorizontalResolution>600</HorizontalResolution> <VerticalResolution>600</VerticalResolution> </Print> <PageLayoutZoom>0</PageLayoutZoom> <Selected/> <Panes> <Pane> <Number>3</Number> <ActiveCol>2</ActiveCol> </Pane> </Panes> <ProtectObjects>False</ProtectObjects> <ProtectScenarios>False</ProtectScenarios> </WorksheetOptions> </Worksheet> </Workbook>
{ "pile_set_name": "Github" }
<template> <div class="user"> <div class="user-header"> <div class="user-img"> <img src="../../assets/a.jpg" alt> </div> <div class="user-name"> <p>这个少年不太冷</p> </div> <div class="mui-card"> <div class="mui-card-header mui-card-media"></div> <div class="mui-card-content"> <div class="mui-card-content-inner"> <p>此项目为学习vue写的因为平时喜欢看小说所以写这个比较有意思些</p> <p>使用技术栈及ui:vue vue-cli3 vue-x vue-router axios mint-ui mui javaScript es6 sass</p> <p>本地服务器跨域在vue-config.js中配置代理接口</p> <p>生产环境使用nginx反向代理即可</p> <p>api接口为追书神器接口.</p> <p>后续会优化整理一些思路和难点</p> <p>阅读时小说需要vip时点击换源即可免费阅读</p> <p> <a href="https://github.com/zgsnbtl/vue-guapi/blob/master/src/components/api/api.js" >查看接口点击这里</a> </p> <p>项目源码已上传至 <a href="https://github.com/zgsnbtl/vue-guapi">GitHub</a> </p> <p>浏览地址<a href="http://39.96.55.152">39.96.55.152</a></p> <p>欢迎大家GitHub Star</p> <p>项目中一些bug见谅~…~</p> </div> </div> <div class="mui-card-footer"> <p>优化及bug联系qq1635942033</p> <!-- <a class="mui-card-link">Like</a> <a class="mui-card-link">Read more</a>--> </div> </div> </div> </div> </template> <script> // import imgss from 'src/assets/a.jpg' // export default { // data () { // return { // imgs:imgss // } // } // } </script> <style lang="scss" scope> .user { position: relative; background-image: url(../../assets/b.jpg); top: 0; width: 100%; min-height: 100%; background-size: 100% 100%; overflow-y: auto; .user-header { .user-img { text-align: center; // margin-top: 30px; padding-top: 50px; img { width: 80px; border-radius: 50%; } } .user-name { text-align: center; p { font-size: 14px; color: #333; } } .mui-card-header.mui-card-media { background-image: url(../../assets/c.jpg); background-size: 100% 100%; height: 200px; } } } </style>
{ "pile_set_name": "Github" }
fileFormatVersion: 2 guid: 02732ee9378d4918a46cef340651fbc1 timeCreated: 1573133312
{ "pile_set_name": "Github" }
{ "1-geodesics": { "title": "General information on geodesics" }, "2-interface": { "title": "The library interface" }, "3-examples": { "title": "Examples of use" } }
{ "pile_set_name": "Github" }
include (../HelloSceneCover.pro)
{ "pile_set_name": "Github" }
/* ****************************************************************************** * Copyright (c) 2006-2012 XMind Ltd. and others. * * This file is a part of XMind 3. XMind releases 3 and * above are dual-licensed under the Eclipse Public License (EPL), * which is available at http://www.eclipse.org/legal/epl-v10.html * and the GNU Lesser General Public License (LGPL), * which is available at http://www.gnu.org/licenses/lgpl.html * See https://www.xmind.net/license.html for details. * * Contributors: * XMind Ltd. - initial API and implementation *******************************************************************************/ package org.xmind.ui.tabfolder; /** * @author Brian Sun */ public interface IPageMoveListener { void pageMoved(int fromIndex, int toIndex); }
{ "pile_set_name": "Github" }
using System; using System.Collections; using System.IO; using Org.BouncyCastle.Asn1; using Org.BouncyCastle.Asn1.X509; using Org.BouncyCastle.Utilities; namespace Org.BouncyCastle.Crypto.Tls { /** * Parsing and encoding of a <i>Certificate</i> struct from RFC 4346. * <p/> * <pre> * opaque ASN.1Cert&lt;2^24-1&gt;; * * struct { * ASN.1Cert certificate_list&lt;0..2^24-1&gt;; * } Certificate; * </pre> * * @see Org.BouncyCastle.Asn1.X509.X509CertificateStructure */ public class Certificate { public static readonly Certificate EmptyChain = new Certificate(new X509CertificateStructure[0]); /** * The certificates. */ protected readonly X509CertificateStructure[] mCertificateList; public Certificate(X509CertificateStructure[] certificateList) { if (certificateList == null) throw new ArgumentNullException("certificateList"); this.mCertificateList = certificateList; } /** * @return an array of {@link org.bouncycastle.asn1.x509.Certificate} representing a certificate * chain. */ public virtual X509CertificateStructure[] GetCertificateList() { return CloneCertificateList(); } public virtual X509CertificateStructure GetCertificateAt(int index) { return mCertificateList[index]; } public virtual int Length { get { return mCertificateList.Length; } } /** * @return <code>true</code> if this certificate chain contains no certificates, or * <code>false</code> otherwise. */ public virtual bool IsEmpty { get { return mCertificateList.Length == 0; } } /** * Encode this {@link Certificate} to a {@link Stream}. * * @param output the {@link Stream} to encode to. * @throws IOException */ public virtual void Encode(Stream output) { IList derEncodings = Platform.CreateArrayList(mCertificateList.Length); int totalLength = 0; foreach (Asn1Encodable asn1Cert in mCertificateList) { byte[] derEncoding = asn1Cert.GetEncoded(Asn1Encodable.Der); derEncodings.Add(derEncoding); totalLength += derEncoding.Length + 3; } TlsUtilities.CheckUint24(totalLength); TlsUtilities.WriteUint24(totalLength, output); foreach (byte[] derEncoding in derEncodings) { TlsUtilities.WriteOpaque24(derEncoding, output); } } /** * Parse a {@link Certificate} from a {@link Stream}. * * @param input the {@link Stream} to parse from. * @return a {@link Certificate} object. * @throws IOException */ public static Certificate Parse(Stream input) { int totalLength = TlsUtilities.ReadUint24(input); if (totalLength == 0) { return EmptyChain; } byte[] certListData = TlsUtilities.ReadFully(totalLength, input); MemoryStream buf = new MemoryStream(certListData, false); IList certificate_list = Platform.CreateArrayList(); while (buf.Position < buf.Length) { byte[] berEncoding = TlsUtilities.ReadOpaque24(buf); Asn1Object asn1Cert = TlsUtilities.ReadAsn1Object(berEncoding); certificate_list.Add(X509CertificateStructure.GetInstance(asn1Cert)); } X509CertificateStructure[] certificateList = new X509CertificateStructure[certificate_list.Count]; for (int i = 0; i < certificate_list.Count; ++i) { certificateList[i] = (X509CertificateStructure)certificate_list[i]; } return new Certificate(certificateList); } protected virtual X509CertificateStructure[] CloneCertificateList() { return (X509CertificateStructure[])mCertificateList.Clone(); } } }
{ "pile_set_name": "Github" }
import _ from 'lodash'; import moment from 'moment'; import PropTypes from 'prop-types'; import React, { Component } from 'react'; import { connect } from 'react-redux'; import { createSelector } from 'reselect'; import CalendarDay from './CalendarDay'; function createCalendarEventsConnector() { return createSelector( (state, { date }) => date, (state) => state.calendar.items, (date, items) => { const filtered = _.filter(items, (item) => { return moment(date).isSame(moment(item.releaseDate), 'day'); }); return _.sortBy(filtered, (item) => moment(item.releaseDate).unix()); } ); } function createMapStateToProps() { return createSelector( (state) => state.calendar, createCalendarEventsConnector(), (calendar, events) => { return { time: calendar.time, view: calendar.view, events }; } ); } class CalendarDayConnector extends Component { // // Render render() { return ( <CalendarDay {...this.props} /> ); } } CalendarDayConnector.propTypes = { date: PropTypes.string.isRequired }; export default connect(createMapStateToProps)(CalendarDayConnector);
{ "pile_set_name": "Github" }
<?xml version="1.0" encoding="UTF-8"?> <!-- 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. --> <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <parent> <groupId>org.apache.knox</groupId> <artifactId>gateway</artifactId> <version>1.5.0-SNAPSHOT</version> </parent> <artifactId>gateway-provider-ha</artifactId> <name>gateway-provider-ha</name> <description>An extension of the gateway that supports Hadoop services standing in HA mode</description> <dependencies> <dependency> <groupId>org.apache.knox</groupId> <artifactId>gateway-i18n</artifactId> </dependency> <dependency> <groupId>org.apache.knox</groupId> <artifactId>gateway-spi</artifactId> </dependency> <dependency> <groupId>org.apache.knox</groupId> <artifactId>gateway-provider-rewrite</artifactId> </dependency> <dependency> <groupId>org.apache.knox</groupId> <artifactId>gateway-util-common</artifactId> </dependency> <dependency> <groupId>org.apache.knox</groupId> <artifactId>gateway-util-configinjector</artifactId> </dependency> <dependency> <groupId>commons-io</groupId> <artifactId>commons-io</artifactId> </dependency> <dependency> <groupId>net.minidev</groupId> <artifactId>json-smart</artifactId> </dependency> <dependency> <groupId>org.apache.httpcomponents</groupId> <artifactId>httpcore</artifactId> </dependency> <dependency> <groupId>org.apache.httpcomponents</groupId> <artifactId>httpclient</artifactId> </dependency> <dependency> <groupId>org.jboss.shrinkwrap</groupId> <artifactId>shrinkwrap-api</artifactId> </dependency> <dependency> <groupId>org.jboss.shrinkwrap.descriptors</groupId> <artifactId>shrinkwrap-descriptors-api-javaee</artifactId> </dependency> <dependency> <groupId>org.apache.curator</groupId> <artifactId>curator-client</artifactId> </dependency> <dependency> <groupId>org.apache.curator</groupId> <artifactId>curator-framework</artifactId> </dependency> <dependency> <groupId>org.apache.zookeeper</groupId> <artifactId>zookeeper</artifactId> </dependency> <dependency> <groupId>org.apache.zookeeper</groupId> <artifactId>zookeeper-jute</artifactId> </dependency> <dependency> <groupId>javax.servlet</groupId> <artifactId>javax.servlet-api</artifactId> </dependency> <dependency> <groupId>org.apache.curator</groupId> <artifactId>curator-test</artifactId> <scope>test</scope> </dependency> <dependency> <groupId>org.xmlmatchers</groupId> <artifactId>xml-matchers</artifactId> <scope>test</scope> </dependency> <dependency> <groupId>org.apache.knox</groupId> <artifactId>gateway-test-utils</artifactId> <scope>test</scope> </dependency> </dependencies> </project>
{ "pile_set_name": "Github" }
/* * Event char devices, giving access to raw input device events. * * Copyright (c) 1999-2002 Vojtech Pavlik * * This program is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 as published by * the Free Software Foundation. */ #define pr_fmt(fmt) KBUILD_MODNAME ": " fmt #define EVDEV_MINOR_BASE 64 #define EVDEV_MINORS 32 #define EVDEV_MIN_BUFFER_SIZE 64U #define EVDEV_BUF_PACKETS 8 #include <linux/poll.h> #include <linux/sched.h> #include <linux/slab.h> #include <linux/vmalloc.h> #include <linux/mm.h> #include <linux/module.h> #include <linux/init.h> #include <linux/input/mt.h> #include <linux/major.h> #include <linux/device.h> #include <linux/cdev.h> #include "input-compat.h" enum evdev_clock_type { EV_CLK_REAL = 0, EV_CLK_MONO, EV_CLK_BOOT, EV_CLK_MAX }; struct evdev { int open; struct input_handle handle; wait_queue_head_t wait; struct evdev_client __rcu *grab; struct list_head client_list; spinlock_t client_lock; /* protects client_list */ struct mutex mutex; struct device dev; struct cdev cdev; bool exist; }; struct evdev_client { unsigned int head; unsigned int tail; unsigned int packet_head; /* [future] position of the first element of next packet */ spinlock_t buffer_lock; /* protects access to buffer, head and tail */ struct fasync_struct *fasync; struct evdev *evdev; struct list_head node; int clk_type; bool revoked; unsigned int bufsize; struct input_event buffer[]; }; /* flush queued events of type @type, caller must hold client->buffer_lock */ static void __evdev_flush_queue(struct evdev_client *client, unsigned int type) { unsigned int i, head, num; unsigned int mask = client->bufsize - 1; bool is_report; struct input_event *ev; BUG_ON(type == EV_SYN); head = client->tail; client->packet_head = client->tail; /* init to 1 so a leading SYN_REPORT will not be dropped */ num = 1; for (i = client->tail; i != client->head; i = (i + 1) & mask) { ev = &client->buffer[i]; is_report = ev->type == EV_SYN && ev->code == SYN_REPORT; if (ev->type == type) { /* drop matched entry */ continue; } else if (is_report && !num) { /* drop empty SYN_REPORT groups */ continue; } else if (head != i) { /* move entry to fill the gap */ client->buffer[head].time = ev->time; client->buffer[head].type = ev->type; client->buffer[head].code = ev->code; client->buffer[head].value = ev->value; } num++; head = (head + 1) & mask; if (is_report) { num = 0; client->packet_head = head; } } client->head = head; } static void __evdev_queue_syn_dropped(struct evdev_client *client) { struct input_event ev; ktime_t time; time = client->clk_type == EV_CLK_REAL ? ktime_get_real() : client->clk_type == EV_CLK_MONO ? ktime_get() : ktime_get_boottime(); ev.time = ktime_to_timeval(time); ev.type = EV_SYN; ev.code = SYN_DROPPED; ev.value = 0; client->buffer[client->head++] = ev; client->head &= client->bufsize - 1; if (unlikely(client->head == client->tail)) { /* drop queue but keep our SYN_DROPPED event */ client->tail = (client->head - 1) & (client->bufsize - 1); client->packet_head = client->tail; } } static void evdev_queue_syn_dropped(struct evdev_client *client) { unsigned long flags; spin_lock_irqsave(&client->buffer_lock, flags); __evdev_queue_syn_dropped(client); spin_unlock_irqrestore(&client->buffer_lock, flags); } static int evdev_set_clk_type(struct evdev_client *client, unsigned int clkid) { unsigned long flags; if (client->clk_type == clkid) return 0; switch (clkid) { case CLOCK_REALTIME: client->clk_type = EV_CLK_REAL; break; case CLOCK_MONOTONIC: client->clk_type = EV_CLK_MONO; break; case CLOCK_BOOTTIME: client->clk_type = EV_CLK_BOOT; break; default: return -EINVAL; } /* * Flush pending events and queue SYN_DROPPED event, * but only if the queue is not empty. */ spin_lock_irqsave(&client->buffer_lock, flags); if (client->head != client->tail) { client->packet_head = client->head = client->tail; __evdev_queue_syn_dropped(client); } spin_unlock_irqrestore(&client->buffer_lock, flags); return 0; } static void __pass_event(struct evdev_client *client, const struct input_event *event) { client->buffer[client->head++] = *event; client->head &= client->bufsize - 1; if (unlikely(client->head == client->tail)) { /* * This effectively "drops" all unconsumed events, leaving * EV_SYN/SYN_DROPPED plus the newest event in the queue. */ client->tail = (client->head - 2) & (client->bufsize - 1); client->buffer[client->tail].time = event->time; client->buffer[client->tail].type = EV_SYN; client->buffer[client->tail].code = SYN_DROPPED; client->buffer[client->tail].value = 0; client->packet_head = client->tail; } if (event->type == EV_SYN && event->code == SYN_REPORT) { client->packet_head = client->head; kill_fasync(&client->fasync, SIGIO, POLL_IN); } } static void evdev_pass_values(struct evdev_client *client, const struct input_value *vals, unsigned int count, ktime_t *ev_time) { struct evdev *evdev = client->evdev; const struct input_value *v; struct input_event event; bool wakeup = false; if (client->revoked) return; event.time = ktime_to_timeval(ev_time[client->clk_type]); /* Interrupts are disabled, just acquire the lock. */ spin_lock(&client->buffer_lock); for (v = vals; v != vals + count; v++) { event.type = v->type; event.code = v->code; event.value = v->value; __pass_event(client, &event); if (v->type == EV_SYN && v->code == SYN_REPORT) wakeup = true; } spin_unlock(&client->buffer_lock); if (wakeup) wake_up_interruptible(&evdev->wait); } /* * Pass incoming events to all connected clients. */ static void evdev_events(struct input_handle *handle, const struct input_value *vals, unsigned int count) { struct evdev *evdev = handle->private; struct evdev_client *client; ktime_t ev_time[EV_CLK_MAX]; ev_time[EV_CLK_MONO] = ktime_get(); ev_time[EV_CLK_REAL] = ktime_mono_to_real(ev_time[EV_CLK_MONO]); ev_time[EV_CLK_BOOT] = ktime_mono_to_any(ev_time[EV_CLK_MONO], TK_OFFS_BOOT); rcu_read_lock(); client = rcu_dereference(evdev->grab); if (client) evdev_pass_values(client, vals, count, ev_time); else list_for_each_entry_rcu(client, &evdev->client_list, node) evdev_pass_values(client, vals, count, ev_time); rcu_read_unlock(); } /* * Pass incoming event to all connected clients. */ static void evdev_event(struct input_handle *handle, unsigned int type, unsigned int code, int value) { struct input_value vals[] = { { type, code, value } }; evdev_events(handle, vals, 1); } static int evdev_fasync(int fd, struct file *file, int on) { struct evdev_client *client = file->private_data; return fasync_helper(fd, file, on, &client->fasync); } static int evdev_flush(struct file *file, fl_owner_t id) { struct evdev_client *client = file->private_data; struct evdev *evdev = client->evdev; int retval; retval = mutex_lock_interruptible(&evdev->mutex); if (retval) return retval; if (!evdev->exist || client->revoked) retval = -ENODEV; else retval = input_flush_device(&evdev->handle, file); mutex_unlock(&evdev->mutex); return retval; } static void evdev_free(struct device *dev) { struct evdev *evdev = container_of(dev, struct evdev, dev); input_put_device(evdev->handle.dev); kfree(evdev); } /* * Grabs an event device (along with underlying input device). * This function is called with evdev->mutex taken. */ static int evdev_grab(struct evdev *evdev, struct evdev_client *client) { int error; if (evdev->grab) return -EBUSY; error = input_grab_device(&evdev->handle); if (error) return error; rcu_assign_pointer(evdev->grab, client); return 0; } static int evdev_ungrab(struct evdev *evdev, struct evdev_client *client) { struct evdev_client *grab = rcu_dereference_protected(evdev->grab, lockdep_is_held(&evdev->mutex)); if (grab != client) return -EINVAL; rcu_assign_pointer(evdev->grab, NULL); synchronize_rcu(); input_release_device(&evdev->handle); return 0; } static void evdev_attach_client(struct evdev *evdev, struct evdev_client *client) { spin_lock(&evdev->client_lock); list_add_tail_rcu(&client->node, &evdev->client_list); spin_unlock(&evdev->client_lock); } static void evdev_detach_client(struct evdev *evdev, struct evdev_client *client) { spin_lock(&evdev->client_lock); list_del_rcu(&client->node); spin_unlock(&evdev->client_lock); synchronize_rcu(); } static int evdev_open_device(struct evdev *evdev) { int retval; retval = mutex_lock_interruptible(&evdev->mutex); if (retval) return retval; if (!evdev->exist) retval = -ENODEV; else if (!evdev->open++) { retval = input_open_device(&evdev->handle); if (retval) evdev->open--; } mutex_unlock(&evdev->mutex); return retval; } static void evdev_close_device(struct evdev *evdev) { mutex_lock(&evdev->mutex); if (evdev->exist && !--evdev->open) input_close_device(&evdev->handle); mutex_unlock(&evdev->mutex); } /* * Wake up users waiting for IO so they can disconnect from * dead device. */ static void evdev_hangup(struct evdev *evdev) { struct evdev_client *client; spin_lock(&evdev->client_lock); list_for_each_entry(client, &evdev->client_list, node) kill_fasync(&client->fasync, SIGIO, POLL_HUP); spin_unlock(&evdev->client_lock); wake_up_interruptible(&evdev->wait); } static int evdev_release(struct inode *inode, struct file *file) { struct evdev_client *client = file->private_data; struct evdev *evdev = client->evdev; mutex_lock(&evdev->mutex); evdev_ungrab(evdev, client); mutex_unlock(&evdev->mutex); evdev_detach_client(evdev, client); if (is_vmalloc_addr(client)) vfree(client); else kfree(client); evdev_close_device(evdev); return 0; } static unsigned int evdev_compute_buffer_size(struct input_dev *dev) { unsigned int n_events = max(dev->hint_events_per_packet * EVDEV_BUF_PACKETS, EVDEV_MIN_BUFFER_SIZE); return roundup_pow_of_two(n_events); } static int evdev_open(struct inode *inode, struct file *file) { struct evdev *evdev = container_of(inode->i_cdev, struct evdev, cdev); unsigned int bufsize = evdev_compute_buffer_size(evdev->handle.dev); unsigned int size = sizeof(struct evdev_client) + bufsize * sizeof(struct input_event); struct evdev_client *client; int error; client = kzalloc(size, GFP_KERNEL | __GFP_NOWARN); if (!client) client = vzalloc(size); if (!client) return -ENOMEM; client->bufsize = bufsize; spin_lock_init(&client->buffer_lock); client->evdev = evdev; evdev_attach_client(evdev, client); error = evdev_open_device(evdev); if (error) goto err_free_client; file->private_data = client; nonseekable_open(inode, file); return 0; err_free_client: evdev_detach_client(evdev, client); kvfree(client); return error; } static ssize_t evdev_write(struct file *file, const char __user *buffer, size_t count, loff_t *ppos) { struct evdev_client *client = file->private_data; struct evdev *evdev = client->evdev; struct input_event event; int retval = 0; if (count != 0 && count < input_event_size()) return -EINVAL; retval = mutex_lock_interruptible(&evdev->mutex); if (retval) return retval; if (!evdev->exist || client->revoked) { retval = -ENODEV; goto out; } while (retval + input_event_size() <= count) { if (input_event_from_user(buffer + retval, &event)) { retval = -EFAULT; goto out; } retval += input_event_size(); input_inject_event(&evdev->handle, event.type, event.code, event.value); } out: mutex_unlock(&evdev->mutex); return retval; } static int evdev_fetch_next_event(struct evdev_client *client, struct input_event *event) { int have_event; spin_lock_irq(&client->buffer_lock); have_event = client->packet_head != client->tail; if (have_event) { *event = client->buffer[client->tail++]; client->tail &= client->bufsize - 1; } spin_unlock_irq(&client->buffer_lock); return have_event; } static ssize_t evdev_read(struct file *file, char __user *buffer, size_t count, loff_t *ppos) { struct evdev_client *client = file->private_data; struct evdev *evdev = client->evdev; struct input_event event; size_t read = 0; int error; if (count != 0 && count < input_event_size()) return -EINVAL; for (;;) { if (!evdev->exist || client->revoked) return -ENODEV; if (client->packet_head == client->tail && (file->f_flags & O_NONBLOCK)) return -EAGAIN; /* * count == 0 is special - no IO is done but we check * for error conditions (see above). */ if (count == 0) break; while (read + input_event_size() <= count && evdev_fetch_next_event(client, &event)) { if (input_event_to_user(buffer + read, &event)) return -EFAULT; read += input_event_size(); } if (read) break; if (!(file->f_flags & O_NONBLOCK)) { error = wait_event_interruptible(evdev->wait, client->packet_head != client->tail || !evdev->exist || client->revoked); if (error) return error; } } return read; } /* No kernel lock - fine */ static unsigned int evdev_poll(struct file *file, poll_table *wait) { struct evdev_client *client = file->private_data; struct evdev *evdev = client->evdev; unsigned int mask; poll_wait(file, &evdev->wait, wait); if (evdev->exist && !client->revoked) mask = POLLOUT | POLLWRNORM; else mask = POLLHUP | POLLERR; if (client->packet_head != client->tail) mask |= POLLIN | POLLRDNORM; return mask; } #ifdef CONFIG_COMPAT #define BITS_PER_LONG_COMPAT (sizeof(compat_long_t) * 8) #define BITS_TO_LONGS_COMPAT(x) ((((x) - 1) / BITS_PER_LONG_COMPAT) + 1) #ifdef __BIG_ENDIAN static int bits_to_user(unsigned long *bits, unsigned int maxbit, unsigned int maxlen, void __user *p, int compat) { int len, i; if (compat) { len = BITS_TO_LONGS_COMPAT(maxbit) * sizeof(compat_long_t); if (len > maxlen) len = maxlen; for (i = 0; i < len / sizeof(compat_long_t); i++) if (copy_to_user((compat_long_t __user *) p + i, (compat_long_t *) bits + i + 1 - ((i % 2) << 1), sizeof(compat_long_t))) return -EFAULT; } else { len = BITS_TO_LONGS(maxbit) * sizeof(long); if (len > maxlen) len = maxlen; if (copy_to_user(p, bits, len)) return -EFAULT; } return len; } #else static int bits_to_user(unsigned long *bits, unsigned int maxbit, unsigned int maxlen, void __user *p, int compat) { int len = compat ? BITS_TO_LONGS_COMPAT(maxbit) * sizeof(compat_long_t) : BITS_TO_LONGS(maxbit) * sizeof(long); if (len > maxlen) len = maxlen; return copy_to_user(p, bits, len) ? -EFAULT : len; } #endif /* __BIG_ENDIAN */ #else static int bits_to_user(unsigned long *bits, unsigned int maxbit, unsigned int maxlen, void __user *p, int compat) { int len = BITS_TO_LONGS(maxbit) * sizeof(long); if (len > maxlen) len = maxlen; return copy_to_user(p, bits, len) ? -EFAULT : len; } #endif /* CONFIG_COMPAT */ static int str_to_user(const char *str, unsigned int maxlen, void __user *p) { int len; if (!str) return -ENOENT; len = strlen(str) + 1; if (len > maxlen) len = maxlen; return copy_to_user(p, str, len) ? -EFAULT : len; } static int handle_eviocgbit(struct input_dev *dev, unsigned int type, unsigned int size, void __user *p, int compat_mode) { unsigned long *bits; int len; switch (type) { case 0: bits = dev->evbit; len = EV_MAX; break; case EV_KEY: bits = dev->keybit; len = KEY_MAX; break; case EV_REL: bits = dev->relbit; len = REL_MAX; break; case EV_ABS: bits = dev->absbit; len = ABS_MAX; break; case EV_MSC: bits = dev->mscbit; len = MSC_MAX; break; case EV_LED: bits = dev->ledbit; len = LED_MAX; break; case EV_SND: bits = dev->sndbit; len = SND_MAX; break; case EV_FF: bits = dev->ffbit; len = FF_MAX; break; case EV_SW: bits = dev->swbit; len = SW_MAX; break; default: return -EINVAL; } return bits_to_user(bits, len, size, p, compat_mode); } static int evdev_handle_get_keycode(struct input_dev *dev, void __user *p) { struct input_keymap_entry ke = { .len = sizeof(unsigned int), .flags = 0, }; int __user *ip = (int __user *)p; int error; /* legacy case */ if (copy_from_user(ke.scancode, p, sizeof(unsigned int))) return -EFAULT; error = input_get_keycode(dev, &ke); if (error) return error; if (put_user(ke.keycode, ip + 1)) return -EFAULT; return 0; } static int evdev_handle_get_keycode_v2(struct input_dev *dev, void __user *p) { struct input_keymap_entry ke; int error; if (copy_from_user(&ke, p, sizeof(ke))) return -EFAULT; error = input_get_keycode(dev, &ke); if (error) return error; if (copy_to_user(p, &ke, sizeof(ke))) return -EFAULT; return 0; } static int evdev_handle_set_keycode(struct input_dev *dev, void __user *p) { struct input_keymap_entry ke = { .len = sizeof(unsigned int), .flags = 0, }; int __user *ip = (int __user *)p; if (copy_from_user(ke.scancode, p, sizeof(unsigned int))) return -EFAULT; if (get_user(ke.keycode, ip + 1)) return -EFAULT; return input_set_keycode(dev, &ke); } static int evdev_handle_set_keycode_v2(struct input_dev *dev, void __user *p) { struct input_keymap_entry ke; if (copy_from_user(&ke, p, sizeof(ke))) return -EFAULT; if (ke.len > sizeof(ke.scancode)) return -EINVAL; return input_set_keycode(dev, &ke); } /* * If we transfer state to the user, we should flush all pending events * of the same type from the client's queue. Otherwise, they might end up * with duplicate events, which can screw up client's state tracking. * If bits_to_user fails after flushing the queue, we queue a SYN_DROPPED * event so user-space will notice missing events. * * LOCKING: * We need to take event_lock before buffer_lock to avoid dead-locks. But we * need the even_lock only to guarantee consistent state. We can safely release * it while flushing the queue. This allows input-core to handle filters while * we flush the queue. */ static int evdev_handle_get_val(struct evdev_client *client, struct input_dev *dev, unsigned int type, unsigned long *bits, unsigned int maxbit, unsigned int maxlen, void __user *p, int compat) { int ret; unsigned long *mem; size_t len; len = BITS_TO_LONGS(maxbit) * sizeof(unsigned long); mem = kmalloc(len, GFP_KERNEL); if (!mem) return -ENOMEM; spin_lock_irq(&dev->event_lock); spin_lock(&client->buffer_lock); memcpy(mem, bits, len); spin_unlock(&dev->event_lock); __evdev_flush_queue(client, type); spin_unlock_irq(&client->buffer_lock); ret = bits_to_user(mem, maxbit, maxlen, p, compat); if (ret < 0) evdev_queue_syn_dropped(client); kfree(mem); return ret; } static int evdev_handle_mt_request(struct input_dev *dev, unsigned int size, int __user *ip) { const struct input_mt *mt = dev->mt; unsigned int code; int max_slots; int i; if (get_user(code, &ip[0])) return -EFAULT; if (!mt || !input_is_mt_value(code)) return -EINVAL; max_slots = (size - sizeof(__u32)) / sizeof(__s32); for (i = 0; i < mt->num_slots && i < max_slots; i++) { int value = input_mt_get_value(&mt->slots[i], code); if (put_user(value, &ip[1 + i])) return -EFAULT; } return 0; } static int evdev_revoke(struct evdev *evdev, struct evdev_client *client, struct file *file) { client->revoked = true; evdev_ungrab(evdev, client); input_flush_device(&evdev->handle, file); wake_up_interruptible(&evdev->wait); return 0; } static long evdev_do_ioctl(struct file *file, unsigned int cmd, void __user *p, int compat_mode) { struct evdev_client *client = file->private_data; struct evdev *evdev = client->evdev; struct input_dev *dev = evdev->handle.dev; struct input_absinfo abs; struct ff_effect effect; int __user *ip = (int __user *)p; unsigned int i, t, u, v; unsigned int size; int error; /* First we check for fixed-length commands */ switch (cmd) { case EVIOCGVERSION: return put_user(EV_VERSION, ip); case EVIOCGID: if (copy_to_user(p, &dev->id, sizeof(struct input_id))) return -EFAULT; return 0; case EVIOCGREP: if (!test_bit(EV_REP, dev->evbit)) return -ENOSYS; if (put_user(dev->rep[REP_DELAY], ip)) return -EFAULT; if (put_user(dev->rep[REP_PERIOD], ip + 1)) return -EFAULT; return 0; case EVIOCSREP: if (!test_bit(EV_REP, dev->evbit)) return -ENOSYS; if (get_user(u, ip)) return -EFAULT; if (get_user(v, ip + 1)) return -EFAULT; input_inject_event(&evdev->handle, EV_REP, REP_DELAY, u); input_inject_event(&evdev->handle, EV_REP, REP_PERIOD, v); return 0; case EVIOCRMFF: return input_ff_erase(dev, (int)(unsigned long) p, file); case EVIOCGEFFECTS: i = test_bit(EV_FF, dev->evbit) ? dev->ff->max_effects : 0; if (put_user(i, ip)) return -EFAULT; return 0; case EVIOCGRAB: if (p) return evdev_grab(evdev, client); else return evdev_ungrab(evdev, client); case EVIOCREVOKE: if (p) return -EINVAL; else return evdev_revoke(evdev, client, file); case EVIOCSCLOCKID: if (copy_from_user(&i, p, sizeof(unsigned int))) return -EFAULT; return evdev_set_clk_type(client, i); case EVIOCGKEYCODE: return evdev_handle_get_keycode(dev, p); case EVIOCSKEYCODE: return evdev_handle_set_keycode(dev, p); case EVIOCGKEYCODE_V2: return evdev_handle_get_keycode_v2(dev, p); case EVIOCSKEYCODE_V2: return evdev_handle_set_keycode_v2(dev, p); } size = _IOC_SIZE(cmd); /* Now check variable-length commands */ #define EVIOC_MASK_SIZE(nr) ((nr) & ~(_IOC_SIZEMASK << _IOC_SIZESHIFT)) switch (EVIOC_MASK_SIZE(cmd)) { case EVIOCGPROP(0): return bits_to_user(dev->propbit, INPUT_PROP_MAX, size, p, compat_mode); case EVIOCGMTSLOTS(0): return evdev_handle_mt_request(dev, size, ip); case EVIOCGKEY(0): return evdev_handle_get_val(client, dev, EV_KEY, dev->key, KEY_MAX, size, p, compat_mode); case EVIOCGLED(0): return evdev_handle_get_val(client, dev, EV_LED, dev->led, LED_MAX, size, p, compat_mode); case EVIOCGSND(0): return evdev_handle_get_val(client, dev, EV_SND, dev->snd, SND_MAX, size, p, compat_mode); case EVIOCGSW(0): return evdev_handle_get_val(client, dev, EV_SW, dev->sw, SW_MAX, size, p, compat_mode); case EVIOCGNAME(0): return str_to_user(dev->name, size, p); case EVIOCGPHYS(0): return str_to_user(dev->phys, size, p); case EVIOCGUNIQ(0): return str_to_user(dev->uniq, size, p); case EVIOC_MASK_SIZE(EVIOCSFF): if (input_ff_effect_from_user(p, size, &effect)) return -EFAULT; error = input_ff_upload(dev, &effect, file); if (error) return error; if (put_user(effect.id, &(((struct ff_effect __user *)p)->id))) return -EFAULT; return 0; } /* Multi-number variable-length handlers */ if (_IOC_TYPE(cmd) != 'E') return -EINVAL; if (_IOC_DIR(cmd) == _IOC_READ) { if ((_IOC_NR(cmd) & ~EV_MAX) == _IOC_NR(EVIOCGBIT(0, 0))) return handle_eviocgbit(dev, _IOC_NR(cmd) & EV_MAX, size, p, compat_mode); if ((_IOC_NR(cmd) & ~ABS_MAX) == _IOC_NR(EVIOCGABS(0))) { if (!dev->absinfo) return -EINVAL; t = _IOC_NR(cmd) & ABS_MAX; abs = dev->absinfo[t]; if (copy_to_user(p, &abs, min_t(size_t, size, sizeof(struct input_absinfo)))) return -EFAULT; return 0; } } if (_IOC_DIR(cmd) == _IOC_WRITE) { if ((_IOC_NR(cmd) & ~ABS_MAX) == _IOC_NR(EVIOCSABS(0))) { if (!dev->absinfo) return -EINVAL; t = _IOC_NR(cmd) & ABS_MAX; if (copy_from_user(&abs, p, min_t(size_t, size, sizeof(struct input_absinfo)))) return -EFAULT; if (size < sizeof(struct input_absinfo)) abs.resolution = 0; /* We can't change number of reserved MT slots */ if (t == ABS_MT_SLOT) return -EINVAL; /* * Take event lock to ensure that we are not * changing device parameters in the middle * of event. */ spin_lock_irq(&dev->event_lock); dev->absinfo[t] = abs; spin_unlock_irq(&dev->event_lock); return 0; } } return -EINVAL; } static long evdev_ioctl_handler(struct file *file, unsigned int cmd, void __user *p, int compat_mode) { struct evdev_client *client = file->private_data; struct evdev *evdev = client->evdev; int retval; retval = mutex_lock_interruptible(&evdev->mutex); if (retval) return retval; if (!evdev->exist || client->revoked) { retval = -ENODEV; goto out; } retval = evdev_do_ioctl(file, cmd, p, compat_mode); out: mutex_unlock(&evdev->mutex); return retval; } static long evdev_ioctl(struct file *file, unsigned int cmd, unsigned long arg) { return evdev_ioctl_handler(file, cmd, (void __user *)arg, 0); } #ifdef CONFIG_COMPAT static long evdev_ioctl_compat(struct file *file, unsigned int cmd, unsigned long arg) { return evdev_ioctl_handler(file, cmd, compat_ptr(arg), 1); } #endif static const struct file_operations evdev_fops = { .owner = THIS_MODULE, .read = evdev_read, .write = evdev_write, .poll = evdev_poll, .open = evdev_open, .release = evdev_release, .unlocked_ioctl = evdev_ioctl, #ifdef CONFIG_COMPAT .compat_ioctl = evdev_ioctl_compat, #endif .fasync = evdev_fasync, .flush = evdev_flush, .llseek = no_llseek, }; /* * Mark device non-existent. This disables writes, ioctls and * prevents new users from opening the device. Already posted * blocking reads will stay, however new ones will fail. */ static void evdev_mark_dead(struct evdev *evdev) { mutex_lock(&evdev->mutex); evdev->exist = false; mutex_unlock(&evdev->mutex); } static void evdev_cleanup(struct evdev *evdev) { struct input_handle *handle = &evdev->handle; evdev_mark_dead(evdev); evdev_hangup(evdev); cdev_del(&evdev->cdev); /* evdev is marked dead so no one else accesses evdev->open */ if (evdev->open) { input_flush_device(handle, NULL); input_close_device(handle); } } /* * Create new evdev device. Note that input core serializes calls * to connect and disconnect. */ static int evdev_connect(struct input_handler *handler, struct input_dev *dev, const struct input_device_id *id) { struct evdev *evdev; int minor; int dev_no; int error; minor = input_get_new_minor(EVDEV_MINOR_BASE, EVDEV_MINORS, true); if (minor < 0) { error = minor; pr_err("failed to reserve new minor: %d\n", error); return error; } evdev = kzalloc(sizeof(struct evdev), GFP_KERNEL); if (!evdev) { error = -ENOMEM; goto err_free_minor; } INIT_LIST_HEAD(&evdev->client_list); spin_lock_init(&evdev->client_lock); mutex_init(&evdev->mutex); init_waitqueue_head(&evdev->wait); evdev->exist = true; dev_no = minor; /* Normalize device number if it falls into legacy range */ if (dev_no < EVDEV_MINOR_BASE + EVDEV_MINORS) dev_no -= EVDEV_MINOR_BASE; dev_set_name(&evdev->dev, "event%d", dev_no); evdev->handle.dev = input_get_device(dev); evdev->handle.name = dev_name(&evdev->dev); evdev->handle.handler = handler; evdev->handle.private = evdev; evdev->dev.devt = MKDEV(INPUT_MAJOR, minor); evdev->dev.class = &input_class; evdev->dev.parent = &dev->dev; evdev->dev.release = evdev_free; device_initialize(&evdev->dev); error = input_register_handle(&evdev->handle); if (error) goto err_free_evdev; cdev_init(&evdev->cdev, &evdev_fops); evdev->cdev.kobj.parent = &evdev->dev.kobj; error = cdev_add(&evdev->cdev, evdev->dev.devt, 1); if (error) goto err_unregister_handle; error = device_add(&evdev->dev); if (error) goto err_cleanup_evdev; return 0; err_cleanup_evdev: evdev_cleanup(evdev); err_unregister_handle: input_unregister_handle(&evdev->handle); err_free_evdev: put_device(&evdev->dev); err_free_minor: input_free_minor(minor); return error; } static void evdev_disconnect(struct input_handle *handle) { struct evdev *evdev = handle->private; device_del(&evdev->dev); evdev_cleanup(evdev); input_free_minor(MINOR(evdev->dev.devt)); input_unregister_handle(handle); put_device(&evdev->dev); } static const struct input_device_id evdev_ids[] = { { .driver_info = 1 }, /* Matches all devices */ { }, /* Terminating zero entry */ }; MODULE_DEVICE_TABLE(input, evdev_ids); static struct input_handler evdev_handler = { .event = evdev_event, .events = evdev_events, .connect = evdev_connect, .disconnect = evdev_disconnect, .legacy_minors = true, .minor = EVDEV_MINOR_BASE, .name = "evdev", .id_table = evdev_ids, }; static int __init evdev_init(void) { return input_register_handler(&evdev_handler); } static void __exit evdev_exit(void) { input_unregister_handler(&evdev_handler); } module_init(evdev_init); module_exit(evdev_exit); MODULE_AUTHOR("Vojtech Pavlik <[email protected]>"); MODULE_DESCRIPTION("Input driver event char devices"); MODULE_LICENSE("GPL");
{ "pile_set_name": "Github" }
/*! ***************************************************************************** Copyright (c) Microsoft Corporation. All rights reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE, MERCHANTABLITY OR NON-INFRINGEMENT. See the Apache Version 2.0 License for specific language governing permissions and limitations under the License. ***************************************************************************** */ /// <reference no-default-lib="true"/> interface BigInt { /** * Returns a string representation of an object. * @param radix Specifies a radix for converting numeric values to strings. */ toString(radix?: number): string; /** Returns a string representation appropriate to the host environment's current locale. */ toLocaleString(): string; /** Returns the primitive value of the specified object. */ valueOf(): bigint; readonly [Symbol.toStringTag]: "BigInt"; } interface BigIntConstructor { (value?: any): bigint; readonly prototype: BigInt; /** * Interprets the low bits of a BigInt as a 2's-complement signed integer. * All higher bits are discarded. * @param bits The number of low bits to use * @param int The BigInt whose bits to extract */ asIntN(bits: number, int: bigint): bigint; /** * Interprets the low bits of a BigInt as an unsigned integer. * All higher bits are discarded. * @param bits The number of low bits to use * @param int The BigInt whose bits to extract */ asUintN(bits: number, int: bigint): bigint; } declare var BigInt: BigIntConstructor; /** * A typed array of 64-bit signed integer values. The contents are initialized to 0. If the * requested number of bytes could not be allocated, an exception is raised. */ interface BigInt64Array { /** The size in bytes of each element in the array. */ readonly BYTES_PER_ELEMENT: number; /** The ArrayBuffer instance referenced by the array. */ readonly buffer: ArrayBufferLike; /** The length in bytes of the array. */ readonly byteLength: number; /** The offset in bytes of the array. */ readonly byteOffset: number; /** * Returns the this object after copying a section of the array identified by start and end * to the same array starting at position target * @param target If target is negative, it is treated as length+target where length is the * length of the array. * @param start If start is negative, it is treated as length+start. If end is negative, it * is treated as length+end. * @param end If not specified, length of the this object is used as its default value. */ copyWithin(target: number, start: number, end?: number): this; /** Yields index, value pairs for every entry in the array. */ entries(): IterableIterator<[number, bigint]>; /** * Determines whether all the members of an array satisfy the specified test. * @param predicate A function that accepts up to three arguments. The every method calls * the predicate function for each element in the array until the predicate returns false, * or until the end of the array. * @param thisArg An object to which the this keyword can refer in the predicate function. * If thisArg is omitted, undefined is used as the this value. */ every(predicate: (value: bigint, index: number, array: BigInt64Array) => boolean, thisArg?: any): boolean; /** * Returns the this object after filling the section identified by start and end with value * @param value value to fill array section with * @param start index to start filling the array at. If start is negative, it is treated as * length+start where length is the length of the array. * @param end index to stop filling the array at. If end is negative, it is treated as * length+end. */ fill(value: bigint, start?: number, end?: number): this; /** * Returns the elements of an array that meet the condition specified in a callback function. * @param predicate A function that accepts up to three arguments. The filter method calls * the predicate function one time for each element in the array. * @param thisArg An object to which the this keyword can refer in the predicate function. * If thisArg is omitted, undefined is used as the this value. */ filter(predicate: (value: bigint, index: number, array: BigInt64Array) => any, thisArg?: any): BigInt64Array; /** * Returns the value of the first element in the array where predicate is true, and undefined * otherwise. * @param predicate find calls predicate once for each element of the array, in ascending * order, until it finds one where predicate returns true. If such an element is found, find * immediately returns that element value. Otherwise, find returns undefined. * @param thisArg If provided, it will be used as the this value for each invocation of * predicate. If it is not provided, undefined is used instead. */ find(predicate: (value: bigint, index: number, array: BigInt64Array) => boolean, thisArg?: any): bigint | undefined; /** * Returns the index of the first element in the array where predicate is true, and -1 * otherwise. * @param predicate find calls predicate once for each element of the array, in ascending * order, until it finds one where predicate returns true. If such an element is found, * findIndex immediately returns that element index. Otherwise, findIndex returns -1. * @param thisArg If provided, it will be used as the this value for each invocation of * predicate. If it is not provided, undefined is used instead. */ findIndex(predicate: (value: bigint, index: number, array: BigInt64Array) => boolean, thisArg?: any): number; /** * Performs the specified action for each element in an array. * @param callbackfn A function that accepts up to three arguments. forEach calls the * callbackfn function one time for each element in the array. * @param thisArg An object to which the this keyword can refer in the callbackfn function. * If thisArg is omitted, undefined is used as the this value. */ forEach(callbackfn: (value: bigint, index: number, array: BigInt64Array) => void, thisArg?: any): void; /** * Determines whether an array includes a certain element, returning true or false as appropriate. * @param searchElement The element to search for. * @param fromIndex The position in this array at which to begin searching for searchElement. */ includes(searchElement: bigint, fromIndex?: number): boolean; /** * Returns the index of the first occurrence of a value in an array. * @param searchElement The value to locate in the array. * @param fromIndex The array index at which to begin the search. If fromIndex is omitted, the * search starts at index 0. */ indexOf(searchElement: bigint, fromIndex?: number): number; /** * Adds all the elements of an array separated by the specified separator string. * @param separator A string used to separate one element of an array from the next in the * resulting String. If omitted, the array elements are separated with a comma. */ join(separator?: string): string; /** Yields each index in the array. */ keys(): IterableIterator<number>; /** * Returns the index of the last occurrence of a value in an array. * @param searchElement The value to locate in the array. * @param fromIndex The array index at which to begin the search. If fromIndex is omitted, the * search starts at index 0. */ lastIndexOf(searchElement: bigint, fromIndex?: number): number; /** The length of the array. */ readonly length: number; /** * Calls a defined callback function on each element of an array, and returns an array that * contains the results. * @param callbackfn A function that accepts up to three arguments. The map method calls the * callbackfn function one time for each element in the array. * @param thisArg An object to which the this keyword can refer in the callbackfn function. * If thisArg is omitted, undefined is used as the this value. */ map(callbackfn: (value: bigint, index: number, array: BigInt64Array) => bigint, thisArg?: any): BigInt64Array; /** * Calls the specified callback function for all the elements in an array. The return value of * the callback function is the accumulated result, and is provided as an argument in the next * call to the callback function. * @param callbackfn A function that accepts up to four arguments. The reduce method calls the * callbackfn function one time for each element in the array. * @param initialValue If initialValue is specified, it is used as the initial value to start * the accumulation. The first call to the callbackfn function provides this value as an argument * instead of an array value. */ reduce(callbackfn: (previousValue: bigint, currentValue: bigint, currentIndex: number, array: BigInt64Array) => bigint): bigint; /** * Calls the specified callback function for all the elements in an array. The return value of * the callback function is the accumulated result, and is provided as an argument in the next * call to the callback function. * @param callbackfn A function that accepts up to four arguments. The reduce method calls the * callbackfn function one time for each element in the array. * @param initialValue If initialValue is specified, it is used as the initial value to start * the accumulation. The first call to the callbackfn function provides this value as an argument * instead of an array value. */ reduce<U>(callbackfn: (previousValue: U, currentValue: bigint, currentIndex: number, array: BigInt64Array) => U, initialValue: U): U; /** * Calls the specified callback function for all the elements in an array, in descending order. * The return value of the callback function is the accumulated result, and is provided as an * argument in the next call to the callback function. * @param callbackfn A function that accepts up to four arguments. The reduceRight method calls * the callbackfn function one time for each element in the array. * @param initialValue If initialValue is specified, it is used as the initial value to start * the accumulation. The first call to the callbackfn function provides this value as an * argument instead of an array value. */ reduceRight(callbackfn: (previousValue: bigint, currentValue: bigint, currentIndex: number, array: BigInt64Array) => bigint): bigint; /** * Calls the specified callback function for all the elements in an array, in descending order. * The return value of the callback function is the accumulated result, and is provided as an * argument in the next call to the callback function. * @param callbackfn A function that accepts up to four arguments. The reduceRight method calls * the callbackfn function one time for each element in the array. * @param initialValue If initialValue is specified, it is used as the initial value to start * the accumulation. The first call to the callbackfn function provides this value as an argument * instead of an array value. */ reduceRight<U>(callbackfn: (previousValue: U, currentValue: bigint, currentIndex: number, array: BigInt64Array) => U, initialValue: U): U; /** Reverses the elements in the array. */ reverse(): this; /** * Sets a value or an array of values. * @param array A typed or untyped array of values to set. * @param offset The index in the current array at which the values are to be written. */ set(array: ArrayLike<bigint>, offset?: number): void; /** * Returns a section of an array. * @param start The beginning of the specified portion of the array. * @param end The end of the specified portion of the array. */ slice(start?: number, end?: number): BigInt64Array; /** * Determines whether the specified callback function returns true for any element of an array. * @param predicate A function that accepts up to three arguments. The some method calls the * predicate function for each element in the array until the predicate returns true, or until * the end of the array. * @param thisArg An object to which the this keyword can refer in the predicate function. * If thisArg is omitted, undefined is used as the this value. */ some(predicate: (value: bigint, index: number, array: BigInt64Array) => boolean, thisArg?: any): boolean; /** * Sorts the array. * @param compareFn The function used to determine the order of the elements. If omitted, the elements are sorted in ascending order. */ sort(compareFn?: (a: bigint, b: bigint) => number | bigint): this; /** * Gets a new BigInt64Array view of the ArrayBuffer store for this array, referencing the elements * at begin, inclusive, up to end, exclusive. * @param begin The index of the beginning of the array. * @param end The index of the end of the array. */ subarray(begin?: number, end?: number): BigInt64Array; /** Converts the array to a string by using the current locale. */ toLocaleString(): string; /** Returns a string representation of the array. */ toString(): string; /** Returns the primitive value of the specified object. */ valueOf(): BigInt64Array; /** Yields each value in the array. */ values(): IterableIterator<bigint>; [Symbol.iterator](): IterableIterator<bigint>; readonly [Symbol.toStringTag]: "BigInt64Array"; [index: number]: bigint; } interface BigInt64ArrayConstructor { readonly prototype: BigInt64Array; new(length?: number): BigInt64Array; new(array: Iterable<bigint>): BigInt64Array; new(buffer: ArrayBufferLike, byteOffset?: number, length?: number): BigInt64Array; /** The size in bytes of each element in the array. */ readonly BYTES_PER_ELEMENT: number; /** * Returns a new array from a set of elements. * @param items A set of elements to include in the new array object. */ of(...items: bigint[]): BigInt64Array; /** * Creates an array from an array-like or iterable object. * @param arrayLike An array-like or iterable object to convert to an array. * @param mapfn A mapping function to call on every element of the array. * @param thisArg Value of 'this' used to invoke the mapfn. */ from(arrayLike: ArrayLike<bigint>): BigInt64Array; from<U>(arrayLike: ArrayLike<U>, mapfn: (v: U, k: number) => bigint, thisArg?: any): BigInt64Array; } declare var BigInt64Array: BigInt64ArrayConstructor; /** * A typed array of 64-bit unsigned integer values. The contents are initialized to 0. If the * requested number of bytes could not be allocated, an exception is raised. */ interface BigUint64Array { /** The size in bytes of each element in the array. */ readonly BYTES_PER_ELEMENT: number; /** The ArrayBuffer instance referenced by the array. */ readonly buffer: ArrayBufferLike; /** The length in bytes of the array. */ readonly byteLength: number; /** The offset in bytes of the array. */ readonly byteOffset: number; /** * Returns the this object after copying a section of the array identified by start and end * to the same array starting at position target * @param target If target is negative, it is treated as length+target where length is the * length of the array. * @param start If start is negative, it is treated as length+start. If end is negative, it * is treated as length+end. * @param end If not specified, length of the this object is used as its default value. */ copyWithin(target: number, start: number, end?: number): this; /** Yields index, value pairs for every entry in the array. */ entries(): IterableIterator<[number, bigint]>; /** * Determines whether all the members of an array satisfy the specified test. * @param predicate A function that accepts up to three arguments. The every method calls * the predicate function for each element in the array until the predicate returns false, * or until the end of the array. * @param thisArg An object to which the this keyword can refer in the predicate function. * If thisArg is omitted, undefined is used as the this value. */ every(predicate: (value: bigint, index: number, array: BigUint64Array) => boolean, thisArg?: any): boolean; /** * Returns the this object after filling the section identified by start and end with value * @param value value to fill array section with * @param start index to start filling the array at. If start is negative, it is treated as * length+start where length is the length of the array. * @param end index to stop filling the array at. If end is negative, it is treated as * length+end. */ fill(value: bigint, start?: number, end?: number): this; /** * Returns the elements of an array that meet the condition specified in a callback function. * @param predicate A function that accepts up to three arguments. The filter method calls * the predicate function one time for each element in the array. * @param thisArg An object to which the this keyword can refer in the predicate function. * If thisArg is omitted, undefined is used as the this value. */ filter(predicate: (value: bigint, index: number, array: BigUint64Array) => any, thisArg?: any): BigUint64Array; /** * Returns the value of the first element in the array where predicate is true, and undefined * otherwise. * @param predicate find calls predicate once for each element of the array, in ascending * order, until it finds one where predicate returns true. If such an element is found, find * immediately returns that element value. Otherwise, find returns undefined. * @param thisArg If provided, it will be used as the this value for each invocation of * predicate. If it is not provided, undefined is used instead. */ find(predicate: (value: bigint, index: number, array: BigUint64Array) => boolean, thisArg?: any): bigint | undefined; /** * Returns the index of the first element in the array where predicate is true, and -1 * otherwise. * @param predicate find calls predicate once for each element of the array, in ascending * order, until it finds one where predicate returns true. If such an element is found, * findIndex immediately returns that element index. Otherwise, findIndex returns -1. * @param thisArg If provided, it will be used as the this value for each invocation of * predicate. If it is not provided, undefined is used instead. */ findIndex(predicate: (value: bigint, index: number, array: BigUint64Array) => boolean, thisArg?: any): number; /** * Performs the specified action for each element in an array. * @param callbackfn A function that accepts up to three arguments. forEach calls the * callbackfn function one time for each element in the array. * @param thisArg An object to which the this keyword can refer in the callbackfn function. * If thisArg is omitted, undefined is used as the this value. */ forEach(callbackfn: (value: bigint, index: number, array: BigUint64Array) => void, thisArg?: any): void; /** * Determines whether an array includes a certain element, returning true or false as appropriate. * @param searchElement The element to search for. * @param fromIndex The position in this array at which to begin searching for searchElement. */ includes(searchElement: bigint, fromIndex?: number): boolean; /** * Returns the index of the first occurrence of a value in an array. * @param searchElement The value to locate in the array. * @param fromIndex The array index at which to begin the search. If fromIndex is omitted, the * search starts at index 0. */ indexOf(searchElement: bigint, fromIndex?: number): number; /** * Adds all the elements of an array separated by the specified separator string. * @param separator A string used to separate one element of an array from the next in the * resulting String. If omitted, the array elements are separated with a comma. */ join(separator?: string): string; /** Yields each index in the array. */ keys(): IterableIterator<number>; /** * Returns the index of the last occurrence of a value in an array. * @param searchElement The value to locate in the array. * @param fromIndex The array index at which to begin the search. If fromIndex is omitted, the * search starts at index 0. */ lastIndexOf(searchElement: bigint, fromIndex?: number): number; /** The length of the array. */ readonly length: number; /** * Calls a defined callback function on each element of an array, and returns an array that * contains the results. * @param callbackfn A function that accepts up to three arguments. The map method calls the * callbackfn function one time for each element in the array. * @param thisArg An object to which the this keyword can refer in the callbackfn function. * If thisArg is omitted, undefined is used as the this value. */ map(callbackfn: (value: bigint, index: number, array: BigUint64Array) => bigint, thisArg?: any): BigUint64Array; /** * Calls the specified callback function for all the elements in an array. The return value of * the callback function is the accumulated result, and is provided as an argument in the next * call to the callback function. * @param callbackfn A function that accepts up to four arguments. The reduce method calls the * callbackfn function one time for each element in the array. * @param initialValue If initialValue is specified, it is used as the initial value to start * the accumulation. The first call to the callbackfn function provides this value as an argument * instead of an array value. */ reduce(callbackfn: (previousValue: bigint, currentValue: bigint, currentIndex: number, array: BigUint64Array) => bigint): bigint; /** * Calls the specified callback function for all the elements in an array. The return value of * the callback function is the accumulated result, and is provided as an argument in the next * call to the callback function. * @param callbackfn A function that accepts up to four arguments. The reduce method calls the * callbackfn function one time for each element in the array. * @param initialValue If initialValue is specified, it is used as the initial value to start * the accumulation. The first call to the callbackfn function provides this value as an argument * instead of an array value. */ reduce<U>(callbackfn: (previousValue: U, currentValue: bigint, currentIndex: number, array: BigUint64Array) => U, initialValue: U): U; /** * Calls the specified callback function for all the elements in an array, in descending order. * The return value of the callback function is the accumulated result, and is provided as an * argument in the next call to the callback function. * @param callbackfn A function that accepts up to four arguments. The reduceRight method calls * the callbackfn function one time for each element in the array. * @param initialValue If initialValue is specified, it is used as the initial value to start * the accumulation. The first call to the callbackfn function provides this value as an * argument instead of an array value. */ reduceRight(callbackfn: (previousValue: bigint, currentValue: bigint, currentIndex: number, array: BigUint64Array) => bigint): bigint; /** * Calls the specified callback function for all the elements in an array, in descending order. * The return value of the callback function is the accumulated result, and is provided as an * argument in the next call to the callback function. * @param callbackfn A function that accepts up to four arguments. The reduceRight method calls * the callbackfn function one time for each element in the array. * @param initialValue If initialValue is specified, it is used as the initial value to start * the accumulation. The first call to the callbackfn function provides this value as an argument * instead of an array value. */ reduceRight<U>(callbackfn: (previousValue: U, currentValue: bigint, currentIndex: number, array: BigUint64Array) => U, initialValue: U): U; /** Reverses the elements in the array. */ reverse(): this; /** * Sets a value or an array of values. * @param array A typed or untyped array of values to set. * @param offset The index in the current array at which the values are to be written. */ set(array: ArrayLike<bigint>, offset?: number): void; /** * Returns a section of an array. * @param start The beginning of the specified portion of the array. * @param end The end of the specified portion of the array. */ slice(start?: number, end?: number): BigUint64Array; /** * Determines whether the specified callback function returns true for any element of an array. * @param predicate A function that accepts up to three arguments. The some method calls the * predicate function for each element in the array until the predicate returns true, or until * the end of the array. * @param thisArg An object to which the this keyword can refer in the predicate function. * If thisArg is omitted, undefined is used as the this value. */ some(predicate: (value: bigint, index: number, array: BigUint64Array) => boolean, thisArg?: any): boolean; /** * Sorts the array. * @param compareFn The function used to determine the order of the elements. If omitted, the elements are sorted in ascending order. */ sort(compareFn?: (a: bigint, b: bigint) => number | bigint): this; /** * Gets a new BigUint64Array view of the ArrayBuffer store for this array, referencing the elements * at begin, inclusive, up to end, exclusive. * @param begin The index of the beginning of the array. * @param end The index of the end of the array. */ subarray(begin?: number, end?: number): BigUint64Array; /** Converts the array to a string by using the current locale. */ toLocaleString(): string; /** Returns a string representation of the array. */ toString(): string; /** Returns the primitive value of the specified object. */ valueOf(): BigUint64Array; /** Yields each value in the array. */ values(): IterableIterator<bigint>; [Symbol.iterator](): IterableIterator<bigint>; readonly [Symbol.toStringTag]: "BigUint64Array"; [index: number]: bigint; } interface BigUint64ArrayConstructor { readonly prototype: BigUint64Array; new(length?: number): BigUint64Array; new(array: Iterable<bigint>): BigUint64Array; new(buffer: ArrayBufferLike, byteOffset?: number, length?: number): BigUint64Array; /** The size in bytes of each element in the array. */ readonly BYTES_PER_ELEMENT: number; /** * Returns a new array from a set of elements. * @param items A set of elements to include in the new array object. */ of(...items: bigint[]): BigUint64Array; /** * Creates an array from an array-like or iterable object. * @param arrayLike An array-like or iterable object to convert to an array. * @param mapfn A mapping function to call on every element of the array. * @param thisArg Value of 'this' used to invoke the mapfn. */ from(arrayLike: ArrayLike<bigint>): BigUint64Array; from<U>(arrayLike: ArrayLike<U>, mapfn: (v: U, k: number) => bigint, thisArg?: any): BigUint64Array; } declare var BigUint64Array: BigUint64ArrayConstructor; interface DataView { /** * Gets the BigInt64 value at the specified byte offset from the start of the view. There is * no alignment constraint; multi-byte values may be fetched from any offset. * @param byteOffset The place in the buffer at which the value should be retrieved. */ getBigInt64(byteOffset: number, littleEndian?: boolean): bigint; /** * Gets the BigUint64 value at the specified byte offset from the start of the view. There is * no alignment constraint; multi-byte values may be fetched from any offset. * @param byteOffset The place in the buffer at which the value should be retrieved. */ getBigUint64(byteOffset: number, littleEndian?: boolean): bigint; /** * Stores a BigInt64 value at the specified byte offset from the start of the view. * @param byteOffset The place in the buffer at which the value should be set. * @param value The value to set. * @param littleEndian If false or undefined, a big-endian value should be written, * otherwise a little-endian value should be written. */ setBigInt64(byteOffset: number, value: bigint, littleEndian?: boolean): void; /** * Stores a BigUint64 value at the specified byte offset from the start of the view. * @param byteOffset The place in the buffer at which the value should be set. * @param value The value to set. * @param littleEndian If false or undefined, a big-endian value should be written, * otherwise a little-endian value should be written. */ setBigUint64(byteOffset: number, value: bigint, littleEndian?: boolean): void; }
{ "pile_set_name": "Github" }
//! moment.js locale configuration //! locale : Polish [pl] //! author : Rafal Hirsz : https://github.com/evoL ;(function (global, factory) { typeof exports === 'object' && typeof module !== 'undefined' && typeof require === 'function' ? factory(require('../moment')) : typeof define === 'function' && define.amd ? define(['../moment'], factory) : factory(global.moment) }(this, function (moment) { 'use strict'; var monthsNominative = 'styczeń_luty_marzec_kwiecień_maj_czerwiec_lipiec_sierpień_wrzesień_październik_listopad_grudzień'.split('_'), monthsSubjective = 'stycznia_lutego_marca_kwietnia_maja_czerwca_lipca_sierpnia_września_października_listopada_grudnia'.split('_'); function plural(n) { return (n % 10 < 5) && (n % 10 > 1) && ((~~(n / 10) % 10) !== 1); } function translate(number, withoutSuffix, key) { var result = number + ' '; switch (key) { case 'm': return withoutSuffix ? 'minuta' : 'minutę'; case 'mm': return result + (plural(number) ? 'minuty' : 'minut'); case 'h': return withoutSuffix ? 'godzina' : 'godzinę'; case 'hh': return result + (plural(number) ? 'godziny' : 'godzin'); case 'MM': return result + (plural(number) ? 'miesiące' : 'miesięcy'); case 'yy': return result + (plural(number) ? 'lata' : 'lat'); } } var pl = moment.defineLocale('pl', { months : function (momentToFormat, format) { if (format === '') { // Hack: if format empty we know this is used to generate // RegExp by moment. Give then back both valid forms of months // in RegExp ready format. return '(' + monthsSubjective[momentToFormat.month()] + '|' + monthsNominative[momentToFormat.month()] + ')'; } else if (/D MMMM/.test(format)) { return monthsSubjective[momentToFormat.month()]; } else { return monthsNominative[momentToFormat.month()]; } }, monthsShort : 'sty_lut_mar_kwi_maj_cze_lip_sie_wrz_paź_lis_gru'.split('_'), weekdays : 'niedziela_poniedziałek_wtorek_środa_czwartek_piątek_sobota'.split('_'), weekdaysShort : 'nie_pon_wt_śr_czw_pt_sb'.split('_'), weekdaysMin : 'Nd_Pn_Wt_Śr_Cz_Pt_So'.split('_'), longDateFormat : { LT : 'HH:mm', LTS : 'HH:mm:ss', L : 'DD.MM.YYYY', LL : 'D MMMM YYYY', LLL : 'D MMMM YYYY HH:mm', LLLL : 'dddd, D MMMM YYYY HH:mm' }, calendar : { sameDay: '[Dziś o] LT', nextDay: '[Jutro o] LT', nextWeek: '[W] dddd [o] LT', lastDay: '[Wczoraj o] LT', lastWeek: function () { switch (this.day()) { case 0: return '[W zeszłą niedzielę o] LT'; case 3: return '[W zeszłą środę o] LT'; case 6: return '[W zeszłą sobotę o] LT'; default: return '[W zeszły] dddd [o] LT'; } }, sameElse: 'L' }, relativeTime : { future : 'za %s', past : '%s temu', s : 'kilka sekund', m : translate, mm : translate, h : translate, hh : translate, d : '1 dzień', dd : '%d dni', M : 'miesiąc', MM : translate, y : 'rok', yy : translate }, ordinalParse: /\d{1,2}\./, ordinal : '%d.', week : { dow : 1, // Monday is the first day of the week. doy : 4 // The week that contains Jan 4th is the first week of the year. } }); return pl; }));
{ "pile_set_name": "Github" }
package com.android.internal.textservice; import android.os.Binder; import android.os.Bundle; import android.os.IBinder; import android.os.IInterface; import android.os.Parcel; import android.os.RemoteException; import android.view.textservice.SpellCheckerInfo; import android.view.textservice.SpellCheckerSubtype; import com.android.internal.textservice.ISpellCheckerSessionListener; import com.android.internal.textservice.ITextServicesSessionListener; public interface ITextServicesManager extends IInterface { void finishSpellCheckerService(int i, ISpellCheckerSessionListener iSpellCheckerSessionListener) throws RemoteException; SpellCheckerInfo getCurrentSpellChecker(int i, String str) throws RemoteException; SpellCheckerSubtype getCurrentSpellCheckerSubtype(int i, boolean z) throws RemoteException; SpellCheckerInfo[] getEnabledSpellCheckers(int i) throws RemoteException; void getSpellCheckerService(int i, String str, String str2, ITextServicesSessionListener iTextServicesSessionListener, ISpellCheckerSessionListener iSpellCheckerSessionListener, Bundle bundle) throws RemoteException; boolean isSpellCheckerEnabled(int i) throws RemoteException; public static class Default implements ITextServicesManager { @Override // com.android.internal.textservice.ITextServicesManager public SpellCheckerInfo getCurrentSpellChecker(int userId, String locale) throws RemoteException { return null; } @Override // com.android.internal.textservice.ITextServicesManager public SpellCheckerSubtype getCurrentSpellCheckerSubtype(int userId, boolean allowImplicitlySelectedSubtype) throws RemoteException { return null; } @Override // com.android.internal.textservice.ITextServicesManager public void getSpellCheckerService(int userId, String sciId, String locale, ITextServicesSessionListener tsListener, ISpellCheckerSessionListener scListener, Bundle bundle) throws RemoteException { } @Override // com.android.internal.textservice.ITextServicesManager public void finishSpellCheckerService(int userId, ISpellCheckerSessionListener listener) throws RemoteException { } @Override // com.android.internal.textservice.ITextServicesManager public boolean isSpellCheckerEnabled(int userId) throws RemoteException { return false; } @Override // com.android.internal.textservice.ITextServicesManager public SpellCheckerInfo[] getEnabledSpellCheckers(int userId) throws RemoteException { return null; } @Override // android.os.IInterface public IBinder asBinder() { return null; } } public static abstract class Stub extends Binder implements ITextServicesManager { private static final String DESCRIPTOR = "com.android.internal.textservice.ITextServicesManager"; static final int TRANSACTION_finishSpellCheckerService = 4; static final int TRANSACTION_getCurrentSpellChecker = 1; static final int TRANSACTION_getCurrentSpellCheckerSubtype = 2; static final int TRANSACTION_getEnabledSpellCheckers = 6; static final int TRANSACTION_getSpellCheckerService = 3; static final int TRANSACTION_isSpellCheckerEnabled = 5; public Stub() { attachInterface(this, DESCRIPTOR); } public static ITextServicesManager asInterface(IBinder obj) { if (obj == null) { return null; } IInterface iin = obj.queryLocalInterface(DESCRIPTOR); if (iin == null || !(iin instanceof ITextServicesManager)) { return new Proxy(obj); } return (ITextServicesManager) iin; } @Override // android.os.IInterface public IBinder asBinder() { return this; } public static String getDefaultTransactionName(int transactionCode) { switch (transactionCode) { case 1: return "getCurrentSpellChecker"; case 2: return "getCurrentSpellCheckerSubtype"; case 3: return "getSpellCheckerService"; case 4: return "finishSpellCheckerService"; case 5: return "isSpellCheckerEnabled"; case 6: return "getEnabledSpellCheckers"; default: return null; } } @Override // android.os.Binder public String getTransactionName(int transactionCode) { return getDefaultTransactionName(transactionCode); } @Override // android.os.Binder public boolean onTransact(int code, Parcel data, Parcel reply, int flags) throws RemoteException { Bundle _arg5; if (code != 1598968902) { switch (code) { case 1: data.enforceInterface(DESCRIPTOR); SpellCheckerInfo _result = getCurrentSpellChecker(data.readInt(), data.readString()); reply.writeNoException(); if (_result != null) { reply.writeInt(1); _result.writeToParcel(reply, 1); } else { reply.writeInt(0); } return true; case 2: data.enforceInterface(DESCRIPTOR); SpellCheckerSubtype _result2 = getCurrentSpellCheckerSubtype(data.readInt(), data.readInt() != 0); reply.writeNoException(); if (_result2 != null) { reply.writeInt(1); _result2.writeToParcel(reply, 1); } else { reply.writeInt(0); } return true; case 3: data.enforceInterface(DESCRIPTOR); int _arg0 = data.readInt(); String _arg1 = data.readString(); String _arg2 = data.readString(); ITextServicesSessionListener _arg3 = ITextServicesSessionListener.Stub.asInterface(data.readStrongBinder()); ISpellCheckerSessionListener _arg4 = ISpellCheckerSessionListener.Stub.asInterface(data.readStrongBinder()); if (data.readInt() != 0) { _arg5 = Bundle.CREATOR.createFromParcel(data); } else { _arg5 = null; } getSpellCheckerService(_arg0, _arg1, _arg2, _arg3, _arg4, _arg5); return true; case 4: data.enforceInterface(DESCRIPTOR); finishSpellCheckerService(data.readInt(), ISpellCheckerSessionListener.Stub.asInterface(data.readStrongBinder())); return true; case 5: data.enforceInterface(DESCRIPTOR); boolean isSpellCheckerEnabled = isSpellCheckerEnabled(data.readInt()); reply.writeNoException(); reply.writeInt(isSpellCheckerEnabled ? 1 : 0); return true; case 6: data.enforceInterface(DESCRIPTOR); SpellCheckerInfo[] _result3 = getEnabledSpellCheckers(data.readInt()); reply.writeNoException(); reply.writeTypedArray(_result3, 1); return true; default: return super.onTransact(code, data, reply, flags); } } else { reply.writeString(DESCRIPTOR); return true; } } /* access modifiers changed from: private */ public static class Proxy implements ITextServicesManager { public static ITextServicesManager sDefaultImpl; private IBinder mRemote; Proxy(IBinder remote) { this.mRemote = remote; } @Override // android.os.IInterface public IBinder asBinder() { return this.mRemote; } public String getInterfaceDescriptor() { return Stub.DESCRIPTOR; } @Override // com.android.internal.textservice.ITextServicesManager public SpellCheckerInfo getCurrentSpellChecker(int userId, String locale) throws RemoteException { SpellCheckerInfo _result; Parcel _data = Parcel.obtain(); Parcel _reply = Parcel.obtain(); try { _data.writeInterfaceToken(Stub.DESCRIPTOR); _data.writeInt(userId); _data.writeString(locale); if (!this.mRemote.transact(1, _data, _reply, 0) && Stub.getDefaultImpl() != null) { return Stub.getDefaultImpl().getCurrentSpellChecker(userId, locale); } _reply.readException(); if (_reply.readInt() != 0) { _result = SpellCheckerInfo.CREATOR.createFromParcel(_reply); } else { _result = null; } _reply.recycle(); _data.recycle(); return _result; } finally { _reply.recycle(); _data.recycle(); } } @Override // com.android.internal.textservice.ITextServicesManager public SpellCheckerSubtype getCurrentSpellCheckerSubtype(int userId, boolean allowImplicitlySelectedSubtype) throws RemoteException { SpellCheckerSubtype _result; Parcel _data = Parcel.obtain(); Parcel _reply = Parcel.obtain(); try { _data.writeInterfaceToken(Stub.DESCRIPTOR); _data.writeInt(userId); _data.writeInt(allowImplicitlySelectedSubtype ? 1 : 0); if (!this.mRemote.transact(2, _data, _reply, 0) && Stub.getDefaultImpl() != null) { return Stub.getDefaultImpl().getCurrentSpellCheckerSubtype(userId, allowImplicitlySelectedSubtype); } _reply.readException(); if (_reply.readInt() != 0) { _result = SpellCheckerSubtype.CREATOR.createFromParcel(_reply); } else { _result = null; } _reply.recycle(); _data.recycle(); return _result; } finally { _reply.recycle(); _data.recycle(); } } @Override // com.android.internal.textservice.ITextServicesManager public void getSpellCheckerService(int userId, String sciId, String locale, ITextServicesSessionListener tsListener, ISpellCheckerSessionListener scListener, Bundle bundle) throws RemoteException { Parcel _data = Parcel.obtain(); try { _data.writeInterfaceToken(Stub.DESCRIPTOR); try { _data.writeInt(userId); } catch (Throwable th) { th = th; _data.recycle(); throw th; } try { _data.writeString(sciId); try { _data.writeString(locale); _data.writeStrongBinder(tsListener != null ? tsListener.asBinder() : null); _data.writeStrongBinder(scListener != null ? scListener.asBinder() : null); if (bundle != null) { _data.writeInt(1); bundle.writeToParcel(_data, 0); } else { _data.writeInt(0); } try { if (this.mRemote.transact(3, _data, null, 1) || Stub.getDefaultImpl() == null) { _data.recycle(); return; } Stub.getDefaultImpl().getSpellCheckerService(userId, sciId, locale, tsListener, scListener, bundle); _data.recycle(); } catch (Throwable th2) { th = th2; _data.recycle(); throw th; } } catch (Throwable th3) { th = th3; _data.recycle(); throw th; } } catch (Throwable th4) { th = th4; _data.recycle(); throw th; } } catch (Throwable th5) { th = th5; _data.recycle(); throw th; } } @Override // com.android.internal.textservice.ITextServicesManager public void finishSpellCheckerService(int userId, ISpellCheckerSessionListener listener) throws RemoteException { Parcel _data = Parcel.obtain(); try { _data.writeInterfaceToken(Stub.DESCRIPTOR); _data.writeInt(userId); _data.writeStrongBinder(listener != null ? listener.asBinder() : null); if (this.mRemote.transact(4, _data, null, 1) || Stub.getDefaultImpl() == null) { _data.recycle(); } else { Stub.getDefaultImpl().finishSpellCheckerService(userId, listener); } } finally { _data.recycle(); } } @Override // com.android.internal.textservice.ITextServicesManager public boolean isSpellCheckerEnabled(int userId) throws RemoteException { Parcel _data = Parcel.obtain(); Parcel _reply = Parcel.obtain(); try { _data.writeInterfaceToken(Stub.DESCRIPTOR); _data.writeInt(userId); boolean _result = false; if (!this.mRemote.transact(5, _data, _reply, 0) && Stub.getDefaultImpl() != null) { return Stub.getDefaultImpl().isSpellCheckerEnabled(userId); } _reply.readException(); if (_reply.readInt() != 0) { _result = true; } _reply.recycle(); _data.recycle(); return _result; } finally { _reply.recycle(); _data.recycle(); } } @Override // com.android.internal.textservice.ITextServicesManager public SpellCheckerInfo[] getEnabledSpellCheckers(int userId) throws RemoteException { Parcel _data = Parcel.obtain(); Parcel _reply = Parcel.obtain(); try { _data.writeInterfaceToken(Stub.DESCRIPTOR); _data.writeInt(userId); if (!this.mRemote.transact(6, _data, _reply, 0) && Stub.getDefaultImpl() != null) { return Stub.getDefaultImpl().getEnabledSpellCheckers(userId); } _reply.readException(); SpellCheckerInfo[] _result = (SpellCheckerInfo[]) _reply.createTypedArray(SpellCheckerInfo.CREATOR); _reply.recycle(); _data.recycle(); return _result; } finally { _reply.recycle(); _data.recycle(); } } } public static boolean setDefaultImpl(ITextServicesManager impl) { if (Proxy.sDefaultImpl != null || impl == null) { return false; } Proxy.sDefaultImpl = impl; return true; } public static ITextServicesManager getDefaultImpl() { return Proxy.sDefaultImpl; } } }
{ "pile_set_name": "Github" }
/*---------------------------------------------------------------------- PuReMD - Purdue ReaxFF Molecular Dynamics Program Copyright (2010) Purdue University Hasan Metin Aktulga, [email protected] Joseph Fogarty, [email protected] Sagar Pandit, [email protected] Ananth Y Grama, [email protected] Please cite the related publication: H. M. Aktulga, J. C. Fogarty, S. A. Pandit, A. Y. Grama, "Parallel Reactive Molecular Dynamics: Numerical Methods and Algorithmic Techniques", Parallel Computing, in press. 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: <http://www.gnu.org/licenses/>. ----------------------------------------------------------------------*/ #ifndef __IO_TOOLS_H_ #define __IO_TOOLS_H_ #include "reaxc_types.h" int Init_Output_Files( reax_system*, control_params*, output_controls*, mpi_datatypes*, char* ); int Close_Output_Files( reax_system*, control_params*, output_controls*, mpi_datatypes* ); void Output_Results( reax_system*, control_params*, simulation_data*, reax_list**, output_controls*, mpi_datatypes* ); #endif
{ "pile_set_name": "Github" }
// Copyright 2009 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. package pflag import ( goflag "flag" "reflect" "strings" ) // flagValueWrapper implements pflag.Value around a flag.Value. The main // difference here is the addition of the Type method that returns a string // name of the type. As this is generally unknown, we approximate that with // reflection. type flagValueWrapper struct { inner goflag.Value flagType string } // We are just copying the boolFlag interface out of goflag as that is what // they use to decide if a flag should get "true" when no arg is given. type goBoolFlag interface { goflag.Value IsBoolFlag() bool } func wrapFlagValue(v goflag.Value) Value { // If the flag.Value happens to also be a pflag.Value, just use it directly. if pv, ok := v.(Value); ok { return pv } pv := &flagValueWrapper{ inner: v, } t := reflect.TypeOf(v) if t.Kind() == reflect.Interface || t.Kind() == reflect.Ptr { t = t.Elem() } pv.flagType = strings.TrimSuffix(t.Name(), "Value") return pv } func (v *flagValueWrapper) String() string { return v.inner.String() } func (v *flagValueWrapper) Set(s string) error { return v.inner.Set(s) } func (v *flagValueWrapper) Type() string { return v.flagType } // PFlagFromGoFlag will return a *pflag.Flag given a *flag.Flag // If the *flag.Flag.Name was a single character (ex: `v`) it will be accessiblei // with both `-v` and `--v` in flags. If the golang flag was more than a single // character (ex: `verbose`) it will only be accessible via `--verbose` func PFlagFromGoFlag(goflag *goflag.Flag) *Flag { // Remember the default value as a string; it won't change. flag := &Flag{ Name: goflag.Name, Usage: goflag.Usage, Value: wrapFlagValue(goflag.Value), // Looks like golang flags don't set DefValue correctly :-( //DefValue: goflag.DefValue, DefValue: goflag.Value.String(), } // Ex: if the golang flag was -v, allow both -v and --v to work if len(flag.Name) == 1 { flag.Shorthand = flag.Name } if fv, ok := goflag.Value.(goBoolFlag); ok && fv.IsBoolFlag() { flag.NoOptDefVal = "true" } return flag } // AddGoFlag will add the given *flag.Flag to the pflag.FlagSet func (f *FlagSet) AddGoFlag(goflag *goflag.Flag) { if f.Lookup(goflag.Name) != nil { return } newflag := PFlagFromGoFlag(goflag) f.AddFlag(newflag) } // AddGoFlagSet will add the given *flag.FlagSet to the pflag.FlagSet func (f *FlagSet) AddGoFlagSet(newSet *goflag.FlagSet) { if newSet == nil { return } newSet.VisitAll(func(goflag *goflag.Flag) { f.AddGoFlag(goflag) }) if f.addedGoFlagSets == nil { f.addedGoFlagSets = make([]*goflag.FlagSet, 0) } f.addedGoFlagSets = append(f.addedGoFlagSets, newSet) }
{ "pile_set_name": "Github" }
<?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE toolbar:toolbar PUBLIC "-//OpenOffice.org//DTD OfficeDocument 1.0//EN" "toolbar.dtd"> <!--*********************************************************** * * 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. * ***********************************************************--> <toolbar:toolbar xmlns:toolbar="http://openoffice.org/2001/toolbar" xmlns:xlink="http://www.w3.org/1999/xlink" toolbar:id="toolbar"> <toolbar:toolbaritem xlink:href=".uno:SpinButton" toolbar:style="radio auto"/> <toolbar:toolbaritem xlink:href=".uno:ScrollBar" toolbar:style="radio auto"/> <toolbar:toolbarbreak/> <toolbar:toolbaritem xlink:href=".uno:Imagebutton" toolbar:style="radio auto"/> <toolbar:toolbaritem xlink:href=".uno:ImageControl" toolbar:style="radio auto"/> <toolbar:toolbarbreak/> <toolbar:toolbaritem xlink:href=".uno:FileControl" toolbar:style="radio auto"/> <toolbar:toolbaritem xlink:href=".uno:DateField" toolbar:style="radio auto"/> <toolbar:toolbarbreak/> <toolbar:toolbaritem xlink:href=".uno:TimeField" toolbar:style="radio auto"/> <toolbar:toolbaritem xlink:href=".uno:NumericField" toolbar:style="radio auto"/> <toolbar:toolbarbreak/> <toolbar:toolbaritem xlink:href=".uno:CurrencyField" toolbar:style="radio auto"/> <toolbar:toolbaritem xlink:href=".uno:PatternField" toolbar:style="radio auto"/> <toolbar:toolbarbreak/> <toolbar:toolbaritem xlink:href=".uno:GroupBox" toolbar:style="radio auto"/> <toolbar:toolbaritem xlink:href=".uno:Grid" toolbar:style="radio auto"/> <toolbar:toolbarbreak/> <toolbar:toolbaritem xlink:href=".uno:NavigationBar"/> </toolbar:toolbar>
{ "pile_set_name": "Github" }
/////////////////////////////////////////////////////////////////////////////// // FILE: CSUXHub.h // PROJECT: Micro-Manager // SUBSYSTEM: DeviceAdapters //----------------------------------------------------------------------------- // DESCRIPTION: CSUX hub module. Required for operation of all // CSUX devices // // COPYRIGHT: University of California, San Francisco, 2006 // All rights reserved // // LICENSE: This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // License as published by the Free Software Foundation. // // You should have received a copy of the GNU Lesser General Public // License along with the source distribution; if not, write to // the Free Software Foundation, Inc., 59 Temple Place, Suite 330, // Boston, MA 02111-1307 USA // // This file 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. // // IN NO EVENT SHALL THE COPYRIGHT OWNER OR // CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, // INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES. // // AUTHOR: Nico Stuurman, [email protected], 02/02/2007 // // Based on NikonTE2000 controller adapter by Nenad Amodaj // // #ifndef _CSUXHUB_H_ #define _CSUXHUB_H_ #include <string> #include <deque> #include <map> #include "../../MMDevice/MMDevice.h" ///////////////////////////////////////////////////////////////////////// // Error codes // #define ERR_NOT_CONNECTED 10002 #define ERR_COMMAND_CANNOT_EXECUTE 10003 #define ERR_NEGATIVE_RESPONSE 10004 enum CommandMode { Sync = 0, Async }; class CSUXHub { public: CSUXHub(); ~CSUXHub(); void SetPort(const char* port) {port_ = port;} bool IsBusy(); void SetChannel(int channel) {ch_ = channel;}; void GetChannel(int& channel) {channel = ch_;}; int SetFilterWheelPosition(MM::Device& device, MM::Core& core, long wheelNr, long pos); int GetFilterWheelPosition(MM::Device& device, MM::Core& core, long wheelNr, long& pos); int SetFilterWheelSpeed(MM::Device& device, MM::Core& core, long wheelNr, long speed); int GetFilterWheelSpeed(MM::Device& device, MM::Core& core, long wheelNr, long& speed); int SetDichroicPosition(MM::Device& device, MM::Core& core, long dichroic); int GetDichroicPosition(MM::Device& device, MM::Core& core, long &dichroic); int SetShutterPosition(MM::Device& device, MM::Core& core, int pos); int GetShutterPosition(MM::Device& device, MM::Core& core, int& pos); int SetDriveSpeed(MM::Device& device, MM::Core& core, int pos); int GetDriveSpeed(MM::Device& device, MM::Core& core, long& pos); int GetMaxDriveSpeed(MM::Device& device, MM::Core& core, long& pos); int SetAutoAdjustDriveSpeed(MM::Device& device, MM::Core& core, double exposureMs); int RunDisk(MM::Device& device, MM::Core& core, bool run); int SetBrightFieldPort(MM::Device& device, MM::Core& core, int pos); int GetBrightFieldPort(MM::Device& device, MM::Core& core, int& pos); private: int ExecuteCommand(MM::Device& device, MM::Core& core, const char* command); int GetAcknowledgment(MM::Device& device, MM::Core& core); int Acknowledge(); int ParseResponse(const char* cmdId, std::string& value); void FetchSerialData(MM::Device& device, MM::Core& core); static const int RCV_BUF_LENGTH = 1024; char rcvBuf_[RCV_BUF_LENGTH]; char asynchRcvBuf_[RCV_BUF_LENGTH]; void ClearRcvBuf(); void ClearAllRcvBuf(MM::Device& device, MM::Core& core); int ch_; std::string port_; std::vector<char> answerBuf_; std::multimap<std::string, long> waitingCommands_; std::string commandMode_; bool driveSpeedBusy_; }; #endif // _CSUXHUB_H_
{ "pile_set_name": "Github" }
//------------------------------------------------------------------------------ // <copyright file="RegexRunner.cs" company="Microsoft"> // Copyright (c) Microsoft Corporation. All rights reserved. // </copyright> //------------------------------------------------------------------------------ // This RegexRunner class is a base class for compiled regex code. // Implementation notes: // // RegexRunner provides a common calling convention and a common // runtime environment for the interpreter and the compiled code. // // It provides the driver code that call's the subclass's Go() // method for either scanning or direct execution. // // It also maintains memory allocation for the backtracking stack, // the grouping stack and the longjump crawlstack, and provides // methods to push new subpattern match results into (or remove // backtracked results from) the Match instance. namespace MonoDevelop.Ide.Editor.Highlighting.RegexEngine { using System; using System.Text; using System.Collections; using System.Diagnostics; using System.ComponentModel; using System.Globalization; using MonoDevelop.Core.Text; /// <internalonly/> // #if !SILVERLIGHT [EditorBrowsable(EditorBrowsableState.Never)] #endif #if !SILVERLIGHT [Obsolete ("Old editor")] abstract class RegexRunner { #else abstract internal class RegexRunner { #endif protected internal int runtextbeg; // beginning of text to search protected internal int runtextend; // end of text to search protected internal int runtextstart; // starting point for search protected internal string runtext; // text to search protected internal int runtextpos; // current position in text protected internal int [] runtrack; // The backtracking stack. Opcodes use this to store data regarding protected internal int runtrackpos; // what they have matched and where to backtrack to. Each "frame" on // the stack takes the form of [CodePosition Data1 Data2...], where // CodePosition is the position of the current opcode and // the data values are all optional. The CodePosition can be negative, and // these values (also called "back2") are used by the BranchMark family of opcodes // to indicate whether they are backtracking after a successful or failed // match. // When we backtrack, we pop the CodePosition off the stack, set the current // instruction pointer to that code position, and mark the opcode // with a backtracking flag ("Back"). Each opcode then knows how to // handle its own data. protected internal int [] runstack; // This stack is used to track text positions across different opcodes. protected internal int runstackpos; // For example, in /(a*b)+/, the parentheses result in a SetMark/CaptureMark // pair. SetMark records the text position before we match a*b. Then // CaptureMark uses that position to figure out where the capture starts. // Opcodes which push onto this stack are always paired with other opcodes // which will pop the value from it later. A successful match should mean // that this stack is empty. protected internal int [] runcrawl; // The crawl stack is used to keep track of captures. Every time a group protected internal int runcrawlpos; // has a capture, we push its group number onto the runcrawl stack. In // the case of a balanced match, we push BOTH groups onto the stack. protected internal int runtrackcount; // count of states that may do backtracking protected internal Match runmatch; // result object protected internal Regex runregex; // regex object private Int32 timeout; // timeout in millisecs (needed for actual) private bool ignoreTimeout; private Int32 timeoutOccursAt; // GPaperin: We have determined this value in a series of experiments where x86 retail // builds (ono-lab-optimised) were run on different pattern/input pairs. Larger values // of TimeoutCheckFrequency did not tend to increase performance; smaller values // of TimeoutCheckFrequency tended to slow down the execution. private const int TimeoutCheckFrequency = 1000; private int timeoutChecksToSkip; protected internal RegexRunner() { } /* * Scans the string to find the first match. Uses the Match object * both to feed text in and as a place to store matches that come out. * * All the action is in the abstract Go() method defined by subclasses. Our * responsibility is to load up the class members (as done here) before * calling Go. * * < */ protected internal Match Scan(Regex regex, string text, int textbeg, int textend, int textstart, int prevlen, bool quick) { return Scan(regex, text, textbeg, textend, textstart, prevlen, quick, regex.MatchTimeout); } #if !SILVERLIGHT protected internal #else internal #endif Match Scan(Regex regex, string text, int textbeg, int textend, int textstart, int prevlen, bool quick, TimeSpan timeout) { int bump; int stoppos; bool initted = false; // We need to re-validate timeout here because Scan is historically protected and // thus there is a possibility it is called from user code: Regex.ValidateMatchTimeout(timeout); this.ignoreTimeout = (Regex.InfiniteMatchTimeout == timeout); this.timeout = this.ignoreTimeout ? (Int32) Regex.InfiniteMatchTimeout.TotalMilliseconds : (Int32) (timeout.TotalMilliseconds + 0.5); // Round runregex = regex; runtext = text; runtextbeg = textbeg; runtextend = textend; runtextstart = textstart; bump = runregex.RightToLeft ? -1 : 1; stoppos = runregex.RightToLeft ? runtextbeg : runtextend; runtextpos = textstart; // If previous match was empty or failed, advance by one before matching if (prevlen == 0) { if (runtextpos == stoppos) return Match.Empty; runtextpos += bump; } StartTimeoutWatch(); for (; ; ) { #if DBG if (runregex.Debug) { Debug.WriteLine(""); Debug.WriteLine("Search range: from " + runtextbeg.ToString(CultureInfo.InvariantCulture) + " to " + runtextend.ToString(CultureInfo.InvariantCulture)); Debug.WriteLine("Firstchar search starting at " + runtextpos.ToString(CultureInfo.InvariantCulture) + " stopping at " + stoppos.ToString(CultureInfo.InvariantCulture)); } #endif if (FindFirstChar()) { CheckTimeout(); if (!initted) { InitMatch(); initted = true; } #if DBG if (runregex.Debug) { Debug.WriteLine("Executing engine starting at " + runtextpos.ToString(CultureInfo.InvariantCulture)); Debug.WriteLine(""); } #endif Go(); if (runmatch._matchcount [0] > 0) { // < return TidyMatch(quick); } // reset state for another go runtrackpos = runtrack.Length; runstackpos = runstack.Length; runcrawlpos = runcrawl.Length; } // failure! if (runtextpos == stoppos) { TidyMatch(true); return Match.Empty; } // < // Bump by one and start again runtextpos += bump; } // We never get here } private void StartTimeoutWatch() { if (ignoreTimeout) return; timeoutChecksToSkip = TimeoutCheckFrequency; // We are using Environment.TickCount and not Timewatch for performance reasons. // Environment.TickCount is an int that cycles. We intentionally let timeoutOccursAt // overflow it will still stay ahead of Environment.TickCount for comparisons made // in DoCheckTimeout(): unchecked { timeoutOccursAt = Environment.TickCount + timeout; } } #if !SILVERLIGHT protected #else internal #endif void CheckTimeout() { if (ignoreTimeout) return; if (--timeoutChecksToSkip != 0) return; timeoutChecksToSkip = TimeoutCheckFrequency; DoCheckTimeout(); } private void DoCheckTimeout() { // Note that both, Environment.TickCount and timeoutOccursAt are ints and can overflow and become negative. // See the comment in StartTimeoutWatch(). int currentMillis = Environment.TickCount; if (currentMillis < timeoutOccursAt) return; if (0 > timeoutOccursAt && 0 < currentMillis) return; #if DBG if (runregex.Debug) { Debug.WriteLine(""); Debug.WriteLine("RegEx match timeout occurred!"); Debug.WriteLine("Specified timeout: " + TimeSpan.FromMilliseconds(timeout).ToString()); Debug.WriteLine("Timeout check frequency: " + TimeoutCheckFrequency); Debug.WriteLine("Search pattern: " + runregex.pattern); Debug.WriteLine("Input: " + runtext); Debug.WriteLine("About to throw RegexMatchTimeoutException."); } #endif throw new RegexMatchTimeoutException(runtext, runregex.pattern, TimeSpan.FromMilliseconds(timeout)); } /* * The responsibility of Go() is to run the regular expression at * runtextpos and call Capture() on all the captured subexpressions, * then to leave runtextpos at the ending position. It should leave * runtextpos where it started if there was no match. */ protected abstract void Go(); /* * The responsibility of FindFirstChar() is to advance runtextpos * until it is at the next position which is a candidate for the * beginning of a successful match. */ protected abstract bool FindFirstChar(); /* * InitTrackCount must initialize the runtrackcount field; this is * used to know how large the initial runtrack and runstack arrays * must be. */ protected abstract void InitTrackCount(); /* * Initializes all the data members that are used by Go() */ private void InitMatch() { // Use a hashtable'ed Match object if the capture numbers are sparse if (runmatch == null) { if (runregex.caps != null) runmatch = new MatchSparse(runregex, runregex.caps, runregex.capsize, runtext, runtextbeg, runtextend - runtextbeg, runtextstart); else runmatch = new Match (runregex, runregex.capsize, runtext, runtextbeg, runtextend - runtextbeg, runtextstart); } else { runmatch.Reset(runregex, runtext, runtextbeg, runtextend, runtextstart); } // note we test runcrawl, because it is the last one to be allocated // If there is an alloc failure in the middle of the three allocations, // we may still return to reuse this instance, and we want to behave // as if the allocations didn't occur. (we used to test _trackcount != 0) if (runcrawl != null) { runtrackpos = runtrack.Length; runstackpos = runstack.Length; runcrawlpos = runcrawl.Length; return; } InitTrackCount(); int tracksize = runtrackcount * 8; int stacksize = runtrackcount * 8; if (tracksize < 32) tracksize = 32; if (stacksize < 16) stacksize = 16; runtrack = new int [tracksize]; runtrackpos = tracksize; runstack = new int [stacksize]; runstackpos = stacksize; runcrawl = new int [32]; runcrawlpos = 32; } /* * Put match in its canonical form before returning it. */ private Match TidyMatch(bool quick) { if (!quick) { Match match = runmatch; runmatch = null; match.Tidy(runtextpos); return match; } else { // in quick mode, a successful match returns null, and // the allocated match object is left in the cache return null; } } /* * Called by the implemenation of Go() to increase the size of storage */ protected void EnsureStorage() { if (runstackpos < runtrackcount * 4) DoubleStack(); if (runtrackpos < runtrackcount * 4) DoubleTrack(); } /* * Called by the implemenation of Go() to decide whether the pos * at the specified index is a boundary or not. It's just not worth * emitting inline code for this logic. */ protected bool IsBoundary(int index, int startpos, int endpos) { return (index > startpos && RegexCharClass.IsWordChar(runtext [index - 1])) != (index < endpos && RegexCharClass.IsWordChar(runtext [index])); } protected bool IsECMABoundary(int index, int startpos, int endpos) { return (index > startpos && RegexCharClass.IsECMAWordChar(runtext [index - 1])) != (index < endpos && RegexCharClass.IsECMAWordChar(runtext [index])); } protected static bool CharInSet(char ch, String set, String category) { string charClass = RegexCharClass.ConvertOldStringsToClass(set, category); return RegexCharClass.CharInClass(ch, charClass); } protected static bool CharInClass(char ch, String charClass) { return RegexCharClass.CharInClass(ch, charClass); } /* * Called by the implemenation of Go() to increase the size of the * backtracking stack. */ protected void DoubleTrack() { int [] newtrack; newtrack = new int [runtrack.Length * 2]; System.Array.Copy(runtrack, 0, newtrack, runtrack.Length, runtrack.Length); runtrackpos += runtrack.Length; runtrack = newtrack; } /* * Called by the implemenation of Go() to increase the size of the * grouping stack. */ protected void DoubleStack() { int [] newstack; newstack = new int [runstack.Length * 2]; System.Array.Copy(runstack, 0, newstack, runstack.Length, runstack.Length); runstackpos += runstack.Length; runstack = newstack; } /* * Increases the size of the longjump unrolling stack. */ protected void DoubleCrawl() { int [] newcrawl; newcrawl = new int [runcrawl.Length * 2]; System.Array.Copy(runcrawl, 0, newcrawl, runcrawl.Length, runcrawl.Length); runcrawlpos += runcrawl.Length; runcrawl = newcrawl; } /* * Save a number on the longjump unrolling stack */ protected void Crawl(int i) { if (runcrawlpos == 0) DoubleCrawl(); runcrawl [--runcrawlpos] = i; } /* * Remove a number from the longjump unrolling stack */ protected int Popcrawl() { return runcrawl [runcrawlpos++]; } /* * Get the height of the stack */ protected int Crawlpos() { return runcrawl.Length - runcrawlpos; } /* * Called by Go() to capture a subexpression. Note that the * capnum used here has already been mapped to a non-sparse * index (by the code generator RegexWriter). */ protected void Capture(int capnum, int start, int end) { if (end < start) { int T; T = end; end = start; start = T; } Crawl(capnum); runmatch.AddMatch(capnum, start, end - start); } /* * Called by Go() to capture a subexpression. Note that the * capnum used here has already been mapped to a non-sparse * index (by the code generator RegexWriter). */ protected void TransferCapture(int capnum, int uncapnum, int start, int end) { int start2; int end2; // these are the two intervals that are cancelling each other if (end < start) { int T; T = end; end = start; start = T; } start2 = MatchIndex(uncapnum); end2 = start2 + MatchLength(uncapnum); // The new capture gets the innermost defined interval if (start >= end2) { end = start; start = end2; } else if (end <= start2) { start = start2; } else { if (end > end2) end = end2; if (start2 > start) start = start2; } Crawl(uncapnum); runmatch.BalanceMatch(uncapnum); if (capnum != -1) { Crawl(capnum); runmatch.AddMatch(capnum, start, end - start); } } /* * Called by Go() to revert the last capture */ protected void Uncapture() { int capnum = Popcrawl(); runmatch.RemoveMatch(capnum); } /* * Call out to runmatch to get around visibility issues */ protected bool IsMatched(int cap) { return runmatch.IsMatched(cap); } /* * Call out to runmatch to get around visibility issues */ protected int MatchIndex(int cap) { return runmatch.MatchIndex(cap); } /* * Call out to runmatch to get around visibility issues */ protected int MatchLength(int cap) { return runmatch.MatchLength(cap); } #if DBG /* * Dump the current state */ internal virtual void DumpState() { Debug.WriteLine("Text: " + TextposDescription()); Debug.WriteLine("Track: " + StackDescription(runtrack, runtrackpos)); Debug.WriteLine("Stack: " + StackDescription(runstack, runstackpos)); } internal static String StackDescription(int [] A, int Index) { StringBuilder Sb = new StringBuilder(); Sb.Append(A.Length - Index); Sb.Append('/'); Sb.Append(A.Length); if (Sb.Length < 8) Sb.Append(' ', 8 - Sb.Length); Sb.Append("("); for (int i = Index; i < A.Length; i++) { if (i > Index) Sb.Append(' '); Sb.Append(A [i]); } Sb.Append(')'); return Sb.ToString(); } internal virtual String TextposDescription() { StringBuilder Sb = new StringBuilder(); int remaining; Sb.Append(runtextpos); if (Sb.Length < 8) Sb.Append(' ', 8 - Sb.Length); if (runtextpos > runtextbeg) Sb.Append(RegexCharClass.CharDescription(runtext [runtextpos - 1])); else Sb.Append('^'); Sb.Append('>'); remaining = runtextend - runtextpos; for (int i = runtextpos; i < runtextend; i++) { Sb.Append(RegexCharClass.CharDescription(runtext [i])); } if (Sb.Length >= 64) { Sb.Length = 61; Sb.Append("..."); } else { Sb.Append('$'); } return Sb.ToString(); } #endif } }
{ "pile_set_name": "Github" }
<?xml version="1.0" encoding="UTF-8"?> <!-- /** * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ --> <tests xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:mftf:Test/etc/testSchema.xsd"> <test name="AdminCancelOrderWithBundleProductDefaultStockTest" extends="AdminCreateOrderWithBundleProductDefaultStockTest"> <annotations> <stories value="Bundle product Default Stock."/> <title value="Cancel order with bundle product on default stock."/> <description value="Verify admin able to cancel order with bundle product on default stock from admin area."/> <testCaseId value="https://app.hiptest.com/projects/69435/test-plan/folders/735226/scenarios/1698409"/> <severity value="CRITICAL"/> <group value="msi"/> <group value="multi_mode"/> </annotations> <!--Get order Id.--> <grabTextFrom selector="|Order # (\d+)|" stepKey="orderId" after="clickSubmitOrder" /> <!--Cancel order.--> <actionGroup ref="OpenOrderByIdActionGroup" stepKey="openOrder" after="checkSimpleProductSalableQtyAfterPlaceOrder"> <argument name="orderId" value="{$orderId}"/> </actionGroup> <click selector="{{AdminOrderDetailsMainActionsSection.cancel}}" stepKey="clickCancelOrder"/> <waitForElement selector="{{AdminConfirmationModalSection.message}}" stepKey="waitForCancelConfirmation"/> <see selector="{{AdminConfirmationModalSection.message}}" userInput="Are you sure you want to cancel this order?" stepKey="seeConfirmationMessage"/> <click selector="{{AdminConfirmationModalSection.ok}}" stepKey="confirmOrderCancel"/> <see selector="{{AdminMessagesSection.success}}" userInput="You canceled the order." stepKey="seeCancelSuccessMessage"/> <!--Verify product quantity after order cancellation.--> <amOnPage url="{{AdminProductIndexPage.url}}" stepKey="navigateToProductGrid"/> <actionGroup ref="AdminGridFilterSearchResultsByInput" stepKey="findProduct"> <argument name="selector" value="AdminProductGridFilterSection.skuFilter"/> <argument name="value" value="$$simpleProduct.sku$$"/> </actionGroup> <see selector="{{AdminProductGridSection.productQtyPerSource('1',_defaultSource.name)}}" userInput="1000" stepKey="verifySourceQuantity"/> <see selector="{{AdminProductGridSection.productSalableQty('1',_defaultStock.name)}}" userInput="1000" stepKey="verifyStockQuantity"/> </test> </tests>
{ "pile_set_name": "Github" }