from datetime import date

from . import GenericCalendarTest
from ..africa.mozambique import Mozambique

class MozambiqueTest(GenericCalendarTest):
    cal_class = Mozambique

    def test_year_new_year_shift(self):
        holidays = self.cal.holidays_set(2019)
        self.assertIn(date(2019, 1, 1), holidays)
        self.assertNotIn(date(2019, 1, 2), holidays)
        holidays = self.cal.holidays_set(2020)
        self.assertIn(date(2020, 1, 1), holidays)
        self.assertNotIn(date(2020, 1, 2), holidays)

    def test_n_holidays(self):
        n_holidays = len(self.cal.holidays_set(2019))
        for holiday in self.cal.get_calendar_holidays(2020):
            print(holiday)
        assert n_holidays == 10

    def test_year_2018(self):
        holidays = self.cal.holidays_set(2018)
        # Fixed days section:
        # 1. New Year's Day
        self.assertIn(date(2018, 1, 1), holidays)
        # 2. Mozambican Heroes' Day
        self.assertIn(date(2018, 2, 3), holidays)
        # 3. Mozambican Women's Day
        self.assertIn(date(2018, 4, 7), holidays)
        # 4. Good Friday
        self.assertIn(date(2018, 3, 30), holidays)
        # 5. Labour Day
        self.assertIn(date(2018, 5, 1), holidays)
        # 6. Independence Day
        self.assertIn(date(2018, 6, 25), holidays)
        # 7. Victory Day
        self.assertIn(date(2018, 9, 7), holidays)
        # 8. Armed Forces Day
        self.assertIn(date(2018, 9, 25), holidays)
        # 9. Peace And Reconciliation Day
        self.assertIn(date(2018, 10, 4), holidays)
        # 10. Christmas day
        self.assertIn(date(2018, 12, 25), holidays)

    def test_year_2019(self):
        holidays = self.cal.holidays_set(2019)
        # Fixed days section:
        # 1. New Year's Day
        self.assertIn(date(2019, 1, 1), holidays)
        # 2. Mozambican Heroes' Day
        self.assertIn(date(2019, 2, 3), holidays)
        # 3. Mozambican Women's Day
        self.assertIn(date(2019, 4, 7), holidays)
        # 4. Good Friday
        self.assertIn(date(2019, 4, 19), holidays)
        # 5. Labour Day
        self.assertIn(date(2019, 5, 1), holidays)
        # 6. Independence Day
        self.assertIn(date(2019, 6, 25), holidays)
        # 7. Victory Day
        self.assertIn(date(2019, 9, 7), holidays)
        # 8. Armed Forces Day
        self.assertIn(date(2019, 9, 25), holidays)
        # 9. Peace And Reconciliation Day
        self.assertIn(date(2019, 10, 4), holidays)
        # 10. Christmas day
        self.assertIn(date(2019, 12, 25), holidays)

    def test_year_2020(self):
        holidays = self.cal.holidays_set(2020)
        # Fixed days section:
        # 1. New Year's Day
        self.assertIn(date(2020, 1, 1), holidays)
        # 2. Mozambican Heroes' Day
        self.assertIn(date(2020, 2, 3), holidays)
        # 3. Mozambican Women's Day
        self.assertIn(date(2020, 4, 7), holidays)
        # 4. Good Friday
        self.assertIn(date(2020, 4, 10), holidays)
        # 5. Labour Day
        self.assertIn(date(2020, 5, 1), holidays)
        # 6. Independence Day
        self.assertIn(date(2020, 6, 25), holidays)
        # 7. Victory Day
        self.assertIn(date(2020, 9, 7), holidays)
        # 8. Armed Forces Day
        self.assertIn(date(2020, 9, 25), holidays)
        # 9. Peace And Reconciliation Day
        self.assertIn(date(2020, 10, 4), holidays)
        # 10. Christmas day
        self.assertIn(date(2020, 12, 25), holidays)

    def test_2020_new_years_day_label(self):
        holidays = self.cal.holidays(2020)
        holidays = dict(holidays)
        self.assertEqual(
            holidays[date(2020, 1, 1)], "New year")

    def test_2020_heroes_day_label(self):
        holidays = self.cal.holidays(2020)
        holidays = dict(holidays)
        self.assertEqual(
            holidays[date(2020, 2, 3)], "Mozambican Heroes' Day")

    def test_2020_women_day_label(self):
        holidays = self.cal.holidays(2020)
        holidays = dict(holidays)
        self.assertEqual(
            holidays[date(2020, 4, 7)], "Mozambican Women's Day")

    def test_2020_good_friday_label(self):
        holidays = self.cal.holidays(2020)
        holidays = dict(holidays)
        self.assertEqual(
            holidays[date(2020, 4, 10)], "Good Friday")

    def test_2020_labour_day_label(self):
        holidays = self.cal.holidays(2020)
        holidays = dict(holidays)
        self.assertEqual(
            holidays[date(2020, 5, 1)], "Labour Day")

    def test_2020_independence_day_label(self):
        holidays = self.cal.holidays(2020)
        holidays = dict(holidays)
        self.assertEqual(
            holidays[date(2020, 6, 25)], "Independence Day")

    def test_2020_victory_day_label(self):
        holidays = self.cal.holidays(2020)
        holidays = dict(holidays)
        self.assertEqual(
            holidays[date(2020, 9, 7)], "Victory Day")

    def test_2020_armed_forces_day_label(self):
        holidays = self.cal.holidays(2020)
        holidays = dict(holidays)
        self.assertEqual(
            holidays[date(2020, 9, 25)], "Armed Forces Day")

    def test_2020_peace_and_reconciliation_day_label(self):
        holidays = self.cal.holidays(2020)
        holidays = dict(holidays)
        self.assertEqual(
            holidays[date(2020, 10, 4)], "Peace And Reconciliation Day")

    def test_2020_christmas_day_label(self):
        holidays = self.cal.holidays(2020)
        holidays = dict(holidays)
        self.assertEqual(
            holidays[date(2020, 12, 25)], "Christmas Day")

{'repo_name': 'peopledoc/workalendar', 'stars': '476', 'repo_language': 'Python', 'file_name': 'iso-registry.md', 'mime_type': 'text/plain', 'hash': 5404465464306154472, 'source_dataset': 'data'}


// Copyright 2019 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.

// +build arm64,netbsd

package unix

func setTimespec(sec, nsec int64) Timespec {
	return Timespec{Sec: sec, Nsec: nsec}
}

func setTimeval(sec, usec int64) Timeval {
	return Timeval{Sec: sec, Usec: int32(usec)}
}

func SetKevent(k *Kevent_t, fd, mode, flags int) {
	k.Ident = uint64(fd)
	k.Filter = uint32(mode)
	k.Flags = uint32(flags)
}

func (iov *Iovec) SetLen(length int) {
	iov.Len = uint64(length)
}

func (msghdr *Msghdr) SetControllen(length int) {
	msghdr.Controllen = uint32(length)
}

func (msghdr *Msghdr) SetIovlen(length int) {
	msghdr.Iovlen = int32(length)
}

func (cmsg *Cmsghdr) SetLen(length int) {
	cmsg.Len = uint32(length)
}

{'repo_name': 'xuperchain/xuperchain', 'stars': '1141', 'repo_language': 'Go', 'file_name': 'spipe.proto', 'mime_type': 'text/plain', 'hash': 8336562847029724613, 'source_dataset': 'data'}


(*
 * Copyright (c) 2015-present, Facebook, Inc.
 *
 * This source code is licensed under the MIT license found in the
 * LICENSE file in the root directory of this source tree.
 *
 *  Forked from OCaml, which is provided under the license below:
 *
 *  Xavier Leroy, projet Cristal, INRIA Rocquencourt
 *
 *  Copyright © 1996, 1997, 1998, 1999, 2000, 2001, 2002, 2003, 2004, 2005, 2006 Inria
 *
 *  Permission is hereby granted, free of charge, to the Licensee 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
 *  under any license of the Licensee's choice, and/or sell copies of the
 *  Software, subject to the following conditions:
 *
 *  1.	Redistributions of source code must retain the above copyright notice
 *  and the following disclaimer.
 *  2.	Redistributions in binary form must reproduce the above copyright
 *  notice, the following disclaimer in the documentation and/or other
 *  materials provided with the distribution.
 *  3.	All advertising materials mentioning features or use of the Software
 *  must display the following acknowledgement: This product includes all or
 *  parts of the Caml system developed by Inria and its contributors.
 *  4.	Other than specified in clause 3, neither the name of Inria nor the
 *  names of its contributors may be used to endorse or promote products
 *  derived from the Software without specific prior written permission.
 *
 *  Disclaimer
 *
 *  This software is provided by Inria 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 Inria or its 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.
 *
 *)

(* This is the Reason lexer. As stated in src/README, there's a good section in
  Real World OCaml that describes what a lexer is:

  https://realworldocaml.org/v1/en/html/parsing-with-ocamllex-and-menhir.html

  Basically, it uses regular expressions to first cut the big code string into
  more meaningful chunks, called tokens. For example, it cuts the string

    let foo = 1

  into `let`, `foo`, `=` and `1`, massage them a bit into nice variants, then
  send the data structures into the parser `reason_parser.mly`, which takes
  care of the next step (turning the stream of tokens into an AST, abstract
  syntax tree).

  The file's syntax's a bit special. It's not the conventional OCaml syntax. An
  ordinary language syntax isn't expressive/convenient enough for a lexer. This
  mll ("ml lexer") syntax is a fine-tuned variation of the usual OCaml syntax.
 *)

{
open Lexing
open Reason_parser
open Reason_errors

(* The table of keywords *)

let keyword_table, reverse_keyword_table =
  let create_hashtable n l =
    let t = Hashtbl.create n in
    let rev_t = Hashtbl.create n in
    List.iter (fun (k, v) ->
      Hashtbl.add t k v;
      Hashtbl.add rev_t v k;
    ) l;
    t, rev_t
  in
  create_hashtable 149 [
    "and", AND;
    "as", AS;
    "assert", ASSERT;
    "begin", BEGIN;
    "class", CLASS;
    "constraint", CONSTRAINT;
    "do", DO;
    "done", DONE;
    "downto", DOWNTO;
    "else", ELSE;
    "end", END;
    "exception", EXCEPTION;
    "external", EXTERNAL;
    "false", FALSE;
    "for", FOR;
    "fun", FUN;
    "esfun", ES6_FUN;
    "function", FUNCTION;
    "functor", FUNCTOR;
    "if", IF;
    "in", IN;
    "include", INCLUDE;
    "inherit", INHERIT;
    "initializer", INITIALIZER;
    "lazy", LAZY;
    "let", LET;
    "switch", SWITCH;
    "module", MODULE;
    "pub", PUB;
    "mutable", MUTABLE;
    "new", NEW;
    "nonrec", NONREC;
    "object", OBJECT;
    "of", OF;
    "open", OPEN;
    "or", OR;
(*  "parser", PARSER; *)
    "pri", PRI;
    "rec", REC;
    "sig", SIG;
    "struct", STRUCT;
    "then", THEN;
    "to", TO;
    "true", TRUE;
    "try", TRY;
    "type", TYPE;
    "val", VAL;
    "virtual", VIRTUAL;
    "when", WHEN;
    "while", WHILE;
    "with", WITH;

    "mod", INFIXOP3("mod");
    "land", INFIXOP3("land");
    "lor", INFIXOP3("lor");
    "lxor", INFIXOP3("lxor");
    "lsl", INFIXOP4("lsl");
    "lsr", INFIXOP4("lsr");
    "asr", INFIXOP4("asr")
]

(* The only internal state of the lexer is two scratch buffers.
   They could be allocated everytime they are needed, but
   for better performance (FIXME: does this really matter?)
   they are preallocated.*)

type state = {
  raw_buffer : Buffer.t;
  txt_buffer : Buffer.t;
}

let get_scratch_buffers { raw_buffer; txt_buffer } =
  Buffer.reset raw_buffer;
  Buffer.reset txt_buffer;
  ( raw_buffer, txt_buffer )

let flush_buffer buffer =
  let result = Buffer.contents buffer in
  Buffer.reset buffer;
  result

let make () = {
  raw_buffer = Buffer.create 255;
  txt_buffer = Buffer.create 255;
}

(* Specialize raise_error for lexing errors *)

let raise_error loc error = raise_error (Lexing_error error) loc

let store_lexeme buffer lexbuf =
  Buffer.add_string buffer (Lexing.lexeme lexbuf)

(* To "unlex" a few characters *)
let set_lexeme_length buf n = (
  let open Lexing in
  if n < 0 then
    invalid_arg "set_lexeme_length: offset should be positive";
  if n > buf.lex_curr_pos - buf.lex_start_pos then
    invalid_arg "set_lexeme_length: offset larger than lexeme";
  buf.lex_curr_pos <- buf.lex_start_pos + n;
  buf.lex_curr_p <- {buf.lex_start_p
                     with pos_cnum = buf.lex_abs_pos + buf.lex_curr_pos};
)

(* This cut comment characters of the current buffer.
 * Operators (including "/*" and "//") are lexed with the same rule, and this
 * function cuts the lexeme at the beginning of an operator. *)
let lexeme_without_comment buf = (
  let lexeme = Lexing.lexeme buf in
  let i = ref 0 and len = String.length lexeme - 1 in
  let found = ref (-1) in
  while !i < len && !found = -1 do
    begin match lexeme.[!i], lexeme.[!i+1] with
      | ('/', '*') | ('/', '/') | ('*', '/') ->
        found := !i;
      | _ -> ()
    end;
    incr i
  done;
  match !found with
  | -1 -> lexeme
  | n ->
      set_lexeme_length buf n;
      String.sub lexeme 0 n
)

(* Operators that could conflict with comments (those containing /*, */ and //)
 * are escaped in the source. The lexer removes the escapes so that the
 * identifier looks like OCaml ones.
 * An escape in first position is kept to distinguish "verbatim" operators
 * (\=== for instance). *)
let unescape_operator str =
  if (str <> "" && String.contains_from str 1 '\\') then (
    let b = Buffer.create (String.length str) in
    Buffer.add_char b str.[0];
    for i = 1 to String.length str - 1 do
      let c = str.[i] in
      if c <> '\\' then Buffer.add_char b c
    done;
    Buffer.contents b
  ) else str

let lexeme_operator lexbuf =
  unescape_operator (lexeme_without_comment lexbuf)

(* To translate escape sequences *)

let char_for_backslash = function
  | 'n' -> '\010'
  | 'r' -> '\013'
  | 'b' -> '\008'
  | 't' -> '\009'
  | c   -> c

let char_for_decimal_code lexbuf i =
  let c = 100 * (Char.code(Lexing.lexeme_char lexbuf i) - 48) +
           10 * (Char.code(Lexing.lexeme_char lexbuf (i+1)) - 48) +
                (Char.code(Lexing.lexeme_char lexbuf (i+2)) - 48) in
  if (c < 0 || c > 255) then (
    raise_error
        (Location.curr lexbuf)
        (Illegal_escape (Lexing.lexeme lexbuf));
    'x'
  ) else Char.chr c

let char_for_hexadecimal_code lexbuf i =
  let d1 = Char.code (Lexing.lexeme_char lexbuf i) in
  let val1 = if d1 >= 97 then d1 - 87
             else if d1 >= 65 then d1 - 55
             else d1 - 48
  in
  let d2 = Char.code (Lexing.lexeme_char lexbuf (i+1)) in
  let val2 = if d2 >= 97 then d2 - 87
             else if d2 >= 65 then d2 - 55
             else d2 - 48
  in
  Char.chr (val1 * 16 + val2)

(* To convert integer literals, allowing max_int + 1 (PR#4210) *)

let cvt_int_literal s =
  - int_of_string ("-" ^ s)
let cvt_int32_literal s =
  Int32.neg (Int32.of_string ("-" ^ String.sub s 0 (String.length s - 1)))
let cvt_int64_literal s =
  Int64.neg (Int64.of_string ("-" ^ String.sub s 0 (String.length s - 1)))
let cvt_nativeint_literal s =
  Nativeint.neg (Nativeint.of_string ("-" ^ String.sub s 0
                                                       (String.length s - 1)))

(* Remove underscores from float literals *)

let remove_underscores s =
  let l = String.length s in
  let b = Bytes.create l in
  let rec remove src dst =
    if src >= l then
      if dst >= l then s else Bytes.sub_string b 0 dst
    else
      match s.[src] with
        '_' -> remove (src + 1) dst
      |  c  -> Bytes.set b dst c; remove (src + 1) (dst + 1)
  in remove 0 0

(* Update the current location with file name and line number. *)

let update_loc lexbuf file line absolute chars =
  let pos = lexbuf.lex_curr_p in
  let new_file = match file with
                 | None -> pos.pos_fname
                 | Some s -> s
  in
  lexbuf.lex_curr_p <- { pos with
    pos_fname = new_file;
    pos_lnum = if absolute then line else pos.pos_lnum + line;
    pos_bol = pos.pos_cnum - chars;
  }

}

let newline = ('\013'* '\010')
let blank = [' ' '\009' '\012']
let lowercase = ['a'-'z' '_']
let lowercase_no_under = ['a'-'z']
let uppercase = ['A'-'Z']
let uppercase_or_lowercase = lowercase | uppercase
let identchar = ['A'-'Z' 'a'-'z' '_' '\'' '0'-'9']
let lowercase_latin1 = ['a'-'z' '\223'-'\246' '\248'-'\255' '_']
let uppercase_latin1 = ['A'-'Z' '\192'-'\214' '\216'-'\222']
let identchar_latin1 =
  ['A'-'Z' 'a'-'z' '_' '\192'-'\214' '\216'-'\246' '\248'-'\255' '\'' '0'-'9']

let operator_chars =
  ['!' '$' '%' '&' '+' '-' ':' '<' '=' '>' '?' '@' '^' '|' '~' '#' '.'] |
  ( '\\'? ['/' '*'] )
let dotsymbolchar =
  ['!' '$' '%' '&' '*' '+' '-' '/' ':' '=' '>' '?' '@' '^' '|' '\\' 'a'-'z' 'A'-'Z' '_' '0'-'9']
let kwdopchar = ['$' '&' '*' '+' '-' '/' '<' '=' '>' '@' '^' '|' '.' '!']

let decimal_literal = ['0'-'9'] ['0'-'9' '_']*

let hex_literal =
  '0' ['x' 'X'] ['0'-'9' 'A'-'F' 'a'-'f']['0'-'9' 'A'-'F' 'a'-'f' '_']*
let oct_literal =
  '0' ['o' 'O'] ['0'-'7'] ['0'-'7' '_']*
let bin_literal =
  '0' ['b' 'B'] ['0'-'1'] ['0'-'1' '_']*

let int_literal =
  decimal_literal | hex_literal | oct_literal | bin_literal

let float_literal =
  ['0'-'9'] ['0'-'9' '_']*
  ('.' ['0'-'9' '_']* )?
  (['e' 'E'] ['+' '-']? ['0'-'9'] ['0'-'9' '_']*)?

let hex_float_literal =
  '0' ['x' 'X']
  ['0'-'9' 'A'-'F' 'a'-'f'] ['0'-'9' 'A'-'F' 'a'-'f' '_']*
  ('.' ['0'-'9' 'A'-'F' 'a'-'f' '_']* )?
  (['p' 'P'] ['+' '-']? ['0'-'9'] ['0'-'9' '_']* )?

let literal_modifier = ['G'-'Z' 'g'-'z']

rule token state = parse
  | "\\" newline {
      raise_error
        (Location.curr lexbuf)
        (Illegal_character (Lexing.lexeme_char lexbuf 0));
      update_loc lexbuf None 1 false 0;
      token state lexbuf
    }
  | newline
    { update_loc lexbuf None 1 false 0;
      token state lexbuf
    }
  | blank +
    { token state lexbuf }
  | "_"
    { UNDERSCORE }
  | "~"
    { TILDE }
  | "?"
    { QUESTION }
  | "=?"
    { set_lexeme_length lexbuf 1; EQUAL }
  | lowercase identchar *
    { let s = Lexing.lexeme lexbuf in
      try Hashtbl.find keyword_table s
      with Not_found -> LIDENT s
    }
  | lowercase_latin1 identchar_latin1 *
    { Ocaml_util.warn_latin1 lexbuf; LIDENT (Lexing.lexeme lexbuf) }
  | uppercase identchar *
    { UIDENT(Lexing.lexeme lexbuf) }       (* No capitalized keywords *)
  | uppercase_latin1 identchar_latin1 *
    { Ocaml_util.warn_latin1 lexbuf; UIDENT(Lexing.lexeme lexbuf) }
  | int_literal
    { INT (Lexing.lexeme lexbuf, None) }
  | (int_literal as lit) (literal_modifier as modif)
    { INT (lit, Some modif) }
  | float_literal | hex_float_literal
    { FLOAT (Lexing.lexeme lexbuf, None) }
  | ((float_literal | hex_float_literal) as lit) (literal_modifier as modif)
    { FLOAT (lit, Some modif) }
  | ((float_literal | hex_float_literal) as lit) identchar+
    { raise_error
        (Location.curr lexbuf)
        (Invalid_literal (Lexing.lexeme lexbuf));
      FLOAT (lit, None)
    }
  | (int_literal as lit) identchar+
    { raise_error
        (Location.curr lexbuf)
        (Invalid_literal (Lexing.lexeme lexbuf));
      INT (lit, None)
    }
  | "\""
    { let string_start = lexbuf.lex_start_p in
      let start_loc = Location.curr lexbuf in
      let raw_buffer, txt_buffer = get_scratch_buffers state in
      if not (string raw_buffer (Some txt_buffer) lexbuf) then
        raise_error start_loc Unterminated_string;
      lexbuf.lex_start_p <- string_start;
      let txt = flush_buffer txt_buffer in
      let raw = flush_buffer raw_buffer in
      STRING (txt, Some raw, None)
    }
  | "{" (lowercase* as delim) "|"
    { let string_start = lexbuf.lex_start_p in
      let start_loc = Location.curr lexbuf in
      let raw_buffer, _ = get_scratch_buffers state in
      if not (quoted_string raw_buffer delim lexbuf) then
        raise_error start_loc Unterminated_string;
      lexbuf.lex_start_p <- string_start;
      let txt = flush_buffer raw_buffer in
      STRING (txt, None, Some delim)
    }
  | "'" newline "'"
    { (* newline can span multiple characters
         (if the newline starts with \13)
         Only the first one is returned, maybe we should warn? *)
      update_loc lexbuf None 1 false 1;
      CHAR (Lexing.lexeme_char lexbuf 1)
    }
  | "'" ([^ '\\' '\'' '\010' '\013'] as c) "'"
    { CHAR c }
  | "'\\" (['\\' '\'' '"' 'n' 't' 'b' 'r' ' '] as c) "'"
    { CHAR (char_for_backslash c) }
  | "'\\" ['0'-'9'] ['0'-'9'] ['0'-'9'] "'"
    { CHAR (char_for_decimal_code lexbuf 2) }
  | "'\\" 'x' ['0'-'9' 'a'-'f' 'A'-'F'] ['0'-'9' 'a'-'f' 'A'-'F'] "'"
    { CHAR (char_for_hexadecimal_code lexbuf 3) }
  | "'" (("\\" _) as esc)
    { raise_error (Location.curr lexbuf) (Illegal_escape esc);
      token state lexbuf
    }
  | "#=<"
    { (* Allow parsing of foo#=<bar /> *)
      set_lexeme_length lexbuf 2;
      SHARPEQUAL
    }
  | "#="
    { SHARPEQUAL }
  | "#" operator_chars+
    { SHARPOP (lexeme_operator lexbuf) }
  | "#" [' ' '\t']* (['0'-'9']+ as num) [' ' '\t']*
        ("\"" ([^ '\010' '\013' '"' ] * as name) "\"")?
        [^ '\010' '\013'] * newline
    { update_loc lexbuf name (int_of_string num) true 0;
      token state lexbuf
    }
  | "&"  { AMPERSAND }
  | "&&" { AMPERAMPER }
  | "`"  { BACKQUOTE }
  | "'"  { QUOTE }
  | "("  { LPAREN }
  | ")"  { RPAREN }
  | "*"  { STAR }
  | ","  { COMMA }
  | "->" { MINUSGREATER }
  | "=>" { EQUALGREATER }
  (* allow lexing of | `Variant =><Component /> *)
  | "=><" uppercase_or_lowercase (identchar | '.') * {
    set_lexeme_length lexbuf 2;
    EQUALGREATER
  }
  | "#"  { SHARP }
  | "."  { DOT }
  | ".." { DOTDOT }
  | "..."{ DOTDOTDOT }
  | ":"  { COLON }
  | "::" { COLONCOLON }
  | ":=" { COLONEQUAL }
  | ":>" { COLONGREATER }
  | ";"  { SEMI }
  | ";;" { SEMISEMI }
  | "<"  { LESS }
  | "="  { EQUAL }
  | "["  { LBRACKET }
  | "[|" { LBRACKETBAR }
  | "[<" { LBRACKETLESS }
  | "[>" { LBRACKETGREATER }
  | "<" (((uppercase identchar* '.')*
         (lowercase_no_under | lowercase identchar identchar*)) as tag)
    (* Parsing <_ helps resolve no conflicts in the parser and creates other
     * challenges with splitting up INFIXOP0 tokens (in Reason_parser_single)
     * so we don't do it. *)
    { LESSIDENT tag }
  | "<" ((uppercase identchar*) as tag)
    { LESSUIDENT tag }
  | ">..." { GREATERDOTDOTDOT }
  (* Allow parsing of Pexp_override:
   * let z = {<state: 0, x: y>};
   *
   * Make sure {<state is emitted as LBRACELESS.
   * This contrasts with jsx:
   * in a jsx context {<div needs to be LBRACE LESS (two tokens)
   * for a valid parse.
   *)
  | "{<" uppercase_or_lowercase identchar* blank*  ":"
    { set_lexeme_length lexbuf 2;
      LBRACELESS
    }
  | "{<" uppercase_or_lowercase (identchar | '.') *
    { (* allows parsing of `{<Text` in <Description term={<Text text="Age" />}>
         as correct jsx
       *)
      set_lexeme_length lexbuf 1;
      LBRACE
    }
  | "{<>" {
    set_lexeme_length lexbuf 1;
    LBRACE
  }
  | "{<>}" {
    set_lexeme_length lexbuf 2;
    LBRACELESS
  }
  | "</" blank* ((uppercase_or_lowercase (identchar|'.')* ) as tag) blank* ">"
    { LESSSLASHIDENTGREATER tag }
  | "]"  { RBRACKET }
  | "{"  { LBRACE }
  | "{<" { LBRACELESS }
  | "|"  { BAR }
  | "||" { BARBAR }
  | "|]" { BARRBRACKET }
  | ">"  { GREATER }
  (* Having a GREATERRBRACKET makes it difficult to parse patterns such
     as > ]. The space in between then becomes significant and must be
     maintained when printing etc. >] isn't even needed!
  | ">]" { GREATERRBRACKET }
  *)
  | "}"  { RBRACE }
  | ">}" { GREATERRBRACE }
  | "=<" uppercase_or_lowercase+
    { (* allow `let x=<div />;` *)
      set_lexeme_length lexbuf 1;
      EQUAL
    }
  | "/>|]"
    { (* jsx in arrays: [|
|]*)
      set_lexeme_length lexbuf 2;
      SLASHGREATER
    }
  | "[|<"
    { set_lexeme_length lexbuf 2;
      LBRACKETBAR
    }
    (* allow parsing of
</Component> *)
  | "/></" uppercase_or_lowercase+
    { (* allow parsing of

 *)
      set_lexeme_length lexbuf 2;
      SLASHGREATER
    }
  | "></" uppercase_or_lowercase+
    { (* allow parsing of

 *)
      set_lexeme_length lexbuf 1;
      GREATER
    }
  | "><" uppercase_or_lowercase+
    { (* allow parsing of
 *)
      set_lexeme_length lexbuf 1;
      GREATER
    }
  | "[@" { LBRACKETAT }
  | "[%" { LBRACKETPERCENT }
  | "[%%" { LBRACKETPERCENTPERCENT }
  | "!"  { BANG }
  | "!=" { INFIXOP0 "!=" }
  | "!==" { INFIXOP0 "!==" }
  | "\\!=" { INFIXOP0 "!=" }
  | "\\!==" { INFIXOP0 "!==" }
  | "+"  { PLUS }
  | "+." { PLUSDOT }
  | "+=" { PLUSEQ }
  | "-"  { MINUS }
  | "-." { MINUSDOT }
  | "<>" { LESSGREATER }
  | "</>" { LESSSLASHGREATER }
  | "<..>" { LESSDOTDOTGREATER }
  | '\\'? ['~' '?' '!'] operator_chars+
    { PREFIXOP (lexeme_operator lexbuf) }
  | '\\'? ['=' '<' '>' '|' '&' '$'] operator_chars*
    {
      (* See decompose_token in Reason_single_parser.ml for how let `x=-1` is lexed
       * and broken up into multiple tokens when necessary. *)
      INFIXOP0 (lexeme_operator lexbuf)
    }
  | '\\'? '@' operator_chars*
    { INFIXOP1 (lexeme_operator lexbuf) }
  | '\\'? '^' ('\\' '.')? operator_chars*
    { match lexeme_without_comment lexbuf with
      | "^." | "^|" ->
        (* ^| is not an infix op in [|a^|] *)
        set_lexeme_length lexbuf
          (if Lexing.lexeme_char lexbuf 0 = '\\' then 2 else 1);
        POSTFIXOP "^"
      | "^" -> POSTFIXOP "^"
      | op -> INFIXOP1 (unescape_operator op)
    }
  | "++" operator_chars*
    { INFIXOP1 (lexeme_operator lexbuf) }
  | '\\'? ['+' '-'] operator_chars*
    { INFIXOP2 (lexeme_operator lexbuf) }
  (* SLASHGREATER is an INFIXOP3 that is handled specially *)
  | "/>" { SLASHGREATER }
  (* The second star must be escaped so that the precedence assumptions for
   * printing match those of parsing. (Imagine what could happen if the other
   * rule beginning with * picked up */*, and we internally escaped it to **.
   * Whe printing, we have an understanding of the precedence of "**", which
   * enables us to safely print/group it, but that understanding would not
   * match the *actual* precedence that it was parsed at thanks to the *other*
   * rule beginning with *, picking it up instead of the special double ** rule
   * below.
   *)
  | '\\'? '*' '\\'? '*' operator_chars*
    { INFIXOP4 (lexeme_operator lexbuf) }
  | '%' { PERCENT }
  | '\\'? ['/' '*'] operator_chars*
    { match lexeme_operator lexbuf with
      | "" ->
          (* If the operator is empty, it means the lexeme is beginning
           * by a comment sequence: we let the comment lexer handle
           * the case. *)
          enter_comment state lexbuf
      | op -> INFIXOP3 op }
  | '%' operator_chars*
    { INFIXOP3 (lexeme_operator lexbuf) }
  | "let" kwdopchar dotsymbolchar *
    { LETOP (Reason_syntax_util.expand_letop_identifier (lexeme_operator lexbuf)) }
  | "and" kwdopchar dotsymbolchar *
    { ANDOP (Reason_syntax_util.expand_letop_identifier (lexeme_operator lexbuf)) }
  | eof { EOF }
  | _
    { raise_error
        (Location.curr lexbuf)
        (Illegal_character (Lexing.lexeme_char lexbuf 0));
      token state lexbuf
    }

and enter_comment state = parse
  | "//" ([^'\010']* newline as line)
    { update_loc lexbuf None 1 false 0;
      let physical_loc = Location.curr lexbuf in
      let location = { physical_loc with
        loc_end = { physical_loc.loc_end with
          (* Don't track trailing `\n` in the location
           * 1| // comment
           * 2| let x = 1;
           * By omitting the `\n` at the end of line 1, the location of the
           * comment spans line 1. Otherwise the comment on line 1 would end
           * on the second line. The printer looks at the closing pos_lnum
           * location to interleave whitespace correct. It needs to align
           * with what we visually see (i.e. it ends on line 1) *)
          pos_lnum = physical_loc.loc_end.pos_lnum - 1;
          pos_cnum = physical_loc.loc_end.pos_cnum + 1;
      }} in
      COMMENT (line, location)
    }
  | "//" ([^'\010']* eof as line)
    { update_loc lexbuf None 1 false 0;
      let physical_loc = Location.curr lexbuf in
      let location = { physical_loc with
        loc_end = { physical_loc.loc_end with
          pos_lnum = physical_loc.loc_end.pos_lnum - 1;
          pos_cnum = physical_loc.loc_end.pos_cnum + 1;
      }} in
      COMMENT (line, location)
    }
  | "/*" ("*" "*"+)?
    { set_lexeme_length lexbuf 2;
      let loc = Location.curr lexbuf in
      let raw_buffer, _ = get_scratch_buffers state in
      ignore (comment raw_buffer loc loc lexbuf : bool);
      lexbuf.Lexing.lex_start_p <- loc.Location.loc_start;
      let loc_end = lexbuf.Lexing.lex_curr_p in
      COMMENT (flush_buffer raw_buffer,
               {loc with Location.loc_end})
    }
  | "/**"
    { let loc = Location.curr lexbuf in
      let raw_buffer, _ = get_scratch_buffers state in
      ignore (comment raw_buffer loc loc lexbuf : bool);
      lexbuf.Lexing.lex_start_p <- loc.Location.loc_start;
      DOCSTRING (flush_buffer raw_buffer)
    }
  | "/**/"
    { DOCSTRING "" }
  | "/*/"
    { let loc = Location.curr lexbuf in
      Location.prerr_warning loc Warnings.Comment_start;
      let raw_buffer, _ = get_scratch_buffers state in
      ignore (comment raw_buffer loc loc lexbuf : bool);
      let loc_end = lexbuf.Lexing.lex_curr_p in
      COMMENT (flush_buffer raw_buffer,
               {loc with Location.loc_end})
    }
  | "*/"
    { let loc = Location.curr lexbuf in
      Location.prerr_warning loc Warnings.Comment_not_end;
      set_lexeme_length lexbuf 1;
      STAR
    }
  | _ { assert false }

(** [comment buffer locs lexbuf] will lex a comment from [lexbuf] and
   stores its raw text in [buffer], without the /* and */ delimiters.
   [locs] is a non-empty list of locations that saves the beginning
   position of each nested comments.
 *)
and comment buffer firstloc nestedloc = parse
  | "/*"
    { store_lexeme buffer lexbuf;
      if comment buffer firstloc (Location.curr lexbuf) lexbuf then (
        store_lexeme buffer lexbuf;
        comment buffer firstloc nestedloc lexbuf
      )
      else
        false
    }
  | "*/"
    { true }
  | "\""
    { Buffer.add_char buffer '"';
      let string_start = Location.curr lexbuf in
      let terminated_string = string buffer None lexbuf in
      Buffer.add_char buffer '"';
      if terminated_string then
        comment buffer firstloc nestedloc lexbuf
      else (
        raise_error nestedloc
          (Unterminated_string_in_comment (firstloc, string_start));
        false
      )
    }
  | "{" (lowercase* as delim) "|"
    { store_lexeme buffer lexbuf;
      let stringloc = Location.curr lexbuf in
      let terminated_string = quoted_string buffer delim lexbuf in
      Buffer.add_char buffer '|';
      Buffer.add_string buffer delim;
      Buffer.add_char buffer '}';
      if terminated_string then
        comment buffer firstloc nestedloc lexbuf
      else (
        raise_error nestedloc
          (Unterminated_string_in_comment (firstloc, stringloc));
        false
      )
    }
  | "''"
    { store_lexeme buffer lexbuf;
      comment buffer firstloc nestedloc lexbuf
    }
  | "'" newline "'"
    { store_lexeme buffer lexbuf;
      update_loc lexbuf None 1 false 1;
      comment buffer firstloc nestedloc lexbuf
    }
  | "'" [^ '\\' '\'' '\010' '\013' ] "'"
  | "'\\" ['\\' '"' '\'' 'n' 't' 'b' 'r' ' '] "'"
  | "'\\" ['0'-'9'] ['0'-'9'] ['0'-'9'] "'"
  | "'\\" 'x' ['0'-'9' 'a'-'f' 'A'-'F'] ['0'-'9' 'a'-'f' 'A'-'F'] "'"
    { store_lexeme buffer lexbuf;
      comment buffer firstloc nestedloc lexbuf
    }
  | eof
    { raise_error nestedloc (Unterminated_comment firstloc);
      false
    }
  | newline
    { store_lexeme buffer lexbuf;
      update_loc lexbuf None 1 false 0;
      comment buffer firstloc nestedloc lexbuf
    }
  | _
    { store_lexeme buffer lexbuf;
      comment buffer firstloc nestedloc lexbuf
    }

(** [string rawbuf txtbuf lexbuf] parses a string from [lexbuf].
    The string contents is stored in two buffers:
    - [rawbuf] for the text as it literally appear in the source
    - [txtbuf] for the processed, unescaped contents.
    [txtbuf] is optional. If it is omitted, contents is not unescaped.
    The call returns [true] iff the string was properly terminated.
    It does not register an error if the string is unterminated, this
    is the responsibility of the caller.
 *)
and string rawbuf txtbuf = parse
  | '"'
    { true }
  | '\\' newline ([' ' '\t'] * as space)
    { store_lexeme rawbuf lexbuf;
      update_loc lexbuf None 1 false (String.length space);
      string rawbuf txtbuf lexbuf
    }
  | '\\' (['\\' '\'' '"' 'n' 't' 'b' 'r' ' '] as c)
    { store_lexeme rawbuf lexbuf;
      begin match txtbuf with
      | None -> ()
      | Some buf -> Buffer.add_char buf (char_for_backslash c);
      end;
      string rawbuf txtbuf lexbuf
    }
  | '\\' ['0'-'9'] ['0'-'9'] ['0'-'9']
    { store_lexeme rawbuf lexbuf;
      begin match txtbuf with
      | None -> ()
      | Some buf -> Buffer.add_char buf (char_for_decimal_code lexbuf 1);
      end;
      string rawbuf txtbuf lexbuf
    }
  | '\\' 'x' ['0'-'9' 'a'-'f' 'A'-'F'] ['0'-'9' 'a'-'f' 'A'-'F']
    { store_lexeme rawbuf lexbuf;
      begin match txtbuf with
      | None -> ()
      | Some buf -> Buffer.add_char buf (char_for_hexadecimal_code lexbuf 2);
      end;
      string rawbuf txtbuf lexbuf
    }
  | '\\' _
    { store_lexeme rawbuf lexbuf;
      begin match txtbuf with
      | None -> ()
      | Some buf ->
         store_lexeme buf lexbuf;
         (*  FIXME: Warnings should probably go in Reason_errors
            Should be an error, but we are very lax.
              raise (Error (Illegal_escape (Lexing.lexeme lexbuf),
                        Location.curr lexbuf))
           FIXME Using Location relies too much on compiler internals
          *)
         Location.prerr_warning (Location.curr lexbuf)
           Warnings.Illegal_backslash;
      end;
      string rawbuf txtbuf lexbuf
    }
  | newline
    { store_lexeme rawbuf lexbuf;
      begin match txtbuf with
      | None -> ()
      | Some buf ->
        store_lexeme buf lexbuf;
        Location.prerr_warning (Location.curr lexbuf)
          Warnings.Eol_in_string
      end;
      update_loc lexbuf None 1 false 0;
      string rawbuf txtbuf lexbuf
    }
  | eof
    { false }
  | _
    { store_lexeme rawbuf lexbuf;
      begin match txtbuf with
      | None -> ()
      | Some buf -> Buffer.add_char buf (Lexing.lexeme_char lexbuf 0);
      end;
      string rawbuf txtbuf lexbuf
    }

(** [quoted_string buffer delim lexbuf] parses a quoted string
    delimited by [delim] from [lexbuf] and stores the literal text in
    [buffer].
    It returns:
    - true if the string was properly delimited and
    - false if EOF was reached before finding "|delim}".
    It does not register an error if the string is unterminated, this
    is the responsibility of the caller.
 *)
and quoted_string buffer delim = parse
  | newline
    { store_lexeme buffer lexbuf;
      update_loc lexbuf None 1 false 0;
      quoted_string buffer delim lexbuf
    }
  | eof
    { false }
  | "|" (lowercase* as edelim) "}"
    { if delim = edelim then
        true
      else (
        store_lexeme buffer lexbuf;
        quoted_string buffer delim lexbuf
      )
    }
  | _ as c
    { Buffer.add_char buffer c;
      quoted_string buffer delim lexbuf
    }

and skip_sharp_bang = parse
  | "#!" [^ '\n']* '\n' [^ '\n']* "\n!#\n"
       { update_loc lexbuf None 3 false 0 }
  | "#!" [^ '\n']* '\n'
       { update_loc lexbuf None 1 false 0 }
  | "" { () }

{'repo_name': 'facebook/reason', 'stars': '8863', 'repo_language': 'OCaml', 'file_name': 'inlineRecord.re', 'mime_type': 'text/plain', 'hash': -467722305668132828, 'source_dataset': 'data'}


/*
 * Copyright (C) ST-Ericsson SA 2010
 *
 * License Terms: GNU General Public License, version 2
 * Author: Rabin Vincent <rabin.vincent@stericsson.com> for ST-Ericsson
 */

#ifndef __STMPE_H
#define __STMPE_H

#include <linux/device.h>
#include <linux/mfd/core.h>
#include <linux/mfd/stmpe.h>
#include <linux/printk.h>
#include <linux/types.h>

extern const struct dev_pm_ops stmpe_dev_pm_ops;

#ifdef STMPE_DUMP_BYTES
static inline void stmpe_dump_bytes(const char *str, const void *buf,
				    size_t len)
{
	print_hex_dump_bytes(str, DUMP_PREFIX_OFFSET, buf, len);
}
#else
static inline void stmpe_dump_bytes(const char *str, const void *buf,
				    size_t len)
{
}
#endif

/**
 * struct stmpe_variant_block - information about block
 * @cell:	base mfd cell
 * @irq:	interrupt number to be added to each IORESOURCE_IRQ
 *		in the cell
 * @block:	block id; used for identification with platform data and for
 *		enable and altfunc callbacks
 */
struct stmpe_variant_block {
	struct mfd_cell		*cell;
	int			irq;
	enum stmpe_block	block;
};

/**
 * struct stmpe_variant_info - variant-specific information
 * @name:	part name
 * @id_val:	content of CHIPID register
 * @id_mask:	bits valid in CHIPID register for comparison with id_val
 * @num_gpios:	number of GPIOS
 * @af_bits:	number of bits used to specify the alternate function
 * @regs: variant specific registers.
 * @blocks:	list of blocks present on this device
 * @num_blocks:	number of blocks present on this device
 * @num_irqs:	number of internal IRQs available on this device
 * @enable:	callback to enable the specified blocks.
 *		Called with the I/O lock held.
 * @get_altfunc: callback to get the alternate function number for the
 *		 specific block
 * @enable_autosleep: callback to configure autosleep with specified timeout
 */
struct stmpe_variant_info {
	const char *name;
	u16 id_val;
	u16 id_mask;
	int num_gpios;
	int af_bits;
	const u8 *regs;
	struct stmpe_variant_block *blocks;
	int num_blocks;
	int num_irqs;
	int (*enable)(struct stmpe *stmpe, unsigned int blocks, bool enable);
	int (*get_altfunc)(struct stmpe *stmpe, enum stmpe_block block);
	int (*enable_autosleep)(struct stmpe *stmpe, int autosleep_timeout);
};

/**
 * struct stmpe_client_info - i2c or spi specific routines/info
 * @data: client specific data
 * @read_byte: read single byte
 * @write_byte: write single byte
 * @read_block: read block or multiple bytes
 * @write_block: write block or multiple bytes
 * @init: client init routine, called during probe
 */
struct stmpe_client_info {
	void *data;
	int irq;
	void *client;
	struct device *dev;
	int (*read_byte)(struct stmpe *stmpe, u8 reg);
	int (*write_byte)(struct stmpe *stmpe, u8 reg, u8 val);
	int (*read_block)(struct stmpe *stmpe, u8 reg, u8 len, u8 *values);
	int (*write_block)(struct stmpe *stmpe, u8 reg, u8 len,
			const u8 *values);
	void (*init)(struct stmpe *stmpe);
};

int stmpe_probe(struct stmpe_client_info *ci, int partnum);
int stmpe_remove(struct stmpe *stmpe);

#define STMPE_ICR_LSB_HIGH	(1 << 2)
#define STMPE_ICR_LSB_EDGE	(1 << 1)
#define STMPE_ICR_LSB_GIM	(1 << 0)

/*
 * STMPE801
 */
#define STMPE801_ID			0x0108
#define STMPE801_NR_INTERNAL_IRQS	1

#define STMPE801_REG_CHIP_ID		0x00
#define STMPE801_REG_VERSION_ID		0x02
#define STMPE801_REG_SYS_CTRL		0x04
#define STMPE801_REG_GPIO_INT_EN	0x08
#define STMPE801_REG_GPIO_INT_STA	0x09
#define STMPE801_REG_GPIO_MP_STA	0x10
#define STMPE801_REG_GPIO_SET_PIN	0x11
#define STMPE801_REG_GPIO_DIR		0x12

#define STMPE801_REG_SYS_CTRL_RESET	(1 << 7)
#define STMPE801_REG_SYS_CTRL_INT_EN	(1 << 2)
#define STMPE801_REG_SYS_CTRL_INT_HI	(1 << 0)

/*
 * STMPE811
 */

#define STMPE811_IRQ_TOUCH_DET		0
#define STMPE811_IRQ_FIFO_TH		1
#define STMPE811_IRQ_FIFO_OFLOW		2
#define STMPE811_IRQ_FIFO_FULL		3
#define STMPE811_IRQ_FIFO_EMPTY		4
#define STMPE811_IRQ_TEMP_SENS		5
#define STMPE811_IRQ_ADC		6
#define STMPE811_IRQ_GPIOC		7
#define STMPE811_NR_INTERNAL_IRQS	8

#define STMPE811_REG_CHIP_ID		0x00
#define STMPE811_REG_SYS_CTRL2		0x04
#define STMPE811_REG_SPI_CFG		0x08
#define STMPE811_REG_INT_CTRL		0x09
#define STMPE811_REG_INT_EN		0x0A
#define STMPE811_REG_INT_STA		0x0B
#define STMPE811_REG_GPIO_INT_EN	0x0C
#define STMPE811_REG_GPIO_INT_STA	0x0D
#define STMPE811_REG_GPIO_SET_PIN	0x10
#define STMPE811_REG_GPIO_CLR_PIN	0x11
#define STMPE811_REG_GPIO_MP_STA	0x12
#define STMPE811_REG_GPIO_DIR		0x13
#define STMPE811_REG_GPIO_ED		0x14
#define STMPE811_REG_GPIO_RE		0x15
#define STMPE811_REG_GPIO_FE		0x16
#define STMPE811_REG_GPIO_AF		0x17

#define STMPE811_SYS_CTRL2_ADC_OFF	(1 << 0)
#define STMPE811_SYS_CTRL2_TSC_OFF	(1 << 1)
#define STMPE811_SYS_CTRL2_GPIO_OFF	(1 << 2)
#define STMPE811_SYS_CTRL2_TS_OFF	(1 << 3)

/*
 * STMPE1601
 */

#define STMPE1601_IRQ_GPIOC		8
#define STMPE1601_IRQ_PWM3		7
#define STMPE1601_IRQ_PWM2		6
#define STMPE1601_IRQ_PWM1		5
#define STMPE1601_IRQ_PWM0		4
#define STMPE1601_IRQ_KEYPAD_OVER	2
#define STMPE1601_IRQ_KEYPAD		1
#define STMPE1601_IRQ_WAKEUP		0
#define STMPE1601_NR_INTERNAL_IRQS	9

#define STMPE1601_REG_SYS_CTRL			0x02
#define STMPE1601_REG_SYS_CTRL2			0x03
#define STMPE1601_REG_ICR_LSB			0x11
#define STMPE1601_REG_IER_LSB			0x13
#define STMPE1601_REG_ISR_MSB			0x14
#define STMPE1601_REG_CHIP_ID			0x80
#define STMPE1601_REG_INT_EN_GPIO_MASK_LSB	0x17
#define STMPE1601_REG_INT_STA_GPIO_MSB		0x18
#define STMPE1601_REG_GPIO_MP_LSB		0x87
#define STMPE1601_REG_GPIO_SET_LSB		0x83
#define STMPE1601_REG_GPIO_CLR_LSB		0x85
#define STMPE1601_REG_GPIO_SET_DIR_LSB		0x89
#define STMPE1601_REG_GPIO_ED_MSB		0x8A
#define STMPE1601_REG_GPIO_RE_LSB		0x8D
#define STMPE1601_REG_GPIO_FE_LSB		0x8F
#define STMPE1601_REG_GPIO_AF_U_MSB		0x92

#define STMPE1601_SYS_CTRL_ENABLE_GPIO		(1 << 3)
#define STMPE1601_SYS_CTRL_ENABLE_KPC		(1 << 1)
#define STMPE1601_SYSCON_ENABLE_SPWM		(1 << 0)

/* The 1601/2403 share the same masks */
#define STMPE1601_AUTOSLEEP_TIMEOUT_MASK	(0x7)
#define STPME1601_AUTOSLEEP_ENABLE		(1 << 3)

/*
 * STMPE1801
 */
#define STMPE1801_ID			0xc110
#define STMPE1801_NR_INTERNAL_IRQS	5
#define STMPE1801_IRQ_KEYPAD_COMBI	4
#define STMPE1801_IRQ_GPIOC		3
#define STMPE1801_IRQ_KEYPAD_OVER	2
#define STMPE1801_IRQ_KEYPAD		1
#define STMPE1801_IRQ_WAKEUP		0

#define STMPE1801_REG_CHIP_ID			0x00
#define STMPE1801_REG_SYS_CTRL			0x02
#define STMPE1801_REG_INT_CTRL_LOW		0x04
#define STMPE1801_REG_INT_EN_MASK_LOW		0x06
#define STMPE1801_REG_INT_STA_LOW		0x08
#define STMPE1801_REG_INT_EN_GPIO_MASK_LOW	0x0A
#define STMPE1801_REG_INT_EN_GPIO_MASK_MID	0x0B
#define STMPE1801_REG_INT_EN_GPIO_MASK_HIGH	0x0C
#define STMPE1801_REG_INT_STA_GPIO_LOW		0x0D
#define STMPE1801_REG_INT_STA_GPIO_MID		0x0E
#define STMPE1801_REG_INT_STA_GPIO_HIGH		0x0F
#define STMPE1801_REG_GPIO_SET_LOW		0x10
#define STMPE1801_REG_GPIO_SET_MID		0x11
#define STMPE1801_REG_GPIO_SET_HIGH		0x12
#define STMPE1801_REG_GPIO_CLR_LOW		0x13
#define STMPE1801_REG_GPIO_CLR_MID		0x14
#define STMPE1801_REG_GPIO_CLR_HIGH		0x15
#define STMPE1801_REG_GPIO_MP_LOW		0x16
#define STMPE1801_REG_GPIO_MP_MID		0x17
#define STMPE1801_REG_GPIO_MP_HIGH		0x18
#define STMPE1801_REG_GPIO_SET_DIR_LOW		0x19
#define STMPE1801_REG_GPIO_SET_DIR_MID		0x1A
#define STMPE1801_REG_GPIO_SET_DIR_HIGH		0x1B
#define STMPE1801_REG_GPIO_RE_LOW		0x1C
#define STMPE1801_REG_GPIO_RE_MID		0x1D
#define STMPE1801_REG_GPIO_RE_HIGH		0x1E
#define STMPE1801_REG_GPIO_FE_LOW		0x1F
#define STMPE1801_REG_GPIO_FE_MID		0x20
#define STMPE1801_REG_GPIO_FE_HIGH		0x21
#define STMPE1801_REG_GPIO_PULL_UP_LOW		0x22
#define STMPE1801_REG_GPIO_PULL_UP_MID		0x23
#define STMPE1801_REG_GPIO_PULL_UP_HIGH		0x24

#define STMPE1801_MSK_SYS_CTRL_RESET		(1 << 7)

#define STMPE1801_MSK_INT_EN_KPC		(1 << 1)
#define STMPE1801_MSK_INT_EN_GPIO		(1 << 3)

/*
 * STMPE24xx
 */

#define STMPE24XX_IRQ_GPIOC		8
#define STMPE24XX_IRQ_PWM2		7
#define STMPE24XX_IRQ_PWM1		6
#define STMPE24XX_IRQ_PWM0		5
#define STMPE24XX_IRQ_ROT_OVER		4
#define STMPE24XX_IRQ_ROT		3
#define STMPE24XX_IRQ_KEYPAD_OVER	2
#define STMPE24XX_IRQ_KEYPAD		1
#define STMPE24XX_IRQ_WAKEUP		0
#define STMPE24XX_NR_INTERNAL_IRQS	9

#define STMPE24XX_REG_SYS_CTRL		0x02
#define STMPE24XX_REG_ICR_LSB		0x11
#define STMPE24XX_REG_IER_LSB		0x13
#define STMPE24XX_REG_ISR_MSB		0x14
#define STMPE24XX_REG_CHIP_ID		0x80
#define STMPE24XX_REG_IEGPIOR_LSB	0x18
#define STMPE24XX_REG_ISGPIOR_MSB	0x19
#define STMPE24XX_REG_GPMR_LSB		0xA5
#define STMPE24XX_REG_GPSR_LSB		0x85
#define STMPE24XX_REG_GPCR_LSB		0x88
#define STMPE24XX_REG_GPDR_LSB		0x8B
#define STMPE24XX_REG_GPEDR_MSB		0x8C
#define STMPE24XX_REG_GPRER_LSB		0x91
#define STMPE24XX_REG_GPFER_LSB		0x94
#define STMPE24XX_REG_GPAFR_U_MSB	0x9B

#define STMPE24XX_SYS_CTRL_ENABLE_GPIO		(1 << 3)
#define STMPE24XX_SYSCON_ENABLE_PWM		(1 << 2)
#define STMPE24XX_SYS_CTRL_ENABLE_KPC		(1 << 1)
#define STMPE24XX_SYSCON_ENABLE_ROT		(1 << 0)

#endif

{'repo_name': 'o11s/open80211s', 'stars': '215', 'repo_language': 'C', 'file_name': 'xt_iprange.c', 'mime_type': 'text/x-c', 'hash': 137586024916960499, 'source_dataset': 'data'}


using System.Threading.Tasks;
using Abp.Application.Services;
using Acme.ProjectName.Authorization.Accounts.Dto;

namespace Acme.ProjectName.Authorization.Accounts
{
    public interface IAccountAppService : IApplicationService
    {
        Task<IsTenantAvailableOutput> IsTenantAvailable(IsTenantAvailableInput input);

        Task<RegisterOutput> Register(RegisterInput input);
    }
}

{'repo_name': 'aspnetboilerplate/aspnetboilerplate-samples', 'stars': '649', 'repo_language': 'JavaScript', 'file_name': 'ui-utils-ieshiv.js', 'mime_type': 'text/html', 'hash': 6606713400958778843, 'source_dataset': 'data'}


// Copyright (c) 2016, Baidu.com, Inc. All Rights Reserved
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#pragma once
#include "collector/collector.h"

#include "boost/thread/mutex.hpp"
#include "boost/shared_ptr.hpp"

namespace baidu {
namespace galaxy {
namespace proto {
class CgroupMetrix;
}

namespace cgroup {
class Cgroup;

class CgroupCollector : public baidu::galaxy::collector::Collector {
public:
    explicit CgroupCollector();
    ~CgroupCollector();

    baidu::galaxy::util::ErrorCode Collect();

    void Enable(bool enable);
    bool Enabled();
    bool Equal(const Collector*);
    void SetCycle(int cycle);
    int Cycle(); // unit second
    std::string Name() const;
    void SetName(const std::string& name);
    boost::shared_ptr<baidu::galaxy::proto::CgroupMetrix> Statistics();

    void SetCpuacctPath(const std::string& path) {
        cpuacct_path_ = path;
    }

    void SetMemoryPath(const std::string& path) {
        memory_path_ = path;
    }

private:
    baidu::galaxy::util::ErrorCode Collect(boost::shared_ptr<baidu::galaxy::proto::CgroupMetrix> metrix);
    baidu::galaxy::util::ErrorCode ContainerCpuStat(boost::shared_ptr<baidu::galaxy::proto::CgroupMetrix> metrix);
    baidu::galaxy::util::ErrorCode SystemCpuStat(boost::shared_ptr<baidu::galaxy::proto::CgroupMetrix> metrix);
    baidu::galaxy::util::ErrorCode MemoryStat(boost::shared_ptr<baidu::galaxy::proto::CgroupMetrix> metrix);

    bool enabled_;
    int cycle_;
    std::string name_;
    boost::mutex mutex_;

    boost::shared_ptr<baidu::galaxy::proto::CgroupMetrix> metrix_;
    int64_t last_time_;
    std::string cpuacct_path_;
    std::string memory_path_;
};
}
}
}

{'repo_name': 'baidu/galaxy', 'stars': '326', 'repo_language': 'C++', 'file_name': 'galaxy_client.md', 'mime_type': 'text/plain', 'hash': 7097870250993808801, 'source_dataset': 'data'}


/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
/* ***** BEGIN LICENSE BLOCK *****
 * Version: MPL 1.1/GPL 2.0/LGPL 2.1
 *
 * The contents of this file are subject to the Mozilla Public License Version
 * 1.1 (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.mozilla.org/MPL/
 *
 * Software distributed under the License is distributed on an "AS IS" basis,
 * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
 * for the specific language governing rights and limitations under the
 * License.
 *
 * The Original Code is JavaScript Engine testing utilities.
 *
 * The Initial Developer of the Original Code is
 * Mozilla Foundation.
 * Portions created by the Initial Developer are Copyright (C) 2005
 * the Initial Developer. All Rights Reserved.
 *
 * Contributor(s): Igor Bukanov
 *
 * Alternatively, the contents of this file may be used under the terms of
 * either the GNU General Public License Version 2 or later (the "GPL"), or
 * the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
 * in which case the provisions of the GPL or the LGPL are applicable instead
 * of those above. If you wish to allow use of your version of this file only
 * under the terms of either the GPL or the LGPL, and not to allow others to
 * use your version of this file under the terms of the MPL, indicate your
 * decision by deleting the provisions above and replace them with the notice
 * and other provisions required by the GPL or the LGPL. If you do not delete
 * the provisions above, a recipient may use your version of this file under
 * the terms of any one of the MPL, the GPL or the LGPL.
 *
 * ***** END LICENSE BLOCK ***** */
//-----------------------------------------------------------------------------
var bug = 310425;
var summary = 'Array.indexOf/lastIndexOf edge cases';
var actual = '';
var expect = '';

printBugNumber (bug);
printStatus (summary);

expect = -1;
actual = Array(1).indexOf(1);
reportCompare(expect, actual, summary);

{'repo_name': 'BlzFans/wke', 'stars': '293', 'repo_language': 'C++', 'file_name': 'wkeDebug.vsprops', 'mime_type': 'text/xml', 'hash': -2854907604996825500, 'source_dataset': 'data'}


/*
 *
 * 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.
 *
*/

/**
 * The CaptureError interface encapsulates all errors in the Capture API.
 */
var CaptureError = function(c) {
   this.code = c || null;
};

// Camera or microphone failed to capture image or sound.
CaptureError.CAPTURE_INTERNAL_ERR = 0;
// Camera application or audio capture application is currently serving other capture request.
CaptureError.CAPTURE_APPLICATION_BUSY = 1;
// Invalid use of the API (e.g. limit parameter has value less than one).
CaptureError.CAPTURE_INVALID_ARGUMENT = 2;
// User exited camera application or audio capture application before capturing anything.
CaptureError.CAPTURE_NO_MEDIA_FILES = 3;
// The requested capture operation is not supported.
CaptureError.CAPTURE_NOT_SUPPORTED = 20;

module.exports = CaptureError;

{'repo_name': 'akveo/chernika-mobile', 'stars': '150', 'repo_language': 'JavaScript', 'file_name': 'index.md', 'mime_type': 'text/plain', 'hash': 6832175583460409404, 'source_dataset': 'data'}


<!DOCTYPE html>

  <meta charset="utf-8" />
  <title translate="yes">Sauniga</title>
  <link href="/public/pure-min.css" rel="stylesheet">
  <link href="/public/content.css" rel="stylesheet">
  <link href="/public/content-additional.css" rel="stylesheet">
  <base target="_top" href="/">

Sauniga

Neʻi fausia i taimi uma saini faʻaaoga se tagata faʻaaoga.

E leai ni sauniga.

        ID
        Teugatupe
        Igoa
        Imeli faʻaaliga
        Na faia
        Ua muta

  <template id="page-link">

      ${page.pageNumber}

  </template>
  <template id="session-row">

        ${session.sessionid}

        ${session.accountid}

      ${session.firstName} ${session.lastName}

        ${session.email}

      ${session.createdFormatted}
      ${session.expiresFormatted}

  </template>

{'repo_name': 'userdashboard/dashboard', 'stars': '220', 'repo_language': 'HTML', 'file_name': 'reset-codes.html', 'mime_type': 'text/html', 'hash': 3522905078281385905, 'source_dataset': 'data'}


/**********************************************************************
Copyright (C) 2008 Geoffrey R. Hutchison
Some portions Copyright (C) 2004 by Chris Morley

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 version 2 of the License.

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.
***********************************************************************/

#include <openbabel/babelconfig.h>
#include <openbabel/obmolecformat.h>
#include <openbabel/mol.h>
#include <openbabel/atom.h>
#include <openbabel/elements.h>
#include <openbabel/generic.h>
#include <openbabel/obiter.h>
#include <openbabel/data.h>

#include <vector>
#include <map>

#include <sstream>
#include <cstdlib>

using namespace std;
namespace OpenBabel
{

  class PQRFormat : public OBMoleculeFormat
  {
  public:
    //Register this format type ID
    PQRFormat()
    {
      OBConversion::RegisterFormat("pqr",this, "chemical/x-pqr");
    }

    virtual const char* Description() //required
    {
      return
        "PQR format\n"
        "Read Options e.g. -as\n"
        "  s  Output single bonds only\n"
        "  b  Disable bonding entirely\n\n";
    };

    virtual const char* SpecificationURL()
    { return "";};

    virtual const char* GetMIMEType()
    { return "chemical/x-pqr"; };

    //*** This section identical for most OBMol conversions ***
    ////////////////////////////////////////////////////
    /// The "API" interface functions
    virtual int SkipObjects(int n, OBConversion* pConv);
    virtual bool ReadMolecule(OBBase* pOb, OBConversion* pConv);
    virtual bool WriteMolecule(OBBase* pOb, OBConversion* pConv);

  };
  //***

  //Make an instance of the format class
  PQRFormat thePQRFormat;

  ////////////////////////////////////////////////////////////////
  /// Utility functions
  static bool parseAtomRecord(char *buffer, OBMol &mol,int /*chainNum*/);
  static double parseAtomRadius(char *buffer, OBMol &mol);
  static double parseAtomCharge(char *buffer, OBMol &mol);

  /////////////////////////////////////////////////////////////////
  int PQRFormat::SkipObjects(int n, OBConversion* pConv)
  {
    if (n == 0)
      ++ n;
    istream &ifs = *pConv->GetInStream();
    char buffer[BUFF_SIZE];
    while (n && ifs.getline(buffer,BUFF_SIZE))
      {
        if (EQn(buffer,"ENDMDL",6))
          -- n;
      }

    return ifs.good() ? 1 : -1;
  }
  /////////////////////////////////////////////////////////////////
  bool PQRFormat::ReadMolecule(OBBase* pOb, OBConversion* pConv)
  {

    OBMol* pmol = pOb->CastAndClear<OBMol>();
    if (pmol == nullptr)
      return false;

    //Define some references so we can use the old parameter names
    istream &ifs = *pConv->GetInStream();
    OBMol &mol = *pmol;
    const char* title = pConv->GetTitle();

    int chainNum = 1;
    char buffer[BUFF_SIZE];
    vector<double> charges, radii;
    string line, key, value;

    mol.SetTitle(title);
    mol.SetChainsPerceived(); // It's a PDB-like file, we read all chain/res info.

    mol.BeginModify();
    while (ifs.good() && ifs.getline(buffer,BUFF_SIZE))
      {
        if (EQn(buffer,"ENDMDL",6))
          break;
        if (EQn(buffer,"END",3)) {
          // eat anything until the next ENDMDL
          while (ifs.getline(buffer,BUFF_SIZE) && !EQn(buffer,"ENDMDL",6));
          break;
        }
        if (EQn(buffer,"TER",3)) {
          chainNum++;
          continue;
        }
        if (EQn(buffer,"ATOM",4) || EQn(buffer,"HETATM",6))
          {
            if( ! parseAtomRecord(buffer,mol,chainNum))
              {
                stringstream errorMsg;
                errorMsg << "WARNING: Problems reading a PQR file\n"
                         << "  Problems reading a ATOM/HETATM record.\n";
                obErrorLog.ThrowError(__FUNCTION__, errorMsg.str() , obError);
              }

            // Read in the partial charge and radius too
            charges.push_back( parseAtomCharge(buffer, mol) );
            radii.push_back( parseAtomRadius(buffer, mol) );
            continue;
          }
        }

    if (!mol.NumAtoms()) { // skip the rest of this processing
      mol.EndModify();
      return(false);
    }

    // Use residue definitions to assign bond orders
    resdat.AssignBonds(mol);

    mol.EndModify();

    /*Now assign hetatm bonds based on distance*/
    if (!pConv->IsOption("b",OBConversion::INOPTIONS))
      mol.ConnectTheDots();

    if (!pConv->IsOption("s",OBConversion::INOPTIONS) && !pConv->IsOption("b",OBConversion::INOPTIONS))
      mol.PerceiveBondOrders();

    FOR_ATOMS_OF_MOL(a, mol) {
      // WARNING: Atom index issue here
      a->SetPartialCharge(charges[a->GetIdx() - 1]);

      cerr << " charge : " << charges[a->GetIdx() - 1] << endl;

      if (!a->HasData("Radius")) {
        std::ostringstream s;
        s << radii[ a->GetIdx()-1 ];
        OBPairData *p = new OBPairData;
        p->SetAttribute("Radius");
        p->SetValue( s.str() );
        a->SetData(p);
      }

      cerr << " radius : " << radii[a->GetIdx() - 1] << endl;

    }
    mol.SetPartialChargesPerceived();
    mol.SetChainsPerceived();

    // clean out remaining blank lines
    std::streampos ipos;
    do
    {
      ipos = ifs.tellg();
      ifs.getline(buffer,BUFF_SIZE);
    }
    while(strlen(buffer) == 0 && !ifs.eof() );
    ifs.seekg(ipos);

    return(true);
  }

  static double parseAtomCharge(char *buffer, OBMol &mol)
  // In PQR format, either:
  // Field name, atom number, atom name, residue name, residue number
  //    x y z charge radius element
  // OR
  // Field, atom number, atom name, chain id, residue number, X, Y, Z, chg, rad, ele
  {
    vector<string> vs;
    tokenize(vs,buffer);

    OBAtom *atom = mol.GetAtom(mol.NumAtoms());

    if (vs.size() == 11)//add element, Zhixiong Zhao
      return atof(vs[8].c_str());
    else if (vs.size() == 12)
      return atof(vs[9].c_str());

    return 0.0;
  }

  static double parseAtomRadius(char *buffer, OBMol &mol)
  {
    vector<string> vs;
    tokenize(vs,buffer);

    OBAtom *atom = mol.GetAtom(mol.NumAtoms());

    if (vs.size() == 11)
      return atof(vs[9].c_str());
    else if (vs.size() == 12)
      return atof(vs[10].c_str());

    return 0.0;
  }

  static bool parseAtomRecord(char *buffer, OBMol &mol,int /*chainNum*/)
  /* ATOMFORMAT "(i5,1x,a4,a1,a3,1x,a1,i4,a1,3x,3f8.3,2f6.2,1x,i3)" */
  {
    string sbuf = &buffer[6];
    if (sbuf.size() < 48)
      return(false);

    bool hetatm = (EQn(buffer,"HETATM",6)) ? true : false;

    /* serial number */
    string serno = sbuf.substr(0,5);
    //SerialNum(the_atom) = atoi(tmp_str);

    /* atom name */
    string atmid = sbuf.substr(6,4);

    /* chain */
    char chain = sbuf.substr(15,1)[0];

    /* element */
    string element;
    if (sbuf.size() > 71)
      element = sbuf.substr(70,2);
    else
      element = "  ";

    //trim spaces on the right and left sides
    while (!atmid.empty() && atmid[0] == ' ')
      atmid = atmid.substr(1,atmid.size()-1);

    while (!atmid.empty() && atmid[atmid.size()-1] == ' ')
      atmid = atmid.substr(0,atmid.size()-1);

    /* residue name */

    string resname = sbuf.substr(11,3);
    if (resname == "   ")
      resname = "UNK";
    else
      {
        while (!resname.empty() && resname[0] == ' ')
          resname = resname.substr(1,resname.size()-1);

        while (!resname.empty() && resname[resname.size()-1] == ' ')
          resname = resname.substr(0,resname.size()-1);
      }

    string type;
    if (EQn(buffer,"ATOM",4))
      {
        type = atmid.substr(0,2);
        if (isdigit(type[0])) {
          // sometimes non-standard files have, e.g 11HH
          if (!isdigit(type[1])) type = atmid.substr(1,1);
          else type = atmid.substr(2,1);
        } else if ((sbuf[6] == ' ' &&
                    strncasecmp(type.c_str(), "Zn", 2) != 0 &&
                    strncasecmp(type.c_str(), "Fe", 2) != 0) ||
                   isdigit(type[1]))    //type[1] is digit in Platon
          type = atmid.substr(0,1);     // one-character element

        if (resname.substr(0,2) == "AS" || resname[0] == 'N')
          {
            if (atmid == "AD1")
              type = "O";
            if (atmid == "AD2")
              type = "N";
          }
        if (resname.substr(0,3) == "HIS" || resname[0] == 'H')
          {
            if (atmid == "AD1" || atmid == "AE2")
              type = "N";
            if (atmid == "AE1" || atmid == "AD2")
              type = "C";
          }
        if (resname.substr(0,2) == "GL" || resname[0] == 'Q')
          {
            if (atmid == "AE1")
              type = "O";
            if (atmid == "AE2")
              type = "N";
          }
        // fix: #2002557
        if (atmid[0] == 'H' &&
            (atmid[1] == 'D' || atmid[1] == 'E' ||
             atmid[1] == 'G' || atmid[1] == 'H')) // HD, HE, HG, HH, ..
          type = "H";
      }
    else //must be hetatm record
      {
        if (isalpha(element[1]) && (isalpha(element[0]) || (element[0] == ' ')))
          {
            if (isalpha(element[0]))
              type = element.substr(0,2);
            else
              type = element.substr(1,1);
            if (type.size() == 2)
              type[1] = tolower(type[1]);
          }
        else
          {
            if (isalpha(atmid[0]))
              {
              if (atmid.size() > 2 && (atmid[2] == '\0' || atmid[2] == ' '))
                type = atmid.substr(0,2);
              else if (atmid[0] == 'A') // alpha prefix
                type = atmid.substr(1, atmid.size() - 1);
              else
                type = atmid.substr(0,1);
              }
            else if (atmid[0] == ' ')
              type = atmid.substr(1,1); // one char element
            else
              type = atmid.substr(1,2);

            // Some cleanup steps
            if (atmid == resname)
              {
                type = atmid;
                if (type.size() == 2)
                  type[1] = tolower(type[1]);
              }
            else
              if (resname == "ADR" || resname == "COA" || resname == "FAD" ||
                  resname == "GPG" || resname == "NAD" || resname == "NAL" ||
                  resname == "NDP" || resname == "ABA")
                {
                  if (type.size() > 1)
                    type = type.substr(0,1);
                  //type.erase(1,type.size()-1);
                }
              else
                if (isdigit(type[0]))
                  {
                    type = type.substr(1,1);
                  }
                else
                  if (type.size() > 1 && isdigit(type[1]))
                    type = type.substr(0,1);
                  else
                    if (type.size() > 1 && isalpha(type[1])) {
                      if (type[0] == 'O' && type[1] == 'H')
                        type = type.substr(0,1); // no "Oh" element (e.g. 1MBN)
                      else if(isupper(type[1]))
                        {
                          type[1] = tolower(type[1]);
                        }
                    }
          }

      }

    OBAtom atom;
    /* X, Y, Z */
    string xstr = sbuf.substr(24,8);
    string ystr = sbuf.substr(32,8);
    string zstr = sbuf.substr(40,8);
    vector3 v(atof(xstr.c_str()),atof(ystr.c_str()),atof(zstr.c_str()));
    atom.SetVector(v);

    // useful for debugging unknown atom types (e.g., PR#1577238)
    //    cout << mol.NumAtoms() + 1 << " " << atmid << " type: " << type << endl;
    atom.SetAtomicNum(OBElements::GetAtomicNum(type.c_str()));

    /* residue sequence number */
    string resnum = sbuf.substr(16,4);
    OBResidue *res  = mol.NumResidues() > 0 ? mol.GetResidue(mol.NumResidues()-1) : nullptr;
    if (res == nullptr || res->GetName() != resname
        || res->GetNumString() != resnum)
      {
        vector<OBResidue*>::iterator ri;
        for (res = mol.BeginResidue(ri) ; res ; res = mol.NextResidue(ri))
          if (res->GetName() == resname
              && res->GetNumString() == resnum
              && static_cast<int>(res->GetChain()) == chain)
            break;

        if (res == nullptr)
          {
            res = mol.NewResidue();
            res->SetChain(chain);
            res->SetName(resname);
            res->SetNum(resnum);
          }
      }

    if (!mol.AddAtom(atom))
      return(false);
    else
      {
        OBAtom *atom = mol.GetAtom(mol.NumAtoms());

        res->AddAtom(atom);
        res->SetSerialNum(atom, atoi(serno.c_str()));
        res->SetAtomID(atom, sbuf.substr(6,4));
        res->SetHetAtom(atom, hetatm);

        return(true);
      }
  }

  bool PQRFormat::WriteMolecule(OBBase* pOb, OBConversion* pConv)
  {
    OBMol* pmol = dynamic_cast<OBMol*>(pOb);
    if (pmol == nullptr)
      return false;

    //Define some references so we can use the old parameter names
    ostream &ofs = *pConv->GetOutStream();
    OBMol &mol = *pmol;

    unsigned int i;
    char buffer[BUFF_SIZE];
    char type_name[10], padded_name[10];
    char the_res[10];
    char the_chain = ' ';
    const char *element_name;
    int res_num;
    bool het=true;
    int model_num = 0;
    if (!pConv->IsLast() || pConv->GetOutputIndex() > 1)
      { // More than one molecule record
      model_num = pConv->GetOutputIndex(); // MODEL 1-based index
      snprintf(buffer, BUFF_SIZE, "MODEL %8d", model_num);
      ofs << buffer << endl;
      }

    if (strlen(mol.GetTitle()) > 0)
      snprintf(buffer, BUFF_SIZE, "COMPND    %s ",mol.GetTitle());
    else
      snprintf(buffer, BUFF_SIZE, "COMPND    UNNAMED");
    ofs << buffer << endl;

    snprintf(buffer, BUFF_SIZE, "AUTHOR    GENERATED BY OPEN BABEL %s",BABEL_VERSION);
    ofs << buffer << endl;

    // before we write any records, we should check to see if any coord < -1000
    // which will cause errors in the formatting

    double minX, minY, minZ;
    minX = minY = minZ = -999.0f;
    FOR_ATOMS_OF_MOL(a, mol)
      {
        if (a->GetX() < minX)
          minX = a->GetX();
        if (a->GetY() < minY)
          minY = a->GetY();
        if (a->GetZ() < minZ)
          minZ = a->GetZ();
      }

    vector3 transV = VZero;
    if (minX < -999.0)
      transV.SetX( -1.0*minX - 900.0 );
    if (minY < -999.0)
      transV.SetY( -1.0*minY - 900.0 );
    if (minZ < -999.0)
      transV.SetZ( -1.0*minZ - 900.0 );

    // if minX, minY, or minZ was never changed, shift will be 0.0f
    // otherwise, move enough so that smallest coord is > -999.0f
    mol.Translate(transV);

    OBAtom *atom;
    OBResidue *res;
    for (i = 1; i <= mol.NumAtoms(); i++)
      {
        atom = mol.GetAtom(i);
        strncpy(type_name, OBElements::GetSymbol(atom->GetAtomicNum()), sizeof(type_name));
        type_name[sizeof(type_name) - 1] = '\0';

        //two char. elements are on position 13 and 14 one char. start at 14
        if (strlen(type_name) > 1)
          type_name[1] = toupper(type_name[1]);
        else
          {
            char tmp[10];
            strncpy(tmp, type_name, 9); // make sure to null-terminate
            snprintf(type_name, sizeof(type_name), " %-3s", tmp);
          }

        if ((res = atom->GetResidue()) != nullptr)
          {
            het = res->IsHetAtom(atom);
            snprintf(the_res,4,"%s",(char*)res->GetName().c_str());
            snprintf(type_name,5,"%s",(char*)res->GetAtomID(atom).c_str());
            the_chain = res->GetChain();

            //two char. elements are on position 13 and 14 one char. start at 14
            if (strlen(OBElements::GetSymbol(atom->GetAtomicNum())) == 1)
              {
                if (strlen(type_name) < 4)
                  {
                    char tmp[16];
                    strncpy(tmp, type_name, 15); // make sure to null-terminate
                    snprintf(padded_name, sizeof(padded_name), " %-3s", tmp);
                    strncpy(type_name,padded_name,4);
                    type_name[4] = '\0';
                  }
                else
                  {
                    type_name[4] = '\0';
                  }
              }
            res_num = res->GetNum();
          }
        else
          {
            strcpy(the_res,"UNK");
            snprintf(padded_name,sizeof(padded_name), "%s",type_name);
            strncpy(type_name,padded_name,4);
            type_name[4] = '\0';
            res_num = 1;
          }

        element_name = OBElements::GetSymbol(atom->GetAtomicNum());
        //snprintf(buffer, BUFF_SIZE, "%s%5d %-4s %-3s %c%4d    %8.3f%8.3f%8.3f  1.00  0.00          %2s  \n",
        snprintf(buffer, BUFF_SIZE, "%s%5d %-4s %-3s %c%4d    %8.3f%8.3f%8.3f %11.8f%8.3f %2s  \n",
                 het?"HETATM":"ATOM  ",
                 i,
                 type_name,
                 the_res,
		 the_chain,
                 res_num,
                 atom->GetX(),
                 atom->GetY(),
                 atom->GetZ(),
                 atom->GetPartialCharge(),
                 atom->HasData("Radius")//use atom radius data,Zhixiong Zhao
				 	?atof(atom->GetData("Radius")->GetValue().c_str())
					:OBElements::GetVdwRad(atom->GetAtomicNum()),
                 element_name);
        ofs << buffer;
      }

    OBAtom *nbr;
    vector<OBBond*>::iterator k;
    for (i = 1; i <= mol.NumAtoms(); i ++)
      {
        atom = mol.GetAtom(i);
        if (atom->GetExplicitDegree() == 0)
          continue; // no need to write a CONECT record -- no bonds

        snprintf(buffer, BUFF_SIZE, "CONECT%5d", i);
        ofs << buffer;
        // Write out up to 4 real bonds per line PR#1711154
        int currentValence = 0;
        for (nbr = atom->BeginNbrAtom(k);nbr;nbr = atom->NextNbrAtom(k))
          {
            snprintf(buffer, BUFF_SIZE, "%5d", nbr->GetIdx());
            ofs << buffer;
            if (++currentValence % 4 == 0) {
              // Add the trailing space to finish this record
              ofs << "                                       \n";
              // write the start of a new CONECT record
              snprintf(buffer, BUFF_SIZE, "CONECT%5d", i);
              ofs << buffer;
            }
          }

        // Add trailing spaces
        int remainingValence = atom->GetExplicitDegree() % 4;
        for (int count = 0; count < (4 - remainingValence); count++) {
          snprintf(buffer, BUFF_SIZE, "     ");
          ofs << buffer;
        }
        ofs << "                                       \n";
      }

    snprintf(buffer, BUFF_SIZE, "MASTER        0    0    0    0    0    0    0    0 ");
    ofs << buffer;
    snprintf(buffer, BUFF_SIZE, "%4d    0 %4d    0\n",mol.NumAtoms(),mol.NumAtoms());
    ofs << buffer;

    ofs << "END\n";
    if (model_num) {
      ofs << "ENDMDL" << endl;
    }

    return(true);
  }

} //namespace OpenBabel

{'repo_name': 'openbabel/openbabel', 'stars': '404', 'repo_language': 'C++', 'file_name': 'README-UNIX.txt', 'mime_type': 'text/plain', 'hash': 4274441747067397110, 'source_dataset': 'data'}


"""Utility module to read input mesh files.  This is primarily for meshes
generated using Gmsh.  This module also provides some simple classes
that allow one to create extruded 3D surfaces by generating a gmsh file
in Python.

There is also a function to read VTK dataset and produce points from them.
This is very useful as Gmsh can generate VTK datasets from its meshes and thus
the meshes can be imported as point clouds that may be used in an SPH
simulation.
"""
# Copyright (c) 2015 Prabhu Ramachandran

import gzip
import json

import numpy as np
import subprocess

import tempfile
from tvtk.api import tvtk

import os
from os.path import exists, expanduser, join
import sys

def _read_vtk_file(fname):
    """Given a .vtk file (or .vtk.gz), read it and return the output.
    """
    if fname.endswith('.vtk.gz'):
        tmpfname = tempfile.mktemp(suffix='.vtk')
        with open(tmpfname, 'wb') as tmpf:
            data = gzip.open(fname).read()
            tmpf.write(data)
        r = tvtk.DataSetReader(file_name=tmpfname)
    else:
        tmpfname = None
        r = tvtk.DataSetReader(file_name=fname)
    r.update()
    if tmpfname is not None:
        os.remove(tmpfname)
    return r.output

def _convert_to_points(dataset, vertices=True, cell_centers=True):
    """Given a VTK dataset, convert it to a set of points that can be used
    for simulation with SPH.

    Parameters
    ----------

    dataset : tvtk.DataSet
    vertices: bool
        If True, it converts the vertices to points.
    cell_centers: bool
        If True, converts the cell centers to points.

    Returns
    -------

    x, y, z of the points.
    """
    pts = np.array([], dtype=float)
    if vertices:
        pts = np.append(pts, dataset.points.to_array())
    if cell_centers:
        cell_centers = tvtk.CellCenters(input=dataset)
        cell_centers.update()
        p = cell_centers.output.points.to_array()
        pts = np.append(pts, p)
    pts.shape = len(pts)//3, 3
    x, y, z = pts.T
    return x, y, z

def vtk_file_to_points(fname, vertices=True, cell_centers=True):
    """Given a file containing a VTK dataset (currently only an old style .vtk
    file), convert it to a set of points that can be used for simulation with
    SPH.

    Parameters
    ----------

    fname : str
        File name.
    vertices: bool
        If True, it converts the vertices to points.
    cell_centers: bool
        If True, converts the cell centers to points.

    Returns
    -------

    x, y, z of the points.
    """
    dataset = _read_vtk_file(fname)
    return _convert_to_points(dataset, vertices, cell_centers)

def transform_points(x, y, z, transform):
    """Given the coordinates, x, y, z and the TVTK transform instance,
    return the transformed coordinates.
    """
    assert isinstance(transform, tvtk.Transform)

    m = transform.matrix.to_array()
    xt, yt, zt, wt = np.dot(m, np.array((x, y, z, np.ones_like(x))))
    return xt, yt, zt

class Loop(object):
    """Create a Line Loop in Gmsh parlance but using a turtle-graphics like
    approach.

    Use this to create a 2D closed surface.  The surface is always in the x-y
    plane.

    Examples
    --------

    Here is a simple example::

      >>> l1 = Loop((0.0, 0.0), mesh_size=0.1)
      >>> l1.move(1.0).turn(90).move(1.0).turn(90).move(1.0).turn(90).move(1.0)

    This will create a square shape.

    """

    def __init__(self, start, mesh_size=0.1):
        self.mesh_size = mesh_size
        self.points = [start]
        self.elems = []
        self.tolerance = 1e-12
        self._last_angle = 0.0
        self._last_position = start
        self._index = 1

    ### Public Protocol ###################################
    def turn(self, angle):
        """Turn by angle (in degrees).
        """
        self._last_angle += angle
        return self

    def move(self, dist):
        """Move by given distance at the current angle.
        """
        x0, y0 = self._last_position
        angle = self._last_angle
        rad = np.pi*angle/180.
        x = x0 + dist*np.cos(rad)
        y = y0 + dist*np.sin(rad)
        p1 = self._index
        p2 = self._add_point(x, y)
        self._add_elem('line', (p1, p2))
        return self

    def arc(self, radius, angle=180):
        """Create a circular arc given the radius and for an angle as
        specified.
        """
        x0, y0 = self._last_position
        last_angle = self._last_angle
        rad = np.pi*last_angle/180.
        last = complex(x0, y0)
        dz = complex(np.cos(rad), np.sin(rad))
        cen = last + radius*dz
        rad = np.pi*angle/180.
        end = cen + (last - cen)*complex(np.cos(rad), np.sin(rad))
        s_idx = self._index
        c_idx = self._add_point(cen.real, cen.imag)
        e_idx = self._add_point(end.real, end.imag)
        self._add_elem('circle', (s_idx, c_idx, e_idx))
        return self

    def write(self, fp, point_id_base=0, elem_id_base=0):
        """Write data to given file object `fp`.
        """
        points = self.points
        for i in range(len(points)):
            idx = point_id_base + i + 1
            self._write_point(fp, points[i], idx)

        elems = self.elems
        idx = 0
        loop = []
        for i in range(len(elems)):
            elem = elems[i]
            idx = elem_id_base + i + 1
            loop.append(str(idx))
            kind, data = elem[0], elem[1]
            if kind == 'line':
                self._write_line(fp, data, idx, point_id_base)
            elif kind == 'circle':
                self._write_circle(fp, data, idx, point_id_base)
        idx += 1
        ids = ', '.join(loop)
        s = 'Line Loop({idx}) = {{{ids}}};\n'.format(idx=idx, ids=ids)
        fp.write(s)
        return len(points), len(elems) + 1

    ### Private Protocol #################################
    def _add_elem(self, kind, data):
        self.elems.append((kind, data))

    def _check_for_existing_point(self, x, y):
        tol = self.tolerance
        for i, (xi, yi) in enumerate(self.points):
            if abs(xi - x) < tol and abs(yi - y) < tol:
                return i + 1

    def _add_point(self, x, y):
        last_x, last_y = self._last_position
        pnt = (x, y)
        existing = self._check_for_existing_point(x, y)
        if existing is None:
            self.points.append(pnt)
            self._index += 1
            index = self._index
        else:
            index = existing
            pnt = self.points[existing]
        self._last_position = pnt
        return index

    def _write_point(self, fp, pnt, idx):
        fp.write('Point({idx}) = {{{x}, {y}, 0.0, {mesh_size}}};\n'.\
            format(x=pnt[0], y=pnt[1], idx=idx, mesh_size=self.mesh_size))

    def _write_line(self, fp, data, e_idx, p_idx):
        s = 'Line({idx}) = {{{p1}, {p2}}};\n'.format(
            idx=e_idx, p1=data[0]+p_idx, p2=data[1] +p_idx
        )
        fp.write(s)

    def _write_circle(self, fp, data, e_idx, p_idx):
        s = 'Circle({idx}) = {{{start}, {cen}, {end}}};\n'.format(
            idx=e_idx, start=data[0]+p_idx, cen=data[1]+p_idx, end=data[2] +p_idx
        )
        fp.write(s)

class Surface(object):
    def __init__(self, *loops):
        """Constructor.

        Parameters
        ----------

        loops : tuple(Loop)
            Any additional positional arguments are treated as loop objects.
        """
        self.loops = list(loops)
        self.idx = 0

    def write(self, fp, point_id_base=0, elem_id_base=0):
        pid_base = point_id_base
        eid_base = elem_id_base
        loop_ids = []
        for loop in self.loops:
            np, ne = loop.write(fp, pid_base, eid_base)
            pid_base += np
            eid_base += ne
            loop_ids.append(str(eid_base))
        idx = eid_base + 1
        loop_str = ', '.join(loop_ids)
        fp.write('Plane Surface({idx}) = {{{loop_str}}};\n'.format(
                idx=idx, loop_str=loop_str))
        self.idx = idx
        return pid_base, eid_base

class Extrude(object):
    def __init__(self, dx=0.0, dy=0.0, dz=1.0, surfaces=None):
        """Extrude a given set of surfaces by the displacements given
        along each directions.

        Parameters
        ----------

        dx : float
            Extrusion along x.
        dy : float
            Extrusion along y.
        dz : float
            Extrusion along z.
        surfaces: list
            List of surfaces to extrude.

        """
        self.dx, self.dy, self.dz = dx, dy, dz
        if surfaces is None:
            self.surfaces = []
        else:
            self.surfaces = list(surfaces)

    def write(self, fp, point_id_base=0, elem_id_base=0):
        pid_base = point_id_base
        eid_base = elem_id_base
        surf_ids = []
        for surf in self.surfaces:
            np, ne = surf.write(fp, pid_base, eid_base)
            pid_base += np
            eid_base += ne
            surf_ids.append(str(surf.idx))

        s_ids = ', '.join(surf_ids)
        fp.write(
            'Extrude {{{dx}, {dy}, {dz}}} {{\n'
            '    Surface{{{s_ids}}};\n}}\n'.format(
            dx=self.dx, dy=self.dy, dz=self.dz, s_ids=s_ids
            )
        )
        return pid_base, eid_base

class Gmsh(object):
    def __init__(self, gmsh=None):
        """Construct a Gmsh helper object that can be used to mesh objects.

        Parameters
        ----------

        gmsh: str
            Path to gmsh executable.
        """
        self.config = expanduser(join('~', '.pysph', 'gmsh.json'))
        if gmsh is None:
            if exists(self.config):
                self._read_config()
            else:
                gmsh = self._ask_user_for_gmsh()
                self._set_gmsh(gmsh)
        else:
            self._set_gmsh(gmsh)

    #### Public Protocol ##################################
    def write_geo(self, entities, fp):
        """Write a list of given entities to the given file pointer.
        """
        p_count, e_count = 0, 0
        for entity in entities:
            np, ne = entity.write(fp, p_count, e_count)
            p_count += np
            e_count += ne

    def write_vtk_mesh(self, entities, fname):
        """Write a list of given entities to the given file name.
        """
        tmp_geo = tempfile.mktemp(suffix='.geo')
        try:
            self.write_geo(entities, open(tmp_geo, 'w'))
            self._call_gmsh('-3', tmp_geo, '-o', fname)
        finally:
            os.remove(tmp_geo)

    def get_points(self, entities, vertices=True, cell_centers=False):
        """Given a list of entities, return x, y, z arrays for the position.

        Parameters
        ----------

        entities : list
            List of entities.
        vertices: bool
            If True, it converts the vertices to points.
        cell_centers: bool
            If True, converts the cell centers to points.

        """
        tmp_vtk = tempfile.mktemp(suffix='.vtk')
        try:
            self.write_vtk_mesh(entities, tmp_vtk)
            x, y, z = vtk_file_to_points(
                tmp_vtk, vertices=vertices, cell_centers=cell_centers
            )
            return x, y, z
        finally:
            os.remove(tmp_vtk)

    def get_points_from_geo(self, geo_file_name, vertices=True,
                            cell_centers=False):
        """Given a .geo file, generate a mesh and get the points from the mesh.

        Parameters
        ----------

        geo_file_name: str
            Filename of the .geo file.
        vertices: bool
            If True, it converts the vertices to points.
        cell_centers: bool
            If True, converts the cell centers to points.

        """
        tmp_vtk = tempfile.mktemp(suffix='.vtk')
        try:
            self._call_gmsh('-3', geo_file_name, '-o', tmp_vtk)
            return vtk_file_to_points(
                tmp_vtk, vertices=vertices, cell_centers=cell_centers
            )
        finally:
            os.remove(tmp_vtk)

    #### Private Protocol #################################
    def _ask_user_for_gmsh(self):
        gmsh = input('Please provide the path to gmsh executable: ')
        return gmsh

    def _read_config(self):
        if exists(self.config):
            data = json.load(open(self.config))
            self.gmsh = data['path']

    def _set_gmsh(self, gmsh):
        self.gmsh = gmsh
        data = dict(path=gmsh)
        json.dump(data, open(self.config, 'w'))

    def _call_gmsh(self, *args):
        if self.gmsh is None:
            raise RuntimeError('Gmsh is not configured, set the gmsh path.')
        cmd = [self.gmsh] + list(args)
        subprocess.check_call(cmd)

def example_3d_p(fp=sys.stdout):
    """Creates a 3D "P" with a hole inside it.
    """
    # The exterior of the "P"
    l1 = Loop((0.0, 0.0), mesh_size=0.1)
    l1.turn(-90).move(1.0).turn(90).move(0.2).turn(90).move(0.5)\
       .arc(0.25, -180).turn(90).move(0.2)
    # The inner loop for the hole in the middle.
    l2 = Loop((0.1, -0.25))
    l2.arc(0.1, 90).turn(90).arc(0.1, 90).turn(90)\
      .arc(0.1, 90).turn(90).arc(0.1, 90)
    s = Surface(l1, l2)
    ex = Extrude(0.0, 0.0, 1.0, surfaces=[s])
    ex.write(fp)
    return ex

def example_cube(fp=sys.stdout):
    """Simple example of a cube.
    """
    l1 = Loop((0.0, 0.0), mesh_size=0.1)
    l1.move(1.0).turn(90).move(1.0).turn(90).move(1.0).turn(90).move(1.0)
    s = Surface(l1)
    ex = Extrude(0.0, 0.0, 1.0, surfaces=[s])
    ex.write(fp)
    return ex

def example_plot_3d_p(gmsh):
    """Note: this will only work if you have gmsh installed.
    """
    import io
    fp = io.StringIO()
    ex = example_3d_p(fp)
    g = Gmsh(gmsh)
    x, y, z = g.get_points([ex])
    from mayavi import mlab
    mlab.points3d(x, y, z, color=(1, 0, 0))

{'repo_name': 'pypr/pysph', 'stars': '170', 'repo_language': 'Python', 'file_name': 'ami.sh', 'mime_type': 'text/plain', 'hash': -6262215149542540529, 'source_dataset': 'data'}


#
#
# 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.
#

module Shell
  module Commands
    class DisableAll < Command
      def help
        return <<-EOF
Disable all of tables matching the given regex:

hbase> disable_all 't.*'
hbase> disable_all 'ns:t.*'
hbase> disable_all 'ns:.*'
EOF
      end

      def command(regex)
        list = admin.list(regex)
        count = list.size
        list.each do |table|
          formatter.row([ table ])
        end
        puts "\nDisable the above #{count} tables (y/n)?" unless count == 0
        answer = 'n'
        answer = gets.chomp unless count == 0
        puts "No tables matched the regex #{regex.to_s}" if count == 0
        return unless answer =~ /y.*/i
        failed = admin.disable_all(regex)
        puts "#{count - failed.size} tables successfully disabled"
        puts "#{failed.size} tables not disabled due to an exception: #{failed.join ','}" unless failed.size == 0
      end
    end
  end
end

{'repo_name': 'thinkaurelius/titan', 'stars': '5063', 'repo_language': 'Java', 'file_name': 'cassandra.yaml', 'mime_type': 'text/plain', 'hash': 4887047263618109921, 'source_dataset': 'data'}


<?php

/*
  Prototype: mixed fscanf ( resource $handle, string $format [, mixed &$...] );
  Description: Parses input from a file according to a format
*/

/* test fscanf() for its return type */

$file_path = dirname(__FILE__);

echo "*** Testing fscanf(): for its return type without third argument ***\n";

// create a file
$filename = "$file_path/fscanf_variation1.tmp";
$file_handle = fopen($filename, "w");
if($file_handle == false)
  exit("Error:failed to open file $filename");
@fwrite($file_handle, "hello_world ");
@fwrite($file_handle, 12345);
fclose($file_handle);

// open file for reading
$file_handle = fopen($filename, "r");
// capturing the return value from fscanf() called without third argument
$return_value = fscanf($file_handle, "%s");
var_dump( is_array($return_value), $return_value); // return type is an array
fclose($file_handle);

echo "\n*** Done ***";
?>

{'repo_name': 'stephens2424/php', 'stars': '509', 'repo_language': 'Go', 'file_name': 'fmt.go', 'mime_type': 'text/x-c', 'hash': 3059800849079460267, 'source_dataset': 'data'}