text:
package org.acra.annotation;

import androidx.annotation.NonNull;
import androidx.annotation.RawRes;
import org.acra.ACRAConstants;
import org.acra.config.BaseHttpConfigurationBuilder;
import org.acra.security.KeyStoreFactory;
import org.acra.security.NoKeyStoreFactory;
import org.acra.sender.HttpSender;

import java.lang.annotation.*;

/**
 * Http sender configuration
 *
 * @author F43nd1r
 * @since 01.06.2017
 */
@Documented
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.TYPE)
@Inherited
@Configuration(baseBuilderClass = BaseHttpConfigurationBuilder.class)
public @interface AcraHttpSender {
    /**
     * The Uri of your own server-side script that will receive reports.
     *
     * @return URI of a server to which to send reports.
     * @since 5.0.0
     */
    @NonNull String uri();

    /**
     * you can set here and in {@link org.acra.annotation.AcraHttpSender#basicAuthPassword()} the credentials for a BASIC HTTP authentication.
     *
     * @return Login to use.
     * @since 5.0.0
     */
    @NonNull String basicAuthLogin() default ACRAConstants.NULL_VALUE;

    /**
     * you can set here and in {@link org.acra.annotation.AcraHttpSender#basicAuthLogin()} the credentials for a BASIC HTTP authentication.
     *
     * @return Password to use.
     * @since 5.0.0
     */
    @NonNull String basicAuthPassword() default ACRAConstants.NULL_VALUE;

    /**
     * <p>
     * The {@link HttpSender.Method} to be used when posting with {@link org.acra.annotation.AcraHttpSender#uri()} .
     * </p>
     *
     * @return HTTP method used when posting reports.
     * @since 5.0.0
     */
    @NonNull HttpSender.Method httpMethod();

    /**
     * timeout for server connection
     *
     * @return Value in milliseconds for timeout attempting to connect to a network.
     * @see java.net.HttpURLConnection#setConnectTimeout(int)
     * @since 5.0.0
     */
    int connectionTimeout() default 5000;

    /**
     * timeout for socket connection
     *
     * @return Value in milliseconds for timeout receiving a response to a network request.
     * @see java.net.HttpURLConnection#setReadTimeout(int)
     * @since 5.0.0
     */
    int socketTimeout() default 20000;

    /**
     * allows to prevent resending of timed out reports, possibly relieving server stress, but also reducing received report counts
     *
     * @return if timed out reports should be dropped
     * @since 5.0.0
     */
    boolean dropReportsOnTimeout() default false;

    /**
     * A custom class supplying a {@link java.security.KeyStore}, which will be used for ssl authentication.
     * A base implementation is available: {@link org.acra.security.BaseKeyStoreFactory}
     *
     * @return Class which creates a keystore that can contain trusted certificates
     * @since 5.0.0
     */
    @NonNull Class<? extends KeyStoreFactory> keyStoreFactoryClass() default NoKeyStoreFactory.class;

    /**
     * a certificate used for ssl authentication
     *
     * @return path to a custom trusted certificate. Must start with "asset://" if the file is in the assets folder
     * @since 5.0.0
     */
    @NonNull String certificatePath() default ACRAConstants.DEFAULT_STRING_VALUE;

    /**
     * a certificate used for ssl authentication
     *
     * @return resource id of a custom trusted certificate.
     * @since 5.0.0
     */
    @RawRes int resCertificate() default ACRAConstants.DEFAULT_RES_VALUE;

    /**
     * type of the certificate used for ssl authentication
     *
     * @return specify the type of the certificate set in either {@link org.acra.annotation.AcraHttpSender#certificatePath()} or {@link org.acra.annotation.AcraHttpSender#resCertificate()}
     * @since 5.0.0
     */
    @NonNull String certificateType() default ACRAConstants.DEFAULT_CERTIFICATE_TYPE;

    /**
     * if the server request should be compressed using gzip
     *
     * @return if compression should be active
     * @since 5.2.0
     */
    boolean compress() default false;
}


text:
from twisted.internet.defer import Deferred, DeferredQueue, succeed
from collections import defaultdict

class DeferredPriorityQueue(DeferredQueue):

    def __init__(self):
        DeferredQueue.__init__(self, None, None)
        self.pending = defaultdict(list)

    def put(self, priority, obj):
        if self.waiting:
            self.waiting.pop(0).callback(obj)
        else:
            self.pending[priority].append(obj)

    def get(self):
        if self.pending:
            min_ = sorted(self.pending.keys())[0]
            ret_val = self.pending[min_].pop(0)
            if not self.pending[min_]:
                del self.pending[min_]
            return succeed(ret_val)
        else:
            d = Deferred(canceller=self._cancelGet)
            self.waiting.append(d)
            return d

    def peek(self):
        return succeed(heap[0])

    def qsize(self):
        return succeed(len(self.pending))

redpajama_set_name: RedPajamaGithub


text:
"""
Created on Thu Feb  1 17:02:19 2018

@author: csh4
"""
import numpy as np
import healpy as hp
import cProfile

def pixpairs(nside):
    """
    Get a list of all HEALPIX neighbor-neighbor pixel-pixel pairs.

    No repeats, as in (2, 1) will not appear if (1, 2) appears

    @ params nside to be used
    @ returns list of 2 integer lists of (self, other) healpix number.

    performance: probably as fast as possible without cython
    """
    n_pix = hp.nside2npix(nside)

    #First do the self-self combos
    self_self = []
    for i in range(n_pix):
        self_self.append([i, i])

    #Now do the self-other combos
    self_neighbor = []
    pixel_pairs_groups = [[] for pixel in range(n_pix)]
    for i in range(n_pix):
        to_add = hp.pixelfunc.get_all_neighbours(nside, i)
        for j in to_add:
            if j == -1:
                pass
            else:
                pair = []
                if j > i:
                    pair = [i, j]
                else:
                    pair = [j, i]

                if (pair in pixel_pairs_groups[pair[0]]):
                    pass
                else:
                    pixel_pairs_groups[pair[0]].append(pair)
    for pixel_pairs_group in pixel_pairs_groups:
        for pixel_pair in pixel_pairs_group:
            self_neighbor.append(pixel_pair)

    #Finally do the 2 separation combos if nside > 16
    self_separated = []
    if nside > 16:
        pixel_pairs_groups = [[] for pixel in range(n_pix)]
        for pixel in range(n_pix):
            neighbors = hp.pixelfunc.get_all_neighbours(nside, pixel)
            neighbor_neighbor_groups = []
            for neighbor in neighbors:
                if neighbor == -1:
                    pass
                else:
                    group = hp.pixelfunc.get_all_neighbours(nside, neighbor)
                    neighbor_neighbor_groups.append(group)

            separated_neighbors = []
            for neighbor_neighbor_group in neighbor_neighbor_groups:
                for neighbor_neighbor in neighbor_neighbor_group:
                    if neighbor_neighbor in neighbors:
                        pass
                    elif neighbor_neighbor == pixel:
                        pass
                    elif neighbor_neighbor == -1:
                        pass
                    elif neighbor_neighbor in separated_neighbors:
                        pass
                    else:
                        separated_neighbors.append(neighbor_neighbor)

            pairs = []
            for separated_neighbor in separated_neighbors:
                if separated_neighbor > pixel:
                    pairs.append([pixel, separated_neighbor])
                else:
                    pairs.append([separated_neighbor, pixel])

            for pair in pairs:
                if pair in pixel_pairs_groups[pair[0]]:
                    pass
                else:
                    pixel_pairs_groups[pair[0]].append(pair)

        for pixel_pairs_group in pixel_pairs_groups:
            for pixel_pair in pixel_pairs_group:
                self_separated.append(pixel_pair)

    final_pairs =  self_self + self_neighbor + self_separated

    print("pixpairs("+str(nside)+") output shape is "+
          str(np.shape(final_pairs)))

    return final_pairs

def profile():
    cProfile.runctx('pixpairs(4)',  globals(), locals())
    cProfile.runctx('pixpairs(8)',  globals(), locals())
    cProfile.runctx('pixpairs(16)', globals(), locals())
    cProfile.runctx('pixpairs(32)', globals(), locals())
    cProfile.runctx('pixpairs(64)', globals(), locals())

def main():
    profile()

if __name__ == "__main__":
    main()


text:
import * as React from 'react';
import './colors.css';
import './common.css';
import * as icons from './icons';
import { AutoChip } from './chip';
import './reportView.css';
import './theme.css';

export type Metainfo = {
  'revision.id'?: string;
  'revision.author'?: string;
  'revision.email'?: string;
  'revision.subject'?: string;
  'revision.timestamp'?: number | Date;
  'revision.link'?: string;
  'ci.link'?: string;
  'timestamp'?: number
};

class ErrorBoundary extends React.Component<React.PropsWithChildren<{}>, { error: Error | null, errorInfo: React.ErrorInfo | null }> {
  state: { error: Error | null, errorInfo: React.ErrorInfo | null } = {
    error: null,
    errorInfo: null,
  };

  componentDidCatch(error: Error, errorInfo: React.ErrorInfo) {
    this.setState({ error, errorInfo });
  }

  render() {
    if (this.state.error || this.state.errorInfo) {
      return (
        <AutoChip header={'Commit Metainfo Error'} dataTestId='metadata-error'>

An error was encountered when trying to render Commit Metainfo. Please file a GitHub issue to report this error.

{this.state.error?.message}
{this.state.error?.stack}
{this.state.errorInfo?.componentStack}

        </AutoChip>
      );
    }

    return this.props.children;
  }
}

export const MetadataView: React.FC<Metainfo> = metadata => <ErrorBoundary><InnerMetadataView {...metadata} /></ErrorBoundary>;

const InnerMetadataView: React.FC<Metainfo> = metadata => {
  if (!Object.keys(metadata).find(k => k.startsWith('revision.') || k.startsWith('ci.')))
    return null;

  return (
    <AutoChip header={

        {metadata['revision.id'] &&
          {metadata['revision.id'].slice(0, 7)}
        }
        {metadata['revision.subject'] || 'Commit Metainfo'}
      } initialExpanded={false} dataTestId='metadata-chip'>
      {metadata['revision.subject'] &&
        <MetadatViewItem
          testId='revision.subject'
          content={{metadata['revision.subject']}}
        />
      }
      {metadata['revision.id'] &&
        <MetadatViewItem
          testId='revision.id'
          content={{metadata['revision.id']}}
          href={metadata['revision.link']}
          icon='commit'
        />
      }
      {(metadata['revision.author'] || metadata['revision.email']) &&
        <MetadatViewItem
          content={`${metadata['revision.author']} ${metadata['revision.email']}`}
          icon='person'
        />
      }
      {metadata['revision.timestamp'] &&
        <MetadatViewItem
          testId='revision.timestamp'
          content={
            <>
              {Intl.DateTimeFormat(undefined, { dateStyle: 'full' }).format(metadata['revision.timestamp'])}
              {' '}
              {Intl.DateTimeFormat(undefined, { timeStyle: 'long' }).format(metadata['revision.timestamp'])}
            </>
          }
          icon='calendar'
        />
      }
      {metadata['ci.link'] &&
        <MetadatViewItem
          content='CI/CD Logs'
          href={metadata['ci.link']}
          icon='externalLink'
        />
      }
      {metadata['timestamp'] &&
        <MetadatViewItem
          content={
            Report generated on {Intl.DateTimeFormat(undefined, { dateStyle: 'full', timeStyle: 'long' }).format(metadata['timestamp'])}
          }></MetadatViewItem>
      }
    </AutoChip>
  );
};

const MetadatViewItem: React.FC<{ content: JSX.Element | string; icon?: keyof typeof icons, href?: string, testId?: string }> = ({ content, icon, href, testId }) => {
  return (

        {icons[icon || 'blank']()}

        {href ? {content} : content}

  );
};


text:
namespace open_spiel {

// Track the count, min max, avg and standard deviation.
class BasicStats {
 public:
  BasicStats() { Reset(); }

  // Reset all the stats to 0.
  void Reset() {
    num_ = 0;
    min_ = std::numeric_limits<double>::max();
    max_ = std::numeric_limits<double>::min();
    sum_ = 0;
    sum_sq_ = 0;
  }

  // Merge two BasicStats. Useful for merging per thread stats before printing.
  BasicStats& operator+=(const BasicStats& o) {
    num_ += o.num_;
    sum_ += o.sum_;
    sum_sq_ += o.sum_sq_;
    min_ = std::min(min_, o.min_);
    max_ = std::max(max_, o.max_);
    return *this;
  }

  void Add(double val) {
    min_ = std::min(min_, val);
    max_ = std::max(max_, val);
    sum_ += val;
    sum_sq_ += val * val;
    num_ += 1;
  }

  int64_t Num() const { return num_; }
  double Min() const { return (num_ == 0 ? 0 : min_); }
  double Max() const { return (num_ == 0 ? 0 : max_); }
  double Avg() const { return (num_ == 0 ? 0 : sum_ / num_); }
  double StdDev() const {
    if (num_ <= 1) return 0;
    // Numerical precision can cause variance to be negative, leading to NaN's.
    double variance = (sum_sq_ - sum_ * sum_ / num_) / (num_ - 1);
    return variance <= 0 ? 0 : std::sqrt(variance);
  }

  json::Object ToJson() const {
    return {
        {"num", Num()},
        {"min", Min()},
        {"max", Max()},
        {"avg", Avg()},
        {"std_dev", StdDev()},
    };
  }

 private:
  int64_t num_;
  double min_;
  double max_;
  double sum_;
  double sum_sq_;
};

// Track the occurences for `count` buckets. You need to decide how to map your
// data into the buckets. Mainly useful for scalar values.
class HistogramNumbered {
 public:
  explicit HistogramNumbered(int num_buckets) : counts_(num_buckets, 0) {}
  void Reset() { absl::c_fill(counts_, 0); }
  void Add(int bucket_id) { counts_[bucket_id] += 1; }
  json::Array ToJson() const { return json::CastToArray(counts_); }

 private:
  std::vector<int> counts_;
};

// Same as HistogramNumbered, but each bucket has a name associated with it
// and is returned in the json output. Mainly useful for categorical values.
class HistogramNamed {
 public:
  explicit HistogramNamed(std::vector<std::string> names)
      : counts_(names.size(), 0), names_(names) {}
  void Reset() { absl::c_fill(counts_, 0); }
  void Add(int bucket_id) { counts_[bucket_id] += 1; }
  json::Object ToJson() const {
    return {
        {"counts", json::CastToArray(counts_)},
        {"names", json::CastToArray(names_)},
    };
  }

 private:
  std::vector<int> counts_;
  std::vector<std::string> names_;
};

}  // namespace open_spiel

#endif  // OPEN_SPIEL_UTILS_STATS_H_


text:
package org.apache.harmony.vts.test.vm.jvms.threads.threads212.threads21202;

/**
 * @author Maxim N. Kurzenev
 * @version $Revision: 1.1 $
 */
public class threads21202p {

    public int test(String[] args) {
        Thread t = new Thread() {
            public void run() {
                while (!Thread.interrupted()) {
                    try {
                        Thread.sleep(100);
                    } catch (InterruptedException e) {
                    }
                }
            }
        };

        t.start();
        int res = t.isAlive() ? 104 : 105;
        t.interrupt();
        return res;
    }

    public static void main(String[] args) {
        System.exit(new threads21202p().test(args));
    }
}


text:
import unittest
import mock
import numpy as np
from builders.procedural_city_builder import ProceduralCityBuilder
from builders.procedural_city.vertex import *
from builders.procedural_city.polygon2d import Polygon2D, Edge

class PcgRunnerTest(unittest.TestCase):

    def test_run(self):
        pcg_runner_mock = mock.Mock()
        builder = ProceduralCityBuilder(pcg_runner=pcg_runner_mock)
        edges = np.array([[0, 0], [1, 1], [2, 2]])
        polygon = Polygon2D(edges, "lot")
        builder._parse_polygons_file = mock.Mock(return_value=[polygon])
        vertex1 = Vertex([0, 0])
        vertex2 = Vertex([1, 1])
        builder._parse_vertices_file = mock.Mock(return_value=[vertex1, vertex2])
        builder.get_city()
        pcg_runner_mock.set_size.assert_called()
        pcg_runner_mock.run.assert_called()
        pcg_runner_mock.get_vertices_filename.assert_called()
        pcg_runner_mock.get_polygons_filename.assert_called()


text:
### Yet Another PHP ORM
🙈 🙉 🙊

- [Documentation](docs)

#### Many idea taken from great PHP ORM Framework [Doctrine2](https://github.com/doctrine/doctrine2)

## Installation
`composer require dezbyte/colibri-orm`


text:
'use strict';

if (process.env.NODE_ENV !== "production") {
  (function() {
'use strict';

var enableSchedulerDebugging = false;
var enableProfiling = false;

var requestHostCallback;
var requestHostTimeout;
var cancelHostTimeout;
var requestPaint;
var hasPerformanceNow = typeof performance === 'object' && typeof performance.now === 'function';

if (hasPerformanceNow) {
  var localPerformance = performance;

  exports.unstable_now = function () {
    return localPerformance.now();
  };
} else {
  var localDate = Date;
  var initialTime = localDate.now();

  exports.unstable_now = function () {
    return localDate.now() - initialTime;
  };
}

if ( // If Scheduler runs in a non-DOM environment, it falls back to a naive
// implementation using setTimeout.
typeof window === 'undefined' || // Check if MessageChannel is supported, too.
typeof MessageChannel !== 'function') {
  // If this accidentally gets imported in a non-browser environment, e.g. JavaScriptCore,
  // fallback to a naive implementation.
  var _callback = null;
  var _timeoutID = null;

  var _flushCallback = function () {
    if (_callback !== null) {
      try {
        var currentTime = exports.unstable_now();
        var hasRemainingTime = true;

        _callback(hasRemainingTime, currentTime);

        _callback = null;
      } catch (e) {
        setTimeout(_flushCallback, 0);
        throw e;
      }
    }
  };

  requestHostCallback = function (cb) {
    if (_callback !== null) {
      // Protect against re-entrancy.
      setTimeout(requestHostCallback, 0, cb);
    } else {
      _callback = cb;
      setTimeout(_flushCallback, 0);
    }
  };

  requestHostTimeout = function (cb, ms) {
    _timeoutID = setTimeout(cb, ms);
  };

  cancelHostTimeout = function () {
    clearTimeout(_timeoutID);
  };

  exports.unstable_shouldYield = function () {
    return false;
  };

  requestPaint = exports.unstable_forceFrameRate = function () {};
} else {
  // Capture local references to native APIs, in case a polyfill overrides them.
  var _setTimeout = window.setTimeout;
  var _clearTimeout = window.clearTimeout;

  if (typeof console !== 'undefined') {
    // TODO: Scheduler no longer requires these methods to be polyfilled. But
    // maybe we want to continue warning if they don't exist, to preserve the
    // option to rely on it in the future?
    var requestAnimationFrame = window.requestAnimationFrame;
    var cancelAnimationFrame = window.cancelAnimationFrame;

    if (typeof requestAnimationFrame !== 'function') {
      // Using console['error'] to evade Babel and ESLint
      console['error']("This browser doesn't support requestAnimationFrame. " + 'Make sure that you load a ' + 'polyfill in older browsers. https://reactjs.org/link/react-polyfills');
    }

    if (typeof cancelAnimationFrame !== 'function') {
      // Using console['error'] to evade Babel and ESLint
      console['error']("This browser doesn't support cancelAnimationFrame. " + 'Make sure that you load a ' + 'polyfill in older browsers. https://reactjs.org/link/react-polyfills');
    }
  }

  var isMessageLoopRunning = false;
  var scheduledHostCallback = null;
  var taskTimeoutID = -1; // Scheduler periodically yields in case there is other work on the main
  // thread, like user events. By default, it yields multiple times per frame.
  // It does not attempt to align with frame boundaries, since most tasks don't
  // need to be frame aligned; for those that do, use requestAnimationFrame.

  var yieldInterval = 5;
  var deadline = 0; // TODO: Make this configurable

  {
    // `isInputPending` is not available. Since we have no way of knowing if
    // there's pending input, always yield at the end of the frame.
    exports.unstable_shouldYield = function () {
      return exports.unstable_now() >= deadline;
    }; // Since we yield every frame regardless, `requestPaint` has no effect.

    requestPaint = function () {};
  }

  exports.unstable_forceFrameRate = function (fps) {
    if (fps < 0 || fps > 125) {
      // Using console['error'] to evade Babel and ESLint
      console['error']('forceFrameRate takes a positive int between 0 and 125, ' + 'forcing frame rates higher than 125 fps is not supported');
      return;
    }

    if (fps > 0) {
      yieldInterval = Math.floor(1000 / fps);
    } else {
      // reset the framerate
      yieldInterval = 5;
    }
  };

  var performWorkUntilDeadline = function () {
    if (scheduledHostCallback !== null) {
      var currentTime = exports.unstable_now(); // Yield after `yieldInterval` ms, regardless of where we are in the vsync
      // cycle. This means there's always time remaining at the beginning of
      // the message event.

      deadline = currentTime + yieldInterval;
      var hasTimeRemaining = true;

      try {
        var hasMoreWork = scheduledHostCallback(hasTimeRemaining, currentTime);

        if (!hasMoreWork) {
          isMessageLoopRunning = false;
          scheduledHostCallback = null;
        } else {
          // If there's more work, schedule the next message event at the end
          // of the preceding one.
          port.postMessage(null);
        }
      } catch (error) {
        // If a scheduler task throws, exit the current browser task so the
        // error can be observed.
        port.postMessage(null);
        throw error;
      }
    } else {
      isMessageLoopRunning = false;
    } // Yielding to the browser will give it a chance to paint, so we can
  };

  var channel = new MessageChannel();
  var port = channel.port2;
  channel.port1.onmessage = performWorkUntilDeadline;

  requestHostCallback = function (callback) {
    scheduledHostCallback = callback;

    if (!isMessageLoopRunning) {
      isMessageLoopRunning = true;
      port.postMessage(null);
    }
  };

  requestHostTimeout = function (callback, ms) {
    taskTimeoutID = _setTimeout(function () {
      callback(exports.unstable_now());
    }, ms);
  };

  cancelHostTimeout = function () {
    _clearTimeout(taskTimeoutID);

    taskTimeoutID = -1;
  };
}

function push(heap, node) {
  var index = heap.length;
  heap.push(node);
  siftUp(heap, node, index);
}
function peek(heap) {
  var first = heap[0];
  return first === undefined ? null : first;
}
function pop(heap) {
  var first = heap[0];

  if (first !== undefined) {
    var last = heap.pop();

    if (last !== first) {
      heap[0] = last;
      siftDown(heap, last, 0);
    }

    return first;
  } else {
    return null;
  }
}

function siftUp(heap, node, i) {
  var index = i;

  while (true) {
    var parentIndex = index - 1 >>> 1;
    var parent = heap[parentIndex];

    if (parent !== undefined && compare(parent, node) > 0) {
      // The parent is larger. Swap positions.
      heap[parentIndex] = node;
      heap[index] = parent;
      index = parentIndex;
    } else {
      // The parent is smaller. Exit.
      return;
    }
  }
}

function siftDown(heap, node, i) {
  var index = i;
  var length = heap.length;

  while (index < length) {
    var leftIndex = (index + 1) * 2 - 1;
    var left = heap[leftIndex];
    var rightIndex = leftIndex + 1;
    var right = heap[rightIndex]; // If the left or right node is smaller, swap with the smaller of those.

    if (left !== undefined && compare(left, node) < 0) {
      if (right !== undefined && compare(right, left) < 0) {
        heap[index] = right;
        heap[rightIndex] = node;
        index = rightIndex;
      } else {
        heap[index] = left;
        heap[leftIndex] = node;
        index = leftIndex;
      }
    } else if (right !== undefined && compare(right, node) < 0) {
      heap[index] = right;
      heap[rightIndex] = node;
      index = rightIndex;
    } else {
      // Neither child is smaller. Exit.
      return;
    }
  }
}

function compare(a, b) {
  // Compare sort index first, then task id.
  var diff = a.sortIndex - b.sortIndex;
  return diff !== 0 ? diff : a.id - b.id;
}

// TODO: Use symbols?
var ImmediatePriority = 1;
var UserBlockingPriority = 2;
var NormalPriority = 3;
var LowPriority = 4;
var IdlePriority = 5;

function markTaskErrored(task, ms) {
}

/* eslint-disable no-var */
// Math.pow(2, 30) - 1
// 0b111111111111111111111111111111

var maxSigned31BitInt = 1073741823; // Times out immediately

var IMMEDIATE_PRIORITY_TIMEOUT = -1; // Eventually times out

var USER_BLOCKING_PRIORITY_TIMEOUT = 250;
var NORMAL_PRIORITY_TIMEOUT = 5000;
var LOW_PRIORITY_TIMEOUT = 10000; // Never times out

var IDLE_PRIORITY_TIMEOUT = maxSigned31BitInt; // Tasks are stored on a min heap

var taskQueue = [];
var timerQueue = []; // Incrementing id counter. Used to maintain insertion order.

var taskIdCounter = 1; // Pausing the scheduler is useful for debugging.
var currentTask = null;
var currentPriorityLevel = NormalPriority; // This is set while performing work, to prevent re-entrancy.

var isPerformingWork = false;
var isHostCallbackScheduled = false;
var isHostTimeoutScheduled = false;

function advanceTimers(currentTime) {
  // Check for tasks that are no longer delayed and add them to the queue.
  var timer = peek(timerQueue);

  while (timer !== null) {
    if (timer.callback === null) {
      // Timer was cancelled.
      pop(timerQueue);
    } else if (timer.startTime <= currentTime) {
      // Timer fired. Transfer to the task queue.
      pop(timerQueue);
      timer.sortIndex = timer.expirationTime;
      push(taskQueue, timer);
    } else {
      // Remaining timers are pending.
      return;
    }

    timer = peek(timerQueue);
  }
}

function handleTimeout(currentTime) {
  isHostTimeoutScheduled = false;
  advanceTimers(currentTime);

  if (!isHostCallbackScheduled) {
    if (peek(taskQueue) !== null) {
      isHostCallbackScheduled = true;
      requestHostCallback(flushWork);
    } else {
      var firstTimer = peek(timerQueue);

      if (firstTimer !== null) {
        requestHostTimeout(handleTimeout, firstTimer.startTime - currentTime);
      }
    }
  }
}

function flushWork(hasTimeRemaining, initialTime) {

  isHostCallbackScheduled = false;

  if (isHostTimeoutScheduled) {
    // We scheduled a timeout but it's no longer needed. Cancel it.
    isHostTimeoutScheduled = false;
    cancelHostTimeout();
  }

  isPerformingWork = true;
  var previousPriorityLevel = currentPriorityLevel;

  try {
    if (enableProfiling) {
      try {
        return workLoop(hasTimeRemaining, initialTime);
      } catch (error) {
        if (currentTask !== null) {
          var currentTime = exports.unstable_now();
          markTaskErrored(currentTask, currentTime);
          currentTask.isQueued = false;
        }

        throw error;
      }
    } else {
      // No catch in prod code path.
      return workLoop(hasTimeRemaining, initialTime);
    }
  } finally {
    currentTask = null;
    currentPriorityLevel = previousPriorityLevel;
    isPerformingWork = false;
  }
}

function workLoop(hasTimeRemaining, initialTime) {
  var currentTime = initialTime;
  advanceTimers(currentTime);
  currentTask = peek(taskQueue);

  while (currentTask !== null && !(enableSchedulerDebugging )) {
    if (currentTask.expirationTime > currentTime && (!hasTimeRemaining || exports.unstable_shouldYield())) {
      // This currentTask hasn't expired, and we've reached the deadline.
      break;
    }

    var callback = currentTask.callback;

    if (typeof callback === 'function') {
      currentTask.callback = null;
      currentPriorityLevel = currentTask.priorityLevel;
      var didUserCallbackTimeout = currentTask.expirationTime <= currentTime;

      var continuationCallback = callback(didUserCallbackTimeout);
      currentTime = exports.unstable_now();

      if (typeof continuationCallback === 'function') {
        currentTask.callback = continuationCallback;
      } else {

        if (currentTask === peek(taskQueue)) {
          pop(taskQueue);
        }
      }

      advanceTimers(currentTime);
    } else {
      pop(taskQueue);
    }

    currentTask = peek(taskQueue);
  } // Return whether there's additional work

  if (currentTask !== null) {
    return true;
  } else {
    var firstTimer = peek(timerQueue);

    if (firstTimer !== null) {
      requestHostTimeout(handleTimeout, firstTimer.startTime - currentTime);
    }

    return false;
  }
}

function unstable_runWithPriority(priorityLevel, eventHandler) {
  switch (priorityLevel) {
    case ImmediatePriority:
    case UserBlockingPriority:
    case NormalPriority:
    case LowPriority:
    case IdlePriority:
      break;

    default:
      priorityLevel = NormalPriority;
  }

  var previousPriorityLevel = currentPriorityLevel;
  currentPriorityLevel = priorityLevel;

  try {
    return eventHandler();
  } finally {
    currentPriorityLevel = previousPriorityLevel;
  }
}

function unstable_next(eventHandler) {
  var priorityLevel;

  switch (currentPriorityLevel) {
    case ImmediatePriority:
    case UserBlockingPriority:
    case NormalPriority:
      // Shift down to normal priority
      priorityLevel = NormalPriority;
      break;

    default:
      // Anything lower than normal priority should remain at the current level.
      priorityLevel = currentPriorityLevel;
      break;
  }

  var previousPriorityLevel = currentPriorityLevel;
  currentPriorityLevel = priorityLevel;

  try {
    return eventHandler();
  } finally {
    currentPriorityLevel = previousPriorityLevel;
  }
}

function unstable_wrapCallback(callback) {
  var parentPriorityLevel = currentPriorityLevel;
  return function () {
    // This is a fork of runWithPriority, inlined for performance.
    var previousPriorityLevel = currentPriorityLevel;
    currentPriorityLevel = parentPriorityLevel;

    try {
      return callback.apply(this, arguments);
    } finally {
      currentPriorityLevel = previousPriorityLevel;
    }
  };
}

function unstable_scheduleCallback(priorityLevel, callback, options) {
  var currentTime = exports.unstable_now();
  var startTime;

  if (typeof options === 'object' && options !== null) {
    var delay = options.delay;

    if (typeof delay === 'number' && delay > 0) {
      startTime = currentTime + delay;
    } else {
      startTime = currentTime;
    }
  } else {
    startTime = currentTime;
  }

  var timeout;

  switch (priorityLevel) {
    case ImmediatePriority:
      timeout = IMMEDIATE_PRIORITY_TIMEOUT;
      break;

    case UserBlockingPriority:
      timeout = USER_BLOCKING_PRIORITY_TIMEOUT;
      break;

    case IdlePriority:
      timeout = IDLE_PRIORITY_TIMEOUT;
      break;

    case LowPriority:
      timeout = LOW_PRIORITY_TIMEOUT;
      break;

    case NormalPriority:
    default:
      timeout = NORMAL_PRIORITY_TIMEOUT;
      break;
  }

  var expirationTime = startTime + timeout;
  var newTask = {
    id: taskIdCounter++,
    callback: callback,
    priorityLevel: priorityLevel,
    startTime: startTime,
    expirationTime: expirationTime,
    sortIndex: -1
  };

  if (startTime > currentTime) {
    // This is a delayed task.
    newTask.sortIndex = startTime;
    push(timerQueue, newTask);

    if (peek(taskQueue) === null && newTask === peek(timerQueue)) {
      // All tasks are delayed, and this is the task with the earliest delay.
      if (isHostTimeoutScheduled) {
        // Cancel an existing timeout.
        cancelHostTimeout();
      } else {
        isHostTimeoutScheduled = true;
      } // Schedule a timeout.

      requestHostTimeout(handleTimeout, startTime - currentTime);
    }
  } else {
    newTask.sortIndex = expirationTime;
    push(taskQueue, newTask);
    // wait until the next time we yield.

    if (!isHostCallbackScheduled && !isPerformingWork) {
      isHostCallbackScheduled = true;
      requestHostCallback(flushWork);
    }
  }

  return newTask;
}

function unstable_pauseExecution() {
}

function unstable_continueExecution() {

  if (!isHostCallbackScheduled && !isPerformingWork) {
    isHostCallbackScheduled = true;
    requestHostCallback(flushWork);
  }
}

function unstable_getFirstCallbackNode() {
  return peek(taskQueue);
}

function unstable_cancelCallback(task) {
  // remove from the queue because you can't remove arbitrary nodes from an
  // array based heap, only the first one.)

  task.callback = null;
}

function unstable_getCurrentPriorityLevel() {
  return currentPriorityLevel;
}

var unstable_requestPaint = requestPaint;
var unstable_Profiling =  null;

exports.unstable_IdlePriority = IdlePriority;
exports.unstable_ImmediatePriority = ImmediatePriority;
exports.unstable_LowPriority = LowPriority;
exports.unstable_NormalPriority = NormalPriority;
exports.unstable_Profiling = unstable_Profiling;
exports.unstable_UserBlockingPriority = UserBlockingPriority;
exports.unstable_cancelCallback = unstable_cancelCallback;
exports.unstable_continueExecution = unstable_continueExecution;
exports.unstable_getCurrentPriorityLevel = unstable_getCurrentPriorityLevel;
exports.unstable_getFirstCallbackNode = unstable_getFirstCallbackNode;
exports.unstable_next = unstable_next;
exports.unstable_pauseExecution = unstable_pauseExecution;
exports.unstable_requestPaint = unstable_requestPaint;
exports.unstable_runWithPriority = unstable_runWithPriority;
exports.unstable_scheduleCallback = unstable_scheduleCallback;
exports.unstable_wrapCallback = unstable_wrapCallback;
  })();
}


text:
#pragma once
#include <aws/rds/RDS_EXPORTS.h>
#include <aws/core/utils/memory/stl/AWSStreamFwd.h>
#include <aws/core/utils/memory/stl/AWSString.h>

namespace Aws
{
namespace Utils
{
namespace Xml
{
  class XmlNode;
} // namespace Xml
} // namespace Utils
namespace RDS
{
namespace Model
{
  /*

The version of the database engine that a DB instance can be upgraded to.

  */
  class AWS_RDS_API UpgradeTarget
  {
  public:
    UpgradeTarget();
    UpgradeTarget(const Aws::Utils::Xml::XmlNode& xmlNode);
    UpgradeTarget& operator=(const Aws::Utils::Xml::XmlNode& xmlNode);

    void OutputToStream(Aws::OStream& ostream, const char* location, unsigned index, const char* locationValue) const;
    void OutputToStream(Aws::OStream& oStream, const char* location) const;

    /*

The name of the upgrade target database engine.

    */
    inline const Aws::String& GetEngine() const{ return m_engine; }

    /*

The name of the upgrade target database engine.

    */
    inline void SetEngine(const Aws::String& value) { m_engineHasBeenSet = true; m_engine = value; }

    /*

The name of the upgrade target database engine.

    */
    inline void SetEngine(Aws::String&& value) { m_engineHasBeenSet = true; m_engine = value; }

    /*

The name of the upgrade target database engine.

    */
    inline void SetEngine(const char* value) { m_engineHasBeenSet = true; m_engine.assign(value); }

    /*

The name of the upgrade target database engine.

    */
    inline UpgradeTarget& WithEngine(const Aws::String& value) { SetEngine(value); return *this;}

    /*

The name of the upgrade target database engine.

    */
    inline UpgradeTarget& WithEngine(Aws::String&& value) { SetEngine(value); return *this;}

    /*

The name of the upgrade target database engine.

    */
    inline UpgradeTarget& WithEngine(const char* value) { SetEngine(value); return *this;}

    /*

The version number of the upgrade target database engine.

    */
    inline const Aws::String& GetEngineVersion() const{ return m_engineVersion; }

    /*

The version number of the upgrade target database engine.

    */
    inline void SetEngineVersion(const Aws::String& value) { m_engineVersionHasBeenSet = true; m_engineVersion = value; }

    /*

The version number of the upgrade target database engine.

    */
    inline void SetEngineVersion(Aws::String&& value) { m_engineVersionHasBeenSet = true; m_engineVersion = value; }

    /*

The version number of the upgrade target database engine.

    */
    inline void SetEngineVersion(const char* value) { m_engineVersionHasBeenSet = true; m_engineVersion.assign(value); }

    /*

The version number of the upgrade target database engine.

    */
    inline UpgradeTarget& WithEngineVersion(const Aws::String& value) { SetEngineVersion(value); return *this;}

    /*

The version number of the upgrade target database engine.

    */
    inline UpgradeTarget& WithEngineVersion(Aws::String&& value) { SetEngineVersion(value); return *this;}

    /*

The version number of the upgrade target database engine.

    */
    inline UpgradeTarget& WithEngineVersion(const char* value) { SetEngineVersion(value); return *this;}

    /*

The version of the database engine that a DB instance can be upgraded to.

    */
    inline const Aws::String& GetDescription() const{ return m_description; }

    /*

The version of the database engine that a DB instance can be upgraded to.

    */
    inline void SetDescription(const Aws::String& value) { m_descriptionHasBeenSet = true; m_description = value; }

    /*

The version of the database engine that a DB instance can be upgraded to.

    */
    inline void SetDescription(Aws::String&& value) { m_descriptionHasBeenSet = true; m_description = value; }

    /*

The version of the database engine that a DB instance can be upgraded to.

    */
    inline void SetDescription(const char* value) { m_descriptionHasBeenSet = true; m_description.assign(value); }

    /*

The version of the database engine that a DB instance can be upgraded to.

    */
    inline UpgradeTarget& WithDescription(const Aws::String& value) { SetDescription(value); return *this;}

    /*

The version of the database engine that a DB instance can be upgraded to.

    */
    inline UpgradeTarget& WithDescription(Aws::String&& value) { SetDescription(value); return *this;}

    /*

The version of the database engine that a DB instance can be upgraded to.

    */
    inline UpgradeTarget& WithDescription(const char* value) { SetDescription(value); return *this;}

    /*

A value that indicates whether the target version will be applied to any source DB instances that have AutoMinorVersionUpgrade set to true.

    */
    inline bool GetAutoUpgrade() const{ return m_autoUpgrade; }

    /*

A value that indicates whether the target version will be applied to any source DB instances that have AutoMinorVersionUpgrade set to true.

    */
    inline void SetAutoUpgrade(bool value) { m_autoUpgradeHasBeenSet = true; m_autoUpgrade = value; }

    /*

A value that indicates whether the target version will be applied to any source DB instances that have AutoMinorVersionUpgrade set to true.

    */
    inline UpgradeTarget& WithAutoUpgrade(bool value) { SetAutoUpgrade(value); return *this;}

    /*

A value that indicates whether a database engine will be upgraded to a major version.

    */
    inline bool GetIsMajorVersionUpgrade() const{ return m_isMajorVersionUpgrade; }

    /*

A value that indicates whether a database engine will be upgraded to a major version.

    */
    inline void SetIsMajorVersionUpgrade(bool value) { m_isMajorVersionUpgradeHasBeenSet = true; m_isMajorVersionUpgrade = value; }

    /*

A value that indicates whether a database engine will be upgraded to a major version.

    */
    inline UpgradeTarget& WithIsMajorVersionUpgrade(bool value) { SetIsMajorVersionUpgrade(value); return *this;}

  private:
    Aws::String m_engine;
    bool m_engineHasBeenSet;
    Aws::String m_engineVersion;
    bool m_engineVersionHasBeenSet;
    Aws::String m_description;
    bool m_descriptionHasBeenSet;
    bool m_autoUpgrade;
    bool m_autoUpgradeHasBeenSet;
    bool m_isMajorVersionUpgrade;
    bool m_isMajorVersionUpgradeHasBeenSet;
  };

} // namespace Model
} // namespace RDS
} // namespace Aws


text:
<?php

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

namespace KtogiasZendLib\Model;

use KtogiasZendLib\Db\Table\DbTableInterface;

/**
 * Description of ReadOnlyDbTableModel
 *
 * @author ktogias
 */
abstract class ReadOnlyDbTableModel implements ReadOnlyDbTableModelInterface{

    /**
     *
     * @var \KtogiasZendLib\Db\Table\DbTableInterface
     */
    protected $table;

    /**
     *
     * @var Array
     */
    protected $fields;

    /**
     *
     * @var Array
     */
    protected $immutableFields;

    /**
     *
     * @var \Zend\ServiceManager\ServiceLocatorInterface
     */
    protected $serviceLocator;

    /**
     *
     * @return Array
     */
    public function getArrayCopy() {
        $copy = [];
        foreach ($this->fields as $field){
            $copy[$field] = $this->{$field};
        }
        return $copy;
    }

    /**
     *
     * @param array $data
     */
    public function exchangeArray(array $data) {
        if (!$this->isEmpty() && !$this->respectsImmutableFields($data)){
            throw new Exception\DbTableModelImmutableFieldChangeException();
        }
        foreach($this->fields as $field){
            if (isset($data[$field])){
                if(is_object($data[$field]) && get_class($data[$field]) == 'DateTime'){
                    $this->{$field} = $data[$field]->format('Y-m-d H:i:s');
                }
                else {
                    $this->{$field} = $data[$field];
                }
            }
            else {
                $this->{$field} = null;
            }
        }
    }

    public function isEmpty(){
        foreach($this->fields as $field){
            if ($this->{$field} !== NULL){
                return false;
            }
        }
        return true;
    }

    private function respectsImmutableFields(array $data){
        if (!empty($this->immutableFields)){
            foreach($this->immutableFields as $field){
                if ($this->{$field} !== $data[$field]){
                    return false;
                }
            }
        }
        return true;
    }

    /**
     *
     * @param type $id
     * @return \KtogiasZendLib\Model\ReadOnlyDbTableModelInterface
     */
    public function load($id){
        $modelObject = $this->table->fetchById($id, TRUE);
        $this->exchangeArray($modelObject->getArrayCopy());
        return $this;
    }

    /**
     *
     * @param \KtogiasZendLib\Db\Table\DbTableInterface $table
     * @return \KtogiasZendLib\Model\ReadOnlyDbTableModelInterface
     */
    public function setTable(DbTableInterface $table) {
        $this->table = $table;
        return $this;
    }

    /**
     *
     * @return scalar or array
     */
    public function getId(){
        if (is_array($this->table->getPrimaryKey())){
            $id = [];
            foreach ($this->table->getPrimaryKey() as $field){
                $id[$field] = $this->{$field};
            }
            return $id;
        }
        else {
            return $this->{$this->table->getPrimaryKey()};
        }
    }

    /**
     *
     * @return \KtogiasZendLib\Db\Table\DbTableInterface
     */
    public function getTable() {
        return $this->table;
    }

    /**
     *
     * @param \Zend\ServiceManager\ServiceLocatorInterface $sl
     */
    public function setServiceLocator(\Zend\ServiceManager\ServiceLocatorInterface $sl) {
        $this->serviceLocator = $sl;
    }

    /**
     *
     * @param string $field
     * @return string
     */
    public function getField($field) {
        if (!in_array($field, $this->fields)){
            throw new Exception\NotExistentFieldException($field);
        }
        return $this->{$field};
    }

    /**
     *
     * @return \Zend\ServiceManager\ServiceLocatorInterface
     */
    public function getServiceLocator() {
        return $this->serviceLocator;
    }

    /**
     *
     * @return $this
     */
    public function clearCache() {
        return $this;
    }

    /**
     *
     * @param array $expand
     * @throws \KtogiasZendLib\Model\Exception\DbTableModelExpansionException
     * @return array
     */
    public function getArrayCopyExpanded(array $expand) {
       if (!empty($expand)){
            throw new Exception\DbTableModelExpansionException('Unable to expand '.json_encode($expand));
       }
       return $this->getArrayCopy();
    }
}


text:
package main

import (
	"go/ast"
	"go/types"
)

var (
	httpResponseType types.Type
	httpClientType   types.Type
)

func init() {
	if typ := importType("net/http", "Response"); typ != nil {
		httpResponseType = typ
	}
	if typ := importType("net/http", "Client"); typ != nil {
		httpClientType = typ
	}
	// if http.Response or http.Client are not defined don't register this check.
	if httpResponseType == nil || httpClientType == nil {
		return
	}

	register("httpresponse",
		"check errors are checked before using an http Response",
		checkHTTPResponse, callExpr)
}

func checkHTTPResponse(f *File, node ast.Node) {
	call := node.(*ast.CallExpr)
	if !isHTTPFuncOrMethodOnClient(f, call) {
		return // the function call is not related to this check.
	}

	finder := &blockStmtFinder{node: call}
	ast.Walk(finder, f.file)
	stmts := finder.stmts()
	if len(stmts) < 2 {
		return // the call to the http function is the last statement of the block.
	}

	asg, ok := stmts[0].(*ast.AssignStmt)
	if !ok {
		return // the first statement is not assignment.
	}
	resp := rootIdent(asg.Lhs[0])
	if resp == nil {
		return // could not find the http.Response in the assignment.
	}

	def, ok := stmts[1].(*ast.DeferStmt)
	if !ok {
		return // the following statement is not a defer.
	}
	root := rootIdent(def.Call.Fun)
	if root == nil {
		return // could not find the receiver of the defer call.
	}

	if resp.Obj == root.Obj {
		f.Badf(root.Pos(), "using %s before checking for errors", resp.Name)
	}
}

// isHTTPFuncOrMethodOnClient checks whether the given call expression is on
// either a function of the net/http package or a method of http.Client that
// returns (*http.Response, error).
func isHTTPFuncOrMethodOnClient(f *File, expr *ast.CallExpr) bool {
	fun, _ := expr.Fun.(*ast.SelectorExpr)
	sig, _ := f.pkg.types[fun].Type.(*types.Signature)
	if sig == nil {
		return false // the call is not on of the form x.f()
	}

	res := sig.Results()
	if res.Len() != 2 {
		return false // the function called does not return two values.
	}
	if ptr, ok := res.At(0).Type().(*types.Pointer); !ok || !types.Identical(ptr.Elem(), httpResponseType) {
		return false // the first return type is not *http.Response.
	}
	if !types.Identical(res.At(1).Type().Underlying(), errorType) {
		return false // the second return type is not error
	}

	typ := f.pkg.types[fun.X].Type
	if typ == nil {
		id, ok := fun.X.(*ast.Ident)
		return ok && id.Name == "http" // function in net/http package.
	}

	if types.Identical(typ, httpClientType) {
		return true // method on http.Client.
	}
	ptr, ok := typ.(*types.Pointer)
	return ok && types.Identical(ptr.Elem(), httpClientType) // method on *http.Client.
}

// blockStmtFinder is an ast.Visitor that given any ast node can find the
// statement containing it and its succeeding statements in the same block.
type blockStmtFinder struct {
	node  ast.Node       // target of search
	stmt  ast.Stmt       // innermost statement enclosing argument to Visit
	block *ast.BlockStmt // innermost block enclosing argument to Visit.
}

// Visit finds f.node performing a search down the ast tree.
// It keeps the last block statement and statement seen for later use.
func (f *blockStmtFinder) Visit(node ast.Node) ast.Visitor {
	if node == nil || f.node.Pos() < node.Pos() || f.node.End() > node.End() {
		return nil // not here
	}
	switch n := node.(type) {
	case *ast.BlockStmt:
		f.block = n
	case ast.Stmt:
		f.stmt = n
	}
	if f.node.Pos() == node.Pos() && f.node.End() == node.End() {
		return nil // found
	}
	return f // keep looking
}

// stmts returns the statements of f.block starting from the one including f.node.
func (f *blockStmtFinder) stmts() []ast.Stmt {
	for i, v := range f.block.List {
		if f.stmt == v {
			return f.block.List[i:]
		}
	}
	return nil
}

// rootIdent finds the root identifier x in a chain of selections x.y.z, or nil if not found.
func rootIdent(n ast.Node) *ast.Ident {
	switch n := n.(type) {
	case *ast.SelectorExpr:
		return rootIdent(n.X)
	case *ast.Ident:
		return n
	default:
		return nil
	}
}


text:
<?php

namespace Cyve\CoreBundle\Service;

use Doctrine\ORM\EntityManagerInterface;
use Symfony\Bundle\TwigBundle\TwigEngine;
use Symfony\Component\ExpressionLanguage\ExpressionLanguage;
use Symfony\Component\Routing\RouterInterface;
use Symfony\Component\Config\Definition\Exception\InvalidConfigurationException;

class SitemapGenerator
{
	/**
	 * @var RouterInterface
	 */
	private $router;

	/**
	 * @var EntityManagerInterface
	 */
	private $em;

	/**
	 * @var TwigEngine
	 */
	private $engine;

	/**
	 * @var array
	 */
	private $parameters;

	/**
	 * Constructor
	 */
	public function __construct(RouterInterface $router, EntityManagerInterface $em, TwigEngine $engine)
	{
		$this->router = $router;
		$this->em = $em;
		$this->engine = $engine;
	}

	/**
	 * @param array $parameters
	 */
	public function setParameters($parameters)
	{
		$this->parameters = $parameters;
	}

	/**
	 * @param string $template
	 * @return string
	 */
	public function generate($template = 'CyveCoreBundle:sitemap:sitemap.xml.twig')
	{
		$urls = $this->generateUrls();

		return $this->engine->render($template, ['urls' => $urls]);
	}

	/**
	 * @return generator
	 */
	public function generateUrls()
	{
		$language = new ExpressionLanguage();

		if(!$this->parameters['enabled']) throw new InvalidConfigurationException('No configuration found for sitemap. Did you set the "cyve_core.sitemap" section in config.yml ?');
		if(empty($this->parameters['routes'])) throw new InvalidConfigurationException('No URLs to generate in sitemap. Did you set the "cyve_core.sitemap.routes" section in config.yml ?');

		foreach($this->parameters['routes'] as $route){
			if(empty($route['name'])) continue;

			if(isset($route['entity'])){
				$entities = $this->em->getRepository($route['entity'])->findAll();
				foreach($entities as $entity){
					$parameters = array_map(function($parameter) use ($language, $entity){
						return $language->evaluate($parameter, ['entity' => $entity]);
					}, $route['parameters']);

					yield $this->generateUrl(array_merge($route, ['parameters' => $parameters]));
				}
			}
			else{
				yield $this->generateUrl($route);
			}
		}
	}

	/**
	 * @param array $route
	 * @return array
	 */
	private function generateUrl($route)
	{
		$url = ['loc' => $this->router->generate($route['name'], $route['parameters'] ?? [], RouterInterface::ABSOLUTE_URL)];
		if(isset($route['changefreq'])) $url['changefreq'] = $route['changefreq'];
		if(isset($route['priority'])) $url['priority'] = $route['priority'];

		return $url;
	}
}


text:
package com.iluwatar.common;

import java.util.List;

/**
 *
 * Dao interface.
 *
 * @param <E>
 *
 */
public interface Dao<E extends BaseEntity> {

	E find(Long id);

	void persist(E entity);

	E merge(E entity);

	void delete(E entity);

	List<E> findAll();
}


text:
@implementation UIScrollView (Refresh)
- (void)configHeader{
    //自定义的刷新动画
    NSArray *images0 = @[[UIImage imageNamed:@"img_top_refresh_gy1"],[UIImage imageNamed:@"img_top_refresh_gy2"],[UIImage imageNamed:@"img_top_refresh_gy3"],[UIImage imageNamed:@"img_top_refresh_gy4"],[UIImage imageNamed:@"img_top_refresh_gy5"],[UIImage imageNamed:@"img_top_refresh_gy6"]];
    NSArray *images1 = @[[UIImage imageNamed:@"img_top_refresh_swz1"],[UIImage imageNamed:@"img_top_refresh_swz2"],[UIImage imageNamed:@"img_top_refresh_swz3"],[UIImage imageNamed:@"img_top_refresh_swz4"],[UIImage imageNamed:@"img_top_refresh_swz5"],[UIImage imageNamed:@"img_top_refresh_swz6"],[UIImage imageNamed:@"img_top_refresh_swz7"],[UIImage imageNamed:@"img_top_refresh_swz8"]];
    NSArray *images2 = @[[UIImage imageNamed:@"img_top_refresh_swzd1"],[UIImage imageNamed:@"img_top_refresh_swzd2"],[UIImage imageNamed:@"img_top_refresh_swzd3"],[UIImage imageNamed:@"img_top_refresh_swzd4"],[UIImage imageNamed:@"img_top_refresh_swzd5"],[UIImage imageNamed:@"img_top_refresh_swzd6"],[UIImage imageNamed:@"img_top_refresh_swzd7"],[UIImage imageNamed:@"img_top_refresh_swzd8"],[UIImage imageNamed:@"img_top_refresh_swzd9"],[UIImage imageNamed:@"img_top_refresh_swzd10"],[UIImage imageNamed:@"img_top_refresh_swzd11"],[UIImage imageNamed:@"img_top_refresh_swzd12"],[UIImage imageNamed:@"img_top_refresh_swzd13"],[UIImage imageNamed:@"img_top_refresh_swzd14"]];
    NSArray *images3 = @[[UIImage imageNamed:@"img_top_refresh_sx1"],[UIImage imageNamed:@"img_top_refresh_sx2"],[UIImage imageNamed:@"img_top_refresh_sx3"],[UIImage imageNamed:@"img_top_refresh_sx4"],[UIImage imageNamed:@"img_top_refresh_sx5"],[UIImage imageNamed:@"img_top_refresh_sx6"],[UIImage imageNamed:@"img_top_refresh_sx7"],[UIImage imageNamed:@"img_top_refresh_sx8"],[UIImage imageNamed:@"img_top_refresh_sx9"],[UIImage imageNamed:@"img_top_refresh_sx10"],[UIImage imageNamed:@"img_top_refresh_sx11"]];
    ZXRefreshHeader *header = (ZXRefreshHeader *)self.mj_header;
    [header placeSubviews];
    header.lastUpdatedTimeLabel.hidden = YES;
    header.stateLabel.hidden = YES;
    NSInteger num = arc4random() % 4;
    NSArray *im = @[images0, images1, images2, images3][num];
    header.label.text = @[@"来嘛..", @"浪哩个浪~", @"嘿嘿嘿嘿~", @"刷一刷,再扭一扭"][num];
    [header setImages:im forState:MJRefreshStateIdle];
    [header setImages:im forState:MJRefreshStatePulling];
    [header setImages:im forState:MJRefreshStateRefreshing];
}
- (void)addHeaderRefresh:(void(^)())block
{
   ZXRefreshHeader* header = [ZXRefreshHeader headerWithRefreshingBlock:^{
       !block ?: block();
   }];
    self.mj_header = header;
    [self configHeader];
}

- (void)endHeaderRefresh
{
    [self.mj_header endRefreshing];
}

- (void)beginHeaderRefresh
{
    [self.mj_header beginRefreshing];
}

- (void)addFooterRefresh:(void(^)())block
{
    NSArray* image = @[[UIImage imageNamed:@"bubble_0_57x63_"]];
    NSMutableArray* images = [NSMutableArray new];
    for (int i = 1; i < 19; i++ ) {
        UIImage * image = [UIImage imageNamed:[NSString stringWithFormat:@"bubble_%d_57x63_",i]];
        [images addObject:image];
    }
    MJRefreshAutoGifFooter *footer = [MJRefreshAutoGifFooter footerWithRefreshingBlock:block];

    [footer setImages:image forState:MJRefreshStatePulling];
    [footer setImages:image forState:MJRefreshStateIdle];
    [footer setImages:image forState:MJRefreshStateRefreshing];
    self.mj_footer = footer;

}
- (void)endFooterRefresh
{
     [self.mj_footer endRefreshing];
}

- (void)endFooterRefreshWithNoMoreData;
{
     [self.mj_footer endRefreshingWithNoMoreData];
}

@end


text:
package net.anotheria.moskito.core.util;

import net.anotheria.moskito.core.accumulation.Accumulators;
import net.anotheria.moskito.core.predefined.OSStats;
import net.anotheria.moskito.core.producers.IStats;
import net.anotheria.moskito.core.producers.IStatsProducer;
import net.anotheria.moskito.core.registry.ProducerRegistryFactory;
import org.apache.commons.lang3.SystemUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.lang.management.ManagementFactory;
import java.lang.management.OperatingSystemMXBean;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.TimerTask;

/**
 * Builtin producer for values supplied by jmx for the operation system.
 *
 * @author lrosenberg
 */
public class BuiltInOSProducer extends AbstractBuiltInProducer implements IStatsProducer, BuiltInProducer {
	/**
	 * Associated stats.
	 */
	private OSStats stats;
	/**
	 * Stats container
	 */
	private List<IStats> statsList;

	/**
	 * The monitored pool.
	 */
	private OperatingSystemMXBean mxBean;

	/**
	 * Name of the mxbean class.
	 */
	private static final String clazzname = "com.sun.management.UnixOperatingSystemMXBean";

	/**
	 * Resolved class of the mx bean.
	 */
	private Class<?> clazz;

	/** The Constant BITS_TO_BYTES_FACTOR. */
	private static final int BITS_TO_BYTES_FACTOR = 1024;

	/**
	 * If true indicates.
	 */
	private final boolean isUnixOS = SystemUtils.IS_OS_UNIX;
	private final boolean isWindowsOS = SystemUtils.IS_OS_WINDOWS;

	/**
	 * Logger.
	 */
	private static Logger log = LoggerFactory.getLogger(BuiltInOSProducer.class);

	public BuiltInOSProducer() {
		mxBean = ManagementFactory.getOperatingSystemMXBean();
		statsList = new ArrayList<IStats>(1);
		stats = new OSStats();
		statsList.add(stats);

		try {
			clazz = Class.forName(clazzname);
		} catch (ClassNotFoundException e) {
			log.warn("Couldn't find unix version of os class: " + clazzname + ", osstats won't operate properly - " + e.getMessage());
		}

		if (!isUnixOS) {
			log.warn("Couldn't find unix version of os class: " + clazzname
					+ ", osstats won't operate properly for all stats. Current type is: "
					+ mxBean.getClass().getName());
		}

		BuiltinUpdater.addTask(new TimerTask() {
			@Override
			public void run() {
				readMbean();
			}
		});

		ProducerRegistryFactory.getProducerRegistryInstance().registerProducer(this);

		Accumulators.setupCPUAccumulators();
	}

	@Override
	public String getCategory() {
		return "os";
	}

	@Override
	public String getProducerId() {
		return "OS";
	}

	@Override
	public List<IStats> getStats() {
		return statsList;
	}

	/**
	 * Reads the management bean and extracts monitored data on regular base.
	 */
	private void readMbean() {
		if (clazz == null) {
			return;
		}
		try {
			if (isUnixOS) {
				long openFiles = getValue("OpenFileDescriptorCount");
				long maxOpenFiles = getValue("MaxFileDescriptorCount");

				long freePhysicalMemorySize = getValue("FreePhysicalMemorySize");
				long totalPhysicalMemorySize = getValue("TotalPhysicalMemorySize");

				long processTime = getValue("ProcessCpuTime");

				double processCPULoad = getDoubleValue("ProcessCpuLoad");
				double systemCPULoad = getDoubleValue("SystemCpuLoad");

				long processors = getValue("AvailableProcessors");

				stats.update((int) openFiles, (int) maxOpenFiles, freePhysicalMemorySize, totalPhysicalMemorySize, processTime, (int) processors, processCPULoad, systemCPULoad);

			} else if (isWindowsOS) {
				long processors = getValue("AvailableProcessors");
				double systemCPULoad = readWindowsCPULoad();

				long totalPhysicalMemorySize = readWindowsTotalMemory();
				long freePhysicalMemorySize = readWindowsFreeMemory();

				stats.update(-1, -1, freePhysicalMemorySize, totalPhysicalMemorySize, -1, (int) processors, -1, systemCPULoad);

			} else {
				long processors = getValue("AvailableProcessors");

				stats.update(-1, -1, -1, -1, -1, (int) processors, -1, -1);
			}

		} catch (Exception e) {
			log.warn("Couldn't read value due to", e);
		}
	}

	private long getValue(String name) throws NoSuchMethodException, IllegalAccessException, InvocationTargetException {
		Method m = clazz.getMethod("get" + name);
		if (name.equals("AvailableProcessors"))
			return (Integer) m.invoke(mxBean);
		Long result = (Long) m.invoke(mxBean);
		return result;
	}

	private double getDoubleValue(String name) throws NoSuchMethodException, IllegalAccessException, InvocationTargetException {
		Method m = clazz.getMethod("get" + name);
		Double result = (Double) m.invoke(mxBean);
		return result;
	}

	public static void main(String[] a) {
		new BuiltInOSProducer();
	}

	private static long readWindowsTotalMemory() {
		Long result = 0L;

		try {
			String[] command = "wmic OS get TotalVisibleMemorySize /Value".split(" ");
			String line = executeMemoryInfoProcess(command); // Output should be something like 'TotalVisibleMemorySize=8225260'
			result = Long.parseLong(line.substring(line.indexOf("=") + 1)) * BITS_TO_BYTES_FACTOR; // convert it to bytes
		} catch (Exception e) {
			log.error("unable to get TotalVisibleMemorySize from wmic", e);
		}

		return result.longValue();
	}

	private static long readWindowsFreeMemory() {
		Long result = 0L;

		try {
			String[] command = "wmic OS get FreePhysicalMemory /Value".split(" ");
			String line = executeMemoryInfoProcess(command); // Output should be something like 'FreePhysicalMemory=8225260'
			result = Long.parseLong(line.substring(line.indexOf("=") + 1)) * BITS_TO_BYTES_FACTOR; // convert it to bytes
		} catch (Exception e) {
			log.error("unable to get FreePhysicalMemory from wmic", e);
		}

		return result.longValue();
	}

	private static double readWindowsCPULoad() {
		Double result = 0d;

		try {
			String[] command = "wmic cpu get LoadPercentage /Value".split(" ");
			String line = executeMemoryInfoProcess(command); // Output should be something like 'LoadPercentage=27'
			result = Double.parseDouble(line.substring(line.indexOf("=") + 1)) / 100; // convert 27% to 0.27 to be represented such as unix's SystemCpuLoad
		} catch (Exception e) {
			log.error("unable to get LoadPercentage from wmic", e);
		}

		return result.doubleValue();
	}

	private static String executeMemoryInfoProcess(String... command) throws IOException {
		ProcessBuilder procBuilder = new ProcessBuilder(command);
		Process process = procBuilder.start();

		InputStream is = process.getInputStream();
		InputStreamReader isr = new InputStreamReader(is);
		BufferedReader br = new BufferedReader(isr);
		try {
			String line;
			while ((line = br.readLine()) != null) {
				if (line.trim().isEmpty()) {
					continue;
				}
				return line;
			}
		} catch (IOException e1) {
			throw e1;
		} finally {
			br.close();
		}
		throw new IOException("Could not read memory process output for command " + Arrays.toString(command));
	}

}


text:
/******************************************************************************
 *  Compilation:  javac PercolationVisualizer.java
 *  Execution:    java PercolationVisualizer input.txt
 *  Dependencies: Percolation.java
 *
 *  This program takes the name of a file as a command-line argument.
 *  From that file, it
 *
 *    - Reads the grid size N of the percolation system.
 *    - Creates an N-by-N grid of sites (intially all blocked)
 *    - Reads in a sequence of sites (row i, column j) to open.
 *
 *  After each site is opened, it draws full sites in light blue,
 *  open sites (that aren't full) in white, and blocked sites in black,
 *  with with site (0, 0) in the upper left-hand corner.
 *
 ******************************************************************************/
package utils;
import java.awt.Font;

import edu.princeton.cs.algs4.In;
import edu.princeton.cs.algs4.StdDraw;
import main.Percolation;
public class PercolationVisualizer {

    // delay in miliseconds (controls animation speed)
    private static final int DELAY = 100;

    // draw N-by-N percolation system
    public static void draw(Percolation perc, int N) {
        StdDraw.clear();
        StdDraw.setPenColor(StdDraw.BLACK);
        StdDraw.setXscale(-.05*N, 1.05*N);
        StdDraw.setYscale(-.05*N, 1.05*N);   // leave a border to write text
        StdDraw.filledSquare(N/2.0, N/2.0, N/2.0);

        // draw N-by-N grid
        for (int row = 0; row < N; row++) {
            for (int col = 0; col < N; col++) {
                if (perc.isFull(row, col)) {
                    StdDraw.setPenColor(StdDraw.BOOK_LIGHT_BLUE);
                }
                else if (perc.isOpen(row, col)) {
                    StdDraw.setPenColor(StdDraw.WHITE);
                }
                else {
                    StdDraw.setPenColor(StdDraw.BLACK);
                }
                StdDraw.filledSquare(col + 0.5, N - row - 0.5, 0.45);
            }
        }

        // write status text
        StdDraw.setFont(new Font("SansSerif", Font.PLAIN, 12));
        StdDraw.setPenColor(StdDraw.BLACK);
        StdDraw.text(.25*N, -N*.025, perc.numberOfOpenSites() + " open sites");
        if (perc.percolates()) StdDraw.text(.75*N, -N*.025, "percolates");
        else                   StdDraw.text(.75*N, -N*.025, "does not percolate");

    }

    private static void simulateFromFile(String filename) {
        In in = new In(filename);
        int N = in.readInt();
        Percolation perc = new Percolation(N);

        // turn on animation mode
        StdDraw.show(0);

        // repeatedly read in sites to open and draw resulting system
        draw(perc, N);
        StdDraw.show(DELAY);
        while (!in.isEmpty()) {
            int i = in.readInt();
            int j = in.readInt();
            perc.open(i, j);
            draw(perc, N);
            StdDraw.show(DELAY);
        }
    }

    public static void main(String[] args) {
        String filename = args[0];
        simulateFromFile(filename);
    }
}


text:
namespace Fort
{
  SyncIO::SyncIO(int readers, int writers, int total)
    : using_total_(total ? true : false),
      available_{ {total, readers, writers} },
      wakeups_{ {0, 0, 0} }
  { }

  void SyncIO::acquire(int type)
  {
    // Always grab one from the total first, if we're using one
    if( type != TOTAL && using_total_ )
    {
      this->acquire(TOTAL);
    }

    // Acquire lock in this scope
    std::unique_lock<std::mutex> lock(mutex_[type]);

    // Claim an appropriate number of instances of the resource
    available_[type]--;

    // Do we need to block until resource becomes available?
    if( available_[type] < 0 )
    {
      // Wait until woken; if woken check that it is non-spurious (i.e.
      // there are a positive number of unclaimed genuine wake-ups) and
      // re-wait otherwise
      cond_[type].wait(lock, [&]() { return (wakeups_[type] > 0); });

      // Genuine wakeup acknowledged
      wakeups_[type]--;
    }

    return;
  }

  void SyncIO::release(int type)
  {
    // Release one from the total, if we're using one
    if( type != TOTAL && using_total_ )
    {
      this->release(TOTAL);
    }

    // Acquire lock in this scope
    std::unique_lock<std::mutex> lock(mutex_[type]);

    // Release one unit of resource
    available_[type]++;

    // Anyone waiting?
    if( available_[type] <= 0 )
    {
      // We are about to generate a genuine wake-up
      wakeups_[type]++;

      // Notify any thread of the appropriate type
      cond_[type].notify_one();
    }

    return;
  }

}


text:
// Copyright 2018 Google LLC
//
// 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
//
//     https://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.

using GooglePlayInstant.Editor.QuickDeploy;
using NUnit.Framework;

namespace GooglePlayInstant.Tests.Editor.QuickDeploy
{
    /// <summary>
    /// Contains unit tests for LoadingBarGenerator methods.
    /// </summary>
    [TestFixture]
    public class LoadingBarGeneratorTest
    {
        [Test]
        public void TestFindLoadingTileTexture()
        {
            Assert.IsNotNull(LoadingBarGenerator.FindLoadingTileTexture());
        }
    }
}


text:
require 'active_support'
require 'active_support/rails'
require 'action_cable/version'

module ActionCable
  extend ActiveSupport::Autoload

  INTERNAL = {
    identifiers: {
      ping: '_ping'.freeze
    },
    message_types: {
      confirmation: 'confirm_subscription'.freeze,
      rejection: 'reject_subscription'.freeze
    }
  }

  # Singleton instance of the server
  module_function def server
    @server ||= ActionCable::Server::Base.new
  end

  autoload :Server
  autoload :Connection
  autoload :Channel
  autoload :RemoteConnections
end


text:
Tiempo antes de darse por vencido

Si la entrega de un mensaje falla por alguna razón temporal (como que el
servidor destinatario esté caído), sendmail mantendrá el correo en su
cola por la cantidad de tiempo especificado por esta opción, reintentando
la entrega ocasionálmente. Una vez que el tiempo límite se alcance, un
mensaje a poner en la calle será enviado de vuelva al remitente y el mensaje
será descartado.

<include units.es>


text:
package com.hmapvis.service.impl;

import java.util.List;

import org.hibernate.Query;
import org.hibernate.classic.Session;
import org.springframework.stereotype.Service;

import com.hmapvis.bean.EventRela;
import com.hmapvis.service.EventRelaService;

@Service("eventrelaService")
public class EventRelaServiceImpl extends BaseServiceImpl<EventRela, Integer>
		implements EventRelaService {

	public List<EventRela> eventrelation(int event_id) {

		String hql = "select e from EventRela e where e.event_id1 = "+event_id;
		List<EventRela> list = (List<EventRela>) sessionFactory.getCurrentSession().createQuery(hql).setCacheable(true).list();
		return list;
	}

	public Object saveeventrelation(int event_id1, int event_id2,
			int relation_id) {
		Session session = sessionFactory.getCurrentSession();

		String sql_insert_event_relation = "insert into event_rela (event_id1,event_id2,relation_id) values "
				+ "("
				+ event_id1
				+ ","
				+ event_id2
				+ ","
				+ relation_id + ")";
		Query query_insert_event_relation  = (Query) session
				.createSQLQuery(sql_insert_event_relation);
		return query_insert_event_relation.executeUpdate();

	}

}


text:
<project>
  <modelVersion>4.0.0</modelVersion>
  <groupId>com.redhat.bayessian.test</groupId>
  <artifactId>test-app-minimal</artifactId>
  <version>1</version>
</project>


text:
const fs = require('fs');

function AssetFingerprint(initializerDirectory, needsFingerprint = true, fingerprintName) {
  _validateInitializerDirectory();
  this.initializerDirectory = initializerDirectory;
  this.initializerPath = `${this.initializerDirectory}/asset_fingerprint.rb`;

  if(fingerprintName) {
    _validateFingerprintName(fingerprintName);

    if(_checkForExistingFingerprint(fingerprintName, this.initializerPath)) {
      throw new Error('The provided fingerprint name has already been used.');
    }
  }

  this.needsFingerprint = needsFingerprint;
  this.fingerprintName = fingerprintName || 'ASSET_FINGERPRINT';

  function _validateInitializerDirectory() {
    if (initializerDirectory === undefined) {
      throw new Error('Please supply a directory path for your initializer, such as `config/initializers`.');
    }
  }

  function _validateFingerprintName(fingerprintName) {
    if(!/^([A-Z]|_)*_FINGERPRINT$/.test(fingerprintName)) {
      throw new Error('Please supply a fingerprint name that is all caps separating words by underscores ending with "_FINGERPRINT" (i.e. CUSTOM_ASSET_FINGERPRINT).');
    }
  }

  function _checkForExistingFingerprint(fingerprintName, initializerPath) {
    if(fs.existsSync(initializerPath)) {
      let file = fs.readFileSync(initializerPath, "utf8");
      return file.indexOf(fingerprintName) >= 0;
    } else {
      return false;
    }
  }
}

AssetFingerprint.prototype.apply = function(compiler) {
  compiler.plugin('done', function(stats) {
    if (this.needsFingerprint) {
        let defaultRun = this.fingerprintName === 'ASSET_FINGERPRINT';
        const newline = defaultRun ? '' : '\r\n';
        const fsMethod = defaultRun ? 'writeFileSync' : 'appendFileSync';
        let output = `${newline}${this.fingerprintName} = '${stats.hash}'`;
        fs[fsMethod](this.initializerPath, output);
        console.log(`asset-fingerprint-webpack-rails: updated file ${this.initializerPath} with ${this.fingerprintName} = ${stats.hash}`)
    }
  }.bind(this));
}

module.exports = AssetFingerprint;


text:
/*
 * All Rights Reserved.
 *
 * ClearSilver Templating System
 *
 * This code is made available under the terms of the ClearSilver License.
 * http://www.clearsilver.net/license.hdf
 *
 */

#ifndef __NEO_AUTO_H_
#define __NEO_AUTO_H_ 1

__BEGIN_DECLS

struct _neos_auto_ctx;
typedef struct _neos_auto_ctx NEOS_AUTO_CTX;

/*
 * Function: neos_auto_escape - Escape input according to auto-escape context.
 * Description: neos_auto_escape takes an auto-escape context, determines the
 *              escaping modifications needed to make input safe in that context.
 *              It applies these modifications to the input string. It will
 *              first determine if any modifications are necessary, if not - the
 *              input string is returned as output.
 * Input: ctx -> an object specifying the currrent auto-escape context.
 *        str -> input string which will be escaped.
 *
 * Output: esc -> the escaped string will be returned in this pointer.
 *         do_free -> if *do_free is true, *esc should be freed. If not, *esc
 *         contains str and should not be freed.
 * Returns: NERR_NOMEM if unable to allocate memory for output.
 *          NERR_ASSERT if any of the supplied pointers are NULL.
 */
NEOERR *neos_auto_escape(NEOS_AUTO_CTX *ctx, const char* str,
                         char **esc, int *do_free);

/*
 * Function: neos_auto_parse_var - Parse input if parser is in interesting state.
 * Description: neos_auto_parse_var takes an auto-escape context, which contains
 *              a pointer to the underlying htmlparser. It passes the input
 *              string to the htmlparser, if the input occurs inside a tag
 *              definition.
 * Input: ctx -> an object specifying the currrent auto-escape context.
 *        str -> input string to parse.
 *        len -> length of str.
 *
 * Output: None
 * Returns: NERR_ASSERT if any of the supplied pointers are NULL.
 */
NEOERR *neos_auto_parse_var(NEOS_AUTO_CTX *ctx, const char *str, int len);

/*
 * Function: neos_auto_parse - Parse input and update auto-escape context.
 * Description: neos_auto_parse takes an auto-escape context, which contains a
 *              pointer to the underlying htmlparser. It passes the input string
 *              to the htmlparser, which updates its internal state accordingly.
 * Input: ctx -> an object specifying the currrent auto-escape context.
 *        str -> input string to parse.
 *        len -> length of str.
 *
 * Output: None
 *
 * Returns: NERR_ASSERT if ctx or str is NULL.
 */
NEOERR *neos_auto_parse(NEOS_AUTO_CTX *ctx, const char *str, int len);

/*
 * Function: neos_auto_init - Create and initialize a NEOS_AUTO_CTX object.
 * Description: Returns an initialized NEOS_AUTO_CTX object, by internally
 *              initializing an htmlparser object.
 * Input: pctx -> pointer to pointer to NEOS_AUTO_CTX structure.
 *
 * Output: pctx -> will contain the newly initialized NEOS_AUTO_CTX object.
 * Returns: NERR_NOMEM if unable to allocate memory for *pctx.
 *          NERR_ASSERT if pctx is NULL.
 */
NEOERR *neos_auto_init(NEOS_AUTO_CTX **pctx);

/*
 * Function: neos_auto_reset - Re-initialize an existing NEOS_AUTO_CTX object.
 * Description: Create the associated htmlparser object if it does not exist,
 *              or reset the existing one.
 * Input: ctx -> pointer to an existing NEOS_AUTO_CTX structure.
 *
 * Output: ctx -> will contain the re-initialized NEOS_AUTO_CTX object.
 * Returns: NERR_NOMEM if unable to allocate memory for *pctx.
 *          NERR_ASSERT if pctx is NULL.
 */
NEOERR* neos_auto_reset(NEOS_AUTO_CTX *ctx);

/*
 * Function: neos_auto_destroy - Free the NEOS_AUTO_CTX object.
 * Description: Calls htmlparser_delete to free the associated htmlparser object.
 * Input: pctx -> pointer to pointer that should be freed.
 *
 * Output: None.
 *
 * Returns: None.
 */
void neos_auto_destroy(NEOS_AUTO_CTX **pctx);

/*
 * Function: neos_auto_set_content_type - Sets expected content type of input.
 * Description: Takes a MIME type header, and configures the underlying
 *              htmlparser object to expect input of the corresponding type.
 *              This functionality is provided for situations where the html
 *              parser cannot itself determine the proper starting context of
 *              the input, for instance - when a javascript source file or a
 *              stylesheet is being parsed.
 *              This function should be called before any input is processed
 *              using neos_auto_parse().
 * Input: ctx -> an object specifying the currrent auto-escape context.
 *        type -> the MIME type of input. Currently supported MIME types are:
 *               "text/html", "text/xml", "text/plain", "application/xhtml+xml",
 *               "application/javascript", "application/json", "text/javascript"
 *
 * Output: None.
 *
 * Returns: NERR_ASSERT for unknown content type.
 */
NEOERR *neos_auto_set_content_type(NEOS_AUTO_CTX *ctx, const char *type);

__END_DECLS

#endif /* __NEO_AUTO_H_ */


text:
// Provides helper sap.ui.core.EnabledPropagator
sap.ui.define(['./Control'],
	function(Control) {
	"use strict";

	/**
	 * @class Helper Class for enhancement of a Control with propagation of enabled property.
	 *
	 * This constructor should be applied to the prototype of a control
	 *
	 * Example:
	 *
	 * sap.ui.core.EnabledPropagator.call(Some-Control.prototype, Default-value, ...);
	 *
	 * e.g.
	 *
	 * sap.ui.core.EnabledPropagator.call(sap.ui.commons.Button.prototype);
	 *
	 *
	 * @author Daniel Brinkmann
	 * @version 1.50.8
	 * @param {boolean} [bDefault=true] the value that should be used as default value for the enhancement of the control.
	 * @param {boolean} [bLegacy=false] whether the introduced property should use the old name 'Enabled'
	 * @public
	 * @alias sap.ui.core.EnabledPropagator
	 */
	var EnabledPropagator = function(bDefault, bLegacy) {
		// Ensure only Controls are enhanced
		if (!(this instanceof Control)) {
			throw new Error("EnabledPropagator only supports subclasses of Control"); // TODO clarify why. Daniel has added this check, but it is not obvious why?
		}

		// default for the default
		if ( bDefault === undefined ) {
			bDefault = true;
		}

		// helper to find a parent that has a getEnabled() method
		function findParentWithEnabled(/**sap.ui.core.Control*/oControl) {
			var oParent = oControl.getParent();
			while (oParent && !oParent.getEnabled && oParent.getParent) {
				oParent = oParent.getParent();
			}
			return oParent;
		}

		// Ensure not to overwrite existing implementations.
		if (this.getEnabled === undefined) {
			// set some default
			this.getEnabled = function() {
				var oParent = findParentWithEnabled(this);
				return (oParent && oParent.getEnabled && !oParent.getEnabled()) ? false : this.getProperty("enabled");
			};

			if ( bLegacy ) {
				// add Enabled with old spelling for compatibility reasons. Shares the getter and setter with new spelling.
				this.getMetadata().addProperty("Enabled", {type : "boolean", group : "Behavior", defaultValue :  !!bDefault});
			}
			this.getMetadata().addProperty("enabled", {type : "boolean", group : "Behavior", defaultValue :  !!bDefault});
			this.getMetadata().addPublicMethods('getEnabled');

		} else {
			//
			var fnOld = this.getEnabled;
			this.getEnabled = function() {
				var oParent = findParentWithEnabled(this);
				return (oParent && oParent.getEnabled && !oParent.getEnabled()) ? false : fnOld.apply(this);
			};
		}

		if (this.setEnabled === undefined) {
			this.setEnabled = function(bEnabled) {
				return this.setProperty("enabled", bEnabled);
			};

			this.getMetadata().addPublicMethods('setEnabled');
		}
	};

	return EnabledPropagator;

}, /* bExport= */ true);


text:
<?php

/*# declare(strict_types=1); */

namespace Phossa2\Shared\Aware;

/**
 * TagAwareInterface
 *
 * Add tagging support
 *
 * @package Phossa2\Shared
 * @author  Hong Zhang <phossa@126.com>
 * @version 2.0.0
 * @since   2.0.0 added
 */
interface TagAwareInterface
{
    /**
     * Add a single tag
     *
     * @param  string $tag
     * @return $this
     * @access public
     * @api
     */
    public function addTag(/*# string */ $tag);

    /**
     * Has this tag ?
     *
     * @param  string $tag
     * @return bool
     * @access public
     * @api
     */
    public function hasTag(/*# string */ $tag)/*# : bool */;

    /**
     * Remove one tag
     *
     * @param  string $tag
     * @return $this
     * @access public
     * @api
     */
    public function removeTag(/*# string */ $tag);

    /**
     * Set/replace all tags, empty array to clear all tags
     *
     * @param  array $tags like ['apple', 'orange']
     * @return $this
     * @access public
     * @api
     */
    public function setTags(array $tags);

    /**
     * Get all tags in array
     *
     * @return array
     * @access public
     * @api
     */
    public function getTags()/*# : array */;

    /**
     * Return array of tags existed, return empty [] if no match found
     *
     * @param  array $tags tags to match against
     * @return array
     * @access public
     * @api
     */
    public function hasTags(array $tags)/*# : array */;
}


text:
package model;

import java.util.ArrayList;

public class PrIS {
	private ArrayList<Klas>		alleKlassen	= new ArrayList<Klas>();
	private ArrayList<Les>		alleLessen	= new ArrayList<Les>();
	private ArrayList<Docent>	deDocenten	= new ArrayList<Docent>();
	private ArrayList<Student>	deStudenten	= new ArrayList<Student>();
	private Rooster				rooster		= new Rooster();

	/**
	 * De klasse fungeert min of meer als ingangspunt voor het domeinmodel.
	 * Deze constructor laad alle lesse, vakken, docenten, klassen en studenten in.
	 */
	public PrIS() {
		// laad alle lessen in
		alleLessen = rooster.getAlleLessen();

		ArrayList<ArrayList<String>> docentenData = CSVReader.getDocentenDataFromFile();

		// laad de vakken in
		ArrayList<Vak> vakken = new ArrayList<Vak>();

		vakken.add(new Vak("TCIF-V1AUI-15", "Analyse en User Interfaces"));
		vakken.add(new Vak("TICT-V1GP-15", "Group Project"));
		vakken.add(new Vak("TICT-V1OODC-15", "Object Oriented Design & Construction"));

		final String password = new String("geheim");

		// laad de docenten in
		for (ArrayList<String> arrayList : docentenData) {
			String docentNaam = arrayList.get(0);

			Docent d = new Docent(docentNaam, password);

			// Voeg alle bestaande vakken aan elke leraar
			for (Vak v : vakken) {
				d.voegVakToe(v);
			}

			deDocenten.add(d);
		}

		// laad de klassen in
		ArrayList<ArrayList<String>> klassenData = CSVReader.getKlassenDataFromFile();

		for (ArrayList<String> arrayList : klassenData) {
			alleKlassen.add(new Klas(arrayList.get(0)));
		}

		// laad de studenten in
		ArrayList<ArrayList<String>> leerlingenData = CSVReader.getLeerlingenDataFromFile();

		for (ArrayList<String> arrayList : leerlingenData) {
			int studieNummer = Integer.parseInt(arrayList.get(0));

			String gebruikersNaam = arrayList.get(3)
					+ (arrayList.get(2).equals("") ? "" : " " + arrayList.get(2)) + " "
					+ arrayList.get(1);

			Student s = new Student(studieNummer, gebruikersNaam, password);

			for (Klas k : alleKlassen) {
				if (k.getKlasCode().equals(arrayList.get(4))) {
					s.setMijnKlas(k);
					break;
				}
			}

			deStudenten.add(s);
		}
	}

	public ArrayList<Les> getAlleLessen() {
		return alleLessen;
	}

	/**
	 * Haal het docent object op met een bepaalde gebruikersnaam
	 *
	 * @param gebruikersnaam
	 * @return een docent object
	 */
	public Docent getDocent(String gebruikersnaam) {
		Docent resultaat = null;

		for (Docent d : deDocenten) {
			if (d.getGebruikersNaam().equals(gebruikersnaam)) {
				resultaat = d;
				break;
			}
		}

		return resultaat;
	}

	public ArrayList<Les> getLessenByKlas(Klas k) {
		return rooster.getAlleLessenByKlas(k);
	}

	public Rooster getRooster() {
		return rooster;
	}

	/**
	 * Haal het student object op met een bepaalde gebruikersnaam
	 *
	 * @param gebruikersnaam
	 * @return een student object
	 */
	public Student getStudent(String gebruikersnaam) {
		Student resultaat = null;

		for (Student s : deStudenten) {
			if (s.getGebruikersNaam().equals(gebruikersnaam)) {
				resultaat = s;
				break;
			}
		}

		return resultaat;
	}

	/**
	 * Haal alle studenten op van een bepaalde klas.
	 *
	 * @param klasCode
	 * @return Een lijst met studenten van de klas met klasCode
	 */
	public ArrayList<Student> getStudentenVanKlas(String klasCode) {
		ArrayList<Student> resultaat = new ArrayList<Student>();

		for (Student s : deStudenten) {
			if (s.getMijnKlas().getKlasCode().equals(klasCode)) {
				resultaat.add(s);
			}
		}

		return resultaat;
	}

	public String login(String gebruikersnaam, String wachtwoord) {
		for (Docent d : deDocenten) {
			if (d.getGebruikersNaam().equals(gebruikersnaam)) {
				if (d.controleerWachtwoord(wachtwoord)) {
					return "docent";
				}
			}
		}

		for (Student s : deStudenten) {
			if (s.getGebruikersNaam().equals(gebruikersnaam)) {
				if (s.controleerWachtwoord(wachtwoord)) {
					return "student";
				}
			}
		}

		return "undefined";
	}
}


text:
<?php

namespace Core {

	/**
	 * Handles all errors.
	 */
	function handleError($errno, $errstr, $errfile, $errline) {
		$error_builder = array();

		$error_builder[] = "" . $errno;
		$error_builder[] = "PHP Error String: " . $errstr;
		$error_builder[] = "PHP Error File:   " . str_replace(BASEPATH, "", $errfile);
		$error_builder[] = "PHP Error Line:   " . $errline;
		// Get backtrace.
		ob_start();
		debug_print_backtrace();
		$error_builder[] = "PHP Backtrace:";
		$error_builder[] = ob_get_clean();

		$error_builder[] = Log::error(implode(PHP_EOL, $error_builder));
	}

}

namespace {

	function asBytes($ini_v) {
		$ini_v = trim($ini_v);
		$s = array('g' => 1 << 30, 'm' => 1 << 20, 'k' => 1 << 10);
		return intval($ini_v) * ($s[strtolower(substr($ini_v, -1))] ? : 1);
	}

	/**
	 * Converts naming conventions between each other.
	 *
	 * @param string $from Type of string naming convention (camel, underscore, hyphen) to convert from.
	 * @param string $to Type of string naming convention (camel, underscore, hyphen) to convert to.
	 * @param string $value Value to convert to a new naming convention.
	 * @return string Converted string.
	 */
	function namingConversion($from, $to, $value) {
		$search_regex = null;

		if(empty($value)) {
			return $value;
		}

		switch($from) {
			case "camel":
				$value[0] = strtolower($value[0]);
				$search_regex = '/([A-Z])/';
				break;

			case "underscore":
				$value[0] = strtoupper($value[0]);
				$search_regex = '/_([a-zA-Z])/';
				break;

			case "hyphen":
				$search_regex = '/-([a-zA-Z])/';
				break;

			default:
				die("Unknown 'from' naming convention: $from");
				break;
		}

		switch($to) {
			case "underscore":
				$value[0] = strtolower($value[0]);
				return preg_replace_callback($search_regex, function($match) {
					return "_" . strtolower($match[1]);
				}, $value);

			case "camel":
				$value[0] = strtoupper($value[0]);
				return preg_replace_callback($search_regex, function($match) {
					return strtoupper($match[1]);
				}, $value);

			case "hyphen":
				$value[0] = strtolower($value[0]);
				return preg_replace_callback($search_regex, function($match) {
					return "-" . strtolower($match[1]);
				}, $value);

			default:
				die("Unknown 'to' naming convention: $to");
				break;
		}
	}

	/**
	 * Returns the first $variable if it isset; Otherwise returns the specified
	 * default variable.
	 *
	 * @param type $variable Variable to check if it is set.
	 * @param type $default The default value for the return value if the variable is not set.
	 * @return mixed The first non-null variable.
	 */
	function ifsetor(&$variable, $default = null) {
		if(isset($variable)) {
			return $variable;
		} else {
			return $default;
		}
	}

}


text:
using Realms;
using System;
using Toggl.Shared;
using Toggl.Shared.Extensions;
using Toggl.Shared.Models;
using Toggl.Storage.Models;
using Toggl.Storage.Realm.Models;
using static Toggl.Shared.PropertySyncStatus;

namespace Toggl.Storage.Realm
{
    internal partial class RealmUser
        : RealmObject, IDatabaseUser, IUpdatable, ISyncable<IUser>
    {
        public string ApiToken { get; set; }

        public DateTimeOffset At { get; set; }

        public long? DefaultWorkspaceId { get; set; }

        //Realm doesn't support enums
        [Ignored]
        public BeginningOfWeek BeginningOfWeek
        {
            get => (BeginningOfWeek)BeginningOfWeekInt;
            set => BeginningOfWeekInt = (int)value;
        }

        public int BeginningOfWeekInt { get; set; }

        [Ignored]
        public Email Email
        {
            get => EmailString.ToEmail();
            set => EmailString = value.ToString();
        }

        [MapTo("Email")]
        public string EmailString { get; set; }

        public string Fullname { get; set; }

        public string ImageUrl { get; set; }

        public string Language { get; set; }

        public string Timezone { get; set; }

        public void PrepareForSyncing()
        {
            SyncStatus = SyncStatus.Syncing;
            changePropertiesSyncStatus(from: SyncNeeded, to: Syncing);
        }

        public void PushFailed(string errorMessage)
        {
            LastSyncErrorMessage = errorMessage;
            SyncStatus = SyncStatus.SyncFailed;
            changePropertiesSyncStatus(from: Syncing, to: SyncNeeded);
        }

        public void UpdateSucceeded()
        {
            if (SyncStatus != SyncStatus.SyncNeeded)
                SyncStatus = SyncStatus.InSync;

            changePropertiesSyncStatus(from: Syncing, to: InSync);
        }

        public void SaveSyncResult(IUser entity, Realms.Realm realm)
        {
            ApiToken = entity.ApiToken;
            At = entity.At;
            DefaultWorkspaceId = entity.DefaultWorkspaceId;
            BeginningOfWeek = entity.BeginningOfWeek;
            Email = entity.Email;
            Fullname = entity.Fullname;
            ImageUrl = entity.ImageUrl;
            Language = entity.Language;
            Timezone = entity.Timezone;
            SyncStatus = SyncStatus.InSync;
            DefaultWorkspaceIdSyncStatus = InSync;
            BeginningOfWeekSyncStatus = InSync;
            LastSyncErrorMessage = null;
        }

        private void changePropertiesSyncStatus(PropertySyncStatus from, PropertySyncStatus to)
        {
            if (DefaultWorkspaceIdSyncStatus == from)
                DefaultWorkspaceIdSyncStatus = to;

            if (BeginningOfWeekSyncStatus == from)
                BeginningOfWeekSyncStatus = to;
        }
    }
}


text:
import java.util.Deque;
import java.util.LinkedList;

public class ValidParentheses {
	public boolean isValid(String s){
		if(s == null || s.length() == 0) return true;
		if(s.length() % 2 != 0) return false;
		Deque<Character> stack = new LinkedList<Character>();
		char temp = 0;
		for(char c : s.toCharArray()){
			if(c == '(' || c == '[' || c == '{')
				stack.offerLast(c); // prefer offerLast method
			else if(c == ')' || c == ']' || c == '}'){
				if(stack.isEmpty()) return false;
				temp = stack.pollLast(); // prefer pollLast method
				if((temp == '(' && c == ')') || (temp == '[' && c == ']') || (temp == '{' && c == '}'))
					continue;
				else
					return false;
			}
		}
		return stack.isEmpty();
	}
}


text:
PROJECT_NAME=helm-charts

include ../../../Makefile.os

RELEASE_VERSION ?= latest
CHART_SEMANTIC_RELEASE_VERSION ?= $(shell cat ../../../release.version | tr A-Z a-z)
CHART_NAME=strimzi-kafka-operator
CHART_PATH ?= ../helm3/strimzi-kafka-operator/
CHART_RENDERED_TEMPLATES_TMP=../../../target/charts
CHART_RENDERED_TEMPLATES_CLUSTERROLES=../../../cluster-operator/src/main/resources/cluster-roles/
CHART_RENDERED_TEMPLATES_INSTALL=../../install/cluster-operator/
HELM_CLI=helm

helm_clean:
	rm -rf $(CHART_RENDERED_TEMPLATES_TMP)
	rm -rf strimzi-$(RELEASE_VERSION)/charts/
	rm -f $(CHART_NAME)-*.tgz

helm_lint:
	# Linting Helm Chart
	$(HELM_CLI) lint --debug $(CHART_PATH)

helm_template:
	../kafka-version-tpl.sh strimzi-kafka-operator/templates/_kafka_image_map.tpl
	# Generating rendered template files to: $(CHART_RENDERED_TEMPLATES_TMP)
	mkdir -p $(CHART_RENDERED_TEMPLATES_TMP)
	$(HELM_CLI) template --namespace myproject --output-dir $(CHART_RENDERED_TEMPLATES_TMP) $(CHART_PATH)

helm_install: helm_clean helm_template
	# Remove Helm-related labels
	$(FIND) $(CHART_RENDERED_TEMPLATES_TMP) -type f -name '*.yaml' -exec $(SED) -i '/^---/d' {} \;
	$(FIND) $(CHART_RENDERED_TEMPLATES_TMP) -type f -name '*.yaml' -exec $(SED) -i '/^# Source: /d' {} \;
	$(FIND) $(CHART_RENDERED_TEMPLATES_TMP) -type f -name '*.yaml' -exec yq eval -i 'del .metadata.labels.chart' {} \;
	$(FIND) $(CHART_RENDERED_TEMPLATES_TMP) -type f -name '*.yaml' -exec yq eval -i 'del .metadata.labels.component' {}  \;
	$(FIND) $(CHART_RENDERED_TEMPLATES_TMP) -type f -name '*.yaml' -exec yq eval -i 'del .metadata.labels.release' {} \;
	$(FIND) $(CHART_RENDERED_TEMPLATES_TMP) -type f -name '*.yaml' -exec yq eval -i 'del .metadata.labels.heritage' {} \;
	$(FIND) $(CHART_RENDERED_TEMPLATES_TMP) -type f -name '*.yaml' -exec yq eval -i 'del .metadata.namespace' {} \;
	# Copying rendered template files to: $(CHART_RENDERED_TEMPLATES_INSTALL)
	mkdir -p $(CHART_RENDERED_TEMPLATES_INSTALL)
	# Find rendered resources which are not CustomResourceDefinition and move them
	$(FIND) $(CHART_RENDERED_TEMPLATES_TMP) -type f -name '*.yaml' -printf "%p " -exec yq eval '.kind' {} \; \
	| grep -v 'CustomResourceDefinition$$' \
	| $(SED) -E 's/([^ ]*) ([a-zA-Z0-9]*)$$/\1/' \
	| xargs -IFILE $(CP) FILE $(CHART_RENDERED_TEMPLATES_INSTALL)
	# Copying rendered template files to: $(CHART_RENDERED_TEMPLATES_CLUSTERROLES)
	mkdir -p $(CHART_RENDERED_TEMPLATES_CLUSTERROLES)
	# Find rendered resources which are not CustomResourceDefinition and move them
	$(FIND) $(CHART_RENDERED_TEMPLATES_TMP) -type f -name '*ClusterRole-*.yaml' -printf "%p " -exec yq eval '.kind' {} \; \
	| $(SED) -E 's/([^ ]*) ([a-zA-Z0-9]*)$$/\1/' \
	| xargs -IFILE $(CP) FILE $(CHART_RENDERED_TEMPLATES_CLUSTERROLES)

helm_pkg: helm_lint helm_install
	# Copying unarchived Helm Chart to release directory
	mkdir -p strimzi-$(RELEASE_VERSION)/charts/
	$(CP) -r $(CHART_PATH) strimzi-$(RELEASE_VERSION)/charts/$(CHART_NAME)
	# Packaging helm chart with semantic version: $(CHART_SEMANTIC_RELEASE_VERSION)
	$(HELM_CLI) package --version $(CHART_SEMANTIC_RELEASE_VERSION) --app-version $(CHART_SEMANTIC_RELEASE_VERSION) --destination ./ $(CHART_PATH)
	rm -rf strimzi-$(RELEASE_VERSION)

java_build: helm_pkg
java_install: java_build
docker_build: helm_pkg
docker_tag:
docker_push:

all: docker_build
clean: helm_clean

.PHONY: build clean release spotbugs


text:
@interface WCAppDelegate : NSObject <NSApplicationDelegate>
@property (strong) WCController *wc;
@property (unsafe_unretained) IBOutlet NSWindow *window;

@end


text:
                <button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>

Adicionar Usuário

            <form class="form-horizontal" novalidate="" action="{{ action('PermissionController@addPermissionUser') }}">

                            Usuário:
                            <input type="hidden" name="id_permissao" value="{{$permissao->id}}">

                            <input type="text" id="search_users" class="form-control" placeholder="Nome ou E-mail">

                    <input type="submit" class="btn btn-primary" value="Salvar">

            </form>