text:
package com.google.cloud.hadoop.util.testing;

import static com.google.api.client.http.HttpStatusCodes.STATUS_CODE_NOT_FOUND;
import static com.google.api.client.http.HttpStatusCodes.STATUS_CODE_SERVER_ERROR;
import static com.google.api.client.http.HttpStatusCodes.STATUS_CODE_SERVICE_UNAVAILABLE;
import static com.google.cloud.hadoop.util.ApiErrorExtractor.GLOBAL_DOMAIN;
import static com.google.cloud.hadoop.util.ApiErrorExtractor.RATE_LIMITED_REASON;
import static com.google.cloud.hadoop.util.ApiErrorExtractor.USAGE_LIMITS_DOMAIN;
import static com.google.common.net.HttpHeaders.CONTENT_ENCODING;
import static com.google.common.net.HttpHeaders.CONTENT_LENGTH;
import static com.google.common.net.HttpHeaders.CONTENT_RANGE;
import static java.nio.charset.StandardCharsets.UTF_8;

import com.google.api.client.googleapis.json.GoogleJsonError;
import com.google.api.client.http.HttpStatusCodes;
import com.google.api.client.http.LowLevelHttpRequest;
import com.google.api.client.http.LowLevelHttpResponse;
import com.google.api.client.json.GenericJson;
import com.google.api.client.json.Json;
import com.google.api.client.json.gson.GsonFactory;
import com.google.api.client.testing.http.MockHttpTransport;
import com.google.api.client.testing.http.MockLowLevelHttpRequest;
import com.google.api.client.testing.http.MockLowLevelHttpResponse;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableMap;
import com.google.common.io.CharStreams;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.Map;
import java.util.function.Supplier;

/** Utility methods for testing with {@link MockHttpTransport} */
public final class MockHttpTransportHelper {

  /** HTTP JSON API error responses */
  public enum ErrorResponses {
    GONE(410, STATUS_CODE_SERVICE_UNAVAILABLE, "backendError", "Backend Error", GLOBAL_DOMAIN),
    NOT_FOUND(STATUS_CODE_NOT_FOUND, "notFound", "Not Found", GLOBAL_DOMAIN),
    RANGE_NOT_SATISFIABLE(
        416, "requestedRangeNotSatisfiable", "Request range not satisfiable", GLOBAL_DOMAIN),
    RATE_LIMITED(429, RATE_LIMITED_REASON, "The total number of changes ...", USAGE_LIMITS_DOMAIN),
    SERVER_ERROR(STATUS_CODE_SERVER_ERROR, "backendError", "Backend Error", GLOBAL_DOMAIN);

    private final int responseCode;
    private final int errorCode;
    private final String errorReason;
    private final String errorMessage;
    private final String errorDomain;

    ErrorResponses(int statusCode, String errorReason, String errorMessage, String errorDomain) {
      this(statusCode, statusCode, errorReason, errorMessage, errorDomain);
    }

    ErrorResponses(
        int responseCode,
        int errorCode,
        String errorReason,
        String errorMessage,
        String errorDomain) {
      this.responseCode = responseCode;
      this.errorCode = errorCode;
      this.errorReason = errorReason;
      this.errorMessage = errorMessage;
      this.errorDomain = errorDomain;
    }

    public int getResponseCode() {
      return responseCode;
    }

    public int getErrorCode() {
      return errorCode;
    }

    public String getErrorReason() {
      return errorReason;
    }

    public String getErrorMessage() {
      return errorMessage;
    }

    public String getErrorDomain() {
      return errorDomain;
    }
  }

  private static final int UNKNOWN_CONTENT_LENGTH = -1;

  private MockHttpTransportHelper() {}

  public static MockHttpTransport mockTransport(Object... responsesIn) {
    return new MockHttpTransport() {
      int responsesIndex = 0;
      final Object[] responses = responsesIn;

      @Override
      public LowLevelHttpRequest buildRequest(String method, String url) {
        return new MockLowLevelHttpRequest() {
          @Override
          public LowLevelHttpResponse execute() throws IOException {
            Object response = responses[responsesIndex++];
            if (response instanceof IOException) {
              throw (IOException) response;
            }
            if (response instanceof RuntimeException) {
              throw (RuntimeException) response;
            }
            return (LowLevelHttpResponse) response;
          }
        };
      }
    };
  }

  public static MockHttpTransport mockBatchTransport(
      int requestsPerBatch, LowLevelHttpResponse... responses) {
    return new MockHttpTransport() {
      int responsesIndex = 0;
      int responseBatchCounter = 0;

      @Override
      public LowLevelHttpRequest buildRequest(String method, String url) {
        return new MockLowLevelHttpRequest() {
          @Override
          public LowLevelHttpResponse execute() {
            responseBatchCounter++;
            String boundary = "batch_pK7JBAk73-E=_AA5eFwv4m2Q=";
            String contentId = "";

            MockLowLevelHttpResponse response =
                new MockLowLevelHttpResponse()
                    .setStatusCode(HttpStatusCodes.STATUS_CODE_OK)
                    .setContentType("multipart/mixed; boundary=" + boundary);

            StringBuilder batchResponse = new StringBuilder();
            int remainingResponses = responses.length - responsesIndex;
            int responsesInBatch =
                Math.min((responseBatchCounter * requestsPerBatch), remainingResponses);
            for (int i = 0; i < responsesInBatch; i++) {
              try {
                LowLevelHttpResponse resp = responses[responsesIndex++];
                batchResponse
                    .append(String.format("\n--%s\n", boundary))
                    .append("Content-Type: application/http\n")
                    .append(String.format("Content-ID: <response-%s%d>\n\n", contentId, i + 1))
                    .append(String.format("HTTP/1.1 %s OK\n", resp.getStatusCode()))
                    .append(String.format("Content-Length: %s\n\n", resp.getContentLength()))
                    .append(CharStreams.toString(new InputStreamReader(resp.getContent(), UTF_8)))
                    .append('\n');
              } catch (IOException e) {
                throw new RuntimeException(e);
              }
            }

            batchResponse.append(String.format("\n--%s--\n", boundary));

            return response.setContent(batchResponse.toString());
          }
        };
      }
    };
  }

  public static MockLowLevelHttpResponse emptyResponse(int statusCode) {
    return new MockLowLevelHttpResponse().setStatusCode(statusCode);
  }

  public static MockLowLevelHttpResponse dataRangeResponse(
      byte[] content, long rangeStart, long totalSize) {
    long rangeEnd = rangeStart + content.length - 1;
    return dataResponse(content)
        .addHeader(CONTENT_RANGE, rangeStart + "-" + rangeEnd + "/" + totalSize);
  }

  public static MockLowLevelHttpResponse jsonDataResponse(Object object) throws IOException {
    return dataResponse(GsonFactory.getDefaultInstance().toByteArray(object));
  }

  public static MockLowLevelHttpResponse dataResponse(byte[] content) {
    return dataResponse(ImmutableMap.of(CONTENT_LENGTH, String.valueOf(content.length)), content);
  }

  public static MockLowLevelHttpResponse dataResponse(Map<String, Object> headers, byte[] content) {
    return setHeaders(new MockLowLevelHttpResponse(), headers, content.length).setContent(content);
  }

  public static MockLowLevelHttpResponse jsonErrorResponse(ErrorResponses errorResponse)
      throws IOException {
    GoogleJsonError.ErrorInfo errorInfo = new GoogleJsonError.ErrorInfo();
    errorInfo.setReason(errorResponse.getErrorReason());
    errorInfo.setDomain(errorResponse.getErrorDomain());
    errorInfo.setFactory(GsonFactory.getDefaultInstance());

    GoogleJsonError jsonError = new GoogleJsonError();
    jsonError.setCode(errorResponse.getErrorCode());
    jsonError.setErrors(ImmutableList.of(errorInfo));
    jsonError.setMessage(errorResponse.getErrorMessage());
    jsonError.setFactory(GsonFactory.getDefaultInstance());

    GenericJson errorResponseJson = new GenericJson();
    errorResponseJson.set("error", jsonError);
    errorResponseJson.setFactory(GsonFactory.getDefaultInstance());

    return new MockLowLevelHttpResponse()
        .setContent(errorResponseJson.toPrettyString())
        .setContentType(Json.MEDIA_TYPE)
        .setStatusCode(errorResponse.getResponseCode());
  }

  public static MockLowLevelHttpResponse inputStreamResponse(
      String header, Object headerValue, InputStream content) {
    return inputStreamResponse(ImmutableMap.of(header, headerValue), content);
  }

  public static MockLowLevelHttpResponse inputStreamResponse(InputStream content) {
    return inputStreamResponse(ImmutableMap.of(), content);
  }

  public static MockLowLevelHttpResponse inputStreamResponse(
      Map<String, Object> headers, InputStream content) {
    return setHeaders(new MockLowLevelHttpResponse(), headers, UNKNOWN_CONTENT_LENGTH)
        .setContent(content);
  }

  /**
   * Return an arbitrary InputStream supplier. This function should only be used to simulate
   * arbitrary runtime behavior when calling {@code execute} and {@code executeMedia}.
   */
  public static MockLowLevelHttpResponse arbitraryInputStreamSupplier(
      Supplier<InputStream> supplier) {
    return new MockLowLevelHttpResponse() {
      @Override
      public InputStream getContent() {
        return supplier.get();
      }
    };
  }

  private static MockLowLevelHttpResponse setHeaders(
      MockLowLevelHttpResponse response, Map<String, Object> headers, long defaultContentLength) {
    Object contentLength = headers.getOrDefault(CONTENT_LENGTH, defaultContentLength);
    Object contentEncoding = headers.get(CONTENT_ENCODING);
    headers.forEach((h, hv) -> response.addHeader(h, String.valueOf(hv)));
    if (!response.getHeaderNames().contains("x-goog-generation")) {
      response.addHeader("x-goog-generation", "1");
    }
    return response
        .setContentLength(Long.parseLong(String.valueOf(contentLength)))
        .setContentEncoding(contentEncoding == null ? null : String.valueOf(contentEncoding));
  }
}


text:
package main

import (
	"fmt"
	"log"
	"net/http"
)

func MainHandler(writer http.ResponseWriter, request *http.Request) {
	request.ParseForm()
	name := "World"
	if val, ok := request.Form["name"]; ok {
		name = val[0]
	}
	fmt.Fprint(writer, "Hello ", name)
}

func main() {
	http.HandleFunc("/", MainHandler)
	if err := http.ListenAndServe(":8080", nil); err != nil {
		log.Fatal("ListenAndServer", err)
	}
}

redpajama_set_name: RedPajamaGithub


text:
This inspection reports JUnit 4.0 @Test methods in product source trees.
This most likely indicates programmer error, and can result in test code being shipped
into production.

Powered by InspectionGadgets


text:
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
  <modelVersion>4.0.0</modelVersion>
  <groupId>br.odb.minefield</groupId>
  <artifactId>minefield-cli</artifactId>
  <packaging>jar</packaging>
  <version>1.0-SNAPSHOT</version>
  <name>minefield</name>
  <url>http://www.montyprojects.com</url>
  <dependencies>
    <dependency>
      <groupId>br.odb</groupId>
      <artifactId>gameapp</artifactId>
      <version>1.0-SNAPSHOT</version>
    </dependency>

    <dependency>
      <groupId>br.odb.minefield</groupId>
      <artifactId>minefield-core</artifactId>
      <version>1.0-SNAPSHOT</version>
    </dependency>
  </dependencies>

	<properties>
		<maven.compiler.source>1.7</maven.compiler.source>
		<maven.compiler.target>1.7</maven.compiler.target>

	</properties>

	<build>
		<plugins>
			<plugin>
				<groupId>org.apache.maven.plugins</groupId>
				<artifactId>maven-surefire-plugin</artifactId>
				<version>2.8.1</version>
				<configuration>
					<include>**/*Spec.*</include>
					<include>**/*Test.*</include>
				</configuration>
			</plugin>
			<plugin>
			<groupId>
				org.codehaus.mojo
			</groupId>
			<artifactId>
				exec-maven-plugin
			</artifactId>
			<configuration>
				<mainClass>br.odb.minefield.MinefieldMainApp</mainClass>
			</configuration>
			</plugin>
		</plugins>
	</build>
</project>


text:
package ssdp

import (
	"net"
	"net/http"
	"testing"
)

func TestControlPoint(t *testing.T) {
	ifi := loopbackInterface()
	if ifi == nil {
		t.Skip("no available multicast network interface found")
	}
	mifs := []net.Interface{*ifi}
	var grps []string
	if supportsIPv4 {
		grps = append(grps, DefaultIPv4Group)
	}
	if supportsIPv6 {
		grps = append(grps, DefaultIPv6LinkLocalGroup)
	}

	for _, grp := range grps {
		ln := Listener{Group: grp}
		cp, err := ln.ListenControlPoint(mifs)
		if err != nil {
			t.Fatal(err)
		}
		hdlr := http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) {
			w.Write(nil)
		})
		go cp.Serve(hdlr)

		for _, ifi := range cp.Interfaces() {
			t.Logf("%v on %v", cp.GroupAddr(), ifi)
		}
		cp.Close()
	}
}


text:
class AuthSourcesController < ApplicationController
  layout 'admin'
  menu_item :ldap_authentication

  before_filter :require_admin
  before_filter :find_auth_source, :only => [:edit, :update, :test_connection, :destroy]

  def index
    @auth_source_pages, @auth_sources = paginate AuthSource, :per_page => 25
  end

  def new
    klass_name = params[:type] || 'AuthSourceLdap'
    @auth_source = AuthSource.new_subclass_instance(klass_name, params[:auth_source])
    render_404 unless @auth_source
  end

  def create
    @auth_source = AuthSource.new_subclass_instance(params[:type], params[:auth_source])
    if @auth_source.save
      flash[:notice] = l(:notice_successful_create)
      redirect_to auth_sources_path
    else
      render :action => 'new'
    end
  end

  def edit
  end

  def update
    if @auth_source.update_attributes(params[:auth_source])
      flash[:notice] = l(:notice_successful_update)
      redirect_to auth_sources_path
    else
      render :action => 'edit'
    end
  end

  def test_connection
    begin
      @auth_source.test_connection
      flash[:notice] = l(:notice_successful_connection)
    rescue Exception => e
      flash[:error] = l(:error_unable_to_connect, e.message)
    end
    redirect_to auth_sources_path
  end

  def destroy
    unless @auth_source.users.exists?
      @auth_source.destroy
      flash[:notice] = l(:notice_successful_delete)
    end
    redirect_to auth_sources_path
  end

  def autocomplete_for_new_user
    results = AuthSource.search(params[:term])

    render :json => results.map {|result| {
      'value' => result[:login],
      'label' => "#{result[:login]} (#{result[:firstname]} #{result[:lastname]})",
      'login' => result[:login].to_s,
      'firstname' => result[:firstname].to_s,
      'lastname' => result[:lastname].to_s,
      'mail' => result[:mail].to_s,
      'auth_source_id' => result[:auth_source_id].to_s
    }}
  end

  private

  def find_auth_source
    @auth_source = AuthSource.find(params[:id])
  rescue ActiveRecord::RecordNotFound
    render_404
  end
end


text:
var AssetsItemView = require('./assets_item_view');

module.exports = AssetsItemView.extend({

  events: {
    'click': '_onClick'
  },

  _deleteAsset: function() {},
  _openDropdown: function() {}

});


text:
<!doctype html>

    <title>Code coverage report for api/controllers/tips.js</title>
    <meta charset="utf-8" />
    <link rel="stylesheet" href="../../prettify.css" />
    <link rel="stylesheet" href="../../base.css" />
    <meta name="viewport" content="width=device-width, initial-scale=1">

      All files / api/controllers tips.js

        57.14%
        Statements
        4/7

        100%
        Branches
        0/0

        0%
        Functions
        0/1

        57.14%
        Lines
        4/7

1
2
3
4
5
6
7
8
9
10
11
12
13
14	1x
1x
1x

1x

const {promisify} = require('util');
const fs = require('fs');
const readFile = promisify(fs.readFile);

async function tip(req, res) {
  const tips = await readFile('../json/tips.json');
  const tip = tips[Math.floor(Math.random() * (tips.length - 1))];
  res.status(200).json({tip});
}

module.exports = {
  tip
}

  Code coverage
  generated by istanbul at Thu Nov 30 2017 16:54:37 GMT+0100 (CET)


text:
package com.foobarsite.core;

import static playn.core.PlayN.assets;
import static playn.core.PlayN.graphics;
import static playn.core.PlayN.pointer;

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

import playn.core.Game;
import playn.core.GroupLayer;
import playn.core.Image;
import playn.core.ImageLayer;
import playn.core.Pointer;

public class PlayGameMain extends Game.Default {

	public static int UPDATE_RATE = 33;
	private GroupLayer peaLayer;
	private List<Pea> peas = new ArrayList<Pea>(0);

	public PlayGameMain() {
		super(UPDATE_RATE); // call update every 33ms (30 times per second)
	}

	@Override
	public void init() {
		// create and add background image layer
		Image bgImage = assets().getImage("images/bg.png");
		ImageLayer bgLayer = graphics().createImageLayer(bgImage);
		graphics().rootLayer().add(bgLayer);

		// create a group layer to hold the peas
		peaLayer = graphics().createGroupLayer();
		graphics().rootLayer().add(peaLayer);

		// preload the pea image into the asset manager cache
		assets().getImage(Pea.IMAGE);

		// add a listener for pointer (mouse, touch) input
		pointer().setListener(new Pointer.Adapter() {
			@Override
			public void onPointerEnd(Pointer.Event event) {
				Pea pea = new Pea(peaLayer, event.x(), event.y());
				peas.add(pea);
			}
		});

	}

	@Override
	public void update(int delta) {
		for (Pea pea : peas) {
			pea.update(delta);
		}
	}

	@Override
	public void paint(float alpha	) {
		for (Pea pea : peas) {
			pea.paint(alpha);
		}
	}
}


text:
'use strict';

Object.defineProperty(exports, "__esModule", {
    value: true
});
exports.default = retry;

var _wrapAsync = require('./internal/wrapAsync.js');

var _wrapAsync2 = _interopRequireDefault(_wrapAsync);

var _promiseCallback = require('./internal/promiseCallback.js');

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }

function constant(value) {
    return function () {
        return value;
    };
}

/**
 * Attempts to get a successful response from `task` no more than `times` times
 * before returning an error. If the task is successful, the `callback` will be
 * passed the result of the successful task. If all attempts fail, the callback
 * will be passed the error and result (if any) of the final attempt.
 *
 * @name retry
 * @static
 * @memberOf module:ControlFlow
 * @method
 * @category Control Flow
 * @see [async.retryable]{@link module:ControlFlow.retryable}
 * @param {Object|number} [opts = {times: 5, interval: 0}| 5] - Can be either an
 * object with `times` and `interval` or a number.
 * * `times` - The number of attempts to make before giving up.  The default
 *   is `5`.
 * * `interval` - The time to wait between retries, in milliseconds.  The
 *   default is `0`. The interval may also be specified as a function of the
 *   retry count (see example).
 * * `errorFilter` - An optional synchronous function that is invoked on
 *   erroneous result. If it returns `true` the retry attempts will continue;
 *   if the function returns `false` the retry flow is aborted with the current
 *   attempt's error and result being returned to the final callback.
 *   Invoked with (err).
 * * If `opts` is a number, the number specifies the number of times to retry,
 *   with the default interval of `0`.
 * @param {AsyncFunction} task - An async function to retry.
 * Invoked with (callback).
 * @param {Function} [callback] - An optional callback which is called when the
 * task has succeeded, or after the final failed attempt. It receives the `err`
 * and `result` arguments of the last attempt at completing the `task`. Invoked
 * with (err, results).
 * @returns {Promise} a promise if no callback provided
 *
 * @example
 *
 * // The `retry` function can be used as a stand-alone control flow by passing
 * // a callback, as shown below:
 *
 * // try calling apiMethod 3 times
 * async.retry(3, apiMethod, function(err, result) {
 *     // do something with the result
 * });
 *
 * // try calling apiMethod 3 times, waiting 200 ms between each retry
 * async.retry({times: 3, interval: 200}, apiMethod, function(err, result) {
 *     // do something with the result
 * });
 *
 * // try calling apiMethod 10 times with exponential backoff
 * // (i.e. intervals of 100, 200, 400, 800, 1600, ... milliseconds)
 * async.retry({
 *   times: 10,
 *   interval: function(retryCount) {
 *     return 50 * Math.pow(2, retryCount);
 *   }
 * }, apiMethod, function(err, result) {
 *     // do something with the result
 * });
 *
 * // try calling apiMethod the default 5 times no delay between each retry
 * async.retry(apiMethod, function(err, result) {
 *     // do something with the result
 * });
 *
 * // try calling apiMethod only when error condition satisfies, all other
 * // errors will abort the retry control flow and return to final callback
 * async.retry({
 *   errorFilter: function(err) {
 *     return err.message === 'Temporary error'; // only retry on a specific error
 *   }
 * }, apiMethod, function(err, result) {
 *     // do something with the result
 * });
 *
 * // to retry individual methods that are not as reliable within other
 * // control flow functions, use the `retryable` wrapper:
 * async.auto({
 *     users: api.getUsers.bind(api),
 *     payments: async.retryable(3, api.getPayments.bind(api))
 * }, function(err, results) {
 *     // do something with the results
 * });
 *
 */
const DEFAULT_TIMES = 5;
const DEFAULT_INTERVAL = 0;

function retry(opts, task, callback) {
    var options = {
        times: DEFAULT_TIMES,
        intervalFunc: constant(DEFAULT_INTERVAL)
    };

    if (arguments.length < 3 && typeof opts === 'function') {
        callback = task || (0, _promiseCallback.promiseCallback)();
        task = opts;
    } else {
        parseTimes(options, opts);
        callback = callback || (0, _promiseCallback.promiseCallback)();
    }

    if (typeof task !== 'function') {
        throw new Error("Invalid arguments for async.retry");
    }

    var _task = (0, _wrapAsync2.default)(task);

    var attempt = 1;
    function retryAttempt() {
        _task((err, ...args) => {
            if (err === false) return;
            if (err && attempt++ < options.times && (typeof options.errorFilter != 'function' || options.errorFilter(err))) {
                setTimeout(retryAttempt, options.intervalFunc(attempt - 1));
            } else {
                callback(err, ...args);
            }
        });
    }

    retryAttempt();
    return callback[_promiseCallback.PROMISE_SYMBOL];
}

function parseTimes(acc, t) {
    if (typeof t === 'object') {
        acc.times = +t.times || DEFAULT_TIMES;

        acc.intervalFunc = typeof t.interval === 'function' ? t.interval : constant(+t.interval || DEFAULT_INTERVAL);

        acc.errorFilter = t.errorFilter;
    } else if (typeof t === 'number' || typeof t === 'string') {
        acc.times = +t || DEFAULT_TIMES;
    } else {
        throw new Error("Invalid arguments for async.retry");
    }
}
module.exports = exports['default'];


text:
global NO_OF_RUNS
global MAX_EPOCHS

global NO_OF_SYLLABLES

global LEARNING_RATE
global MOMENTUM
global REINFORCEMENT_THRESHOLD

global Temperature
global Fahlman_offset
global BIAS_VALUE

NO_OF_SYLLABLES = 6;   % 12 for Aslin, Saffran, Fwd, Bkwd ;  18 for Cognition Exp1, Arnaud; 27 for expt3, last data set
NO_OF_SUBJECTS = 1;
NO_OF_RUNS = 20;   % default 10 for Arnaud, Expt1, Expt3; 25 for fwd, bkwd, saffran, aslin
MAX_EPOCHS = 1;   %default 3 for the Cognition expts where after each sentence, there is a refresh.  1 in bkwd, fwd, saffran, aslin
CRITERION = 0.4;
LEARNING_RATE = .04;
MOMENTUM = 0;    %default
REINFORCEMENT_THRESHOLD = 0.25;

Temperature = 1;
Fahlman_offset = 0.1;
BIAS_VALUE = -1;


text:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

    <TITLE>Adobe Software Technology Lab: count.hpp Source File</TITLE>
    <META HTTP-EQUIV="content-type" CONTENT="text/html;charset=ISO-8859-1"/>
    <LINK TYPE="text/css" REL="stylesheet" HREF="adobe_source.css"/>
    <LINK REL="alternate" TITLE="stlab.adobe.com RSS" HREF="http://sourceforge.net/export/rss2_projnews.php?group_id=132417&rss_fulltext=1" TYPE="application/rss+xml"/>

Documentation

        Overview

        Building ASL

        Documentation

        Library Wiki Docs

        Indices

        Browse Perforce

More Info

        Release Notes

        Wiki

        Site Search

        License

        Success Stories

        Contributors

Media

        Download

        Perforce Depots

Support

        ASL SourceForge Home

        Mailing Lists

        Discussion Forums

        Report Bugs

        Suggest Features

        Contribute to ASL

RSS

        Short-text news

        Full-text news

        File releases

Other Adobe Projects

        Open @ Adobe

        Adobe Open Source

        Adobe Labs

        Adobe Media Gallery

        C++ Benchmarks

Other Resources

        Boost

        RIAForge

        SGI STL

count.hpp

Go to the documentation of this file.

00001
00006
00007 /*************************************************************************************************/
00008
00009 #ifndef ADOBE_ALGORITHM_COUNT_HPP
00010 #define ADOBE_ALGORITHM_COUNT_HPP
00011
00012 #include <adobe/config.hpp>
00013
00014 #include <boost/range/begin.hpp>
00015 #include <boost/range/difference_type.hpp>
00016 #include <boost/range/end.hpp>
00017 #include <boost/bind.hpp>
00018
00019 #include <algorithm>
00020
00021 /*************************************************************************************************/
00022
00023 namespace adobe {
00024
00025 /*************************************************************************************************/
00034 /*************************************************************************************************/
00040 template <class InputRange, class T>
00041 inline typename boost::range_difference<InputRange>::type count(InputRange& range, T& value)
00042 {
00043     return std::count(boost::begin(range), boost::end(range), value);
00044 }
00045
00051 template <class InputRange, class T>
00052 inline typename boost::range_difference<InputRange>::type
00053 count(const InputRange& range, T& value)
00054 {
00055     return std::count(boost::begin(range), boost::end(range), value);
00056 }
00057
00063 template <class InputIterator, class Predicate>
00064 inline typename std::iterator_traits<InputIterator>::difference_type
00065 count_if(InputIterator first, InputIterator last, Predicate pred)
00066 {
00067     return std::count_if(first, last, boost::bind(pred, _1));
00068 }
00069
00075 template <class InputRange, class Predicate>
00076 inline typename boost::range_difference<InputRange>::type
00077 count_if(InputRange& range, Predicate pred)
00078 {
00079     return adobe::count_if(boost::begin(range), boost::end(range), pred);
00080 }
00081
00087 template <class InputRange, class Predicate>
00088 inline typename boost::range_difference<InputRange>::type
00089 count_if(const InputRange& range, Predicate pred)
00090 {
00091     return adobe::count_if(boost::begin(range), boost::end(range), pred);
00092 }
00093
00094 /*************************************************************************************************/
00095
00096 } // namespace adobe
00097
00098 /*************************************************************************************************/
00099
00100 #endif
00101
00102 /*************************************************************************************************/

Company |

Online Privacy Policy |

Terms of Use |

Contact Us |

Accessibility |

Report Piracy |

Permissions & Trademarks |

Product License Agreements |

Send Feedback

Copyright © 2006-2007 Adobe Systems Incorporated.

Use of this website signifies your agreement to the Terms of Use and Online Privacy Policy.

Search powered by Google


text:
Remove-Module -Name 'Rubrik' -ErrorAction 'SilentlyContinue'
Import-Module -Name './Rubrik/Rubrik.psd1' -Force

foreach ( $privateFunctionFilePath in ( Get-ChildItem -Path './Rubrik/Private' | Where-Object extension -eq '.ps1').FullName  ) {
    . $privateFunctionFilePath
}

Describe -Name 'Public/Get-RubrikAPIVersion' -Tag 'Public', 'Get-RubrikAPIVersion' -Fixture {
    #region init
    $global:rubrikConnection = @{
        id      = 'test-id'
        userId  = 'test-userId'
        token   = 'test-token'
        server  = 'test-server'
        header  = @{ 'Authorization' = 'Bearer test-authorization' }
        time    = (Get-Date)
        api     = 'v1'
        version = '4.0.5'
    }
    #endregion

    Context -Name 'Results Filtering' {
        Mock -CommandName Submit-Request -Verifiable -ModuleName 'Rubrik' -MockWith { return 1}
        It -Name 'Should return 1' -Test {
            ( Get-RubrikAPIVersion -Server 'server') |
                Should -BeExactly 1
        }
        It -Name 'Server cannot be null' -Test {
            { Get-RubrikAPIVersion -Server $null } |
                Should -Throw "Cannot bind argument to parameter 'Server' because it is an empty string."
        }
        Assert-VerifiableMock
        Assert-MockCalled -CommandName Submit-Request -ModuleName 'Rubrik' -Exactly 1
    }
}


text:
using OLEDB.Test.ModuleCore;

namespace System.Xml.Tests
{
    public partial class TCThisOrdinal : TCXMLReaderBaseGeneral
    {
        // Type is System.Xml.Tests.TCThisOrdinal
        // Test Case
        public override void AddChildren()
        {
            // for function OrdinalWithGetAttrDoubleQ
            {
                this.AddChild(new CVariation(OrdinalWithGetAttrDoubleQ) { Attribute = new Variation("This[i] Verify with GetAttribute[i] - Double Quote") { Pri = 0 } });
            }

            // for function OrdinalWithGetAttrSingleQ
            {
                this.AddChild(new CVariation(OrdinalWithGetAttrSingleQ) { Attribute = new Variation("This[i] Verify with GetAttribute[i] - Single Quote") });
            }

            // for function OrdinalWithMoveAttrDoubleQ
            {
                this.AddChild(new CVariation(OrdinalWithMoveAttrDoubleQ) { Attribute = new Variation("This[i] Verify with MoveToAttribute[i] - Double Quote") { Pri = 0 } });
            }

            // for function OrdinalWithMoveAttrSingleQ
            {
                this.AddChild(new CVariation(OrdinalWithMoveAttrSingleQ) { Attribute = new Variation("This[i] Verify with MoveToAttribute[i] - Single Quote") });
            }

            // for function NegativeOneOrdinal
            {
                this.AddChild(new CVariation(NegativeOneOrdinal) { Attribute = new Variation("ThisOrdinal NegativeOneOrdinal") { Pri = 0 } });
            }

            // for function FieldCountOrdinal
            {
                this.AddChild(new CVariation(FieldCountOrdinal) { Attribute = new Variation("ThisOrdinal FieldCountOrdinal") });
            }

            // for function OrdinalPlusOne
            {
                this.AddChild(new CVariation(OrdinalPlusOne) { Attribute = new Variation("ThisOrdinal OrdinalPlusOne") { Pri = 0 } });
            }

            // for function OrdinalMinusOne
            {
                this.AddChild(new CVariation(OrdinalMinusOne) { Attribute = new Variation("ThisOrdinal OrdinalMinusOne") });
            }
        }
    }
}


text:
<extend name="Public/base"/>

<block name="body">

{:isset($info['id'])?'编辑':'新增'}公告

    <form action="{$postUrl}" method="post" class="form-horizontal">

            标题

                <input type="text" class="text input-large" name="title" value="{$info.title|default=''}">

            内容

                <textarea name="content" >{$info.content}</textarea>
                 {:hook('adminArticleEdit', array('name'=>'content','value'=>$info[content]))}

            <input type="hidden" name="id" value="{$info.id|default=''}">
            <button class="btn submit-btn ajax-post" id="submit" type="submit" target-form="form-horizontal">确 定</button>
            <button class="btn btn-return" onclick="javascript:history.back(-1);return false;">返 回</button>

    </form>
</block>

<block name="script">

</block>


text:
module LB

include("module_common.jl")

const _libcloud_lb_types = PyCall.PyNULL()
const _libcloud_lb_providers = PyCall.PyNULL()
const _libcloud_lb_base = PyCall.PyNULL()

immutable LBDriver
    o::PyObject

    function LBDriver(provider::Compat.String, args...; kwargs...)
        cls = _libcloud_lb_providers[:get_driver](provider)
        LBDriver(cls(args...; kwargs...))
    end
    LBDriver(driver::PyObject) = new(driver)
end
show(io::IO, c::LBDriver) = print(io, c.o[:__str__]())

immutable LoadBalancer
    o::PyObject

    id::Nullable{Compat.String}
    name::Compat.String
    state::Int
    ip::Compat.String
    port::Nullable{Int}
    driver::LBDriver
    extra::Dict

    function LoadBalancer(o::PyObject)
        new(o, o[:id], o[:name], o[:state], o[:ip], o[:port], LBDriver(o[:driver]), o[:extra])
    end
end
PyObject(o::LoadBalancer) = o.o
convert(::Type{LoadBalancer}, o::PyObject) =  LoadBalancer(o)
show(io::IO, o::LoadBalancer) = print(io, o.o[:__str__]())
@doc LazyHelp(_libcloud_lb_base, "LoadBalancer") LoadBalancer

immutable Member
    o::PyObject

    id::Nullable{Compat.String}
    ip::Nullable{Compat.String}
    port::Nullable{Compat.String}
    balancer::Nullable{LoadBalancer}
    extra::Dict

    function Member(o::PyObject)
        balancer = (o[:balancer] == nothing) ? Nullable{LoadBalancer}() : Nullable(LoadBalancer(o[:balancer]))
        new(o, o[:id], o[:ip], o[:port], balancer, o[:extra])
    end
end
PyObject(o::Member) = o.o
convert(::Type{Member}, o::PyObject) =  Member(o)
show(io::IO, o::Member) = print(io, o.o[:__str__]())
@doc LazyHelp(_libcloud_lb_base, "Member") Member

const _lbdriver_fns = [
    :list_protocols, :list_balancers, :create_balancer, :destroy_balancer,
    :get_balancer, :update_balancer, :balancer_attach_compute_node, :balancer_attach_member,
    :balancer_detach_member, :balancer_list_members, :list_supported_algorithms
]

const _lb_fns = [
    :attach_compute_node, :attach_member, :detach_member, :list_members, :destroy
]

for f in union(Set(_lbdriver_fns), Set(_base_driver_fns))
    sf = string(f)
    @eval @doc LazyHelp(_libcloud_lb_base, "Driver", $sf) $(f)(lb::LBDriver, args...; kwargs...) = lb.o[$(sf)](args...; kwargs...)
end

for f in _lb_fns
    sf = string(f)
    @eval @doc LazyHelp(_libcloud_lb_base, "LoadBalancer", $sf) $(f)(lb::LoadBalancer, args...; kwargs...) = lb.o[$(sf)](args...; kwargs...)
end

# Initialize load balancer
function __init__()
    copy!(_libcloud_lb_types, pyimport("libcloud.loadbalancer.types"))
    copy!(_libcloud_lb_providers, pyimport("libcloud.loadbalancer.providers"))
    copy!(_libcloud_lb_base, pyimport("libcloud.loadbalancer.base"))

    global const LBProvider = pywrap(_libcloud_lb_types[:Provider])
    global const State = pywrap(_libcloud_lb_types[:State])
    global const MemberCondition = pywrap(_libcloud_lb_types[:MemberCondition])
    global const Algorithm = pywrap(_libcloud_lb_base[:Algorithm])
    global const DefaultAlgorithm = Algorithm.ROUND_ROBIN

    _map_types(_libcloud_lb_base, (Member, LoadBalancer))
end

# types
export LBProvider, LBDriver, State, MemberCondition, Algorithm, DefaultAlgorithm, LoadBalancer, Member
# lb driver functions
export list_protocols, list_balancers, create_balancer, destroy_balancer,
       get_balancer, update_balancer, balancer_attach_compute_node, balancer_attach_member,
       balancer_detach_member, balancer_list_members, list_supported_algorithms
# lb functons
export attach_compute_node, attach_member, detach_member, list_members, destroy

end # module LoadBalancer


text:
module Bpl
  class EntrypointLocalization < Pass

    DEFAULT_ENTRYPOINT_ANNOTATION = :entrypoint

    switch "--entrypoint-localization", "Locate & annotate entry points."
    option :attribute, DEFAULT_ENTRYPOINT_ANNOTATION
    result :entrypoints, Set.new

    flag "--entrypoint-attribute NAME", "Attribute NAME for entrypoints." do |y, name|
      y.yield :attribute, name
    end

    def default_entrypoint? name
      name =~ /\bmain\b/i
    end

    def run! program
      program.declarations.each do |d|
        entrypoints << d if d.has_attribute?(attribute)
      end

      program.declarations.each do |d|
        next unless d.is_a?(ProcedureDeclaration)
        entrypoints << d if default_entrypoint?(d.name)
      end if entrypoints.empty?

      warn "No entrypoints found." if entrypoints.empty?
      warn "Found call to entrypoint." if program.any? do |elem|
        elem.is_a?(CallStatement) && entrypoints.include?(elem.target)
      end
    end

  end
end


text:
package main

import (
	"context"
	"encoding/json"
	"errors"
	"fmt"
	"io"
	"io/ioutil"
	"log"
	"net/http"
	"os"
	"path"
	"sort"
	"strconv"
	"strings"
	"sync"
	"time"

	"cloud.google.com/go/compute/metadata"
	"cloud.google.com/go/datastore"
	"cloud.google.com/go/errorreporting"
	monapi "cloud.google.com/go/monitoring/apiv3"
	"cloud.google.com/go/storage"
	"golang.org/x/build/buildenv"
	"golang.org/x/build/buildlet"
	"golang.org/x/build/cmd/coordinator/spanlog"
	"golang.org/x/build/dashboard"
	"golang.org/x/build/gerrit"
	"golang.org/x/build/internal/buildstats"
	"golang.org/x/build/internal/lru"
	"golang.org/x/oauth2"
	"golang.org/x/oauth2/google"
	compute "google.golang.org/api/compute/v1"
	"google.golang.org/api/googleapi"
	oauth2api "google.golang.org/api/oauth2/v2"
)

func init() {
	buildlet.GCEGate = gceAPIGate
}

// apiCallTicker ticks regularly, preventing us from accidentally making
// GCE API calls too quickly. Our quota is 20 QPS, but we temporarily
// limit ourselves to less than that.
var apiCallTicker = time.NewTicker(time.Second / 10)

func gceAPIGate() {
	<-apiCallTicker.C
}

// Initialized by initGCE:
var (
	buildEnv *buildenv.Environment

	dsClient       *datastore.Client
	computeService *compute.Service
	tokenSource    oauth2.TokenSource
	errTryDeps     error // non-nil if try bots are disabled
	gerritClient   *gerrit.Client
	storageClient  *storage.Client
	metricsClient  *monapi.MetricClient
	inStaging      bool                   // are we running in the staging project? (named -dev)
	errorsClient   *errorreporting.Client // Stackdriver errors client

	initGCECalled bool
)

// oAuthHTTPClient is the OAuth2 HTTP client used to make API calls to Google Cloud APIs.
// It is initialized by initGCE.
var oAuthHTTPClient *http.Client

func initGCE() error {
	initGCECalled = true
	var err error

	// If the coordinator is running on a GCE instance and a
	// buildEnv was not specified with the env flag, set the
	// buildEnvName to the project ID
	if *buildEnvName == "" {
		if *mode == "dev" {
			*buildEnvName = "dev"
		} else if metadata.OnGCE() {
			*buildEnvName, err = metadata.ProjectID()
			if err != nil {
				log.Fatalf("metadata.ProjectID: %v", err)
			}
		}
	}

	buildEnv = buildenv.ByProjectID(*buildEnvName)
	inStaging = (buildEnv == buildenv.Staging)

	// If running on GCE, override the zone and static IP, and check service account permissions.
	if metadata.OnGCE() {
		projectZone, err := metadata.Get("instance/zone")
		if err != nil || projectZone == "" {
			return fmt.Errorf("failed to get current GCE zone: %v", err)
		}
		// Convert the zone from "projects/1234/zones/us-central1-a" to "us-central1-a".
		projectZone = path.Base(projectZone)
		buildEnv.Zone = projectZone

		if buildEnv.StaticIP == "" {
			buildEnv.StaticIP, err = metadata.ExternalIP()
			if err != nil {
				return fmt.Errorf("ExternalIP: %v", err)
			}
		}

		if !hasComputeScope() {
			return errors.New("coordinator is not running with access to read and write Compute resources. VM support disabled")
		}

		if value, err := metadata.ProjectAttributeValue("farmer-run-bench"); err == nil {
			*shouldRunBench, _ = strconv.ParseBool(value)
		}
	}

	cfgDump, _ := json.MarshalIndent(buildEnv, "", "  ")
	log.Printf("Loaded configuration %q for project %q:\n%s", *buildEnvName, buildEnv.ProjectName, cfgDump)

	ctx := context.Background()
	if *mode != "dev" {
		storageClient, err = storage.NewClient(ctx)
		if err != nil {
			log.Fatalf("storage.NewClient: %v", err)
		}

		metricsClient, err = monapi.NewMetricClient(ctx)
		if err != nil {
			log.Fatalf("monapi.NewMetricClient: %v", err)
		}
	}

	dsClient, err = datastore.NewClient(ctx, buildEnv.ProjectName)
	if err != nil {
		if *mode == "dev" {
			log.Printf("Error creating datastore client: %v", err)
		} else {
			log.Fatalf("Error creating datastore client: %v", err)
		}
	}

	// don't send dev errors to Stackdriver.
	if *mode != "dev" {
		errorsClient, err = errorreporting.NewClient(ctx, buildEnv.ProjectName, errorreporting.Config{
			ServiceName: "coordinator",
		})
		if err != nil {
			// don't exit, we still want to run coordinator
			log.Printf("Error creating errors client: %v", err)
		}
	}

	tokenSource, err = google.DefaultTokenSource(ctx, oauth2api.UserinfoEmailScope, compute.CloudPlatformScope)
	if err != nil {
		if *mode == "dev" {
			// don't try to do anything else with GCE, as it will likely fail
			return nil
		}
		log.Fatalf("failed to get a token source: %v", err)
	}
	oAuthHTTPClient = oauth2.NewClient(ctx, tokenSource)
	computeService, _ = compute.New(oAuthHTTPClient)
	errTryDeps = checkTryBuildDeps()
	if errTryDeps != nil {
		log.Printf("TryBot builders disabled due to error: %v", errTryDeps)
	} else {
		log.Printf("TryBot builders enabled.")
	}

	if *mode != "dev" {
		go syncBuildStatsLoop(buildEnv)
	}

	go gcePool.pollQuotaLoop()
	return nil
}

func checkTryBuildDeps() error {
	if !hasStorageScope() {
		return errors.New("coordinator's GCE instance lacks the storage service scope")
	}
	if *mode == "dev" {
		return errors.New("running in dev mode")
	}
	wr := storageClient.Bucket(buildEnv.LogBucket).Object("hello.txt").NewWriter(context.Background())
	fmt.Fprintf(wr, "Hello, world! Coordinator start-up at %v", time.Now())
	if err := wr.Close(); err != nil {
		return fmt.Errorf("test write of a GCS object to bucket %q failed: %v", buildEnv.LogBucket, err)
	}
	if inStaging {
		// Don't expect to write to Gerrit in staging mode.
		gerritClient = gerrit.NewClient("https://go-review.googlesource.com", gerrit.NoAuth)
	} else {
		gobotPass, err := metadata.ProjectAttributeValue("gobot-password")
		if err != nil {
			return fmt.Errorf("failed to get project metadata 'gobot-password': %v", err)
		}
		gerritClient = gerrit.NewClient("https://go-review.googlesource.com",
			gerrit.BasicAuth("git-gobot.golang.org", strings.TrimSpace(string(gobotPass))))
	}

	return nil
}

var gcePool = &gceBuildletPool{}

var _ BuildletPool = (*gceBuildletPool)(nil)

// maxInstances is a temporary hack because we can't get buildlets to boot
// without IPs, and we only have 200 IP addresses.
// TODO(bradfitz): remove this once fixed.
const maxInstances = 190

type gceBuildletPool struct {
	mu sync.Mutex // guards all following

	disabled bool

	// CPU quota usage & limits.
	cpuLeft   int // dead-reckoning CPUs remain
	instLeft  int // dead-reckoning instances remain
	instUsage int
	cpuUsage  int
	addrUsage int
	inst      map[string]time.Time // GCE VM instance name -> creationTime
}

func (p *gceBuildletPool) pollQuotaLoop() {
	if computeService == nil {
		log.Printf("pollQuotaLoop: no GCE access; not checking quota.")
		return
	}
	if buildEnv.ProjectName == "" {
		log.Printf("pollQuotaLoop: no GCE project name configured; not checking quota.")
		return
	}
	for {
		p.pollQuota()
		time.Sleep(5 * time.Second)
	}
}

func (p *gceBuildletPool) pollQuota() {
	gceAPIGate()
	reg, err := computeService.Regions.Get(buildEnv.ProjectName, buildEnv.Region()).Do()
	if err != nil {
		log.Printf("Failed to get quota for %s/%s: %v", buildEnv.ProjectName, buildEnv.Region(), err)
		return
	}
	p.mu.Lock()
	defer p.mu.Unlock()
	for _, quota := range reg.Quotas {
		switch quota.Metric {
		case "CPUS":
			p.cpuLeft = int(quota.Limit) - int(quota.Usage)
			p.cpuUsage = int(quota.Usage)
		case "INSTANCES":
			p.instLeft = int(quota.Limit) - int(quota.Usage)
			p.instUsage = int(quota.Usage)
		case "IN_USE_ADDRESSES":
			p.addrUsage = int(quota.Usage)
		}
	}
}

func (p *gceBuildletPool) SetEnabled(enabled bool) {
	p.mu.Lock()
	defer p.mu.Unlock()
	p.disabled = !enabled
}

func (p *gceBuildletPool) GetBuildlet(ctx context.Context, hostType string, lg logger) (bc *buildlet.Client, err error) {
	hconf, ok := dashboard.Hosts[hostType]
	if !ok {
		return nil, fmt.Errorf("gcepool: unknown host type %q", hostType)
	}
	qsp := lg.CreateSpan("awaiting_gce_quota")
	err = p.awaitVMCountQuota(ctx, hconf.GCENumCPU())
	qsp.Done(err)
	if err != nil {
		return nil, err
	}

	deleteIn, ok := ctx.Value(buildletTimeoutOpt{}).(time.Duration)
	if !ok {
		deleteIn = vmDeleteTimeout
	}

	instName := "buildlet-" + strings.TrimPrefix(hostType, "host-") + "-rn" + randHex(7)
	instName = strings.Replace(instName, "_", "-", -1) // Issue 22905; can't use underscores in GCE VMs
	p.setInstanceUsed(instName, true)

	gceBuildletSpan := lg.CreateSpan("create_gce_buildlet", instName)
	defer func() { gceBuildletSpan.Done(err) }()

	var (
		needDelete   bool
		createSpan   = lg.CreateSpan("create_gce_instance", instName)
		waitBuildlet spanlog.Span // made after create is done
		curSpan      = createSpan // either instSpan or waitBuildlet
	)

	log.Printf("Creating GCE VM %q for %s", instName, hostType)
	bc, err = buildlet.StartNewVM(tokenSource, instName, hostType, buildlet.VMOpts{
		ProjectID:   buildEnv.ProjectName,
		Zone:        buildEnv.Zone,
		Description: fmt.Sprintf("Go Builder for %s", hostType),
		DeleteIn:    deleteIn,
		OnInstanceRequested: func() {
			log.Printf("GCE VM %q now booting", instName)
		},
		FallbackToFullPrice: func() string {
			lg.LogEventTime("gce_fallback_to_full_price", "for "+instName)
			p.setInstanceUsed(instName, false)
			newName := instName + "-f"
			log.Printf("Gave up on preemptible %q; now booting %q", instName, newName)
			instName = newName
			p.setInstanceUsed(instName, true)
			return newName
		},
		OnInstanceCreated: func() {
			needDelete = true

			createSpan.Done(nil)
			waitBuildlet = lg.CreateSpan("wait_buildlet_start", instName)
			curSpan = waitBuildlet
		},
		OnGotInstanceInfo: func() {
			lg.LogEventTime("got_instance_info", "waiting_for_buildlet...")
		},
	})
	if err != nil {
		curSpan.Done(err)
		log.Printf("Failed to create VM for %s: %v", hostType, err)
		if needDelete {
			deleteVM(buildEnv.Zone, instName)
			p.putVMCountQuota(hconf.GCENumCPU())
		}
		p.setInstanceUsed(instName, false)
		return nil, err
	}
	waitBuildlet.Done(nil)
	bc.SetDescription("GCE VM: " + instName)
	bc.SetOnHeartbeatFailure(func() {
		p.putBuildlet(bc, hostType, instName)
	})
	return bc, nil
}

func (p *gceBuildletPool) putBuildlet(bc *buildlet.Client, hostType, instName string) error {
	// TODO(bradfitz): add the buildlet to a freelist (of max N
	// items) for up to 10 minutes since when it got started if
	// it's never seen a command execution failure, and we can
	// wipe all its disk content? (perhaps wipe its disk content
	// when it's retrieved, like the reverse buildlet pool) But
	// this will require re-introducing a distinction in the
	// buildlet client library between Close, Destroy/Halt, and
	// tracking execution errors.  That was all half-baked before
	// and thus removed. Now Close always destroys everything.
	deleteVM(buildEnv.Zone, instName)
	p.setInstanceUsed(instName, false)

	hconf, ok := dashboard.Hosts[hostType]
	if !ok {
		panic("failed to lookup conf") // should've worked if we did it before
	}
	p.putVMCountQuota(hconf.GCENumCPU())
	return nil
}

func (p *gceBuildletPool) WriteHTMLStatus(w io.Writer) {
	fmt.Fprintf(w, "GCE pool capacity: %s", p.capacityString())
	const show = 6 // must be even
	active := p.instancesActive()
	if len(active) > 0 {
		fmt.Fprintf(w, "
")
		for i, inst := range active {
			if i < show/2 || i >= len(active)-(show/2) {
				fmt.Fprintf(w, "
%v, %s
\n", inst.name, friendlyDuration(time.Since(inst.creation)))
			} else if i == show/2 {
				fmt.Fprintf(w, "
... %d of %d total omitted ...
\n", len(active)-show, len(active))
			}
		}
		fmt.Fprintf(w, "
")
	}
}

func (p *gceBuildletPool) String() string {
	return fmt.Sprintf("GCE pool capacity: %s", p.capacityString())
}

func (p *gceBuildletPool) capacityString() string {
	p.mu.Lock()
	defer p.mu.Unlock()
	return fmt.Sprintf("%d/%d instances; %d/%d CPUs",
		len(p.inst), p.instUsage+p.instLeft,
		p.cpuUsage, p.cpuUsage+p.cpuLeft)
}

// awaitVMCountQuota waits for numCPU CPUs of quota to become available,
// or returns ctx.Err.
func (p *gceBuildletPool) awaitVMCountQuota(ctx context.Context, numCPU int) error {
	// Poll every 2 seconds, which could be better, but works and
	// is simple.
	for {
		if p.tryAllocateQuota(numCPU) {
			return nil
		}
		select {
		case <-time.After(2 * time.Second):
		case <-ctx.Done():
			return ctx.Err()
		}
	}
}

func (p *gceBuildletPool) tryAllocateQuota(numCPU int) bool {
	p.mu.Lock()
	defer p.mu.Unlock()
	if p.disabled {
		return false
	}
	if p.cpuLeft >= numCPU && p.instLeft >= 1 && len(p.inst) < maxInstances && p.addrUsage < maxInstances {
		p.cpuUsage += numCPU
		p.cpuLeft -= numCPU
		p.instLeft--
		p.addrUsage++
		return true
	}
	return false
}

// putVMCountQuota adjusts the dead-reckoning of our quota usage by
// one instance and cpu CPUs.
func (p *gceBuildletPool) putVMCountQuota(cpu int) {
	p.mu.Lock()
	defer p.mu.Unlock()
	p.cpuUsage -= cpu
	p.cpuLeft += cpu
	p.instLeft++
}

func (p *gceBuildletPool) setInstanceUsed(instName string, used bool) {
	p.mu.Lock()
	defer p.mu.Unlock()
	if p.inst == nil {
		p.inst = make(map[string]time.Time)
	}
	if used {
		p.inst[instName] = time.Now()
	} else {
		delete(p.inst, instName)
	}
}

func (p *gceBuildletPool) instanceUsed(instName string) bool {
	p.mu.Lock()
	defer p.mu.Unlock()
	_, ok := p.inst[instName]
	return ok
}

func (p *gceBuildletPool) instancesActive() (ret []resourceTime) {
	p.mu.Lock()
	defer p.mu.Unlock()
	for name, create := range p.inst {
		ret = append(ret, resourceTime{
			name:     name,
			creation: create,
		})
	}
	sort.Sort(byCreationTime(ret))
	return ret
}

// resourceTime is a GCE instance or Kube pod name and its creation time.
type resourceTime struct {
	name     string
	creation time.Time
}

type byCreationTime []resourceTime

func (s byCreationTime) Len() int           { return len(s) }
func (s byCreationTime) Less(i, j int) bool { return s[i].creation.Before(s[j].creation) }
func (s byCreationTime) Swap(i, j int)      { s[i], s[j] = s[j], s[i] }

// cleanUpOldVMs loops forever and periodically enumerates virtual
// machines and deletes those which have expired.
//
// A VM is considered expired if it has a "delete-at" metadata
// attribute having a unix timestamp before the current time.
//
// This is the safety mechanism to delete VMs which stray from the
// normal deleting process. VMs are created to run a single build and
// should be shut down by a controlling process. Due to various types
// of failures, they might get stranded. To prevent them from getting
// stranded and wasting resources forever, we instead set the
// "delete-at" metadata attribute on them when created to some time
// that's well beyond their expected lifetime.
func (p *gceBuildletPool) cleanUpOldVMs() {
	if *mode == "dev" {
		return
	}
	if computeService == nil {
		return
	}

	// TODO(bradfitz): remove this list and just query it from the compute API?
	// http://godoc.org/google.golang.org/api/compute/v1#RegionsService.Get
	// and Region.Zones: http://godoc.org/google.golang.org/api/compute/v1#Region

	for {
		for _, zone := range buildEnv.ZonesToClean {
			if err := p.cleanZoneVMs(zone); err != nil {
				log.Printf("Error cleaning VMs in zone %q: %v", zone, err)
			}
		}
		time.Sleep(time.Minute)
	}
}

// cleanZoneVMs is part of cleanUpOldVMs, operating on a single zone.
func (p *gceBuildletPool) cleanZoneVMs(zone string) error {
	// Fetch the first 500 (default) running instances and clean
	// thoes. We expect that we'll be running many fewer than
	// that. Even if we have more, eventually the first 500 will
	// either end or be cleaned, and then the next call will get a
	// partially-different 500.
	// TODO(bradfitz): revist this code if we ever start running
	// thousands of VMs.
	gceAPIGate()
	list, err := computeService.Instances.List(buildEnv.ProjectName, zone).Do()
	if err != nil {
		return fmt.Errorf("listing instances: %v", err)
	}
	for _, inst := range list.Items {
		if inst.Metadata == nil {
			// Defensive. Not seen in practice.
			continue
		}
		var sawDeleteAt bool
		var deleteReason string
		for _, it := range inst.Metadata.Items {
			if it.Key == "delete-at" {
				if it.Value == nil {
					log.Printf("missing delete-at value; ignoring")
					continue
				}
				unixDeadline, err := strconv.ParseInt(*it.Value, 10, 64)
				if err != nil {
					log.Printf("invalid delete-at value %q seen; ignoring", it.Value)
					continue
				}
				sawDeleteAt = true
				if time.Now().Unix() > unixDeadline {
					deleteReason = "delete-at expiration"
				}
			}
		}
		isBuildlet := strings.HasPrefix(inst.Name, "buildlet-")

		if isBuildlet && !sawDeleteAt && !p.instanceUsed(inst.Name) {
			createdAt, _ := time.Parse(time.RFC3339Nano, inst.CreationTimestamp)
			if createdAt.Before(time.Now().Add(-3 * time.Hour)) {
				deleteReason = fmt.Sprintf("no delete-at, created at %s", inst.CreationTimestamp)
			}
		}

		// Delete buildlets (things we made) from previous
		// generations. Only deleting things starting with "buildlet-"
		// is a historical restriction, but still fine for paranoia.
		if deleteReason == "" && sawDeleteAt && isBuildlet && !p.instanceUsed(inst.Name) {
			if _, ok := deletedVMCache.Get(inst.Name); !ok {
				deleteReason = "from earlier coordinator generation"
			}
		}

		if deleteReason != "" {
			log.Printf("deleting VM %q in zone %q; %s ...", inst.Name, zone, deleteReason)
			deleteVM(zone, inst.Name)
		}

	}
	return nil
}

var deletedVMCache = lru.New(100) // keyed by instName

// deleteVM starts a delete of an instance in a given zone.
//
// It either returns an operation name (if delete is pending) or the
// empty string if the instance didn't exist.
func deleteVM(zone, instName string) (operation string, err error) {
	deletedVMCache.Add(instName, token{})
	gceAPIGate()
	op, err := computeService.Instances.Delete(buildEnv.ProjectName, zone, instName).Do()
	apiErr, ok := err.(*googleapi.Error)
	if ok {
		if apiErr.Code == 404 {
			return "", nil
		}
	}
	if err != nil {
		log.Printf("Failed to delete instance %q in zone %q: %v", instName, zone, err)
		return "", err
	}
	log.Printf("Sent request to delete instance %q in zone %q. Operation ID, Name: %v, %v", instName, zone, op.Id, op.Name)
	return op.Name, nil
}

func hasScope(want string) bool {
	// If not on GCE, assume full access
	if !metadata.OnGCE() {
		return true
	}
	scopes, err := metadata.Scopes("default")
	if err != nil {
		log.Printf("failed to query metadata default scopes: %v", err)
		return false
	}
	for _, v := range scopes {
		if v == want {
			return true
		}
	}
	return false
}

func hasComputeScope() bool {
	return hasScope(compute.ComputeScope) || hasScope(compute.CloudPlatformScope)
}

func hasStorageScope() bool {
	return hasScope(storage.ScopeReadWrite) || hasScope(storage.ScopeFullControl) || hasScope(compute.CloudPlatformScope)
}

func readGCSFile(name string) ([]byte, error) {
	if *mode == "dev" {
		b, ok := testFiles[name]
		if !ok {
			return nil, &os.PathError{
				Op:   "open",
				Path: name,
				Err:  os.ErrNotExist,
			}
		}
		return []byte(b), nil
	}

	r, err := storageClient.Bucket(buildEnv.BuildletBucket).Object(name).NewReader(context.Background())
	if err != nil {
		return nil, err
	}
	defer r.Close()
	return ioutil.ReadAll(r)
}

// syncBuildStatsLoop runs forever in its own goroutine and syncs the
// coordinator's datastore Build & Span entities to BigQuery
// periodically.
func syncBuildStatsLoop(env *buildenv.Environment) {
	ticker := time.NewTicker(5 * time.Minute)
	for {
		ctx, cancel := context.WithTimeout(context.Background(), 10*time.Minute)
		if err := buildstats.SyncBuilds(ctx, env); err != nil {
			log.Printf("buildstats: SyncBuilds: %v", err)
		}
		if err := buildstats.SyncSpans(ctx, env); err != nil {
			log.Printf("buildstats: SyncSpans: %v", err)
		}
		cancel()
		<-ticker.C
	}
}


text:
"""

[env]
# Conda Environment
# NO CONDA ENV

conda create --name web_scraping_selenium python=3.9.7
conda info --envs
source activate web_scraping_selenium
conda deactivate
# if needed to remove
conda env remove -n [NAME_OF_THE_CONDA_ENVIRONMENT]

# update conda
conda update -n base -c defaults conda

[path]
cd /Users/brunoflaven/Documents/03_git/BlogArticlesExamples/using_selenium_web_scraping_automation/stackabuse_scraper/

[file]
# local
python3 stackabuse_scraper_001.py
# with anaconda env
python stackabuse_scraper_001.py

# do not use python 2
python --version

#  use python 3
python3 --version

[required]
# install

#  do not use pip 2
pip --version

#  do not use pip 3
pip3 --version

# BeautifulSoup
pip3 install bs4

# other module
pip3 install requests
pip3 install pandas
pip3 install selenium
pip3 install matplotlib
pip3 install seaborn

# update conda if needed by running
# NO CONDA ENV
conda update -n base -c defaults conda

[source]
https://sodocumentation.net/beautifulsoup/topic/1940/locating-elements
https://stackabuse.com/guide-to-parsing-html-with-beautifulsoup-in-python/
https://stackabuse.com/guide-to-parsing-html-with-beautifulsoup-in-python/

"""

from bs4 import BeautifulSoup

file_to_scrap = "stackabuse_doc.html"

with open(file_to_scrap) as fp:
    soup = BeautifulSoup(fp, "html.parser")

    # output
    # print(soup)

    #ouput
    # print(soup.head.title)
    # print(soup.body.a.text)
    # print(soup.body.p.b)

    # ouput
    # print(soup.find_all("a"))

    # output
    # print(soup.find_all("a", class_="element"))

    # output
    print(soup.find("a", href=True)["href"])


text:
using System;
using System.IO;
using System.Net;
using System.Reflection;
using System.Text;
using System.Web;
using System.Web.UI;

namespace SapphireLib.Paypal {
    public abstract class AdvPage : Page {
        protected AdvPage() {
            this.Load += new EventHandler(Page_Load);
        }

        protected override void OnInit(EventArgs e) {
            MaintainScrollPositionOnPostBack = true;
            base.OnInit(e);
        }

        protected abstract void Page_Load(object sender, EventArgs eventArgs);
    }

}


text:
using System;

namespace Org.BouncyCastle.Crypto.Parameters
{
    public class DesEdeParameters
		: DesParameters
    {
        /*
        * DES-EDE Key length in bytes.
        */
		public const int DesEdeKeyLength = 24;

		private static byte[] FixKey(
			byte[]	key,
			int		keyOff,
			int		keyLen)
		{
			byte[] tmp = new byte[24];

			switch (keyLen)
			{
				case 16:
					Array.Copy(key, keyOff, tmp, 0, 16);
					Array.Copy(key, keyOff, tmp, 16, 8);
					break;
				case 24:
					Array.Copy(key, keyOff, tmp, 0, 24);
					break;
				default:
					throw new ArgumentException("Bad length for DESede key: " + keyLen, "keyLen");
			}

			if (IsWeakKey(tmp))
				throw new ArgumentException("attempt to create weak DESede key");

			return tmp;
		}

		public DesEdeParameters(
            byte[] key)
			: base(FixKey(key, 0, key.Length))
        {
        }

		public DesEdeParameters(
			byte[]	key,
			int		keyOff,
			int		keyLen)
			: base(FixKey(key, keyOff, keyLen))
		{
		}

		/**
         * return true if the passed in key is a DES-EDE weak key.
         *
         * @param key bytes making up the key
         * @param offset offset into the byte array the key starts at
         * @param length number of bytes making up the key
         */
        public static bool IsWeakKey(
            byte[]  key,
            int     offset,
            int     length)
        {
            for (int i = offset; i < length; i += DesKeyLength)
            {
                if (DesParameters.IsWeakKey(key, i))
                {
                    return true;
                }
            }

            return false;
        }

        /**
         * return true if the passed in key is a DES-EDE weak key.
         *
         * @param key bytes making up the key
         * @param offset offset into the byte array the key starts at
         */
        public static new bool IsWeakKey(
            byte[]	key,
            int		offset)
        {
            return IsWeakKey(key, offset, key.Length - offset);
        }

		public static new bool IsWeakKey(
			byte[] key)
		{
			return IsWeakKey(key, 0, key.Length);
		}
    }
}


text:
/*==-- clang-c/BuildSystem.h - Utilities for use by build systems -*- C -*-===*\
|*                                                                            *|
|*                     The LLVM Compiler Infrastructure                       *|
|*                                                                            *|
|* This file is distributed under the University of Illinois Open Source      *|
|* License. See LICENSE.TXT for details.                                      *|
|*                                                                            *|
|*===----------------------------------------------------------------------===*|
|*                                                                            *|
|* This header provides various utilities for use by build systems.           *|
|*                                                                            *|
\*===----------------------------------------------------------------------===*/

#ifndef CLANG_C_BUILD_SYSTEM_H
#define CLANG_C_BUILD_SYSTEM_H

#include "clang-c/Platform.h"
#include "clang-c/CXErrorCode.h"
#include "clang-c/CXString.h"

#ifdef __cplusplus
extern "C" {
#endif

/**
 * \defgroup BUILD_SYSTEM Build system utilities
 * @{
 */

/**
 * \brief Return the timestamp for use with Clang's
 * \c -fbuild-session-timestamp= option.
 */
CINDEX_LINKAGE unsigned long long clang_getBuildSessionTimestamp(void);

/**
 * \brief Object encapsulating information about overlaying virtual
 * file/directories over the real file system.
 */
typedef struct CXVirtualFileOverlayImpl *CXVirtualFileOverlay;

/**
 * \brief Create a \c CXVirtualFileOverlay object.
 * Must be disposed with \c clang_VirtualFileOverlay_dispose().
 *
 * \param options is reserved, always pass 0.
 */
CINDEX_LINKAGE CXVirtualFileOverlay
clang_VirtualFileOverlay_create(unsigned options);

/**
 * \brief Map an absolute virtual file path to an absolute real one.
 * The virtual path must be canonicalized (not contain "."/"..").
 * \returns 0 for success, non-zero to indicate an error.
 */
CINDEX_LINKAGE enum CXErrorCode
clang_VirtualFileOverlay_addFileMapping(CXVirtualFileOverlay,
                                        const char *virtualPath,
                                        const char *realPath);

/**
 * \brief Set the case sensitivity for the \c CXVirtualFileOverlay object.
 * The \c CXVirtualFileOverlay object is case-sensitive by default, this
 * option can be used to override the default.
 * \returns 0 for success, non-zero to indicate an error.
 */
CINDEX_LINKAGE enum CXErrorCode
clang_VirtualFileOverlay_setCaseSensitivity(CXVirtualFileOverlay,
											int caseSensitive);

/**
 * \brief Write out the \c CXVirtualFileOverlay object to a char buffer.
 *
 * \param options is reserved, always pass 0.
 * \param out_buffer_ptr pointer to receive the buffer pointer, which should be
 * disposed using \c free().
 * \param out_buffer_size pointer to receive the buffer size.
 * \returns 0 for success, non-zero to indicate an error.
 */
CINDEX_LINKAGE enum CXErrorCode
clang_VirtualFileOverlay_writeToBuffer(CXVirtualFileOverlay, unsigned options,
                                       char **out_buffer_ptr,
                                       unsigned *out_buffer_size);

/**
 * \brief Dispose a \c CXVirtualFileOverlay object.
 */
CINDEX_LINKAGE void clang_VirtualFileOverlay_dispose(CXVirtualFileOverlay);

/**
 * \brief Object encapsulating information about a module.map file.
 */
typedef struct CXModuleMapDescriptorImpl *CXModuleMapDescriptor;

/**
 * \brief Create a \c CXModuleMapDescriptor object.
 * Must be disposed with \c clang_ModuleMapDescriptor_dispose().
 *
 * \param options is reserved, always pass 0.
 */
CINDEX_LINKAGE CXModuleMapDescriptor
clang_ModuleMapDescriptor_create(unsigned options);

/**
 * \brief Sets the framework module name that the module.map describes.
 * \returns 0 for success, non-zero to indicate an error.
 */
CINDEX_LINKAGE enum CXErrorCode
clang_ModuleMapDescriptor_setFrameworkModuleName(CXModuleMapDescriptor,
                                                 const char *name);

/**
 * \brief Sets the umbrealla header name that the module.map describes.
 * \returns 0 for success, non-zero to indicate an error.
 */
CINDEX_LINKAGE enum CXErrorCode
clang_ModuleMapDescriptor_setUmbrellaHeader(CXModuleMapDescriptor,
                                            const char *name);

/**
 * \brief Write out the \c CXModuleMapDescriptor object to a char buffer.
 *
 * \param options is reserved, always pass 0.
 * \param out_buffer_ptr pointer to receive the buffer pointer, which should be
 * disposed using \c free().
 * \param out_buffer_size pointer to receive the buffer size.
 * \returns 0 for success, non-zero to indicate an error.
 */
CINDEX_LINKAGE enum CXErrorCode
clang_ModuleMapDescriptor_writeToBuffer(CXModuleMapDescriptor, unsigned options,
                                       char **out_buffer_ptr,
                                       unsigned *out_buffer_size);

/**
 * \brief Dispose a \c CXModuleMapDescriptor object.
 */
CINDEX_LINKAGE void clang_ModuleMapDescriptor_dispose(CXModuleMapDescriptor);

/**
 * @}
 */

#ifdef __cplusplus
}
#endif

#endif /* CLANG_C_BUILD_SYSTEM_H */


text:
Torch
=====

Torch Framework : A better way to handle application depedencies and build robust software.


text:
def getManagers(employees):
    return list(filter(lambda e: e.manager, employees))
    # return [e for e in employees if e.manager is True]


text:
@interface RTFlyoutItem : UIButton

//@property (nonatomic, getter = isActive) BOOL active;
@property (nonatomic) NSInteger mainItemIndex;
@property (nonatomic) NSInteger subItemIndex;

@end


text:
using System.Configuration;
using Autofac;
using Autofac.Core;
using Autofac.Extras.Multitenant;

namespace EventSpike.SqlIntegration
{
    public class SqlConectionSettingsModule : Module
    {
        protected override void Load(ContainerBuilder builder)
        {
            builder.RegisterType<ConventionTenantSqlConnectionSettingsFactory>().WithParameter(ResolvedParameter.ForNamed<string>(InstanceNames.CurrentTenantId));

            builder.Register(context => context.Resolve<ConventionTenantSqlConnectionSettingsFactory>().GetSettings())
                .InstancePerTenant()
                .AsSelf();

            builder.Register(context => context.Resolve<ConventionTenantSqlConnectionSettingsFactory>().GetSettings("Projections"))
                .InstancePerTenant()
                .Named<ConnectionStringSettings>("Projections");
        }
    }
}


text:
/**
 * @file    game.h
 * @brief   Arquivo com a implementacao de funcoes
                que controlam o jogo.
 * @author  Edivania Pontes (edivaniap@ufrn.edu.br)
 * @author  Jaine Budke (jainebudke@hotmail.com)
 * @since   30/05/2017
 * @date    21/06/2017
 */

#include "game.h"
#include "snake.h"

Level lv; // instanciando classe level
Snake sk; // instanciando classe snake

// ======================================================
// ACTIONS
// ======================================================

/** @brief Identifica a posicao inicial da Snake no tabuleiro.
    @return Posicao inicial da Snake */
Position Game::initialPosition(){

    // Percorre board tentando encontrar inicio
    for( int i = 0 ; i < lv.currentBoard.size() ; i++ ){        // Percorre cada pos do vector
        for( int j=0 ; j < lv.currentBoard[i].length() ; j++ ){ // Percorre cada pos da string
            if( lv.currentBoard[i][j] == '*' ){
                Position inicial;
                inicial.x = j; // coluna
            	inicial.y = i; // linha
                lv.initial = inicial;
            	   return inicial;
            }
        }
    }

}

/** @brief Lança uma maçã no jogo, dentro das coordenadas do tabuleiro da fase.
    @return Posicao em que a maçã foi lançada */
Position Game::throwApple(){

    bool invalido = true;

    std::srand(std::time(0)); // semente do rand
    Position tamanho = sizesBoards[lv.currentLevel-1]; // pega tamanho do level atual

    // sorteia a maçã até cair num espaço livre
    do{

        int menor = 1;
        int maiorLinha  = tamanho.y -1;
        int maiorColuna = tamanho.x -1;

        Position pos;

        pos.y = rand()%(maiorLinha-menor+1) + menor;  // sorteia um numero aleatorio para a linha
        pos.x = rand()%(maiorColuna-menor+1) + menor; // sorteia um numero aleatorio para a coluna

        if( isFree(lv.currentBoard[pos.y][pos.x]) ){
            invalido = false;
            lv.currentBoard[pos.y][pos.x] = 'a';
            maca = pos;
        }

    } while( invalido );

}

void Game::paint_snake_on_board()
{
    lv.currentBoard[sk.snakeBody[0].y][sk.snakeBody[0].x] = '@'; //desenha a cabeça
    for(auto i = 1u; i < sk.snakeBody.size(); i++)
        lv.currentBoard[sk.snakeBody[i].y][sk.snakeBody[i].x] = '0';
}

void Game::clear_snake_of_board()
{
    for(auto i = 0u; i < sk.snakeBody.size(); i++)
        lv.currentBoard[sk.snakeBody[i].y][sk.snakeBody[i].x] = ' ';
}

/** @brief Move a cobra de acordo com as coordenadas passadas.
     @return 1 se cobra chegou na maca, bateu na parede ou rabo. 0 otherwise. */
bool Game::moveSnake(){
    //std::cin.ignore(); //esperar enter

    /* apaga desenho das antigas posicoes da cobra */
    clear_snake_of_board();

    Position dir = sk.listDirections[sk.currentDirection];
    sk.snakeBody.push_front( dir );
    sk.snakeBody.pop_back();

    /* pintar toda a cobra no tab */
    paint_snake_on_board();

    // se chegou na maçã
    if( eatingApple() ){
        currentState = EXPAND;
        lv.eatenApples += 1;
        return true; // muda stop pra true
    }

    if( sk.listDirections.size() == sk.currentDirection ){
        return true;
    }

    sk.currentDirection += 1;

    return false; // muda stop pra false - continua rodando
}

// ======================================================
// AUXILIO
// ======================================================

/** @brief Verifica se o caractere passado é uma parede.
     @return 1 se for, 0 se não for */
bool Game::isWall( char ch ){
    return ( ch == '#' );
}

/** @brief Verifica se o caractere passado é uma parede invisivel.
     @return 1 se for, 0 se não for */
bool Game::isInvisibleWall( char ch ){
    return ( ch == '.' );
}

/** @brief Verifica se o caractere passado é um lugar livre.
     @return 1 se for, 0 se não for */
bool Game::isFree( char ch ){
    return ( ch == ' ' );
}

/** @brief Verifica se o caractere passado é a posicao inicial.
     @return 1 se for, 0 se não for */
bool Game::isInitialPosition( char ch ){
    return ( ch == '*' );
}

/** @brief Verifica se a snake chegou na maca.
     @return 1 se chegou, 0 otherwise */
bool Game::eatingApple( ){

    Position pos = sk.snakeBody.front();

    if( pos == maca ){
        return true;
    } else {
        return false;
    }

}

// ======================================================
// ESTADOS
// ======================================================

/** @brief Aumenta o tamanho da cobra. */
void Game::expandSnake(){

    Position pos = initialPosition();

    throwApple();

    // SE tamanho da snake for 1 ela é transformada na cobra
    if( sk.sizeSnake == 0 ){
        lv.currentBoard[pos.y][pos.x] = '@';
        sk.snakeBody.push_front( pos );

        sk.sizeSnake += 1; // snake cresce
    }

    // SE tamanho da snake for maior a 1 ela cresce
    if( sk.sizeSnake >= 1 ){
        sk.listDirections.clear();
        sk.currentDirection = 0;
        lv.initial = sk.snakeBody.front();

        /*AQUI NA VERDADE TENHO QUE GERAR UMA NOVA PÓS VALIDA !!!!!!!!1 PRA HEAD*/
        sk.snakeBody.push_front( sk.snakeBody.front() ); // add nova posição para uma nova parte do corpo

        sk.sizeSnake += 1; // snake cresce
    }

    // SE qntidade de maçãs comidas for o total -> STATE = LEVEL_UP
    if( lv.eatenApples == lv.totalApples ){
        currentState = LEVEL_UP;
    }

    // SE qntidade de maçãs comidas for menor que o total -> STATE = RUN e lança maçã
    if( lv.eatenApples < lv.totalApples ){
        currentState = RUN;
    }

}

/** @brief Faz a chamada da próxima fase do jogo setando os valores da classe Level. */
void Game::levelUp(){

    lv.currentLevel += 1; // em level é acrescentado um nível

    if( lv.currentLevel <= levels ){
        lv.currentBoard = boards[lv.currentLevel-1]; // recupera o tabuleiro do level
    }

    // zera tudo das classes level e snake
    lv.eatenApples = 0;
    sk.snakeBody.clear();
    sk.sizeSnake = 0;

    currentState = EXPAND;

}

/** @brief Verifica se a cobra teve alguma colisão. */
bool Game::crashSnake(){

    std::cout << "Oh no! You're crash!\n";
    currentState = DEAD;

}

/** @brief Simula a morte da cobra (diminui uma vida). */
void Game::deadSnake(){

    lives -= 1;

    std::cout << ">>> Pressione <ENTER> quando estiver pronto para continuar.";
    std::string dummy;
    std::getline( std::cin, dummy );

    currentState = RUN;

}

/** @brief A cobra anda a quantidade de vezes até chegar na maçã. */
void Game::runSnake(){

    bool solve = sk.solveMaze( lv.currentBoard, lv.initial, sizesBoards[ lv.currentLevel - 1 ], maca );

    bool stop = moveSnake();

    // se não há solução, execução para e vai pro estado CRASH
    if( solve == false ){
    	currentState = CRASH;
    	return;
    }

    // verifica se a condicao de parada foi acionada
    if( stop == false ){
        currentState = RUN;
    }

}

// ======================================================
// SETTERS AND GETTERS
// ======================================================

/** @brief Define a quantidade de fases do jogo.
    @param levels_ As fases
    @return True se tiver um numero de fases maior que zero; False otherwise. */
bool Game::setLevels( int levels_ ){
	if( levels_ > 0 ){
		levels = levels_;
		return true;
	} else {
		return false;
	}
}

/** @brief Recupera a quantidade de fases do jogo.
    @return As fases. */
int Game::getLevels( void ) const{
	return levels;
}

/** @brief Define um vetor com os tabuleiros do jogo.
    @param boards_ Os tabuleiros
    @return True se tiver um numero de tabuleiros maior que zero; False otherwise. */
bool Game::setBoards( std::vector<std::vector<std::string>> boards_ ){
	int qntidade = boards_.size();
	if( qntidade > 0 ){
		boards = boards_;
		return true;
	} else {
		return false;
	}
}

/** @brief Recupera os tabuleiros do jogo.
    @return Os tabuleiros. */
std::vector<std::vector<std::string>> Game::getBoards( void ) const{
	return boards;
}

/** @brief Diminui uma vida do jogador.
    @return True se tinha vidas pra diminuir; False otherwise. */
bool Game::setLives( ){
	if( lives > 0 ){
		lives--;
		return true;
	} else {
		return false;
	}
}

/** @brief Recupera a quantidade de vidas do jogador.
    @return As vidas. */
int Game::getLives( void ) const{
	return lives;
}

/** @brief Atualiza status do jogador
    @param state_ O status */
void Game::setState( int state_ ){
	state = state_;
}

/** @brief Recupera o status do jogador
    @return True se jogador ganhou; False se perdeu */
bool Game::getState( void ) const{
	if( state == 1 ){
		return true;
	}else if( state == 0 ){
		return false;
	}
}

/** @brief Atualiza os tamanhos dos tabuleiros do jogo
    @param sizesBoards_ Vetor com os tamanhos */
void Game::setSizeBoards( std::vector<Position> sizesBoards_ ){
	sizesBoards = sizesBoards_;
}

/** @brief Recupera o vetor com os tamanhos */
std::vector<Position> Game::getSizeBoards( void ) const{
	return sizesBoards;
}

// ======================================================
// GETTERS AND SETTERS DA CLASSE LEVEL
// ======================================================

/** @brief Define a fase atual que o jogador se encontra.
    @param level_ A fase
    @return True se tiver um numero de fases maior que zero; False otherwise. */
bool Game::setCurrentLevel( int level_ ){
    if( level_ > 0 ){
        lv.currentLevel = level_;
        return true;
    } else {
        return false;
    }
}

/** @brief Recupera a fase atual do jogo.
    @return A fase. */
int Game::getCurrentLevel( void ) const{
    return lv.currentLevel;
}

/** @brief Recupera o tabuleiro atual do jogo.
    @return O tabuleiro. */
std::vector<std::string> Game::getCurrentBoard( void ) const{
    return lv.currentBoard;
}

/** @brief Define o tabuleiro atual do jogo.
    @param level_ O tabuleiro
    @return True se tiver um tabuleiro; False otherwise. */
bool setCurrentBoard( std::vector<std::string> tabuleiro ){
    lv.currentBoard = tabuleiro;
}

/** @brief Recupera as macas comidas do jogo.
     @return A quandiade de macas. */
int Game::getEatenApples( void ) {
    return lv.eatenApples;
}


text:
package kallax

import (
	"testing"

	"github.com/stretchr/testify/require"
)

var emptySchema = NewBaseSchema("", "", nil, nil, nil, false)

func TestBaseSchemaFieldQualifiedName(t *testing.T) {
	var cases = []struct {
		name     string
		field    SchemaField
		schema   Schema
		expected string
	}{
		{"non empty schema alias", f("foo"), ModelSchema, "__model.foo"},
		{"empty schema alias", f("foo"), emptySchema, "foo"},
	}

	r := require.New(t)
	for _, c := range cases {
		r.Equal(c.expected, c.field.QualifiedName(c.schema), c.name)
	}
}

func TestJSONSchemaKeyQualifiedName(t *testing.T) {
	var cases = []struct {
		name     string
		key      *JSONSchemaKey
		schema   Schema
		expected string
	}{
		{
			"json text key",
			NewJSONSchemaKey(JSONText, "foo", "bar", "baz"),
			ModelSchema,
			"__model.foo #>>'{bar,baz}'",
		},
		{
			"json int key",
			NewJSONSchemaKey(JSONInt, "foo", "bar", "baz"),
			ModelSchema,
			"CAST(__model.foo #>>'{bar,baz}' as bigint)",
		},
		{
			"json any key",
			NewJSONSchemaKey(JSONAny, "foo", "bar", "baz"),
			ModelSchema,
			"__model.foo #>'{bar,baz}'",
		},
		{
			"json key with empty schema",
			NewJSONSchemaKey(JSONBool, "foo", "bar", "baz"),
			nil,
			"CAST(foo #>>'{bar,baz}' as bool)",
		},
	}

	r := require.New(t)
	for _, c := range cases {
		r.Equal(c.expected, c.key.QualifiedName(c.schema), c.name)
	}
}


text:
from __future__ import print_function
from distutils.core import setup
import os
import errno
import subprocess
import sys

def mkdir_p(path):
    '''Make a directory including parent directories.
    '''
    try:
        os.makedirs(path)
    except os.error as exc:
        if exc.errno != errno.EEXIST or not os.path.isdir(path):
            raise

print("Configuring...")
mkdir_p('cmake_build')
cmake_command = ['cmake', '../opensfm/src']
if sys.version_info >= (3, 0):
    cmake_command.extend([
        '-DBUILD_FOR_PYTHON3=ON',
        '-DBOOST_PYTHON3_COMPONENT=python-py{}{}'.format(
            sys.version_info.major,
            sys.version_info.minor)])
subprocess.Popen(cmake_command, cwd='cmake_build').wait()

print "Compiling extension..."
subprocess.Popen(['make','-j64'], cwd='cmake_build').wait()

print("Building package")
setup(
    name='OpenSfM',
    version='0.1',
    description='A Structure from Motion library',
    url='https://github.com/mapillary/OpenSfM',
    author='Mapillary',
    license='BSD',
    packages=['opensfm', 'opensfm.commands', 'opensfm.large'],
    scripts=['bin/opensfm_run_all', 'bin/opensfm'],
    package_data={
        'opensfm': ['csfm.so', 'data/sensor_data.json']
    },
)