text:
<!DOCTYPE html>
<html>
   <head>
<!--
   Ray Marching demo by Kevin Roast

   - Lots of code/ideas for this demo come from reading:
     http://www.iquilezles.org/www/material/nvscene2008/rwwtt.pdf
     http://www.pouet.net/topic.php?which=7931&page=1
     http://www.pouet.net/topic.php?which=7920&page=1
     http://iquilezles.org/www/articles/distfunctions/distfunctions.htm
     https://www.shadertoy.com/

   If you want to understand this stuff read through the PDF and pouet.net links above!
-->
      <script src="scripts/dat.gui.min.js"></script>
      <script src="scripts/stats.min.js"></script>
      <script id="vertex" type="x-shader">
attribute vec2 aVertexPosition;

void main()
{
   gl_Position = vec4(aVertexPosition, 0.0, 1.0);
}
      </script>
      <script id="fragment" type="x-shader">
#ifdef GL_ES
precision highp float;
#endif

uniform float time;
uniform vec2 resolution;
uniform vec3 cameraPos;
uniform vec3 cameraLookat;
uniform vec3 lightDir;
uniform vec3 lightColour;
uniform float specular;
uniform float specularHardness;
uniform vec3 diffuse;
uniform float ambientFactor;
uniform bool ao;
uniform bool shadows;
uniform bool rotateWorld;
uniform bool antialias;
uniform bool dof;

// Symmetry group type.
uniform int Type;

// Barycentric coordinates for the principal node
uniform float U;
uniform float V;
uniform float W;

// Vertex radius
uniform float VRadius;

// Segments radius
uniform float SRadius;

uniform bool displayFaces;
uniform bool displaySegments;
uniform bool displayVertices;
uniform bool textureSurface;

#define AO_SAMPLES 4
#define RAY_DEPTH 128
#define MAX_DEPTH 100.0
#define SHADOW_RAY_DEPTH 40
#define DISTANCE_MIN 0.001
#define PI 3.14159265
#define NoiseSize 128.0
#define NoiseRoughness 0.25
#define FLOOR_YPOS -0.9

vec3 nc,p,pab,pbc,pca;

const vec2 delta = vec2(DISTANCE_MIN, 0.);

float Hash(in float n)
{
    return fract(sin(n)*43758.5453123*PI);
}

float Noise(in vec2 x)
{
    vec2 p = floor(x);
    vec2 f = fract(x);
    f = f*f*(3.0-2.0*f);
    float n = p.x + p.y*57.0;
    float res = mix(mix( Hash(n+  0.0), Hash(n+  1.0),f.x),
                    mix( Hash(n+ 57.0), Hash(n+ 58.0),f.x),f.y);
    return res;
}

float Noise(in vec3 x)
{
    vec3 p = floor(x);
    vec3 f = fract(x);
    f = f*f*(3.0-2.0*f);
    float n = p.x + p.y*57.0 + 113.0*p.z;
    return mix(mix(mix( Hash(n+  0.0), Hash(n+  1.0),f.x),
                   mix( Hash(n+ 57.0), Hash(n+ 58.0),f.x),f.y),
               mix(mix( Hash(n+113.0), Hash(n+114.0),f.x),
                   mix( Hash(n+270.0), Hash(n+271.0),f.x),f.y),f.z);
}

vec3 RotateY(vec3 p, float a)
{
   float c,s;
   vec3 q=p;
   c = cos(a);
   s = sin(a);
   p.x = c * q.x + s * q.z;
   p.z = -s * q.x + c * q.z;
   return p;
}

vec3 fold(vec3 pos)
{
   for (int i=0; i<5; i++)
   {
      pos.xy = abs(pos.xy);
      float t = -2.*min(0.,dot(pos,nc));
      pos += t*nc;
      if (i == Type) break;
   }
   return pos;
}

float D2Planes(vec3 pos)
{
   float d0=dot(pos,pab)-dot(pab,p);
   float d1=dot(pos,pbc)-dot(pbc,p);
   float d2=dot(pos,pca)-dot(pca,p);
   return max(max(d0,d1),d2);
}

float D2Segments(vec3 pos)
{
   pos -= p;
   float dla = length(pos-min(0.,pos.x)*vec3(1.,0.,0.));
   float dlb = length(pos-min(0.,pos.y)*vec3(0.,1.,0.));
   float dlc = length(pos-min(0.,dot(pos,nc))*nc);
   return min(min(dla,dlb),dlc)-SRadius;//max(max(dla,dlb),max(dlc,dlp))-SRadius;
}

float D2Vertices(vec3 pos)
{
   return length(pos-p)-VRadius;
}

// Distance estimator from here: (Knighty)
// https://github.com/Syntopia/Fragmentarium/blob/master/Fragmentarium-Source/Examples/Knighty%20Collection/Fold%20and%20Cut%20Polyhedra%20-%20Original.frag
float Dist(vec3 pos)
{
   if (rotateWorld) pos = RotateY(pos, sin(time*0.1)*PI);

   // copy position before it is folded (duplicates across planes!)
   vec3 p = pos;

   // fold and render display options
   pos = fold(pos);
   float d = 10000.0;
   if (displayVertices) d = min(d,D2Vertices(pos));
   if (displaySegments) d = min(d,D2Segments(pos));

   // do not display texture on the panel faces
   bool ts = textureSurface;
   if (displayFaces)
   {
      float dp = min(d,D2Planes(pos));
      if (dp < d)
      {
         ts = false;
         d = dp;
      }
   }

   // floor plane
   d = min(d, dot(p-vec3(0.,FLOOR_YPOS,0.), vec3(0.,1.,0.)));
   float flr = p.y-FLOOR_YPOS;
   if (d < flr)
   {
      if (ts)
      {
         d = d + Noise(p*NoiseSize)*NoiseRoughness/NoiseSize;
      }
   }
   /*else if (ts)
   {
      d = flr + Noise(p.xz*NoiseSize)*NoiseRoughness/NoiseSize;
   }
   else
   {
      d = flr;
   }*/
   return d;
}

// Based on original by IQ - optimized to remove a divide
float CalcAO(vec3 p, vec3 n)
{
   float r = 0.0;
   float w = 1.0;
   for (int i=1; i<=AO_SAMPLES; i++)
   {
      float d0 = float(i) * 0.3;
      r += w * (d0 - Dist(p + n * d0));
      w *= 0.5;
   }
   return 1.0 - clamp(r,0.0,1.0);
}

// Based on original code by IQ
float SoftShadow(vec3 ro, vec3 rd, float k)
{
   float res = 1.0;
   float t = 0.05;         // min-t see http://www.iquilezles.org/www/articles/rmshadows/rmshadows.htm
   for (int i=0; i<SHADOW_RAY_DEPTH; i++)
   {
      float h = Dist(ro + rd * t);
      res = min(res, k*h/t);
      t += h;
      if (t > 10.0) break; // max-t
   }
   return clamp(res,0.0,1.0);
}

vec3 GetNormal(vec3 pos)
{
   vec3 n;
   n.x = Dist( pos + delta.xyy ) - Dist( pos - delta.xyy );
   n.y = Dist( pos + delta.yxy ) - Dist( pos - delta.yxy );
   n.z = Dist( pos + delta.yyx ) - Dist( pos - delta.yyx );

   return normalize(n);
}

// Based on a shading method by Ben Weston. Added AO and SoftShadows to original.
vec4 Shading(vec3 pos, vec3 rd, vec3 norm)
{
   // simple pos test on pos.y for floor (see Dist() above) - different colour and no spec for floor
   if (pos.y > FLOOR_YPOS+DISTANCE_MIN)
   {
      vec3 light = lightColour * max(0.0, dot(norm, lightDir));
      vec3 heading = normalize(-rd + lightDir);
      float spec = pow(max(0.0, dot(heading, norm)), specularHardness);
      light = (diffuse * light) + (spec * specular * lightColour);
      if (shadows) light *= SoftShadow(pos, lightDir, 64.0);   // harder edged shadows on object
      if (ao) light += CalcAO(pos, norm) * ambientFactor;
      return vec4(light, 1.0);
   }
   else
   {
      vec3 light = vec3(0.6,0.8,0.3) * max(0.0, dot(norm, lightDir));
      if (shadows) light *= SoftShadow(pos, lightDir, 32.0);   // softer edged shadows on floor
      if (ao) light += CalcAO(pos, norm) * ambientFactor;
      return vec4(light, 1.0);
   }
}

// Original method by David Hoskins
vec3 Sky(in vec3 rd)
{
   float sunAmount = max(dot(rd, lightDir), 0.0);
   float v = pow(1.0 - max(rd.y,0.0),6.);
   vec3 sky = mix(vec3(.1, .2, .3), vec3(.32, .32, .32), v);
   sky += lightColour * sunAmount * sunAmount * .25 + lightColour * min(pow(sunAmount, 800.0)*1.5, .3);
   return sky;
}

// Camera function by TekF
// Compute ray from camera parameters
vec3 GetRay(vec3 dir, vec2 pos)
{
   pos = pos - 0.5;
   pos.x *= resolution.x/resolution.y;

   dir = normalize(dir);
   vec3 right = normalize(cross(vec3(0.,1.,0.),dir));
   vec3 up = normalize(cross(dir,right));

   return dir + right*pos.x + up*pos.y;
}

vec4 March(vec3 ro, vec3 rd)
{
   float t = 0.0;
   float d = 1.0;
   for (int i=0; i<RAY_DEPTH; i++)
   {
      vec3 p = ro + rd * t;
      d = Dist(p);
      if (abs(d) < DISTANCE_MIN)
      {
         return vec4(p, 1.0);
      }
      t += d;
      if (t >= MAX_DEPTH) break;
   }
   return vec4(0.0);
}

void main()
{
   const int ANTIALIAS_SAMPLES = 4;
   const int DOF_SAMPLES = 16;

   // precalc - once...
   float cospin=cos(PI/float(Type)), scospin=sqrt(0.75-cospin*cospin);
   nc=vec3(-0.5,-cospin,scospin);
   pab=vec3(0.,0.,1.);
   pbc=normalize(vec3(scospin,0.,0.5));
   pca=normalize(vec3(0.,scospin,cospin));
   p=normalize((U*pab+V*pbc+W*pca));

   vec4 res = vec4(0.0);

   if (antialias)
   {
      float d_ang = 2.*PI / float(ANTIALIAS_SAMPLES);
      float ang = d_ang * 0.33333;
      float r = 0.3;
      for (int i = 0; i < ANTIALIAS_SAMPLES; i++)
      {
         vec2 p = vec2((gl_FragCoord.x + cos(ang)*r) / resolution.x, (gl_FragCoord.y + sin(ang)*r) / resolution.y);
         vec3 ro = cameraPos;
         vec3 rd = normalize(GetRay(cameraLookat-cameraPos, p));
         vec4 _res = March(ro, rd);
         // TODO: If floor, optimize normal generation i.e. already known!!
         if (_res.a == 1.0) res.xyz += Shading(_res.xyz, rd, GetNormal(_res.xyz)).xyz;
         else res.xyz += Sky(rd);
         ang += d_ang;
      }
      res.xyz /= float(ANTIALIAS_SAMPLES);
   }
   /*else if (dof)
   {
      vec2 p = gl_FragCoord.xy / resolution.xy;
      vec3 ro = cameraPos;
      vec3 rd = normalize(GetRay(cameraLookat-cameraPos, p));
      vec4 _res = March(ro, rd);

      float d_ang = 2.*PI / float(DOF_SAMPLES);
      float ang = d_ang * 0.33333;
      // cheap DOF!
      float r = abs(cameraLookat.z - _res.z) * 1.0;
      for (int i = 0; i < DOF_SAMPLES; i++)
      {
         p = vec2((gl_FragCoord.x + cos(ang)*r) / resolution.x, (gl_FragCoord.y + sin(ang)*r) / resolution.y);
         ro = cameraPos;
         rd = normalize(GetRay(cameraLookat-cameraPos, p));
         _res = March(ro, rd);
         if (_res.a == 1.0) res.xyz += Shading(_res.xyz, rd, GetNormal(_res.xyz)).xyz;
         else res.xyz += Sky(rd);
         ang += d_ang;
      }
      res.xyz /= float(DOF_SAMPLES);
   }*/
   else
   {
      vec2 p = gl_FragCoord.xy / resolution.xy;
      vec3 ro = cameraPos;
      vec3 rd = normalize(GetRay(cameraLookat-cameraPos, p));
      res = March(ro, rd);
      if (res.a == 1.0) res.xyz = Shading(res.xyz, rd, GetNormal(res.xyz)).xyz;
      else res.xyz = Sky(rd);
   }

   gl_FragColor = vec4(res.xyz, 1.0);
}
      </script>

      <script type="text/javascript">
var requestAnimationFrame = window.requestAnimationFrame || window.webkitRequestAnimationFrame ||
                            window.mozRequestAnimationFrame || window.msRequestAnimationFrame ||
                            function(c) {window.setTimeout(c, 15)};
var config = {
   camera: {
      x: 2.0, y: 2.0, z: 1.0
   },
   lookat: {
      x: 0.0, y: 0.0, z: 0.0
   },
   lightDir: {
      x: -7.0, y: 6.5, z: 0.5
   },
   lightColour: {
      r: 0.6, g: 0.7, b: 0.8
   },
   surface: {
      specular: 2.0,
      specularHardness: 16.0,
      diffuse: 0.35,
      ambientFactor: 0.35
   },
   global: {
      ao: true,
      shadows: true,
      rotateWorld: true,
      antialias: "None"// None|Classic|DOF
   },
   polyhedra: {
      type: 4,
      u: 0.5,
      v: 0.37,
      w: 0.5,
      vradius: 0.066,
      sradius: 0.050,
      displayFaces: false,
      displaySegments: true,
      displayVertices: true,
      textureSurface: true
   }
};

var pause = false;
var stats = new Stats();
var aspect, gl;
function init()
{
   document.addEventListener('keydown', function(e) {
      switch (e.keyCode)
      {
         case 27: // ESC
            pause = !pause;
            break;
      }
   }, false);

   // add GUI controls
   var mobile = (navigator.userAgent.indexOf("Android") !== -1);
   var gui = new dat.GUI();
   var panel = gui.addFolder('Camera Position');
   panel.add(config.camera, "x").min(-16.0).max(16.0).step(0.1);
   panel.add(config.camera, "y").min(-16.0).max(16.0).step(0.1);
   panel.add(config.camera, "z").min(-64.0).max(64.0).step(0.1);
   panel = gui.addFolder('Camera LookAt');
   panel.add(config.lookat, "x").min(-16.0).max(16.0).step(0.1);
   panel.add(config.lookat, "y").min(-16.0).max(16.0).step(0.1);
   panel.add(config.lookat, "z").min(-16.0).max(16.0).step(0.1);
   panel = gui.addFolder('Light Direction');
   panel.add(config.lightDir, "x").min(-16.0).max(16.0).step(0.1);
   panel.add(config.lightDir, "y").min(-16.0).max(16.0).step(0.1);
   panel.add(config.lightDir, "z").min(-16.0).max(16.0).step(0.1);
   panel = gui.addFolder('Light Colour');
   panel.add(config.lightColour, "r").min(0.0).max(3.0).step(0.1);
   panel.add(config.lightColour, "g").min(0.0).max(3.0).step(0.1);
   panel.add(config.lightColour, "b").min(0.0).max(3.0).step(0.1);
   panel = gui.addFolder('Surface');
   panel.add(config.surface, "specular").min(0).max(64);
   panel.add(config.surface, "specularHardness").min(16).max(1024).step(16);
   panel.add(config.surface, "diffuse").min(0).max(1).step(0.05);
   panel.add(config.surface, "ambientFactor").min(0).max(1).step(0.05);
   panel = gui.addFolder('Global');
   panel.add(config.global, "antialias", ["None", "Classic"]).name("Anti Alias");   //, "DOF"
   panel.add(config.global, "shadows").name("Shadows");
   panel.add(config.global, "ao").name("Ambient Occlusion");
   panel.add(config.global, "rotateWorld").name("Rotate World");
   if (!mobile) panel.open();
   panel = gui.addFolder('Polyhedra');
   panel.add(config.polyhedra, "type").min(1).max(5).step(1);
   panel.add(config.polyhedra, "u").min(0).max(1).step(0.01);
   panel.add(config.polyhedra, "v").min(0).max(1).step(0.01);
   panel.add(config.polyhedra, "w").min(0).max(1).step(0.01);
   panel.add(config.polyhedra, "vradius").min(0).max(0.1);
   panel.add(config.polyhedra, "sradius").min(0).max(0.05);
   panel.add(config.polyhedra, "displayFaces").name("Display Faces");
   panel.add(config.polyhedra, "displaySegments").name("Display Segments");
   panel.add(config.polyhedra, "displayVertices").name("Display Vertices");
   panel.add(config.polyhedra, "textureSurface").name("Textured Edges");
   if (!mobile) panel.open();

   document.body.appendChild(stats.domElement);

   // create webgl context on the canvas element
   var canvas = document.getElementById("canvas");
   aspect = canvas.width / canvas.height;
   try
   {
      gl = canvas.getContext("experimental-webgl");
   }
   catch (e)
   {
      document.write("Whoops! No useful WEB-GL impl available. Shame on you and your browser vendor.<br>" + e.message);
      return;
   }
   gl.viewport(0, 0, canvas.width, canvas.height);
   gl.clearColor(0, 0, 0, 1);
   gl.clear(gl.COLOR_BUFFER_BIT);

   // get the vertex and fragment shader source
   var v = document.getElementById("vertex").firstChild.nodeValue;
   var f = document.getElementById("fragment").firstChild.nodeValue;

   // compile and link the shaders
   var vs = gl.createShader(gl.VERTEX_SHADER);
   gl.shaderSource(vs, v);
   gl.compileShader(vs);

   var fs = gl.createShader(gl.FRAGMENT_SHADER);
   gl.shaderSource(fs, f);
   gl.compileShader(fs);

   var program = gl.createProgram();
   gl.attachShader(program, vs);
   gl.attachShader(program, fs);
   gl.linkProgram(program);

   // debug shader compile status
   var error = false;
   if (!gl.getShaderParameter(vs, gl.COMPILE_STATUS))
   {
      error = true;
      console.log(gl.getShaderInfoLog(vs));
   }

   if (!gl.getShaderParameter(fs, gl.COMPILE_STATUS))
   {
      error = true;
      console.log(gl.getShaderInfoLog(fs));
   }

   if (!gl.getProgramParameter(program, gl.LINK_STATUS))
   {
      error = true;
      console.log(gl.getProgramInfoLog(program));
   }
   if (error) return;

   var firstTime = Date.now();
   (f = function() {
      if (!pause)
      {
         stats.begin();

         // create vertices to fill the canvas with a single quad
         var vertices = new Float32Array(
            [
               -1, 1*aspect, 1, 1*aspect, 1, -1*aspect,
               -1, 1*aspect, 1, -1*aspect, -1, -1*aspect
            ]);

         var vbuffer = gl.createBuffer();
         gl.bindBuffer(gl.ARRAY_BUFFER, vbuffer);
         gl.bufferData(gl.ARRAY_BUFFER, vertices, gl.STATIC_DRAW);

         var triCount = 2,
             numItems = vertices.length / triCount;

         gl.useProgram(program);

         var time = (Date.now() - firstTime) / 1000.0;
         program.time = gl.getUniformLocation(program, "time");
         gl.uniform1f(program.time, time);

         program.resolution = gl.getUniformLocation(program, "resolution");
         gl.uniform2f(program.resolution, canvas.width, canvas.height);

         program.cameraPos = gl.getUniformLocation(program, "cameraPos");
         gl.uniform3f(program.cameraPos, config.camera.x, config.camera.y, config.camera.z);

         program.cameraLookat = gl.getUniformLocation(program, "cameraLookat");
         gl.uniform3f(program.cameraLookat, config.lookat.x, config.lookat.y, config.lookat.z);

         program.lightDir = gl.getUniformLocation(program, "lightDir");
         // pre normalise light dir
         var x = config.lightDir.x, y = config.lightDir.y, z = config.lightDir.z;
         var len = x*x + y*y + z*z;
         len = 1.0 / Math.sqrt(len);
         gl.uniform3f(program.lightDir, config.lightDir.x*len, config.lightDir.y*len, config.lightDir.z*len);

         program.lightColour = gl.getUniformLocation(program, "lightColour");
         gl.uniform3f(program.lightColour, config.lightColour.r, config.lightColour.g, config.lightColour.b);

         program.specular = gl.getUniformLocation(program, "specular");
         gl.uniform1f(program.specular, config.surface.specular);

         program.specularHardness = gl.getUniformLocation(program, "specularHardness");
         gl.uniform1f(program.specularHardness, config.surface.specularHardness);

         program.diffuse = gl.getUniformLocation(program, "diffuse");
         gl.uniform3f(program.diffuse, config.surface.diffuse,config.surface.diffuse,config.surface.diffuse);

         program.ambientFactor = gl.getUniformLocation(program, "ambientFactor");
         gl.uniform1f(program.ambientFactor, config.surface.ambientFactor);

         program.rotateWorld = gl.getUniformLocation(program, "rotateWorld");
         gl.uniform1f(program.rotateWorld, config.global.rotateWorld);

         program.ao = gl.getUniformLocation(program, "ao");
         gl.uniform1f(program.ao, config.global.ao);

         program.shadows = gl.getUniformLocation(program, "shadows");
         gl.uniform1f(program.shadows, config.global.shadows);

         program.antialias = gl.getUniformLocation(program, "antialias");
         gl.uniform1f(program.antialias, (config.global.antialias === "Classic"));
         program.dof = gl.getUniformLocation(program, "dof");
         gl.uniform1f(program.dof, (config.global.antialias === "DOF"));

         program.Type = gl.getUniformLocation(program, "Type");
         gl.uniform1i(program.Type, config.polyhedra.type);

         program.U = gl.getUniformLocation(program, "U");
         gl.uniform1f(program.U, config.polyhedra.u);

         program.V = gl.getUniformLocation(program, "V");
         gl.uniform1f(program.V, config.polyhedra.v);

         program.W = gl.getUniformLocation(program, "W");
         gl.uniform1f(program.W, config.polyhedra.w);

         program.VRadius= gl.getUniformLocation(program, "VRadius");
         gl.uniform1f(program.VRadius, config.polyhedra.vradius);

         program.SRadius= gl.getUniformLocation(program, "SRadius");
         gl.uniform1f(program.SRadius, config.polyhedra.sradius);

         program.displayFaces = gl.getUniformLocation(program, "displayFaces");
         gl.uniform1f(program.displayFaces, config.polyhedra.displayFaces);
         program.displaySegments = gl.getUniformLocation(program, "displaySegments");
         gl.uniform1f(program.displaySegments, config.polyhedra.displaySegments);
         program.displayVertices = gl.getUniformLocation(program, "displayVertices");
         gl.uniform1f(program.displayVertices, config.polyhedra.displayVertices);

         program.textureSurface = gl.getUniformLocation(program, "textureSurface");
         gl.uniform1f(program.textureSurface, config.polyhedra.textureSurface);

         program.aVertexPosition = gl.getAttribLocation(program, "aVertexPosition");
         gl.enableVertexAttribArray(program.aVertexPosition);
         gl.vertexAttribPointer(program.aVertexPosition, triCount, gl.FLOAT, false, 0, 0);

         gl.drawArrays(gl.TRIANGLES, 0, numItems);

         stats.end();
         //pause = true;
      }
      requestAnimationFrame(f);
   })();
}
      </script>
      <script src="scripts/utils.js"></script>
      <link rel="stylesheet" href="../../reset.css">
      <link rel="stylesheet" href="./page.css">
      <link href='http://fonts.googleapis.com/css?family=Open+Sans:400,300,600' rel='stylesheet' type='text/css'>
   </head>
   <body onload="init()">
      <canvas id="canvas" width="512" height="512"></canvas>
      <a href="#" id="fullscreen">Toggle Full Screen</a>
      <a href="." id="back">Show me more awesome demos!</a>
   </body>
</html>


text: A dumping ground of old projects, scripts, and programs of mine.

redpajama_set_name: RedPajamaGithub


text:
RSpec.shared_examples 'import/export json legacy reader' do
  let(:relation_names) { [] }

  let(:legacy_reader) do
    described_class.new(
      data,
      relation_names: relation_names,
      allowed_path: "project")
  end

  describe '#consume_attributes' do
    context 'when valid path is passed' do
      subject { legacy_reader.consume_attributes("project") }

      context 'no excluded attributes' do
        let(:relation_names) { [] }

        it 'returns the whole tree from parsed JSON' do
          expect(subject).to eq(json_data)
        end
      end

      context 'some attributes are excluded' do
        let(:relation_names) { %w[milestones labels] }

        it 'returns hash without excluded attributes and relations' do
          expect(subject).not_to include('milestones', 'labels')
        end
      end
    end

    context 'when invalid path is passed' do
      it 'raises an exception' do
        expect { legacy_reader.consume_attributes("invalid-path") }
          .to raise_error(ArgumentError)
      end
    end
  end

  describe '#consume_relation' do
    context 'when valid path is passed' do
      let(:key) { 'labels' }

      subject { legacy_reader.consume_relation("project", key) }

      context 'key has not been consumed' do
        it 'returns an Enumerator' do
          expect(subject).to be_an_instance_of(Enumerator)
        end

        context 'value is nil' do
          before do
            expect(legacy_reader).to receive(:relations).and_return({ key => nil })
          end

          it 'yields nothing to the Enumerator' do
            expect(subject.to_a).to eq([])
          end
        end

        context 'value is an array' do
          before do
            expect(legacy_reader).to receive(:relations).and_return({ key => %w[label1 label2] })
          end

          it 'yields every relation value to the Enumerator' do
            expect(subject.to_a).to eq([['label1', 0], ['label2', 1]])
          end
        end

        context 'value is not array' do
          before do
            expect(legacy_reader).to receive(:relations).and_return({ key => 'non-array value' })
          end

          it 'yields the value with index 0 to the Enumerator' do
            expect(subject.to_a).to eq([['non-array value', 0]])
          end
        end
      end

      context 'key has been consumed' do
        before do
          legacy_reader.consume_relation("project", key).first
        end

        it 'yields nothing to the Enumerator' do
          expect(subject.to_a).to eq([])
        end
      end
    end

    context 'when invalid path is passed' do
      it 'raises an exception' do
        expect { legacy_reader.consume_relation("invalid") }
          .to raise_error(ArgumentError)
      end
    end
  end
end


text:
package edu.cloudy.nlp;

public abstract class ContextDelimiter
{
	public final static String SENTIMENT_DELIMITER_TEXT = "@$@$";
	public final static String SENTIMENT_DELIMITER_REGEX = "\\@\\$\\@\\$";

	public final static String DYNAMIC_DELIMITER_TEXT = "$@$@$";
	public final static String DYNAMIC_DELIMITER_REGEX = "\\$\\@\\$\\@\\$";
}


text:
ITEM.Name = "Karambit Knife" .. " | " .. "Autotronic"
ITEM.Price = 20000
ITEM.Model = "models/weapons/w_csgo_karambit.mdl"
ITEM.Skin = 14
ITEM.WeaponClass = "csgo_karambit_autotronic"

function ITEM:OnEquip(ply)
	ply:Give(self.WeaponClass)
end

function ITEM:OnBuy(ply)
	ply:Give(self.WeaponClass)
	ply:SelectWeapon(self.WeaponClass)
end

function ITEM:OnSell(ply)
	ply:StripWeapon(self.WeaponClass)
end

function ITEM:OnHolster(ply)
	ply:StripWeapon(self.WeaponClass)
end


text:
'use strict';

const _ = require('lodash/fp');
const co = require('co');
const util = require('./util');

/**
 * Filters the given Array using the given function asynchronously.
 * This function is curried so you may leave of the second parameter to delay execution.
 * If the function returns a Promise the Promise will be resolved and the result will be used.
 * If the given function is a GeneratorFunction it will be wrapped with co.
 *
 * Example:
 * const result = yield cf.filter(function* (number) {
 *     return yield asyncIsOddNumber(number);
 * }, [1, 2, 4]);
 *
 * @param {GeneratorFunction} fn that will be used to filter the Array.
 * @param {Object|Array} data that will be filtered.
 * @returns {Promise}
 */
const filter = _.curry(function filter(fn, data) {
    return co(function* () {

        if (_.isArray(data)) {

            if(util.isGenerator(fn)) {
                fn = co.wrap(fn);
            }

            //first build an Array of Promises that will contain if data at a specific index passed the test
            let filteredData = [];
            for(let i = 0; i < data.length; i++) {
                filteredData.push(fn(data[i]));
            }

            if(filteredData.length < 1) {
                return [];
            }

            //if the function did return a Promise we'll yield it
            if(util.isPromise(filteredData[0])) {
                //resolve promises in parallel
                filteredData = yield filteredData;
            }

            //now we fill a result array with the filtered data
            let result = [];
            for(let i = 0; i < data.length; i++) {
                if(filteredData[i]) {
                    result.push(data[i]);
                }
            }

            return result;
        }

        //error
        else {
            throw new Error(`You can only filter Arrays! Given: ${typeof data}`);
        }

    });
});

/**
 * Filters the given Array using the given generator function asynchronously but one after another.
 * If you want the highest possible speed you should not use this function but the completely asynchronous filter function!
 * That means your elements will get filtered in order and the function will wait until something
 * has been returned by your function before continuing execution.
 *
 * This function is curried so you may leave of the second parameter to delay execution.
 * If the function returns a Promise the Promise will be resolved and the result will be used.
 * If the given function is a GeneratorFunction it will be wrapped with co.
 *
 * Example:
 * const result = yield cf.filterSerial(function* (number) {
 *     return yield asyncIsOddNumber(number);
 * }, [1, 2, 4]);
 *
 * @param {GeneratorFunction} fn that will be used to filter the Array.
 * @param {Object|Array} data that will be filtered.
 * @returns {Promise}
 */
const filterSerial = _.curry(function filter(fn, data) {
    return co(function* () {

        if(util.isGenerator(fn)) {
            fn = co.wrap(fn);
        }

        //filter array
        if (_.isArray(data)) {
            let result = [];
            for(let i = 0; i < data.length; i++) {
                let fnResult = fn(data[i]);
                let isPromise = util.isPromise(fnResult);
                if((isPromise && (yield fnResult)) || (!isPromise && fnResult)) {
                    result.push(data[i]);
                }
            }
            return result;
        }

        //error
        else {
            throw new Error(`You can only filter Arrays! Given: ${typeof data}`);
        }

    });
});

module.exports = {
    filter: filter,
    filterSerial: filterSerial
};


text:
<?php

$params = require(__DIR__ . '/params.php');

$config = [
    'id' => 'basic',
    'basePath' => dirname(__DIR__),
    'bootstrap' => ['log'],
    'components' => [
        'request' => [
            // !!! insert a secret key in the following (if it is empty) - this is required by cookie validation
            'cookieValidationKey' => 'mondayInitializing',
        ],
        'cache' => [
            'class' => 'yii\caching\FileCache',
        ],
        'user' => [
            'identityClass' => 'app\models\User',
            'enableAutoLogin' => true,
        ],
        'errorHandler' => [
            'errorAction' => 'site/error',
        ],
        'mailer' => [
            'class' => 'yii\swiftmailer\Mailer',
            // send all mails to a file by default. You have to set
            // 'useFileTransport' to false and configure a transport
            // for the mailer to send real emails.
            'useFileTransport' => true,
        ],
        'log' => [
            'traceLevel' => YII_DEBUG ? 3 : 0,
            'targets' => [
                [
                    'class' => 'yii\log\FileTarget',
                    'levels' => ['error', 'warning'],
                ],
            ],
        ],
        'db' => require(__DIR__ . '/db.php'),
        'urlManager' => [
            //Disable index.php
            'showScriptName'=>false,
            'enablePrettyUrl' => true,
            'rules' => [
                '<controller:\w+>/<id:\d+>' => '<controller>/view',
                '<controller:\w+>/<action:\w+>/<id:\d+>' => '<controller>/<action>',
                '<controller:\w+>/<action:\w+>' => '<controller>/<action>',
            ],
        ],
    ],
    'params' => $params,
];

if (YII_ENV_DEV) {
    // configuration adjustments for 'dev' environment
    /* Don't use the debug module for now
    $config['bootstrap'][] = 'debug';
    $config['modules']['debug'] = [
        'class' => 'yii\debug\Module',
    ];
    */

    $config['bootstrap'][] = 'gii';
    $config['modules']['gii'] = [
        'class' => 'yii\gii\Module',
    ];
}

return $config;


text:
using System;
using System.ComponentModel.DataAnnotations;

namespace Queryable.Web.Models
{
    public class CreatePersonCommand
    {
        public int Id { get; set; }

        [Required]
        [Display(Name = "First Name")]
        public string FirstName { get; set; }

        [Required]
        [Display(Name = "Last Name")]
        public string LastName { get; set; }

        [Required]
        [Display(Name = "Date of Birth")]
        public DateTime? DateOfBirth { get; set; }
    }
}


text:
Prefix	Suffixes

	A	B	A B

A	out: 0	out: 1	out: 2	out: 3

A B	out: 3	out: 2	out: 1	out: 0

A B C	out: 0123	out: 0123	out: 0123	out: 0123


text:
module AssetGen
  class Asset

  end
end


text:
import Renascence

def main():
    Renascence.setStreamPath("./")
    Renascence.setLibPath("./")
    producer = Renascence.init(["func.xml"])
    print producer.listAllFunctions()
    print producer.listAllTypes()
    x0 = producer.load('TrBmp', "input.jpg")
    x1 = producer.load('TrBmp', "input_sharp.jpg")
    x2 = producer.load('TrBmp', "output.jpg")
    filterMatrix = producer.build("FR(x0, x1)").run(producer.merge(x2, x1))
    print filterMatrix.dump()

    [Trainner, BestValue] = producer.train("S(ADF(Treator,x0,x1))", producer.merge(x0, x1), 5, cacheFile='temp.txt', postFormula='FIT(x0, x1)', postExtraInput=x2)
    formula = Trainner.ADF("")
    print 'Formula: ', formula
    print 'Parameters: ', Trainner.parameters()
    print BestValue
    predictor = producer.build(formula, Trainner.parameters())
    y_p = predictor.run(producer.merge(x0,x1))
    y_p.save("output/output_trained.jpg")

main()


text:
Write a program that outputs the lyrics of the song 'I Know an Old Lady Who Swallowed a Fly'

This is a [cumulative song](http://en.wikipedia.org/wiki/Cumulative_song) of unknown origin.

This is one of many common variants.

```plain
I know an old lady who swallowed a fly.
I don't know why she swallowed the fly. Perhaps she'll die.

I know an old lady who swallowed a spider.
It wriggled and jiggled and tickled inside her.
She swallowed the spider to catch the fly.
I don't know why she swallowed the fly. Perhaps she'll die.

I know an old lady who swallowed a bird.
How absurd to swallow a bird!
She swallowed the bird to catch the spider that wriggled and jiggled and tickled inside her.
She swallowed the spider to catch the fly.
I don't know why she swallowed the fly. Perhaps she'll die.

I know an old lady who swallowed a cat.
Imagine that, to swallow a cat!
She swallowed the cat to catch the bird.
She swallowed the bird to catch the spider that wriggled and jiggled and tickled inside her.
She swallowed the spider to catch the fly.
I don't know why she swallowed the fly. Perhaps she'll die.

I know an old lady who swallowed a dog.
What a hog, to swallow a dog!
She swallowed the dog to catch the cat.
She swallowed the cat to catch the bird.
She swallowed the bird to catch the spider that wriggled and jiggled and tickled inside her.
She swallowed the spider to catch the fly.
I don't know why she swallowed the fly. Perhaps she'll die.

I know an old lady who swallowed a goat.
Just opened her throat and swallowed a goat!
She swallowed the goat to catch the dog.
She swallowed the dog to catch the cat.
She swallowed the cat to catch the bird.
She swallowed the bird to catch the spider that wriggled and jiggled and tickled inside her.
She swallowed the spider to catch the fly.
I don't know why she swallowed the fly. Perhaps she'll die.

I know an old lady who swallowed a cow.
I don't know how she swallowed a cow!
She swallowed the cow to catch the goat.
She swallowed the goat to catch the dog.
She swallowed the dog to catch the cat.
She swallowed the cat to catch the bird.
She swallowed the bird to catch the spider that wriggled and jiggled and tickled inside her.
She swallowed the spider to catch the fly.
I don't know why she swallowed the fly. Perhaps she'll die.

I know an old lady who swallowed a horse.
She's dead, of course!
```

## Making the Test Suite Pass

Execute the tests with:

```bash
$ jasmine-node .
```

In many test suites all but the first test have been skipped.

Once you get a test passing, you can unskip the next one by
changing `xit` to `it`.

## Source

Wikipedia [view source](http://en.wikipedia.org/wiki/There_Was_an_Old_Lady_Who_Swallowed_a_Fly)


text:
<?php
defined('BASEPATH') OR exit('No direct script access allowed');

class Pay extends CI_Controller
{
    function __construct()
    {
        parent::__construct();
        $this->load->helper('url');
        $this->load->model("UserModel");
    }

    public function redeem()
    {
        $username = $this->input->get('user');
        $points['points'] = $this->UserModel->getPoints($username);
        $points['total'] = $this->input->get('total');;
        $this->load->view('redeem_points',$points);
    }

}


text:
package com.dslplatform.json.models;

import com.dslplatform.json.CompiledJson;
import com.dslplatform.json.JsonAttribute;

@CompiledJson(formats = {CompiledJson.Format.ARRAY, CompiledJson.Format.OBJECT})
public abstract class FreeBuilder {
	@JsonAttribute(index = 1, name = "name")
	public abstract String name();

	@JsonAttribute(index = 2, name = "id")
	public abstract int id();

	public static Builder builder() {
		return new Builder();
	}

	public static class Builder extends Employee_Builder {
	}

	static abstract class Employee_Builder {
		private String name;
		private int id;

		public Builder name(String name) {
			this.name = name;
			return (Builder) this;
		}

		public String name() {
			return name;
		}

		public Builder id(int id) {
			this.id = id;
			return (Builder) this;
		}

		public int id() {
			return id;
		}

		public FreeBuilder build() {
			return new Employee_Builder.Value(this);
		}

		private static final class Value extends FreeBuilder {
			private final String name;
			private final int id;

			private Value(Employee_Builder builder) {
				this.name = builder.name;
				this.id = builder.id;
			}

			@Override
			public String name() {
				return name;
			}

			@Override
			public int id() {
				return id;
			}
		}
	}
}


text:
package com.zaradai.kunzite.trader.config;

import com.zaradai.kunzite.config.ConfigurationSource;
import org.junit.Before;
import org.junit.Test;

import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify;

public class SourcedTraderConfigurationTest {
    private ConfigurationSource source;
    private SourcedTraderConfiguration uut;

    @Before
    public void setUp() throws Exception {
        source = mock(ConfigurationSource.class);
        uut = new SourcedTraderConfiguration(source);
    }

    @Test
    public void shouldGetStaticConfigUri() throws Exception {
        uut.getStaticConfigUri();

        verify(source).get(SourcedTraderConfiguration.STATIC_CONFIG_URI,
                SourcedTraderConfiguration.DEFAULT_STATIC_CONFIG_URI);
    }

    @Test
    public void shouldGetMarketDataConfigUri() throws Exception {
        uut.getMarketDataConfigUri();

        verify(source).get(SourcedTraderConfiguration.MD_CONFIG_URI, SourcedTraderConfiguration.DEFAULT_MD_CONFIG_URI);
    }

    @Test
    public void shouldGetOrderGatewayConfigUri() throws Exception {
        uut.getOrderGatewayConfigUri();

        verify(source).get(SourcedTraderConfiguration.OG_URI,SourcedTraderConfiguration.DEFAULT_OG_CONFIG_URI);
    }
}


text:
<!--
Copyright (c) 2018 Google Inc.

Licensed under the Apache License, Version 2.0 (the "License"); you may not
use this file except in compliance with the License. You may obtain a copy of
the License at

    http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
License for the specific language governing permissions and limitations under
the License.
-->

<!doctype html>
<html>
  <head>
    <title>Hello Custom Elements</title>
  </head>
  <body>
    <hello-element>
      Hello, I'm a custom element.
      If you see this static text, it means I haven't been upgraded. :(
    </hello-element>
    <script src="/external/polyfill/src/native-shim.js"></script>
    <script src="/external/polyfill/custom-elements.min.js"></script>
    <script src="hello_bin.js"></script>
  </body>
</html>


text:
#include <aws/codebuild/model/LanguageType.h>
#include <aws/core/utils/HashingUtils.h>
#include <aws/core/Globals.h>
#include <aws/core/utils/EnumParseOverflowContainer.h>

using namespace Aws::Utils;

namespace Aws
{
  namespace CodeBuild
  {
    namespace Model
    {
      namespace LanguageTypeMapper
      {

        static const int JAVA_HASH = HashingUtils::HashString("JAVA");
        static const int PYTHON_HASH = HashingUtils::HashString("PYTHON");
        static const int NODE_JS_HASH = HashingUtils::HashString("NODE_JS");
        static const int RUBY_HASH = HashingUtils::HashString("RUBY");
        static const int GOLANG_HASH = HashingUtils::HashString("GOLANG");
        static const int DOCKER_HASH = HashingUtils::HashString("DOCKER");
        static const int ANDROID__HASH = HashingUtils::HashString("ANDROID");
        static const int DOTNET_HASH = HashingUtils::HashString("DOTNET");
        static const int BASE_HASH = HashingUtils::HashString("BASE");

        LanguageType GetLanguageTypeForName(const Aws::String& name)
        {
          int hashCode = HashingUtils::HashString(name.c_str());
          if (hashCode == JAVA_HASH)
          {
            return LanguageType::JAVA;
          }
          else if (hashCode == PYTHON_HASH)
          {
            return LanguageType::PYTHON;
          }
          else if (hashCode == NODE_JS_HASH)
          {
            return LanguageType::NODE_JS;
          }
          else if (hashCode == RUBY_HASH)
          {
            return LanguageType::RUBY;
          }
          else if (hashCode == GOLANG_HASH)
          {
            return LanguageType::GOLANG;
          }
          else if (hashCode == DOCKER_HASH)
          {
            return LanguageType::DOCKER;
          }
          else if (hashCode == ANDROID__HASH)
          {
            return LanguageType::ANDROID_;
          }
          else if (hashCode == DOTNET_HASH)
          {
            return LanguageType::DOTNET;
          }
          else if (hashCode == BASE_HASH)
          {
            return LanguageType::BASE;
          }
          EnumParseOverflowContainer* overflowContainer = Aws::GetEnumOverflowContainer();
          if(overflowContainer)
          {
            overflowContainer->StoreOverflow(hashCode, name);
            return static_cast<LanguageType>(hashCode);
          }

          return LanguageType::NOT_SET;
        }

        Aws::String GetNameForLanguageType(LanguageType enumValue)
        {
          switch(enumValue)
          {
          case LanguageType::JAVA:
            return "JAVA";
          case LanguageType::PYTHON:
            return "PYTHON";
          case LanguageType::NODE_JS:
            return "NODE_JS";
          case LanguageType::RUBY:
            return "RUBY";
          case LanguageType::GOLANG:
            return "GOLANG";
          case LanguageType::DOCKER:
            return "DOCKER";
          case LanguageType::ANDROID_:
            return "ANDROID";
          case LanguageType::DOTNET:
            return "DOTNET";
          case LanguageType::BASE:
            return "BASE";
          default:
            EnumParseOverflowContainer* overflowContainer = Aws::GetEnumOverflowContainer();
            if(overflowContainer)
            {
              return overflowContainer->RetrieveOverflow(static_cast<int>(enumValue));
            }

            return "";
          }
        }

      } // namespace LanguageTypeMapper
    } // namespace Model
  } // namespace CodeBuild
} // namespace Aws


text:
@interface CDTQMatcherIndexManager : CDTQIndexManager

@end


text:
[![Build Status](https://travis-ci.org/mmalecki/voter.png?branch=master)](https://travis-ci.org/mmalecki/voter)

Distributed voting based on Scuttlebutt

## Installation

```sh
npm install voter
```

## Usage

```js
var Voter = require('voter');

var timeout = 100;

function onNew(key, voting) {
  console.log(this.id + ': voting ' + key + ' with quorum ' + voting.quorum + ' started');
  setTimeout(function () {
    this.vote(key, true);
  }.bind(this), timeout += 100);
}

function onVote(key, origin, vote) {
  console.log(this.id + ': ' + origin + ' voted: ' + JSON.stringify(vote));
}

function onQuorum(key, vote) {
  console.log(this.id + ': voting ' + key + ' reached quorum: ' + JSON.stringify(vote));
}

var a = new Voter();
var b = new Voter();
var c = new Voter();

a.on('new', onNew);
b.on('new', onNew);
c.on('new', onNew);

a.on('vote', onVote);
b.on('vote', onVote);
c.on('vote', onVote);

a.on('quorum', onQuorum);
b.on('quorum', onQuorum);
c.on('quorum', onQuorum);

var ab = a.createStream();
var bc = b.createStream();

ab.pipe(b.createStream()).pipe(ab);
bc.pipe(c.createStream()).pipe(bc);

a.startVoting('voting', { quorum: 4, timeout: 10000 });

setTimeout(function () {
  var d = new Voter();
  var cd = c.createStream();
  cd.pipe(d.createStream()).pipe(cd);

  d.on('new', onNew);
  d.on('vote', onVote);
  d.on('quorum', onQuorum);

}, 4000);
```


text:
function init(callback) {
	if ((self.registration) && (self.registration.pushManager) && (self.registration.pushManager.getSubscription)) {
		return self.registration.pushManager.getSubscription().then(function(subscription) {
			if (subscription) {
				var token = "";
				if ((subscription.subscriptionId) && (subscription.endpoint.indexOf(subscription.subscriptionId) < 0))
					token = subscription.endpoint + "/" + subscription.subscriptionId;
				else
					token = subscription.endpoint;
				callback("/@msg.csp?token=" + encodeURIComponent(token));
			}
		});
	}
}

self.addEventListener('activate', function(event) {
    init();
});

function do_notify(url) {
		fetch(url).then(function(response) {
			if (response.status !== 200) {
				console.log('Looks like there was a problem. Status Code: ' + response.status);
				throw new Error();
			}

			return response.json().then(function(data) {
					if (data.error || !data.notification) {
						console.error('The API returned an error.', data.error);
						throw new Error();
					}

					var title = 'Concept Client';
					var body = 'Your attention is needed.';
					var icon = '/@/img/icon-192x192.png';
					var notificationTag = 'concept-client-notification-tag';

					if (data.notification.title)
						title = data.notification.title;
					if (data.notification.message)
						message = data.notification.message;
					if (data.notification.icon)
						icon = data.notification.icon;
					if (data.notification.tag)
						notificationTag = data.notification.tag;
					return self.registration.showNotification(title, {
						body: message,
						icon: icon,
						tag: notificationTag
					});
			});
		}).catch(function(err) {
			console.error('Unable to retrieve data', err);

			var title = 'Concept Client';
			var body = 'Your attention is needed.';
			var icon = '/img/icon-192x192.png';
			var tag = 'concept-client-notification-tag';

			return self.registration.showNotification(title, {
				body: body,
				icon: icon,
				tag: tag
			});
		})
}

self.addEventListener('push', function(event) {
	event.waitUntil(init(do_notify));
});


text:
<?php

namespace minion\Commands;

use Symfony\Component\Console\Command\Command;
use Symfony\Component\Console\Input\InputArgument;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Input\InputOption;
use Symfony\Component\Console\Output\OutputInterface;
use Symfony\Component\Console\Style\SymfonyStyle;

class MakeCommand extends Command
{

    protected function configure()
    {
        $this->setName('make:command')
            ->setDescription('Make a new command')
            ->setHelp('Make a new command')
            ->addArgument('class', InputArgument::REQUIRED, 'Class name of the command to make')
            ->addOption('name', null, InputOption::VALUE_OPTIONAL, 'The command name to execute');
    }

    public function execute(InputInterface $input, OutputInterface $output)
    {

        $style = new SymfonyStyle($input, $output);
        $style->title('Making command');

        $className = $input->getArgument('class');
        $filename = "{$className}.php";
        $path = "Commands";

        if( ($commandName = $input->getOption('name')) == false ){
            $commandName = $className;
        }

        if( file_exists($path) == false ){
            mkdir('Commands');
        }

        // Does file name already exist?
        if( file_exists("{$path}/{$filename}") ){
            throw new \Exception("File {$path}/{$filename} already exists");
        }

        // Write new command to disk
        $template = file_get_contents(__DIR__.'/../Templates/Command.php.tpl');
        $template = preg_replace('/\:ClassName/', $className, $template);
        $template = preg_replace('/\:CommandName/', $commandName, $template);
        file_put_contents("{$path}/{$filename}", $template);

        $style->success('Command created');

        return null;
    }

}


text:
"""Ce fichier contient la classe PotionVente, détaillée plus bas."""

from abstraits.obase import BaseObj
from corps.fonctions import lisser

class PotionVente(BaseObj):

    """Cette classe enveloppe un conteneur de potion et une potion.

    Elle simule certains comportements d'un objet standard afin de permettre
    la vente des deux en magasin via la syntaxe /s conteneur/potion (voir
    l'éditeur de magasin du module salle).

    """

    type_achat = "potion"
    def __init__(self, proto_conteneur, proto_potion):
        """Constructeur de la classe"""
        BaseObj.__init__(self)
        self.conteneur = proto_conteneur
        self.potion = proto_potion
        self._construire()

    def __getnewargs__(self):
        return (None, None)

    def __repr__(self):
        return "<{} dans {}>".format(self.potion.cle, self.conteneur.cle)

    def __str__(self):
        return self.conteneur.cle + "/" + self.potion.cle

    @property
    def cle(self):
        return self.conteneur.cle + "/" + self.potion.cle

    @property
    def m_valeur(self):
        return self.conteneur.prix + self.potion.prix

    @property
    def nom_achat(self):
        if self.potion == "eau":
            nom = "eau"
        else:
            nom = self.potion.nom_singulier
        ajout = lisser(
                " " + self.conteneur.connecteur.format(s="") + " " + nom)
        return self.conteneur.nom_singulier + ajout

    def get_nom(self, nombre=1):
        """Retourne le nom complet en fonction du nombre.

        Par exemple :
        Si nombre == 1 : retourne le nom singulier
        Sinon : retourne le nombre et le nom pluriel

        """
        ajout = ""
        if self.potion is not None:
            s = "s" if nombre > 1 else ""
            if self.potion == "eau":
                nom = "eau"
            else:
                nom = self.potion.get_nom()
            ajout = lisser(
                    " " + self.conteneur.connecteur.format(s=s) + " " + nom)
        if nombre <= 0:
            raise ValueError("la fonction get_nom a été appelée " \
                    "avec un nombre négatif ou nul.")
        elif nombre == 1:
            return self.conteneur.nom_singulier + ajout
        else:
            if self.conteneur.noms_sup:
                noms_sup = list(self.conteneur.noms_sup)
                noms_sup.reverse()
                for nom in noms_sup:
                    if nombre >= nom[0]:
                        return nom[1] + ajout
            return str(nombre) + " " + self.conteneur.nom_pluriel + ajout

    def acheter(self, quantite, magasin, transaction):
        """Achète les objets dans la quantité spécifiée."""
        salle = magasin.parent
        for i in range(quantite):
            conteneur = importeur.objet.creer_objet(self.conteneur)
            conteneur.potion = importeur.objet.creer_objet(self.potion)
            salle.objets_sol.ajouter(conteneur)

    def regarder(self, personnage):
        """Le personnage regarde le service (avant achat)."""
        msg = self.conteneur.regarder(personnage) + "\n"
        msg += self.potion.description.regarder(personnage)
        return msg


text:
namespace Microsoft.Azure.Management.ManagementPartner.Models
{
    using Microsoft.Rest;
    using Microsoft.Rest.Azure;
    using Microsoft.Rest.Serialization;
    using Newtonsoft.Json;
    using System.Linq;

    /// <summary>
    /// this is the management partner operations response
    /// </summary>
    [Rest.Serialization.JsonTransformation]
    public partial class PartnerResponse : IResource
    {
        /// <summary>
        /// Initializes a new instance of the PartnerResponse class.
        /// </summary>
        public PartnerResponse()
        {
            CustomInit();
        }

        /// <summary>
        /// Initializes a new instance of the PartnerResponse class.
        /// </summary>
        /// <param name="etag">Type of the partner</param>
        /// <param name="id">Identifier of the partner</param>
        /// <param name="name">Name of the partner</param>
        /// <param name="partnerId">This is the partner id</param>
        /// <param name="partnerName">This is the partner name</param>
        /// <param name="tenantId">This is the tenant id.</param>
        /// <param name="objectId">This is the object id.</param>
        /// <param name="version">This is the version.</param>
        /// <param name="updatedTime">This is the DateTime when the partner was
        /// updated.</param>
        /// <param name="createdTime">This is the DateTime when the partner was
        /// created.</param>
        /// <param name="state">This is the partner state. Possible values
        /// include: 'Active', 'Deleted'</param>
        /// <param name="type">Type of resource.
        /// "Microsoft.ManagementPartner/partners"</param>
        public PartnerResponse(int? etag = default(int?), string id = default(string), string name = default(string), string partnerId = default(string), string partnerName = default(string), string tenantId = default(string), string objectId = default(string), string version = default(string), System.DateTime? updatedTime = default(System.DateTime?), System.DateTime? createdTime = default(System.DateTime?), string state = default(string), string type = default(string))
        {
            Etag = etag;
            Id = id;
            Name = name;
            PartnerId = partnerId;
            PartnerName = partnerName;
            TenantId = tenantId;
            ObjectId = objectId;
            Version = version;
            UpdatedTime = updatedTime;
            CreatedTime = createdTime;
            State = state;
            Type = type;
            CustomInit();
        }

        /// <summary>
        /// An initialization method that performs custom operations like setting defaults
        /// </summary>
        partial void CustomInit();

        /// <summary>
        /// Gets or sets type of the partner
        /// </summary>
        [JsonProperty(PropertyName = "etag")]
        public int? Etag { get; set; }

        /// <summary>
        /// Gets identifier of the partner
        /// </summary>
        [JsonProperty(PropertyName = "id")]
        public string Id { get; private set; }

        /// <summary>
        /// Gets name of the partner
        /// </summary>
        [JsonProperty(PropertyName = "name")]
        public string Name { get; private set; }

        /// <summary>
        /// Gets or sets this is the partner id
        /// </summary>
        [JsonProperty(PropertyName = "properties.partnerId")]
        public string PartnerId { get; set; }

        /// <summary>
        /// Gets or sets this is the partner name
        /// </summary>
        [JsonProperty(PropertyName = "properties.partnerName")]
        public string PartnerName { get; set; }

        /// <summary>
        /// Gets or sets this is the tenant id.
        /// </summary>
        [JsonProperty(PropertyName = "properties.tenantId")]
        public string TenantId { get; set; }

        /// <summary>
        /// Gets or sets this is the object id.
        /// </summary>
        [JsonProperty(PropertyName = "properties.objectId")]
        public string ObjectId { get; set; }

        /// <summary>
        /// Gets or sets this is the version.
        /// </summary>
        [JsonProperty(PropertyName = "properties.version")]
        public string Version { get; set; }

        /// <summary>
        /// Gets or sets this is the DateTime when the partner was updated.
        /// </summary>
        [JsonProperty(PropertyName = "properties.updatedTime")]
        public System.DateTime? UpdatedTime { get; set; }

        /// <summary>
        /// Gets or sets this is the DateTime when the partner was created.
        /// </summary>
        [JsonProperty(PropertyName = "properties.createdTime")]
        public System.DateTime? CreatedTime { get; set; }

        /// <summary>
        /// Gets or sets this is the partner state. Possible values include:
        /// 'Active', 'Deleted'
        /// </summary>
        [JsonProperty(PropertyName = "properties.state")]
        public string State { get; set; }

        /// <summary>
        /// Gets type of resource. "Microsoft.ManagementPartner/partners"
        /// </summary>
        [JsonProperty(PropertyName = "type")]
        public string Type { get; private set; }

    }
}


text:
Code chunks that are used across multiple reports.

These are different from functions in that they are used via source().

## Files

- example.Rmd: Description.


text:
// Copyright 2005 Bob Ippolito. All Rights Reserved.
// Modifications Copyright 2009 The Closure Library Authors.
// All Rights Reserved.

/**
 * @fileoverview Class for tracking multiple asynchronous operations and
 * handling the results. The DeferredList object here is patterned after the
 * DeferredList object in the Twisted python networking framework.
 *
 * Based on the MochiKit code.
 *
 * See: http://twistedmatrix.com/projects/core/documentation/howto/defer.html
 *
 * @author brenneman@google.com (Shawn Brenneman)
 */

goog.provide('goog.async.DeferredList');

goog.require('goog.async.Deferred');

/**
 * Constructs an object that waits on the results of multiple asynchronous
 * operations and marshals the results. It is itself a Deferred,
 * and may have an execution sequence of callback functions added to it. Each
 * DeferredList instance is single use and may be fired only once.
 *
 * The default behavior of a DeferredList is to wait for a success
 * or error result from every Deferred in its input list. Once
 * every result is available, the DeferredList's execution sequence
 * is fired with a list of [success, result] array pairs, where
 * success is a boolean indicating whether result was
 * the product of a callback or errback. The list's completion criteria and
 * result list may be modified by setting one or more of the boolean options
 * documented below.
 *
 * Deferred instances passed into a DeferredList are
 * independent, and may have additional callbacks and errbacks added to their
 * execution sequences after they are passed as inputs to the list.
 *
 * @param {!Array.<!goog.async.Deferred>} list An array of deferred results to
 *     wait for.
 * @param {boolean=} opt_fireOnOneCallback Whether to stop waiting as soon as
 *     one input completes successfully. In this case, the
 *     DeferredList's callback chain will be called with a two
 *     element array, [index, result], where index
 *     identifies which input Deferred produced the successful
 *     result.
 * @param {boolean=} opt_fireOnOneErrback Whether to stop waiting as soon as one
 *     input reports an error. The failing result is passed to the
 *     DeferredList's errback sequence.
 * @param {boolean=} opt_consumeErrors When true, any errors fired by a
 *     Deferred in the input list will be captured and replaced
 *     with a succeeding null result. Any callbacks added to the
 *     Deferred after its use in the DeferredList will
 *     receive null instead of the error.
 * @param {Function=} opt_canceler A function that will be called if the
 *     DeferredList is canceled. @see goog.async.Deferred#cancel
 * @param {Object=} opt_defaultScope The default scope to invoke callbacks or
 *     errbacks in.
 * @constructor
 * @extends {goog.async.Deferred}
 */
goog.async.DeferredList = function(
    list, opt_fireOnOneCallback, opt_fireOnOneErrback, opt_consumeErrors,
    opt_canceler, opt_defaultScope) {

  goog.base(this, opt_canceler, opt_defaultScope);

  /**
   * The list of Deferred objects to wait for.
   * @const {!Array.<!goog.async.Deferred>}
   * @private
   */
  this.list_ = list;

  /**
   * The stored return values of the Deferred objects.
   * @const {!Array}
   * @private
   */
  this.deferredResults_ = [];

  /**
   * Whether to fire on the first successful callback instead of waiting for
   * every Deferred to complete.
   * @const {boolean}
   * @private
   */
  this.fireOnOneCallback_ = !!opt_fireOnOneCallback;

  /**
   * Whether to fire on the first error result received instead of waiting for
   * every Deferred to complete.
   * @const {boolean}
   * @private
   */
  this.fireOnOneErrback_ = !!opt_fireOnOneErrback;

  /**
   * Whether to stop error propagation on the input Deferred objects. If the
   * DeferredList sees an error from one of the Deferred inputs, the error will
   * be captured, and the Deferred will be returned to success state with a null
   * return value.
   * @const {boolean}
   * @private
   */
  this.consumeErrors_ = !!opt_consumeErrors;

  /**
   * The number of input deferred objects that have fired.
   * @private {number}
   */
  this.numFinished_ = 0;

  for (var i = 0; i < list.length; i++) {
    var d = list[i];
    d.addCallbacks(goog.bind(this.handleCallback_, this, i, true),
                   goog.bind(this.handleCallback_, this, i, false));
  }

  if (list.length == 0 && !this.fireOnOneCallback_) {
    this.callback(this.deferredResults_);
  }
};
goog.inherits(goog.async.DeferredList, goog.async.Deferred);

/**
 * Registers the result from an input deferred callback or errback. The result
 * is returned and may be passed to additional handlers in the callback chain.
 *
 * @param {number} index The index of the firing deferred object in the input
 *     list.
 * @param {boolean} success Whether the result is from a callback or errback.
 * @param {*} result The result of the callback or errback.
 * @return {*} The result, to be handled by the next handler in the deferred's
 *     callback chain (if any). If consumeErrors is set, an error result is
 *     replaced with null.
 * @private
 */
goog.async.DeferredList.prototype.handleCallback_ = function(
    index, success, result) {

  this.numFinished_++;
  this.deferredResults_[index] = [success, result];

  if (!this.hasFired()) {
    if (this.fireOnOneCallback_ && success) {
      this.callback([index, result]);
    } else if (this.fireOnOneErrback_ && !success) {
      this.errback(result);
    } else if (this.numFinished_ == this.list_.length) {
      this.callback(this.deferredResults_);
    }
  }

  if (this.consumeErrors_ && !success) {
    result = null;
  }

  return result;
};

/** @override */
goog.async.DeferredList.prototype.errback = function(res) {
  goog.base(this, 'errback', res);

  // On error, cancel any pending requests.
  for (var i = 0; i < this.list_.length; i++) {
    this.list_[i].cancel();
  }
};

/**
 * Creates a DeferredList that gathers results from multiple
 * Deferred inputs. If all inputs succeed, the callback is fired
 * with the list of results as a flat array. If any input fails, the list's
 * errback is fired immediately with the offending error, and all other pending
 * inputs are canceled.
 *
 * @param {!Array.<!goog.async.Deferred>} list The list of Deferred
 *     inputs to wait for.
 * @return {!goog.async.Deferred} The deferred list of results from the inputs
 *     if they all succeed, or the error result of the first input to fail.
 */
goog.async.DeferredList.gatherResults = function(list) {
  return new goog.async.DeferredList(list, false, true).
      addCallback(function(results) {
        var output = [];
        for (var i = 0; i < results.length; i++) {
          output[i] = results[i][1];
        }
        return output;
      });
};


text:
import arcpy
import os

currentPath = os.path.dirname(__file__)
geodatabasePath = os.path.normpath(os.path.join(currentPath, r"../../../data_management/data/geodatabases/"))
csvPath = os.path.normpath(os.path.join(currentPath, r"../../../data_management/data/geodatabases/csv/"))

scratchPath = geodatabasePath
toolboxesPath = os.path.normpath(os.path.join(currentPath, r"../../toolboxes/"))

inputGDB  = os.path.join(geodatabasePath, "test_position_analysis_inputs.gdb")
#outputGDB = os.path.join(geodatabasePath, "test_outputs.gdb")
#defaultGDB = os.path.join(geodatabasePath, "default.gdb")
scratchGDB = os.path.join(scratchPath, "scratch.gdb")
outputGDB = scratchGDB
defaultGDB = scratchGDB
toolbox = os.path.join(toolboxesPath, "Import and Conversion Tools_10.3.tbx")

def createScratch() :
    try :
        print("creating 'scratch' in " + str(scratchPath))
        arcpy.CreateFileGDB_management(scratchPath, "scratch")
    except:
        print("scratch.gdb already exists")
    return

def deleteScratch() :
    try :
        arcpy.Delete_management(scratchGDB)
    except:
        print("scratch.gdb delete failed")
    return


text:
"""
Example Airflow DAG that starts, stops and sets the machine type of a Google Compute
Engine instance.

This DAG relies on the following OS environment variables

* GCP_PROJECT_ID - Google Cloud Platform project where the Compute Engine instance exists.
* GCE_ZONE - Google Cloud Platform zone where the instance exists.
* GCE_INSTANCE - Name of the Compute Engine instance.
* GCE_SHORT_MACHINE_TYPE_NAME - Machine type resource name to set, e.g. 'n1-standard-1'.
    See https://cloud.google.com/compute/docs/machine-types
"""

import os

from airflow import models
from airflow.providers.google.cloud.operators.compute import (
    ComputeEngineSetMachineTypeOperator, ComputeEngineStartInstanceOperator,
    ComputeEngineStopInstanceOperator,
)
from airflow.utils.dates import days_ago

# [START howto_operator_gce_args_common]
GCP_PROJECT_ID = os.environ.get('GCP_PROJECT_ID', 'example-project')
GCE_ZONE = os.environ.get('GCE_ZONE', 'europe-west1-b')
GCE_INSTANCE = os.environ.get('GCE_INSTANCE', 'testinstance')
# [END howto_operator_gce_args_common]

default_args = {
    'start_date': days_ago(1),
}

# [START howto_operator_gce_args_set_machine_type]
GCE_SHORT_MACHINE_TYPE_NAME = os.environ.get('GCE_SHORT_MACHINE_TYPE_NAME', 'n1-standard-1')
SET_MACHINE_TYPE_BODY = {
    'machineType': 'zones/{}/machineTypes/{}'.format(GCE_ZONE, GCE_SHORT_MACHINE_TYPE_NAME)
}
# [END howto_operator_gce_args_set_machine_type]

with models.DAG(
    'example_gcp_compute',
    default_args=default_args,
    schedule_interval=None,  # Override to match your needs
    tags=['example'],
) as dag:
    # [START howto_operator_gce_start]
    gce_instance_start = ComputeEngineStartInstanceOperator(
        project_id=GCP_PROJECT_ID,
        zone=GCE_ZONE,
        resource_id=GCE_INSTANCE,
        task_id='gcp_compute_start_task'
    )
    # [END howto_operator_gce_start]
    # Duplicate start for idempotence testing
    # [START howto_operator_gce_start_no_project_id]
    gce_instance_start2 = ComputeEngineStartInstanceOperator(
        zone=GCE_ZONE,
        resource_id=GCE_INSTANCE,
        task_id='gcp_compute_start_task2'
    )
    # [END howto_operator_gce_start_no_project_id]
    # [START howto_operator_gce_stop]
    gce_instance_stop = ComputeEngineStopInstanceOperator(
        project_id=GCP_PROJECT_ID,
        zone=GCE_ZONE,
        resource_id=GCE_INSTANCE,
        task_id='gcp_compute_stop_task'
    )
    # [END howto_operator_gce_stop]
    # Duplicate stop for idempotence testing
    # [START howto_operator_gce_stop_no_project_id]
    gce_instance_stop2 = ComputeEngineStopInstanceOperator(
        zone=GCE_ZONE,
        resource_id=GCE_INSTANCE,
        task_id='gcp_compute_stop_task2'
    )
    # [END howto_operator_gce_stop_no_project_id]
    # [START howto_operator_gce_set_machine_type]
    gce_set_machine_type = ComputeEngineSetMachineTypeOperator(
        project_id=GCP_PROJECT_ID,
        zone=GCE_ZONE,
        resource_id=GCE_INSTANCE,
        body=SET_MACHINE_TYPE_BODY,
        task_id='gcp_compute_set_machine_type'
    )
    # [END howto_operator_gce_set_machine_type]
    # Duplicate set machine type for idempotence testing
    # [START howto_operator_gce_set_machine_type_no_project_id]
    gce_set_machine_type2 = ComputeEngineSetMachineTypeOperator(
        zone=GCE_ZONE,
        resource_id=GCE_INSTANCE,
        body=SET_MACHINE_TYPE_BODY,
        task_id='gcp_compute_set_machine_type2'
    )
    # [END howto_operator_gce_set_machine_type_no_project_id]

    gce_instance_start >> gce_instance_start2 >> gce_instance_stop >> \
        gce_instance_stop2 >> gce_set_machine_type >> gce_set_machine_type2


text:
namespace Minesweeper
{
    public class Score
    {
        public Score(string name, int points)
        {
            this.PlayerName = name;
            this.PlayerPoints = points;
        }

        public string PlayerName { get; set; }
        public int PlayerPoints { get; set; }
    }
}


text:
using System;
using Hellang.Middleware.ProblemDetails;
using Xunit;
using ReasonPhrases = Microsoft.AspNetCore.WebUtilities.ReasonPhrases;

namespace ProblemDetails.Tests
{
    public class ProblemDetailsExceptionTests
    {
        [Fact]
        public void Constructor_InitializesMessage()
        {
            var problemDetails = CreateProblemDetails();

            var exception = new ProblemDetailsException(problemDetails);

            Assert.Equal("https://httpstatuses.io/303 : See other", exception.Message);
        }

        [Fact]
        public void ToString_ReturnsAllDetails()
        {
            var problemDetails = CreateProblemDetails();

            var exception = new ProblemDetailsException(problemDetails);
            var actual = exception.ToString();

            var expected = @"Type    : https://httpstatuses.io/303
Title   : See other
Status  : 303
Detail  : Look somewhere else.
Instance: https://example.com/problem/123
";

            Assert.Equal(expected, actual, ignoreLineEndingDifferences: true);
        }

        [Fact]
        public void Constructor_FromHttpStatusCode()
        {
            var exception = new ProblemDetailsException(400);

            Assert.IsType<Microsoft.AspNetCore.Mvc.ProblemDetails>(exception.Details);

            Assert.Equal(400, exception.Details.Status);
            Assert.Equal(ReasonPhrases.GetReasonPhrase(400), exception.Details.Title);
        }

        [Fact]
        public void Constructor_FromHttpStatusCodeAndTitle()
        {
            var exception = new ProblemDetailsException(400, "foobar");

            Assert.IsType<Microsoft.AspNetCore.Mvc.ProblemDetails>(exception.Details);

            Assert.Equal(400, exception.Details.Status);
            Assert.Equal("foobar", exception.Details.Title);
        }

        [Fact]
        public void Constructor_FromHttpStatusCodeAndInnerException()
        {
            var exception = new ProblemDetailsException(400, new DivideByZeroException());

            Assert.IsType<Microsoft.AspNetCore.Mvc.ProblemDetails>(exception.Details);
            Assert.IsType<DivideByZeroException>(exception.InnerException);
            Assert.Equal(400, exception.Details.Status);
            Assert.Equal(ReasonPhrases.GetReasonPhrase(400), exception.Details.Title);
        }

        [Fact]
        public void Constructor_FromHttpStatusCodeTitleAndInnerException()
        {
            var exception = new ProblemDetailsException(400, "foobar", new DivideByZeroException());

            Assert.IsType<Microsoft.AspNetCore.Mvc.ProblemDetails>(exception.Details);
            Assert.IsType<DivideByZeroException>(exception.InnerException);
            Assert.Equal(400, exception.Details.Status);
            Assert.Equal("foobar", exception.Details.Title);
        }

        private static Microsoft.AspNetCore.Mvc.ProblemDetails CreateProblemDetails()
        {
            return new Microsoft.AspNetCore.Mvc.ProblemDetails
            {
                Type = "https://httpstatuses.io/303",
                Title = "See other",
                Status = 303,
                Detail = "Look somewhere else.",
                Instance = "https://example.com/problem/123",
            };
        }
    }
}


text:
#ifndef _LINUX_PATCHKEY_H_INDIRECT
#error "patchkey.h included directly"
#endif
#ifndef _UAPI_LINUX_PATCHKEY_H
#define _UAPI_LINUX_PATCHKEY_H
#include <endian.h>
#ifdef __BYTE_ORDER
#if __BYTE_ORDER == __BIG_ENDIAN
#define _PATCHKEY(id) (0xfd00 | id)
#elif __BYTE_ORDER==__LITTLE_ENDIAN
#define _PATCHKEY(id) ((id << 8) | 0x00fd)
#else
#error "could not determine byte order"
#endif
#endif
#endif


text:
function runView(){

    function createTable(){
        var tableHtml = `

             Date
             Player
             Character
             Player
             Character

`;
        $('#output').html(tableHtml);
        $('.table-video').each(function (){
            $(this).DataTable({
                "fixedHeader": true,
                "paging": true,
                "pagingType": "simple",
                "pageLength": 100,
                "lengthChange": false,
                "ordering": true,
                "info": false,
                "bFilter": false,
                "columnDefs": [
                    // { "orderable": false, "targets": 0 }
                ],
                "order": [[0, 'desc']],
            });
        });
    }

    function checkValue(elemId, value){
        if (!value){
            return false;
        }
        var selector = TOOL.format("#{1} option[value='{2}']", elemId, value);
        return $(selector).length > 0;
    }

    function setUrlParams(gameId, player, char1, char2){
        var params = "?game=" + gameId;
        if (player){
            params += "&player=" + player;
        }
        if (char1){
            params += "&char=" + char1;
        }
        if (char2){
            params += "&char=" + char2;
        }
        window.history.pushState({}, "", params);
    }

    function readUrlParams(){
        var game = TOOL.readUrlParam("game");
        if (checkValue('game', game)){
            $('#game').val(game).prop('selected', true);
            var player = TOOL.readUrlParam("player");
            var chars = TOOL.readUrlParam("char", true);

            updateDropdowns(game);

            if (checkValue('player', player)){
                $('#player').val(player).prop('selected', true);
            }
            if (chars){
                var charId = 1;
                chars.forEach(function (char){
                    if (checkValue('char1', char)){
                        $('#char' + charId).val(char).prop('selected', true);
                        charId += 1;
                    }
                });
            }
        }
        printResults();
    }

    function updateDropdowns(){
        VideoManager.currentGameId = $('#game').val();
        var base_select = '<option value="">-</option>';
        var html_char1 = base_select;
        var html_char2 = base_select;
        var html_player = base_select;
        VideoManager.getCharacters().forEach(function (char){
            html_char1 += TOOL.option(char);
            html_char2 += TOOL.option(char);
        });
        VideoManager.getPlayers().forEach(function (player){
            html_player += TOOL.option(player);
        });
        $('#char1').html(html_char1);
        $('#char2').html(html_char2);
        $('#player').html(html_player);
    }

    function printResults(){
        if (VideoManager.currentGameId != $('#game').val()){
            updateDropdowns();
        }

        var player = $('#player').val();
        var char1 = $('#char1').val();
        var char2 = $('#char2').val();
        setUrlParams(VideoManager.currentGameId, player, char1, char2);

        var videos = VideoManager.getVideos(player, char1, char2);
        var out = $('#videos').DataTable()
        out.clear();
        var videoData = [];
        videos.forEach(function (video){
            videoData.push(video.toData());
        });
        out.rows.add(videoData);
        out.draw();
    }

    function onLoad(parsedVideos){
        $('#loading').hide();
        createTable();
        VideoManager.organize(parsedVideos);

        // setup game dropdown
        var html_game = "";
        VideoManager.getGames().forEach(function (gameItem){
            html_game += TOOL.option(gameItem);
        });
        $('#game').html(html_game);
        $('#game').val('SF5').prop('selected', true);

        // setup triggers
        $('.filter').change(function (){
            printResults();
        });
        $('.reset').click(function (){
            var select_id = $(this).data('id');
            $('#' + select_id).val('').prop('selected', true);
            $('#' + select_id).trigger('change');
        });
        $(window).bind("popstate", readUrlParams);  //Back button
        $(window).bind("pushstate", readUrlParams); //Forward button, OR window.history.pushState()

        $('.table-video').on('click', '.link-player', function (){
            var playerValue = $(this).data("value");
            $('#player').val(playerValue).prop('selected', true);
            $('#char1').val('').prop('selected', true);
            $('#char2').val('').prop('selected', true);
            $('#player').trigger('change');
        });
        $('.table-video').on('click', '.link-character', function (){
            var characterValue = $(this).data("value");
            if ($('#char1').val()){
                $('#char2').val(characterValue).prop('selected', true);
                $('#char2').trigger('change');
            } else {
                $('#char1').val(characterValue).prop('selected', true);
                $('#char1').trigger('change');
            }
        });

        // start
        readUrlParams();
    }

    function setup(){
        if (TOOL.is_local){
            $(".container").append('

');
        }
        $('#enableJs').hide();
        Store.load(onLoad);
    }

    setup();
}


text:
/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package practice;

/**
 *
 * @author mars
 */
public class Bicycle {

    //The Bicycle class has three fields
    private int cadence;
    private int gear;
    private int speed;

    //the bicycle class has one constructor
    public Bicycle(int startCadence, int startSpeed, int startGear) {
        gear = startGear;
        cadence = startCadence;
        speed = startSpeed;
    }

    //the Bicycle class has four methods
    public void setCadence(int newValue) {
        cadence = newValue;
    }

    public void setGear(int newValue) {
        gear = newValue;
    }

    public void applyBrake(int decrement) {
        speed -= decrement;
    }

    public void speedUp(int increment) {
        speed += increment;
    }
}


text:
<?php

/**
 * @file
 * Contains \Drupal\Tests\Core\Config\Entity\ThirdPartySettingsTraitTest.
 */

namespace Drupal\Tests\Core\Config\Entity;

use Drupal\Core\Config\Entity\ThirdPartySettingsTrait;
use Drupal\Tests\UnitTestCase;

/**
 * @coversDefaultClass \Drupal\Core\Config\Entity\ThirdPartySettingsTrait
 * @group Config
 */
class ThirdPartySettingsTraitTest extends UnitTestCase {

  /**
   * @covers ::getThirdPartySetting
   * @covers ::setThirdPartySetting
   * @covers ::getThirdPartySettings
   * @covers ::unsetThirdPartySetting
   * @covers ::getThirdPartyProviders
   */
  public function testThirdPartySettings() {
    $key = 'test';
    $third_party = 'test_provider';
    $value = $this->getRandomGenerator()->string();

    $trait_object = new TestThirdPartySettingsTrait();

    // Test getThirdPartySetting() with no settings.
    $this->assertEquals($value, $trait_object->getThirdPartySetting($third_party, $key, $value));
    $this->assertNull($trait_object->getThirdPartySetting($third_party, $key));

    // Test setThirdPartySetting().
    $trait_object->setThirdPartySetting($third_party, $key, $value);
    $this->assertEquals($value, $trait_object->getThirdPartySetting($third_party, $key));
    $this->assertEquals($value, $trait_object->getThirdPartySetting($third_party, $key, $this->randomGenerator->string()));

    // Test getThirdPartySettings().
    $trait_object->setThirdPartySetting($third_party, 'test2', 'value2');
    $this->assertEquals(array($key => $value, 'test2' => 'value2'), $trait_object->getThirdPartySettings($third_party));

    // Test getThirdPartyProviders().
    $trait_object->setThirdPartySetting('test_provider2', $key, $value);
    $this->assertEquals(array($third_party, 'test_provider2'), $trait_object->getThirdPartyProviders());

    // Test unsetThirdPartyProviders().
    $trait_object->unsetThirdPartySetting('test_provider2', $key);
    $this->assertEquals(array($third_party), $trait_object->getThirdPartyProviders());
  }
}

class TestThirdPartySettingsTrait {

  use ThirdPartySettingsTrait;

}


text:
/**********************************************************************

    Generic modern device trampolines and other helpers, to minimize
    the amount of redundant copy/pasting between modernized devices.

**********************************************************************/

#ifndef __DEVHELPR_H__
#define __DEVHELPR_H__

#define READ32_DEVICE_HANDLER_TRAMPOLINE(devname, funcname) \
	READ32_DEVICE_HANDLER( funcname ) \
	{ return downcast<devname##_device*>(device)->funcname(offset); } \
	UINT32 devname##_device::funcname(UINT32 offset)

#define WRITE32_DEVICE_HANDLER_TRAMPOLINE(devname, funcname) \
	WRITE32_DEVICE_HANDLER( funcname ) \
	{ downcast<devname##_device*>(device)->funcname(offset, data, mem_mask); } \
	void devname##_device::funcname(UINT32 offset, UINT32 data, UINT32 mem_mask)

#define READ8_DEVICE_HANDLER_TRAMPOLINE(devname, funcname) \
	READ8_DEVICE_HANDLER( funcname ) \
	{ return downcast<devname##_device*>(device)->funcname(offset); } \
	UINT8 devname##_device::funcname(UINT32 offset)

#define WRITE8_DEVICE_HANDLER_TRAMPOLINE(devname, funcname) \
	WRITE8_DEVICE_HANDLER( funcname ) \
	{ downcast<devname##_device*>(device)->funcname(offset, data); } \
	void devname##_device::funcname(UINT32 offset, UINT8 data)

#define READ_LINE_DEVICE_HANDLER_TRAMPOLINE(devname, funcname) \
	READ_LINE_DEVICE_HANDLER( funcname ) \
	{ return downcast<devname##_device *>(device)->funcname(); } \
	void devname##_device::funcname()

#define WRITE_LINE_DEVICE_HANDLER_TRAMPOLINE(devname, funcname) \
	WRITE_LINE_DEVICE_HANDLER( funcname ) \
	{ return downcast<devname##_device *>(device)->funcname(state); } \
	void devname##_device::funcname(UINT8 state)

#endif // __DEVHELPR_H__


text:
@implementation XCFUploadDataTool

//- (CGFloat)tagsViewHeight {
//
//    CGFloat totalWidth = 0;
//    NSUInteger currentLine = 0;
//    for (NSString *tagString in self.tagsArray) {
//        CGFloat textWidth = [tagString getSizeWithTextSize:CGSizeMake(MAXFLOAT, 30) fontSize:14].width;
//        CGFloat displayWidth = textWidth + 55;
//
//        totalWidth += displayWidth+5;
//        if (totalWidth > XCFScreenWidth) {
//            totalWidth = 0;
//            currentLine++;
//        }
//    }
//
//    CGFloat currentX = 15;
//    CGFloat currentY = 8;
//    NSMutableArray *frameArray = [NSMutableArray array];
//    for (NSInteger index=0; index<self.tagsArray.count; index++) {
//        NSString *tagString = self.tagsArray[index];
//        CGFloat textWidth = [tagString getSizeWithTextSize:CGSizeMake(MAXFLOAT, 30) fontSize:14].width;
//        CGFloat displayWidth = textWidth + 55;
//
//        if ((currentX+displayWidth-15) > XCFScreenWidth) { // 如果当前x+标签宽度大于屏幕高度,就转行
//            currentX = 15;
//            currentY += 35;
//            if (displayWidth >= XCFScreenWidth) displayWidth = XCFScreenWidth - 55; // 如果单个标签宽度大于屏幕宽度
//        } else {
//            if (index > 0) currentX += displayWidth+5; // 如果不大于,就叠加
//        }
//        NSDictionary *frameDict = @{@"x"     : @(currentX),
//                                    @"y"     : @(currentY),
//                                    @"width" : @(displayWidth)};
//        [frameArray addObject:frameDict];
//    }
//
//}

@end


text:
<?php

if (!defined('PHPUnit_MAIN_METHOD')) {
    define('PHPUnit_MAIN_METHOD', 'Zend_Log_Formatter_SimpleTest::main');
}

/** Zend_Log_Formatter_Simple */
require_once 'Zend/Log/Formatter/Simple.php';

/**
 * @category   Zend
 * @package    Zend_Log
 * @subpackage UnitTests
 * @copyright  Copyright (c) 2005-2012 Zend Technologies USA Inc. (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 * @group      Zend_Log
 */
class Zend_Log_Formatter_SimpleTest extends PHPUnit_Framework_TestCase
{
    public static function main()
    {
        $suite  = new PHPUnit_Framework_TestSuite(__CLASS__);
        $result = PHPUnit_TextUI_TestRunner::run($suite);
    }

    public function testConstructorThrowsOnBadFormatString()
    {
        try {
            new Zend_Log_Formatter_Simple(1);
            $this->fail();
        } catch (Exception $e) {
            $this->assertType('Zend_Log_Exception', $e);
            $this->assertRegExp('/must be a string/i', $e->getMessage());
        }
    }

    public function testDefaultFormat()
    {
        $fields = array('timestamp'    => 0,
                        'message'      => 'foo',
                        'priority'     => 42,
                        'priorityName' => 'bar');

        $f = new Zend_Log_Formatter_Simple();
        $line = $f->format($fields);

        $this->assertContains((string)$fields['timestamp'], $line);
        $this->assertContains($fields['message'], $line);
        $this->assertContains($fields['priorityName'], $line);
        $this->assertContains((string)$fields['priority'], $line);
    }

    function testComplexValues()
    {
        $fields = array('timestamp'    => 0,
                        'priority'     => 42,
                        'priorityName' => 'bar');

        $f = new Zend_Log_Formatter_Simple();

        $fields['message'] = 'Foo';
        $line = $f->format($fields);
        $this->assertContains($fields['message'], $line);

        $fields['message'] = 10;
        $line = $f->format($fields);
        $this->assertContains($fields['message'], $line);

        $fields['message'] = 10.5;
        $line = $f->format($fields);
        $this->assertContains($fields['message'], $line);

        $fields['message'] = true;
        $line = $f->format($fields);
        $this->assertContains('1', $line);

        $fields['message'] = fopen('php://stdout', 'w');
        $line = $f->format($fields);
        $this->assertContains('Resource id ', $line);
        fclose($fields['message']);

        $fields['message'] = range(1,10);
        $line = $f->format($fields);
        $this->assertContains('array', $line);

        $fields['message'] = new Zend_Log_Formatter_SimpleTest_TestObject1();
        $line = $f->format($fields);
        $this->assertContains($fields['message']->__toString(), $line);

        $fields['message'] = new Zend_Log_Formatter_SimpleTest_TestObject2();
        $line = $f->format($fields);
        $this->assertContains('object', $line);
    }

    /**
     * @group ZF-9176
     */
    public function testFactory()
    {
        $options = array(
            'format' => '%timestamp% [%priority%]: %message% -- %info%'
        );
        $formatter = Zend_Log_Formatter_Simple::factory($options);
        $this->assertType('Zend_Log_Formatter_Simple', $formatter);
    }
}

class Zend_Log_Formatter_SimpleTest_TestObject1 {

    public function __toString()
    {
        return 'Hello World';
    }
}

class Zend_Log_Formatter_SimpleTest_TestObject2 {
}

if (PHPUnit_MAIN_METHOD == 'Zend_Log_Formatter_SimpleTest::main') {
    Zend_Log_Formatter_SimpleTest::main();
}


text:
<?php

abstract class PhabricatorPolicyCapability extends Phobject {

  const CAN_VIEW        = 'view';
  const CAN_EDIT        = 'edit';
  const CAN_JOIN        = 'join';

  /**
   * Get the unique key identifying this capability. This key must be globally
   * unique. Application capabilities should be namespaced. For example:
   *
   *   application.create
   *
   * @return string Globally unique capability key.
   */
  final public function getCapabilityKey() {
    $class = new ReflectionClass($this);

    $const = $class->getConstant('CAPABILITY');
    if ($const === false) {
      throw new Exception(
        pht(
          '%s class "%s" must define a %s property.',
          __CLASS__,
          get_class($this),
          'CAPABILITY'));
    }

    if (!is_string($const)) {
      throw new Exception(
        pht(
          '%s class "%s" has an invalid %s property. '.
          'Capability constants must be a string.',
          __CLASS__,
          get_class($this),
          'CAPABILITY'));
    }

    return $const;
  }

  /**
   * Return a human-readable descriptive name for this capability, like
   * "Can View".
   *
   * @return string Human-readable name describing the capability.
   */
  abstract public function getCapabilityName();

  /**
   * Return a human-readable string describing what not having this capability
   * prevents the user from doing. For example:
   *
   *   - You do not have permission to edit this object.
   *   - You do not have permission to create new tasks.
   *
   * @return string Human-readable name describing what failing a check for this
   *   capability prevents the user from doing.
   */
  public function describeCapabilityRejection() {
    return null;
  }

  /**
   * Can this capability be set to "public"? Broadly, this is only appropriate
   * for view and view-related policies.
   *
   * @return bool True to allow the "public" policy. Returns false by default.
   */
  public function shouldAllowPublicPolicySetting() {
    return false;
  }

  final public static function getCapabilityByKey($key) {
    return idx(self::getCapabilityMap(), $key);
  }

  final public static function getCapabilityMap() {
    return id(new PhutilClassMapQuery())
      ->setAncestorClass(__CLASS__)
      ->setUniqueMethod('getCapabilityKey')
      ->execute();
  }

}


text:
package com.github.czyzby.autumn.mvc.component.ui.dto.provider;

import com.badlogic.gdx.utils.ObjectSet;
import com.github.czyzby.kiwi.util.gdx.collection.GdxSets;
import com.github.czyzby.lml.parser.LmlParser;

/** Base implementation for {@link ViewActionProvider} that
 * manages handled view types.
 *
 * @author MJ */
public abstract class AbstractViewActionProvider implements ViewActionProvider {
    private final ObjectSet<String> viewIds;

    public AbstractViewActionProvider(final String[] viewIds) {
        this.viewIds = GdxSets.newSet(viewIds);
    }

    @Override
    public void register(final LmlParser parser, final String viewId) {
        if (viewIds.contains(viewId)) {
            register(parser);
        }
    }

    /** The view ID is valid.
     *
     * @param parser should have the action registered. */
    protected abstract void register(LmlParser parser);

    @Override
    public void unregister(final LmlParser parser, final String viewId) {
        if (viewIds.contains(viewId)) {
            unregister(parser);
        }
    }

    /** The view ID is valid.
     *
     * @param parser should have the action removed. */
    protected abstract void unregister(LmlParser parser);
}


text:
package sc.ala.http.mock

import play.core.server.NettyServer

case class HttpMockUp(setting: Setting, netty: NettyServer) extends HttpMock {
  def port: Int = netty.httpPort.get  // port must exist cause we set it and server is running

  def start(): HttpMock = this
  def stop() : HttpMock = { netty.stop(); HttpMockDown(setting, port) }
  def run[A](action: HttpMockUp => A): Unit = try { action(this) } finally { stop() }
}


text:
package li.strolch.command;

import java.text.MessageFormat;
import java.util.List;

import li.strolch.agent.api.OrderMap;
import li.strolch.exception.StrolchException;
import li.strolch.model.Order;
import li.strolch.persistence.api.StrolchTransaction;
import li.strolch.service.api.Command;
import li.strolch.utils.dbc.DBC;

/**
 * @author Robert von Burg <eitch@eitchnet.ch>
 */
public class AddOrderCollectionCommand extends Command {

	private List<Order> orders;
	private boolean added;

	public AddOrderCollectionCommand(StrolchTransaction tx) {
		super(tx);
	}

	/**
	 * @param orders
	 * 		the orders to set
	 */
	public void setOrders(List<Order> orders) {
		this.orders = orders;
	}

	@Override
	public void validate() {
		DBC.PRE.assertNotNull("Order list may not be null!", this.orders);
	}

	@Override
	public void doCommand() {

		for (Order order : this.orders) {
			tx().lock(order);
		}

		OrderMap orderMap = tx().getOrderMap();
		for (Order order : this.orders) {
			if (orderMap.hasElement(tx(), order.getType(), order.getId())) {
				String msg = MessageFormat.format("The Order {0} already exists!", order.getLocator());
				throw new StrolchException(msg);
			}
		}

		orderMap.addAll(tx(), this.orders);
		this.added = true;
	}

	@Override
	public void undo() {
		if (this.added && this.orders != null && !this.orders.isEmpty() && tx().isRollingBack()) {
			OrderMap orderMap = tx().getOrderMap();
			for (Order order : this.orders) {
				if (orderMap.hasElement(tx(), order.getType(), order.getId())) {
					orderMap.remove(tx(), order);
				}
			}
		}
	}
}


text:
<?php
namespace Reports\Model;

// Simple class for holding plan data to make passing to view easier
class PlanData
{
    public $id; // Plan id
    public $metaFlag; // Has meta?
    public $hasReport; // Has a report?
    public $descriptions; // Text of either outcome or meta assessment

    public function __construct($id, $meta, $hasReport)
    {
        $this->id = $id;
        $this->metaFlag = $meta;
        $this->hasReport = $hasReport;
        $this->descriptions = array();
    }
}


text:
<!DOCTYPE compass-core-configuration PUBLIC
    "-//Compass/Compass Core Configuration DTD 1.0//EN"
    "http://www.opensymphony.com/compass/dtd/compass-core-configuration.dtd">

<compass-core-configuration>

    <compass>

        <setting name="compass.engine.connection">target/test-index</setting>
        <setting name="compass.engine.optimizer">org.compass.core.lucene.engine.optimizer.type.NullOptimizer</setting>
        <setting name="compass.engine.optimizer.schedule">false</setting>

        <mapping resource="org/compass/gps/device/jdo/jdo.cpm.xml" />

    </compass>

</compass-core-configuration>


text:
from trigger.models import Trigger, Event
from trigger.serializers import TriggerSerializer, EventSerializer
from trigger.tasks import send_email, send_sms
from rest_framework import generics
from rest_framework.response import Response
from django.conf import settings

import datetime

class TriggerListView(generics.CreateAPIView):
    queryset = Trigger.objects.all()
    serializer_class = TriggerSerializer

    def post(self, request, *args, **kwargs):
        step_user = request.data.get('step_user', None)
        if step_user is None:
            return Response(data={'detail': 'step_user is need for get trigger list.'}, status=400)

        queryset = Trigger.objects.filter(step_user=step_user)
        serializer = self.get_serializer(queryset, many=True)

        return Response(serializer.data)

class TriggerCreateView(generics.CreateAPIView):
    queryset = Trigger.objects.all()
    serializer_class = TriggerSerializer

class TriggerRetrieveUpdateDestroyView(generics.RetrieveUpdateDestroyAPIView):
    queryset = Trigger.objects.all()
    serializer_class = TriggerSerializer

    def put(self, request, *args, **kwargs):
        trigger = self.get_object()
        request_status = request.data.get('status')
        if trigger.status != request_status:
            if request_status is True:
                try:
                    Event.objects.get(trigger=trigger, status=True)
                except Event.DoesNotExist:
                    event = Event(trigger=trigger, status=True)
                    event.save()
                    send_sms.delay(event)
                    send_email.delay(event)
            else:
                try:
                    event = Event.objects.get(trigger=trigger, status=True)
                    event.end_time = datetime.datetime.now()
                    event.status = False
                    event.save()
                except Event.DoesNotExist:
                    pass

        return super(TriggerRetrieveUpdateDestroyView, self).put(request, args, kwargs)

class EventListView(generics.CreateAPIView):
    queryset = []
    serializer_class = EventSerializer

    def post(self, request, *args, **kwargs):
        events = []
        uuids = request.data.get('uuids', None)
        for uuid in uuids:
            triggers = Trigger.objects.filter(instance_uuid=uuid)
            for trigger in triggers:
                events.extend(trigger.get_events())

        return Response(events)


text:
require "discogs2/resources/artist"

module Discogs2
  module Resources
    class ExtraArtist < Artist
      attr_reader :join,
                  :anv,
                  :tracks,
                  :role
    end
  end
end