text:
var keystone = require('../'),
	demand = require('must'),
	path = require('path'),
	getExpressApp = require('./helpers/getExpressApp');

describe('Keystone "module root" setting', function () {

	before(function() {
		getExpressApp();
	});

	describe('default', function() {

		it('should be set to the path where keystone was required', function() {
			demand(keystone.get('module root')).to.be(__dirname);
		});

		it('should be used by keystone.getPath()', function() {
			var viewsPath = 'relative/path/to/views'
			keystone.set('views', viewsPath);
			demand(keystone.getPath('views')).to.be(path.resolve(__dirname, viewsPath));
		});

	});

	describe('custom with relative path', function() {
		var customPath = '../..';

		before(function() {
			keystone.set('module root', customPath);
		});

		it('should return the custom configured path', function() {
			demand(keystone.get('module root')).to.be(path.resolve(__dirname, customPath));
		});

		it('should be used by keystone.getPath() to resolve relative paths', function() {
			var viewsPath = 'relative/path/to/views'
			keystone.set('views', viewsPath);
			demand(keystone.getPath('views')).to.be(path.resolve(__dirname, customPath, viewsPath));
		});
	});

	describe('custom with absolute path', function() {
		var customPath = path.resolve(__dirname, '../..');

		before(function() {
			keystone.set('module root', customPath);
		});

		it('should return the custom configured path', function() {
			demand(keystone.get('module root')).to.be(customPath);
		});

		it('should be used by keystone.getPath() to resolve relative paths', function() {
			var viewsPath = 'relative/path/to/views'
			keystone.set('views', viewsPath);
			demand(keystone.getPath('views')).to.be(path.resolve(customPath, viewsPath));
		});
	});
});


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>com.fasterxml.jackson.dataformat.xml.jaxb (Jackson-dataformat-XML 2.11.0 API)</title>
<meta name="date" content="2020-04-25">
<link rel="stylesheet" type="text/css" href="../../../../../../stylesheet.css" title="Style">

com.fasterxml.jackson.dataformat.xml.jaxb

Classes

XmlJaxbAnnotationIntrospector

redpajama_set_name: RedPajamaGithub


text:
<?xml version="1.0" encoding="utf-8"?>
<bitmap xmlns:android="http://schemas.android.com/apk/res/android"
    android:src="@drawable/ic_share_black"
    android:tileMode="disabled" android:gravity="left" >
</bitmap>


text:
@implementation SampleNativeContentAd

- (void)handleClickOnView:(UIView *)view {
  NSLog(@"A click occurred on a SampleNativeContentAd!");
  // In a real SDK, some type of click action (such as the opening of a destination URL in an
  // external browser) would likely be initiated here.
}

- (void)recordImpression {
  NSLog(@"An impression was recorded for a SampleNativeContentAd!");
  // In a real SDK, some work would be done here to record the impression.
}

@end


text:
package com.bornneet.generativepolygon;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.PointF;
import android.util.AttributeSet;
import android.view.View;

import java.util.ArrayList;
import java.util.List;
import java.util.Random;

import static java.util.Collections.*;

/**
 * Created by tnantoka on 7/17/16.
 */
public class PolygonView extends View {

    int circuits = 3;
    int number;
    Bitmap bitmap;

    private Paint paint = new Paint();

    public PolygonView(Context context, AttributeSet attrs) {
        super(context, attrs);
    }

    @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);

        paint.setStrokeWidth(3);
        paint.setAntiAlias(true);

        bitmap = Bitmap.createBitmap(getWidth(), getHeight(), Bitmap.Config.ARGB_8888);
        Canvas bitmapCanvas = new Canvas(bitmap);

//        bitmapCanvas.drawColor(Color.WHITE);

        number = getNumber();
        for (int i = 0; i < getPolygons(); i++) {
            drawPolygon(bitmapCanvas);
        }

        canvas.drawBitmap(bitmap, 0, 0, null);
    }

    private void drawPolygon(Canvas canvas) {
        float radius = getRadius();

        PointF firstPoint = getPoint(0, radius);
        PointF lastPoint = firstPoint;

        int step = 360 / number;

        for (int i = 1; i <= 360; i += step) {
            paint.setColor(getColor());
            paint.setAlpha(200);

            float degree = i;
            PointF point = getPoint(degree, radius);
            canvas.drawLine(lastPoint.x, lastPoint.y, point.x, point.y, paint);

            lastPoint = point;
            radius = getRadius();
        }

        canvas.drawLine(lastPoint.x, lastPoint.y, firstPoint.x, firstPoint.y, paint);
    }

    private PointF getPoint(float degree, float radius) {
        float centerX = getWidth() / 2;
        float centerY = getHeight() / 2;

        double radian = degree * Math.PI / 180;
        float x = (float)Math.cos(radian) * radius + centerX;
        float y = (float)Math.sin(radian) * radius + centerY;

        return new PointF(x, y);
    }

    private float getRadius() {
        float maxRadius = (getWidth() - getResources().getDimension(R.dimen.activity_horizontal_margin)) / 2;
        float step = maxRadius / circuits;

        List<Float> radiuses = new ArrayList<Float>();

        for (float i = step; i <= maxRadius; i += step) {
            radiuses.add(i);
        }

        shuffle(radiuses);

        return radiuses.get(0);
    }

    private int getColor() {
        int[] colors = {
                Color.parseColor("#f44336"),
                Color.parseColor("#e91e63"),
                Color.parseColor("#9c27b0"),
                Color.parseColor("#673ab7"),
                Color.parseColor("#3f51b5"),
                Color.parseColor("#2196f3"),
                Color.parseColor("#03a9f4"),
                Color.parseColor("#00bcd4"),
                Color.parseColor("#009688"),
                Color.parseColor("#4caf50"),
                Color.parseColor("#8bc34a"),
                Color.parseColor("#cddc39"),
                Color.parseColor("#ffeb3b"),
                Color.parseColor("#ffc107"),
                Color.parseColor("#ff9800"),
                Color.parseColor("#ff5722"),
                Color.parseColor("#795548"),
                Color.parseColor("#9e9e9e"),
                Color.parseColor("#607d8b"),
        };
        return colors[new Random().nextInt(colors.length)];
    }

    private int getPolygons() {
        return new Random().nextInt(15) + 5;
    }

    private int getNumber() {
        return new Random().nextInt(35) + 5;
    }
}


text:
package org.gradle.api.plugins;

import org.gradle.api.Project;
import org.gradle.api.internal.file.FileLookup;
import org.gradle.api.internal.project.ProjectInternal;

import java.io.File;

/**
 *
A {@link Convention} used for the BasePlugin.

 */
public class BasePluginConvention {
    private ProjectInternal project;

    private String distsDirName;

    private String libsDirName;

    // cached resolved values
    private File buildDir;
    private File libsDir;
    private File distsDir;

    private String archivesBaseName;

    public BasePluginConvention(Project project) {
        this.project = (ProjectInternal) project;
        archivesBaseName = project.getName();
        distsDirName = "distributions";
        libsDirName = "libs";
    }

    /**
     * Returns the directory to generate TAR and ZIP archives into.
     *
     * @return The directory. Never returns null.
     */
    public File getDistsDir() {
        File curProjectBuildDir = project.getBuildDir();
        if (distsDir != null && curProjectBuildDir.equals(buildDir)) {
            return distsDir;
        }
        buildDir = curProjectBuildDir;
        File dir = project.getServices().get(FileLookup.class).getFileResolver(curProjectBuildDir).resolve(distsDirName);
        distsDir = dir;
        return dir;
    }

    /**
     * Returns the directory to generate JAR and WAR archives into.
     *
     * @return The directory. Never returns null.
     */
    public File getLibsDir() {
        File curProjectBuildDir = project.getBuildDir();
        if (libsDir != null && curProjectBuildDir.equals(buildDir)) {
            return libsDir;
        }
        buildDir = curProjectBuildDir;
        File dir = project.getServices().get(FileLookup.class).getFileResolver(curProjectBuildDir).resolve(libsDirName);
        libsDir = dir;
        return dir;
    }

    public ProjectInternal getProject() {
        return project;
    }

    public void setProject(ProjectInternal project) {
        this.project = project;
    }

    /**
     * The name for the distributions directory. This in interpreted relative to the project' build directory.
     */
    public String getDistsDirName() {
        return distsDirName;
    }

    public void setDistsDirName(String distsDirName) {
        this.distsDirName = distsDirName;
        this.distsDir = null;
    }

    /**
     * The name for the libs directory. This in interpreted relative to the project' build directory.
     */
    public String getLibsDirName() {
        return libsDirName;
    }

    public void setLibsDirName(String libsDirName) {
        this.libsDirName = libsDirName;
        this.libsDir = null;
    }

    /**
     * The base name to use for archive files.
     */
    public String getArchivesBaseName() {
        return archivesBaseName;
    }

    public void setArchivesBaseName(String archivesBaseName) {
        this.archivesBaseName = archivesBaseName;
    }
}


text:
Welcome to Python Bytes. Python headlines delivered directly to your earbuds. In this episode we cover the new features in Python 3.6, text processing with Pynini, Python is 2nd most popular language on GitHub and more. [more]

This episode was brought to you by [Rollbar: they help you take the pain out of errors](http://rollbar.com/pythonbytes).

## News items

[**How to get superior text processing with Pynini**](https://www.oreilly.com/ideas/how-to-get-superior-text-processing-in-python-with-pynini)

- how to change your thinking from regular expression matching to FSAs (finite-state acceptor), then FSTs.
- Example using cheese names (love the Python tradition with that).
- library developed at Google called pynini for easily using FSTs

[**Python 3.6 b4 Is out! (beta!!!)**](https://docs.python.org/3.6/whatsnew/3.6.html)

- [PEP 498](https://docs.python.org/3.6/whatsnew/3.6.html#whatsnew36-pep498), formatted string literals.
- [PEP 515](https://docs.python.org/3.6/whatsnew/3.6.html#whatsnew36-pep515), underscores in numeric literals.
- [PEP 525](https://docs.python.org/3.6/whatsnew/3.6.html#whatsnew36-pep525), asynchronous generators.
- [PEP 530](https://docs.python.org/3.6/whatsnew/3.6.html#whatsnew36-pep530): asynchronous comprehensions.
- The **dict** type has been reimplemented to use a faster, more compact representation similar to the PyPy dict implementation. This resulted in dictionaries using 20% to 25% less memory when compared to Python 3.5.
- The class attribute definition order is now preserved.
- **Security**: The new secrets module has been added to simplify the generation of cryptographically strong pseudo-random numbers suitable for managing secrets such as account authentication, tokens, and similar.
- **Windows**: python.exe and pythonw.exe have been marked as long-path aware, which means that when the 260 character path limit may no longer apply. See removing the MAX_PATH limitation for details.

[**Create an Excellent Python Dev Env**](http://www.dougalmatthews.com/2016/Nov/12/create-an-excellent-python-dev-env/)

- pyenv, like virtualenv, I think, but independent of Python.
- pyenv-virtualenv instead of virtualenvwrapper
- pipsi - a tool to let you install python based CLI utilities in their own virtualenv easily.
- Tools he installs with pipsi:
	- tox - testing multiple environments
	- mkdocs - documentation static site generator
	- git-review - gerrit integration with git.
	- flake8 - static analysis
- He also mentions a shell called fish, which I hadn't heard of before.

[**GitHub language statistics, Python is 2nd most popular language**](https://www.reddit.com/r/Python/comments/5craf4/github_language_statistics_python_is_2nd_most/)

- An active repository should meet this requirements:
created or updated during the evaluated period,
	- at least one star
	- at least one fork
	- a size larger than 10 Kb
- JavaScript is likely over counted

[**Handling Unicode Strings in Python**](http://blog.emacsos.com/unicode-in-python.html)
- Text Representation in Python and the differences between 2.7 and 3.4+
- Converting between unicode strings and bytes
- IO boundary issues with databases, file system, or network services
- Logging
- JSON encoding
- Redis
- A pointer to a 2012 article from Ned Batchelder called Pragmatic Unicode.

[**Python extensions for VS Code for Mac / PC / Linux**](https://marketplace.visualstudio.com/items?itemName=donjayamanne.python)

- Linting (Prospector, Pylint, pycodestyle/Pep8, Flake8, pylama, pydocstyle with config files and plugins)
- Intellisense (autocompletion with support for PEP-0484)
- Scientific tools (Jupyter/IPython)
- Auto indenting
- Code formatting (autopep8, yapf, with config files)
- Code refactoring (Rename, Extract Variable, Extract Method, Sort Imports)
- Viewing references, code navigation, view signature
- Excellent debugging support (remote debugging over SSH, mutliple threads, django, flask)
- Unit testing, including debugging (unittest, pytest, nosetests, with config files)
- Execute file or code in a python terminal
- Local help file (offline documentation)
- Snippets

## Our personal news

### Brian
- Lot's of writing. My target is to get the book in print by PyCon US 2017 in May. But that's an aggressive schedule with the rest of my projects.
- Still working on getting #25 out the door. Interview with Dave Hunt from Mozilla about Selenium, Mozilla, pytest, tox, CI, and much more. Should go out within the next couple of days.
- Next interview scheduled is with David Hussman from DevJam. This will be a higher level discussion about software development practices. Look for that this month also.

### Michael
- Shipped: [Episode #85: Parsing horrible things with Python](https://talkpython.fm/episodes/show/85/parsing-horrible-things-with-python)
- Quick correction: github's awesome-python isn't the newsletter, that's [https://python.libhunt.com](https://python.libhunt.com)


text:
package com.wakeup.qcloud.domain;

import java.util.List;

import com.alibaba.fastjson.annotation.JSONField;

/**
 * @since 2017年3月4日
 * @author kalman03
 */
public class UserProfileItemDO extends BaseDO {

	private static final long serialVersionUID = -3193659732463420974L;
	@JSONField(name = "ProfileItem")
	private List<ProfileItemDO> profileItemList;
	/**
	 * 返回的用户的Identifier。
	 */
	@JSONField(name = "To_Account")
	private String toAccount;

	public List<ProfileItemDO> getProfileItemList() {
		return profileItemList;
	}

	public void setProfileItemList(List<ProfileItemDO> profileItemList) {
		this.profileItemList = profileItemList;
	}

	public String getToAccount() {
		return toAccount;
	}

	public void setToAccount(String toAccount) {
		this.toAccount = toAccount;
	}
}


text:
package org.cactoos.iterable;

import org.cactoos.text.TextOf;
import org.hamcrest.MatcherAssert;
import org.hamcrest.Matchers;
import org.junit.Test;

/**
 * Test case for {@link IterableOf}.
 * @author Yegor Bugayenko (yegor256@gmail.com)
 * @author Ix (ixmanuel@yahoo.com)
 * @version $Id$
 * @since 0.12
 * @checkstyle JavadocMethodCheck (500 lines)
 */
public final class IterableOfTest {

    @Test
    public void convertsScalarsToIterable() {
        MatcherAssert.assertThat(
            "Can't convert scalars to iterable",
            new LengthOf(
                new IterableOf<>(
                    "a", "b", "c"
                )
            ).intValue(),
            // @checkstyle MagicNumber (1 line)
            Matchers.equalTo(3)
        );
    }

    @Test
    public void convertsArrayOfIntsToIterable() {
        MatcherAssert.assertThat(
            "Can't convert int scalars to iterable",
            new IterableOf<>(1, 2, 0, 2),
            Matchers.hasItem(0)
        );
    }

    @Test
    public void convertsObjectsToIterable() {
        MatcherAssert.assertThat(
            "Can't convert objects to iterable",
            new LengthOf(
                new IterableOf<>(
                    new TextOf("a"), new TextOf("b"), new TextOf("c")
                )
            ).intValue(),
            // @checkstyle MagicNumber (1 line)
            Matchers.equalTo(3)
        );
    }

}


text:
""" LAR implementation of morphological operators on multidimensional images."""
import sys,os
import scipy.misc, numpy, pickle
from numpy.random import randint
from pyplasm import *

""" import modules from larcc/lib """
sys.path.insert(0, 'lib/py/')

import largrid
from largrid import *

def randomImage(shape, structure, noiseFraction=0.0):
   """ Generation of random image of given shape and structure.
      Return scipy.ndarray(shape)
   """
   print "noiseFraction =",noiseFraction
   ranges = [shape[k]/structure[k] for k in range(len(shape))]
   random_array = randint(0, 255, size=structure)
   image_array = numpy.zeros(shape)
   for index in scipy.array(CART(AA(range)(shape))):
      block = index/ranges
      if random_array[tuple(block)] < 127:
         image_array[tuple(index)] = 0
      else:
         image_array[tuple(index)] = 255

   noiseQuantity = PROD(list(shape))*noiseFraction
   k = 0
   while k < noiseQuantity:
      index = tuple(AA(randint)(list(shape)))
      if image_array[index] == 0: image_array[index] = 255
      else: image_array[index] = 0
      k += 1
   if len(shape)==3:
      for k in range(shape[0]):
         scipy.misc.imsave('tmp/outfile'+str(k).zfill(3)+'.png', image_array[k])
   else:
      scipy.misc.imsave('tmp/outfile'+str(k).zfill(3)+'.png', image_array)

   return image_array

def dump(object,filename):
   with open(filename, 'wb') as f:
       pickle.dump(object, f)

def load(filename):
   with open(filename, 'rb') as f:
       object = pickle.load(f)
   return object

def imageChainComplex (shape):
   tokens = str(shape)[1:-1].split(',')
   tokens = [token.strip() for token in tokens]
   filename = "tmp/larimage-" + "-".join(tokens) + ".pickle"

   if os.path.isfile(filename):
      shape, skeletons, operators = loadImageLAR(filename)
   else:
      skeletons = gridSkeletons(list(shape))
      operators = boundaryOps(skeletons)
      imageLAR = (shape, skeletons, operators)
      dump(imageLAR,filename)
      print "filename =",filename
   return shape, skeletons, operators

def loadImageLAR(filename):
   object = load(filename)
   shape, skeletons, operators = object
   return shape, skeletons, operators

def mapTupleToInt(shape):
   d = len(shape)
   weights = [PROD(shape[(k+1):]) for k in range(d-1)]+[1]

   def mapTupleToInt0(tuple):
      return INNERPROD([tuple,weights])
   return mapTupleToInt0

def setMaskWindow(window,image_array):
   minPoint, maxPoint = window
   imageShape = list(image_array.shape)
   indexRanges = zip(minPoint,maxPoint)
   tuples = CART([range(min,max) for min,max in indexRanges])

   imageCochain = image_array.reshape(PROD(imageShape))
   mapping = mapTupleToInt(imageShape)
   windowChain = [mapping(tuple) for tuple in tuples]
   segmentChain = [cell for cell in windowChain if imageCochain[cell]==255]

   for cell in segmentChain: imageCochain[cell] = 127
   image_array = imageCochain.reshape(imageShape)
   #for k in range(shape[0]):
   #  scipy.misc.imsave('tmp/outfile'+str(k).zfill(3)+'.png', image_array[k])

   return segmentChain

def larImage(shape):
   """ Compute vertices and skeletons of an image of given shape """
   imageVerts = larImageVerts(shape)
   skeletons = gridSkeletons(list(shape))
   return imageVerts, skeletons

def boundaryOps(skeletons):
   """ CSR matrices of boundary operators from list of skeletons """
   return [boundary(skeletons[k+1],faces)
      for k,faces in enumerate(skeletons[:-1])]

def chainTransform(skeletons,d,chain,csrMatrix,n):
   # n: number of vertices shared in the incidence relation
   cellNumber = len(skeletons[d])
   csrChain = scipy.sparse.csr_matrix((cellNumber,1))
   for h in chain: csrChain[h,0] = 1
   cooOutChain = matrixProduct(csrMatrix, csrChain).tocoo()
   outChain = [cooOutChain.row[h]
      for h,val in enumerate(cooOutChain.data) if int(val) >= n]
   return outChain

def visImageChain (shape,chain, imageVerts, skeletons):
   # imageVerts, skeletons = larImage(shape)
   chainLAR = [cell for k,cell in enumerate(skeletons[-1]) if k in chain]
   return imageVerts,chainLAR

def imageChainBoundary(shape, operators):
   imageVerts, skeletons = larImage(shape)
   # operators = boundaryOps(skeletons)
   cellNumber = PROD(list(shape))

   def imageChainBoundary0(k):
      csrBoundaryMat = operators[-1]
      facets = skeletons[k-1]

      def imageChainBoundary1(chain):
         csrChain = scipy.sparse.csr_matrix((cellNumber,1))
         for h in chain: csrChain[h,0] = 1
         csrBoundaryChain = matrixProduct(csrBoundaryMat, csrChain)
         for h,value in enumerate(csrBoundaryChain.data):
            if MOD([value,2]) == 0: csrBoundaryChain.data[h] = 0
         cooBoundaryChain = csrBoundaryChain.tocoo()
         boundaryChain = [cooBoundaryChain.row[h]
            for h,val in enumerate(cooBoundaryChain.data) if val == 1]

         boundaryChainModel = imageVerts, [facets[h] for h in boundaryChain]
         return boundaryChainModel,boundaryChain

      return imageChainBoundary1
   return imageChainBoundary0

def larDown(skeletons,d):
   """ Down operator, to multiply a d-chain and return the incident (d-1)-chain """
   csrMd = csrCreate(skeletons[d])
   csrMinus = csrCreate(skeletons[d-1])
   csrDown = matrixProduct(csrMinus,csrTranspose(csrMd))
   return csrDown

def larUp(skeletons,d):
   """ Up operator, to multiply a d-chain and return the incident (d+1)-chain """
   csrMd = csrCreate(skeletons[d])
   csrPlus = csrCreate(skeletons[d+1])
   csrUp = matrixProduct(csrPlus,csrTranspose(csrMd))
   return csrUp

def UUD(skeletons,d):
   """ Compute the morphological operator UUP.
      Return a CSR matrix to be applied to the coordinate representation of a chain
   """
   D = larDown(skeletons,d)
   U1 = larUp(skeletons,d-1)
   U2 = larUp(skeletons,d)
   UUDout = matrixProduct(U2,matrixProduct(U1,D))
   return D,U1,U2,UUDout

def testAlgebraicMorphologyStepByStep (solid, b_rep, chain, imageVerts, skeletons):
   d = len(skeletons)-1
   D,U1,U2,csrMorphOp = UUD(skeletons,d-1)

   VIEW(EXPLODE(1.5,1.5,1)(MKPOLS(solid)))
   VIEW(COLOR(MAGENTA)(STRUCT(MKPOLS(b_rep))))

   outputChain = chainTransform(skeletons,d-1,chain,D,d-1)
   chainLAR = [cell for k,cell in enumerate(skeletons[0]) if k in outputChain]
   model0 = (imageVerts,chainLAR)
   VIEW(COLOR(RED)(STRUCT(MKPOLS(model0))))

   M2 = csrCreate(skeletons[d])

   outputChain = chainTransform(skeletons,0,outputChain,M2,d)
   chainLAR = [cell for k,cell in enumerate(skeletons[d]) if k in outputChain]
   model2 = (imageVerts,chainLAR)
   VIEW(COLOR(YELLOW)(STRUCT(MKPOLS(model2))))

   return imageVerts,chainLAR

def testAlgebraicMorphology (solid, b_rep, chain, imageVerts, skeletons):
   d = len(skeletons)-1
   D,U1,U2,csrMorphOp = UUD(skeletons,d-1)
   outputChain = chainTransform(skeletons,1,chain,csrMorphOp,d)
   chainLAR = [cell for k,cell in enumerate(skeletons[d]) if k in outputChain]
   model2 = (imageVerts,chainLAR)
   return imageVerts,chainLAR


text:
namespace Envoy {
namespace Upstream {

DEFINE_PROTO_FUZZER(const test::common::upstream::RandomLoadBalancerTestCase& input) {
  try {
    TestUtility::validate(input);
  } catch (const ProtoValidationException& e) {
    ENVOY_LOG_MISC(debug, "ProtoValidationException: {}", e.what());
    return;
  }

  LoadBalancerFuzzBase load_balancer_fuzz = LoadBalancerFuzzBase();
  load_balancer_fuzz.initializeLbComponents(input.load_balancer_test_case());

  try {
    load_balancer_fuzz.lb_ = std::make_unique<RandomLoadBalancer>(
        load_balancer_fuzz.priority_set_, nullptr, load_balancer_fuzz.stats_,
        load_balancer_fuzz.runtime_, load_balancer_fuzz.random_,
        input.load_balancer_test_case().common_lb_config());
  } catch (EnvoyException& e) {
    ENVOY_LOG_MISC(debug, "EnvoyException; {}", e.what());
    return;
  }

  load_balancer_fuzz.replay(input.load_balancer_test_case().actions());
}

} // namespace Upstream
} // namespace Envoy


text:
def prompt
  puts 'Enter a number or bye'
end

def hi_hi_goodbye
  prompt
  while (line = gets) && (line !~ /bye/) # first is an assignment statement that returns a line or nil, and is thus boolean
    line.to_i.times { print 'hi ' }
    puts
    prompt
  end
  puts "Goodbye!"
end

# This will just invoke the method if you run this program directly
# This way you can try it out by running "$ ruby 2_input_output_control.rb"
# but it will still work for our tests
hi_hi_goodbye if $0 == __FILE__


text:
package org.drip.analytics.holiday;

/*
 * -*- mode: java; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*-
 */

/*!
 * Copyright (C) 2013 Lakshmi Krishnamurthy
 * Copyright (C) 2012 Lakshmi Krishnamurthy
 * Copyright (C) 2011 Lakshmi Krishnamurthy
 *
 * This file is part of CreditAnalytics, a free-software/open-source library for fixed income analysts and
 * 		developers - http://www.credit-trader.org
 *
 * CreditAnalytics is a free, full featured, fixed income credit analytics library, developed with a special
 * 		focus towards the needs of the bonds and credit products community.
 *
 *  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.
 */

/**
 * Static implements a complete date as a specific holiday.
 *
 * @author Lakshmi Krishnamurthy
 */

public class Static extends Base {
	private double _dblDate = java.lang.Double.NaN;

	/**
	 * Creates a static holiday from the date string and the description
	 *
	 * @param strDate Date string
	 * @param strDescription Description
	 *
	 * @return StaticHoliday instance
	 */

	public static final Static CreateFromDateDescription (
		final java.lang.String strDate,
		final java.lang.String strDescription)
	{
		org.drip.analytics.date.JulianDate dtHol = org.drip.analytics.date.JulianDate.CreateFromDDMMMYYYY
			(strDate);

		if (null == dtHol) return null;

		try {
			return new Static (dtHol, strDescription);
		} catch (java.lang.Exception e) {
			e.printStackTrace();
		}

		return null;
	}

	/**
	 * Constructs a static holiday from the date and the description
	 *
	 * @param dt Date
	 * @param strDescription Description
	 */

	public Static (
		final org.drip.analytics.date.JulianDate dt,
		final java.lang.String strDescription)
		throws java.lang.Exception
	{
		super (strDescription);

		if (null == dt) throw new java.lang.Exception ("Null date into Static Holiday");

		_dblDate = dt.getJulian();
	}

	/**
	 * De-serialization of StaticHoliday from byte stream
	 *
	 * @param ab Byte stream
	 *
	 * @throws java.lang.Exception Thrown if cannot properly de-serialize StaticHoliday
	 */

	public Static (
		final byte[] ab)
		throws java.lang.Exception
	{
		super (ab);

		if (null == ab || 0 == ab.length)
			throw new java.lang.Exception ("StaticHoliday de-serialize: Invalid byte stream input");

		java.lang.String strRawString = new java.lang.String (ab);

		if (null == strRawString || strRawString.isEmpty())
			throw new java.lang.Exception ("StaticHoliday de-serializer: Empty state");

		java.lang.String strFH = strRawString.substring (0, strRawString.indexOf (getObjectTrailer()));

		if (null == strFH || strFH.isEmpty())
			throw new java.lang.Exception ("StaticHoliday de-serializer: Cannot locate state");

		java.lang.String[] astrField = org.drip.math.common.StringUtil.Split (strFH, getFieldDelimiter());

		if (null == astrField || 2 > astrField.length)
			throw new java.lang.Exception ("StaticHoliday de-serialize: Invalid number of fields");

		if (null == astrField[1] || astrField[1].isEmpty() ||
			org.drip.service.stream.Serializer.NULL_SER_STRING.equalsIgnoreCase (astrField[1]))
			throw new java.lang.Exception ("StaticHoliday de-serializer: Cannot locate static holiday date");

		_dblDate = new java.lang.Double (astrField[1]);
	}

	@Override public double getDateInYear (
		final int iYear,
		final boolean bAdjusted)
	{
		return _dblDate;
	}

	@Override public java.lang.String getFieldDelimiter()
	{
		return "#";
	}

	@Override public java.lang.String getObjectTrailer()
	{
		return "^";
	}

	@Override public byte[] serialize()
	{
		java.lang.StringBuffer sb = new java.lang.StringBuffer();

		sb.append (new java.lang.String (super.serialize()) + getFieldDelimiter() + _dblDate);

		return sb.append (getObjectTrailer()).toString().getBytes();
	}

	@Override public org.drip.service.stream.Serializer deserialize (
		final byte[] ab)
	{
		try {
			return new Static (ab);
		} catch (java.lang.Exception e) {
			e.printStackTrace();
		}

		return null;
	}

	public static final void main (
		final java.lang.String[] astrArgs)
		throws java.lang.Exception
	{
		Static sh = Static.CreateFromDateDescription ("12-JUN-2020", "Are you kidding me?");

		byte[] abSH = sh.serialize();

		System.out.println ("Input: " + new java.lang.String (abSH));

		Static shDeser = new Static (abSH);

		System.out.println ("Output: " + new java.lang.String (shDeser.serialize()));
	}
}


text:
import * as vsc from 'vscode'

export const AllTabs = /^\t+$/
export const AllSpaces = /^ +$/

export function adjustMultilineIndentation(code: string, indentSize?: number) {
  if (!indentSize) {
    return code
  }

  const reNewLine = /\r?\n/
  const lines = code.split(reNewLine)

  if (lines.length === 1) {
    return code
  }

  const newLine = reNewLine.exec(code)[0]

  return lines.map((line, i) => i > 0 ? stripLineIndent(line, indentSize) : line)
    .join(newLine)
}

function stripLineIndent(line: string, indentSize: number) {
  const whitespacesMatch = /^[\t ]+/.exec(line)
  if (!whitespacesMatch) {
    return line
  }

  const whitespaces = whitespacesMatch[0]

  if (AllTabs.test(whitespaces) && indentSize <= whitespaces.length) {
    return line.substring(indentSize)
  }

  const tabSize = vsc.window.activeTextEditor.options.tabSize as number

  if (AllSpaces.test(whitespaces) && indentSize <= (whitespaces.length / tabSize)) {
    return line.substring(indentSize * tabSize)
  }

  return line
}

export const adjustLeadingWhitespace = (content: string, leadingWhitespace = '') => {
  return content.split(/\r?\n/).map((line, i) => !i ? line : leadingWhitespace+line).join('\n')
}


text:
require 'spec_helper'

describe TextRazor do

  describe ".topics" do

    it "should make correct calls" do
      expect(TextRazor::Client).to receive(:topics).
        with('api_key', 'text', {})

      TextRazor.topics('api_key', 'text', {})
    end

  end

  describe ".entities" do

    it "should make correct calls" do
      expect(TextRazor::Client).to receive(:entities).
        with('api_key', 'text', {})

      TextRazor.entities('api_key', 'text', {})
    end

  end

  describe ".words" do

    it "should make correct calls" do
      expect(TextRazor::Client).to receive(:words).
        with('api_key', 'text', {})

      TextRazor.words('api_key', 'text', {})
    end

  end

  describe ".phrases" do

    it "should make correct calls" do
      expect(TextRazor::Client).to receive(:phrases).
        with('api_key', 'text', {})

      TextRazor.phrases('api_key', 'text', {})
    end

  end

  describe ".reset" do
    before :each do
      TextRazor.configure do |config|
        config.secure = false
      end
    end

    it "resets the configuration" do
      TextRazor.reset
      config = TextRazor.configuration
      expect(config.secure).to eq(true)
    end
  end

end


text:
package mg.fishchicken.audio;

import mg.fishchicken.core.assets.AssetMap;
import mg.fishchicken.core.assets.Assets;
import mg.fishchicken.core.configuration.Configuration;
import mg.fishchicken.core.logging.Log;
import mg.fishchicken.core.logging.Log.LogType;

import com.badlogic.gdx.utils.GdxRuntimeException;

public class Music extends AudioTrack<com.badlogic.gdx.audio.Music> {

	private com.badlogic.gdx.audio.Music music;

	private static Music playingMusic;

	public Music() {
		super();
	}

	public Music(String fileName) {
		super();
		setFilename(fileName);
	}

	public Music(AudioTrack<?> sountToInitFrom) {
		super();
		initFrom(sountToInitFrom);
	}

	public com.badlogic.gdx.audio.Music getTrack() {
		if (music == null) {
			music = Assets.get(getFilename(), com.badlogic.gdx.audio.Music.class);
		}
		return music;
	}

	@Override
	public void setLooping(boolean value) {
		super.setLooping(value);
		getTrack().setLooping(value);
	}

	/**
	 * Updates this audiotrack in time. Used
	 * mostly for fading away tracks.
	 *
	 * This should be called each frame.
	 *
	 * @param deltaTime
	 */
	public void update(float deltaTime) {
		super.update(deltaTime);
		if (this.equals(playingMusic)) {
			if (!getTrack().isPlaying()) {
				playingMusic = null;
			}
		}
	}

	protected boolean shouldPlay(int rollResult) {
		if (getTrack().isPlaying()) {
			return false;
		}
		return super.shouldPlay(rollResult);
	}

	protected void playTrack() {
		if (playingMusic != null) {
			playingMusic.stop();
		}
		getTrack().setVolume(getVolume());
		int retryCounter = 0;
		Exception exception = null;
		while (retryCounter < 10) {
			try {
				getTrack().play();
				exception = null;
				break;
			} catch (GdxRuntimeException e) {
				exception = e;
			}
		}
		if (exception != null) {
			Log.log("Error playng music: "+exception, LogType.ERROR);
		}
		playingMusic = this;
	}

	public void stop() {
		delayedPlayIn = 0;
		fadeOut();
	}

	public void stopTrack() {
		delayedPlayIn = 0;
		getTrack().stop();
		playingMusic = null;
	}

	public void setVolume(float volume) {
		super.setVolume(volume);
		getTrack().setVolume(volume);
	}

	@Override
	public void setTrack(com.badlogic.gdx.audio.Music track) {
		music = track;
	}

	@Override
	public void gatherAssets(AssetMap assetStore) {
		assetStore.put(getFilename(),  com.badlogic.gdx.audio.Music.class);
	}

	public static boolean isPlayingMusic() {
		return playingMusic != null;
	}

	public static void stopPlayingMusic() {
		if (playingMusic != null) {
			playingMusic.stopTrack();
			playingMusic = null;
		}
	}

	public static void updatePlayingMusicVolume() {
		if (playingMusic != null) {
			playingMusic.modifyVolume();
		}
	}

	@Override
	public void clearAssetReferences() {
		music = null;
	}

	@Override
	protected float getConfigurationVolumeModifier() {
		return Configuration.getMusicVolume();
	}

}


text:
package org.apache.camel.test.main.junit5.legacy;

import org.apache.camel.component.mock.MockEndpoint;
import org.apache.camel.test.main.junit5.CamelMainTestSupport;
import org.apache.camel.test.main.junit5.common.MyMainClass;
import org.junit.jupiter.api.MethodOrderer;
import org.junit.jupiter.api.Order;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.TestInstance;
import org.junit.jupiter.api.TestMethodOrder;

import static org.junit.jupiter.api.Assertions.assertEquals;

/**
 * A test class ensuring that a new camel context is created for each test method.
 */
@TestInstance(TestInstance.Lifecycle.PER_METHOD)
@TestMethodOrder(MethodOrderer.OrderAnnotation.class)
class TestInstancePerMethodTest extends CamelMainTestSupport {

    @Override
    protected Class<?> getMainClass() {
        return MyMainClass.class;
    }

    @Order(1)
    @Test
    void shouldBeLaunchedFirst() throws Exception {
        MockEndpoint mock = context.getEndpoint("mock:bean", MockEndpoint.class);
        mock.expectedBodiesReceived(1);
        int result = template.requestBody("direct:bean", null, Integer.class);
        mock.assertIsSatisfied();
        assertEquals(1, result);
    }

    @Order(2)
    @Test
    void shouldBeLaunchedSecondWithSameResult() throws Exception {
        MockEndpoint mock = context.getEndpoint("mock:bean", MockEndpoint.class);
        mock.expectedBodiesReceived(1);
        int result = template.requestBody("direct:bean", null, Integer.class);
        mock.assertIsSatisfied();
        assertEquals(1, result);
    }
}


text:
UIActivityIndicatorView with a label which can be added to UIButton and UINavigationBar.UINavigationItem

## 给导航栏添加类似于微信的小菊花

先上一张微信聊天界面导航栏表示网络请求的效果图

![Wechat](https://github.com/camoufleur/LabeledActivityIndicatorView/blob/master/Demo/Images/weChat.png)

再放一张最终的效果图

![UIActivityIndicatorView](https://github.com/camoufleur/LabeledActivityIndicatorView/blob/master/Demo/Images/Demo.gif)

Installation
==============

### CocoaPods

1. Add `pod 'LabeledActivityIndicatorView'` to your Podfile.
2. Run `pod install` or `pod update`.
3. import "LabeledActivityIndicatorView.h".

### 直接下载
clone 项目到本地, 将LabeledActivityIndicatorView文件夹拖入项目中使用

- 喜欢的给个Star吧.
- 简书个人主页[Camoufleur](http://www.jianshu.com/u/5eb32816c254)


text:
#include <linux/init.h>
#include <linux/module.h>
#include <linux/pm.h>
#include <linux/sched.h>
#include <linux/interrupt.h>
#include <linux/sysctl.h>
#include <linux/errno.h>
#include <linux/delay.h>
#include <asm/uaccess.h>

#include <asm/mb86943a.h>

#include "local.h"

/*
 * Debug macros
 */
#define DEBUG

int pm_do_suspend(void)
{
	local_irq_disable();

	__set_LEDS(0xb1);

	/* go zzz */
	frv_cpu_suspend(pdm_suspend_mode);

	__set_LEDS(0xb2);

	local_irq_enable();

	return 0;
}

static unsigned long __irq_mask;

/*
 * Setup interrupt masks, etc to enable wakeup by power switch
 */
static void __default_power_switch_setup(void)
{
	/* default is to mask all interrupt sources. */
	__irq_mask = *(unsigned long *)0xfeff9820;
	*(unsigned long *)0xfeff9820 = 0xfffe0000;
}

/*
 * Cleanup interrupt masks, etc after wakeup by power switch
 */
static void __default_power_switch_cleanup(void)
{
	*(unsigned long *)0xfeff9820 = __irq_mask;
}

/*
 * Return non-zero if wakeup irq was caused by power switch
 */
static int __default_power_switch_check(void)
{
	return 1;
}

void (*__power_switch_wake_setup)(void) = __default_power_switch_setup;
int  (*__power_switch_wake_check)(void) = __default_power_switch_check;
void (*__power_switch_wake_cleanup)(void) = __default_power_switch_cleanup;

int pm_do_bus_sleep(void)
{
	local_irq_disable();

	/*
         * Here is where we need some platform-dependent setup
	 * of the interrupt state so that appropriate wakeup
	 * sources are allowed and all others are masked.
	 */
	__power_switch_wake_setup();

	__set_LEDS(0xa1);

	/* go zzz
	 *
	 * This is in a loop in case power switch shares an irq with other
	 * devices. The wake_check() tells us if we need to finish waking
	 * or go back to sleep.
	 */
	do {
		frv_cpu_suspend(HSR0_PDM_BUS_SLEEP);
	} while (__power_switch_wake_check && !__power_switch_wake_check());

	__set_LEDS(0xa2);

	/*
         * Here is where we need some platform-dependent restore
	 * of the interrupt state prior to being called.
	 */
	__power_switch_wake_cleanup();

	local_irq_enable();

	return 0;
}

unsigned long sleep_phys_sp(void *sp)
{
	return virt_to_phys(sp);
}

#ifdef CONFIG_SYSCTL
/*
 * Use a temporary sysctl number. Horrid, but will be cleaned up in 2.6
 * when all the PM interfaces exist nicely.
 */
#define CTL_PM_SUSPEND 1
#define CTL_PM_CMODE 2
#define CTL_PM_P0 4
#define CTL_PM_CM 5

static int user_atoi(char __user *ubuf, size_t len)
{
	char buf[16];
	unsigned long ret;

	if (len > 15)
		return -EINVAL;

	if (copy_from_user(buf, ubuf, len))
		return -EFAULT;

	buf[len] = 0;
	ret = simple_strtoul(buf, NULL, 0);
	if (ret > INT_MAX)
		return -ERANGE;
	return ret;
}

/*
 * Send us to sleep.
 */
static int sysctl_pm_do_suspend(struct ctl_table *ctl, int write,
				void __user *buffer, size_t *lenp, loff_t *fpos)
{
	int mode;

	if (*lenp <= 0)
		return -EIO;

	mode = user_atoi(buffer, *lenp);
	switch (mode) {
	case 1:
	    return pm_do_suspend();

	case 5:
	    return pm_do_bus_sleep();

	default:
	    return -EINVAL;
	}
}

static int try_set_cmode(int new_cmode)
{
	if (new_cmode > 15)
		return -EINVAL;
	if (!(clock_cmodes_permitted & (1<<new_cmode)))
		return -EINVAL;

	/* now change cmode */
	local_irq_disable();
	frv_dma_pause_all();

	frv_change_cmode(new_cmode);

	determine_clocks(0);
	time_divisor_init();

#ifdef DEBUG
	determine_clocks(1);
#endif
	frv_dma_resume_all();
	local_irq_enable();

	return 0;
}

static int cmode_procctl(struct ctl_table *ctl, int write,
			 void __user *buffer, size_t *lenp, loff_t *fpos)
{
	int new_cmode;

	if (!write)
		return proc_dointvec(ctl, write, buffer, lenp, fpos);

	new_cmode = user_atoi(buffer, *lenp);

	return try_set_cmode(new_cmode)?:*lenp;
}

static int try_set_p0(int new_p0)
{
	unsigned long flags, clkc;

	if (new_p0 < 0 || new_p0 > 1)
		return -EINVAL;

	local_irq_save(flags);
	__set_PSR(flags & ~PSR_ET);

	frv_dma_pause_all();

	clkc = __get_CLKC();
	if (new_p0)
		clkc |= CLKC_P0;
	else
		clkc &= ~CLKC_P0;
	__set_CLKC(clkc);

	determine_clocks(0);
	time_divisor_init();

#ifdef DEBUG
	determine_clocks(1);
#endif
	frv_dma_resume_all();
	local_irq_restore(flags);
	return 0;
}

static int try_set_cm(int new_cm)
{
	unsigned long flags, clkc;

	if (new_cm < 0 || new_cm > 1)
		return -EINVAL;

	local_irq_save(flags);
	__set_PSR(flags & ~PSR_ET);

	frv_dma_pause_all();

	clkc = __get_CLKC();
	clkc &= ~CLKC_CM;
	clkc |= new_cm;
	__set_CLKC(clkc);

	determine_clocks(0);
	time_divisor_init();

#if 1 //def DEBUG
	determine_clocks(1);
#endif

	frv_dma_resume_all();
	local_irq_restore(flags);
	return 0;
}

static int p0_procctl(struct ctl_table *ctl, int write,
		      void __user *buffer, size_t *lenp, loff_t *fpos)
{
	int new_p0;

	if (!write)
		return proc_dointvec(ctl, write, buffer, lenp, fpos);

	new_p0 = user_atoi(buffer, *lenp);

	return try_set_p0(new_p0)?:*lenp;
}

static int cm_procctl(struct ctl_table *ctl, int write,
		      void __user *buffer, size_t *lenp, loff_t *fpos)
{
	int new_cm;

	if (!write)
		return proc_dointvec(ctl, write, buffer, lenp, fpos);

	new_cm = user_atoi(buffer, *lenp);

	return try_set_cm(new_cm)?:*lenp;
}

static struct ctl_table pm_table[] =
{
	{
		.procname	= "suspend",
		.data		= NULL,
		.maxlen		= 0,
		.mode		= 0200,
		.proc_handler	= sysctl_pm_do_suspend,
	},
	{
		.procname	= "cmode",
		.data		= &clock_cmode_current,
		.maxlen		= sizeof(int),
		.mode		= 0644,
		.proc_handler	= cmode_procctl,
	},
	{
		.procname	= "p0",
		.data		= &clock_p0_current,
		.maxlen		= sizeof(int),
		.mode		= 0644,
		.proc_handler	= p0_procctl,
	},
	{
		.procname	= "cm",
		.data		= &clock_cm_current,
		.maxlen		= sizeof(int),
		.mode		= 0644,
		.proc_handler	= cm_procctl,
	},
	{ }
};

static struct ctl_table pm_dir_table[] =
{
	{
		.procname	= "pm",
		.mode		= 0555,
		.child		= pm_table,
	},
	{ }
};

/*
 * Initialize power interface
 */
static int __init pm_init(void)
{
	register_sysctl_table(pm_dir_table);
	return 0;
}

__initcall(pm_init);

#endif


text:
"""The tests for SleepIQ sensor platform."""
from unittest.mock import MagicMock

import homeassistant.components.sleepiq.sensor as sleepiq
from homeassistant.setup import async_setup_component

from tests.components.sleepiq.test_init import mock_responses

CONFIG = {"username": "foo", "password": "bar"}

async def test_setup(hass, requests_mock):
    """Test for successfully setting up the SleepIQ platform."""
    mock_responses(requests_mock)

    assert await async_setup_component(hass, "sleepiq", {"sleepiq": CONFIG})

    device_mock = MagicMock()
    sleepiq.setup_platform(hass, CONFIG, device_mock, MagicMock())
    devices = device_mock.call_args[0][0]
    assert len(devices) == 2

    left_side = devices[1]
    left_side.hass = hass
    assert left_side.name == "SleepNumber ILE Test1 SleepNumber"
    assert left_side.state == 40

    right_side = devices[0]
    right_side.hass = hass
    assert right_side.name == "SleepNumber ILE Test2 SleepNumber"
    assert right_side.state == 80

async def test_setup_single(hass, requests_mock):
    """Test for successfully setting up the SleepIQ platform."""
    mock_responses(requests_mock, single=True)

    assert await async_setup_component(hass, "sleepiq", {"sleepiq": CONFIG})

    device_mock = MagicMock()
    sleepiq.setup_platform(hass, CONFIG, device_mock, MagicMock())
    devices = device_mock.call_args[0][0]
    assert len(devices) == 1

    right_side = devices[0]
    right_side.hass = hass
    assert right_side.name == "SleepNumber ILE Test1 SleepNumber"
    assert right_side.state == 40


text:
// This file is a part of the IntcludeOS unikernel - www.includeos.org
//
// Copyright 2017 Oslo and Akershus University College of Applied Sciences
// and Alfred Bratterud
//
// 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.

//#define SMP_DEBUG 1
#include <kernel/fiber.hpp>
#include <common> // assert-based Exepcts/Ensures
#include <cstdint>
#include <memory>
#include <smp>

// Default location for previous stack. Asm will always save a pointer.
#if defined(INCLUDEOS_SINGLE_THREADED)
int Fiber::next_id_{0};
#else
std::atomic<int> Fiber::next_id_{0};
#endif

thread_local void* caller_stack_ = nullptr;
thread_local Fiber* Fiber::main_ = nullptr;
thread_local Fiber* Fiber::current_ = nullptr;

extern "C" {
  void __fiber_jumpstart(volatile void* th_stack, volatile Fiber* f, volatile void* parent_stack);
  void __fiber_yield(volatile void* stack, volatile void* parent_stack);

  /** Jumpstart a fiber. Called from __fiber_jumpstart (assembly) */
  void fiber_jumpstarter(Fiber* f)
  {

    Expects(f);
    f->ret_= f->func_(f->param_);

    // Last stackframe before switching back. Done.
    Fiber::current_ = f->parent_ ? f->parent_ : nullptr;
    f->done_ = true;
  }
}

void Fiber::start() {

  if (not func_)
    throw Err_bad_fiber("Can't start fiber without a function");

  // Become main if none exists
  if (not main_)
    main_ = this;

  // Suspend current running fiber if any
  if (current_) {
    current_ -> suspended_ = true;
    make_parent(current_);
  }

  // Become current
  current_ = this;

  started_ = true;
  running_ = true;

  // Switch stacks and call function
  __fiber_jumpstart(stack_loc_, this, &(parent_stack_));

  // Returns here after first yield / final return

  if (main_ == this)
    main_ = nullptr;

  Expects(current_ != this);

  return;
}

void Fiber::yield() {

  auto* from = current_;
  Expects(from);
  auto* into = current_->parent_;
  Expects(into);
  Expects(into->suspended());
  Expects(into->stack_loc_);
  Expects(from->stack_loc_);
  Expects(not into->done_);

  from->suspended_ = true;
  from->running_ = false;

  current_ = into;

  __fiber_yield(from->parent_stack_, &(from->stack_loc_));

};

void Fiber::resume()
{

  if (not suspended_ or done_ or func_ == nullptr)
    return;

  Expects(current_);

  make_parent(current_);

  current_ = this;
  suspended_ = false;
  running_ = true;
  parent_->suspended_ = true;
  parent_->running_ = false;

  Expects(stack_loc_ > stack_.get() and stack_loc_ < stack_.get() + stack_size_);
  Expects(not done_);

  __fiber_yield(stack_loc_, &(parent_stack_));

  // Returns here after yield

}


text:
package org.ovirt.engine.ui.webadmin.section.main.presenter.tab;

import java.util.List;

import org.ovirt.engine.core.common.businessentities.vm_pools;
import org.ovirt.engine.ui.common.uicommon.model.MainModelProvider;
import org.ovirt.engine.ui.common.widget.tab.ModelBoundTabData;
import org.ovirt.engine.ui.uicommonweb.models.pools.PoolListModel;
import org.ovirt.engine.ui.webadmin.gin.ClientGinjector;
import org.ovirt.engine.ui.webadmin.place.ApplicationPlaces;
import org.ovirt.engine.ui.webadmin.section.main.presenter.AbstractMainTabWithDetailsPresenter;
import org.ovirt.engine.ui.webadmin.section.main.presenter.MainTabPanelPresenter;

import com.google.gwt.event.shared.EventBus;
import com.google.inject.Inject;
import com.gwtplatform.dispatch.annotation.GenEvent;
import com.gwtplatform.mvp.client.TabData;
import com.gwtplatform.mvp.client.annotations.NameToken;
import com.gwtplatform.mvp.client.annotations.ProxyCodeSplit;
import com.gwtplatform.mvp.client.annotations.TabInfo;
import com.gwtplatform.mvp.client.proxy.PlaceManager;
import com.gwtplatform.mvp.client.proxy.PlaceRequest;
import com.gwtplatform.mvp.client.proxy.TabContentProxyPlace;

public class MainTabPoolPresenter extends AbstractMainTabWithDetailsPresenter<vm_pools, PoolListModel, MainTabPoolPresenter.ViewDef, MainTabPoolPresenter.ProxyDef> {

    @GenEvent
    public static class PoolSelectionChange {

        List<vm_pools> selectedItems;

    }

    @ProxyCodeSplit
    @NameToken(ApplicationPlaces.poolMainTabPlace)
    public interface ProxyDef extends TabContentProxyPlace<MainTabPoolPresenter> {
    }

    public interface ViewDef extends AbstractMainTabWithDetailsPresenter.ViewDef<vm_pools> {
    }

    @TabInfo(container = MainTabPanelPresenter.class)
    static TabData getTabData(ClientGinjector ginjector) {
        return new ModelBoundTabData(ginjector.getApplicationConstants().poolMainTabLabel(), 6,
                ginjector.getMainTabPoolModelProvider());
    }

    @Inject
    public MainTabPoolPresenter(EventBus eventBus, ViewDef view, ProxyDef proxy,
            PlaceManager placeManager, MainModelProvider<vm_pools, PoolListModel> modelProvider) {
        super(eventBus, view, proxy, placeManager, modelProvider);
    }

    @Override
    protected void fireTableSelectionChangeEvent() {
        PoolSelectionChangeEvent.fire(this, getSelectedItems());
    }

    @Override
    protected PlaceRequest getMainTabRequest() {
        return new PlaceRequest(ApplicationPlaces.poolMainTabPlace);
    }
}


text: include_recipe 'base-template'


text:
PROVIDERS.fetch(:wikipedia).register_metric :edit_count do |metric|
  metric.title = "Edit Count"
  metric.description = "The number of edits made."

  metric.block = proc do |adapter|
    Datapoint.new value: adapter.edit_count
  end
end


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

System_Auth::set_permission(3);

Alt_Validation::instance()
    ->rule(Alt_Validation::required($_REQUEST["queueid"]), "Queueid tidak boleh kosong!")
    ->rule(Alt_Validation::required($_REQUEST["name"]), "Nama tidak boleh kosong!")
    ->check();

$dbo = new Queue_Counter();

return $dbo->insert($_REQUEST);


text:
import pytest

from contextlib import suppress

import matplotlib as mpl
mpl.use('Agg')  # disable `plt.show()` popup window during testing
import matplotlib.pyplot as plt

import pybinding as pb

from .utils.path import path_from_fixture
from .utils.compare_figures import CompareFigure
from .utils.fuzzy_equal import FuzzyEqual

def pytest_configure():
    pytest.fuzzy_equal = FuzzyEqual

def pytest_addoption(parser):
    parser.addoption("--alwaysplot", action="store_true",
                     help="Plot even for tests which pass.")
    parser.addoption("--failpath", action="store", default="failed",
                     help="Where to put failure plots. Relative to tests dir or absolute path.")
    parser.addoption("--savebaseline", action="store_true",
                     help="Save a new baseline for all tests.")
    parser.addoption("--readonly", action="store_true",
                     help="Don't save new baseline data.")

@pytest.hookimpl(hookwrapper=True)
def pytest_runtest_makereport(item):
    """Allows fixtures to access test reports

    Adds test reports `rep_setup`, `rep_call`, `rep_teardown` to `request.node`.
    Required by the `plot_if_fails` fixture to determine if a test failed.
    """
    outcome = yield
    report = outcome.get_result()
    setattr(item, "rep_" + report.when, report)
    return report

@pytest.fixture
def baseline(request):
    """Return baseline data for this result. If non exist create it."""
    def get_expected(result, group=''):
        file = path_from_fixture(request, prefix='baseline_data', ext='.pbz',
                                 override_group=group)

        if not request.config.getoption("--savebaseline") and file.exists():
            return pb.load(file)
        elif not request.config.getoption("--readonly"):
            if not file.parent.exists():
                file.parent.mkdir(parents=True)
            pb.save(result, file)
            return result
        else:
            raise RuntimeError("Missing baseline data: {}".format(file))

    return get_expected

@pytest.fixture
def compare_figure(request):
    """Compare a figure to a baseline image"""
    return CompareFigure(request)

@pytest.yield_fixture
def plot_if_fails(request):
    """This fixture will plot the actual and expected data if the test fails"""
    class Gather:
        def __init__(self):
            self.data = []

        def __call__(self, result, expected, method, *args, **kwargs):
            self.data.append(locals().copy())

        def plot(self, what):
            for d in self.data:
                getattr(d[what], d['method'])(*d['args'], **d['kwargs'])

            plt.title(what)
            pb.pltutils.legend()

    gather = Gather()
    yield gather

    prefix = request.config.getoption("--failpath")
    figure_path = path_from_fixture(request, prefix, ext='.png')
    if request.config.getoption("--alwaysplot") or request.node.rep_call.failed:
        plt.figure(figsize=(6, 3))
        plt.subplot(121)
        gather.plot('result')

        plt.subplot(122)
        gather.plot('expected')

        if not figure_path.parent.exists():
            figure_path.parent.mkdir(parents=True)

        plt.savefig(str(figure_path))
        plt.close()
    elif figure_path.exists():
        # test passed -> delete old fail figure file
        with suppress(OSError):
            figure_path.unlink()


text:
<?xml version="1.0" encoding="UTF-8"?>
<Tokens version="1.0">
	<File path="Protocols/CouchbaseDelegate.html">

		<Token>
			<TokenIdentifier>//apple_ref/occ/intf/CouchbaseDelegate</TokenIdentifier>
			<Abstract type="html"></Abstract>
			<DeclaredIn>CouchbaseMobile.h</DeclaredIn>

			<NodeRef refid="37"/>
		</Token>

		<Token>
			<TokenIdentifier>//apple_ref/occ/intfm/CouchbaseDelegate/couchbaseMobile:didStart:</TokenIdentifier>
			<Abstract type="html">Called after a CouchbaseMobile instance finishes starting up.</Abstract>
			<DeclaredIn>CouchbaseMobile.h</DeclaredIn>

			<Declaration>- (void)couchbaseMobile:(CouchbaseMobile *)couchbase didStart:(NSURL *)serverURL</Declaration>
			<Parameters>
				<Parameter>
					<Name>couchbase</Name>
					<Abstract type="html">The instance of CouchbaseMobile.</Abstract>
				</Parameter><Parameter>
					<Name>serverURL</Name>
					<Abstract type="html">The URL at which the Couchbase server is listening. </Abstract>
				</Parameter>
			</Parameters>

			<Anchor>//api/name/couchbaseMobile:didStart:</Anchor>
		</Token>

		<Token>
			<TokenIdentifier>//apple_ref/occ/intfm/CouchbaseDelegate/couchbaseMobile:failedToStart:</TokenIdentifier>
			<Abstract type="html">Called after a CouchbaseMobile instance fails to start up.</Abstract>
			<DeclaredIn>CouchbaseMobile.h</DeclaredIn>

			<Declaration>- (void)couchbaseMobile:(CouchbaseMobile *)couchbase failedToStart:(NSError *)error</Declaration>
			<Parameters>
				<Parameter>
					<Name>couchbase</Name>
					<Abstract type="html">The instance of CouchbaseMobile.</Abstract>
				</Parameter><Parameter>
					<Name>error</Name>
					<Abstract type="html">The error that occurred. </Abstract>
				</Parameter>
			</Parameters>

			<Anchor>//api/name/couchbaseMobile:failedToStart:</Anchor>
		</Token>

	</File>
</Tokens>


text:
    {                        \
    if( x != NULL )        \
	    {                      \
      delete x;            \
	  x = NULL;              \
	    }                      \
    }

// Deletes an array of buffers
#define RELEASE_ARRAY( x ) \
    {                              \
    if( x != NULL )              \
	    {                            \
      delete[] x;                \
	  x = NULL;                    \
	    }                            \
                              \
    }

#define IN_RANGE( value, min, max ) ( ((value) >= (min) && (value) <= (max)) ? 1 : 0 )
#define MIN( a, b ) ( ((a) < (b)) ? (a) : (b) )
#define MAX( a, b ) ( ((a) > (b)) ? (a) : (b) )
#define TO_BOOL( a )  ( (a != 0) ? true : false )

typedef unsigned int uint;
typedef unsigned __int32 uint32;
typedef unsigned __int64 uint64;
typedef unsigned char uchar;

template <class VALUE_TYPE> void SWAP(VALUE_TYPE& a, VALUE_TYPE& b)
{
	VALUE_TYPE tmp = a;
	a = b;
	b = tmp;
}

// Standard string size
#define SHORT_STR	32
#define MID_STR		255
#define HUGE_STR	8192

// Joins a path and file
inline const char* const PATH(const char* folder, const char* file)
{
	static char path[MID_STR];
	sprintf_s(path, MID_STR, "%s/%s", folder, file);
	return path;
}

// Performance macros
#define PERF_START(timer) timer.Start()
#define PERF_PEEK(timer) LOG("%s took %f ms", __FUNCTION__, timer.ReadMs())

//some usefull str
//doing that, they are created only one time
static const std::string empty_char = "";
static const std::string password_char = "*";
static const std::string true_str = "true";
static const std::string false_str = "false";
static const std::string left_str = "left";
static const std::string right_str = "right";

static const SDL_Rect rect_button = { 0,0,32,32 };
static const SDL_Rect rect_pressed_button = { 192,64,32,32 };
static const SDL_Rect rect_movable_block = { 96,0,32,32 };
static const SDL_Rect rect_block = { 64,0,32,32 };
static const SDL_Rect rect_Heart = { 128,0,32,32 };
static const SDL_Rect rect_jar = { 160,0,32,32 };
static const SDL_Rect rect_key = { 192,0,16,32 };
static const SDL_Rect rect_boss_key = { 208,0,32,32 };
static const SDL_Rect rect_sign = { 144,32,32,32 };
static const SDL_Rect rect_lever_blue = { 176,32,32,32 };
static const SDL_Rect rect_lever_red = { 208,32,32,32 };
static const SDL_Rect rect_lever_block_blue_off = { 0,64,32,32 };
static const SDL_Rect rect_lever_block_blue_on = { 32,64,32,32 };
static const SDL_Rect rect_lever_block_red_off = { 64,64,32,32 };
static const SDL_Rect rect_lever_block_red_on = { 96,64,32,32 };
static const SDL_Rect rect_chest_close = { 128,64,32,32 };
static const SDL_Rect rect_chest_open = { 160,64,32,32 };
static const SDL_Rect rect_Giant_chest_close = { 0,96,64,48 };
static const SDL_Rect rect_Giant_chest_open = { 64,96,64,48 };
static const SDL_Rect rect_door_down = { 240,-1,64,50 };
static const SDL_Rect rect_door_up = { 304 ,144,64,50 };
static const SDL_Rect rect_door_right = {367 ,0,48,64 };
static const SDL_Rect rect_door_left = { 415 ,0,48,64};
static const SDL_Rect rect_double_button_idle = { 128,208,64,64 };
static const SDL_Rect rect_double_button_one = { 64,208,64,64 };
static const SDL_Rect rect_double_button_two = { 0,208,64,64 };

static const SDL_Rect rect_arrow_up = {158,96,10,30};
static const SDL_Rect rect_arrow_down = { 168,96,10,30 };
static const SDL_Rect rect_arrow_left = { 128,106,30,10 };
static const SDL_Rect rect_arrow_right =  {128, 96, 30, 10};

static const SDL_Rect rect_diana_right_idle = { 192,176,32,32 };
static const SDL_Rect rect_diana_right_active = { 192,208,32,32 };
static const SDL_Rect rect_diana_left_idle = { 224,176,32,32 };
static const SDL_Rect rect_diana_left_active = { 224,208,32,32 };
static const SDL_Rect rect_diana_up_active = { 192,240,32,32 };
static const SDL_Rect rect_diana_up_idle = { 224,240,32,32 };
static const SDL_Rect rect_diana_down_active = { 256,240,32,32 };
static const SDL_Rect rect_diana_down_idle = {288,240,32,32 };

static const SDL_Rect rect_red_block = { 160,272,32,32 };
static const SDL_Rect rect_yellow_block = { 192,272,32,32 };
static const SDL_Rect rect_green_block = { 128,304,32,32 };
static const SDL_Rect rect_blue_block = { 160,304,32,32 };

static const SDL_Rect rect_red_button_idle = {0,272,32,32};
static const SDL_Rect rect_blue_button_idle = { 64,272,32,32 };
static const SDL_Rect rect_green_button_idle = { 0,304,32,32 };
static const SDL_Rect rect_yellow_button_idle = { 64,304,32,32 };

static const SDL_Rect rect_red_button_pressed = { 32,272,32,32 };
static const SDL_Rect rect_blue_button_pressed = { 96,272,32,32 };
static const SDL_Rect rect_green_button_pressed = { 32,304,32,32 };
static const SDL_Rect rect_yellow_button_pressed = { 96,304,32,32 };

static const SDL_Rect rect_bridge = { 464,0,96,118 };
static const SDL_Rect rect_heart_healing = { 191,95,32,32 };
static const SDL_Rect rect_bomb = { 224,272,32,32 };
static const SDL_Rect explosion1 = { 0,400,94,102 };
static const SDL_Rect smoke = { 187,501,94,81 };
static const SDL_Rect rect_bush = { 0,336,32,32 };

static const SDL_Rect rect_double_button_music_pressed = { 256,272,64,64 };
static const SDL_Rect rect_double_button_music_one = { 320,272,64,64 };
static const SDL_Rect rect_double_button_music_idle = { 384,272,64,64 };

static const SDL_Rect rect_double_red_button_pressed = { 448,272,64,64 };
static const SDL_Rect rect_double_red_button_one = { 512,272,64,64 };
static const SDL_Rect rect_double_red_button_idle = { 576,272,64,64 };

#endif


text:
#include "kaa/bootstrap/BootstrapTransport.hpp"

#include <set>

#include "kaa/channel/IKaaChannelManager.hpp"
#include "kaa/bootstrap/IBootstrapManager.hpp"

namespace kaa {

BootstrapTransport::BootstrapTransport(IKaaChannelManager& channelManager, IBootstrapManager &bootstrapManager, IKaaClientContext &context)
    : AbstractKaaTransport(channelManager, context)
    , requestId_(0)
    , bootstrapManager_(bootstrapManager)
{

}

void BootstrapTransport::sync()
{
    syncByType();
}

std::shared_ptr<BootstrapSyncRequest> BootstrapTransport::createBootstrapSyncRequest()
{
    std::shared_ptr<BootstrapSyncRequest> sync;

    const auto& channels = channelManager_.getChannels();

    if (channels.size()) {
        /**
         * To avoid duplicates.
         */
        std::set<TransportProtocolId> protocolIds;

        for (const auto& channel : channels) {
            protocolIds.insert(channel->getTransportProtocolId());
        }

        sync.reset(new BootstrapSyncRequest);
        sync->requestId = ++requestId_;
        sync->supportedProtocols.reserve(protocolIds.size());

        ProtocolVersionPair protocolVersion;
        for (auto& protocolId : protocolIds) {
            protocolVersion.id = protocolId.getId();
            protocolVersion.version = protocolId.getVersion();

            sync->supportedProtocols.push_back(protocolVersion);
        }
    }

    return sync;
}

void BootstrapTransport::onBootstrapResponse(const BootstrapSyncResponse& response)
{
    bootstrapManager_.onServerListUpdated(response.supportedProtocols);
}

}  // namespace kaa


text:
using System;
using System.Globalization;
using System.Text;
using Common.Logging;
using ToolKit.Validation;

namespace ToolKit.Xml
{
    /// <summary>
    /// This class contains two static methods to encode and decode text to be compatible with being
    /// put into an XML document.
    /// </summary>
    public static class XmlEncoder
    {
        private static readonly ILog _log = LogManager.GetLogger(typeof(XmlEncoder));

        /// <summary>
        /// Decodes a string to remove XML entity markups.
        /// </summary>
        /// <param name="inputText">Input text containing entity markups.</param>
        /// <returns>an decoded string.</returns>
        public static string Decode(string inputText)
        {
            inputText = Check.NotEmpty(inputText, nameof(inputText));

            // If the string doesn't have a & character, it doesn't have any entities.
            if (inputText.IndexOf('&') < 0)
            {
                return inputText;
            }

            // If the string contains a & but not a ;, it doesn't have any entities.
            if ((inputText.IndexOf('&') > -1)
                && (inputText.IndexOf(';') < 0))
            {
                return inputText;
            }

            var sb = new StringBuilder();

            for (var i = 0; i < inputText.Length; i++)
            {
                var ch = inputText[i];
                if (ch != '&')
                {
                    sb.AppendFormat(CultureInfo.InvariantCulture, "{0}", ch);
                    continue;
                }

                var endOfEntity = inputText.IndexOfAny(new char[] { ';', '&' }, i + 1);

                // If the end marker is not ; then ignore this "entity" and continue on
                if ((endOfEntity > 0) && (inputText[endOfEntity] == '&'))
                {
                    sb.AppendFormat(CultureInfo.InvariantCulture, "{0}", ch);
                    continue;
                }

                var entity = inputText.Substring(i, endOfEntity + 1 - i);

                if ((entity.Length > 1) && (entity[1] == '#'))
                {
                    entity = entity.Substring(2, entity.Length - 3);
                    try
                    {
                        if ((entity[0] == 'x') || (entity[0] == 'X'))
                        {
                            // It's encoded in hexadecimal
                            ch = (char)int.Parse(
                                entity.Substring(2),
                                NumberStyles.AllowHexSpecifier,
                                CultureInfo.InvariantCulture);
                        }
                        else
                        {
                            // It's encoded in decimal
                            ch = (char)int.Parse(entity, CultureInfo.InvariantCulture);
                        }
                    }
                    catch (FormatException fex)
                    {
                        _log.Warn($"{inputText}: {fex.Message}", fex);
                        continue;
                    }
                    catch (ArgumentException aex)
                    {
                        _log.Warn(inputText + ": " + aex.Message, aex);
                        continue;
                    }
                }
                else
                {
                    // It's not an Entity Number but instead an Entity Name... Keep in mind that this
                    // is not the entire list of named entities. This Decode method is designed to
                    // decode only what was encoded with this class...
                    switch (entity.ToString())
                    {
                        case "&":
                            ch = '&';
                            break;

                        case "<":
                            ch = '<';
                            break;

                        case ">":
                            ch = '>';
                            break;

                        case "'":
                            ch = '\'';
                            break;

                        case """:
                            ch = '"';
                            break;

                        case " ":
                            ch = ' ';
                            break;

                        default:

                            // I don't know what it is...
                            sb.Append(entity);
                            continue;
                    }
                }

                i = endOfEntity;
                sb.AppendFormat(CultureInfo.InvariantCulture, "{0}", ch);
            }

            return sb.ToString();
        }

        /// <summary>
        /// Encodes a string to replace certain types of characters that are not "XML-Friendly".
        /// </summary>
        /// <param name="inputText">Input text to be encoded.</param>
        /// <returns>an encoded string.</returns>
        public static string Encode(string inputText)
        {
            inputText = Check.NotNull(inputText, nameof(inputText));
            var sb = new StringBuilder();

            foreach (var item in inputText)
            {
                if ((item > 31) && (item < 127))
                {
                    switch (item)
                    {
                        case '&':
                            sb.Append("&");
                            break;

                        case '<':
                            sb.Append("<");
                            break;

                        case '>':
                            sb.Append(">");
                            break;

                        case '\'':
                            sb.Append("'");
                            break;

                        case '"':
                            sb.Append(""");
                            break;

                        default:
                            sb.Append(item.ToString(CultureInfo.InvariantCulture));
                            break;
                    }
                }
                else
                {
                    sb.AppendFormat(CultureInfo.InvariantCulture, "&#{0};", (int)item);
                }
            }

            return sb.ToString().Replace("  ", "  ");
        }
    }
}


text:
#include "FairyGUIMacros.h"
#include "cocos2d.h"
#include "PackageItem.h"

NS_FGUI_BEGIN

class BitmapFont : public cocos2d::Font
{
public:
    BitmapFont();
    virtual ~BitmapFont();

    static BitmapFont* create();

    virtual int* getHorizontalKerningForTextUTF32(const std::u32string& text, int &outNumLetters) const override;
    virtual cocos2d::FontAtlas *createFontAtlas() override { return _fontAtlas; }
    void releaseAtlas() { _fontAtlas->release(); }
    void setFontSize(float fontSize) {}
    int getOriginalFontSize()const { return _originalFontSize; }
    bool isResizable() { return _resizable; }
    bool canTint() { return _canTint; }

private:
    float _originalFontSize;
    bool _resizable;
    bool _canTint;
    cocos2d::FontAtlas* _fontAtlas;

    friend class UIPackage;
};

NS_FGUI_END

#endif


text:
@interface BFTask (LoadLessonContent)

-(BFTask *)loadLessonContent;

@end


text:
class AddLastGeneratedToBuildpacks < ActiveRecord::Migration
  def change
    add_column :buildpacks, :last_weighed, :datetime

    Buildpack.all.each do |buildpack|
      buildpack.update_attributes!(last_weighed: Time.now)
    end
  end
end


text:
<resources>
    <!-- Default screen margins, per the Android Design guidelines. -->
    <dimen name="activity_horizontal_margin">16dp</dimen>
    <dimen name="activity_vertical_margin">16dp</dimen>

    <dimen name="small_margin">8dp</dimen>

    <dimen name="movie_detail_thumbnail_width">88dp</dimen>
    <dimen name="movie_detail_thumbnail_height">132dp</dimen>

    <dimen name="text_highlight">18sp</dimen>
    <dimen name="text_huge">24sp</dimen>
</resources>


text:
import tempfile
import subprocess
import signal
import os
import sys

G4APP_PATH = os.getenv("G4APP_PATH") or "."
G4APP_NAME = os.getenv("G4APP_NAME") or "g4"

def kill(_signal, _frame):
    '''A special method to be substituted for default interrupt signal handling.

    It passes interrupt signal to the executed process.'''
    global g4process
    g4process.terminate()
    g4process = None
    signal.signal(signal.SIGINT, signal.SIG_DFL)

def execute(macro, macro_path=None, delete_macro_file=True, valgrind=False, gdb=False):
    '''Create a temporary file from the commands and run it.

    :param macro: A Macro to write and execute.
    :param macro_path: A path where the macro file should be written.
        If not set, a temporary file will be created.
    :param delete_macro_file: If set, delete macro file after execution.
    :param valgrind: Run the application in valgrind for debugging.
    :param gdb: Run the application in gdb for debugging.
    '''
    global g4process

    # TODO: Make cwd and application name configurable
    # TODO: Ensure all paths are treated well (Escape them)
    if macro_path:
        f = open(macro_path, "w")
    else:
        f = tempfile.NamedTemporaryFile(suffix=".mac", delete=False)
        macro_path = f.name
    # TODO: Change to real logging
    print "Writing macro to {}".format( macro_path )
    print
    print "*" * 80
    macro.write(sys.stdout)
    print "*" * 80

    print
    sys.stdout.flush()
    macro.write(f)
    f.close()
    signal.signal(signal.SIGINT, kill) # Bubble interruption to subprocess (and kill it)
    if valgrind:
        g4process = subprocess.Popen(["valgrind", "./" + G4APP_NAME, macro_path], cwd=G4APP_PATH)
    elif gdb:
        g4process = subprocess.Popen(["gdb", "./" + G4APP_NAME, "-ex", "run {}".format(macro_path)], cwd=G4APP_PATH)
    else:
        g4process = subprocess.Popen(["./" + G4APP_NAME, macro_path], cwd=G4APP_PATH)
    g4process.wait()
    signal.signal(signal.SIGINT, signal.SIG_DFL) # Restore default interruption behaviour
    if delete_macro_file:
        os.remove( macro_path )


text:
all: python

python:
	cp main.py washing-machine-python
	chmod u+x washing-machine-python

clean:
	rm --force washing-machine-*


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace RippleCommonUtilities
{
    public static class Globals
    {
        public static int PreviouslySelectedBox;
        public static int CurrentlySelectedBox;
        public static RippleSystemStates currentAppState;
        public static DateTime currentBoxTimeStamp;
        public static int CurrentlySelectedParent;
        public static DateTime currentUserTimestamp;
        public static int OptionSelected;
        public static String SelectedOptionFullName;
        public static RippleScreenResoultion CurrentResolution = new RippleScreenResoultion();
        public static String EmpAlias;
        public static String UserName;

        static Globals()
        {
            PreviouslySelectedBox = -1;
            OptionSelected = -1;
            CurrentlySelectedBox = -1;
            currentAppState = RippleSystemStates.NoUser;
            CurrentlySelectedParent = 0;
            currentBoxTimeStamp = DateTime.Now;
            currentUserTimestamp = DateTime.Now;
            SelectedOptionFullName = String.Empty;
            EmpAlias = String.Empty;
            UserName = String.Empty;
        }

        public static void ResetGlobals()
        {
            PreviouslySelectedBox = -1;
            CurrentlySelectedBox = -1;
            currentAppState = RippleSystemStates.NoUser;
            CurrentlySelectedParent = 0;
            currentBoxTimeStamp = DateTime.Now;
            currentUserTimestamp = DateTime.Now;
            EmpAlias = String.Empty;
            SelectedOptionFullName = String.Empty;
            UserName = String.Empty;
        }
    }

}


text:
<?php
function makeyogurt($type = "acidophilus", $flavour)
{
    return "Making a bowl of $type $flavour.\n";
}

echo makeyogurt("raspberry");   // won't work as expected
?>


text:
module Autoparts
  module Packages
    class Scons < Package
      name 'scons'
      version '2.3.1'
      description 'SCons: an Open Source software construction tool—that is, a next-generation build tool. '
      category Category::DEVELOPMENT_TOOLS

      source_url 'https://downloads.sourceforge.net/scons/scons-2.3.1.tar.gz'
      source_sha1 '775e715e49fe5fd8e1d29551a296fdc9267509e7'
      source_filetype 'tar.gz'

      def install
        Dir.chdir(name_with_version) do
          execute "/usr/bin/python", "setup.py", "install",
             "--prefix=#{prefix_path}",
             "--standalone-lib",
             # SCons gets handsy with sys.path---`scons-local` is one place it
             # will look when all is said and done.
             "--install-lib=#{lib_path}/scons-local",
             "--install-scripts=#{bin_path}",
             "--install-data=#{lib_path}",
             "--no-version-script", "--no-install-man"

             # Re-root scripts to libexec so they can import SCons and symlink back into
             # bin. Similar tactics are used in the duplicity formula.
             bin_path.children.each do |p|
               execute 'mv', p.to_s, "#{lib_path}/#{p.basename}.py"
               execute 'ln', '-s', "#{lib_path}/#{p.basename}.py", "#{bin_path}/#{p.basename}"
             end
        end
      end
    end
  end
end


text:
<!doctype html>

    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width,  initial-scale=1.0, maximum-scale=1.0, user-scalable=no">
    <title>layer control test</title>
    <link rel="stylesheet" href="http://cdn.leafletjs.com/leaflet-0.7.3/leaflet.css" />

        <button class='toggleButton' value='play'>Play</button>


text:
@interface PFProjectCellStyleModel : NSObject

@property (nonatomic) BOOL isIOS;
@property (nonatomic) BOOL isAndroid;
@property (strong, nonatomic) UIImage *iconApp;
@property (strong, nonatomic) NSString *name;
@property (strong, nonatomic) NSArray *projectDetails;

@end


text:
<?php

declare(strict_types=1);

namespace GrumPHPTest\Unit\Task;

use GrumPHP\Task\Context\GitPreCommitContext;
use GrumPHP\Task\Context\RunContext;
use GrumPHP\Task\PhpMd;
use GrumPHP\Task\TaskInterface;
use GrumPHP\Test\Task\AbstractExternalTaskTestCase;

class PhpMdTest extends AbstractExternalTaskTestCase
{
    protected function provideTask(): TaskInterface
    {
        return new PhpMd(
            $this->processBuilder->reveal(),
            $this->formatter->reveal()
        );
    }

    public function provideConfigurableOptions(): iterable
    {
        yield 'defaults' => [
            [],
            [
                'whitelist_patterns' => [],
                'exclude' => [],
                'report_format' => 'text',
                'ruleset' => ['cleancode', 'codesize', 'naming'],
                'triggered_by' => ['php'],
            ]
        ];

        yield 'invalidcase' => [
            [
                'whitelist_patterns' => 'thisisnotanarray'
            ],
            null
        ];
    }

    public function provideRunContexts(): iterable
    {
        yield 'run-context' => [
            true,
            $this->mockContext(RunContext::class)
        ];

        yield 'pre-commit-context' => [
            true,
            $this->mockContext(GitPreCommitContext::class)
        ];

        yield 'other' => [
            false,
            $this->mockContext()
        ];
    }

    public function provideFailsOnStuff(): iterable
    {
        yield 'exitCode1' => [
            [],
            $this->mockContext(RunContext::class, ['hello.php']),
            function () {
                $this->mockProcessBuilder('phpmd', $process = $this->mockProcess(1));
                $this->formatter->format($process)->willReturn('nope');
            },
            'nope'
        ];
    }

    public function providePassesOnStuff(): iterable
    {
        yield 'exitCode0' => [
            [],
            $this->mockContext(RunContext::class, ['hello.php']),
            function () {
                $this->mockProcessBuilder('phpmd', $this->mockProcess(0));
            }
        ];
    }

    public function provideSkipsOnStuff(): iterable
    {
        yield 'no-files' => [
            [],
            $this->mockContext(RunContext::class),
            function () {}
        ];
        yield 'no-files-after-triggered-by' => [
            [],
            $this->mockContext(RunContext::class, ['notaphpfile.txt']),
            function () {}
        ];
        yield 'no-files-after-whitelist' => [
            [
                'whitelist_patterns' => ['src/'],
            ],
            $this->mockContext(RunContext::class, ['test/file.php']),
            function () {}
        ];
    }

    public function provideExternalTaskRuns(): iterable
    {
        yield 'defaults' => [
            [],
            $this->mockContext(RunContext::class, ['hello.php', 'hello2.php']),
            'phpmd',
            [
                'hello.php,hello2.php',
                'text',
                'cleancode,codesize,naming',
            ]
        ];

        yield 'excludes' => [
            [
                'exclude' => ['hello.php', 'hello2.php'],
            ],
            $this->mockContext(RunContext::class, ['hello.php', 'hello2.php']),
            'phpmd',
            [
                'hello.php,hello2.php',
                'text',
                'cleancode,codesize,naming',
                '--exclude',
                'hello.php,hello2.php',
            ]
        ];

        yield 'rulesets' => [
            [
                'ruleset' => ['cleancode'],
            ],
            $this->mockContext(RunContext::class, ['hello.php', 'hello2.php']),
            'phpmd',
            [
                'hello.php,hello2.php',
                'text',
                'cleancode',
            ]
        ];

        yield 'report_formats' => [
            [
                'report_format' => 'ansi',
            ],
            $this->mockContext(RunContext::class, ['hello.php', 'hello2.php']),
            'phpmd',
            [
                'hello.php,hello2.php',
                'ansi',
                'cleancode,codesize,naming',
            ]
        ];
    }
}