text:
import sys
import argparse
import topic_model_merge

if __name__ == '__main__':
    parser = argparse.ArgumentParser()
    parser.add_argument('--model_dir', action='store', default='../model/news',
                        dest='model_dir', help='the directory of model file')
    parser.add_argument('--conf', action='store', default='lda.conf',
                        dest='conf', help='the configure file')
    parser.add_argument('--k', action='store', default=30, type=int,
                        dest='topk', help='the number of selected words for each topic')
    parser.add_argument('--Jac_opt', action='store', type=int,
                        default=0, dest='Jac_opt',
                        help='0 stands for Jaccard Similarity, 1 stands for Weighted Jaccard Similarity')
    parser.add_argument('--threshold', action='store', type=float, default=0.4,
                        dest='threshold', help='the threshold to tell whether two topics are redundant')
    parser.add_argument('--output_file', action='store', default='./word_topic_merge.model',
                        dest='output_file', help='the output file of the merged model')
    paras = parser.parse_args()

    merger = topic_model_merge.TopicModelMerge(paras.model_dir, paras.conf)
    merger.reduce_topic(paras.topk, paras.threshold, paras.Jac_opt, paras.output_file)


text:
@media screen and (max-width: 900px) {
    #mega_calendar__calendar {
        padding-left: 5px !important;
        padding-right: 5px !important;
    }
}

.mega_calendar_event {
    pointer: cursor !important;
    color:#000000 !important;
}

.mega_calendar_event_closed {
    text-decoration: line-through !important;
    opacity: 0.6 !important;
}

.mega_calendar__filter_fieldset {
    padding-bottom: 20px;
}

.mega_calendar__filter_td {
    padding-left: 10px !important;
}

.mega_calendar__select_operator {
    width: 100px;
}

.mega_calendar__select_value {
    width: 200px;
    height: 80px;
}

.mega_calendar__hide {
    display: none;
}

.mega_calendar__export_ics_div {
    width: 250px;
    position: absolute;
    top: 50%;
    left: 50%;
    margin-top: -125px;
    margin-left:-125px;
    background-color:#628DB6;
    z-index:99;
    text-align: center;
    box-shadow: 0px 0px 10px grey;
    padding: 10px;
    display: none;
}

.mega_calendar__export_ics_div_title {
    font-weight: bold;
}

.mega_calendar__export_ics_div_table {
    display: table; width:250px; padding: 5px;
}

.mega_calendar__export_ics_div_table_row {
    display: table-row;
}

.mega_calendar__export_ics_div_table_cell {
    display: table-cell;
}

.mega_calendar__export_ics_div_cancel_btn {
    background-color: #E6E6E6;
    cursor: pointer;
    display: inline;
    padding: 3px;
}

.mega_calendar__export_ics_div_submit_btn {
    background-color: #E6E6E6;
    cursor: pointer;
    display: inline;
    padding: 3px;
}

redpajama_set_name: RedPajamaGithub


text:
import ReactDOM from 'react-dom';
import {ClientConn} from '../../../src/core/editor';

let callbacks = new Set<() => void>();
let pending = false;

function batch() {
  for (let callback of callbacks) {
    callback();
  }
  callbacks.clear();
  pending = false;
}
function resolve() {
  ReactDOM.unstable_batchedUpdates(batch);
}

export function batchUpdateReact(callback: () => void, conn: ClientConn) {
  callbacks.add(callback);
  if (!pending) {
    pending = true;
    conn.callImmediate(resolve);
  }
}


text:
/*
 * DocuSign REST API
 *
 * The DocuSign REST API provides you with a powerful, convenient, and simple Web services API for interacting with DocuSign.
 *
 * OpenAPI spec version: v2
 * Contact: devcenter@docusign.com
 * Generated by: https://github.com/swagger-api/swagger-codegen.git
 */

using System;
using System.Linq;
using System.IO;
using System.Text;
using System.Text.RegularExpressions;
using System.Collections;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Runtime.Serialization;
using Newtonsoft.Json;
using Newtonsoft.Json.Converters;
using System.ComponentModel.DataAnnotations;

namespace DocuSign.eSign.Model
{
    /// <summary>
    /// BulkEnvelopesResponse
    /// </summary>
    [DataContract]
    public partial class BulkEnvelopesResponse :  IEquatable<BulkEnvelopesResponse>, IValidatableObject
    {
        public BulkEnvelopesResponse()
        {
            // Empty Constructor
        }

        /// <summary>
        /// Initializes a new instance of the <see cref="BulkEnvelopesResponse" /> class.
        /// </summary>
        /// <param name="BulkEnvelopeStatuses">Reserved: TBD.</param>
        /// <param name="EndPosition">The last position in the result set. .</param>
        /// <param name="NextUri">The URI to the next chunk of records based on the search request. If the endPosition is the entire results of the search, this is null. .</param>
        /// <param name="PreviousUri">The postal code for the billing address..</param>
        /// <param name="ResultSetSize">The number of results returned in this response. .</param>
        /// <param name="StartPosition">Starting position of the current result set..</param>
        /// <param name="TotalSetSize">The total number of items available in the result set. This will always be greater than or equal to the value of the property returning the results in the in the response..</param>
        public BulkEnvelopesResponse(List<BulkEnvelopeStatus> BulkEnvelopeStatuses = default(List<BulkEnvelopeStatus>), string EndPosition = default(string), string NextUri = default(string), string PreviousUri = default(string), string ResultSetSize = default(string), string StartPosition = default(string), string TotalSetSize = default(string))
        {
            this.BulkEnvelopeStatuses = BulkEnvelopeStatuses;
            this.EndPosition = EndPosition;
            this.NextUri = NextUri;
            this.PreviousUri = PreviousUri;
            this.ResultSetSize = ResultSetSize;
            this.StartPosition = StartPosition;
            this.TotalSetSize = TotalSetSize;
        }

        /// <summary>
        /// Reserved: TBD
        /// </summary>
        /// <value>Reserved: TBD</value>
        [DataMember(Name="bulkEnvelopeStatuses", EmitDefaultValue=false)]
        public List<BulkEnvelopeStatus> BulkEnvelopeStatuses { get; set; }
        /// <summary>
        /// The last position in the result set.
        /// </summary>
        /// <value>The last position in the result set. </value>
        [DataMember(Name="endPosition", EmitDefaultValue=false)]
        public string EndPosition { get; set; }
        /// <summary>
        /// The URI to the next chunk of records based on the search request. If the endPosition is the entire results of the search, this is null.
        /// </summary>
        /// <value>The URI to the next chunk of records based on the search request. If the endPosition is the entire results of the search, this is null. </value>
        [DataMember(Name="nextUri", EmitDefaultValue=false)]
        public string NextUri { get; set; }
        /// <summary>
        /// The postal code for the billing address.
        /// </summary>
        /// <value>The postal code for the billing address.</value>
        [DataMember(Name="previousUri", EmitDefaultValue=false)]
        public string PreviousUri { get; set; }
        /// <summary>
        /// The number of results returned in this response.
        /// </summary>
        /// <value>The number of results returned in this response. </value>
        [DataMember(Name="resultSetSize", EmitDefaultValue=false)]
        public string ResultSetSize { get; set; }
        /// <summary>
        /// Starting position of the current result set.
        /// </summary>
        /// <value>Starting position of the current result set.</value>
        [DataMember(Name="startPosition", EmitDefaultValue=false)]
        public string StartPosition { get; set; }
        /// <summary>
        /// The total number of items available in the result set. This will always be greater than or equal to the value of the property returning the results in the in the response.
        /// </summary>
        /// <value>The total number of items available in the result set. This will always be greater than or equal to the value of the property returning the results in the in the response.</value>
        [DataMember(Name="totalSetSize", EmitDefaultValue=false)]
        public string TotalSetSize { get; set; }
        /// <summary>
        /// Returns the string presentation of the object
        /// </summary>
        /// <returns>String presentation of the object</returns>
        public override string ToString()
        {
            var sb = new StringBuilder();
            sb.Append("class BulkEnvelopesResponse {\n");
            sb.Append("  BulkEnvelopeStatuses: ").Append(BulkEnvelopeStatuses).Append("\n");
            sb.Append("  EndPosition: ").Append(EndPosition).Append("\n");
            sb.Append("  NextUri: ").Append(NextUri).Append("\n");
            sb.Append("  PreviousUri: ").Append(PreviousUri).Append("\n");
            sb.Append("  ResultSetSize: ").Append(ResultSetSize).Append("\n");
            sb.Append("  StartPosition: ").Append(StartPosition).Append("\n");
            sb.Append("  TotalSetSize: ").Append(TotalSetSize).Append("\n");
            sb.Append("}\n");
            return sb.ToString();
        }

        /// <summary>
        /// Returns the JSON string presentation of the object
        /// </summary>
        /// <returns>JSON string presentation of the object</returns>
        public string ToJson()
        {
            return JsonConvert.SerializeObject(this, Formatting.Indented);
        }

        /// <summary>
        /// Returns true if objects are equal
        /// </summary>
        /// <param name="obj">Object to be compared</param>
        /// <returns>Boolean</returns>
        public override bool Equals(object obj)
        {
            // credit: http://stackoverflow.com/a/10454552/677735
            return this.Equals(obj as BulkEnvelopesResponse);
        }

        /// <summary>
        /// Returns true if BulkEnvelopesResponse instances are equal
        /// </summary>
        /// <param name="other">Instance of BulkEnvelopesResponse to be compared</param>
        /// <returns>Boolean</returns>
        public bool Equals(BulkEnvelopesResponse other)
        {
            // credit: http://stackoverflow.com/a/10454552/677735
            if (other == null)
                return false;

            return
                (
                    this.BulkEnvelopeStatuses == other.BulkEnvelopeStatuses ||
                    this.BulkEnvelopeStatuses != null &&
                    this.BulkEnvelopeStatuses.SequenceEqual(other.BulkEnvelopeStatuses)
                ) &&
                (
                    this.EndPosition == other.EndPosition ||
                    this.EndPosition != null &&
                    this.EndPosition.Equals(other.EndPosition)
                ) &&
                (
                    this.NextUri == other.NextUri ||
                    this.NextUri != null &&
                    this.NextUri.Equals(other.NextUri)
                ) &&
                (
                    this.PreviousUri == other.PreviousUri ||
                    this.PreviousUri != null &&
                    this.PreviousUri.Equals(other.PreviousUri)
                ) &&
                (
                    this.ResultSetSize == other.ResultSetSize ||
                    this.ResultSetSize != null &&
                    this.ResultSetSize.Equals(other.ResultSetSize)
                ) &&
                (
                    this.StartPosition == other.StartPosition ||
                    this.StartPosition != null &&
                    this.StartPosition.Equals(other.StartPosition)
                ) &&
                (
                    this.TotalSetSize == other.TotalSetSize ||
                    this.TotalSetSize != null &&
                    this.TotalSetSize.Equals(other.TotalSetSize)
                );
        }

        /// <summary>
        /// Gets the hash code
        /// </summary>
        /// <returns>Hash code</returns>
        public override int GetHashCode()
        {
            // credit: http://stackoverflow.com/a/263416/677735
            unchecked // Overflow is fine, just wrap
            {
                int hash = 41;
                // Suitable nullity checks etc, of course :)
                if (this.BulkEnvelopeStatuses != null)
                    hash = hash * 59 + this.BulkEnvelopeStatuses.GetHashCode();
                if (this.EndPosition != null)
                    hash = hash * 59 + this.EndPosition.GetHashCode();
                if (this.NextUri != null)
                    hash = hash * 59 + this.NextUri.GetHashCode();
                if (this.PreviousUri != null)
                    hash = hash * 59 + this.PreviousUri.GetHashCode();
                if (this.ResultSetSize != null)
                    hash = hash * 59 + this.ResultSetSize.GetHashCode();
                if (this.StartPosition != null)
                    hash = hash * 59 + this.StartPosition.GetHashCode();
                if (this.TotalSetSize != null)
                    hash = hash * 59 + this.TotalSetSize.GetHashCode();
                return hash;
            }
        }

        public IEnumerable<ValidationResult> Validate(ValidationContext validationContext)
        {
            yield break;
        }
    }

}


text:
(function (root, factory) {
  if (typeof define === 'function' && define.amd) {
    // AMD. Register as an anonymous module.
    define(['jquery'],function(jQuery) {
      // Also create a global in case some scripts
      // that are loaded still are looking for
      // a global even when an AMD loader is in use.
      return (root.Material = factory(jQuery))
    })
  } else if (typeof exports === 'object') {
    // Node. Does not work with strict CommonJS, but
    // only CommonJS-like environments that support module.exports,
    // like Node.
    module.exports = factory(require('jquery'))
  } else {
    // Browser globals (root is window)
    root.Material = factory(jQuery)
  }
}(this, function ($) {'use strict';

var _supportCssAnimations = (function () {
  var el = document.createElement('Material'),
      animEndEvents = {
    WebkitAnimation: 'webkitAnimationEnd',
    MozAnimation: 'animationend',
    OAnimation: 'oAnimationEnd oanimationend',
    animation: 'animationend'
  };

  for (var name in animEndEvents) {
    if (el.style[name] !== undefined) {
      return {
        end: animEndEvents[name]
      };
    }
  }

  return false;
})(),

// Returns a function, that, as long as it continues to be invoked, will not
// be triggered. The function will be called after it stops being called for
// N milliseconds. If `immediate` is passed, trigger the function on the
// leading edge, instead of the trailing.
_debounce = function _debounce(func, wait, immediate) {
  var timeout;
  return function () {
    var context = this,
        args = arguments;
    var later = function later() {
      timeout = null;
      if (!immediate) {
        func.apply(context, args);
      }
    };
    var callNow = immediate && !timeout;
    clearTimeout(timeout);
    timeout = setTimeout(later, wait);
    if (callNow) {
      func.apply(context, args);
    }
  };
},
    _isTouch = 'ontouchstart' in window;

function Material() {
  var _this = this;

  var $container = arguments.length <= 0 || arguments[0] === undefined ? $('body') : arguments[0];

  /**
   *  Get the right mouse/finger coordinates
   */

  this.getCoordinates = function (e) {

    return e.originalEvent.targetTouches ? e.originalEvent.targetTouches[0] : e;
  };

  /**
   *  Append the ripple to the body and let it grow
   */

  this.generateRipple = function (e) {

    var deferredRedirect, $el, $link, $ripple, d, x, y, pointer;

    pointer = _this.getCoordinates(e);

    $el = $(e.currentTarget);
    $link = $el[0].tagName === 'A' ? $el : $(e.target);

    deferredRedirect = $link[0].tagName === 'A' && !$el.hasClass('bypass');

    if (deferredRedirect) {
      e.preventDefault();
    }

    // Create the DOM node to generate the ripple effect
    $ripple = $('');

    // append it to the element clicked
    $el.prepend($ripple);

    //use $el's width or height whichever is larger for the diameter to make a circle which can cover the entire element.
    d = Math.max($el.outerWidth(), $el.outerHeight());
    $ripple.css({
      height: d,
      width: d
    });

    //get click coordinates
    //logic = click coordinates relative to page - $el's position relative to page - half of self height/width to make it controllable from the center
    x = pointer.pageX - $el.offset().left - d / 2;
    y = pointer.pageY - $el.offset().top - d / 2;

    //set the position and add class .animate
    $ripple.css({
      top: y + 'px',
      left: x + 'px'
    }).addClass('animate')
    // remove the element once the animation is finished
    .one(_this.supportCssAnimations.end, function (e) {

      // browse to the page if this is a link
      if (deferredRedirect) {
        window.location.href = $link[0].href;
      }

      $ripple.remove();
    });
  };

  /**
   *  Bind the UI touch/click events
   */

  this.bind = function () {

    if (!_this.supportCssAnimations) {
      return;
    }

    _this.$container.on('click.material dbclick.material', '.ui-effects-material', _debounce(function (e) {
      return _this.generateRipple(e);
    }, 150, true));
  };

  /**
   *  Kill the the UI touch/click events
   */

  this.unbind = function () {

    if (!_this.supportCssAnimations) {
      return;
    }
    _this.$container.off('.material');
  };

  this.supportCssAnimations = _supportCssAnimations;
  this.$container = $container;
  this.bind();

  return this;
}

	return Material
}));


text:
<?php namespace components\forum; if(!defined('TX')) die('No direct access.'); ?>

{{each(i, forum) data}}

      ${forum.title}
      ${forum.description}

      <a href="<?php echo URL_BASE; ?>?pid=${page_id}&fid=${forum.id}" target="_blank" class="icon-eye-open view-forum">

      {{if forum.extra.last_post}}
        <a href="<?php echo URL_BASE; ?>?pid=${page_id}&fid=${forum.id}&tid=${forum.extra.last_post.topic_id}" class="last_post">
          <?php __($component, 'Last post'); ?>: ${forum.extra.last_post.topic_title}

      {{/if}}
      <?php __($component, 'Topics'); ?>: ${forum.extra.num_topics}

      <?php __($component, 'Posts'); ?>: ${forum.extra.num_posts}

  <form method="PUT" action="?rest=forum/forum/${forum.id}" class="edit-sub-forum-form hidden">

      <?php __($component, 'Edit sub forum'); ?>

      <input type="text" class="title" name="title" placeholder="<?php __('Title'); ?>" value="${forum.title}" />

      <textarea class="description" name="description" placeholder="<?php __('Description'); ?>">${forum.description}</textarea>

      <input type="submit" class="button black" value="<?php __('Save'); ?>"/>

  </form>
  {{if forum.subfora}}
{{html template('forumList', forum.subfora)}}
{{/if}}

{{/each}}


text:
<resources>
    <string name="app_name">MyCustomViewDemo</string>

    <string name="refresh_and_loadmore_header_hint_normal">下拉刷新</string>
    <string name="refresh_and_loadmore_header_hint_ready">释放立即刷新</string>
    <string name="refresh_and_loadmore_header_hint_loading">正在刷新...</string>
    <string name="refresh_and_loadmore_header_hint_sucess">刷新成功</string>
    <string name="refresh_and_loadmore_footer_hint_normal">上拉加载更多</string>
    <string name="refresh_and_loadmore_footer_hint_ready">松开加载更多</string>
    <string name="refresh_and_loadmore_footer_hint_loading">正在加载...</string>
    <string name="refresh_and_loadmore_footer_hint_no_more">没有更多</string>
</resources>


text:
using System.Data.Entity;
using DumpDays.AttendeeRegistration.Common;
using DumpDays.AttendeeRegistration.Data.Models;

namespace DumpDays.AttendeeRegistration.Data.Contexts
{
    public interface IAttendeeRegistrationContext
    {
        IDbSet<Attendee> Attendees { get; set; }
        IDbSet<User>     Users     { get; set; }
        IDbSet<Session>  Sessions  { get; set; }
    }

    public class AttendeeRegistrationContext : DbContext, IAttendeeRegistrationContext
    {
        public virtual IDbSet<Attendee> Attendees { get; set; }
        public virtual IDbSet<User>     Users     { get; set; }
        public virtual IDbSet<Session>  Sessions  { get; set; }

        public AttendeeRegistrationContext()
            : base("name=DumpDays.AttendeeRegistration")
        {
            Database.SetInitializer(new CreateDatabaseIfNotExistsAndSeedAdminUser());
        }

        public class CreateDatabaseIfNotExistsAndSeedAdminUser : DropCreateDatabaseIfModelChanges<AttendeeRegistrationContext>
        {
            protected override void Seed(AttendeeRegistrationContext context)
            {
                var rootAdminUser = new User()
                {
                    Username = Data.Configuration.RootAdminUsername,
                    Password = "$2a$12$TdXibCH/0/Ul1NewTIi05.c0m7gvEZghzyMk1i7SfnLyCjYFrzv8m",
                    IsSetup  = true,
                    IsActive = true,
                    Role     = Roles.Administrator
                };

                context.Users.Add(rootAdminUser);
                base.Seed(context);
            }
        }
    }
}


text:
package com.github.jjYBdx4IL.utils.remoterobot.dto;

import java.io.Serializable;

public class MouseReleaseRequest extends Request implements Serializable {

    private static final long serialVersionUID = 1L;

    public int buttons;

    public MouseReleaseRequest() {
    }

    /**
     * Create an instance.
     *
     * @param seq
     *            the request sequence id
     * @param buttons
     *            the mouse buttons to release
     * @return the instance
     */
    public static MouseReleaseRequest create(long seq, int buttons) {
        MouseReleaseRequest request = new MouseReleaseRequest();
        request.seq = seq;
        request.buttons = buttons;
        return request;
    }

}


text:
package org.zalando.intellij.swagger.completion.style;

import org.zalando.intellij.swagger.completion.traversal.PositionResolver;

public class CompletionStyleFactory {

    public static CompletionStyle required(final PositionResolver positionResolver) {
        return positionResolver.shouldQuote()
                ? new CompletionStyle(CompletionStyle.FontWeight.BOLD, positionResolver.getQuoteStyle())
                : new CompletionStyle(CompletionStyle.FontWeight.BOLD);
    }

    public static CompletionStyle optional(final PositionResolver positionResolver) {
        return positionResolver.shouldQuote()
                ? new CompletionStyle(CompletionStyle.FontWeight.NORMAL, positionResolver.getQuoteStyle())
                : new CompletionStyle(CompletionStyle.FontWeight.NORMAL);
    }

}


text:
<?xml version="1.0" encoding="utf-8"?>
<!-- Copyright 2016 Ralph Kristofelle A. Santiago

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

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

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

<android.support.design.widget.CoordinatorLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:fitsSystemWindows="true"
    tools:context="com.rappsantiago.weighttracker.settings.SettingsActivity">

    <include layout="@layout/app_bar" />

    <FrameLayout
        android:id="@+id/content"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        app:layout_behavior="@string/appbar_scrolling_view_behavior" />

</android.support.design.widget.CoordinatorLayout>


text:
A Ruby library for interacting with DynECT Email Delivery API.

[DynECT Email](http://dyn.com/enterprise-email/dynect-email)
[DynECT Email API](https://dynectemail.tenderapp.com/help/kb/api/introduction-to-dynect-email-deliverys-api)

## Installation

### From Git

You can check out the latest source from git:

    git clone git://github.com/Shopify/dynect_email.git

## Usage Example

```ruby
require 'rubygems'
require 'dynect_email'

# Set your API key
DynectEmail.api_key = "your-api-key"

# Add a sender to your account
DynectEmail.add_sender("myemail@example.com")

# Add a sub account with username, password, company, phone
response = DynectEmail.add_account("myemail@example.com", "secretpassword", "Shopify", "1231231231")

# response hash includes the api key for the account that was created
# Add a sender to the sub account
DynectEmail.add_sender("myemail@example.com", response['apikey'])

# Set headers
DynectEmail.set_headers({:xheader1 => "X-Sample1", :xheader2 => "X-Sample2"})

# Remove sender
DynectEmail.remove_sender("myemail@example.com")

# Remove account
DynectEmail.remove_account("myemail@example.com")
```

Check out the [API docs](https://dynectemail.tenderapp.com/help/kb/api/introduction-to-dynect-email-deliverys-api) for more information on what parameters are available.

## Contributing

1. Fork the [official repository](https://github.com/Shopify/dynect_email).
2. Make your changes in a topic branch.
3. Send a pull request.

Notes:

* Contributions without tests won't be accepted.
* Please don't update the Gem version.


text:
FROM ericmdev/essentials-common

# Set the author.
MAINTAINER Eric Mugerwa <dev@ericmugerwa.com>

# Set environment variables.
ENV FILES config/

# Install packages.
RUN apt-get update && apt-get install -y \
    php5-dev \
    php5-common \
    php5-cli \
    php5-mcrypt \
    php5-mysql \
    php5-gd \
    php5-imagick \
    php5-curl \
    php5-intl

# Configure executable.
ENTRYPOINT ["/bin/bash"]

# Define default command.
CMD []


text:
codeigniter-html5boilerplate-twitter-bootstrap
==============================================


text:
module PivotalCardChecker
  # Prints out the report when given the card violation info (bad_card_info).
  class ReportGenerator
    def initialize(bad_card_info, all_stories)
      @bad_card_info = bad_card_info
      @all_stories = all_stories
    end

    # Initializes the report, processes the card info data, and then returns the
    # report, as a string.
    def generate_report
      report_formatting do
        print_card_violations
      end
    end

    # Basic format for the report with a title and clean report message
    def report_formatting
      report = "========= Pivotal Card Checker ===========\n"
      if @bad_card_info.empty?
        report << "CONGRATS! No card violations.\n\n"
      else
        report << yield
      end
    end

    # Loops through the card violations, processes each one, then returns the
    # result.
    def print_card_violations
      card_violations = ''
      @bad_card_info.each do |owner_name, card_manager|
        card_violations << "OWNER(s): #{owner_name}\n"
        card_violations << print_section("        Missing prod description label (\'to_prod\', \'delayed_prod\', \'not_to_prod\', or \'done when merged\'):\n", card_manager.prod_info_issues, false)
        card_violations << print_section("        Missing system label(s):\n", card_manager.sys_label_issues, true)
        card_violations << print_section("        Missing acceptance criteria:\n", card_manager.acceptance_crit_issues, true)
        card_violations << print_section("        Other issues:\n", card_manager.other_issues, true)
        card_violations << print_section("        Nobody is assigned to the following card(s):\n", card_manager.unassigned_cards_issues, false)
        card_violations <<  "\n"
      end
      card_violations
    end

    def generate_validation_report
      report_formatting do
        print_validation_results
      end
    end

    def print_validation_results
      print_section("Card validation errors:\n", @bad_card_info, true)
    end

    # Appends a section to the report. This includes the section heading (missing system label(s),
    # missing acceptance criteria, etc.), and all of the violation information (story name,
    # link, message).
    def print_section(header_text, list, print_message)
      violation_section = ''
      unless list.empty?
        violation_section << header_text
        list.each do |violation|
          story_card = violation.story_card
          link = "https://www.pivotaltracker.com/story/show/#{story_card.id}"
          if print_message
            violation_section << "                #{story_card.name} - #{link} - #{violation.message}\n"
          else
            violation_section << "                #{story_card.name} - #{link}\n"
          end
        end
      end
      violation_section
    end
  end
end


text:
**Asynchronous promises in rust using threads**

|Crate|Travis|
|:------:|:-------:|
|[![](http://meritbadge.herokuapp.com/asynchronous)](https://crates.io/crates/asynchronous)|[![Build Status](https://travis-ci.org/bcndanos/asynchronous.svg?branch=master)](https://travis-ci.org/bcndanos/asynchronous)|

| [API Documentation](http://bcndanos.github.io/asynchronous/asynchronous/) |

#Overview

This library provides an usefull way to invoke functions (clousures) in a **Promise Style** using separated threads. A Promise
is a Struct that represents the return value or the error that the funcion produces.

It also allows the execution of tasks in Parallel or Series in deferred, joining the result in a Promise.

It includes methods to manage Event Loops, where there are tasks that "emit" events in background, and they are collected by a promise.

[Project github page](https://github.com/bcndanos/asynchronous)

This project is based on the [Q Promise](https://github.com/kriskowal/q) library for Node JS and [Async.js](https://github.com/caolan/async)

#License

Dual-licensed to be compatible with the Rust project.

Licensed under the Apache License, Version 2.0
http://www.apache.org/licenses/LICENSE-2.0 or the MIT license
http://opensource.org/licenses/MIT, at your
option. This file may not be copied, modified, or distributed
except according to those terms.

# Examples

This is a simple setup for a promise based execution:

```rust
use asynchronous::Promise;

Promise::new(|| {
  // Do something
  let ret = 10.0 / 3.0;
  if ret > 0.0 { Ok(ret) } else { Err("Incorrect Value") }
}).success(|res| {            // res has type f64
  // Do something if the previous result is correct
  assert_eq!(res, 10.0 / 3.0);
  let res_int = res as u32 * 2;
  Ok(res_int)
}).finally_sync(|res| {       // res has type Result<u32,&str>
  // Executed always at the end
  assert_eq!(res.unwrap(), 6u32);
});
```

Deferred execution:

```rust
use asynchronous::{Promise,Deferred,ControlFlow};

let d_a = Deferred::<&str, &str>::new(|| { Ok("a") });
let p_b = Promise::<&str, &str>::new(|| { Ok("b") });  // Executed right now
let d1 = Deferred::<u32, &str>::new(|| { Ok(1u32) });
let d2 = Deferred::<u32, &str>::new(|| { Err("Mock Error") });
let d3 = Deferred::<u32, &str>::new(|| { Ok(3u32) });
let d4 = Deferred::<u32, &str>::new(|| { Ok(4u32) });
let d5 = Deferred::<u32, &str>::new(|| { Ok(5u32) });

let promise = Deferred::vec_to_promise(vec![d1,d2,d3], ControlFlow::Parallel);
// Only d1, d2 and d3 are being executed at this time.

assert_eq!("ab", d_a.to_promise().success(|res_a| {
    p_b.success(move |res_b| {
        Ok(res_a.to_string() + res_b)
    }).sync()
}).sync().unwrap());

promise.success(|res| {
    // Catch the result. In this case, tasks d4 and d5 never will be executed
    Ok(res)
}).fail(|error| {
    // Catch the error and execute another Promise
    assert_eq!(error, vec![Ok(1u32), Err("Mock Error"), Ok(3u32)]);
    Deferred::vec_to_promise(vec![d4,d5], ControlFlow::Series).sync()
}).finally_sync(|res| {   // res : Result<Vec<u32>,&str>
    // Do something here
    assert_eq!(res.unwrap(), vec![4u32, 5u32]);
});

```

Simple event loop:

```rust
use asynchronous::EventLoop;

let el = EventLoop::new().finish_in_ms(100);
el.emit("Event1");
el.emit("Event2");
// Do something here
el.to_promise().finally_sync(|res| {  // res: Result<Vec<Ev>,()>
    assert_eq!(res.unwrap(), vec!["Event1", "Event2"]);
});
```


text:
package com.coolweather.app;

import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.view.Menu;

public class MainActivity extends ActionBarActivity {

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		getMenuInflater().inflate(R.menu.main, menu);
		return true;
	}

}


text:
/**
 * Lets developers connect their apps to a server-side API securely with OAuth.
 */
package io.pivotal.greenhouse.develop;


text:
module JsonApiController
  module UpdatableResource
    extend ActiveSupport::Concern
    include RelationManager
    include PreconditionCheck

    included do
      before_action only: :update do |controller|
        controller.precondition_check
      end
    end

    def update
      controlled_resources.zip(Array.wrap(update_params)).each do |resource, update_hash|
        resource.assign_attributes(build_update_hash(update_hash,resource))
      end

      resource_class.transaction(requires_new: true) do
        controlled_resources.each do |resource|
          yield resource if block_given?
          resource.save!
        end
      end

      updated_resource_response
    end

    def update_links
      check_relation
      resource = controlled_resources.first
      resource_class.transaction(requires_new: true) do
        add_relation(resource, relation, params[relation])
        resource.save!
      end

      yield resource if block_given?

      updated_resource_response
    end

    def destroy_links
      resource = controlled_resources.first
      resource_class.transaction do
        destroy_relation(resource, relation, params[:link_ids])
      end

      yield resource if block_given?

      deleted_resource_response
    end

    protected

    def build_update_hash(update_params, resource)
      return update_params unless links = update_params.delete(:links)
      links.try(:reduce, update_params) do |params, (k, v)|
        params[k] = update_relation(resource, k.to_sym, v)
        params
      end
    end

    def check_relation
      if params[relation].nil?
        raise BadLinkParams.new("Link relation #{relation} must match body key")
      end
    end

    def update_response
      serializer.resource({}, controlled_resources, context)
    end

    def relation
      params[:link_relation].to_sym
    end
  end
end


text:
package com.github.semres.babelnet;

import com.github.semres.Edge;
import com.github.semres.Synset;

import java.time.LocalDateTime;
import java.util.*;

public class BabelNetSynset extends Synset {
    private Set<String> removedRelations = new HashSet<>();
    boolean downloadedWithEdges;

    public BabelNetSynset(BabelNetSynset babelNetSynset) {
        super(babelNetSynset);
        this.downloadedWithEdges = babelNetSynset.downloadedWithEdges;
        this.removedRelations = new HashSet<>(babelNetSynset.removedRelations);
    }

    public BabelNetSynset(String representation, String id) {
        super(representation, id);
    }

    public BabelNetSynset(String representation, String id, String description) {
        super(representation, id, description);
    }

    private BabelNetSynset(String representation, String id, String description, Set<String> removedRelations) {
        super(representation, id, description);
        this.removedRelations = removedRelations;
    }

    private BabelNetSynset(String representation, String id, String description, Set<String> removedRelations, boolean isDownloadedWithEdges) {
        this(representation, id, description, removedRelations);
        this.downloadedWithEdges = isDownloadedWithEdges;
    }

    public BabelNetSynset(String representation, String id, String description, boolean isDownloadedWithEdges) {
        this(representation, id, description);
        this.downloadedWithEdges = isDownloadedWithEdges;
    }

    public BabelNetSynset(String representation, String id, boolean isDownloadedWithEdges) {
        this(representation, id);
        this.downloadedWithEdges = isDownloadedWithEdges;
    }

    public BabelNetSynset(String representation, String id, String description, Set<String> removedRelations, boolean edgesLoaded, LocalDateTime lastEditedTime) {
        this(representation, id, description, removedRelations, edgesLoaded);
        this.lastEditedTime = lastEditedTime;
    }

    public Set<String> getRemovedRelations() {
        return removedRelations;
    }

    @Override
    public BabelNetSynset removeOutgoingEdge(String id) {
        BabelNetSynset newSynset = new BabelNetSynset(this);
        if (outgoingEdges.get(id) instanceof BabelNetEdge) {
            newSynset.removedRelations.add(outgoingEdges.get(id).getPointedSynsetId());
        } else {
            throw new RuntimeException("No edge with specified ID to remove.");
        }
        newSynset.outgoingEdges.remove(id);
        return newSynset;
    }

    @Override
    public BabelNetSynset addOutgoingEdge(Edge edge) {
        if (edge instanceof BabelNetEdge && removedRelations.contains(edge.getPointedSynsetId())) {
            throw new RuntimeException("Trying to add removed relation.");
        }
        BabelNetSynset newSynset = new BabelNetSynset(this);
        newSynset.outgoingEdges.put(edge.getId(), edge);
        return newSynset;
    }

    public boolean isDownloadedWithEdges() {
        return downloadedWithEdges;
    }

    @Override
    public BabelNetSynset changeOutgoingEdge(Edge edge) {
        if (!outgoingEdges.containsKey(edge.getId())) {
            throw new RuntimeException("No edge with specified ID.");
        }

        BabelNetSynset newSynset = new BabelNetSynset(this);
        newSynset.outgoingEdges.put(edge.getId(), edge);
        return newSynset;
    }

    @Override
    protected void setOutgoingEdges(Map<String, Edge> newEdges) {
        super.setOutgoingEdges(newEdges);
    }
}


text:
#include "input.h"

#include "../3rdparty/SDL2/include/SDL_keyboard.h"
#include "../3rdparty/SDL2/include/SDL.h"

SDL_Event event;

ar_Value* ar_event_quit(ar_State* S, ar_Value* args, ar_Value* env)
{
	if (event.type == SDL_QUIT)
		return S->t;
	return NULL;
}

ar_Value* ar_keyboard_update(ar_State* S, ar_Value* args, ar_Value* env)
{
	SDL_PollEvent(&event);
	return NULL;
}

ar_Value* ar_keyboard_keypressed(ar_State* S, ar_Value* args, ar_Value* env)
{
	if (event.type == SDL_KEYDOWN)
		return ar_new_number(S, event.key.keysym.sym);
	return NULL;
}

ar_Value* ar_keyboard_keyreleased(ar_State* S, ar_Value* args, ar_Value* env)
{
	if (event.type == SDL_KEYUP)
		return ar_new_number(S, event.key.keysym.sym);
	return NULL;
}

ar_Value* ar_mouse_mousepressed(ar_State* S, ar_Value* args, ar_Value* env)
{
	if (event.type == SDL_MOUSEBUTTONDOWN)
	{
		return ar_new_list(S, 3, ar_new_number(S, event.button.x),
				ar_new_number(S, event.button.y),
				ar_new_number(S, event.button.button));
	}
	return NULL;
}

ar_Value* ar_mouse_mousereleased(ar_State* S, ar_Value* args, ar_Value* env)
{
	if (event.type == SDL_MOUSEBUTTONUP)
	{
		return ar_new_list(S, 3, ar_new_number(S, event.button.x),
				ar_new_number(S, event.button.y),
				ar_new_number(S, event.button.button));
	}
	return NULL;
}

ar_Value* ar_mouse_mousewheel(ar_State* S, ar_Value* args, ar_Value* env)
{
	if (event.type == SDL_MOUSEBUTTONUP)
	{
		int _what = event.wheel.y == 1 ? SDL_BUTTON_WHEEL_UP : SDL_BUTTON_WHEEL_DOWN;
		return ar_new_number(S, _what);
	}
	return NULL;
}

ar_Value* ar_mouse_mousemoved(ar_State* S, ar_Value* args, ar_Value* env)
{
	if (event.type == SDL_MOUSEMOTION)
		return ar_new_pair(S, ar_new_number(S, event.motion.x),
				ar_new_number(S, event.motion.y));
	return NULL;
}

void ar_input_register(ar_State* S)
{
	struct { const char* name; ar_Prim fn; } prims[] =
	{
		{"love:event-quit",      ar_event_quit},
		{"love:keyboard-update", ar_keyboard_update},

		{"love:mouse-pressed", ar_mouse_mousepressed},
		{"love:mouse-released", ar_mouse_mousereleased},
		{"love:mouse-wheel", ar_mouse_mousewheel},
		{"love:mouse-moved", ar_mouse_mousemoved},

		{"love:keyboard-keypressed", ar_keyboard_keypressed},
		{"love:keyboard-keyreleased", ar_keyboard_keyreleased},
		{NULL, NULL}
	};
	for (int i = 0; prims[i].name; i++)
		ar_bind_global(S, prims[i].name, ar_new_prim(S, prims[i].fn));
}


text:
package org.juniversal.buildtools.gradle.support;

import org.gradle.api.Project;
import org.gradle.api.tasks.JavaExec;
import org.juniversal.buildtools.common.support.CommonJavaExec;

import java.io.File;

/**
 * Created by Bret Johnson on 11/11/2014.
 */
public class GradleJavaExec extends CommonJavaExec {
    private JavaExec javaExec;

    public GradleJavaExec(Project project, String name, File executableJar) {
        javaExec = project.getTasks().create(name, JavaExec.class);

        javaExec.setWorkingDir(project.getProjectDir());

        // Because JavaExec doesn't have proper support for exec'ing runnable jars, use this hack,
        // saying the main class is "-jar", to make it work
        javaExec.setMain("-jar");
        javaExec.args(executableJar.getAbsolutePath());
    }

    @Override public void addArg(String... args) {
        for (String arg : args) {
            javaExec.args(arg);
        }
    }

    @Override public String getCommandLine() {
        return javaExec.getCommandLine().toString();
    }

    @Override public void exec() {
        javaExec.exec();
    }
}


text:
using HarmonyLib;
using LmpClient.Systems.Warp;
using LmpCommon.Enums;

// ReSharper disable All

namespace LmpClient.Harmony
{
    /// <summary>
    /// This harmony patch is intended to deny the warping if needed. Adds another layer of security
    /// </summary>
    [HarmonyPatch(typeof(TimeWarp))]
    [HarmonyPatch("setMode")]
    public class TimeWarp_setMode
    {
        [HarmonyPrefix]
        private static bool PrefixSetMode()
        {
            if (MainSystem.NetworkState < ClientState.Connected) return true;

            return WarpSystem.Singleton.WarpValidation();
        }
    }
}


text:
package com.namelessdev.mpdroid;

import com.namelessdev.mpdroid.tools.Tools;

import android.os.Bundle;
import android.support.v4.app.FragmentActivity;

public class AlbumsActivity extends FragmentActivity {

	@Override
	protected void onCreate(Bundle arg0) {
		if (!Tools.isTabletMode(this)) {
			setTheme(android.R.style.Theme_Black_NoTitleBar);
		}
		super.onCreate(arg0);
		setContentView(R.layout.albums_activity);
	}
}


text:
<?php

namespace StackGuru\Commands\Drug;

use StackGuru\Core\Command\AbstractCommand;
use StackGuru\Core\Command\CommandContext;
use StackGuru\Core\Utils\Response as Response;
use React\Promise\Promise as Promise;
use React\Promise\Deferred as Deferred;

class Info extends AbstractCommand
{
    protected static $name = "info";
    protected static $description = "something about the info command";

    const QUERY_URLS = ["https://www.ncbi.nlm.nih.gov/pubmed/?term="];

    // Temporary data while i have no database
    // Schema
    //  id: string or int
    //  trivialName: string
    //  dose: string (ALWAYS milligram (mg))
    //  duration: string
    //  effects: string[]
    //  bioavailability: string
    //  alias: string[]
    //  resources: string[]
    private $datas = [
        [
            "id" => 14389,
            "name" => "modafinil",
            "dose" => "100", //mg
            "duration" => "9t - 15t", // t m s must be specified
            "effects" => [],
            "bioavailability" => "75% - 80%",
            "alias" => ["provigil", "modafinil", "nzt-48 precursor"],
            "resources" => ["https://examine.com/supplements/modafinil/", "https://psychonautwiki.org/wiki/Modafinil"]
        ]
    ];

    /**
     * Retrieves information about a known drug.
     *
     * @param  string $query Message input from the user after the commands have been stripped off.
     * @param  ?CommandContext $ctx   Context class to access parent object, among others.
     *
     * @return string Response to be sent.
     */
    public function process(string $query, CommandContext $ctx): Promise
    {
        $args = explode(' ', $query);

        var_dump($args);

        $result = '';

        if (2 <= sizeof($args)) {
            $result .= $this->getProperty($args[0], $args[1]);

            if ('' === $result) {
                $args = [$args[0]]; // so that the next if picks it up and returns all the data.
            }
        }

        if (1 === sizeof($args)) {
            $results = $this->getDatasheet($args[0]);

            foreach ($results as $key => $value) {
                $result .= $key . ": " . $this->parseValue($key, $value) . PHP_EOL;
            }
        }

        // in cae result is empty
        if (empty($result) || 1 >= strlen($result)) {
            $result = "Not found!";
        }
        else {
            $result = PHP_EOL . strtoupper($args[0]) . PHP_EOL . $result;
        }

        return Response::sendMessage($result, $ctx->message);
    }

    private function getProperty(string $drugname, string $category, array $drugData = null): mixed // :int, :string, :array.....
    {
        // set drug record
        $drug = [];
        if (null === $drugData) {
            $drug = $this->getDatasheet($drugname);
        }
        else {
            $drug = $drugData;
            $drugData = null; //clear memory
        }

        // validate it....
        if (empty($drug)) {
            return ''; // nothing
        }

        // check if category exists
        $category = strtolower(trim($category));
        if (!isset($drug[$category])) {
            return ''; // nothing
        }

        // Drug and category exists
        return $category .": " . $this->parseValue($category, $drug[$category]);
    }

    private function getDatasheet(string $drugname): array
    {
        $drug = [];

        if (null !== $drugname) {
            // check if drug exists in record
            foreach ($this->datas as $data) {
                if (in_array($drugname, $data["alias"])) {
                    $drug = $data;
                    break;
                }
            }
        }

        return $drug;
    }

    private function parseValue(string $key, $value): string
    {
        if (is_array($value)) {
            $value = implode(", ", $value);
        }

        if ("dose" === $key) {
            $value .= "mg";
        }

        return $value;
    }
}


text:
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.Entity;
using System.Data.Entity.Infrastructure;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;
using System.Web.Http.ModelBinding;
using System.Web.Http.OData;
using System.Web.Http.OData.Routing;
using BookingApp.Models;

namespace BookingApp.Controllers.OData
{
    /*
    The WebApiConfig class may require additional changes to add a route for this controller. Merge these statements into the Register method of the WebApiConfig class as applicable. Note that OData URLs are case sensitive.

    using System.Web.Http.OData.Builder;
    using System.Web.Http.OData.Extensions;
    using BookingApp.Models;
    ODataConventionModelBuilder builder = new ODataConventionModelBuilder();
    builder.EntitySet<AppUser>("AppUsers");
    config.Routes.MapODataServiceRoute("odata", "odata", builder.GetEdmModel());
    */
    public class OAppUsersController : ODataController
    {
        private BAContext db = new BAContext();

        // GET: odata/AppUsers
        [EnableQuery]
        public IQueryable<AppUser> GetAppUsers()
        {
            return db.AppUsers;
        }

        // GET: odata/AppUsers(5)
        [EnableQuery]
        public SingleResult<AppUser> GetAppUser([FromODataUri] int key)
        {
            return SingleResult.Create(db.AppUsers.Where(appUser => appUser.Id == key));
        }

        // PUT: odata/AppUsers(5)
        public IHttpActionResult Put([FromODataUri] int key, Delta<AppUser> patch)
        {
            Validate(patch.GetEntity());

            if (!ModelState.IsValid)
            {
                return BadRequest(ModelState);
            }

            AppUser appUser = db.AppUsers.Find(key);
            if (appUser == null)
            {
                return NotFound();
            }

            patch.Put(appUser);

            try
            {
                db.SaveChanges();
            }
            catch (DbUpdateConcurrencyException)
            {
                if (!AppUserExists(key))
                {
                    return NotFound();
                }
                else
                {
                    throw;
                }
            }

            return Updated(appUser);
        }

        // POST: odata/AppUsers
        public IHttpActionResult Post(AppUser appUser)
        {
            if (!ModelState.IsValid)
            {
                return BadRequest(ModelState);
            }

            db.AppUsers.Add(appUser);
            db.SaveChanges();

            return Created(appUser);
        }

        // PATCH: odata/AppUsers(5)
        [AcceptVerbs("PATCH", "MERGE")]
        public IHttpActionResult Patch([FromODataUri] int key, Delta<AppUser> patch)
        {
            Validate(patch.GetEntity());

            if (!ModelState.IsValid)
            {
                return BadRequest(ModelState);
            }

            AppUser appUser = db.AppUsers.Find(key);
            if (appUser == null)
            {
                return NotFound();
            }

            patch.Patch(appUser);

            try
            {
                db.SaveChanges();
            }
            catch (DbUpdateConcurrencyException)
            {
                if (!AppUserExists(key))
                {
                    return NotFound();
                }
                else
                {
                    throw;
                }
            }

            return Updated(appUser);
        }

        // DELETE: odata/AppUsers(5)
        public IHttpActionResult Delete([FromODataUri] int key)
        {
            AppUser appUser = db.AppUsers.Find(key);
            if (appUser == null)
            {
                return NotFound();
            }

            db.AppUsers.Remove(appUser);
            db.SaveChanges();

            return StatusCode(HttpStatusCode.NoContent);
        }

        protected override void Dispose(bool disposing)
        {
            if (disposing)
            {
                db.Dispose();
            }
            base.Dispose(disposing);
        }

        private bool AppUserExists(int key)
        {
            return db.AppUsers.Count(e => e.Id == key) > 0;
        }
    }
}


text:
ruby_version_is "1.9" do
  require File.expand_path("../versions/parameters_1.9", __FILE__)
end


text:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
    android:id="@+id/layout_splash"
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="@color/white"
    android:orientation="vertical">

    <ImageView
        android:layout_width="300dp"
        android:layout_height="300dp"
        android:layout_centerInParent="true"
        android:src="@mipmap/ic_erha"/>

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentBottom="true"
        android:layout_centerHorizontal="true"
        android:layout_marginBottom="20dp"
        android:gravity="center_horizontal"
        android:text="Something about Android \n Author: tiny"
        android:textColor="@color/font_main_1"/>

</RelativeLayout>


text:
<?php
namespace Everyman\Neo4j\Command\Batch;

use Everyman\Neo4j\Client,
	Everyman\Neo4j\Relationship,
	Everyman\Neo4j\Command\UpdateRelationship as SingleUpdateRelationship;

/**
 * Update a relationship in a batch
 */
class UpdateRelationship extends Command
{
	/**
	 * Set the operation to drive the command
	 *
	 * @param Client $client
	 * @param Relationship $rel
	 * @param integer $opId
	 */
	public function __construct(Client $client, Relationship $rel, $opId)
	{
		parent::__construct($client, new SingleUpdateRelationship($client, $rel), $opId);
	}

	/**
	 * Return the data to pass
	 *
	 * @return array
	 */
	protected function getData()
	{
		$opData = array(array(
			'method' => strtoupper($this->base->getMethod()),
			'to' => $this->base->getPath(),
			'body' => $this->base->getData(),
			'id' => $this->opId,
		));
		return $opData;
	}
}


text:
package com.capitalone.dashboard.gitlab;

import java.net.URI;
import java.util.ArrayList;
import java.util.List;

import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestOperations;

import com.capitalone.dashboard.gitlab.model.GitlabBoard;
import com.capitalone.dashboard.gitlab.model.GitlabIssue;
import com.capitalone.dashboard.gitlab.model.GitlabLabel;
import com.capitalone.dashboard.gitlab.model.GitlabList;
import com.capitalone.dashboard.gitlab.model.GitlabProject;
import com.capitalone.dashboard.gitlab.model.GitlabTeam;

@Component
public class DefaultGitlabClient implements GitlabClient {

	private static final String PAGINATION_HEADER = "X-Next-Page";

	private final RestOperations restOperations;
	private final GitlabUriUtility urlUtility;

	@Autowired
	public DefaultGitlabClient(RestOperations restOperations, GitlabUriUtility urlUtility) {
		this.restOperations = restOperations;
		this.urlUtility = urlUtility;
	}

	@Override
	public List<GitlabTeam> getTeams() {
		URI gitlabTeamUri = urlUtility.buildTeamsUri();
		return makePaginatedGitlabRequest(gitlabTeamUri, GitlabTeam[].class);
	}

	@Override
	public List<GitlabProject> getProjects() {
		URI uri = urlUtility.buildProjectsUri();
		return makePaginatedGitlabRequest(uri, GitlabProject[].class);
	}

    @Override
    public List<GitlabProject> getProjectsForTeam(String teamId) {
        URI uri = urlUtility.buildProjectsForTeamUri(teamId);
        return makePaginatedGitlabRequest(uri, GitlabProject[].class);
    }

    @Override
    public GitlabProject getProjectById(String projectId) {
        URI uri = urlUtility.buildProjectsByIdUri(projectId);
        HttpEntity<String> headersEntity = urlUtility.buildAuthenticationHeader();
        return restOperations.exchange(uri, HttpMethod.GET, headersEntity, GitlabProject.class).getBody();
    }

	@Override
	public List<GitlabLabel> getInProgressLabelsForProject(Long projectId) {
		List<GitlabLabel> labels = new ArrayList<>();
		List<GitlabBoard> boards = getBoardsForProject(String.valueOf(projectId));
		for (GitlabBoard board : boards) {
			 labels.addAll(getLabelsForInProgressIssues(board));
		}

		return labels;
	}

	@Override
	public List<GitlabIssue> getIssuesForProject(GitlabProject project) {
		URI uri = urlUtility.buildIssuesForProjectUri(String.valueOf(project.getId()));
		List<GitlabIssue> issues = makePaginatedGitlabRequest(uri, GitlabIssue[].class);
		for(GitlabIssue issue : issues) {
			issue.setProject(project);
		}
		return issues;
	}

	@SuppressWarnings({ "unchecked", "rawtypes" })
	private <T> List<T> makePaginatedGitlabRequest(URI uri, Class gitlabResponseType) {
		URI restUri = uri;
		HttpEntity<String> headersEntity = urlUtility.buildAuthenticationHeader();

		List<T> body =  new ArrayList<>();
		boolean hasNextPage = true;
		while (hasNextPage) {
			ResponseEntity<T[]> response = restOperations.exchange(restUri, HttpMethod.GET, headersEntity, gitlabResponseType);
			CollectionUtils.addAll(body, response.getBody());

			if(hasNextPage = hasNextPage(response.getHeaders())) {
				restUri = urlUtility.updatePage(restUri, response.getHeaders().get(PAGINATION_HEADER).get(0));
			}
		}

		return body;
	}

	private List<GitlabLabel> getLabelsForInProgressIssues(GitlabBoard board) {
		List<GitlabLabel> labels = new ArrayList<>();
		for (GitlabList list : board.getLists()) {
			labels.add(list.getLabel());
		}
		return labels;
	}

	private List<GitlabBoard> getBoardsForProject(String projectId) {
		URI gitlabBoardsUrl = urlUtility.buildBoardsUri(projectId);
		return makePaginatedGitlabRequest(gitlabBoardsUrl, GitlabBoard[].class);
	}

	private boolean hasNextPage(HttpHeaders headers) {
		if (null == headers || CollectionUtils.isEmpty(headers.get(PAGINATION_HEADER))) {
			return false;
		}
		String nextPage = headers.get(PAGINATION_HEADER).get(0);
		return StringUtils.isNotBlank(nextPage);
	}

}


text:
package ec2

import (
	"context"

	"github.com/aws/aws-sdk-go-v2/aws"
	"github.com/aws/aws-sdk-go-v2/internal/awsutil"
)

type UnassignIpv6AddressesInput struct {
	_ struct{} `type:"structure"`

	// The IPv6 addresses to unassign from the network interface.
	//
	// Ipv6Addresses is a required field
	Ipv6Addresses []string `locationName:"ipv6Addresses" locationNameList:"item" type:"list" required:"true"`

	// The ID of the network interface.
	//
	// NetworkInterfaceId is a required field
	NetworkInterfaceId *string `locationName:"networkInterfaceId" type:"string" required:"true"`
}

// String returns the string representation
func (s UnassignIpv6AddressesInput) String() string {
	return awsutil.Prettify(s)
}

// Validate inspects the fields of the type to determine if they are valid.
func (s *UnassignIpv6AddressesInput) Validate() error {
	invalidParams := aws.ErrInvalidParams{Context: "UnassignIpv6AddressesInput"}

	if s.Ipv6Addresses == nil {
		invalidParams.Add(aws.NewErrParamRequired("Ipv6Addresses"))
	}

	if s.NetworkInterfaceId == nil {
		invalidParams.Add(aws.NewErrParamRequired("NetworkInterfaceId"))
	}

	if invalidParams.Len() > 0 {
		return invalidParams
	}
	return nil
}

type UnassignIpv6AddressesOutput struct {
	_ struct{} `type:"structure"`

	// The ID of the network interface.
	NetworkInterfaceId *string `locationName:"networkInterfaceId" type:"string"`

	// The IPv6 addresses that have been unassigned from the network interface.
	UnassignedIpv6Addresses []string `locationName:"unassignedIpv6Addresses" locationNameList:"item" type:"list"`
}

// String returns the string representation
func (s UnassignIpv6AddressesOutput) String() string {
	return awsutil.Prettify(s)
}

const opUnassignIpv6Addresses = "UnassignIpv6Addresses"

// UnassignIpv6AddressesRequest returns a request value for making API operation for
// Amazon Elastic Compute Cloud.
//
// Unassigns one or more IPv6 addresses from a network interface.
//
//    // Example sending a request using UnassignIpv6AddressesRequest.
//    req := client.UnassignIpv6AddressesRequest(params)
//    resp, err := req.Send(context.TODO())
//    if err == nil {
//        fmt.Println(resp)
//    }
//
// Please also see https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/UnassignIpv6Addresses
func (c *Client) UnassignIpv6AddressesRequest(input *UnassignIpv6AddressesInput) UnassignIpv6AddressesRequest {
	op := &aws.Operation{
		Name:       opUnassignIpv6Addresses,
		HTTPMethod: "POST",
		HTTPPath:   "/",
	}

	if input == nil {
		input = &UnassignIpv6AddressesInput{}
	}

	req := c.newRequest(op, input, &UnassignIpv6AddressesOutput{})

	return UnassignIpv6AddressesRequest{Request: req, Input: input, Copy: c.UnassignIpv6AddressesRequest}
}

// UnassignIpv6AddressesRequest is the request type for the
// UnassignIpv6Addresses API operation.
type UnassignIpv6AddressesRequest struct {
	*aws.Request
	Input *UnassignIpv6AddressesInput
	Copy  func(*UnassignIpv6AddressesInput) UnassignIpv6AddressesRequest
}

// Send marshals and sends the UnassignIpv6Addresses API request.
func (r UnassignIpv6AddressesRequest) Send(ctx context.Context) (*UnassignIpv6AddressesResponse, error) {
	r.Request.SetContext(ctx)
	err := r.Request.Send()
	if err != nil {
		return nil, err
	}

	resp := &UnassignIpv6AddressesResponse{
		UnassignIpv6AddressesOutput: r.Request.Data.(*UnassignIpv6AddressesOutput),
		response:                    &aws.Response{Request: r.Request},
	}

	return resp, nil
}

// UnassignIpv6AddressesResponse is the response type for the
// UnassignIpv6Addresses API operation.
type UnassignIpv6AddressesResponse struct {
	*UnassignIpv6AddressesOutput

	response *aws.Response
}

// SDKResponseMetdata returns the response metadata for the
// UnassignIpv6Addresses request.
func (r *UnassignIpv6AddressesResponse) SDKResponseMetdata() *aws.Response {
	return r.response
}


text:
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
// Code generated by Microsoft (R) AutoRest Code Generator.

package com.azure.resourcemanager.network.implementation;

import com.azure.core.annotation.ExpectedResponses;
import com.azure.core.annotation.Get;
import com.azure.core.annotation.HeaderParam;
import com.azure.core.annotation.Headers;
import com.azure.core.annotation.Host;
import com.azure.core.annotation.HostParam;
import com.azure.core.annotation.PathParam;
import com.azure.core.annotation.QueryParam;
import com.azure.core.annotation.ReturnType;
import com.azure.core.annotation.ServiceInterface;
import com.azure.core.annotation.ServiceMethod;
import com.azure.core.annotation.UnexpectedResponseExceptionType;
import com.azure.core.http.rest.Response;
import com.azure.core.http.rest.RestProxy;
import com.azure.core.management.exception.ManagementException;
import com.azure.core.util.Context;
import com.azure.core.util.FluxUtil;
import com.azure.resourcemanager.network.fluent.ServiceAssociationLinksClient;
import com.azure.resourcemanager.network.fluent.models.ServiceAssociationLinksListResultInner;
import reactor.core.publisher.Mono;

/** An instance of this class provides access to all the operations defined in ServiceAssociationLinksClient. */
public final class ServiceAssociationLinksClientImpl implements ServiceAssociationLinksClient {
    /** The proxy service used to perform REST calls. */
    private final ServiceAssociationLinksService service;

    /** The service client containing this operation class. */
    private final NetworkManagementClientImpl client;

    /**
     * Initializes an instance of ServiceAssociationLinksClientImpl.
     *
     * @param client the instance of the service client containing this operation class.
     */
    ServiceAssociationLinksClientImpl(NetworkManagementClientImpl client) {
        this.service =
            RestProxy
                .create(ServiceAssociationLinksService.class, client.getHttpPipeline(), client.getSerializerAdapter());
        this.client = client;
    }

    /**
     * The interface defining all the services for NetworkManagementClientServiceAssociationLinks to be used by the
     * proxy service to perform REST calls.
     */
    @Host("{$host}")
    @ServiceInterface(name = "NetworkManagementCli")
    private interface ServiceAssociationLinksService {
        @Headers({"Content-Type: application/json"})
        @Get(
            "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network"
                + "/virtualNetworks/{virtualNetworkName}/subnets/{subnetName}/ServiceAssociationLinks")
        @ExpectedResponses({200})
        @UnexpectedResponseExceptionType(ManagementException.class)
        Mono<Response<ServiceAssociationLinksListResultInner>> list(
            @HostParam("$host") String endpoint,
            @PathParam("resourceGroupName") String resourceGroupName,
            @PathParam("virtualNetworkName") String virtualNetworkName,
            @PathParam("subnetName") String subnetName,
            @QueryParam("api-version") String apiVersion,
            @PathParam("subscriptionId") String subscriptionId,
            @HeaderParam("Accept") String accept,
            Context context);
    }

    /**
     * Gets a list of service association links for a subnet.
     *
     * @param resourceGroupName The name of the resource group.
     * @param virtualNetworkName The name of the virtual network.
     * @param subnetName The name of the subnet.
     * @throws IllegalArgumentException thrown if parameters fail the validation.
     * @throws ManagementException thrown if the request is rejected by server.
     * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent.
     * @return a list of service association links for a subnet along with {@link Response} on successful completion of
     *     {@link Mono}.
     */
    @ServiceMethod(returns = ReturnType.SINGLE)
    public Mono<Response<ServiceAssociationLinksListResultInner>> listWithResponseAsync(
        String resourceGroupName, String virtualNetworkName, String subnetName) {
        if (this.client.getEndpoint() == null) {
            return Mono
                .error(
                    new IllegalArgumentException(
                        "Parameter this.client.getEndpoint() is required and cannot be null."));
        }
        if (resourceGroupName == null) {
            return Mono
                .error(new IllegalArgumentException("Parameter resourceGroupName is required and cannot be null."));
        }
        if (virtualNetworkName == null) {
            return Mono
                .error(new IllegalArgumentException("Parameter virtualNetworkName is required and cannot be null."));
        }
        if (subnetName == null) {
            return Mono.error(new IllegalArgumentException("Parameter subnetName is required and cannot be null."));
        }
        if (this.client.getSubscriptionId() == null) {
            return Mono
                .error(
                    new IllegalArgumentException(
                        "Parameter this.client.getSubscriptionId() is required and cannot be null."));
        }
        final String apiVersion = "2022-05-01";
        final String accept = "application/json";
        return FluxUtil
            .withContext(
                context ->
                    service
                        .list(
                            this.client.getEndpoint(),
                            resourceGroupName,
                            virtualNetworkName,
                            subnetName,
                            apiVersion,
                            this.client.getSubscriptionId(),
                            accept,
                            context))
            .contextWrite(context -> context.putAll(FluxUtil.toReactorContext(this.client.getContext()).readOnly()));
    }

    /**
     * Gets a list of service association links for a subnet.
     *
     * @param resourceGroupName The name of the resource group.
     * @param virtualNetworkName The name of the virtual network.
     * @param subnetName The name of the subnet.
     * @param context The context to associate with this operation.
     * @throws IllegalArgumentException thrown if parameters fail the validation.
     * @throws ManagementException thrown if the request is rejected by server.
     * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent.
     * @return a list of service association links for a subnet along with {@link Response} on successful completion of
     *     {@link Mono}.
     */
    @ServiceMethod(returns = ReturnType.SINGLE)
    private Mono<Response<ServiceAssociationLinksListResultInner>> listWithResponseAsync(
        String resourceGroupName, String virtualNetworkName, String subnetName, Context context) {
        if (this.client.getEndpoint() == null) {
            return Mono
                .error(
                    new IllegalArgumentException(
                        "Parameter this.client.getEndpoint() is required and cannot be null."));
        }
        if (resourceGroupName == null) {
            return Mono
                .error(new IllegalArgumentException("Parameter resourceGroupName is required and cannot be null."));
        }
        if (virtualNetworkName == null) {
            return Mono
                .error(new IllegalArgumentException("Parameter virtualNetworkName is required and cannot be null."));
        }
        if (subnetName == null) {
            return Mono.error(new IllegalArgumentException("Parameter subnetName is required and cannot be null."));
        }
        if (this.client.getSubscriptionId() == null) {
            return Mono
                .error(
                    new IllegalArgumentException(
                        "Parameter this.client.getSubscriptionId() is required and cannot be null."));
        }
        final String apiVersion = "2022-05-01";
        final String accept = "application/json";
        context = this.client.mergeContext(context);
        return service
            .list(
                this.client.getEndpoint(),
                resourceGroupName,
                virtualNetworkName,
                subnetName,
                apiVersion,
                this.client.getSubscriptionId(),
                accept,
                context);
    }

    /**
     * Gets a list of service association links for a subnet.
     *
     * @param resourceGroupName The name of the resource group.
     * @param virtualNetworkName The name of the virtual network.
     * @param subnetName The name of the subnet.
     * @throws IllegalArgumentException thrown if parameters fail the validation.
     * @throws ManagementException thrown if the request is rejected by server.
     * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent.
     * @return a list of service association links for a subnet on successful completion of {@link Mono}.
     */
    @ServiceMethod(returns = ReturnType.SINGLE)
    public Mono<ServiceAssociationLinksListResultInner> listAsync(
        String resourceGroupName, String virtualNetworkName, String subnetName) {
        return listWithResponseAsync(resourceGroupName, virtualNetworkName, subnetName)
            .flatMap(res -> Mono.justOrEmpty(res.getValue()));
    }

    /**
     * Gets a list of service association links for a subnet.
     *
     * @param resourceGroupName The name of the resource group.
     * @param virtualNetworkName The name of the virtual network.
     * @param subnetName The name of the subnet.
     * @param context The context to associate with this operation.
     * @throws IllegalArgumentException thrown if parameters fail the validation.
     * @throws ManagementException thrown if the request is rejected by server.
     * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent.
     * @return a list of service association links for a subnet along with {@link Response}.
     */
    @ServiceMethod(returns = ReturnType.SINGLE)
    public Response<ServiceAssociationLinksListResultInner> listWithResponse(
        String resourceGroupName, String virtualNetworkName, String subnetName, Context context) {
        return listWithResponseAsync(resourceGroupName, virtualNetworkName, subnetName, context).block();
    }

    /**
     * Gets a list of service association links for a subnet.
     *
     * @param resourceGroupName The name of the resource group.
     * @param virtualNetworkName The name of the virtual network.
     * @param subnetName The name of the subnet.
     * @throws IllegalArgumentException thrown if parameters fail the validation.
     * @throws ManagementException thrown if the request is rejected by server.
     * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent.
     * @return a list of service association links for a subnet.
     */
    @ServiceMethod(returns = ReturnType.SINGLE)
    public ServiceAssociationLinksListResultInner list(
        String resourceGroupName, String virtualNetworkName, String subnetName) {
        return listWithResponse(resourceGroupName, virtualNetworkName, subnetName, Context.NONE).getValue();
    }
}


text:
package android.keystore.cts;

import android.security.KeyChain;
import junit.framework.TestCase;

public class KeyChainTest extends TestCase {
    public void testIsKeyAlgorithmSupported_RequiredAlgorithmsSupported() throws Exception {
        assertTrue("DSA must be supported", KeyChain.isKeyAlgorithmSupported("DSA"));
        assertTrue("EC must be supported", KeyChain.isKeyAlgorithmSupported("EC"));
        assertTrue("RSA must be supported", KeyChain.isKeyAlgorithmSupported("RSA"));
    }

    /**
     * Tests whether the required algorithms are backed by a Keymaster HAL that
     * binds the key material to the specific device it was created or imported
     * to. For more information on the Keymaster HAL, look at the header file at
     * hardware/libhardware/include/hardware/keymaster.h and the associated
     * tests in hardware/libhardware/tests/keymaster/
     */
    public void testIsBoundKeyAlgorithm_RequiredAlgorithmsSupported() throws Exception {
        assertTrue("RSA must be hardware-backed by a hardware-specific Keymaster HAL",
                KeyChain.isBoundKeyAlgorithm("RSA"));

        // These are not required, but must not throw an exception
        KeyChain.isBoundKeyAlgorithm("DSA");
        KeyChain.isBoundKeyAlgorithm("EC");
    }
}


text:
package com.github.scalaz_examples.magic

object CreatingEquals extends App {
  // as you see in the equal package, the equal typeclass can be very useful to make sure that
  // equality checks are type-safe.  But how could you implement this without scalaz?

  // simple Equal interface to define the equal behavior
  trait Equal[A] {
    def equal(a1: A, a2: A): Boolean
  }
  // thats cool and all, but isn't this just Comparator in java?  How will this come together to give me ===?

  // so how do we decorate (pimp) other objects to get this behavior?  With scala implicits, you can define a function
  // that takes a A and creates a Opt[A] that has new methods.
  trait InstanceOpt[A] {
    def self: A
    def ===(a2: A)(implicit eq: Equal[A]): Boolean = eq.equal(self, a2)
    def =/=(a2: A)(implicit eq: Equal[A]): Boolean = !eq.equal(self, a2)
    def println(prefix: String = ""): Unit = Predef.println(s"${prefix}${self}") // too lazy to include show
  }
  import scala.language.implicitConversions
  implicit def toInstance[A](a: A): InstanceOpt[A] = new InstanceOpt[A] {def self: A = a}
  // an implication with Int
  implicit val intEqual: Equal[Int] = new Equal[Int] {
    override def equal(a1: Int, a2: Int): Boolean = a1 == a2
  }

  // now we can use === with int
  (1 =/= 3).println("1 =/= 3: ")
  (3 === 3).println("3 === 3: ")

  // but int === string won't compile
//  1 === "1"
// type mismatch;
//  found   : String("1")
//  required: Int
//  1 === "1"
//     ^

  // This is slightly different than how scalaz implemented equals, but its a very simple one that lets you
  // override the Equal used without defining different implicits.  The spirit of the implementation is the same.

  // This lets you define new behaviors without using inheritance, but can you still use the object like it was?
//  def selfEquals[A](eq: Equal[A]) = eq.equal(eq, eq)
//  selfEquals(1)
//  type mismatch;
//  found   : Int(1)
//  required: com.github.scalaz_examples.typeclasses.CreatingEquals.Equal[?]
//  selfEquals(1)
//         ^

  // this should make sense since A is not of type Equal[A].  We can get what we want using the same trick InstanceOpt does
  def selfEquals[A](a: A)(implicit eq: Equal[A]): Boolean = eq.equal(a, a)
  selfEquals(1) println("selfEquals(1): ")
}


text:
FactoryGirl.define do
  factory :worldwide_office_staff_role do
    name "Defence Attaché"
  end
end


text:
A small clojure app to simulate periodically wiggling the mouse to prevent idleness in online games and such.

## Installation

Download from the [github repo][].

[github repo]: http://github.com/psquid/idle-robot

## Usage

For the moment, running idle-robot in a terminal window is _highly_ recommended, as there is presently no way to terminate it other than forcibly halting the process.

To run the app, build the jar with either

    $ lein jar

or

    $ lein uberjar

then run the resulting jar (produced in the `target` directory) in java with:

    $ java -jar idle-robot-0.1.0[-standalone].jar

Alternatively, get the latest standalone snapshot jar from the repo's [downloads][] page, and then use the last command from above, substituting in the name of the file you just downloaded (this option avoids the need to install clojure or leiningen, since everything needed is bundled).

[downloads]: http://github.com/psquid/idle-robot/downloads

## License

Copyright © 2012 Psychedelic Squid

Distributed under the Simplified BSD License. See LICENSE for the full license text.


text:
<?php

namespace Jjanvier\Bundle\CrowdinBundle\Command\Api;

use Crowdin\Api\UpdateFile;
use Symfony\Component\Console\Input\InputArgument;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Input\InputOption;
use Symfony\Component\Console\Output\OutputInterface;

class FileUpdateCommand extends AbstractApiCommand
{
    protected function configure()
    {
        $this
            ->setName('crowdin:api:update-file')
            ->setDescription('Update a file in the Crowdin project.')
            ->addArgument('file', InputArgument::REQUIRED, 'File you want to update.')
            ->addArgument('crowdinPath', InputArgument::REQUIRED, 'Crowdin path for file you want to update.')
            ->addOption('exportPattern', 'p', InputOption::VALUE_REQUIRED, 'Export pattern of your file.')
            ->addOption('title', 't', InputOption::VALUE_REQUIRED, 'Title of your file.')
        ;
    }

    protected function execute(InputInterface $input, OutputInterface $output)
    {
        /** @var UpdateFile $updateFile */
        $updateFile = $this->getClient()->api('update-file');
        $updateFile->addTranslation(
            $input->getArgument('file'),
            $input->getArgument('file'),
            $input->getOption('exportPattern'),
            $input->getOption('title')
        );

        $output->writeln($updateFile->execute());
    }
}


text:
require 'grpc'

Thread.abort_on_exception = true

def wakey_thread(&blk)
  n = GRPC::Notifier.new
  t = Thread.new do
    blk.call(n)
  end
  t.abort_on_exception = true
  n.wait
  t
end

def load_test_certs
  test_root = File.join(File.dirname(File.dirname(__FILE__)), 'testdata')
  files = ['ca.pem', 'server1.key', 'server1.pem']
  files.map { |f| File.open(File.join(test_root, f)).read }
end

include GRPC::Core::StatusCodes
include GRPC::Core::TimeConsts
include GRPC::Core::CallOps

describe 'ClientStub' do
  let(:noop) { proc { |x| x } }

  before(:each) do
    Thread.abort_on_exception = true
    @server = nil
    @method = 'an_rpc_method'
    @pass = OK
    @fail = INTERNAL
  end

  after(:each) do
    @server.close(from_relative_time(2)) unless @server.nil?
  end

  describe '#new' do
    let(:fake_host) { 'localhost:0' }
    it 'can be created from a host and args' do
      opts = { channel_args: { a_channel_arg: 'an_arg' } }
      blk = proc do
        GRPC::ClientStub.new(fake_host, :this_channel_is_insecure, **opts)
      end
      expect(&blk).not_to raise_error
    end

    it 'can be created with an channel override' do
      opts = {
        channel_args: { a_channel_arg: 'an_arg' },
        channel_override: @ch
      }
      blk = proc do
        GRPC::ClientStub.new(fake_host, :this_channel_is_insecure, **opts)
      end
      expect(&blk).not_to raise_error
    end

    it 'cannot be created with a bad channel override' do
      blk = proc do
        opts = {
          channel_args: { a_channel_arg: 'an_arg' },
          channel_override: Object.new
        }
        GRPC::ClientStub.new(fake_host, :this_channel_is_insecure, **opts)
      end
      expect(&blk).to raise_error
    end

    it 'cannot be created with bad credentials' do
      blk = proc do
        opts = { channel_args: { a_channel_arg: 'an_arg' } }
        GRPC::ClientStub.new(fake_host, Object.new, **opts)
      end
      expect(&blk).to raise_error
    end

    it 'can be created with test test credentials' do
      certs = load_test_certs
      blk = proc do
        opts = {
          channel_args: {
            GRPC::Core::Channel::SSL_TARGET => 'foo.test.google.fr',
            a_channel_arg: 'an_arg'
          }
        }
        creds = GRPC::Core::ChannelCredentials.new(certs[0], nil, nil)
        GRPC::ClientStub.new(fake_host, creds,  **opts)
      end
      expect(&blk).to_not raise_error
    end
  end

  describe '#request_response' do
    before(:each) do
      @sent_msg, @resp = 'a_msg', 'a_reply'
    end

    shared_examples 'request response' do
      it 'should send a request to/receive a reply from a server' do
        server_port = create_test_server
        th = run_request_response(@sent_msg, @resp, @pass)
        stub = GRPC::ClientStub.new("localhost:#{server_port}",
                                    :this_channel_is_insecure)
        expect(get_response(stub)).to eq(@resp)
        th.join
      end

      it 'should send metadata to the server ok' do
        server_port = create_test_server
        host = "localhost:#{server_port}"
        th = run_request_response(@sent_msg, @resp, @pass,
                                  k1: 'v1', k2: 'v2')
        stub = GRPC::ClientStub.new(host, :this_channel_is_insecure)
        expect(get_response(stub)).to eq(@resp)
        th.join
      end

      it 'should send a request when configured using an override channel' do
        server_port = create_test_server
        alt_host = "localhost:#{server_port}"
        th = run_request_response(@sent_msg, @resp, @pass)
        ch = GRPC::Core::Channel.new(alt_host, nil, :this_channel_is_insecure)
        stub = GRPC::ClientStub.new('ignored-host',
                                    :this_channel_is_insecure,
                                    channel_override: ch)
        expect(get_response(stub)).to eq(@resp)
        th.join
      end

      it 'should raise an error if the status is not OK' do
        server_port = create_test_server
        host = "localhost:#{server_port}"
        th = run_request_response(@sent_msg, @resp, @fail)
        stub = GRPC::ClientStub.new(host, :this_channel_is_insecure)
        blk = proc { get_response(stub) }
        expect(&blk).to raise_error(GRPC::BadStatus)
        th.join
      end
    end

    describe 'without a call operation' do
      def get_response(stub)
        stub.request_response(@method, @sent_msg, noop, noop,
                              metadata: { k1: 'v1', k2: 'v2' })
      end

      it_behaves_like 'request response'
    end

    describe 'via a call operation' do
      def get_response(stub)
        op = stub.request_response(@method, @sent_msg, noop, noop,
                                   return_op: true,
                                   metadata: { k1: 'v1', k2: 'v2' },
                                   deadline: from_relative_time(2))
        expect(op).to be_a(GRPC::ActiveCall::Operation)
        op.execute
      end

      it_behaves_like 'request response'
    end
  end

  describe '#client_streamer' do
    shared_examples 'client streaming' do
      before(:each) do
        server_port = create_test_server
        host = "localhost:#{server_port}"
        @stub = GRPC::ClientStub.new(host, :this_channel_is_insecure)
        @metadata = { k1: 'v1', k2: 'v2' }
        @sent_msgs = Array.new(3) { |i| 'msg_' + (i + 1).to_s }
        @resp = 'a_reply'
      end

      it 'should send requests to/receive a reply from a server' do
        th = run_client_streamer(@sent_msgs, @resp, @pass)
        expect(get_response(@stub)).to eq(@resp)
        th.join
      end

      it 'should send metadata to the server ok' do
        th = run_client_streamer(@sent_msgs, @resp, @pass, **@metadata)
        expect(get_response(@stub)).to eq(@resp)
        th.join
      end

      it 'should raise an error if the status is not ok' do
        th = run_client_streamer(@sent_msgs, @resp, @fail)
        blk = proc { get_response(@stub) }
        expect(&blk).to raise_error(GRPC::BadStatus)
        th.join
      end

      it 'should raise ArgumentError if metadata contains invalid values' do
        @metadata.merge!(k3: 3)
        expect do
          get_response(@stub)
        end.to raise_error(ArgumentError,
                           /Header values must be of type string or array/)
      end
    end

    describe 'without a call operation' do
      def get_response(stub)
        stub.client_streamer(@method, @sent_msgs, noop, noop,
                             metadata: @metadata)
      end

      it_behaves_like 'client streaming'
    end

    describe 'via a call operation' do
      def get_response(stub)
        op = stub.client_streamer(@method, @sent_msgs, noop, noop,
                                  return_op: true, metadata: @metadata)
        expect(op).to be_a(GRPC::ActiveCall::Operation)
        op.execute
      end

      it_behaves_like 'client streaming'
    end
  end

  describe '#server_streamer' do
    shared_examples 'server streaming' do
      before(:each) do
        @sent_msg = 'a_msg'
        @replys = Array.new(3) { |i| 'reply_' + (i + 1).to_s }
      end

      it 'should send a request to/receive replies from a server' do
        server_port = create_test_server
        host = "localhost:#{server_port}"
        th = run_server_streamer(@sent_msg, @replys, @pass)
        stub = GRPC::ClientStub.new(host, :this_channel_is_insecure)
        expect(get_responses(stub).collect { |r| r }).to eq(@replys)
        th.join
      end

      it 'should raise an error if the status is not ok' do
        server_port = create_test_server
        host = "localhost:#{server_port}"
        th = run_server_streamer(@sent_msg, @replys, @fail)
        stub = GRPC::ClientStub.new(host, :this_channel_is_insecure)
        e = get_responses(stub)
        expect { e.collect { |r| r } }.to raise_error(GRPC::BadStatus)
        th.join
      end

      it 'should send metadata to the server ok' do
        server_port = create_test_server
        host = "localhost:#{server_port}"
        th = run_server_streamer(@sent_msg, @replys, @fail,
                                 k1: 'v1', k2: 'v2')
        stub = GRPC::ClientStub.new(host, :this_channel_is_insecure)
        e = get_responses(stub)
        expect { e.collect { |r| r } }.to raise_error(GRPC::BadStatus)
        th.join
      end
    end

    describe 'without a call operation' do
      def get_responses(stub)
        e = stub.server_streamer(@method, @sent_msg, noop, noop,
                                 metadata: { k1: 'v1', k2: 'v2' })
        expect(e).to be_a(Enumerator)
        e
      end

      it_behaves_like 'server streaming'
    end

    describe 'via a call operation' do
      def get_responses(stub)
        op = stub.server_streamer(@method, @sent_msg, noop, noop,
                                  return_op: true,
                                  metadata: { k1: 'v1', k2: 'v2' })
        expect(op).to be_a(GRPC::ActiveCall::Operation)
        e = op.execute
        expect(e).to be_a(Enumerator)
        e
      end

      it_behaves_like 'server streaming'
    end
  end

  describe '#bidi_streamer' do
    shared_examples 'bidi streaming' do
      before(:each) do
        @sent_msgs = Array.new(3) { |i| 'msg_' + (i + 1).to_s }
        @replys = Array.new(3) { |i| 'reply_' + (i + 1).to_s }
        server_port = create_test_server
        @host = "localhost:#{server_port}"
      end

      it 'supports sending all the requests first', bidi: true do
        th = run_bidi_streamer_handle_inputs_first(@sent_msgs, @replys,
                                                   @pass)
        stub = GRPC::ClientStub.new(@host, :this_channel_is_insecure)
        e = get_responses(stub)
        expect(e.collect { |r| r }).to eq(@replys)
        th.join
      end

      it 'supports client-initiated ping pong', bidi: true do
        th = run_bidi_streamer_echo_ping_pong(@sent_msgs, @pass, true)
        stub = GRPC::ClientStub.new(@host, :this_channel_is_insecure)
        e = get_responses(stub)
        expect(e.collect { |r| r }).to eq(@sent_msgs)
        th.join
      end

      it 'supports a server-initiated ping pong', bidi: true do
        th = run_bidi_streamer_echo_ping_pong(@sent_msgs, @pass, false)
        stub = GRPC::ClientStub.new(@host, :this_channel_is_insecure)
        e = get_responses(stub)
        expect(e.collect { |r| r }).to eq(@sent_msgs)
        th.join
      end
    end

    describe 'without a call operation' do
      def get_responses(stub)
        e = stub.bidi_streamer(@method, @sent_msgs, noop, noop)
        expect(e).to be_a(Enumerator)
        e
      end

      it_behaves_like 'bidi streaming'
    end

    describe 'via a call operation' do
      def get_responses(stub)
        op = stub.bidi_streamer(@method, @sent_msgs, noop, noop,
                                return_op: true)
        expect(op).to be_a(GRPC::ActiveCall::Operation)
        e = op.execute
        expect(e).to be_a(Enumerator)
        e
      end

      it_behaves_like 'bidi streaming'
    end
  end

  def run_server_streamer(expected_input, replys, status, **kw)
    wanted_metadata = kw.clone
    wakey_thread do |notifier|
      c = expect_server_to_be_invoked(notifier)
      wanted_metadata.each do |k, v|
        expect(c.metadata[k.to_s]).to eq(v)
      end
      expect(c.remote_read).to eq(expected_input)
      replys.each { |r| c.remote_send(r) }
      c.send_status(status, status == @pass ? 'OK' : 'NOK', true)
    end
  end

  def run_bidi_streamer_handle_inputs_first(expected_inputs, replys,
                                            status)
    wakey_thread do |notifier|
      c = expect_server_to_be_invoked(notifier)
      expected_inputs.each { |i| expect(c.remote_read).to eq(i) }
      replys.each { |r| c.remote_send(r) }
      c.send_status(status, status == @pass ? 'OK' : 'NOK', true)
    end
  end

  def run_bidi_streamer_echo_ping_pong(expected_inputs, status, client_starts)
    wakey_thread do |notifier|
      c = expect_server_to_be_invoked(notifier)
      expected_inputs.each do |i|
        if client_starts
          expect(c.remote_read).to eq(i)
          c.remote_send(i)
        else
          c.remote_send(i)
          expect(c.remote_read).to eq(i)
        end
      end
      c.send_status(status, status == @pass ? 'OK' : 'NOK', true)
    end
  end

  def run_client_streamer(expected_inputs, resp, status, **kw)
    wanted_metadata = kw.clone
    wakey_thread do |notifier|
      c = expect_server_to_be_invoked(notifier)
      expected_inputs.each { |i| expect(c.remote_read).to eq(i) }
      wanted_metadata.each do |k, v|
        expect(c.metadata[k.to_s]).to eq(v)
      end
      c.remote_send(resp)
      c.send_status(status, status == @pass ? 'OK' : 'NOK', true)
    end
  end

  def run_request_response(expected_input, resp, status, **kw)
    wanted_metadata = kw.clone
    wakey_thread do |notifier|
      c = expect_server_to_be_invoked(notifier)
      expect(c.remote_read).to eq(expected_input)
      wanted_metadata.each do |k, v|
        expect(c.metadata[k.to_s]).to eq(v)
      end
      c.remote_send(resp)
      c.send_status(status, status == @pass ? 'OK' : 'NOK', true)
    end
  end

  def create_test_server
    @server = GRPC::Core::Server.new(nil)
    @server.add_http2_port('0.0.0.0:0', :this_port_is_insecure)
  end

  def expect_server_to_be_invoked(notifier)
    @server.start
    notifier.notify(nil)
    recvd_rpc = @server.request_call
    recvd_call = recvd_rpc.call
    recvd_call.metadata = recvd_rpc.metadata
    recvd_call.run_batch(SEND_INITIAL_METADATA => nil)
    GRPC::ActiveCall.new(recvd_call, noop, noop, INFINITE_FUTURE,
                         metadata_received: true)
  end
end


text:
package net.sweet.test.submit.reader;

import java.io.FileInputStream;
import java.io.InputStream;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

import net.sweet.test.base.ApplicationContextTest;

import com.gtm.cpims.business.datacollection.submit.base.BaseReportReader;
import com.gtm.cpims.dao.BsOrgDAO;
import com.gtm.cpims.model.BsOrg;

public class FinancialICCheckYrReaderTestCase extends
// AbstractDependencyInjectionSpringContextTests
        ApplicationContextTest {

    private BaseReportReader financialICCheckYRReader;
    private BsOrgDAO bsOrgDao;

    public void test_read() {
        try {
            InputStream is = new FileInputStream(TEST_TEMPOTORY_PATH
                    + "/FinancialICCheckYr.xls");
            Map<String, String> reportParam = new HashMap<String, String>();
            reportParam.put(BaseReportReader.PARAM_SUBMIT_NO, UUID.randomUUID()
                    .toString());
            BsOrg org = bsOrgDao.get("C1091251000018");// 重庆银行-C1093151000011,
                                                        // 浙江民泰银行-C1093051000010,
            reportParam.put(BaseReportReader.PARAM_BANKNO, org.getNo());
            reportParam.put(BaseReportReader.PARAM_BANKNAME, org.getName());
            reportParam.put(BaseReportReader.PARAM_BANKTYPE_NO, org
                    .getOrgtypeno());
            reportParam.put(BaseReportReader.PARAM_BANKTYPE_NAME, org
                    .getOrgtypename());
            reportParam.put(BaseReportReader.PARAM_DURING, "Y-2013");
            List<String> msgs = financialICCheckYRReader.read(is, reportParam);
            if (msgs != null) {
                for (int i = 0; i < msgs.size(); i++) {
                    System.out.println(msgs.get(i));
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public void setFinancialICCheckYRReader(
            BaseReportReader financialICCheckYRReader) {
        this.financialICCheckYRReader = financialICCheckYRReader;
    }

    public void setBsOrgDao(BsOrgDAO bsOrgDao) {
        this.bsOrgDao = bsOrgDao;
    }
}


text:
<?php

declare(strict_types=1);

namespace ListSorter;

class SortableItem
{
    private $key;
    private $tableAlias;
    private $column;
    private $title;
    private $isSelected;
    private $sortDir;
    private $isHidden;

    public function __construct($key, $column = '', $tableAlias = '')
    {
        $this->setKey($key);
        $this->setTableAlias($tableAlias);
        $this->setColumn($column);
    }

    /**
     * @return string
     */
    public function getKey()
    {
        return $this->key;
    }

    /**
     * @param $key
     *
     * @throws \Exception
     */
    public function setKey($key)
    {
        if (empty($key)) {
            throw new \Exception('Sortable item key can not be empty');
        }

        $this->key = $key;
    }

    /**
     * @return string
     */
    public function getTableAlias()
    {
        return $this->tableAlias;
    }

    /**
     * @param string $tableAlias
     */
    public function setTableAlias($tableAlias)
    {
        $this->tableAlias = $tableAlias;
    }

    /**
     * @return string
     */
    public function getColumn()
    {
        if (empty($this->column)) {
            // fall back option: replace the spaces with under line
            return strtolower(str_replace(' ', '_', $this->getKey()));
        }

        return $this->column;
    }

    /**
     * @param string $column
     */
    public function setColumn($column)
    {
        $this->column = $column;
    }

    /**
     * @return string
     */
    public function getTitle()
    {
        if (empty($this->title)) {
            // fall back option: replace under line with space
            return ucwords(str_replace('_', ' ', $this->getKey()));
        }

        return $this->title;
    }

    /**
     * @param string $title
     */
    public function setTitle($title)
    {
        $this->title = $title;
    }

    /**
     * @return bool
     */
    public function isSelected()
    {
        return empty($this->isSelected) ? false : true;
    }

    /**
     * @param bool $isSelected
     */
    public function setIsSelected($isSelected)
    {
        $this->isSelected = $isSelected;
    }

    /**
     * @return string
     */
    public function getSortDir()
    {
        return $this->sortDir;
    }

    /**
     * @param string $sortDir
     */
    public function setSortDir($sortDir)
    {
        if (in_array($sortDir, ['asc', 'desc'])) {
            $this->sortDir = $sortDir;
        }
    }

    /**
     * @return string
     */
    public function getNewSortDir()
    {
        return $this->getSortDir() === 'asc' ? 'desc' : 'asc';
    }

    /**
     * @return string
     */
    public function getSortBy()
    {
        $table = $this->getTableAlias();

        if (empty($table)) {
            return $this->getColumn();
        }

        return $table.'.'.$this->getColumn();
    }

    /**
     * @return bool
     */
    public function isHidden()
    {
        return $this->isHidden;
    }

    /**
     * @param bool $isHidden
     */
    public function setIsHidden($isHidden)
    {
        $this->isHidden = $isHidden;
    }
}


text:
#pragma once
#include <aws/comprehendmedical/ComprehendMedical_EXPORTS.h>
#include <aws/core/utils/memory/stl/AWSString.h>

namespace Aws
{
namespace ComprehendMedical
{
namespace Model
{
  enum class ICD10CMRelationshipType
  {
    NOT_SET,
    OVERLAP,
    SYSTEM_ORGAN_SITE
  };

namespace ICD10CMRelationshipTypeMapper
{
AWS_COMPREHENDMEDICAL_API ICD10CMRelationshipType GetICD10CMRelationshipTypeForName(const Aws::String& name);

AWS_COMPREHENDMEDICAL_API Aws::String GetNameForICD10CMRelationshipType(ICD10CMRelationshipType value);
} // namespace ICD10CMRelationshipTypeMapper
} // namespace Model
} // namespace ComprehendMedical
} // namespace Aws


text: Angular component for Facebook style gif


text:
		 {{::getCommonData('navbar').tasks.count}} Tasks to complete

						{{task.title}}
						{{task.percentage}}%

					<uib-progressbar ng-class="['progress-mini' , task['progress-class'] || '']" value="task.percentage" type="{{task['progress-bar-type']}}"></uib-progressbar>

			See tasks with details