.Version 9.0.0 of ABINIT
.(MPI version, prepared for a x86_64_linux_gnu9.2 computer)

.Copyright (C) 1998-2020 ABINIT group .
 ABINIT comes with ABSOLUTELY NO WARRANTY.
 It is free software, and you are welcome to redistribute it
 under certain conditions (GNU General Public License,
 see ~abinit/COPYING or http://www.gnu.org/copyleft/gpl.txt).

 ABINIT is a project of the Universite Catholique de Louvain,
 Corning Inc. and other collaborators, see ~abinit/doc/developers/contributors.txt .
 Please read https://docs.abinit.org/theory/acknowledgments for suggested
 acknowledgments of the ABINIT effort.
 For more information, see https://www.abinit.org .

.Starting date : Mon 24 Feb 2020.
- ( at 16h19 )

- input  file    -> /home/gmatteo/git_repos/abinit/_abiref_gnu9.2_openmpi/tests/Test_suite/v5_t43/t43.in
- output file    -> t43.out
- root for input  files -> t43i
- root for output files -> t43o

 Symmetries : space group P4/m m m (#123); Bravais tP (primitive tetrag.)
================================================================================
 Values of the parameters that define the memory need of the present run
     intxc =       0    ionmov =       0      iscf =       7    lmnmax =       1
     lnmax =       1     mgfft =    1500  mpssoang =       1    mqgrid =   73969
     natom =       1  nloc_mem =       1    nspden =       1   nspinor =       1
    nsppol =       1      nsym =      16    n1xccc =       0    ntypat =       1
    occopt =       1   xclevel =       1
-    mband =           1        mffmem =           1         mkmem =           1
       mpw =       18928          nfft =      600000          nkpt =           1
================================================================================
P This job should need less than                     168.367 Mbytes of memory.
  Rough estimation (10% accuracy) of disk space for files :
_ WF disk file :      0.291 Mbytes ; DEN or POT disk file :      4.580 Mbytes.
================================================================================

--------------------------------------------------------------------------------
------------- Echo of variables that govern the present computation ------------
--------------------------------------------------------------------------------
-
- outvars: echo of selected default values
-   iomode0 =  0 , fftalg0 =312 , wfoptalg0 =  0
-
- outvars: echo of global parameters not present in the input file
-  max_nthreads =    0
-
 -outvars: echo values of preprocessed input variables --------
            acell      3.0000000000E+02  4.0000000000E+00  4.0000000000E+00 Bohr
              amu      1.00794000E+00
             ecut      3.00000000E+01 Hartree
-          fftalg         312
           istwfk        9
              kpt      5.00000000E-01  5.00000000E-01  5.00000000E-01
           kptopt           0
P           mkmem           1
            natom           1
            nband           1
            ngfft        1500      20      20
             nkpt           1
            nline           2
            nstep           1
             nsym          16
           ntypat           1
              occ      1.000000
          spgroup         123
           symrel      1  0  0   0  1  0   0  0  1      -1  0  0   0 -1  0   0  0 -1
                      -1  0  0   0 -1  0   0  0  1       1  0  0   0  1  0   0  0 -1
                       1  0  0   0 -1  0   0  0 -1      -1  0  0   0  1  0   0  0  1
                      -1  0  0   0  1  0   0  0 -1       1  0  0   0 -1  0   0  0  1
                       1  0  0   0  0  1   0  1  0      -1  0  0   0  0 -1   0 -1  0
                      -1  0  0   0  0 -1   0  1  0       1  0  0   0  0  1   0 -1  0
                       1  0  0   0  0 -1   0 -1  0      -1  0  0   0  0  1   0  1  0
                      -1  0  0   0  0  1   0 -1  0       1  0  0   0  0 -1   0  1  0
           tolwfr      1.00000000E-22
            typat      1
            znucl        1.00000

================================================================================

 chkinp: Checking input parameters for consistency.

================================================================================
== DATASET  1 ==================================================================
-   mpi_nproc: 1, omp_nthreads: -1 (-1 if OMP is not activated)

--- !DatasetInfo
iteration_state: {dtset: 1, }
dimensions: {natom: 1, nkpt: 1, mband: 1, nsppol: 1, nspinor: 1, nspden: 1, mpw: 18928, }
cutoff_energies: {ecut:  30.0, pawecutdg:  -1.0, }
electrons: {nelect:   1.00000000E+00, charge:   0.00000000E+00, occopt:   1.00000000E+00, tsmear:   1.00000000E-02, }
meta: {optdriver: 0, ionmov: 0, optcell: 0, iscf: 7, paral_kgb: 0, }
...

 Exchange-correlation functional for the present dataset will be:
  LDA: new Teter (4/93) with spin-polarized option - ixc=1
 Citation for XC functional:
  S. Goedecker, M. Teter, J. Huetter, PRB 54, 1703 (1996)

 Real(R)+Recip(G) space primitive vectors, cartesian coordinates (Bohr,Bohr^-1):
 R(1)=300.0000000  0.0000000  0.0000000  G(1)=  0.0033333  0.0000000  0.0000000
 R(2)=  0.0000000  4.0000000  0.0000000  G(2)=  0.0000000  0.2500000  0.0000000
 R(3)=  0.0000000  0.0000000  4.0000000  G(3)=  0.0000000  0.0000000  0.2500000
 Unit cell volume ucvol=  4.8000000E+03 bohr^3
 Angles (23,13,12)=  9.00000000E+01  9.00000000E+01  9.00000000E+01 degrees

 getcut: wavevector=  0.0000  0.0000  0.0000  ngfft=1500  20  20
         ecut(hartree)=     30.000   => boxcut(ratio)=   2.02789

--- Pseudopotential description ------------------------------------------------
- pspini: atom type   1  psp file is /home/gmatteo/git_repos/abinit/tests/Psps_for_tests/01h.pspgth
- pspatm: opening atomic psp file    /home/gmatteo/git_repos/abinit/tests/Psps_for_tests/01h.pspgth
- Goedecker-Teter-Hutter  Wed May  8 14:27:44 EDT 1996
-  1.00000   1.00000    960508                znucl, zion, pspdat
    2    1    0    0      2001   0.00000      pspcod,pspxc,lmax,lloc,mmax,r2well
 rloc=   0.2000000
  cc1=  -4.0663326; cc2=   0.6778322; cc3=   0.0000000; cc4=   0.0000000
  rrs=   0.0000000; h1s=   0.0000000; h2s=   0.0000000
  rrp=   0.0000000; h1p=   0.0000000
-  Local part computed in reciprocal space.

 pspatm : COMMENT -
  the projectors are not normalized,
  so that the KB energies are not consistent with
  definition in PRB44, 8503 (1991).
  However, this does not influence the results obtained hereafter.
  pspatm : epsatm=   -0.00480358
         --- l  ekb(1:nproj) -->
 pspatm: atomic psp has been read  and splines computed

  -4.80358038E-03                                ecore*ucvol(ha*bohr**3)
--------------------------------------------------------------------------------

_setup2: Arith. and geom. avg. npw (full set) are   37856.000   37856.000

================================================================================

--- !BeginCycle
iteration_state: {dtset: 1, }
solver: {iscf: 7, nstep: 1, nline: 2, wfoptalg: 0, }
tolerances: {tolwfr: 1.00E-22, }
...

     iter   Etot(hartree)      deltaE(h)  residm     vres2
 ETOT  1 -0.24378484018994    -2.438E-01 1.348E-02 4.175E+01

 Cartesian components of stress tensor (hartree/bohr^3)
  sigma(1 1)= -2.25424513E-06  sigma(3 2)=  0.00000000E+00
  sigma(2 2)= -7.07010697E-05  sigma(3 1)=  0.00000000E+00
  sigma(3 3)= -7.07010697E-05  sigma(2 1)=  0.00000000E+00

 scprqt:  WARNING -
  nstep=    1 was not enough SCF cycles to converge;
  maximum residual=  1.348E-02 exceeds tolwfr=  1.000E-22

--- !ResultsGS
iteration_state: {dtset: 1, }
comment   : Summary of ground state results
lattice_vectors:
- [300.0000000,   0.0000000,   0.0000000, ]
- [  0.0000000,   4.0000000,   0.0000000, ]
- [  0.0000000,   0.0000000,   4.0000000, ]
lattice_lengths: [ 300.00000,    4.00000,    4.00000, ]
lattice_angles: [ 90.000,  90.000,  90.000, ] # degrees, (23, 13, 12)
lattice_volume:   4.8000000E+03
convergence: {deltae: -2.438E-01, res2:  4.175E+01, residm:  1.348E-02, diffor: null, }
etotal    :  -2.43784840E-01
entropy   :   0.00000000E+00
fermie    :   6.42132376E-03
cartesian_stress_tensor: # hartree/bohr^3
- [ -2.25424513E-06,   0.00000000E+00,   0.00000000E+00, ]
- [  0.00000000E+00,  -7.07010697E-05,   0.00000000E+00, ]
- [  0.00000000E+00,   0.00000000E+00,  -7.07010697E-05, ]
pressure_GPa:   1.4088E+00
xred      :
- [  0.0000E+00,   0.0000E+00,   0.0000E+00,  H]
cartesian_forces: # hartree/bohr
- [ -0.00000000E+00,  -0.00000000E+00,  -0.00000000E+00, ]
force_length_stats: {min:   0.00000000E+00, max:   0.00000000E+00, mean:   0.00000000E+00, }
...

 Integrated electronic density in atomic spheres:
 ------------------------------------------------
 Atom  Sphere_radius  Integrated_density
    1        2.00000          0.93459831
================================================================================

 ----iterations are completed or convergence reached----

 Mean square residual over all n,k,spin=   13.476E-03; max=  13.476E-03
 reduced coordinates (array xred) for    1 atoms
       0.000000000000      0.000000000000      0.000000000000
 rms dE/dt=  0.0000E+00; max dE/dt=  0.0000E+00; dE/dt below (all hartree)
    1       0.000000000000      0.000000000000      0.000000000000

 cartesian coordinates (angstrom) at end:
    1      0.00000000000000     0.00000000000000     0.00000000000000

 cartesian forces (hartree/bohr) at end:
    1     -0.00000000000000    -0.00000000000000    -0.00000000000000
 frms,max,avg= 0.0000000E+00 0.0000000E+00   0.000E+00  0.000E+00  0.000E+00 h/b

 cartesian forces (eV/Angstrom) at end:
    1     -0.00000000000000    -0.00000000000000    -0.00000000000000
 frms,max,avg= 0.0000000E+00 0.0000000E+00   0.000E+00  0.000E+00  0.000E+00 e/A
 length scales=300.000000000000  4.000000000000  4.000000000000 bohr
              =158.753162577000  2.116708834360  2.116708834360 angstroms
 prteigrs : about to open file t43o_EIG
 Fermi (or HOMO) energy (hartree) =   0.00642   Average Vxc (hartree)=  -0.00804
 Eigenvalues (hartree) for nkpt=   1  k points:
 kpt#   1, nband=  1, wtk=  1.00000, kpt=  0.5000  0.5000  0.5000 (reduced coord)
   0.00642

--- !EnergyTerms
iteration_state     : {dtset: 1, }
comment             : Components of total free energy in Hartree
kinetic             :  9.08254430876015E-01
hartree             :  9.71903337603166E+00
xc                  : -3.28470656082497E-01
Ewald energy        :  9.32994392746786E+00
psp_core            : -1.00074591287442E-06
local_psp           : -1.98725449177371E+01
non_local_psp       :  0.00000000000000E+00
total_energy        : -2.43784840189939E-01
total_energy_eV     : -6.63372286565718E+00
band_energy         :  6.42132376350980E-03
...

 Cartesian components of stress tensor (hartree/bohr^3)
  sigma(1 1)= -2.25424513E-06  sigma(3 2)=  0.00000000E+00
  sigma(2 2)= -7.07010697E-05  sigma(3 1)=  0.00000000E+00
  sigma(3 3)= -7.07010697E-05  sigma(2 1)=  0.00000000E+00

-Cartesian components of stress tensor (GPa)         [Pressure=  1.4088E+00 GPa]
- sigma(1 1)= -6.63221704E-02  sigma(3 2)=  0.00000000E+00
- sigma(2 2)= -2.08009694E+00  sigma(3 1)=  0.00000000E+00
- sigma(3 3)= -2.08009694E+00  sigma(2 1)=  0.00000000E+00

== END DATASET(S) ==============================================================
================================================================================

 -outvars: echo values of variables after computation  --------
            acell      3.0000000000E+02  4.0000000000E+00  4.0000000000E+00 Bohr
              amu      1.00794000E+00
             ecut      3.00000000E+01 Hartree
           etotal     -2.4378484019E-01
            fcart     -0.0000000000E+00 -0.0000000000E+00 -0.0000000000E+00
-          fftalg         312
           istwfk        9
              kpt      5.00000000E-01  5.00000000E-01  5.00000000E-01
           kptopt           0
P           mkmem           1
            natom           1
            nband           1
            ngfft        1500      20      20
             nkpt           1
            nline           2
            nstep           1
             nsym          16
           ntypat           1
              occ      1.000000
          spgroup         123
           strten     -2.2542451331E-06 -7.0701069727E-05 -7.0701069727E-05
                       0.0000000000E+00  0.0000000000E+00  0.0000000000E+00
           symrel      1  0  0   0  1  0   0  0  1      -1  0  0   0 -1  0   0  0 -1
                      -1  0  0   0 -1  0   0  0  1       1  0  0   0  1  0   0  0 -1
                       1  0  0   0 -1  0   0  0 -1      -1  0  0   0  1  0   0  0  1
                      -1  0  0   0  1  0   0  0 -1       1  0  0   0 -1  0   0  0  1
                       1  0  0   0  0  1   0  1  0      -1  0  0   0  0 -1   0 -1  0
                      -1  0  0   0  0 -1   0  1  0       1  0  0   0  0  1   0 -1  0
                       1  0  0   0  0 -1   0 -1  0      -1  0  0   0  0  1   0  1  0
                      -1  0  0   0  0  1   0 -1  0       1  0  0   0  0 -1   0  1  0
           tolwfr      1.00000000E-22
            typat      1
            znucl        1.00000

================================================================================

- Timing analysis has been suppressed with timopt=0

================================================================================

 Suggested references for the acknowledgment of ABINIT usage.

 The users of ABINIT have little formal obligations with respect to the ABINIT group
 (those specified in the GNU General Public License, http://www.gnu.org/copyleft/gpl.txt).
 However, it is common practice in the scientific literature,
 to acknowledge the efforts of people that have made the research possible.
 In this spirit, please find below suggested citations of work written by ABINIT developers,
 corresponding to implementations inside of ABINIT that you have used in the present run.
 Note also that it will be of great value to readers of publications presenting these results,
 to read papers enabling them to understand the theoretical formalism and details
 of the ABINIT implementation.
 For information on why they are suggested, see also https://docs.abinit.org/theory/acknowledgments.
-
- [1] The Abinit project: Impact, environment and recent developments.
- Computer Phys. Comm. 248, 107042 (2020).
- X.Gonze, B. Amadon, G. Antonius, F.Arnardi, L.Baguet, J.-M.Beuken,
- J.Bieder, F.Bottin, J.Bouchet, E.Bousquet, N.Brouwer, F.Bruneval,
- G.Brunin, T.Cavignac, J.-B. Charraud, Wei Chen, M.Cote, S.Cottenier,
- J.Denier, G.Geneste, Ph.Ghosez, M.Giantomassi, Y.Gillet, O.Gingras,
- D.R.Hamann, G.Hautier, Xu He, N.Helbig, N.Holzwarth, Y.Jia, F.Jollet,
- W.Lafargue-Dit-Hauret, K.Lejaeghere, M.A.L.Marques, A.Martin, C.Martins,
- H.P.C. Miranda, F.Naccarato, K. Persson, G.Petretto, V.Planes, Y.Pouillon,
- S.Prokhorenko, F.Ricci, G.-M.Rignanese, A.H.Romero, M.M.Schmitt, M.Torrent,
- M.J.van Setten, B.Van Troeye, M.J.Verstraete, G.Zerah and J.W.Zwanzig
- Comment: the fifth generic paper describing the ABINIT project.
- Note that a version of this paper, that is not formatted for Computer Phys. Comm.
- is available at https://www.abinit.org/sites/default/files/ABINIT20.pdf .
- The licence allows the authors to put it on the Web.
- DOI and bibtex: see https://docs.abinit.org/theory/bibliography/#gonze2020
-
- [2] Recent developments in the ABINIT software package.
- Computer Phys. Comm. 205, 106 (2016).
- X.Gonze, F.Jollet, F.Abreu Araujo, D.Adams, B.Amadon, T.Applencourt,
- C.Audouze, J.-M.Beuken, J.Bieder, A.Bokhanchuk, E.Bousquet, F.Bruneval
- D.Caliste, M.Cote, F.Dahm, F.Da Pieve, M.Delaveau, M.Di Gennaro,
- B.Dorado, C.Espejo, G.Geneste, L.Genovese, A.Gerossier, M.Giantomassi,
- Y.Gillet, D.R.Hamann, L.He, G.Jomard, J.Laflamme Janssen, S.Le Roux,
- A.Levitt, A.Lherbier, F.Liu, I.Lukacevic, A.Martin, C.Martins,
- M.J.T.Oliveira, S.Ponce, Y.Pouillon, T.Rangel, G.-M.Rignanese,
- A.H.Romero, B.Rousseau, O.Rubel, A.A.Shukri, M.Stankovski, M.Torrent,
- M.J.Van Setten, B.Van Troeye, M.J.Verstraete, D.Waroquier, J.Wiktor,
- B.Xu, A.Zhou, J.W.Zwanziger.
- Comment: the fourth generic paper describing the ABINIT project.
- Note that a version of this paper, that is not formatted for Computer Phys. Comm.
- is available at https://www.abinit.org/sites/default/files/ABINIT16.pdf .
- The licence allows the authors to put it on the Web.
- DOI and bibtex: see https://docs.abinit.org/theory/bibliography/#gonze2016
-
- [3] ABINIT: First-principles approach of materials and nanosystem properties.
- Computer Phys. Comm. 180, 2582-2615 (2009).
- X. Gonze, B. Amadon, P.-M. Anglade, J.-M. Beuken, F. Bottin, P. Boulanger, F. Bruneval,
- D. Caliste, R. Caracas, M. Cote, T. Deutsch, L. Genovese, Ph. Ghosez, M. Giantomassi
- S. Goedecker, D.R. Hamann, P. Hermet, F. Jollet, G. Jomard, S. Leroux, M. Mancini, S. Mazevet,
- M.J.T. Oliveira, G. Onida, Y. Pouillon, T. Rangel, G.-M. Rignanese, D. Sangalli, R. Shaltaf,
- M. Torrent, M.J. Verstraete, G. Zerah, J.W. Zwanziger
- Comment: the third generic paper describing the ABINIT project.
- Note that a version of this paper, that is not formatted for Computer Phys. Comm.
- is available at https://www.abinit.org/sites/default/files/ABINIT_CPC_v10.pdf .
- The licence allows the authors to put it on the Web.
- DOI and bibtex: see https://docs.abinit.org/theory/bibliography/#gonze2009
-
- And optionally:
-
- [4] A brief introduction to the ABINIT software package.
- Z. Kristallogr. 220, 558-562 (2005).
- X. Gonze, G.-M. Rignanese, M. Verstraete, J.-M. Beuken, Y. Pouillon, R. Caracas, F. Jollet,
- M. Torrent, G. Zerah, M. Mikami, Ph. Ghosez, M. Veithen, J.-Y. Raty, V. Olevano, F. Bruneval,
- L. Reining, R. Godby, G. Onida, D.R. Hamann, and D.C. Allan.
- Comment: the second generic paper describing the ABINIT project. Note that this paper
- should be cited especially if you are using the GW part of ABINIT, as several authors
- of this part are not in the list of authors of the first or third paper.
- The .pdf of the latter paper is available at https://www.abinit.org/sites/default/files/zfk_0505-06_558-562.pdf.
- Note that it should not redistributed (Copyright by Oldenburg Wissenschaftverlag,
- the licence allows the authors to put it on the Web).
- DOI and bibtex: see https://docs.abinit.org/theory/bibliography/#gonze2005
-
- Proc.   0 individual time (sec): cpu=        388.0  wall=        388.6

================================================================================

 Calculation completed.
.Delivered   2 WARNINGs and   4 COMMENTs to log file.
+Overall time at end (sec) : cpu=        388.0  wall=        388.6

{'repo_name': 'abinit/abinit', 'stars': '110', 'repo_language': 'Fortran', 'file_name': 'INSTALL.in', 'mime_type': 'text/plain', 'hash': 5463596680435619949, 'source_dataset': 'data'}


using Microsoft.VisualStudio.TestTools.UnitTesting;
using SenseNet.ContentRepository.Schema;
using SenseNet.ContentRepository.Storage.Data;
using SenseNet.Tests.Core;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using SenseNet.Testing;

namespace SenseNet.ContentRepository.Tests
{
    [TestClass]
    public class AutoNamingTests : TestBase
    {
        private static string ContentType_Car1Name = "Car1_AutoNamingTests";
        private static string ContentType_Car2Name = "Car2_AutoNamingTests";
        private static ContentType ContentType_Car1;
        private static ContentType ContentType_Car2;
        public static void InstallContentTypes()
        {
            var ctdformat = @"<?xml version=""1.0"" encoding=""utf-8""?>
                <ContentType name=""{0}"" parentType=""Car"" handler=""SenseNet.ContentRepository.GenericContent""
                             xmlns=""http://schemas.sensenet.com/SenseNet/ContentRepository/ContentTypeDefinition"">
                  <AllowIncrementalNaming>{1}</AllowIncrementalNaming>
                </ContentType>";
            var ctd1 = String.Format(ctdformat, ContentType_Car1Name, "true");
            var ctd2 = String.Format(ctdformat, ContentType_Car2Name, "false");
            ContentTypeInstaller.InstallContentType(CarContentType, ctd1, ctd2);
            ContentType_Car1 = ContentType.GetByName(ContentType_Car1Name);
            ContentType_Car2 = ContentType.GetByName(ContentType_Car2Name);
        }

        [TestMethod]
        public void ContentNaming_FromDisplayName()
        {
            var providers = new[] {
                (ContentNamingProvider)new CharReplacementContentNamingProvider(),
                (ContentNamingProvider)new Underscore5FContentNamingProvider()
            };

            var contentNamingProviderAcc = new TypeAccessor(typeof(ContentNamingProvider));
            var originalProvider = contentNamingProviderAcc.GetStaticField("__instance");
            try
            {
                foreach (var provider in providers)
                {
                    contentNamingProviderAcc.SetStaticField("__instance", provider);
                    var providerName = provider.GetType().Name;

                    Assert.AreEqual("árvíztűrőtükörfúrógép", ContentNamingProvider.GetNameFromDisplayName("árvíztűrőtükörfúrógép"));
                    Assert.AreEqual("ÁRVÍZTŰRŐTÜKÖRFÚRÓGÉP", ContentNamingProvider.GetNameFromDisplayName("ÁRVÍZTŰRŐTÜKÖRFÚRÓGÉP"));
                    Assert.AreEqual("ÁrvíztűrőTükörfúrógép", ContentNamingProvider.GetNameFromDisplayName("ÁrvíztűrőTükörfúrógép"));
                    Assert.AreEqual("árvíztűrőtükörfúrógép.txt", ContentNamingProvider.GetNameFromDisplayName("árvíztűrőtükörfúrógép.txt"));
                    Assert.AreEqual("árvíztűrőtükörfúrógép.doc.txt", ContentNamingProvider.GetNameFromDisplayName("árvíztűrőtükörfúrógép.txt", "árvíztűrőtükörfúrógép.doc"));
                    Assert.AreEqual("árvíztűrőtükörfúrógép.doc.txt", ContentNamingProvider.GetNameFromDisplayName(".txt", "árvíztűrőtükörfúrógép.doc"));

                    var name =  ContentNamingProvider.GetNameFromDisplayName("!*_~@#$%a^&()b{}+\"'|:<>?c/.,");
                    if (providerName == typeof(CharReplacementContentNamingProvider).Name)
                    {
                        Assert.AreEqual("!-_-a-()b-c", name);
                    }
                    else if (providerName == typeof(Underscore5FContentNamingProvider).Name)
                    {
                        Assert.AreEqual("!_2a_5f_7e_40_23_24_25a_5e_26()b_7b_7d_2b_22_27_7c_3a_3c_3e_3fc_2f._2c", name);
                    }
                    else
                    {
                        Assert.Inconclusive("Unknown ContentNamingProvider: " + providerName);
                    }
                }
            }
            finally
            {
                contentNamingProviderAcc.SetStaticField("__instance", originalProvider);
            }
        }
        [TestMethod]
        public void ContentNaming_AllowIncrementalNaming_Allowed()
        {
            Test(() =>
            {
                InstallContentTypes();
                var testRoot = new SystemFolder(Repository.Root);
                testRoot.Save();

                Content content1, content2;
                do
                {
                    content1 = Content.CreateNew(ContentType_Car1Name, testRoot, null);
                    content2 = Content.CreateNew(ContentType_Car1Name, testRoot, null);
                } while (content1.Name != content2.Name);
                content1.Save();
                content2.Save();
            });
        }
        [TestMethod]
        public void ContentNaming_AllowIncrementalNaming_Disallowed()
        {
            Test(() =>
            {
                var thrown = false;
                try
                {
                    InstallContentTypes();
                    var testRoot = new SystemFolder(Repository.Root);
                    testRoot.Save();

                    Content content1, content2;
                    do
                    {
                        content1 = Content.CreateNew(ContentType_Car2Name, testRoot, null);
                        content2 = Content.CreateNew(ContentType_Car2Name, testRoot, null);
                    } while (content1.Name != content2.Name);
                    content1.Save();
                    content2.Save();
                }
                catch (NodeAlreadyExistsException)
                {
                    thrown = true;
                }
                catch (AggregateException ae)
                {
                    thrown = ae.InnerException is NodeAlreadyExistsException;
                }
                if (!thrown)
                    Assert.Fail("The expected NodeAlreadyExistsException was not thrown.");
            });
        }
        [TestMethod]
        public void ContentNaming_IncrementNameSuffixOnSave()
        {
            Test(() =>
            {
                InstallContentTypes();
                var testRoot = new SystemFolder(Repository.Root);
                testRoot.Save();

                var root = new SystemFolder(testRoot) { Name = Guid.NewGuid().ToString() };
                root.Save();

                // increment check
                var content1 = Content.CreateNew(ContentType_Car1Name, root, "mycar");
                content1.Save();
                var content2 = Content.CreateNew(ContentType_Car1Name, root, "mycar");
                content2.Save();
                var content3 = Content.CreateNew(ContentType_Car1Name, root, "mycar");
                content3.Save();
                Assert.AreEqual("mycar", content1.Name);    // if mycar does not exist, name does not change
                Assert.AreEqual("mycar(1)", content2.Name); // first increment
                Assert.AreEqual("mycar(2)", content3.Name); // second increment

                // 9 - 10 order problem: if mycar(9) and mycar(10) exists, mycar(11) is the next even though 10 is smaller than 9 if compared as strings
                Content.CreateNew(ContentType_Car1Name, root, "mycar(9)").Save();
                Content.CreateNew(ContentType_Car1Name, root, "mycar(10)").Save();
                var content4 = Content.CreateNew(ContentType_Car1Name, root, "mycar");
                content4.Save();
                Assert.AreEqual("mycar(11)", content4.Name);

                // (string) suffix problem 1: string(test) should be incremented to string(test)(1)
                var content5 = Content.CreateNew(ContentType_Car1Name, root, "string(test)");
                content5.Save();
                var content6 = Content.CreateNew(ContentType_Car1Name, root, "string(test)");
                content6.Save();
                Assert.AreEqual("string(test)", content5.Name);    // if string(test) does not exist, name does not change
                Assert.AreEqual("string(test)(1)", content6.Name); // first increment

                // (string) suffix problem 2: string should be incremented to string(guid), since string(test) already exists
                var content7 = Content.CreateNew(ContentType_Car1Name, root, "string");
                content7.Save();
                var content8 = Content.CreateNew(ContentType_Car1Name, root, "string");
                content8.Save();
                Assert.AreEqual("string", content7.Name);       // did not exist yet
                Assert.AreEqual("string(1)", content8.Name);       // did not exist yet
            });
        }
        [TestMethod]
        public void ContentNaming_IncrementNameSuffixOnSaveWithExtension()
        {
            Test(() =>
            {
                InstallContentTypes();
                var testRoot = new SystemFolder(Repository.Root);
                testRoot.Save();

                var root = new SystemFolder(testRoot) { Name = Guid.NewGuid().ToString() };
                root.Save();

                // increment check
                var content1 = Content.CreateNew(ContentType_Car1Name, root, "mycar.xml");
                content1.Save();
                var content2 = Content.CreateNew(ContentType_Car1Name, root, "mycar.xml");
                content2.Save();
                var content3 = Content.CreateNew(ContentType_Car1Name, root, "mycar.xml");
                content3.Save();
                Assert.AreEqual("mycar.xml", content1.Name);    // if mycar does not exist, name does not change
                Assert.AreEqual("mycar(1).xml", content2.Name); // first increment
                Assert.AreEqual("mycar(2).xml", content3.Name); // second increment

                // 9 - 10 order problem: if mycar(9) and mycar(10) exists, mycar(11) is the next even though 10 is smaller than 9 if compared as strings
                Content.CreateNew(ContentType_Car1Name, root, "mycar(9).xml").Save();
                Content.CreateNew(ContentType_Car1Name, root, "mycar(10).xml").Save();
                var content4 = Content.CreateNew(ContentType_Car1Name, root, "mycar.xml");
                content4.Save();
                Assert.IsTrue(content4.Name == "mycar(11).xml");

                // (string) suffix problem 1: string(test) should be incremented to string(test)(1)
                var content5 = Content.CreateNew(ContentType_Car1Name, root, "string(test).xml");
                content5.Save();
                var content6 = Content.CreateNew(ContentType_Car1Name, root, "string(test).xml");
                content6.Save();
                Assert.AreEqual("string(test).xml", content5.Name);    // if string(test) does not exist, name does not change
                Assert.AreEqual("string(test)(1).xml", content6.Name); // first increment

                // (string) suffix problem 2: string should be incremented to string(guid), since string(test) already exists
                var content7 = Content.CreateNew(ContentType_Car1Name, root, "string.xml");
                content7.Save();
                var content8 = Content.CreateNew(ContentType_Car1Name, root, "string.xml");
                content8.Save();
                Assert.AreEqual("string.xml", content7.Name);
                Assert.AreEqual("string(1).xml", content8.Name);
            });
        }
        [TestMethod]
        public void ContentNaming_AutoIncrementOnDemand()
        {
            Test(() =>
            {
                InstallContentTypes();
                var testRoot = new SystemFolder(Repository.Root);
                testRoot.Save();

                var root = new SystemFolder(testRoot) { Name = Guid.NewGuid().ToString() };
                root.Save();

                var content1 = Content.CreateNew(ContentType_Car2Name, root, "ondemand");
                content1.Save();

                // take a non-autoincrement type, and save it with autoincrement
                bool typeNotAutoIncrement = false;
                var content2 = Content.CreateNew(ContentType_Car2Name, root, "ondemand");
                try
                {
                    content2.Save();
                }
                catch (NodeAlreadyExistsException)
                {
                    typeNotAutoIncrement = true;
                }
                catch(AggregateException ae)
                {
                    typeNotAutoIncrement = ae.InnerException is NodeAlreadyExistsException;
                }
                Assert.IsTrue(typeNotAutoIncrement);    // the type is non-autoincremental

                content2.ContentHandler.AllowIncrementalNaming = true;
                content2.Save();
                Assert.AreEqual("ondemand(1)", content2.Name);  // non-autoincremental type is saved autoincrementally
            });
        }
        [TestMethod]
        public void ContentNaming_NameOnlyChangesAfterSave()
        {
            Test(() =>
            {
                InstallContentTypes();
                var testRoot = new SystemFolder(Repository.Root);
                testRoot.Save();

                var content1 = Content.CreateNew(ContentType_Car1Name, testRoot, "changeonsave");
                content1.Save();

                var content2 = Content.CreateNew(ContentType_Car1Name, testRoot, "changeonsave");
                Assert.IsTrue(content2.Name == "changeonsave");     // name is not changed before saving, no queries are run (queries would be slow)
                content2.Save();
                Assert.IsTrue(content2.Name == "changeonsave(1)");  // name is changed after saving - we check here that name should actually be changed, so previous assert is correct
            });
        }
        [TestMethod]
        public void ContentNaming_IncrementNameSuffix()
        {
            string msg;

            msg = IncrementNameSuffixTest("Car", "Car(1)"); Assert.IsNull(msg, msg);
            msg = IncrementNameSuffixTest("Car(12)", "Car(13)"); Assert.IsNull(msg, msg);
            msg = IncrementNameSuffixTest("Car.xml", "Car(1).xml"); Assert.IsNull(msg, msg);
            msg = IncrementNameSuffixTest("Car(8).xml", "Car(9).xml"); Assert.IsNull(msg, msg);
            msg = IncrementNameSuffixTest("Car((8).xml", "Car((9).xml"); Assert.IsNull(msg, msg);
            msg = IncrementNameSuffixTest("(1)", "(2)"); Assert.IsNull(msg, msg); Assert.IsNull(msg, msg);
            msg = IncrementNameSuffixTest(")", ")(1)"); Assert.IsNull(msg, msg); Assert.IsNull(msg, msg);

            msg = IncrementNameSuffixTest("Car(string)(12)", "Car(string)(13)"); Assert.IsNull(msg, msg);

            // suffices are guids for the following.
            // if the last suffixed name from db is in the form 'name(x)' where x is not a number, we are not able to decide the next suffix, so it is guid
            var actual = ContentNamingProvider.IncrementNameSuffix("Car(string)");
            Assert.AreEqual("Car(string)(1)", actual);
            actual = ContentNamingProvider.IncrementNameSuffix("Car(8)).xml");
            Assert.AreEqual("Car(8))(1).xml", actual);
            actual = ContentNamingProvider.IncrementNameSuffix("Car()");
            Assert.AreEqual("Car()(1)", actual);
        }
        [TestMethod]
        public void ContentNaming_ParseSuffix()
        {
            string msg;
            msg = ParseSuffixTest("Car(1)", 1); Assert.IsNull(msg, msg);
            msg = ParseSuffixTest("Car(1).xml", 1); Assert.IsNull(msg, msg);
            msg = ParseSuffixTest("Car(test)(1)", 1); Assert.IsNull(msg, msg);
            msg = ParseSuffixTest("Car(test)(1).xml", 1); Assert.IsNull(msg, msg);
            msg = ParseSuffixTest("Car", 0); Assert.IsNull(msg, msg);
            msg = ParseSuffixTest("Car(test)", 0); Assert.IsNull(msg, msg);
            msg = ParseSuffixTest("Car(test)(1", 0); Assert.IsNull(msg, msg);
            msg = ParseSuffixTest("Car.xml", 0); Assert.IsNull(msg, msg);
            msg = ParseSuffixTest("Car(test).xml", 0); Assert.IsNull(msg, msg);
            msg = ParseSuffixTest("Car(test)(1.xml", 0); Assert.IsNull(msg, msg);
            msg = ParseSuffixTest("Car((8).xml", 8); Assert.IsNull(msg, msg);
            msg = ParseSuffixTest("Car(8)).xml", 0); Assert.IsNull(msg, msg);
        }
        private string IncrementNameSuffixTest(string name, string expected)
        {
            var actual = ContentNamingProvider.IncrementNameSuffix(name);
            if(actual == expected)
                return null;
            return String.Format("Name is {0}, expected: {1}", actual, expected);
        }
        private string ParseSuffixTest(string name, int expected)
        {
            name = System.IO.Path.GetFileNameWithoutExtension(name);
            string nameBase;
            var actual = ContentNamingProvider.ParseSuffix(name, out nameBase);
            if (actual == expected)
                return null;
            return String.Format("Result is {0}, expected: {1}", actual, expected);
        }
        //private bool SuffixIsGuid(string name)
        //{
        //    name = Path.GetFileNameWithoutExtension(name);
        //    Guid guid;
        //    var guidstr = name.Substring(name.Length - 36 - 1, 36);
        //    return Guid.TryParse(guidstr, out guid);
        //}
    }
}

{'repo_name': 'SenseNet/sensenet', 'stars': '108', 'repo_language': 'C#', 'file_name': 'content-query.md', 'mime_type': 'text/plain', 'hash': -3188954360259353222, 'source_dataset': 'data'}


# WAAS

## Introduction
OCI WAF is a global security service that protects applications from malicious and unwanted internet traffic. WAF can protect any internet facing endpoint, providing consistent rule enforcement across a customer's applications.

WAF provides you with the ability to create and manage rules for internet threats including Cross-Site Scripting (XSS), SQL Injection and other OWASP-defined vulnerabilities. Unwanted bots can be mitigated while tactically allowed desirable bots to enter. Access rules can limit based on geography or the signature of the request.

## Prerequisites

- Terraform v0.12.9 or greater - <https://www.terraform.io/downloads.html/>
- OCI Provider for Terraform v3.61 or greater - <https://github.com/oracle/terraform-provider-oci/releases>
- 1 VCN, 2 Virtual Machines, 1 Public Load Balancer

## Deployment

Install all the software components from the Prerequisites section. Use the links from each description.

You will have to generate an API signing key (public/private keys) and the public key should be uploaded in the OCI
console, for the iam user that will be used to create the resources. Also, you should make sure that this user has
enough permissions to create resources in OCI. In order to generate the API Signing key, follow the steps
from: <https://docs.us-phoenix-1.oraclecloud.com/Content/API/Concepts/apisigningkey.htm#How>
The API signing key will generate a fingerprint in the OCI console, and that fingerprint will be used in a terraform
file described below.

In addition to this, you are required to generate a ssh key for the user that will run the scripts.

You will need an oci provider which can be defined in an \*.auto.tfvars file in your example folder and the values must reflect your OCI tenancy:

```
provider_oci = {
  tenancy              = ""
  user_id              = ""
  fingerprint          = ""
  key_file_path        = ""
  private_key_password = ""
  region               = ""
}
```

## Description

- WAF Policy parameters
    - domain = The web application domain that the WAAS policy protects
    - additional_domains = An array of additional domains for the specified web application
    - compartment_name = The name of the compartment in which to create the WAAS policy
    - display_name = The name for the WAAS policy
    - label = The label of the origin
    - http_port = The HTTP port on the origin that the web application listens on
    - https_port = The HTTPS port on the origin that the web application listens on
    - uri_name = The URI name of the origin.
    - certificate_id = The OCID of the SSL certificate to use if HTTPS is supported
    - cipher_group = The set cipher group for the configured TLS protocol
    - client\_address\_header = Specifies an HTTP header name which is treated as the connecting client's IP address
    - is\_behind\_cdn = Enabling isBehindCdn allows for the collection of IP addresses from client requests if the WAF is connected to a CDN
    - is\_cache\_control\_respected = Enable or disable automatic content caching based on the response cache-control header
    - is\_https\_enabled = Enable or disable HTTPS support
    - is\_https\_forced = Force HTTP to HTTPS redirection
    - is\_origin\_compression\_enabled = Enable or disable GZIP compression of origin responses
    - is\_response\_buffering\_enabled = Enable or disable buffering of responses from the origin
    - tls_protocols = A list of allowed TLS protocols
    - Access rule parameters:
        - action = The action to take when the access criteria are met for a rule
        - name = The name of the access rule
        - block_action = The method used to block requests if action is set to BLOCK and the access criteria are met
        - block\_error\_page\_code = The error code to show on the error page when action is set to BLOCK
        * block\_error\_page\_description = The description text to show on the error page when action is set to BLOCK
        * block\_error\_page\_message = The message to show on the error page when action is set to BLOCK
        * block\_response\_code = The response status code to return when action is set to BLOCK
        * bypass\_challenges = The list of challenges to bypass when action is set to BYPASS
        * redirect\_response\_code = The response status code to return when action is set to REDIRECT
        * redirect_url = The target to which the request should be redirected, represented as a URI reference
        * criteria:
            - condition = The criteria the access rule uses to determine if action should be taken on a request
            - value = The unique name of the access rule
    - Address Rate Limiting rule parameters:
        - is_enabled = Enables or disables the address rate limiting WAF feature
        - allowed\_rate\_per\_address = The number of allowed requests per second from one IP address
        - block\_response\_code = The response status code returned when a request is blocked
        - max\_delayed\_count\_per\_address = The maximum number of requests allowed to be queued before subsequent requests are dropped
    - Caching rule parameters:
        * action                    = The action to take when the criteria of a caching rule are met
        * name                      = The name of the caching rule
        * caching\_duration          = The duration to cache content for the caching rule, specified in ISO 8601 extended format
        * client\_caching\_duration   = The duration to cache content in the user's browser, specified in ISO 8601 extended format
        * is\_client\_caching\_enabled = Enables or disables client caching
        * key                       =  The unique key for the caching rule
        * criteria :
            * condition = The condition of the caching rule criteria
            * value     = The value of the caching rule criteria
    - Capchas rule parameters
        * failure_message               = The text to show when incorrect CAPTCHA text is entered
        * session\_expiration\_in\_seconds = The amount of time before the CAPTCHA expires, in seconds
        * submit_label                  = The text to show on the label of the CAPTCHA challenge submit button
        * title                         = The title used when displaying a CAPTCHA challenge
        * url                           = The unique URL path at which to show the CAPTCHA challenge.
        * footer_text                   =  The text to show in the footer when showing a CAPTCHA challenge
        * header_text                   = The text to show in the header when showing a CAPTCHA challenge
    - Device Fingerprint Challenge rule parameters:
        * is_enabled                              = Enables or disables the device fingerprint challenge WAF feature
        * action                                  = The action to take on requests from detected bots
        * action\_expiration\_in\_seconds            = The number of seconds between challenges for the same IP address
        * failure_threshold                       =  The number of failed requests allowed before taking action
        * failure\_threshold\_expiration\_in\_seconds = The number of seconds before the failure threshold resets
        * max\_address\_count                       = The maximum number of IP addresses permitted with the same device fingerprint
        * max\_address\_count\_expiration\_in\_seconds = The number of seconds before the maximum addresses count resets
        * challenge_settings:
            * block_action                 =  The method used to block requests that fail the challenge, if action is set to BLOCK
            * block\_error\_page\_code        = The error code to show on the error page when action is set to BLOCK
            * block\_error\_page\_description = The description text to show on the error page when action is set to BLOCK
            * block\_error\_page\_message     = The message to show on the error page when action is set to BLOCK
            * block\_response\_code          = The response status code to return when action is set to BLOCK
            * captcha_footer               = The text to show in the footer when showing a CAPTCHA challenge when action is set to BLOCK
            * captcha_header               = The text to show in the header when showing a CAPTCHA challenge when action is set to BLOCK
            * captcha\_submit\_label         = The text to show on the label of the CAPTCHA challenge submit button when action is set to BLOCK
            * captcha_title                = he title used when showing a CAPTCHA challenge when action is set to BLOCK
    - Human Interaction Challenge rule parameters:
        * is_enabled                              = Enables or disables the human interaction challenge WAF feature
        * action                                  =  The action to take against requests from detected bots
        * action\_expiration\_in\_seconds            = The number of seconds between challenges for the same IP address
        * failure_threshold                       = The number of failed requests before taking action
        * failure\_threshold\_expiration\_in\_seconds = The number of seconds before the failure threshold resets
        * interaction_threshold                   = The number of interactions required to pass the challenge
        * recording\_period\_in\_seconds             = The number of seconds to record the interactions from the use
        * challenge_settings:
            * block_action                 =  The method used to block requests that fail the challenge, if action is set to BLOCK
            * block\_error\_page\_code        = The error code to show on the error page when action is set to BLOCK
            * block\_error\_page\_description = The description text to show on the error page when action is set to BLOCK
            * block\_error\_page\_message     = The message to show on the error page when action is set to BLOCK
            * block\_response\_code          = The response status code to return when action is set to BLOCK
            * captcha_footer               = The text to show in the footer when showing a CAPTCHA challenge when action is set to BLOCK
            * captcha_header               = The text to show in the header when showing a CAPTCHA challenge when action is set to BLOCK
            * captcha\_submit\_label         = The text to show on the label of the CAPTCHA challenge submit button when action is set to BLOCK
            * captcha_title                = he title used when showing a CAPTCHA challenge when action is set to BLOCK
        * set\_http\_header:
            * name  = The name of the header
            * value = The value of the header
    - Java Script Challenge rule parameters:
        * is_enabled                   = Enables or disables the JavaScript challenge WAF feature
        * action                       = The action to take against requests from detected bots
        * action\_expiration\_in\_seconds = The number of seconds between challenges from the same IP address
        * failure_threshold            = The number of failed requests before taking action
        * challenge_settings:
            * block_action                 =  The method used to block requests that fail the challenge, if action is set to BLOCK
            * block\_error\_page\_code        = The error code to show on the error page when action is set to BLOCK
            * block\_error\_page\_description = The description text to show on the error page when action is set to BLOCK
            * block\_error\_page\_message     = The message to show on the error page when action is set to BLOCK
            * block\_response\_code          = The response status code to return when action is set to BLOCK
            * captcha_footer               = The text to show in the footer when showing a CAPTCHA challenge when action is set to BLOCK
            * captcha_header               = The text to show in the header when showing a CAPTCHA challenge when action is set to BLOCK
            * captcha\_submit\_label         = The text to show on the label of the CAPTCHA challenge submit button when action is set to BLOCK
            * captcha_title                = he title used when showing a CAPTCHA challenge when action is set to BLOCK
        * set\_http\_header:
            * name  = The name of the header
            * value = The value of the header
    - Protection rule parameters:
        * allowed\_http\_methods               = The list of allowed HTTP methods
        * block_action                       = If action is set to BLOCK, this specifies how the traffic is blocked when detected as malicious by a protection rule
        * block\_error\_page\_code              = The error code to show on the error page when action is set to BLOCK
        * block\_error\_page\_description       = The description text to show on the error page when action is set to BLOCK
        * block\_error\_page\_message           = The message to show on the error page when action is set to BLOCK
        * block\_response\_code                = The response code returned when action is set to BLOCK
        * is\_response\_inspected              = Inspects the response body of origin responses
        * max\_argument\_count                 = The maximum number of arguments allowed to be passed to your application before an action is taken
        * max\_name\_length\_per\_argument       = The maximum length allowed for each argument name, in characters
        * max\_response\_size\_in\_ki\_b          = The maximum response size to be fully inspected, in binary kilobytes (KiB)
        * max\_total\_name\_length\_of\_arguments = The maximum length allowed for the sum of the argument name and value, in characters
        * media\_types                        = The list of media types to allow for inspection, if isResponseInspected is enabled
        * recommendations\_period\_in\_days     = The length of time to analyze traffic traffic, in days
     - Whitelists rule paramters:
        * addresses = A set of IP addresses or CIDR notations to include in the whitelist
        * name      = The unique name of the whitelist

## Dependencies
Apart from the **provider.auto.tfvars**, there may be some other dependencies in the **terraform.tfvars** file that you will have to address.
All the dependencies from this section should have resources that already exist in OCI.

### Compartment Dependency
In order to be able to run the sample code, you will have to prepare a map variable (like in the **terraform.tfvars** file) called **compartment\_ids**, which will hold key/value pairs with the names and ids of the compartments that you want to use.
This variable will be external in order to offer multiple ways of linking them from a terraform perspective.

```
compartment_ids = {
  sandbox = "ocid1.compartment.oc1..aaaaaaaaiu3vfcpbjwwgpil3xakqts4jhtjq42kktmisriiszdvvouwsirgq"
}
```

### Load Balancer Dependency
In order to be able to run the sample code, you will have to prepare a map variable (like in the **terraform.tfvars** file) called **uri**, which will hold key/value pairs with the names and ip of the load balancers that you want to use.
This variable will be external in order to offer multiple ways of linking them from a terraform perspective.

```
uri = {
  primary = "150.136.204.78" # Complete with the public ip address of the load balancer
}
```

## Example

In the provided example, the following resources are created:

1 WAF Policy with the rules:
  - Access Rules
  - Rate Limiting
  - Captcha Challenge
  - Device Fingerprinting Challenge
  - Human Interaction Challenge
  - JavaScript Challenge
  - Protection Rules
  - IP Whitelists

In the example from below, there is a list of compartments containing 1 elements and a list of uri containing 1 element. By setting in waas\_policy\_params `compartment_name` to sandbox, WAF will be created in the sandbox compartmanet `ocid1.compartment.oc1..aaaaaaaaiu3vfcpbjwwgpil3xakqts4jhtjq42kktmisriiszdvvouwsirgq`.
The same thing is happening to uri. You will need to associate the name of the uri with the public ip of the public load balancer.
All lists can be extended in order to satisfy your needs.
After the creation of the policy, you should visit your DNS provider and add your CNAME to your domain's DNS configuration.

The example is based on terraform.tfvars values:

```

compartment_ids = {
  sandbox = "ocid1.compartment.oc1..aaaaaaaaiu3vfcpbjwwgpil3xakqts4jhtjq42kktmisriiszdvvouwsirgq"
}

uri = {
  primary = "150.136.204.78" # Complete with the public ip address of the load balancer
}

cert_params = {}

waas_policy_params = {
    hurricane1 = {
        domain = "hurricane1.com"
        additional_domains = ["prod.hurricane1.com", "dev.hurricane1.com"]
        compartment_name = "sandbox"
        display_name = "Hurricane"
        label = "primary"
        http_port = "80"
        https_port = "443"
        uri_name = "primary"
        #certificate_id = oci_waas_certificate.this.id
        cipher_group = "DEFAULT"
        client_address_header = "X_FORWARDED_FOR"
        is_behind_cdn = true
        is_cache_control_respected = true
        is_https_enabled = false
        is_https_forced = false
        is_origin_compression_enabled = true
        is_response_buffering_enabled = true
        tls_protocols = ["TLS_V1_1"]

        waf_config = {
            waf_config_1 = {
                origin = "primary"
                access_rules = {
                    access_rule_1 = {
                        action = "ALLOW"
                        name   = "hurricane_example_access_rule"
                        #complete the following variables only if action is set to BLOCK
                        block_action                 = "SET_RESPONSE_CODE"
                        block_error_page_code        = 403
                        block_error_page_description = "blockErrorPageDescription"
                        block_error_page_message     = "blockErrorPageMessage"
                        block_response_code          = 403
                        bypass_challenges            = []      # when action is set to BYPASS
                        redirect_response_code       = "FOUND" # when action is set to REDIRECT.
                        redirect_url                 = "http://10.0.0.3"

                        criteria = {
                            crit1 = {
                                condition = "URL_IS"
                                value     = "/public"
                            }
                        }
                    }
                }

                address_rate_limiting = {
                    address_rate_limiting_1 = {
                        is_enabled                    = true
                        allowed_rate_per_address      = 1
                        block_response_code           = 503
                        max_delayed_count_per_address = 10
                    }
                }

                caching_rules = {
                    caching_rule_1 = {
                        action                    = "CACHE"
                        name                      = "hurricane_caching_rule_name"
                        caching_duration          = "PT1S"
                        client_caching_duration   = "PT1S"
                        is_client_caching_enabled = false
                        key                       = "hurricane_key"

                        criteria = {
                            crit1 = {
                                condition = "URL_IS"
                                value     = "/public"
                            }
                        }
                    }
                }

                captchas = {
                    captchas_rule_1 = {
                        failure_message               = "The CAPTCHA was incorrect. Try again."
                        session_expiration_in_seconds = 300
                        submit_label                  = "Yes, I am human."
                        title                         = "Are you human?"
                        url                           = "url"
                        footer_text                   = "Enter the letters and numbers as they are shown in the image above."
                        header_text                   = "We have detected an increased number of attempts to access this website. To help us keep this site secure, please let us know that you are not a robot by entering the text from the image below"
                    }
                }

                device_fingerprint_challenge = {
                    device_fingerprint_1 = {
                        is_enabled                              = true
                        action                                  = "DETECT"
                        action_expiration_in_seconds            = 30
                        failure_threshold                       = 10
                        failure_threshold_expiration_in_seconds = 10
                        max_address_count                       = 10
                        max_address_count_expiration_in_seconds = 10

                        challenge_settings = {
                            settings_1 = {
                                block_action                 = "SHOW_ERROR_PAGE"
                                block_error_page_code        = "DFC"
                                block_error_page_description = "Access blocked by website owner. Please contact support."
                                block_error_page_message     = "Access to the website is blocked."
                                block_response_code          = 403
                                captcha_footer               = "Enter the letters and numbers as they are shown in image above."
                                captcha_header               = "We have detected an increased number of attempts to access this website. To help us keep this site secure, please let us know that you are not a robot by entering the text from the image below."
                                captcha_submit_label         = "Yes, I am human."
                                captcha_title                = "Are you human?"
                            }
                        }
                    }
                }

                human_interaction_challenge = {
                    first_human_interaction = {
                        is_enabled                              = true
                        action                                  = "DETECT"
                        action_expiration_in_seconds            = 10
                        failure_threshold                       = 10
                        failure_threshold_expiration_in_seconds = 10
                        interaction_threshold                   = 3
                        recording_period_in_seconds             = 15

                        challenge_settings = {
                            first_challenge = {
                                block_action                 = "SHOW_ERROR_PAGE"
                                block_error_page_code        = "HIC"
                                block_error_page_description = "Access blocked by website owner. Please contact support."
                                block_error_page_message     = "Access to the website is blocked."
                                block_response_code          = 403
                                captcha_footer               = "Enter the letters and numbers as they are shown in image above."
                                captcha_header               = "We have detected an increased number of attempts to access this website. To help us keep this site secure, please let us know that you are not a robot by entering the text from the image below."
                                captcha_submit_label         = "Yes, I am human."
                                captcha_title                = "Are you human?"
                            }
                        }

                        set_http_header = {
                            first_http_header = {
                                name  = "hurricane-hic-alerts"
                                value = "{failed_amount}"
                            }
                        }
                    }
                }

                js_challenge = {
                    first_js_challenge = {
                        is_enabled                   = true
                        action                       = "DETECT"
                        action_expiration_in_seconds = 10
                        failure_threshold            = 10

                        challenge_settings = {
                            first_challenge = {
                                block_action                 = "SHOW_ERROR_PAGE"
                                block_error_page_code        = "JSC"
                                block_error_page_description = "Access blocked by website owner. Please contact support."
                                block_error_page_message     = "Access to the website is blocked."
                                block_response_code          = 403
                                captcha_footer               = "Enter the letters and numbers as they are shown in image above."
                                captcha_header               = "We have detected an increased number of attempts to access this website. To help us keep this site secure, please let us know that you are not a robot by entering the text from the image below."
                                captcha_submit_label         = "Yes, I am human."
                                captcha_title                = "Are you human?"
                            }
                        }

                        set_http_header = {
                            first_http_header = {
                                name  = "hurricane-jsc-alerts"
                                value = "{failed_amount}"
                            }
                        }
                    }
                }

                protection_settings = {
                    first_protection_setting = {
                        allowed_http_methods               = ["GET", "POST", "HEAD", "OPTIONS"]
                        block_action                       = "SET_RESPONSE_CODE"
                        block_error_page_code              = "403"
                        block_error_page_description       = "Access blocked by website owner. Please contact support."
                        block_error_page_message           = "Access to the website is blocked."
                        block_response_code                = 403
                        is_response_inspected              = false
                        max_argument_count                 = 255
                        max_name_length_per_argument       = 400
                        max_response_size_in_ki_b          = 1024
                        max_total_name_length_of_arguments = 64000
                        media_types                        = ["text/html", "text/plain"]
                        recommendations_period_in_days     = 10
                    }
                }

                whitelists = {
                    first_whitelist = {
                        addresses = ["192.168.127.127", "192.168.127.128"]
                        name      = "whitelist_name"
                    }
                }
            }
        }
    }
}

```

This is just an example, but the number of the resources can be increased/decreased to suit any needs by adding another map in the specific resource type.

Don't forget to populate the provider with the details of your tenancy as specified in the main README.md file.

## Running the code

Go to **thunder/examples/run/waas**
```
# Run init to get terraform modules
$ terraform init

# Create the infrastructure
$ terraform apply --var-file=path_to_provider.auto.tfvars

# If you are done with this infrastructure, take it down
$ terraform destroy --var-file=path_to_provider.auto.tfvars
```

## Useful Links

[WAF Concepts](https://docs.cloud.oracle.com/en-us/iaas/Content/WAF/Concepts/overview.htm)

[DNS Zones](https://docs.cloud.oracle.com/en-us/iaas/Content/DNS/Tasks/managingdnszones.htm)

{'repo_name': 'oracle/learning-library', 'stars': '430', 'repo_language': 'PLSQL', 'file_name': 'dp_to_adb_intro.md', 'mime_type': 'text/html', 'hash': 292740290230225886, 'source_dataset': 'data'}


<?php

final class PhabricatorProfileMenuItemConfigurationQuery
  extends PhabricatorCursorPagedPolicyAwareQuery {

  private $ids;
  private $phids;
  private $profilePHIDs;
  private $customPHIDs;
  private $includeGlobal;
  private $affectedObjectPHIDs;

  public function withIDs(array $ids) {
    $this->ids = $ids;
    return $this;
  }

  public function withPHIDs(array $phids) {
    $this->phids = $phids;
    return $this;
  }

  public function withProfilePHIDs(array $phids) {
    $this->profilePHIDs = $phids;
    return $this;
  }

  public function withCustomPHIDs(array $phids, $include_global = false) {
    $this->customPHIDs = $phids;
    $this->includeGlobal = $include_global;
    return $this;
  }

  public function withAffectedObjectPHIDs(array $phids) {
    $this->affectedObjectPHIDs = $phids;
    return $this;
  }

  public function newResultObject() {
    return new PhabricatorProfileMenuItemConfiguration();
  }

  protected function loadPage() {
    return $this->loadStandardPage($this->newResultObject());
  }

  protected function buildWhereClauseParts(AphrontDatabaseConnection $conn) {
    $where = parent::buildWhereClauseParts($conn);

    if ($this->ids !== null) {
      $where[] = qsprintf(
        $conn,
        'config.id IN (%Ld)',
        $this->ids);
    }

    if ($this->phids !== null) {
      $where[] = qsprintf(
        $conn,
        'config.phid IN (%Ls)',
        $this->phids);
    }

    if ($this->profilePHIDs !== null) {
      $where[] = qsprintf(
        $conn,
        'config.profilePHID IN (%Ls)',
        $this->profilePHIDs);
    }

    if ($this->customPHIDs !== null) {
      if ($this->customPHIDs && $this->includeGlobal) {
        $where[] = qsprintf(
          $conn,
          'config.customPHID IN (%Ls) OR config.customPHID IS NULL',
          $this->customPHIDs);
      } else if ($this->customPHIDs) {
        $where[] = qsprintf(
          $conn,
          'config.customPHID IN (%Ls)',
          $this->customPHIDs);
      } else {
        $where[] = qsprintf(
          $conn,
          'config.customPHID IS NULL');
      }
    }

    if ($this->affectedObjectPHIDs !== null) {
      $where[] = qsprintf(
        $conn,
        'affected.dst IN (%Ls)',
        $this->affectedObjectPHIDs);
    }

    return $where;
  }

  protected function buildJoinClauseParts(AphrontDatabaseConnection $conn) {
    $joins = parent::buildJoinClauseParts($conn);

    if ($this->affectedObjectPHIDs !== null) {
      $joins[] = qsprintf(
        $conn,
        'JOIN %T affected ON affected.src = config.phid
          AND affected.type = %d',
        PhabricatorEdgeConfig::TABLE_NAME_EDGE,
        PhabricatorProfileMenuItemAffectsObjectEdgeType::EDGECONST);
    }

    return $joins;
  }

  protected function willFilterPage(array $page) {
    $items = PhabricatorProfileMenuItem::getAllMenuItems();
    foreach ($page as $key => $item) {
      $item_type = idx($items, $item->getMenuItemKey());
      if (!$item_type) {
        $this->didRejectResult($item);
        unset($page[$key]);
        continue;
      }
      $item_type = clone $item_type;
      $item_type->setViewer($this->getViewer());
      $item->attachMenuItem($item_type);
    }

    if (!$page) {
      return array();
    }

    $profile_phids = mpull($page, 'getProfilePHID');

    $profiles = id(new PhabricatorObjectQuery())
      ->setViewer($this->getViewer())
      ->setParentQuery($this)
      ->withPHIDs($profile_phids)
      ->execute();
    $profiles = mpull($profiles, null, 'getPHID');

    foreach ($page as $key => $item) {
      $profile = idx($profiles, $item->getProfilePHID());
      if (!$profile) {
        $this->didRejectResult($item);
        unset($page[$key]);
        continue;
      }

      $item->attachProfileObject($profile);
    }

    return $page;
  }

  public function getQueryApplicationClass() {
    return 'PhabricatorSearchApplication';
  }

  protected function getPrimaryTableAlias() {
    return 'config';
  }

}

{'repo_name': 'phacility/phabricator', 'stars': '11612', 'repo_language': 'PHP', 'file_name': 'jsShrink.php', 'mime_type': 'text/x-php', 'hash': -248176611494265422, 'source_dataset': 'data'}


import { Beans } from "../beans";
import { CellComp } from "../cellComp";
import { RowNode } from "../../entities/rowNode";
import { Column } from "../../entities/column";
import { RowContainerComponent } from "./rowContainerComponent";
import { Component } from "../../widgets/component";
import { IFrameworkOverrides } from "../../interfaces/iFrameworkOverrides";
export declare class RowComp extends Component {
    static DOM_DATA_KEY_RENDERED_ROW: string;
    private static FULL_WIDTH_CELL_RENDERER;
    private static GROUP_ROW_RENDERER;
    private static GROUP_ROW_RENDERER_COMP_NAME;
    private static LOADING_CELL_RENDERER;
    private static LOADING_CELL_RENDERER_COMP_NAME;
    private static DETAIL_CELL_RENDERER;
    private static DETAIL_CELL_RENDERER_COMP_NAME;
    private readonly rowNode;
    private readonly beans;
    private ePinnedLeftRow;
    private ePinnedRightRow;
    private eBodyRow;
    private eAllRowContainers;
    private eFullWidthRow;
    private eFullWidthRowBody;
    private eFullWidthRowLeft;
    private eFullWidthRowRight;
    private readonly bodyContainerComp;
    private readonly fullWidthContainerComp;
    private readonly pinnedLeftContainerComp;
    private readonly pinnedRightContainerComp;
    private fullWidthRowComponent;
    private fullWidthRowComponentBody;
    private fullWidthRowComponentLeft;
    private fullWidthRowComponentRight;
    private firstRowOnPage;
    private lastRowOnPage;
    private active;
    private fullWidthRow;
    private editingRow;
    private rowFocused;
    private rowContainerReadyCount;
    private refreshNeeded;
    private columnRefreshPending;
    private cellComps;
    private createSecondPassFuncs;
    private removeFirstPassFuncs;
    private removeSecondPassFuncs;
    private fadeRowIn;
    private slideRowIn;
    private readonly useAnimationFrameForCreate;
    private rowIsEven;
    private paginationPage;
    private parentScope;
    private scope;
    private initialised;
    private elementOrderChanged;
    private lastMouseDownOnDragger;
    private rowLevel;
    private readonly printLayout;
    private readonly embedFullWidth;
    constructor(parentScope: any, bodyContainerComp: RowContainerComponent, pinnedLeftContainerComp: RowContainerComponent, pinnedRightContainerComp: RowContainerComponent, fullWidthContainerComp: RowContainerComponent, rowNode: RowNode, beans: Beans, animateIn: boolean, useAnimationFrameForCreate: boolean, printLayout: boolean, embedFullWidth: boolean);
    init(): void;
    private setupAngular1Scope;
    private createTemplate;
    getCellForCol(column: Column): HTMLElement;
    afterFlush(): void;
    private executeProcessRowPostCreateFunc;
    private getInitialRowTopStyle;
    private getRowBusinessKey;
    private areAllContainersReady;
    private lazyCreateCells;
    private createRowContainer;
    private setupRowContainers;
    private setupNormalRowContainers;
    private createFullWidthRows;
    private setAnimateFlags;
    isEditing(): boolean;
    stopRowEditing(cancel: boolean): void;
    isFullWidth(): boolean;
    refreshFullWidth(): boolean;
    private addListeners;
    private addListenersForCellComps;
    private onRowNodeDataChanged;
    private onRowNodeCellChanged;
    private postProcessCss;
    private onRowNodeHighlightChanged;
    private onRowNodeDraggingChanged;
    private postProcessRowDragging;
    private updateExpandedCss;
    private onDisplayedColumnsChanged;
    private destroyFullWidthComponents;
    private getContainerForCell;
    private onVirtualColumnsChanged;
    private onColumnResized;
    private refreshCells;
    private refreshCellsInAnimationFrame;
    private onColumnMoved;
    private destroyCells;
    private isCellEligibleToBeRemoved;
    private ensureCellInCorrectContainer;
    private isCellInWrongRow;
    private insertCellsIntoContainer;
    private addDomData;
    private createNewCell;
    onMouseEvent(eventName: string, mouseEvent: MouseEvent): void;
    private createRowEvent;
    private createRowEventWithSource;
    private onRowDblClick;
    private onRowMouseDown;
    onRowClick(mouseEvent: MouseEvent): void;
    private createFullWidthRowContainer;
    private angular1Compile;
    private createFullWidthParams;
    private getInitialRowClasses;
    private onUiLevelChanged;
    private isFirstRowOnPage;
    private isLastRowOnPage;
    private onModelUpdated;
    stopEditing(cancel?: boolean): void;
    private setEditingRow;
    startRowEditing(keyPress?: number | null, charPress?: string | null, sourceRenderedCell?: CellComp | null): void;
    forEachCellComp(callback: (renderedCell: CellComp) => void): void;
    private postProcessClassesFromGridOptions;
    private postProcessRowClassRules;
    private preProcessStylesFromGridOptions;
    private postProcessStylesFromGridOptions;
    private processStylesFromGridOptions;
    private createCells;
    private onRowSelected;
    private refreshAriaLabel;
    private callAfterRowAttachedOnCells;
    private afterRowAttached;
    private addHoverFunctionality;
    private roundRowTopToBounds;
    protected getFrameworkOverrides(): IFrameworkOverrides;
    private onRowHeightChanged;
    addEventListener(eventType: string, listener: Function): void;
    removeEventListener(eventType: string, listener: Function): void;
    destroy(animate?: boolean): void;
    private destroyContainingCells;
    getAndClearDelayedDestroyFunctions(): Function[];
    private onCellFocusChanged;
    private onPaginationChanged;
    private onTopChanged;
    private onPaginationPixelOffsetChanged;
    private applyPaginationOffset;
    private setRowTop;
    getAndClearNextVMTurnFunctions(): Function[];
    getRowNode(): RowNode;
    getRenderedCellForColumn(column: Column): CellComp | undefined;
    private onRowIndexChanged;
    private updateRowIndexes;
    ensureDomOrder(): void;
    getPinnedLeftRowElement(): HTMLElement;
    getPinnedRightRowElement(): HTMLElement;
    getBodyRowElement(): HTMLElement;
    getFullWidthRowElement(): HTMLElement;
}

{'repo_name': 'ag-grid/ag-grid', 'stars': '6412', 'repo_language': 'JavaScript', 'file_name': 'linkedList.js', 'mime_type': 'text/plain', 'hash': 1489680582857793535, 'source_dataset': 'data'}


require "predicated/predicate"
require "predicated/from/ruby_code_string"
require "predicated/to/sentence"

require "wrong/chunk"
require "wrong/config"
require "wrong/failure_message"
require "wrong/rainbow"

module Wrong
  module Assert

    class AssertionFailedError < RuntimeError
    end

    def failure_class
      AssertionFailedError
    end

    # Actual signature: assert(explanation = nil, depth = 0, &block)
    def assert(*args, &block)
      # to notice (and fail fast from) odd recursion problem
      raise "Reentry bug while trying to assert(#{args.join(', ')})" if (@_inside_wrong_assert ||= nil)
      @_inside_wrong_assert = true

      if block.nil?
        begin
          super(*args) # if there's a framework assert method (sans block), then call it
        rescue NoMethodError
          # note: we're not raising an AssertionFailedError because this is a programmer error, not a failed assertion
          raise "You must pass a block to Wrong's assert and deny methods"
        end
      else
        aver(:assert, *args, &block)
      end
    ensure
      @_inside_wrong_assert = false
    end

    # Actual signature: deny(explanation = nil, depth = 0, &block)
    def deny(*args, &block)
      if block.nil?
        test = args.first
        msg = args[1]
        assert !test, msg  # this makes it get passed up to the framework
      else
        aver(:deny, *args, &block)
      end
    end

    protected

    # for debugging -- if we couldn't make a predicate out of the code block, then this was why
    def self.last_predicated_error
      @@last_predicated_error ||= nil
    end

    # override (redefine) in adapter if necessary
    def increment_assertion_count
    end

    def aver(valence, explanation = nil, depth = 0, &block)
      increment_assertion_count
      require "wrong/rainbow" if Wrong.config[:color]

      value = block.call
      value = !value if valence == :deny
      if value
        if Wrong.config[:verbose]
          code = Wrong::Chunk.from_block(block, depth + 2).code
          if Wrong.config[:color]
            explanation = explanation.color(:blue) if explanation
            code = code.color(:green)
          end
          message = "#{explanation + ": " if explanation}#{code}"
          puts message
        end
      else
        chunk = Wrong::Chunk.from_block(block, depth + 2)

        message = FailureMessage.new(chunk, valence, explanation).full
        raise failure_class.new(message)
      end
    end
  end

end

{'repo_name': 'sconover/wrong', 'stars': '429', 'repo_language': 'Ruby', 'file_name': 'slides.md', 'mime_type': 'text/x-ruby', 'hash': -5395398732383728588, 'source_dataset': 'data'}


/*
 * CTS: Cipher Text Stealing mode
 *
 * COPYRIGHT (c) 2008
 * The Regents of the University of Michigan
 * ALL RIGHTS RESERVED
 *
 * Permission is granted to use, copy, create derivative works
 * and redistribute this software and such derivative works
 * for any purpose, so long as the name of The University of
 * Michigan is not used in any advertising or publicity
 * pertaining to the use of distribution of this software
 * without specific, written prior authorization.  If the
 * above copyright notice or any other identification of the
 * University of Michigan is included in any copy of any
 * portion of this software, then the disclaimer below must
 * also be included.
 *
 * THIS SOFTWARE IS PROVIDED AS IS, WITHOUT REPRESENTATION
 * FROM THE UNIVERSITY OF MICHIGAN AS TO ITS FITNESS FOR ANY
 * PURPOSE, AND WITHOUT WARRANTY BY THE UNIVERSITY OF
 * MICHIGAN OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING
 * WITHOUT LIMITATION THE IMPLIED WARRANTIES OF
 * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE
 * REGENTS OF THE UNIVERSITY OF MICHIGAN SHALL NOT BE LIABLE
 * FOR ANY DAMAGES, INCLUDING SPECIAL, INDIRECT, INCIDENTAL, OR
 * CONSEQUENTIAL DAMAGES, WITH RESPECT TO ANY CLAIM ARISING
 * OUT OF OR IN CONNECTION WITH THE USE OF THE SOFTWARE, EVEN
 * IF IT HAS BEEN OR IS HEREAFTER ADVISED OF THE POSSIBILITY OF
 * SUCH DAMAGES.
 */

/* Derived from various:
 *	Copyright (c) 2006 Herbert Xu <herbert@gondor.apana.org.au>
 */

/*
 * This is the Cipher Text Stealing mode as described by
 * Section 8 of rfc2040 and referenced by rfc3962.
 * rfc3962 includes errata information in its Appendix A.
 */

#include <crypto/algapi.h>
#include <crypto/internal/skcipher.h>
#include <linux/err.h>
#include <linux/init.h>
#include <linux/kernel.h>
#include <linux/log2.h>
#include <linux/module.h>
#include <linux/scatterlist.h>
#include <crypto/scatterwalk.h>
#include <linux/slab.h>
#include <linux/compiler.h>

struct crypto_cts_ctx {
	struct crypto_skcipher *child;
};

struct crypto_cts_reqctx {
	struct scatterlist sg[2];
	unsigned offset;
	struct skcipher_request subreq;
};

static inline u8 *crypto_cts_reqctx_space(struct skcipher_request *req)
{
	struct crypto_cts_reqctx *rctx = skcipher_request_ctx(req);
	struct crypto_skcipher *tfm = crypto_skcipher_reqtfm(req);
	struct crypto_cts_ctx *ctx = crypto_skcipher_ctx(tfm);
	struct crypto_skcipher *child = ctx->child;

	return PTR_ALIGN((u8 *)(rctx + 1) + crypto_skcipher_reqsize(child),
			 crypto_skcipher_alignmask(tfm) + 1);
}

static int crypto_cts_setkey(struct crypto_skcipher *parent, const u8 *key,
			     unsigned int keylen)
{
	struct crypto_cts_ctx *ctx = crypto_skcipher_ctx(parent);
	struct crypto_skcipher *child = ctx->child;

	crypto_skcipher_clear_flags(child, CRYPTO_TFM_REQ_MASK);
	crypto_skcipher_set_flags(child, crypto_skcipher_get_flags(parent) &
					 CRYPTO_TFM_REQ_MASK);
	return crypto_skcipher_setkey(child, key, keylen);
}

static void cts_cbc_crypt_done(struct crypto_async_request *areq, int err)
{
	struct skcipher_request *req = areq->data;

	if (err == -EINPROGRESS)
		return;

	skcipher_request_complete(req, err);
}

static int cts_cbc_encrypt(struct skcipher_request *req)
{
	struct crypto_cts_reqctx *rctx = skcipher_request_ctx(req);
	struct crypto_skcipher *tfm = crypto_skcipher_reqtfm(req);
	struct skcipher_request *subreq = &rctx->subreq;
	int bsize = crypto_skcipher_blocksize(tfm);
	u8 d[MAX_CIPHER_BLOCKSIZE * 2] __aligned(__alignof__(u32));
	struct scatterlist *sg;
	unsigned int offset;
	int lastn;

	offset = rctx->offset;
	lastn = req->cryptlen - offset;

	sg = scatterwalk_ffwd(rctx->sg, req->dst, offset - bsize);
	scatterwalk_map_and_copy(d + bsize, sg, 0, bsize, 0);

	memset(d, 0, bsize);
	scatterwalk_map_and_copy(d, req->src, offset, lastn, 0);

	scatterwalk_map_and_copy(d, sg, 0, bsize + lastn, 1);
	memzero_explicit(d, sizeof(d));

	skcipher_request_set_callback(subreq, req->base.flags &
					      CRYPTO_TFM_REQ_MAY_BACKLOG,
				      cts_cbc_crypt_done, req);
	skcipher_request_set_crypt(subreq, sg, sg, bsize, req->iv);
	return crypto_skcipher_encrypt(subreq);
}

static void crypto_cts_encrypt_done(struct crypto_async_request *areq, int err)
{
	struct skcipher_request *req = areq->data;

	if (err)
		goto out;

	err = cts_cbc_encrypt(req);
	if (err == -EINPROGRESS || err == -EBUSY)
		return;

out:
	skcipher_request_complete(req, err);
}

static int crypto_cts_encrypt(struct skcipher_request *req)
{
	struct crypto_skcipher *tfm = crypto_skcipher_reqtfm(req);
	struct crypto_cts_reqctx *rctx = skcipher_request_ctx(req);
	struct crypto_cts_ctx *ctx = crypto_skcipher_ctx(tfm);
	struct skcipher_request *subreq = &rctx->subreq;
	int bsize = crypto_skcipher_blocksize(tfm);
	unsigned int nbytes = req->cryptlen;
	unsigned int offset;

	skcipher_request_set_tfm(subreq, ctx->child);

	if (nbytes < bsize)
		return -EINVAL;

	if (nbytes == bsize) {
		skcipher_request_set_callback(subreq, req->base.flags,
					      req->base.complete,
					      req->base.data);
		skcipher_request_set_crypt(subreq, req->src, req->dst, nbytes,
					   req->iv);
		return crypto_skcipher_encrypt(subreq);
	}

	offset = rounddown(nbytes - 1, bsize);
	rctx->offset = offset;

	skcipher_request_set_callback(subreq, req->base.flags,
				      crypto_cts_encrypt_done, req);
	skcipher_request_set_crypt(subreq, req->src, req->dst,
				   offset, req->iv);

	return crypto_skcipher_encrypt(subreq) ?:
	       cts_cbc_encrypt(req);
}

static int cts_cbc_decrypt(struct skcipher_request *req)
{
	struct crypto_cts_reqctx *rctx = skcipher_request_ctx(req);
	struct crypto_skcipher *tfm = crypto_skcipher_reqtfm(req);
	struct skcipher_request *subreq = &rctx->subreq;
	int bsize = crypto_skcipher_blocksize(tfm);
	u8 d[MAX_CIPHER_BLOCKSIZE * 2] __aligned(__alignof__(u32));
	struct scatterlist *sg;
	unsigned int offset;
	u8 *space;
	int lastn;

	offset = rctx->offset;
	lastn = req->cryptlen - offset;

	sg = scatterwalk_ffwd(rctx->sg, req->dst, offset - bsize);

	/* 1. Decrypt Cn-1 (s) to create Dn */
	scatterwalk_map_and_copy(d + bsize, sg, 0, bsize, 0);
	space = crypto_cts_reqctx_space(req);
	crypto_xor(d + bsize, space, bsize);
	/* 2. Pad Cn with zeros at the end to create C of length BB */
	memset(d, 0, bsize);
	scatterwalk_map_and_copy(d, req->src, offset, lastn, 0);
	/* 3. Exclusive-or Dn with C to create Xn */
	/* 4. Select the first Ln bytes of Xn to create Pn */
	crypto_xor(d + bsize, d, lastn);

	/* 5. Append the tail (BB - Ln) bytes of Xn to Cn to create En */
	memcpy(d + lastn, d + bsize + lastn, bsize - lastn);
	/* 6. Decrypt En to create Pn-1 */

	scatterwalk_map_and_copy(d, sg, 0, bsize + lastn, 1);
	memzero_explicit(d, sizeof(d));

	skcipher_request_set_callback(subreq, req->base.flags &
					      CRYPTO_TFM_REQ_MAY_BACKLOG,
				      cts_cbc_crypt_done, req);

	skcipher_request_set_crypt(subreq, sg, sg, bsize, space);
	return crypto_skcipher_decrypt(subreq);
}

static void crypto_cts_decrypt_done(struct crypto_async_request *areq, int err)
{
	struct skcipher_request *req = areq->data;

	if (err)
		goto out;

	err = cts_cbc_decrypt(req);
	if (err == -EINPROGRESS || err == -EBUSY)
		return;

out:
	skcipher_request_complete(req, err);
}

static int crypto_cts_decrypt(struct skcipher_request *req)
{
	struct crypto_skcipher *tfm = crypto_skcipher_reqtfm(req);
	struct crypto_cts_reqctx *rctx = skcipher_request_ctx(req);
	struct crypto_cts_ctx *ctx = crypto_skcipher_ctx(tfm);
	struct skcipher_request *subreq = &rctx->subreq;
	int bsize = crypto_skcipher_blocksize(tfm);
	unsigned int nbytes = req->cryptlen;
	unsigned int offset;
	u8 *space;

	skcipher_request_set_tfm(subreq, ctx->child);

	if (nbytes < bsize)
		return -EINVAL;

	if (nbytes == bsize) {
		skcipher_request_set_callback(subreq, req->base.flags,
					      req->base.complete,
					      req->base.data);
		skcipher_request_set_crypt(subreq, req->src, req->dst, nbytes,
					   req->iv);
		return crypto_skcipher_decrypt(subreq);
	}

	skcipher_request_set_callback(subreq, req->base.flags,
				      crypto_cts_decrypt_done, req);

	space = crypto_cts_reqctx_space(req);

	offset = rounddown(nbytes - 1, bsize);
	rctx->offset = offset;

	if (offset <= bsize)
		memcpy(space, req->iv, bsize);
	else
		scatterwalk_map_and_copy(space, req->src, offset - 2 * bsize,
					 bsize, 0);

	skcipher_request_set_crypt(subreq, req->src, req->dst,
				   offset, req->iv);

	return crypto_skcipher_decrypt(subreq) ?:
	       cts_cbc_decrypt(req);
}

static int crypto_cts_init_tfm(struct crypto_skcipher *tfm)
{
	struct skcipher_instance *inst = skcipher_alg_instance(tfm);
	struct crypto_skcipher_spawn *spawn = skcipher_instance_ctx(inst);
	struct crypto_cts_ctx *ctx = crypto_skcipher_ctx(tfm);
	struct crypto_skcipher *cipher;
	unsigned reqsize;
	unsigned bsize;
	unsigned align;

	cipher = crypto_spawn_skcipher(spawn);
	if (IS_ERR(cipher))
		return PTR_ERR(cipher);

	ctx->child = cipher;

	align = crypto_skcipher_alignmask(tfm);
	bsize = crypto_skcipher_blocksize(cipher);
	reqsize = ALIGN(sizeof(struct crypto_cts_reqctx) +
			crypto_skcipher_reqsize(cipher),
			crypto_tfm_ctx_alignment()) +
		  (align & ~(crypto_tfm_ctx_alignment() - 1)) + bsize;

	crypto_skcipher_set_reqsize(tfm, reqsize);

	return 0;
}

static void crypto_cts_exit_tfm(struct crypto_skcipher *tfm)
{
	struct crypto_cts_ctx *ctx = crypto_skcipher_ctx(tfm);

	crypto_free_skcipher(ctx->child);
}

static void crypto_cts_free(struct skcipher_instance *inst)
{
	crypto_drop_skcipher(skcipher_instance_ctx(inst));
	kfree(inst);
}

static int crypto_cts_create(struct crypto_template *tmpl, struct rtattr **tb)
{
	struct crypto_skcipher_spawn *spawn;
	struct skcipher_instance *inst;
	struct skcipher_alg *alg;
	u32 mask;
	int err;

	err = crypto_check_attr_type(tb, CRYPTO_ALG_TYPE_SKCIPHER, &mask);
	if (err)
		return err;

	inst = kzalloc(sizeof(*inst) + sizeof(*spawn), GFP_KERNEL);
	if (!inst)
		return -ENOMEM;

	spawn = skcipher_instance_ctx(inst);

	err = crypto_grab_skcipher(spawn, skcipher_crypto_instance(inst),
				   crypto_attr_alg_name(tb[1]), 0, mask);
	if (err)
		goto err_free_inst;

	alg = crypto_spawn_skcipher_alg(spawn);

	err = -EINVAL;
	if (crypto_skcipher_alg_ivsize(alg) != alg->base.cra_blocksize)
		goto err_free_inst;

	if (strncmp(alg->base.cra_name, "cbc(", 4))
		goto err_free_inst;

	err = crypto_inst_setname(skcipher_crypto_instance(inst), "cts",
				  &alg->base);
	if (err)
		goto err_free_inst;

	inst->alg.base.cra_priority = alg->base.cra_priority;
	inst->alg.base.cra_blocksize = alg->base.cra_blocksize;
	inst->alg.base.cra_alignmask = alg->base.cra_alignmask;

	inst->alg.ivsize = alg->base.cra_blocksize;
	inst->alg.chunksize = crypto_skcipher_alg_chunksize(alg);
	inst->alg.min_keysize = crypto_skcipher_alg_min_keysize(alg);
	inst->alg.max_keysize = crypto_skcipher_alg_max_keysize(alg);

	inst->alg.base.cra_ctxsize = sizeof(struct crypto_cts_ctx);

	inst->alg.init = crypto_cts_init_tfm;
	inst->alg.exit = crypto_cts_exit_tfm;

	inst->alg.setkey = crypto_cts_setkey;
	inst->alg.encrypt = crypto_cts_encrypt;
	inst->alg.decrypt = crypto_cts_decrypt;

	inst->free = crypto_cts_free;

	err = skcipher_register_instance(tmpl, inst);
	if (err) {
err_free_inst:
		crypto_cts_free(inst);
	}
	return err;
}

static struct crypto_template crypto_cts_tmpl = {
	.name = "cts",
	.create = crypto_cts_create,
	.module = THIS_MODULE,
};

static int __init crypto_cts_module_init(void)
{
	return crypto_register_template(&crypto_cts_tmpl);
}

static void __exit crypto_cts_module_exit(void)
{
	crypto_unregister_template(&crypto_cts_tmpl);
}

subsys_initcall(crypto_cts_module_init);
module_exit(crypto_cts_module_exit);

MODULE_LICENSE("Dual BSD/GPL");
MODULE_DESCRIPTION("CTS-CBC CipherText Stealing for CBC");
MODULE_ALIAS_CRYPTO("cts");

{'repo_name': 'ceph/ceph-client', 'stars': '163', 'repo_language': 'C', 'file_name': 'Kconfig', 'mime_type': 'text/plain', 'hash': 8965725528611826013, 'source_dataset': 'data'}


<?xml version="1.0" encoding="utf-8"?>
<Project ToolsVersion="4.0" DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
  <Import Project="$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props" Condition="Exists('$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props')" />
  <PropertyGroup>
    <Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration>
    <Platform Condition=" '$(Platform)' == '' ">AnyCPU</Platform>
    <ProjectGuid>{3872F86E-927B-44A3-A4F1-BD177681AF87}</ProjectGuid>
    <OutputType>Library</OutputType>
    <AppDesignerFolder>Properties</AppDesignerFolder>
    <RootNamespace>DeltaEngine.Editor.AppBuilder.Tests</RootNamespace>
    <AssemblyName>DeltaEngine.Editor.AppBuilder.Tests</AssemblyName>
    <TargetFrameworkVersion>v4.0</TargetFrameworkVersion>
    <FileAlignment>512</FileAlignment>
    <RestorePackages>true</RestorePackages>
  </PropertyGroup>
  <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' ">
    <DebugSymbols>true</DebugSymbols>
    <DebugType>full</DebugType>
    <Optimize>false</Optimize>
    <OutputPath>bin\Debug</OutputPath>
    <DefineConstants>DEBUG;TRACE</DefineConstants>
    <ErrorReport>prompt</ErrorReport>
    <WarningLevel>4</WarningLevel>
    <PlatformTarget>x86</PlatformTarget>
  </PropertyGroup>
  <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|AnyCPU' ">
    <DebugType>pdbonly</DebugType>
    <Optimize>true</Optimize>
    <OutputPath>bin\Release</OutputPath>
    <DefineConstants>TRACE</DefineConstants>
    <ErrorReport>prompt</ErrorReport>
    <WarningLevel>4</WarningLevel>
    <PlatformTarget>x86</PlatformTarget>
  </PropertyGroup>
  <ItemGroup>
    <Reference Include="ApprovalTests">
      <HintPath>..\..\packages\ApprovalTests.3.0.5\lib\net40\ApprovalTests.dll</HintPath>
    </Reference>
    <Reference Include="ApprovalUtilities">
      <HintPath>..\..\packages\ApprovalUtilities.3.0.5\lib\net35\ApprovalUtilities.dll</HintPath>
    </Reference>
    <Reference Include="GalaSoft.MvvmLight.WPF4">
      <HintPath>..\..\packages\MvvmLightLibs.4.2.30.0\lib\net40\GalaSoft.MvvmLight.WPF4.dll</HintPath>
    </Reference>
    <Reference Include="nunit.framework">
      <HintPath>..\..\packages\NUnit.2.6.3\lib\nunit.framework.dll</HintPath>
    </Reference>
    <Reference Include="PresentationCore" />
    <Reference Include="PresentationFramework" />
    <Reference Include="System" />
    <Reference Include="System.Xaml" />
    <Reference Include="WindowsBase" />
  </ItemGroup>
  <ItemGroup>
    <ProjectReference Include="..\..\..\Content\Online\DeltaEngine.Content.Online.csproj">
      <Project>{68AA6280-09EF-4325-B5F8-B8A967004144}</Project>
      <Name>DeltaEngine.Content.Online</Name>
    </ProjectReference>
    <ProjectReference Include="..\..\..\DeltaEngine.csproj">
      <Project>{20FA8D33-A964-4000-AD82-67BD6900793B}</Project>
      <Name>DeltaEngine</Name>
    </ProjectReference>
    <ProjectReference Include="..\..\..\Mocks\DeltaEngine.Mocks.csproj">
      <Project>{A5F4EF37-7B5F-4AAE-BFF2-C2D04DB805F7}</Project>
      <Name>DeltaEngine.Mocks</Name>
    </ProjectReference>
    <ProjectReference Include="..\..\..\Networking\Messages\DeltaEngine.Networking.Messages.csproj">
      <Project>{74863E62-A568-4C0A-A37F-F04BFA8EB9DB}</Project>
      <Name>DeltaEngine.Networking.Messages</Name>
    </ProjectReference>
    <ProjectReference Include="..\..\Core\DeltaEngine.Editor.Core.csproj">
      <Project>{C667C7FC-A1C7-4CBC-98C0-C97F776E4570}</Project>
      <Name>DeltaEngine.Editor.Core</Name>
    </ProjectReference>
    <ProjectReference Include="..\..\DeltaEngine.Editor.csproj">
      <Project>{4C0891C0-CE79-4A2D-919E-6F706B62C8EA}</Project>
      <Name>DeltaEngine.Editor</Name>
    </ProjectReference>
    <ProjectReference Include="..\..\Messages\DeltaEngine.Editor.Messages.csproj">
      <Project>{E4BF1DFC-4753-42E8-AF9C-06B5B3E6748E}</Project>
      <Name>DeltaEngine.Editor.Messages</Name>
    </ProjectReference>
    <ProjectReference Include="..\..\Mocks\DeltaEngine.Editor.Mocks.csproj">
      <Project>{2A38417D-2378-41F8-BCC6-A65E1894835A}</Project>
      <Name>DeltaEngine.Editor.Mocks</Name>
    </ProjectReference>
    <ProjectReference Include="..\..\AppBuilder\DeltaEngine.Editor.AppBuilder.csproj">
      <Project>{C10F83F9-B20B-4362-8953-9B916B5894BE}</Project>
      <Name>DeltaEngine.Editor.AppBuilder</Name>
    </ProjectReference>
  </ItemGroup>
  <ItemGroup>
    <None Include="packages.config" />
  </ItemGroup>
  <ItemGroup>
    <Compile Include="Properties\AssemblyInfo.cs" />
    <Compile Include="Android\AdbPathProviderTests.cs" />
    <Compile Include="Android\AndroidAppInfoTests.cs" />
    <Compile Include="Android\AndroidDebugBridgeRunnerTests.cs" />
    <Compile Include="Android\AndroidDeviceFinderTests.cs" />
    <Compile Include="Android\AndroidDeviceTests.cs" />
    <Compile Include="Android\AndroidDriverDownloaderTests.cs" />
    <Compile Include="AppBuilderInfoListViewTests.cs" />
    <Compile Include="AppBuilderViewTests.cs" />
    <Compile Include="AppBuilderViewModelTests.cs" />
    <Compile Include="AppBuildMessagesListViewModelTests.cs" />
    <Compile Include="AppBuildMessagesListViewTests.cs" />
    <Compile Include="AppBuildMessageViewModelTests.cs" />
    <Compile Include="AppInfoExtensionsTests.cs" />
    <Compile Include="AppInfoTests.cs" />
    <Compile Include="AppsStorageTests.cs" />
    <Compile Include="UnknownDeviceTests.cs" />
    <Compile Include="Web\WebAppInfoTests.cs" />
    <Compile Include="Web\WebDeviceTests.cs" />
    <Compile Include="Windows\WindowsDeviceTests.cs" />
    <Compile Include="Windows\WindowsAppInfoTests.cs" />
    <Compile Include="BuiltAppsListViewModelTests.cs" />
    <Compile Include="BuiltAppsListViewTests.cs" />
    <Compile Include="MockBuildService.cs" />
    <Compile Include="DeviceTests.cs" />
    <Compile Include="AppBuilderTestExtensions.cs" />
    <Compile Include="TextExtensionsTests.cs" />
    <Compile Include="WindowsPhone7\WP7AppInfoTests.cs" />
    <Compile Include="WindowsPhone7\WP7DeviceFinderTests.cs" />
    <Compile Include="WindowsPhone7\WP7DeviceTests.cs" />
  </ItemGroup>
  <Import Project="$(MSBuildBinPath)\Microsoft.CSharp.targets" />
</Project>

{'repo_name': 'DeltaEngine/DeltaEngine', 'stars': '127', 'repo_language': 'C#', 'file_name': 'AssemblyInfo.cs', 'mime_type': 'text/plain', 'hash': 1242101300771605075, 'source_dataset': 'data'}


/*
Copyright 2014 The Perkeep 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 main

import (
	"encoding/json"
	"flag"
	"fmt"
	"os"
	"strings"
	"text/tabwriter"

	"perkeep.org/pkg/cmdmain"
	"perkeep.org/pkg/search"
)

type searchDocCmd struct{}

func init() {
	cmdmain.RegisterMode("searchdoc", func(flags *flag.FlagSet) cmdmain.CommandRunner {
		return new(searchDocCmd)
	})
}

func (c *searchDocCmd) Describe() string {
	return "Provide help on the predicates for search expressions"
}

func (c *searchDocCmd) Usage() {
	cmdmain.Errorf("pk searchdoc")
}

func (c *searchDocCmd) RunCommand(args []string) error {
	if len(args) > 0 {
		return cmdmain.UsageError("No arguments allowed")
	}

	formattedSearchHelp()
	return nil
}

func formattedSearchHelp() {
	s := search.SearchHelp()
	type help struct{ Name, Description string }
	h := []help{}
	err := json.Unmarshal([]byte(s), &h)
	if err != nil {
		cmdmain.Errorf("%v", err)
		os.Exit(1)
	}

	w := new(tabwriter.Writer)
	w.Init(cmdmain.Stdout, 0, 8, 0, '\t', 0)
	fmt.Fprintln(w, "Predicates for search expressions")
	fmt.Fprintln(w)
	fmt.Fprintln(w, "Predicate\tDescription")
	fmt.Fprintln(w)
	for _, predicate := range h {
		desc := strings.Split(predicate.Description, "\n")
		for i, d := range desc {
			if i == 0 {
				fmt.Fprintf(w, "%s\t%s\n", predicate.Name, d)
			} else {
				fmt.Fprintf(w, "\t%s\n", d)
			}
		}
	}
	w.Flush()
}

{'repo_name': 'perkeep/perkeep', 'stars': '5071', 'repo_language': 'Go', 'file_name': 'camnetdns.go', 'mime_type': 'text/plain', 'hash': 1569798068547829685, 'source_dataset': 'data'}