text:
package org.fedoraproject.xmvn.connector.maven;

import java.io.File;
import java.nio.file.Path;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

import org.codehaus.plexus.component.annotations.Component;
import org.codehaus.plexus.component.annotations.Requirement;
import org.eclipse.aether.artifact.Artifact;
import org.eclipse.aether.repository.WorkspaceReader;
import org.eclipse.aether.repository.WorkspaceRepository;

import org.fedoraproject.xmvn.resolver.ResolutionRequest;
import org.fedoraproject.xmvn.resolver.ResolutionResult;
import org.fedoraproject.xmvn.resolver.Resolver;

/**
 * @author Mikolaj Izdebski
 */
@Component( role = WorkspaceReader.class, hint = "ide" )
public class XMvnWorkspaceReader
    implements WorkspaceReader
{
    @Requirement
    private Resolver resolver;

    private static final WorkspaceRepository REPOSITORY = new WorkspaceRepository();

    private final List<ResolutionListener> listeners = new ArrayList<>();

    public void addResolutionListener( ResolutionListener listener )
    {
        listeners.add( listener );
    }

    private ResolutionResult resolve( Artifact artifact )
    {
        org.fedoraproject.xmvn.artifact.Artifact xmvnArtifact =
            new org.fedoraproject.xmvn.artifact.DefaultArtifact( artifact.getGroupId(), artifact.getArtifactId(),
                                                                 artifact.getExtension(), artifact.getClassifier(),
                                                                 artifact.getVersion() );
        ResolutionRequest request = new ResolutionRequest( xmvnArtifact );

        for ( ResolutionListener listener : listeners )
            listener.resolutionRequested( request );

        ResolutionResult result = resolver.resolve( request );

        for ( ResolutionListener listener : listeners )
            listener.resolutionCompleted( request, result );

        return result;
    }

    @Override
    public File findArtifact( Artifact artifact )
    {
        ResolutionResult result = resolve( artifact );

        Path artifactPath = result.getArtifactPath();
        return artifactPath != null ? artifactPath.toFile() : null;
    }

    @Override
    public List<String> findVersions( Artifact artifact )
    {
        ResolutionResult result = resolve( artifact );

        if ( result.getArtifactPath() == null )
            return Collections.emptyList();

        String version = result.getCompatVersion();
        if ( version == null )
            version = org.fedoraproject.xmvn.artifact.Artifact.DEFAULT_VERSION;

        return Collections.singletonList( version );
    }

    @Override
    public WorkspaceRepository getRepository()
    {
        return REPOSITORY;
    }
}


text:
// Copyright 2019 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

/**
 * Video player with chrome's native controls.
 */
class NativeControlsVideoPlayer {
  constructor() {
    /**
     * List of open videos.
     * @private {Array<!FileEntry>}
     */
    this.videos_ = null;

    /**
     * Index of current playing video.
     * @private {number}
     */
    this.currentPos_ = 0;

    /**
     * HTML video element that contains the video player.
     * @private {HTMLVideoElement}
     */
    this.videoElement_ = null;
  }

  /**
   * Initializes the video player window. This method must be called after DOM
   * initialization.
   * @param {!Array<!FileEntry>} videos List of videos.
   */
  prepare(videos) {
    this.videos_ = videos;

    // TODO: Move these setting to html and css file when
    // we are confident to remove the feature flag
    this.videoElement_ =
        assertInstanceof(document.createElement('video'), HTMLVideoElement);
    this.videoElement_.autoPictureInPicture = true;
    this.videoElement_.controls = true;
    this.videoElement_.controlsList = 'nodownload';
    this.videoElement_.style.pointerEvents = 'auto';
    getRequiredElement('video-container').appendChild(this.videoElement_);

    // TODO: remove the element in html when remove the feature flag
    getRequiredElement('controls-wrapper').style.display = 'none';
    getRequiredElement('spinner-container').style.display = 'none';
    getRequiredElement('error-wrapper').style.display = 'none';
    getRequiredElement('thumbnail').style.display = 'none';
    getRequiredElement('cast-container').style.display = 'none';

    this.videoElement_.addEventListener('pause', this.onPause_.bind(this));

    // Restore playback position when duration change.
    // Duration change happens when video is loading where the duration
    // change from NaN to the actual video duration.
    this.videoElement_.addEventListener(
        'durationchange', this.restorePlayState_.bind(this));

    // Clear stored playback position
    this.videoElement_.addEventListener(
        'onmediacomplete', this.onMediaComplete_.bind(this));

    this.preparePlayList_();
    this.addKeyControls_();
  }

  /**
   * Attach arrow box for previous/next track to document and set
   * 'multiple' attribute if user opens more than 1 videos.
   *
   * @private
   */
  preparePlayList_() {
    const videoPlayerElement =
        assertInstanceof(getRequiredElement('video-player'), HTMLDivElement);
    if (this.videos_.length > 1) {
      videoPlayerElement.setAttribute('multiple', true);
    } else {
      videoPlayerElement.removeAttribute('multiple');
    }

    const arrowRight = assertInstanceof(
        queryRequiredElement('.arrow-box .arrow.right'), HTMLDivElement);
    arrowRight.addEventListener(
        'click', this.advance_.bind(this, true /* next track */));
    const arrowLeft = assertInstanceof(
        queryRequiredElement('.arrow-box .arrow.left'), HTMLDivElement);
    arrowLeft.addEventListener(
        'click', this.advance_.bind(this, false /* previous track */));
  }

  /**
   * Add keyboard controls to document.
   *
   * @private
   */
  addKeyControls_() {
    document.addEventListener('keydown', (/** !Event */ event) => {
      const keyboardEvent = /** @type {!KeyboardEvent} */ (event);
      const key =
          (keyboardEvent.ctrlKey && keyboardEvent.shiftKey ? 'Ctrl+Shift+' :
                                                             '') +
          keyboardEvent.key;
      switch (key) {
          // Handle debug shortcut keys.
        case 'Ctrl+Shift+I':
          chrome.fileManagerPrivate.openInspector('normal');
          break;
        case 'Ctrl+Shift+J':
          chrome.fileManagerPrivate.openInspector('console');
          break;
        case 'Ctrl+Shift+C':
          chrome.fileManagerPrivate.openInspector('element');
          break;
        case 'Ctrl+Shift+B':
          chrome.fileManagerPrivate.openInspector('background');
          break;

        case 'k':
        case 'MediaPlayPause':
          this.togglePlayState_();
          break;
        case 'MediaTrackNext':
          this.advance_(true /* next track */);
          break;
        case 'MediaTrackPrevious':
          this.advance_(false /* previous track */);
          break;
        case 'l':
          this.skip_(true /* forward */);
          break;
        case 'j':
          this.skip_(false /* backward */);
          break;
        case 'BrowserBack':
          chrome.app.window.current().close();
          break;
        case 'MediaStop':
          // TODO: Define "Stop" behavior.
          break;
      }
    });

    getRequiredElement('video-container')
        .addEventListener('click', (/** !Event */ event) => {
          const mouseEvent = /** @type {!MouseEvent} */ (event);
          // Turn on loop mode when ctrl+click while the video is playing.
          // If the video is paused, ignore ctrl and play the video.
          if (mouseEvent.ctrlKey && !this.videoElement_.paused) {
            this.setLoopedModeWithFeedback_(true);
            mouseEvent.preventDefault();
          }
        });
  }

  /**
   * Skips forward/backward.
   * @param {boolean} forward Whether to skip forward or backward.
   * @private
   */
  skip_(forward) {
    let secondsToSkip = Math.min(
        NativeControlsVideoPlayer.PROGRESS_MAX_SECONDS_TO_SKIP,
        this.videoElement_.duration *
            NativeControlsVideoPlayer.PROGRESS_MAX_RATIO_TO_SKIP);

    if (!forward) {
      secondsToSkip *= -1;
    }

    this.videoElement_.currentTime = Math.max(
        Math.min(
            this.videoElement_.currentTime + secondsToSkip,
            this.videoElement_.duration),
        0);
  }

  /**
   * Toggle play/pause.
   *
   * @private
   */
  togglePlayState_() {
    if (this.videoElement_.paused) {
      this.videoElement_.play();
    } else {
      this.videoElement_.pause();
    }
  }

  /**
   * Set the looped mode with feedback.
   *
   * @param {boolean} on Whether enabled or not.
   * @private
   */
  setLoopedModeWithFeedback_(on) {
    this.videoElement_.loop = on;
    if (on) {
      this.showNotification_('VIDEO_PLAYER_LOOPED_MODE');
    }
  }

  /**
   * Briefly show a text notification at top left corner.
   *
   * @param {string} identifier String identifier.
   * @private
   */
  showNotification_(identifier) {
    getRequiredElement('toast-content').textContent =
        loadTimeData.getString(identifier);
    getRequiredElement('toast').show();
  }

  /**
   * Plays the first video.
   */
  playFirstVideo() {
    this.currentPos_ = 0;
    this.reloadCurrentVideo_(this.onFirstVideoReady_.bind(this));
  }

  /**
   * Called when the first video is ready after starting to load.
   * Make the video player app window the same dimension as the video source
   * Restrict the app window inside the screen.
   *
   * @private
   */
  onFirstVideoReady_() {
    const videoWidth = this.videoElement_.videoWidth;
    const videoHeight = this.videoElement_.videoHeight;

    const aspect = videoWidth / videoHeight;
    let newWidth = videoWidth;
    let newHeight = videoHeight;

    const shrinkX = newWidth / window.screen.availWidth;
    const shrinkY = newHeight / window.screen.availHeight;
    if (shrinkX > 1 || shrinkY > 1) {
      if (shrinkY > shrinkX) {
        newHeight = newHeight / shrinkY;
        newWidth = newHeight * aspect;
      } else {
        newWidth = newWidth / shrinkX;
        newHeight = newWidth / aspect;
      }
    }

    let oldLeft = window.screenX;
    let oldTop = window.screenY;
    const oldWidth = window.innerWidth;
    const oldHeight = window.innerHeight;

    if (!oldWidth && !oldHeight) {
      oldLeft = window.screen.availWidth / 2;
      oldTop = window.screen.availHeight / 2;
    }

    let appWindow = chrome.app.window.current();
    appWindow.innerBounds.width = Math.round(newWidth);
    appWindow.innerBounds.height = Math.round(newHeight);
    appWindow.outerBounds.left =
        Math.max(0, Math.round(oldLeft - (newWidth - oldWidth) / 2));
    appWindow.outerBounds.top =
        Math.max(0, Math.round(oldTop - (newHeight - oldHeight) / 2));
    appWindow.show();

    this.videoElement_.focus();
    this.videoElement_.play();
  }

  /**
   * Advance to next video when the current one ends.
   * Not using 'ended' event because dragging the timeline
   * thumb to the end when seeking will trigger 'ended' event.
   *
   * @private
   */
  onPause_() {
    this.videoElement_.loop = false;
    if (this.videoElement_.ended) {
      this.advance_(true);
    }
  }

  /**
   * Onmediacomplete handler.
   * Clear playback position when media completes.
   * @private
   */
  onMediaComplete_() {
    this.savePosition(false);
  }

  /**
   * Advances to the next (or previous) track.
   *
   * @param {boolean} direction True to the next, false to the previous.
   * @private
   */
  advance_(direction) {
    const newPos = this.currentPos_ + (direction ? 1 : -1);
    if (newPos < 0 || newPos >= this.videos_.length) {
      return;
    }

    this.currentPos_ = newPos;
    this.reloadCurrentVideo_(() => {
      this.videoElement_.play();
    });
  }

  /**
   * Reloads the current video.
   *
   * @param {function()=} opt_callback Completion callback.
   * @private
   */
  reloadCurrentVideo_(opt_callback) {
    const videoPlayerElement =
        assertInstanceof(getRequiredElement('video-player'), HTMLDivElement);
    if (this.currentPos_ == (this.videos_.length - 1)) {
      videoPlayerElement.setAttribute('last-video', true);
    } else {
      videoPlayerElement.removeAttribute('last-video');
    }

    if (this.currentPos_ === 0) {
      videoPlayerElement.setAttribute('first-video', true);
    } else {
      videoPlayerElement.removeAttribute('first-video');
    }

    const currentVideo = this.videos_[this.currentPos_];
    this.loadVideo_(currentVideo, opt_callback);
  }

  /**
   * Loads the video file.
   * @param {!FileEntry} video Entry of the video to be played.
   * @param {function()=} opt_callback Completion callback.
   * @private
   */
  async loadVideo_(video, opt_callback) {
    document.title = video.name;
    const videoUrl = video.toURL();

    if (opt_callback) {
      this.videoElement_.addEventListener(
          'loadedmetadata', opt_callback, {once: true});
    }

    this.videoElement_.src = videoUrl;

    // Clear all tracks.
    while (this.videoElement_.firstChild) {
      this.videoElement_.firstChild.remove();
    }

    const subtitleUrl = await this.searchSubtitle_(videoUrl);
    if (subtitleUrl) {
      const track =
          assertInstanceof(document.createElement('track'), HTMLTrackElement);
      track.src = subtitleUrl;
      track.kind = 'subtitles';
      track.default = true;
      this.videoElement_.appendChild(track);
    }
  }

  /**
   * Saves the playback position to the persistent storage.
   * @param {boolean} saveAsync True if the position must be saved
   *     asynchronously (required when closing app windows).
   */
  savePosition(saveAsync) {
    if (!this.videoElement_ || !this.videoElement_.duration ||
        this.videoElement_.duration <
            NativeControlsVideoPlayer.RESUME_THRESHOLD_SECONDS) {
      return;
    }

    const resumeTime = this.videoElement_.currentTime -
        NativeControlsVideoPlayer.RESUME_REWIND_SECONDS;
    const ratio = resumeTime / this.videoElement_.duration;

    // If we are too close to the beginning or the end,
    // remove the resume position so that next time we start from the beginning.
    const position = (ratio < NativeControlsVideoPlayer.RESUME_MARGIN ||
                      ratio > (1 - NativeControlsVideoPlayer.RESUME_MARGIN)) ?
        null :
        resumeTime;

    if (saveAsync) {
      saveEntryAsync(this.videoElement_.src, position);
    } else {
      appUtil.AppCache.update(this.videoElement_.src, position);
    }
  }

  /**
   * Resumes the playback position saved in the persistent storage.
   * @private
   */
  restorePlayState_() {
    if (this.videoElement_ && this.videoElement_.seekable &&
        this.videoElement_.duration >=
            NativeControlsVideoPlayer.RESUME_THRESHOLD_SECONDS) {
      appUtil.AppCache.getValue(
          this.videoElement_.src, (/** number */ position) => {
            if (position) {
              this.videoElement_.currentTime = position;
            }
          });
    }
  }

  /**
   * Search subtitle file corresponding to a video.
   * @param {string} url a url of a video.
   * @return {Promise} a Promise returns url of subtitle file, or an empty
   *     string.
   */
  async searchSubtitle_(url) {
    const resolveLocalFileSystemWithExtension = (extension) => {
      const subtitleUrl = this.getSubtitleUrl_(url, extension);
      return new Promise(
          window.webkitResolveLocalFileSystemURL.bind(null, subtitleUrl));
    };

    try {
      const subtitle = await resolveLocalFileSystemWithExtension('.vtt');
      return subtitle.toURL();
    } catch (error) {
      // TODO: figure out if there could be any error other than
      // file not found or not accessible. If not, remove this log.
      console.error(error);
      return '';
    }
  }

  /**
   * Get the subtitle url.
   *
   * @private
   * @param {string} srcUrl Source url of the video file.
   * @param {string} extension Extension of the subtitle we are looking for.
   * @return {string} Subtitle url.
   */
  getSubtitleUrl_(srcUrl, extension) {
    return srcUrl.replace(/\.[^\.]+$/, extension);
  }
}

/**
 * Save an entry asynchronously when exiting app.
 *
 * @param {*} key Key of the entry to be saved.
 * @param {*} value Value of the entry to be saved.
 */
function saveEntryAsync(key, value) {
  // Packaged apps cannot save synchronously.
  // Pass the data to the background page.
  if (!window.saveOnExit) {
    window.saveOnExit = [];
  }
  window.saveOnExit.push({key: key, value: value});
}

/**
 * 10 seconds should be skipped when J/L key is pressed.
 * @const {number}
 */
NativeControlsVideoPlayer.PROGRESS_MAX_SECONDS_TO_SKIP = 10;

/**
 * 20% of duration should be skipped when the video is too short to skip 10
 * seconds.
 * @const {number}
 */
NativeControlsVideoPlayer.PROGRESS_MAX_RATIO_TO_SKIP = 0.2;

/**
 * No resume if we are within this margin from the start or the end.
 * @const {number}
 */
NativeControlsVideoPlayer.RESUME_MARGIN = 0.05;  // 5%

/**
 * No resume for videos shorter than this.
 * @const {number}
 */
NativeControlsVideoPlayer.RESUME_THRESHOLD_SECONDS = 5 * 60;  // 5 min.

/**
 * When resuming rewind back this much.
 * @const {number}
 */
NativeControlsVideoPlayer.RESUME_REWIND_SECONDS = 5;

redpajama_set_name: RedPajamaGithub


text:
require "peru_sunat_ruc/version"
require "peru_sunat_ruc/connector"
require "peru_sunat_ruc/company"

module PeruSunatRuc
  def self.name_from(ruc_number)
    self.info_from(ruc_number).name
  end

  def self.info_from(ruc_number)
    Connector.get_info ruc_number
  end

  class InvalidRucNumber < StandardError
  end
end


text: Bus Audio Video


text:
/* main.js
 *
 * Starting point for functionality of program. Sets up other objects and
 * does searching for main Dom elements, which get passed into the various
 * other control objects.
 */

// remap jQuery to $
(function($){
	var STATES = Object.freeze({EMPTY:0,UNLOADED:1,LOADING:2,LOADED:3});

	var typeTimeout = -1;
	var loadTimeout = -1;
	var averageRespTime = 100;
	var state = STATES.EMPTY;
	var search = null;

	var KEYTIMEOUT = 1000;

	/* trigger when page is ready */
	$(document).ready(function (){
		var searchDiv = $(".search")
		var searchBar = $(".search .search-bar");
		var searchProgress = $(".search .search-progress");
		var resultsDiv = $(".content");
		var footer = $("footer");

		searchBar.eq(0).focus();

		var progress = new ProgressIndicator(searchProgress);
		var pos = new BoxPos(searchDiv);

		var hash = location.hash;
		var results = new ResultsDisplayer(resultsDiv,SEARCHSTRING[hash]);

		//to stop flash at top before centred.
		searchDiv.transition({opacity:1},500);

		searchBar.keyup(function(ev){
			//enter
			if(ev.keyCode == 13) {
				searchBar.blur();
			}
		});

		//Waits for a change to the actual data contained within the search bar
		searchBar.bind('input propertychange', function(d,e,f) {

			var l = searchBar.val().length;

			if(l > 2) {
				//start progress bar animation
				progress.startForward();
				//start waiting to move box to top
				pos.startForward();
				//start waiting for repeated user interaction before searching
				results.startSearch(searchBar.val());
			} else if (l == 0){
				//clear back to beginning if box is emptied
				progress.startBackwards();
				pos.startBackwards();
				results.clear();
			}
		});

		//hook up attribution dialog
		var attrInfo = $(".moreinfo",footer).remodal()
		footer.click(function(){
			attrInfo.open();
		});
	});

	//keep search bar in middle of window on resize (or flip on mobile)
	$(window).resize(function (){
		if(state == STATES.EMPTY){
			$('.search').css({
				top: ($(window).height() - $('.search').outerHeight())/2
			});
		}
    });

    $(window).resize();

})(window.jQuery);


text:
<?xml version="1.0" encoding="UTF-8"?>
<LinearLayout android:orientation="horizontal"
	android:layout_width="fill_parent" android:layout_height="fill_parent"
	xmlns:android="http://schemas.android.com/apk/res/android">
	<ImageView android:id="@+id/icon" android:layout_width="48.0dip"
		android:layout_height="48.0dip" android:layout_marginRight="2.0dip"
		android:layout_alignParentLeft="true" />
	<TextView android:textSize="17.0dip" android:textColor="#ffffffff"
		android:layout_gravity="center_vertical" android:id="@+id/label"
		android:layout_width="0.0dip" android:layout_height="wrap_content"
		android:text="TextView" android:layout_weight="1.0" />
</LinearLayout>


text:
Loading data...

            {{thermostat.name}}

            {{thermostat.lastTemperature}}

            Address:

{{thermostat.address}}

            Last Connection:

{{thermostat.lastConnection}}

            Last Temperature

{{thermostat.lastTemperature}}


text:
.. _associated_projects:

Associated Projects
===================

.. _application-bindings:

Application Bindings
--------------------

* OpenStack supported binding:

  * `Python-SwiftClient <http://pypi.python.org/pypi/python-swiftclient>`_

* Unofficial libraries and bindings:

  * `PHP-opencloud <http://php-opencloud.com>`_ - Official Rackspace PHP bindings that should work for other Swift deployments too.
  * `PyRAX <https://github.com/rackspace/pyrax>`_ - Official Rackspace Python bindings for CloudFiles that should work for other Swift deployments too.
  * `openstack.net <https://github.com/rackspace/openstack.net/>`_ - Official Rackspace .NET bindings that should work for other Swift deployments too.
  * `RSwift <https://github.com/pandemicsyn/RSwift>`_ - R API bindings.
  * `Go language bindings <https://github.com/ncw/swift>`_
  * `supload <https://github.com/selectel/supload>`_ - Bash script to upload file to cloud storage based on OpenStack Swift API.
  * `libcloud <http://libcloud.apache.org>`_ - Apache Libcloud - a unified interface in Python for different clouds with OpenStack Swift support.
  * `SwiftBox <https://github.com/suniln/SwiftBox>`_ - C# library using RestSharp
  * `jclouds <http://jclouds.incubator.apache.org/documentation/quickstart/openstack/>`_ - Java library offering bindings for all OpenStack projects
  * `java-openstack-swift <https://github.com/dkocher/java-openstack-swift>`_ - Java bindings for OpenStack Swift
  * `swift_client <https://github.com/mrkamel/swift_client>`_ - Small but powerful Ruby client to interact with OpenStack Swift
  * `nightcrawler_swift <https://github.com/tulios/nightcrawler_swift>`_ - This Ruby gem teleports your assets to a OpenStack Swift bucket/container
  * `swift storage <https://rubygems.org/gems/swift-storage>`_ - Simple OpenStack Swift storage client.
  * `javaswift <http://javaswift.org/>`_ - Collection of Java tools for Swift

Authentication
--------------

* `Keystone <https://github.com/openstack/keystone>`_ - Official Identity Service for OpenStack.
* `Swauth <https://github.com/openstack/swauth>`_ - An alternative Swift authentication service that only requires Swift itself.
* `Basicauth <https://github.com/CloudVPS/swift-basicauth>`_ - HTTP Basic authentication support (keystone backed).

Command Line Access
-------------------

* `Swiftly <https://github.com/gholt/swiftly>`_ - Alternate command line access to Swift with direct (no proxy) access capabilities as well.

Log Processing
--------------

* `Slogging <https://github.com/notmyname/slogging>`_ - Basic stats and logging tools.

Monitoring & Statistics
-----------------------

* `Swift Informant <https://github.com/pandemicsyn/swift-informant>`_ - Swift Proxy Middleware to send events to a statsd instance.
* `Swift Inspector <https://github.com/hurricanerix/swift-inspector>`_ - Swift middleware to relay information about a request back to the client.

Content Distribution Network Integration
----------------------------------------

* `SOS <https://github.com/dpgoetz/sos>`_ - Swift Origin Server.

Alternative API
---------------

* `Swift3 <https://github.com/openstack/swift3>`_ - Amazon S3 API emulation.
* `CDMI <https://github.com/osaddon/cdmi>`_ - CDMI support
* `SwiftHLM <https://github.com/ibm-research/SwiftHLM>`_ - a middleware for using OpenStack Swift with tape and other high latency media storage backends

Benchmarking/Load Generators
----------------------------

* `getput <https://github.com/markseger/getput>`_ - getput tool suite
* `COSbench <https://github.com/intel-cloud/cosbench>`_ - COSbench tool suite
* `ssbench <https://github.com/swiftstack/ssbench>`_ - ssbench tool suite

.. _custom-logger-hooks-label:

Custom Logger Hooks
-------------------

* `swift-sentry <https://github.com/pandemicsyn/swift-sentry>`_ - Sentry exception reporting for Swift

Storage Backends (DiskFile API implementations)
-----------------------------------------------
* `Swift-on-File <https://github.com/openstack/swiftonfile>`_ - Enables objects created using Swift API to be accessed as files on a POSIX filesystem and vice versa.
* `swift-ceph-backend <https://github.com/openstack/swift-ceph-backend>`_ - Ceph RADOS object server implementation for Swift.
* `kinetic-swift <https://github.com/swiftstack/kinetic-swift>`_ - Seagate Kinetic Drive as backend for Swift
* `swift-scality-backend <https://github.com/scality/ScalitySproxydSwift>`_ - Scality sproxyd object server implementation for Swift.

Developer Tools
---------------
* `SAIO bash scripts <https://github.com/ntata/swift-setup-scripts.git>`_ -
  Well commented simple bash scripts for Swift all in one setup.
* `vagrant-swift-all-in-one
  <https://github.com/swiftstack/vagrant-swift-all-in-one>`_ - Quickly setup a
  standard development environment using Vagrant and Chef cookbooks in an
  Ubuntu virtual machine.
* `SAIO Ansible playbook <https://github.com/thiagodasilva/swift-aio>`_ -
  Quickly setup a standard development environment using Vagrant and Ansible in
  a Fedora virtual machine (with built-in `Swift-on-File
  <https://github.com/openstack/swiftonfile>`_ support).

Other
-----

* `Glance <https://github.com/openstack/glance>`_ - Provides services for discovering, registering, and retrieving virtual machine images (for OpenStack Compute [Nova], for example).
* `Better Staticweb <https://github.com/CloudVPS/better-staticweb>`_ - Makes swift containers accessible by default.
* `Django Swiftbrowser <https://github.com/cschwede/django-swiftbrowser>`_ - Simple Django web app to access OpenStack Swift.
* `Swift-account-stats <https://github.com/enovance/swift-account-stats>`_ - Swift-account-stats is a tool to report statistics on Swift usage at tenant and global levels.
* `PyECLib <https://github.com/openstack/pyeclib>`_ - High Level Erasure Code library used by Swift
* `liberasurecode <https://github.com/openstack/liberasurecode>`_ - Low Level Erasure Code library used by PyECLib
* `Swift Browser <https://github.com/zerovm/swift-browser>`_ - JavaScript interface for Swift
* `swift-ui <https://github.com/fanatic/swift-ui>`_ - OpenStack Swift web browser
* `Swift Durability Calculator <https://github.com/enovance/swift-durability-calculator>`_ - Data Durability Calculation Tool for Swift
* `swiftbackmeup <https://github.com/redhat-cip/swiftbackmeup>`_ -  Utility that allows one to create backups and upload them to OpenStack Swift
* `Multi Swift <https://github.com/ntata/multi-swift-POC>`_ - Bash scripts to spin up multiple Swift clusters sharing the same hardware


text:
package com.jikken2;

import android.os.AsyncTask;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.ProgressDialog;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;

@SuppressLint("NewApi")
public class ConnectDBDist extends AsyncTask<Void, Void, String>{

    private static String URL = "172.29.139.104/db_group_a";
    private static String USER = "group_a";
    private static String PASS = "m4we6baq";

    private static int TIMEOUT = 5;
    private Activity act = null;
    private String sql = "";
    private ProgressDialog dialog;
    private ResultSet rs = null;
    private String result = "";
    public double totalDistance = 0.0;
    private AsyncTaskCallback callback = null;
    public int loopCounter = 1;
    public int pointBalance = 0;
    public int newPointBalance = 0;
    private static int JAPAN_LOOP = 12000;
    private static int BONUS = 500;
    private String id;

    public interface AsyncTaskCallback{
        void preExecute();
        void postExecute(String result);
        void progressUpdate(int progress);
        void cancel();
    }

    public ConnectDBDist(Activity act){
        this.act = act;
    }

    public ConnectDBDist(Activity act,String sql){
        this.act = act;
        this.sql = sql;
    }

    public ConnectDBDist(Activity act,String sql,AsyncTaskCallback _callback){
        this.act = act;
        this.sql = sql;
        this.callback = _callback;
    }

    public String getResult(){
        return result;
    }

    public double getTotalDistance(){
        return totalDistance;
    }

    public int getLoopCounter(){
        return loopCounter;
    }

    public int getPointBalance(){
        return pointBalance;
    }

    @Override
    protected void onPreExecute(){
        super.onPreExecute();
        callback.preExecute();

        this.dialog = new ProgressDialog(this.act);
        this.dialog.setMessage("Now Loading...");
        this.dialog.show();
    }

    @Override
    protected String doInBackground(Void... arg0){
       String text = "";
        try {
            Class.forName("com.mysql.jdbc.Driver");
            DriverManager.setLoginTimeout(TIMEOUT);
            Connection con = DriverManager.getConnection("jdbc:mysql://"+URL,USER,PASS);

            Statement stmt = con.createStatement();
//            String[] strAry = sql.split("");

//            switch (strAry[0]) {
//                case "SELECT" :
                    rs = stmt.executeQuery(sql);
                    while (rs.next()) {
                        id = rs.getString("id");
                        totalDistance = rs.getDouble("totalDistance");
                        pointBalance = rs.getInt("pointBalance");
                        loopCounter = rs.getInt("loopCounter");
//                    }
//                    break;

//                case "UPDATE":
//                    stmt.executeUpdate(sql);
//                    break;
            }
            rs.close();
            stmt.close();
            con.close();
        }catch (Exception e){
            //text = e.getMessage()
            text = "Connect Error";
            result = "Connect Error";
        }
        return text;
    }

    protected void onPostExecute(String result){
        super.onPostExecute(result);
        callback.postExecute(result);

        if(this.dialog != null && this.dialog.isShowing()){
            this.dialog.dismiss();
        }
    }
}


text:
<!-- Diese Komponente kümmert sich um die Fehlermeldung -->
<div class="logger">
    <div *ngFor="let error of errors | async" class="alert alert-danger" role="alert">
        {{error}}
    </div>
    <div *ngFor="let hint of hints | async" class="alert alert-success" role="alert">
        {{hint}}
    </div>
</div>


text:
SYNONYM

#### According to
The Catalogue of Life, 3rd January 2011

#### Published in
Gen. Fungi Sporul. Cult. (Vaduz), Edn 3 156 (1981)

#### Original name
Melanospora moreaui Doguet, 1955

### Remarks
null


text:
require 'spec_helper'

describe Unrest::ResourceNameInvestigator do
  def resource_name_dynamic_class(dynamic_name)
    already_defined = eval("#{dynamic_name}") rescue nil
    return already_defined if already_defined
    the_class    = Class.new do
      extend Unrest::ResourceNameInvestigator
    end
    Object.const_set(dynamic_name, the_class)
    eval("#{dynamic_name}")
  end

  [{class_name: 'Target', pluralized_resource_name: 'targets', singularized_resource_name: 'target'},
   {class_name: 'SwampThing', pluralized_resource_name: 'swamp_things', singularized_resource_name: 'swamp_thing'},
   {class_name: 'BigDummy', pluralized_resource_name: 'big_dummies', singularized_resource_name: 'big_dummy'}
  ].each do |test_hash|
    it "pluralized #{test_hash[:class_name]} to #{test_hash[:pluralized_resource_name]}" do
      expect(resource_name_dynamic_class(test_hash[:class_name]).pluralized_resource_name).to eq(test_hash[:pluralized_resource_name])
    end

    it "singularized #{test_hash[:class_name]} to #{test_hash[:singularized_resource_name]}" do
      expect(resource_name_dynamic_class(test_hash[:class_name]).singularized_resource_name).to eq(test_hash[:singularized_resource_name])
    end
  end
end


text:
Posts tagged with Sweet - de
Test Post - de


text:
package controllers

import (
	"fmt"
	"io"
	"net"
	"sync"
	"time"

	"github.com/convox/rack/api/httperr"
	"github.com/gorilla/mux"
	"golang.org/x/net/websocket"
)

func Proxy(ws *websocket.Conn) *httperr.Error {
	vars := mux.Vars(ws.Request())
	host := vars["host"]
	port := vars["port"]

	conn, err := net.DialTimeout("tcp", fmt.Sprintf("%s:%s", host, port), 3*time.Second)

	if neterr, ok := err.(net.Error); ok && neterr.Timeout() {
		return httperr.Errorf(403, "timeout")
	}

	if err != nil {
		return httperr.Server(err)
	}

	var wg sync.WaitGroup

	wg.Add(2)
	go copyAsync(ws, conn, &wg)
	go copyAsync(conn, ws, &wg)
	wg.Wait()

	return nil
}

func copyAsync(dst io.Writer, src io.Reader, wg *sync.WaitGroup) {
	defer wg.Done()
	io.Copy(dst, src)
}


text:
#include <iostream>
#include <unordered_map>
#include <string>
#include <algorithm>
#include <vector>
#include <sstream>
using namespace std;

/*
 * Approaches:
 *
 * 1) Do the following:
 *
 * a) For each count-paired domain, initialize a stringstream with the cpdomain string and then parse out the
 * number of times the domain has been visited and the domain string. Then, if the domain is not in the hashtable,
 * we add it and map it to the number of times it has been visited. If the domain has been seen before, just increment
 * the number of times it has been visited by its visited count. Next, we parse out all subdomains from the domain.
 * If the subdomain has not seen before, then map it to its visited count. If it has been seen before, then we increment
 * the number of it has been seen by the domain's visited count. After looping through all the domains, we build the
 * count-paired domains strings and add them to our vector<string> result.
 *
 * Time complexity: O(n * L) [where n is the number of count-paired domains and L is the average length of a count-paired domain]
 * Space complexity: O(number of count-paired domains and number of subdomains for each count-paired domains)
 *
 * 2) Same logic as the first solution except that we use getline instead of >> when parsing the count-paired domain strings.
 *
 * Time complexity: O(n * L) [where n is the number of count-paired domains and L is the average length of a count-paired domain]
 * Space complexity: O(number of count-paired domains and number of subdomains for each count-paired domains)
 */

vector<string> subdomainVisits(vector<string>& cpdomains)
{
    vector<string> result;

    if(cpdomains.empty())
    {
        return result;
    }

    unordered_map<string, int> hashtable;

    for(string & cpdomain : cpdomains)
    {
        stringstream ss(cpdomain);

        int count=0;

        string buffer{};

        int visitedCount=0;

        string domain{};

        while(ss >> buffer)
        {
            if(count==0)
            {
                visitedCount=stoi(buffer);
            }
            else
            {
                domain=buffer;
            }

            count++;
        }

        if(!hashtable.count(domain))
        {
            hashtable[domain]=visitedCount;
        }
        else
        {
            hashtable[domain]+=visitedCount;
        }

        char period='.';

        size_t dotPosition=domain.find(period);

        while(dotPosition!=string::npos)
        {
            string subdomain(domain.substr(dotPosition+1));

            if(!hashtable.count(subdomain))
            {
                hashtable[subdomain]=visitedCount;
            }
            else
            {
                hashtable[subdomain]+=visitedCount;
            }

            dotPosition=domain.find(period, dotPosition+1);
        }
    }

    for(auto & element : hashtable)
    {
        string cpdomain{};

        cpdomain+=to_string(element.second);

        cpdomain+=" ";

        cpdomain+=element.first;

        result.push_back(cpdomain);
    }

    return result;
}

vector<string> subdomainVisits(vector<string>& cpdomains)
{
    vector<string> result;

    if(cpdomains.empty())
    {
        return result;
    }

    unordered_map<string, int> hashtable;

    for(string & cpdomain : cpdomains)
    {
        stringstream ss(cpdomain);

        int count=0;

        string buffer{};

        int visitedCount=0;

        string domain{};

        while(getline(ss, buffer, ' '))
        {
            if(count==0)
            {
                visitedCount=stoi(buffer);
            }
            else
            {
                domain=buffer;
            }

            count++;
        }

        if(!hashtable.count(domain))
        {
            hashtable[domain]=visitedCount;
        }
        else
        {
            hashtable[domain]+=visitedCount;
        }

        char period='.';

        size_t dotPosition=domain.find(period);

        while(dotPosition!=string::npos)
        {
            string subdomain(domain.substr(dotPosition+1));

            if(!hashtable.count(subdomain))
            {
                hashtable[subdomain]=visitedCount;
            }
            else
            {
                hashtable[subdomain]+=visitedCount;
            }

            dotPosition=domain.find(period, dotPosition+1);
        }
    }

    for(auto & element : hashtable)
    {
        string cpdomain(to_string(element.second) + " " + element.first);

        result.push_back(cpdomain);
    }

    return result;
}


text:
// Copyright 2014 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "android_webview/browser/hardware_renderer.h"

#include "android_webview/browser/aw_gl_surface.h"
#include "android_webview/browser/deferred_gpu_command_service.h"
#include "android_webview/browser/parent_output_surface.h"
#include "android_webview/browser/shared_renderer_state.h"
#include "android_webview/public/browser/draw_gl.h"
#include "base/auto_reset.h"
#include "base/strings/string_number_conversions.h"
#include "base/trace_event/trace_event.h"
#include "cc/layers/delegated_frame_provider.h"
#include "cc/layers/delegated_renderer_layer.h"
#include "cc/layers/layer.h"
#include "cc/output/compositor_frame.h"
#include "cc/output/output_surface.h"
#include "cc/scheduler/begin_frame_source.h"
#include "cc/trees/layer_tree_host.h"
#include "cc/trees/layer_tree_settings.h"
#include "gpu/blink/webgraphicscontext3d_in_process_command_buffer_impl.h"
#include "gpu/command_buffer/client/gl_in_process_context.h"
#include "gpu/command_buffer/common/gles2_cmd_utils.h"
#include "ui/gfx/frame_time.h"
#include "ui/gfx/geometry/rect_conversions.h"
#include "ui/gfx/geometry/rect_f.h"
#include "ui/gfx/transform.h"
#include "ui/gl/gl_bindings.h"
#include "webkit/common/gpu/context_provider_in_process.h"

namespace android_webview {

namespace {

using gpu_blink::WebGraphicsContext3DImpl;
using gpu_blink::WebGraphicsContext3DInProcessCommandBufferImpl;

scoped_refptr<cc::ContextProvider> CreateContext(
    scoped_refptr<gfx::GLSurface> surface,
    scoped_refptr<gpu::InProcessCommandBuffer::Service> service) {
  const gfx::GpuPreference gpu_preference = gfx::PreferDiscreteGpu;

  blink::WebGraphicsContext3D::Attributes attributes;
  attributes.antialias = false;
  attributes.depth = false;
  attributes.stencil = false;
  attributes.shareResources = true;
  attributes.noAutomaticFlushes = true;
  gpu::gles2::ContextCreationAttribHelper attribs_for_gles2;
  WebGraphicsContext3DImpl::ConvertAttributes(
      attributes, &attribs_for_gles2);
  attribs_for_gles2.lose_context_when_out_of_memory = true;

  scoped_ptr<gpu::GLInProcessContext> context(gpu::GLInProcessContext::Create(
      service,
      surface,
      surface->IsOffscreen(),
      gfx::kNullAcceleratedWidget,
      surface->GetSize(),
      NULL /* share_context */,
      false /* share_resources */,
      attribs_for_gles2,
      gpu_preference,
      gpu::GLInProcessContextSharedMemoryLimits(),
      nullptr,
      nullptr));
  DCHECK(context.get());

  return webkit::gpu::ContextProviderInProcess::Create(
      WebGraphicsContext3DInProcessCommandBufferImpl::WrapContext(
          context.Pass(), attributes),
      "Parent-Compositor");
}

}  // namespace

HardwareRenderer::HardwareRenderer(SharedRendererState* state)
    : shared_renderer_state_(state),
      last_egl_context_(eglGetCurrentContext()),
      stencil_enabled_(false),
      viewport_clip_valid_for_dcheck_(false),
      gl_surface_(new AwGLSurface),
      root_layer_(cc::Layer::Create()),
      resource_collection_(new cc::DelegatedFrameResourceCollection),
      output_surface_(NULL) {
  DCHECK(last_egl_context_);

  resource_collection_->SetClient(this);

  cc::LayerTreeSettings settings;

  // Should be kept in sync with compositor_impl_android.cc.
  settings.renderer_settings.allow_antialiasing = false;
  settings.renderer_settings.highp_threshold_min = 2048;

  // Webview does not own the surface so should not clear it.
  settings.renderer_settings.should_clear_root_render_pass = false;

  // TODO(enne): Update this this compositor to use a synchronous scheduler.
  settings.single_thread_proxy_scheduler = false;

  layer_tree_host_ = cc::LayerTreeHost::CreateSingleThreaded(
      this, this, nullptr, nullptr, settings, nullptr, nullptr);
  layer_tree_host_->SetRootLayer(root_layer_);
  layer_tree_host_->SetLayerTreeHostClientReady();
  layer_tree_host_->set_has_transparent_background(true);
}

HardwareRenderer::~HardwareRenderer() {
  SetFrameData();

  // Must reset everything before |resource_collection_| to ensure all
  // resources are returned before resetting |resource_collection_| client.
  layer_tree_host_.reset();
  root_layer_ = NULL;
  delegated_layer_ = NULL;
  frame_provider_ = NULL;
#if DCHECK_IS_ON()
  // Check collection is empty.
  cc::ReturnedResourceArray returned_resources;
  resource_collection_->TakeUnusedResourcesForChildCompositor(
      &returned_resources);
  DCHECK_EQ(0u, returned_resources.size());
#endif  // DCHECK_IS_ON()

  resource_collection_->SetClient(NULL);

  // Reset draw constraints.
  shared_renderer_state_->UpdateDrawConstraintsOnRT(
      ParentCompositorDrawConstraints());
}

void HardwareRenderer::DidBeginMainFrame() {
  // This is called after OutputSurface is created, but before the impl frame
  // starts. We set the draw constraints here.
  DCHECK(output_surface_);
  DCHECK(viewport_clip_valid_for_dcheck_);
  output_surface_->SetExternalStencilTest(stencil_enabled_);
  output_surface_->SetDrawConstraints(viewport_, clip_);
}

void HardwareRenderer::CommitFrame() {
  TRACE_EVENT0("android_webview", "CommitFrame");
  scroll_offset_ = shared_renderer_state_->GetScrollOffsetOnRT();
  if (committed_frame_.get()) {
    TRACE_EVENT_INSTANT0("android_webview",
                         "EarlyOut_PreviousFrameUnconsumed",
                         TRACE_EVENT_SCOPE_THREAD);
    shared_renderer_state_->DidSkipCommitFrameOnRT();
    return;
  }

  committed_frame_ = shared_renderer_state_->PassCompositorFrameOnRT();
  // Happens with empty global visible rect.
  if (!committed_frame_.get())
    return;

  DCHECK(!committed_frame_->gl_frame_data);
  DCHECK(!committed_frame_->software_frame_data);

  // DelegatedRendererLayerImpl applies the inverse device_scale_factor of the
  // renderer frame, assuming that the browser compositor will scale
  // it back up to device scale.  But on Android we put our browser layers in
  // physical pixels and set our browser CC device_scale_factor to 1, so this
  // suppresses the transform.
  committed_frame_->delegated_frame_data->device_scale_factor = 1.0f;
}

void HardwareRenderer::SetFrameData() {
  if (!committed_frame_.get())
    return;

  scoped_ptr<cc::CompositorFrame> frame = committed_frame_.Pass();
  gfx::Size frame_size =
      frame->delegated_frame_data->render_pass_list.back()->output_rect.size();
  bool size_changed = frame_size != frame_size_;
  frame_size_ = frame_size;

  if (!frame_provider_.get() || size_changed) {
    if (delegated_layer_.get()) {
      delegated_layer_->RemoveFromParent();
    }

    frame_provider_ = new cc::DelegatedFrameProvider(
        resource_collection_.get(), frame->delegated_frame_data.Pass());

    delegated_layer_ = cc::DelegatedRendererLayer::Create(frame_provider_);
    delegated_layer_->SetBounds(frame_size_);
    delegated_layer_->SetIsDrawable(true);

    root_layer_->AddChild(delegated_layer_);
  } else {
    frame_provider_->SetFrameData(frame->delegated_frame_data.Pass());
  }
}

void HardwareRenderer::DrawGL(bool stencil_enabled,
                              int framebuffer_binding_ext,
                              AwDrawGLInfo* draw_info) {
  TRACE_EVENT0("android_webview", "HardwareRenderer::DrawGL");

  // We need to watch if the current Android context has changed and enforce
  // a clean-up in the compositor.
  EGLContext current_context = eglGetCurrentContext();
  DCHECK(current_context) << "DrawGL called without EGLContext";

  // TODO(boliu): Handle context loss.
  if (last_egl_context_ != current_context)
    DLOG(WARNING) << "EGLContextChanged";

  SetFrameData();
  if (shared_renderer_state_->ForceCommitOnRT()) {
    CommitFrame();
    SetFrameData();
  }

  gfx::Transform transform(gfx::Transform::kSkipInitialization);
  transform.matrix().setColMajorf(draw_info->transform);
  transform.Translate(scroll_offset_.x(), scroll_offset_.y());

  // Need to post the new transform matrix back to child compositor
  // because there is no onDraw during a Render Thread animation, and child
  // compositor might not have the tiles rasterized as the animation goes on.
  ParentCompositorDrawConstraints draw_constraints(
      draw_info->is_layer, transform, gfx::Rect(viewport_));

  draw_constraints_ = draw_constraints;
  shared_renderer_state_->PostExternalDrawConstraintsToChildCompositorOnRT(
      draw_constraints);

  if (!delegated_layer_.get())
    return;

  viewport_.SetSize(draw_info->width, draw_info->height);
  layer_tree_host_->SetViewportSize(viewport_);
  clip_.SetRect(draw_info->clip_left,
                draw_info->clip_top,
                draw_info->clip_right - draw_info->clip_left,
                draw_info->clip_bottom - draw_info->clip_top);
  stencil_enabled_ = stencil_enabled;

  delegated_layer_->SetTransform(transform);

  gl_surface_->SetBackingFrameBufferObject(framebuffer_binding_ext);
  {
    base::AutoReset<bool> frame_resetter(&viewport_clip_valid_for_dcheck_,
                                         true);
    layer_tree_host_->SetNeedsRedrawRect(clip_);
    layer_tree_host_->Composite(gfx::FrameTime::Now());
  }
  gl_surface_->ResetBackingFrameBufferObject();
}

void HardwareRenderer::RequestNewOutputSurface() {
  scoped_refptr<cc::ContextProvider> context_provider =
      CreateContext(gl_surface_,
                    DeferredGpuCommandService::GetInstance());
  scoped_ptr<ParentOutputSurface> output_surface_holder(
      new ParentOutputSurface(context_provider));
  output_surface_ = output_surface_holder.get();
  layer_tree_host_->SetOutputSurface(output_surface_holder.Pass());
}

void HardwareRenderer::DidFailToInitializeOutputSurface() {
  RequestNewOutputSurface();
}

void HardwareRenderer::UnusedResourcesAreAvailable() {
  cc::ReturnedResourceArray returned_resources;
  resource_collection_->TakeUnusedResourcesForChildCompositor(
      &returned_resources);
  shared_renderer_state_->InsertReturnedResourcesOnRT(returned_resources);
}

}  // namespace android_webview


text:
package pwalk

import (
	"fmt"
	"os"
	"path/filepath"
	"runtime"
	"sync"
)

type WalkFunc = filepath.WalkFunc

// Walk is a wrapper for filepath.Walk which can call multiple walkFn
// in parallel, allowing to handle each item concurrently. A maximum of
// twice the runtime.NumCPU() walkFn will be called at any one time.
// If you want to change the maximum, use WalkN instead.
//
// The order of calls is non-deterministic.
//
// Note that this implementation only supports primitive error handling:
//
// - no errors are ever passed to walkFn;
//
// - once a walkFn returns any error, all further processing stops
// and the error is returned to the caller of Walk;
//
// - filepath.SkipDir is not supported;
//
// - if more than one walkFn instance will return an error, only one
// of such errors will be propagated and returned by Walk, others
// will be silently discarded.
func Walk(root string, walkFn WalkFunc) error {
	return WalkN(root, walkFn, runtime.NumCPU()*2)
}

// WalkN is a wrapper for filepath.Walk which can call multiple walkFn
// in parallel, allowing to handle each item concurrently. A maximum of
// num walkFn will be called at any one time.
//
// Please see Walk documentation for caveats of using this function.
func WalkN(root string, walkFn WalkFunc, num int) error {
	// make sure limit is sensible
	if num < 1 {
		return fmt.Errorf("walk(%q): num must be > 0", root)
	}

	files := make(chan *walkArgs, 2*num)
	errCh := make(chan error, 1) // get the first error, ignore others

	// Start walking a tree asap
	var (
		err error
		wg  sync.WaitGroup
	)
	wg.Add(1)
	go func() {
		err = filepath.Walk(root, func(p string, info os.FileInfo, err error) error {
			if err != nil {
				close(files)
				return err
			}
			// add a file to the queue unless a callback sent an error
			select {
			case e := <-errCh:
				close(files)
				return e
			default:
				files <- &walkArgs{path: p, info: &info}
				return nil
			}
		})
		if err == nil {
			close(files)
		}
		wg.Done()
	}()

	wg.Add(num)
	for i := 0; i < num; i++ {
		go func() {
			for file := range files {
				if e := walkFn(file.path, *file.info, nil); e != nil {
					select {
					case errCh <- e: // sent ok
					default: // buffer full
					}
				}
			}
			wg.Done()
		}()
	}

	wg.Wait()

	return err
}

// walkArgs holds the arguments that were passed to the Walk or WalkN
// functions.
type walkArgs struct {
	path string
	info *os.FileInfo
}


text:
/// <reference path="~/Scripts/_references.js" />

Microsoft.WebPortal.Views.NewCustomerProfileView = function (webPortal, elementSelector, isShown, animation) {
    /// <summary>
    /// A view that render input fields for a new customer company and contact information.
    /// </summary>
    /// <param name="webPortal">The web portal instance</param>
    /// <param name="elementSelector">The JQuery selector for the HTML element this view will own.</param>
    /// <param name="isShown">The initial show state. Optional. Default is false.</param>
    /// <param name="animation">Optional animation to use for showing and hiding the view.</param>

    this.base.constructor.call(this, webPortal, elementSelector, isShown, null, animation);
    this.template = "newCustomerProfile-template";

    this.viewModel = {
        Countries: [
            {
                Id: "US",
                Name: "United States"
            }
        ],
        Country: ko.observable(),
        CompanyName: ko.observable(""),
        AddressLine1: ko.observable(""),
        AddressLine2: ko.observable(""),
        City: ko.observable(""),
        State: ko.observable(""),
        ZipCode: ko.observable(""),
        Email: ko.observable(""),
        Password: ko.observable(""),
        PasswordConfirmation: ko.observable(""),
        FirstName: ko.observable(""),
        LastName: ko.observable(""),
        Phone: ko.observable(""),
        DomainPrefix: ko.observable(""),
        CustomerMicrosoftID: ko.observable("") // manage the client id field value.

    }

    this.viewModel.UserName = ko.computed(function () {
        return "admin@" + this.viewModel.DomainPrefix() + ".onmicrosoft.com";
    }, this);
}

// extend the base view
$WebPortal.Helpers.inherit(Microsoft.WebPortal.Views.NewCustomerProfileView, Microsoft.WebPortal.Core.View);

Microsoft.WebPortal.Views.NewCustomerProfileView.prototype.onRender = function () {
    /// <summary>
    /// Called when the view is rendered.
    /// </summary>

    $(this.elementSelector).attr("data-bind", "template: { name: '" + this.template + "'}");
    ko.applyBindings(this, $(this.elementSelector)[0]);
}

Microsoft.WebPortal.Views.NewCustomerProfileView.prototype.onShowing = function (isShowing) {
}

Microsoft.WebPortal.Views.NewCustomerProfileView.prototype.onShown = function (isShowing) {
}

Microsoft.WebPortal.Views.NewCustomerProfileView.prototype.onDestroy = function () {
    /// <summary>
    /// Called when the journey trail is about to be destroyed.
    /// </summary>

    if ($(this.elementSelector)[0]) {
        // if the element is there, clear its bindings and clean up its content
        ko.cleanNode($(this.elementSelector)[0]);
        $(this.elementSelector).empty();
    }
}

//@ sourceURL=NewCustomerProfileView.js


text: public zgif plugin for icred


text:
using base::StringPiece;
using base::hash_map;
using base::hash_set;
using std::vector;

namespace net {

// We want to make sure we delete any closed streams in a safe manner.
// To avoid deleting a stream in mid-operation, we have a simple shim between
// us and the stream, so we can delete any streams when we return from
// processing.
//
// We could just override the base methods, but this makes it easier to make
// sure we don't miss any.
class VisitorShim : public QuicConnectionVisitorInterface {
 public:
  explicit VisitorShim(QuicSession* session) : session_(session) {}

  virtual bool OnPacket(const IPEndPoint& self_address,
                        const IPEndPoint& peer_address,
                        const QuicPacketHeader& header,
                        const vector<QuicStreamFrame>& frame) OVERRIDE {
    bool accepted = session_->OnPacket(self_address, peer_address, header,
                                       frame);
    session_->PostProcessAfterData();
    return accepted;
  }
  virtual void OnRstStream(const QuicRstStreamFrame& frame) OVERRIDE {
    session_->OnRstStream(frame);
    session_->PostProcessAfterData();
  }

  virtual void OnGoAway(const QuicGoAwayFrame& frame) OVERRIDE {
    session_->OnGoAway(frame);
    session_->PostProcessAfterData();
  }

  virtual void OnAck(const SequenceNumberSet& acked_packets) OVERRIDE {
    session_->OnAck(acked_packets);
    session_->PostProcessAfterData();
  }

  virtual bool OnCanWrite() OVERRIDE {
    bool rc = session_->OnCanWrite();
    session_->PostProcessAfterData();
    return rc;
  }

  virtual void ConnectionClose(QuicErrorCode error, bool from_peer) OVERRIDE {
    session_->ConnectionClose(error, from_peer);
    // The session will go away, so don't bother with cleanup.
  }

 private:
  QuicSession* session_;
};

QuicSession::QuicSession(QuicConnection* connection, bool is_server)
    : connection_(connection),
      visitor_shim_(new VisitorShim(this)),
      max_open_streams_(kDefaultMaxStreamsPerConnection),
      next_stream_id_(is_server ? 2 : 3),
      is_server_(is_server),
      largest_peer_created_stream_id_(0),
      goaway_received_(false),
      goaway_sent_(false) {
  connection->set_visitor(visitor_shim_.get());
}

QuicSession::~QuicSession() {
  STLDeleteElements(&closed_streams_);
  STLDeleteValues(&stream_map_);
}

bool QuicSession::OnPacket(const IPEndPoint& self_address,
                           const IPEndPoint& peer_address,
                           const QuicPacketHeader& header,
                           const vector<QuicStreamFrame>& frames) {
  if (header.public_header.guid != connection()->guid()) {
    DLOG(INFO) << "Got packet header for invalid GUID: "
               << header.public_header.guid;
    return false;
  }
  for (size_t i = 0; i < frames.size(); ++i) {
    // TODO(rch) deal with the error case of stream id 0
    if (IsClosedStream(frames[i].stream_id)) continue;

    ReliableQuicStream* stream = GetStream(frames[i].stream_id);
    if (stream == NULL) return false;
    if (!stream->WillAcceptStreamFrame(frames[i])) return false;

    // TODO(alyssar) check against existing connection address: if changed, make
    // sure we update the connection.
  }

  for (size_t i = 0; i < frames.size(); ++i) {
    ReliableQuicStream* stream = GetStream(frames[i].stream_id);
    if (stream) {
      stream->OnStreamFrame(frames[i]);
    }
  }
  return true;
}

void QuicSession::OnRstStream(const QuicRstStreamFrame& frame) {
  ReliableQuicStream* stream = GetStream(frame.stream_id);
  if (!stream) {
    return;  // Errors are handled by GetStream.
  }
  stream->OnStreamReset(frame.error_code);
}

void QuicSession::OnGoAway(const QuicGoAwayFrame& frame) {
  DCHECK(frame.last_good_stream_id < next_stream_id_);
  goaway_received_ = true;
}

void QuicSession::ConnectionClose(QuicErrorCode error, bool from_peer) {
  while (stream_map_.size() != 0) {
    ReliableStreamMap::iterator it = stream_map_.begin();
    QuicStreamId id = it->first;
    it->second->ConnectionClose(error, from_peer);
    // The stream should call CloseStream as part of ConnectionClose.
    if (stream_map_.find(id) != stream_map_.end()) {
      LOG(DFATAL) << "Stream failed to close under ConnectionClose";
      CloseStream(id);
    }
  }
}

bool QuicSession::OnCanWrite() {
  // We latch this here rather than doing a traditional loop, because streams
  // may be modifying the list as we loop.
  int remaining_writes = write_blocked_streams_.size();

  while (!connection_->HasQueuedData() &&
         remaining_writes > 0) {
    DCHECK(!write_blocked_streams_.empty());
    ReliableQuicStream* stream = GetStream(write_blocked_streams_.front());
    write_blocked_streams_.pop_front();
    if (stream != NULL) {
      // If the stream can't write all bytes, it'll re-add itself to the blocked
      // list.
      stream->OnCanWrite();
    }
    --remaining_writes;
  }

  return write_blocked_streams_.empty();
}

QuicConsumedData QuicSession::WriteData(QuicStreamId id,
                                        StringPiece data,
                                        QuicStreamOffset offset,
                                        bool fin) {
  return connection_->SendStreamData(id, data, offset, fin);
}

void QuicSession::SendRstStream(QuicStreamId id,
                                QuicErrorCode error) {
  connection_->SendRstStream(id, error);
  CloseStream(id);
}

void QuicSession::SendGoAway(QuicErrorCode error_code, const string& reason) {
  goaway_sent_ = true;
  connection_->SendGoAway(error_code, largest_peer_created_stream_id_, reason);
}

void QuicSession::CloseStream(QuicStreamId stream_id) {
  DLOG(INFO) << "Closing stream " << stream_id;

  ReliableStreamMap::iterator it = stream_map_.find(stream_id);
  if (it == stream_map_.end()) {
    DLOG(INFO) << "Stream is already closed: " << stream_id;
    return;
  }
  it->second->OnClose();
  closed_streams_.push_back(it->second);
  stream_map_.erase(it);
}

bool QuicSession::IsCryptoHandshakeComplete() {
  return GetCryptoStream()->handshake_complete();
}

void QuicSession::OnCryptoHandshakeComplete(QuicErrorCode error) {
  // TODO(rch): tear down the connection if error != QUIC_NO_ERROR.
}

void QuicSession::ActivateStream(ReliableQuicStream* stream) {
  DLOG(INFO) << "num_streams: " << stream_map_.size()
            << ". activating " << stream->id();
  DCHECK(stream_map_.count(stream->id()) == 0);
  stream_map_[stream->id()] = stream;
}

QuicStreamId QuicSession::GetNextStreamId() {
  QuicStreamId id = next_stream_id_;
  next_stream_id_ += 2;
  return id;
}

ReliableQuicStream* QuicSession::GetStream(const QuicStreamId stream_id) {
  if (stream_id == kCryptoStreamId) {
    return GetCryptoStream();
  }

  ReliableStreamMap::iterator it = stream_map_.find(stream_id);
  if (it != stream_map_.end()) {
    return it->second;
  }

  if (IsClosedStream(stream_id)) {
    return NULL;
  }

  if (stream_id % 2 == next_stream_id_ % 2) {
    // We've received a frame for a locally-created stream that is not
    // currently active.  This is an error.
    connection()->SendConnectionClose(QUIC_PACKET_FOR_NONEXISTENT_STREAM);
    return NULL;
  }

  return GetIncomingReliableStream(stream_id);
}

ReliableQuicStream* QuicSession::GetIncomingReliableStream(
    QuicStreamId stream_id) {
  if (IsClosedStream(stream_id)) {
    return NULL;
  }

  if (goaway_sent_) {
    // We've already sent a GoAway
    connection()->SendRstStream(stream_id, QUIC_PEER_GOING_AWAY);
    return NULL;
  }

  implicitly_created_streams_.erase(stream_id);
  if (stream_id > largest_peer_created_stream_id_) {
    // TODO(rch) add unit test for this
    if (stream_id - largest_peer_created_stream_id_ > kMaxStreamIdDelta) {
      connection()->SendConnectionClose(QUIC_INVALID_STREAM_ID);
      return NULL;
    }
    if (largest_peer_created_stream_id_ != 0) {
      for (QuicStreamId id = largest_peer_created_stream_id_ + 2;
           id < stream_id;
           id += 2) {
        implicitly_created_streams_.insert(id);
      }
    }
    largest_peer_created_stream_id_ = stream_id;
  }
  ReliableQuicStream* stream = CreateIncomingReliableStream(stream_id);
  if (stream == NULL) {
    return NULL;
  }
  ActivateStream(stream);
  return stream;
}

bool QuicSession::IsClosedStream(QuicStreamId id) {
  DCHECK_NE(0u, id);
  if (id == kCryptoStreamId) {
    return false;
  }
  if (stream_map_.count(id) != 0) {
    // Stream is active
    return false;
  }
  if (id % 2 == next_stream_id_ % 2) {
    // Locally created streams are strictly in-order.  If the id is in the
    // range of created streams and it's not active, it must have been closed.
    return id < next_stream_id_;
  }
  // For peer created streams, we also need to consider implicitly created
  // streams.
  return id <= largest_peer_created_stream_id_ &&
      implicitly_created_streams_.count(id) == 0;
}

size_t QuicSession::GetNumOpenStreams() const {
  return stream_map_.size() + implicitly_created_streams_.size();
}

void QuicSession::MarkWriteBlocked(QuicStreamId id) {
  write_blocked_streams_.push_back(id);
}

void QuicSession::PostProcessAfterData() {
  STLDeleteElements(&closed_streams_);
  closed_streams_.clear();
}

}  // namespace net


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
Revta Fac. Agron. Vet. Univ. nac. La Plata 2(22): 344 (1896)

#### Original name
Capnodium trichostomum Speg.

### Remarks
null


text:
package main

import (
	"encoding/json"
	"time"

	"github.com/gorilla/websocket"
	"github.com/kokomo88/bitrise-cli-webui/models"
)

const (
	// Time allowed to write a message to the peer.
	writeWait = 10 * time.Second

	// Time allowed to read the next pong message from the peer.
	pongWait = 60 * time.Second

	// Send pings to peer with this period. Must be less than pongWait.
	pingPeriod = (pongWait * 9) / 10

	// Maximum message size allowed from peer.
	maxMessageSize = 1024000
)

var upgrader = websocket.Upgrader{
	ReadBufferSize:  1024000,
	WriteBufferSize: 1024000,
}

// connection is an middleman between the websocket connection and the hub.
type connection struct {
	// The websocket connection.
	ws *websocket.Conn

	// Buffered channel of outbound messages.
	send chan []byte
}

func sendMessage(Type string, msg string) {
	var m = &models.Message{}
	m.Type = Type
	m.Msg = msg
	byteArr, err := json.Marshal(m)
	printError("Json encoding:", err)
	h.broadcast <- byteArr
}

// readPump pumps messages from the websocket connection to the hub.
func (c *connection) readPump() {
	defer func() {
		h.unregister <- c
		err := c.ws.Close()
		printError("Websocket Close:", err)
	}()
	c.ws.SetReadLimit(maxMessageSize)
	err := c.ws.SetReadDeadline(time.Now().Add(pongWait))
	printError("Websocket SetReadDeadline:", err)
	c.ws.SetPongHandler(func(string) error {
		err = c.ws.SetReadDeadline(time.Now().Add(pongWait))
		printError("Websocket SetReadDeadline:", err)
		return nil
	})

	for {
		_, message, err := c.ws.ReadMessage()
		if err != nil {
			break
		}

		//Handle incomming messages
		var dat = &models.Message{}
		err = json.Unmarshal(message, &dat)
		printError("Json encoding :", err)
		if dat.Type == "init" {
			message = readYAMLToBytes()
			h.broadcast <- message
		} else if dat.Type == "build" && !testRunning {
			go runCommand(c, dat.Msg)
			sendMessage("info", "$bitrise-cli run "+dat.Msg+"\n")
		} else if dat.Type == "save" {
			var data = &models.SaveMessage{}
			err = json.Unmarshal(message, &data)
			printError("Json encoding :", err)
			saveConfig(data.Msg)
			// fmt.Printf("%#v", dat.Msg)
		} else if dat.Type == "abort" && testRunning {
			abort <- "Aborting build"
			sendMessage("info", "Aborting build\n")
		}
	}

}

// write writes a message with the given message type and payload.
func (c *connection) write(mt int, payload []byte) error {
	err := c.ws.SetWriteDeadline(time.Now().Add(writeWait))
	printError("Websocket SetWriteDeadline :", err)
	return c.ws.WriteMessage(mt, payload)
}

// writePump pumps messages from the hub to the websocket connection.
func (c *connection) writePump() {
	ticker := time.NewTicker(pingPeriod)
	defer func() {
		ticker.Stop()
		err := c.ws.Close()
		printError("Websocket close :", err)
	}()
	for {
		select {
		case message, ok := <-c.send:
			if !ok {
				err := c.write(websocket.CloseMessage, []byte{})
				printError("Websocket write :", err)
				return
			}

			if err := c.write(websocket.TextMessage, message); err != nil {
				return
			}
		case <-ticker.C:
			if err := c.write(websocket.PingMessage, []byte{}); err != nil {
				return
			}
		}
	}
}

func (c *connection) sendHistory() {
	for _, val := range history {
		//c.send <- val
		sendMessage("info", (string)(val))
		time.Sleep(time.Millisecond * 1)
	}
}


text:
from datetime import datetime

from pymongo import MongoClient, ASCENDING
from scrapy.utils.project import get_project_settings

class MongoDB:

    def __init__(self):
        self._db = None

    def _create_indexes(self):
        db = self._db
        feed = db['feed']
        feed.create_index('url', name='idx_url')
        article = db['article']
        article.create_index('crawl_date', name='idx_crawl_date')
        article.create_index(
                [('spider', ASCENDING), ('crawl_date', ASCENDING)],
                name='idx_spider_crawl_date'
        )
        scrapecount = db['scrapecount']
        scrapecount.create_index('spider', name='idx_spider')

    def _connect(self):
        settings = get_project_settings()
        client = MongoClient(settings['MONGODB_URI'], connect=False)
        db = client[settings['MONGODB_DB_NAME']]
        db.authenticate(settings['MONGODB_USER'], settings['MONGODB_PWD'])
        self._db = db
        self._create_indexes()

    def __getattr__(self, key):
        if self._db is None:
            self._connect()
        try:
            return self._db[key]
        except KeyError:
            raise AttributeError(f'collection[{key}] not found')

ScrapyDB = MongoDB()

def is_exists_feed(url):
    cursor = ScrapyDB.feed.find({'url': url}).limit(1)
    if cursor.count() == 0:
        return False
    else:
        return True

def save_feed(url):
    result = ScrapyDB.feed.insert_one(
        {
            'url': url,
            'create_date': datetime.now()
        }
    )
    return result.inserted_id

def is_exists_article(item):
    day = datetime.combine(item['crawl_date'].date(), datetime.min.time())
    cursor = ScrapyDB.article.find(
        {
            'spider': item['spider'],
            'crawl_date': {'$lt': day},
            'title': item['title'],
            'domain': item['domain'],
            'source': item['source']
        }
    ).limit(1)
    if cursor.count() > 0:
        return True
    cursor = ScrapyDB.article.find(
        {
            'spider': item['spider'],
            'crawl_date': {'$gte': day},
            'title': item['title']
        },
        {
            'content': 1
        }
    ).limit(1)
    if (cursor.count() > 0 and
       len(cursor[0]['content']) > len(item['content'])):
        return True
    return False

def save_article(item):
    day = datetime.combine(item['crawl_date'].date(), datetime.min.time())
    result = ScrapyDB.article.update(
        {
            'spider': item['spider'],
            'crawl_date': {'$gte': day},
            'title': item['title']
        },
        item,
        upsert=True
    )
    return result

def is_exists_spider(url):
    cursor = ScrapyDB.spider.find(
            {
                'start_urls': {'$in': [url]}
            }
    )
    if cursor.count() == 0:
        return False
    else:
        return True

def save_spider_settings(settings):
    try:
        del settings['_id']
    except KeyError:
        pass
    result = ScrapyDB.spider.insert_one(settings)
    return result.inserted_id

def get_spider_settings():
    settings = []
    cursor = ScrapyDB.spider.find()
    for item in cursor:
        setting = dict(item)
        setting['_id'] = str(item['_id'])
        settings.append(setting)
    return settings

def get_category_tags():
    cursor = ScrapyDB.category.find()
    return {
            item['category']: item['tags']
            for item in cursor
    }

def log_spider_scrape_count(spider, count):
    result = ScrapyDB.scrapecount.insert_one(
        {
            'spider': spider._id,
            'time': datetime.now(),
            'count': count,
        }
    )
    return result.inserted_id


text:
package br.org.buildtools.checkstyle;

import static br.org.buildtools.arquitetura.ArquiteturaUtils.buscarInterfaceArquitetural;
import static com.puppycrawl.tools.checkstyle.api.TokenTypes.IDENT;
import static com.puppycrawl.tools.checkstyle.api.TokenTypes.IMPLEMENTS_CLAUSE;

import java.util.List;

import com.puppycrawl.tools.checkstyle.api.DetailAST;

import br.org.buildtools.arquitetura.RestricoesArquiteturais;
import br.org.buildtools.arquitetura.TipoArquitetural;
import br.org.buildtools.arquitetura.enums.InterfaceArquitetural;

public class InterfaceArquiteturalCheck extends CustomCheck {

    private static final String MSG_INTERFACE_INVALIDA = MSG_PREFIX + "interfaceInvalida";

    private RestricoesArquiteturais restricoesArquiteturais = RestricoesArquiteturais.getInstance();

    @Override
    public int[] getAcceptableTokens() {
        return new int[] { IMPLEMENTS_CLAUSE };
    }

    @Override
    public int[] getDefaultTokens() {
        return getAcceptableTokens();
    }

    @Override
    public int[] getRequiredTokens() {
        return getAcceptableTokens();
    }

    @Override
    public void visitToken(DetailAST astImplements) {
        TipoArquitetural tipo = new TipoArquiteturalCheck().recuperarTipoValido(astImplements.getParent());

        if (tipo != null) {
            verificarConformidadeInterfacesImplementadas(astImplements, tipo);
        }
    }

    private void verificarConformidadeInterfacesImplementadas(DetailAST astImplements, TipoArquitetural tipo) {
        List<DetailAST> astImplementsIdents = findAllAstsOfType(astImplements, IDENT);
        for (DetailAST astIdent : astImplementsIdents) {
            if (astIdent.getParent().getType() == IMPLEMENTS_CLAUSE) {
                verificarConformidadeInterfaceImplementada(astIdent, tipo);
            }
        }
    }

    private void verificarConformidadeInterfaceImplementada(DetailAST astInterfaceIdent, TipoArquitetural tipo) {
        String nomeInterface = astInterfaceIdent.getText();
        InterfaceArquitetural interfaceArquitetural = buscarInterfaceArquitetural(nomeInterface);
        if (interfaceArquitetural != null
            && !restricoesArquiteturais.ehInterfaceArquiteturalValida(tipo, interfaceArquitetural)) {
            log(astInterfaceIdent.getLineNo(), MSG_INTERFACE_INVALIDA, interfaceArquitetural.name());
        }
    }

}


text:
import unittest
from mock import mock, call

from hpOneView.connection import connection
from hpOneView.resources.task_monitor import TaskMonitor, MSG_UNKNOWN_OBJECT_TYPE, MSG_TASK_TYPE_UNRECONIZED, \
    MSG_TIMEOUT, MSG_UNKNOWN_EXCEPTION, MSG_INVALID_TASK
from hpOneView.exceptions import HPOneViewUnknownType, HPOneViewInvalidResource, HPOneViewTimeout, HPOneViewTaskError

class TaskMonitorTest(unittest.TestCase):
    URI = "/rest/testuri"

    def setUp(self):
        super(TaskMonitorTest, self).setUp()
        self.host = '127.0.0.1'
        self.connection = connection(self.host)
        self.task_monitor = TaskMonitor(self.connection)

    @mock.patch.object(connection, 'get')
    def test_get_associated_resource_with_task(self, mock_get):

        task = {
            "category": "tasks",
            "type": "TaskResourceV2",
            "associatedResource": {
                "resourceUri": "/rest/associatedresourceuri"
            }}

        mock_get.return_value = {"resource": "resource1"}

        ret_task, entity = self.task_monitor.get_associated_resource(task.copy())

        self.assertEqual(entity, {"resource": "resource1"})
        self.assertEqual(ret_task, task)
        mock_get.assert_called_once_with("/rest/associatedresourceuri")

    @mock.patch.object(connection, 'get')
    def test_get_associated_resource_with_backup(self, mock_get):
        backup = {
            "category": "backups",
            "type": "BACKUP",
            "taskUri": "/rest/taskuri",
        }

        task = {
            "category": "TaskResourceV2",
            "type": "tasks",
            "uri": "/rest/justuri",
        }

        def inner_get(uri):
            if uri == "/rest/taskuri":
                return task.copy()
            else:
                return {"resource": "resource1"}

        mock_get.side_effect = inner_get
        mock_get.return_value = task.copy()

        ret_task, entity = self.task_monitor.get_associated_resource(backup.copy())

        self.assertEqual(entity, {"resource": "resource1"})
        self.assertEqual(ret_task, task)

    def test_get_associated_resource_support_dump(self):

        task = {
            "category": "tasks",
            "type": "TaskResourceV2",
            "associatedResource": {
                "resourceUri": "/rest/appliance/support-dumps/hennig59.eco-MyDump16-E-2016_07_07-17_53_42.867287.sdmp"
            }}

        ret_task, entity = self.task_monitor.get_associated_resource(task.copy())

        self.assertEqual(
            entity,
            "/rest/appliance/support-dumps/hennig59.eco-MyDump16-E-2016_07_07-17_53_42.867287.sdmp")
        self.assertEqual(ret_task, task)

    def test_get_associated_resource_with_task_empty(self):
        try:
            self.task_monitor.get_associated_resource({})
        except HPOneViewUnknownType as e:
            self.assertEqual(MSG_INVALID_TASK, e.msg)
        else:
            self.fail()

    def test_get_associated_resource_with_invalid_task(self):
        try:
            self.task_monitor.get_associated_resource({"category": "networking"})
        except HPOneViewUnknownType as e:
            self.assertEqual(MSG_UNKNOWN_OBJECT_TYPE, e.msg)
        else:
            self.fail()

    def test_get_associated_resource_with_invalid_type(self):
        try:
            self.task_monitor.get_associated_resource({"category": "tasks",
                                                       "type": "TaskResource"})
        except HPOneViewInvalidResource as e:
            self.assertEqual(MSG_TASK_TYPE_UNRECONIZED % "TaskResource", e.msg)
        else:
            self.fail()

    @mock.patch.object(TaskMonitor, 'get')
    def test_is_task_running(self, mock_get):

        mock_get.return_value = {"uri": "uri",
                                 "taskState": "Pending"}

        self.assertTrue(self.task_monitor.is_task_running({"uri": "uri"}))

    @mock.patch.object(TaskMonitor, 'get')
    def test_is_task_running_false(self, mock_get):
        mock_get.return_value = {"uri": "uri",
                                 "taskState": "Warning"}

        self.assertFalse(self.task_monitor.is_task_running({"uri": "uri"}))

    @mock.patch.object(TaskMonitor, 'is_task_running')
    def test_wait_for_task_timeout(self, mock_is_running):

        mock_is_running.return_value = True
        timeout = 2

        try:
            self.task_monitor.wait_for_task({"uri": "uri"}, timeout)
        except HPOneViewTimeout as e:
            self.assertEqual(MSG_TIMEOUT % timeout, e.msg)
        else:
            self.fail()

    @mock.patch.object(TaskMonitor, 'is_task_running')
    @mock.patch('time.sleep')
    def test_wait_for_task_increasing_sleep(self, mock_sleep, mock_is_running):

        mock_is_running.return_value = True
        timeout = 0.1

        # should call sleep increasing 1 until 10
        calls = [call(1), call(2), call(3), call(4), call(5), call(6), call(7),
                 call(8), call(9), call(10), call(10), call(10)]

        try:
            self.task_monitor.wait_for_task({"uri": "uri"}, timeout)
        except HPOneViewTimeout as e:
            mock_sleep.assert_has_calls(calls)
            self.assertEqual(MSG_TIMEOUT % timeout, e.msg)
        else:
            self.fail()

    @mock.patch.object(TaskMonitor, 'is_task_running')
    @mock.patch.object(TaskMonitor, 'get')
    def test_wait_for_task_with_error_message(self, mock_get, mock_is_running):

        task = {"uri": "uri",
                "taskState": "Error",
                "taskErrors": [{"message": "Error Message"}]}

        mock_is_running.return_value = False
        mock_get.return_value = task

        try:
            self.task_monitor.wait_for_task(task.copy())
        except HPOneViewTaskError as e:
            self.assertEqual("Error Message", e.msg)
        else:
            self.fail()

    def test_wait_for_task_empty(self):
        try:
            self.task_monitor.wait_for_task({})
        except HPOneViewUnknownType as e:
            self.assertEqual(MSG_INVALID_TASK, e.msg)
        else:
            self.fail()

    @mock.patch.object(TaskMonitor, 'is_task_running')
    @mock.patch.object(TaskMonitor, 'get')
    def test_wait_for_task_with_error_empty(self, mock_get, mock_is_running):

        task = {"uri": "uri",
                "taskState": "Error",
                "taskStatus": "Failed",
                }

        mock_is_running.return_value = False
        mock_get.return_value = task

        try:
            self.task_monitor.wait_for_task(task.copy())
        except HPOneViewTaskError as e:
            self.assertEqual("Failed", e.msg)
        else:
            self.fail()

    @mock.patch.object(TaskMonitor, 'is_task_running')
    @mock.patch.object(TaskMonitor, 'get')
    def test_wait_for_task_with_error_unknown(self, mock_get, mock_is_running):

        task = {"uri": "uri",
                "taskState": "Error",
                }

        mock_is_running.return_value = False
        mock_get.return_value = task

        try:
            self.task_monitor.wait_for_task(task.copy())
        except HPOneViewTaskError as e:
            self.assertEqual(MSG_UNKNOWN_EXCEPTION, e.msg)
        else:
            self.fail()

    @mock.patch.object(TaskMonitor, 'get_associated_resource')
    @mock.patch.object(TaskMonitor, 'is_task_running')
    @mock.patch.object(TaskMonitor, 'get')
    def test_wait_for_task(self, mock_get, mock_is_running, mock_assoc_res):
        task = {"uri": "uri",
                "type": "TaskResourceV2",
                "name": "update",
                "taskState": "Completed",
                }

        mock_is_running.return_value = False
        mock_get.return_value = task
        mock_assoc_res.return_value = task.copy(), {"resource": "resource1"}

        ret_entity = self.task_monitor.wait_for_task(task.copy())

        self.assertEqual(ret_entity, {"resource": "resource1"})

    @mock.patch.object(TaskMonitor, 'is_task_running')
    @mock.patch.object(TaskMonitor, 'get')
    def test_wait_for_task_unexpected_result(self, mock_get, mock_is_running):
        task = {"uri": "uri",
                "type": "Undefined",
                "name": "Undefined",
                "taskState": "Completed",
                }

        mock_is_running.return_value = False
        mock_get.return_value = task

        ret_entity = self.task_monitor.wait_for_task(task.copy())

        self.assertEqual(ret_entity, task.copy())

    @mock.patch.object(TaskMonitor, 'get_associated_resource')
    @mock.patch.object(TaskMonitor, 'is_task_running')
    @mock.patch.object(TaskMonitor, 'get')
    def test_wait_for_task_delete(self, mock_get, mock_is_running, mock_assoc_res):
        task = {"uri": "uri",
                "type": "TaskResourceV2",
                "name": "Delete",
                "taskState": "Completed",
                }

        mock_is_running.return_value = False
        mock_get.return_value = task
        mock_assoc_res.return_value = task.copy(), {"resource": "resource1"}

        ret = self.task_monitor.wait_for_task(task.copy())

        # may return a different type
        self.assertEqual(True, ret)

    @mock.patch.object(connection, 'get')
    def test_get(self, mock_get):
        self.task_monitor.get({"uri": "an uri"})
        mock_get.assert_called_once_with("an uri")


text:
var mongo = require('mongodb').MongoClient;

function setresult(id, ac, all) {
    mongo.connect('mongodb://localhost/cboj', function(err, db) {
        db.collection('problem', function(err, collection) {
            collection.update({id: id}, {$set: {ac: ac, all: all}}, function(err, doc) {});
        });
        db.collection('problems', function(err, collection) {
            collection.update({id: id}, {$set: {ac: ac, all: all}}, function(err, doc) {});
        });
    });
}

function addall(id) {
    mongo.connect('mongodb://localhost/cboj', function(err, db) {
        db.collection('problem', function(err, collection) {
            collection.update({id: id}, {$inc: {all: 1}}, function(err, doc) {});
        });
        db.collection('problems', function(err, collection) {
            collection.update({id: id}, {$inc: {all: 1}}, function(err, doc) {});
        });
    });
}

function addac(id) {
    mongo.connect('mongodb://localhost/cboj', function(err, db) {
        db.collection('problem', function(err, collection) {
            collection.update({id: id}, {$inc: {ac: 1}}, function(err, doc) {});
        });
        db.collection('problems', function(err, collection) {
            collection.update({id: id}, {$inc: {ac: 1}}, function(err, doc) {});
        });
    });
}

function execu() {
mongo.connect('mongodb://localhost/cboj', function(err, db) {
    db.collection('submissions', function(err, collection) {
        collection.find({processed: {$ne: true}}, function(err, doc) {
            doc.toArray(function(err, doc1) {
                for (var i = 0; i < doc1.length; ++ i) {
                    if (doc1[i].status != undefined) {
                        if (Number(doc1[i].status) == 0) addac(Number(doc1[i].problemId));
                        addall(Number(doc1[i].problemId));
                        collection.update({submissionId: doc1[i].submissionId}, {$set: {processed: true}}, function(err, doc) {});
                    }
                }
            });
        });
    });
});
}

exports.exec = execu;


text:
/*
 * UAVCAN data structure definition for libuavcan.
 *
 * Autogenerated, do not edit.
 *
 * Source file: /Users/bendyer/Projects/ARM/workspace/libuavcan/dsdl/uavcan/equipment/indication/SingleLightCommand.uavcan
 */

#ifndef UAVCAN_EQUIPMENT_INDICATION_SINGLELIGHTCOMMAND_HPP_INCLUDED
#define UAVCAN_EQUIPMENT_INDICATION_SINGLELIGHTCOMMAND_HPP_INCLUDED

#include <uavcan/build_config.hpp>
#include <uavcan/node/global_data_type_registry.hpp>
#include <uavcan/marshal/types.hpp>

#include <uavcan/equipment/indication/RGB565.hpp>

/******************************* Source text **********************************
#
# Nested type.
# Controls single light source, color or monochrome.
#

uint8 light_id

RGB565 color      # Monocolor lights should interpret this as brightness
******************************************************************************/

/********************* DSDL signature source definition ***********************
uavcan.equipment.indication.SingleLightCommand
saturated uint8 light_id
uavcan.equipment.indication.RGB565 color
******************************************************************************/

#undef light_id
#undef color

namespace uavcan
{
namespace equipment
{
namespace indication
{

template <int _tmpl>
struct UAVCAN_EXPORT SingleLightCommand_
{
    typedef const SingleLightCommand_<_tmpl>& ParameterType;
    typedef SingleLightCommand_<_tmpl>& ReferenceType;

    struct ConstantTypes
    {
    };

    struct FieldTypes
    {
        typedef ::uavcan::IntegerSpec< 8, ::uavcan::SignednessUnsigned, ::uavcan::CastModeSaturate > light_id;
        typedef ::uavcan::equipment::indication::RGB565 color;
    };

    enum
    {
        MinBitLen
            = FieldTypes::light_id::MinBitLen
            + FieldTypes::color::MinBitLen
    };

    enum
    {
        MaxBitLen
            = FieldTypes::light_id::MaxBitLen
            + FieldTypes::color::MaxBitLen
    };

    // Constants

    // Fields
    typename ::uavcan::StorageType< typename FieldTypes::light_id >::Type light_id;
    typename ::uavcan::StorageType< typename FieldTypes::color >::Type color;

    SingleLightCommand_()
        : light_id()
        , color()
    {
        ::uavcan::StaticAssert<_tmpl == 0>::check();  // Usage check

#if UAVCAN_DEBUG
        /*
         * Cross-checking MaxBitLen provided by the DSDL compiler.
         * This check shall never be performed in user code because MaxBitLen value
         * actually depends on the nested types, thus it is not invariant.
         */
        ::uavcan::StaticAssert<24 == MaxBitLen>::check();
#endif
    }

    bool operator==(ParameterType rhs) const;
    bool operator!=(ParameterType rhs) const { return !operator==(rhs); }

    /**
     * This comparison is based on @ref uavcan::areClose(), which ensures proper comparison of
     * floating point fields at any depth.
     */
    bool isClose(ParameterType rhs) const;

    static int encode(ParameterType self, ::uavcan::ScalarCodec& codec,
                      ::uavcan::TailArrayOptimizationMode tao_mode = ::uavcan::TailArrayOptEnabled);

    static int decode(ReferenceType self, ::uavcan::ScalarCodec& codec,
                      ::uavcan::TailArrayOptimizationMode tao_mode = ::uavcan::TailArrayOptEnabled);

    /*
     * Static type info
     */
    enum { DataTypeKind = ::uavcan::DataTypeKindMessage };
    // This type has no default data type ID

    static const char* getDataTypeFullName()
    {
        return "uavcan.equipment.indication.SingleLightCommand";
    }

    static void extendDataTypeSignature(::uavcan::DataTypeSignature& signature)
    {
        signature.extend(getDataTypeSignature());
    }

    static ::uavcan::DataTypeSignature getDataTypeSignature();

};

/*
 * Out of line struct method definitions
 */

template <int _tmpl>
bool SingleLightCommand_<_tmpl>::operator==(ParameterType rhs) const
{
    return
        light_id == rhs.light_id &&
        color == rhs.color;
}

template <int _tmpl>
bool SingleLightCommand_<_tmpl>::isClose(ParameterType rhs) const
{
    return
        ::uavcan::areClose(light_id, rhs.light_id) &&
        ::uavcan::areClose(color, rhs.color);
}

template <int _tmpl>
int SingleLightCommand_<_tmpl>::encode(ParameterType self, ::uavcan::ScalarCodec& codec,
    ::uavcan::TailArrayOptimizationMode tao_mode)
{
    (void)self;
    (void)codec;
    (void)tao_mode;
    int res = 1;
    res = FieldTypes::light_id::encode(self.light_id, codec,  ::uavcan::TailArrayOptDisabled);
    if (res <= 0)
    {
        return res;
    }
    res = FieldTypes::color::encode(self.color, codec,  tao_mode);
    return res;
}

template <int _tmpl>
int SingleLightCommand_<_tmpl>::decode(ReferenceType self, ::uavcan::ScalarCodec& codec,
    ::uavcan::TailArrayOptimizationMode tao_mode)
{
    (void)self;
    (void)codec;
    (void)tao_mode;
    int res = 1;
    res = FieldTypes::light_id::decode(self.light_id, codec,  ::uavcan::TailArrayOptDisabled);
    if (res <= 0)
    {
        return res;
    }
    res = FieldTypes::color::decode(self.color, codec,  tao_mode);
    return res;
}

/*
 * Out of line type method definitions
 */
template <int _tmpl>
::uavcan::DataTypeSignature SingleLightCommand_<_tmpl>::getDataTypeSignature()
{
    ::uavcan::DataTypeSignature signature(0x945D0D4A16EE764EULL);

    FieldTypes::light_id::extendDataTypeSignature(signature);
    FieldTypes::color::extendDataTypeSignature(signature);

    return signature;
}

/*
 * Out of line constant definitions
 */

/*
 * Final typedef
 */
typedef SingleLightCommand_<0> SingleLightCommand;

// No default registration

} // Namespace indication
} // Namespace equipment
} // Namespace uavcan

/*
 * YAML streamer specialization
 */
namespace uavcan
{

template <>
class UAVCAN_EXPORT YamlStreamer< ::uavcan::equipment::indication::SingleLightCommand >
{
public:
    template <typename Stream>
    static void stream(Stream& s, ::uavcan::equipment::indication::SingleLightCommand::ParameterType obj, const int level);
};

template <typename Stream>
void YamlStreamer< ::uavcan::equipment::indication::SingleLightCommand >::stream(Stream& s, ::uavcan::equipment::indication::SingleLightCommand::ParameterType obj, const int level)
{
    (void)s;
    (void)obj;
    (void)level;
    if (level > 0)
    {
        s << '\n';
        for (int pos = 0; pos < level; pos++)
        {
            s << "  ";
        }
    }
    s << "light_id: ";
    YamlStreamer< ::uavcan::equipment::indication::SingleLightCommand::FieldTypes::light_id >::stream(s, obj.light_id, level + 1);
    s << '\n';
    for (int pos = 0; pos < level; pos++)
    {
        s << "  ";
    }
    s << "color: ";
    YamlStreamer< ::uavcan::equipment::indication::SingleLightCommand::FieldTypes::color >::stream(s, obj.color, level + 1);
}

}

namespace uavcan
{
namespace equipment
{
namespace indication
{

template <typename Stream>
inline Stream& operator<<(Stream& s, ::uavcan::equipment::indication::SingleLightCommand::ParameterType obj)
{
    ::uavcan::YamlStreamer< ::uavcan::equipment::indication::SingleLightCommand >::stream(s, obj, 0);
    return s;
}

} // Namespace indication
} // Namespace equipment
} // Namespace uavcan

#endif // UAVCAN_EQUIPMENT_INDICATION_SINGLELIGHTCOMMAND_HPP_INCLUDED


text:
#ifndef FOORAM_PROTOBOARD_HPP_
#define FOORAM_PROTOBOARD_HPP_

#include "gadgetlib1/gadget.hpp"
#include "relations/ram_computations/rams/fooram/fooram_aux.hpp"

namespace libsnark {

template<typename FieldT>
class fooram_protoboard : public protoboard<FieldT> {
public:
    const fooram_architecture_params ap;

    fooram_protoboard(const fooram_architecture_params &ap);
};

template<typename FieldT>
class fooram_gadget : public gadget<FieldT> {
protected:
    fooram_protoboard<FieldT> &pb;
public:
    fooram_gadget(fooram_protoboard<FieldT> &pb, const std::string &annotation_prefix="");
};

} // libsnark

#include "gadgetlib1/gadgets/cpu_checkers/fooram/components/fooram_protoboard.tcc"

#endif // FOORAM_PROTOBOARD_HPP_


text:
1.  SELECT * FROM states;
2.  SELECT * FROM regions;
3.  SELECT state_name, population
    FROM states;
4.  SELECT state_name, population
    FROM states
    ORDER BY population DESC;
5.  SELECT state_name
    FROM states
    WHERE region_id
    IN (7);
6.  SELECT state_name, population_density
    FROM states
    WHERE population_density > 50
    ORDER BY population_density ASC;
7.  SELECT state_name
    FROM states
    WHERE population
    BETWEEN 1000000 and 1500000;
8.  SELECT state_name, region_id
    FROM states
    ORDER BY region_id ASC;
9.  SELECT region_name
    FROM regions
    WHERE region_name
    LIKE "%Central%";
10. SELECT regions.region_name, states. state_name
    FROM regions
    JOIN states
    ON states.region_id = regions.id
    ORDER BY region_id ASC;

=begin REFLECTION
What are databases for?
Databases are for storing and organizing similar pieces of data => "FACTS related to any object in consideration, ex: age, height, weight, etc."  Data can be in the form of strings, integers, floats, dates, measurements, abbreviations, id numbers or many other types.

What is a one-to-many relationship?
A one-to-many relationship is where one piece of data or object points to a number of other pieces of data or objects.  For instance, a person, identified by their name or id_number, can point to zero, one, or more than one car that they own.  In this case, the piece of data that identifies the individual person can point to multiple pieces of data that identify multiple unique cars.  Not all data types work this way.

What is a primary key? What is a foreign key? How can you determine which is which?
A primary key is unique to each instance of data.  Every instance has one but no two can have the same one.  This could be a name or a coded number like a user_id, social security number, phone number, student id, etc.  In relational databases, a foreign key is a value in one database that points to the primary key of another database.  For example, if you had a database of people, some of whom had one car, others had multiple, and others yet had none, you might want to create a new database to store the information on their cars or lack thereof.  In the Cars table, you would have an ownerID which would point back to the individual person's uniqe primary key ID, to show who owns which car(s).  This allows you to create a unique table to store the attributes of each car and connect them to the people in the other table.  So, in this way, a the relationship between the primary key and foreign key is what connects the one in the one-to-many relationship with its many.

How can you select information out of a SQL database? What are some general guidelines for that?
You generally state which columns you want to select from and then state which table that column can be found in.  You can then input additional commands which allow you to pick pieces of data within a specific range, containing a keyword or string, or grouped in a specific way.  You always must end your commands with a semicolon and convention states that commands should be all caps while the columns/tables should be lower case.  Though, this doesn't actually affect the interpretation of the commands and is mostly for readability.  This was pretty intuitive for the most part.  The commands are all generally symantic and what you'd think they are, there isn't really any tricky context or complex formulas involved.

=end


text:
export interface IAppEngineDuplicateProjectResp {
  projectId: string;
  newOwnerId: string;
}

export enum DuplicateProjectStatus {
  Done = 'done',
  Error = 'error',
  Pending = 'pending',
}

export interface IAppEngineErrorResponse {
  error: string;
}


text:
@class BSBserValues;
@class BSBserWriter;
@class IOSByteArray;
@protocol JavaUtilList;

@interface ImActorModelModulesNotificationsEntityPendingStorage : BSBserObject

#pragma mark Public

- (instancetype)init;

+ (ImActorModelModulesNotificationsEntityPendingStorage *)fromBytesWithByteArray:(IOSByteArray *)data;

- (id<JavaUtilList>)getNotifications;

- (void)parseWithBSBserValues:(BSBserValues *)values;

- (void)serializeWithBSBserWriter:(BSBserWriter *)writer;

@end

J2OBJC_EMPTY_STATIC_INIT(ImActorModelModulesNotificationsEntityPendingStorage)

FOUNDATION_EXPORT ImActorModelModulesNotificationsEntityPendingStorage *ImActorModelModulesNotificationsEntityPendingStorage_fromBytesWithByteArray_(IOSByteArray *data);

FOUNDATION_EXPORT void ImActorModelModulesNotificationsEntityPendingStorage_init(ImActorModelModulesNotificationsEntityPendingStorage *self);

FOUNDATION_EXPORT ImActorModelModulesNotificationsEntityPendingStorage *new_ImActorModelModulesNotificationsEntityPendingStorage_init() NS_RETURNS_RETAINED;

J2OBJC_TYPE_LITERAL_HEADER(ImActorModelModulesNotificationsEntityPendingStorage)

#endif // _ImActorModelModulesNotificationsEntityPendingStorage_H_


text:
namespace aura {
namespace test {

AuraTestHelper::AuraTestHelper(MessageLoopForUI* message_loop)
    : setup_called_(false),
      teardown_called_(false),
      owns_root_window_(false) {
  DCHECK(message_loop);
  message_loop_ = message_loop;
  // Disable animations during tests.
  ui::LayerAnimator::set_disable_animations_for_test(true);
}

AuraTestHelper::~AuraTestHelper() {
  CHECK(setup_called_)
      << "You have overridden SetUp but never called super class's SetUp";
  CHECK(teardown_called_)
      << "You have overridden TearDown but never called super class's TearDown";
}

void AuraTestHelper::SetUp() {
  setup_called_ = true;
  Env::GetInstance()->SetDisplayManager(new SingleDisplayManager);
  root_window_.reset(aura::DisplayManager::CreateRootWindowForPrimaryDisplay());
  test_screen_.reset(new aura::TestScreen(root_window_.get()));
  gfx::Screen::SetScreenInstance(gfx::SCREEN_TYPE_NATIVE, test_screen_.get());
  ui_controls::InstallUIControlsAura(CreateUIControlsAura(root_window_.get()));

  focus_manager_.reset(new FocusManager);
  root_window_->set_focus_manager(focus_manager_.get());
  stacking_client_.reset(new TestStackingClient(root_window_.get()));
  test_activation_client_.reset(
      new test::TestActivationClient(root_window_.get()));
  root_window_capture_client_.reset(
      new shared::RootWindowCaptureClient(root_window_.get()));
  test_input_method_.reset(new ui::test::DummyInputMethod);
  root_window_->SetProperty(
      aura::client::kRootWindowInputMethodKey,
      test_input_method_.get());

  root_window_->Show();
  // Ensure width != height so tests won't confuse them.
  root_window_->SetHostSize(gfx::Size(800, 600));
}

void AuraTestHelper::TearDown() {
  teardown_called_ = true;
  test_input_method_.reset();
  stacking_client_.reset();
  test_activation_client_.reset();
  root_window_capture_client_.reset();
  focus_manager_.reset();
  root_window_.reset();
  test_screen_.reset();
  gfx::Screen::SetScreenInstance(gfx::SCREEN_TYPE_NATIVE, NULL);
  aura::Env::DeleteInstance();
}

void AuraTestHelper::RunAllPendingInMessageLoop() {
#if !defined(OS_MACOSX)
  // TODO(jbates) crbug.com/134753 Find quitters of this RunLoop and have them
  //              use run_loop.QuitClosure().
  base::RunLoop run_loop(Env::GetInstance()->GetDispatcher());
  run_loop.RunUntilIdle();
#endif
}

}  // namespace test
}  // namespace aura