text:
HelloWorldLKM
=============

A simple example of Linux Kernel Module

```
$ make
# insmod helloworld.ko
# rmmod helloworld.ko
```

You will see on dmesg something like:

```
[ 6519.343791] Hello world!
[ 6525.014934] Cleaning up module.
```

Interesting related topics:

* http://elinux.org/Deferred_Initcalls
* http://www.tldp.org/LDP/lkmpg/2.4/html/x354.html

redpajama_set_name: RedPajamaGithub


text:
package com.scottlogic.thull.appstore.api.dao.hibernate.commands;

import org.hibernate.Session;

import com.scottlogic.thull.appstore.api.dao.hibernate.HibernateMethod;

public class CreateMethod<T> implements HibernateMethod<T, Integer>{

	@Override
	public Integer call(Session session, T input) {
		session.beginTransaction();
		Integer id = (Integer) session.save(input);
		session.getTransaction().commit();
		return id;
	}

}


text:
Create Disk Image for passed files/folders.
* For **more than one** files/folders; it'll ask for name of the disk image.
The created disk image will be placed on your __Desktop__.
* For **one** file/folder, it'll name the disk image according to the file/folder.
You can force it to ask for name by pressing Shift (⇧) while invoking the action.
The create disk image will be placed where the passed file/folder is.

_Note_: The action will not run if the sum of passed files/folders is larger than 1 GB.
You can access the logs of the created disk images in the action's support
folder i.e. `~/Library/Application Support/LaunchBar/Action Support/com.xqz.LaunchBar.Action.CreateDMG`
You can see this folder by running the action without sending any items to it.


text:
package org.apache.uima.caseditor.editor.util;

/**
 * This class usually specifies an continous are of text. This area has an start and end index. The
 * difference of the end and start is the length of the area.
 */
public class Span implements Comparable {
  /**
   * The start index of the text.
   */
  private int mStart;

  /**
   * The length of the text.
   */
  private int mLength;

  /**
   * Initializes a new Span instance.
   *
   * @param start
   *          the start
   * @param length
   *          the length
   */
  public Span(int start, int length) {
    mStart = start;
    mLength = length;
  }

  /**
   * Returns the start index.
   *
   * @return - start index
   */
  public int getStart() {
    return mStart;
  }

  /**
   * Returns the length.
   *
   * @return - length
   */
  public int getLength() {
    return mLength;
  }

  /**
   * Returns the end index.
   *
   * @return - end index
   */
  public int getEnd() {
    return mStart + mLength;
  }

  /**
   * Returns true if the given span is a subset of this span.
   *
   * @param containingSpan
   *          - the span to compare
   * @return - true if containingSpan is a subset.
   */
  public boolean isContaining(Span containingSpan) {
    boolean isStartContaining = getStart() <= containingSpan.getStart();
    if (!isStartContaining) {
      return false;
    }

    return getEnd() >= containingSpan.getEnd();
  }

  /**
   * Checks if is intersecting.
   *
   * @param s
   *          the s
   * @return true, if is intersecting
   */
  public boolean isIntersecting(Span s) {
    int sstart = s.getStart();
    return this.isContaining(s) || s.isContaining(this) || getStart() <= sstart && sstart < getEnd()
            || sstart <= getStart() && getStart() < s.getEnd();
  }

  /**
   * Compares the current instance to another {@link Span} object.
   *
   * @param span
   *          the span
   * @return the int
   */
  @Override
  public int compareTo(Span span) {
    return span.getStart() - getStart();
  }

  /**
   * Tests if the current instance is equal to o;.
   *
   * @param o
   *          the o
   * @return true, if successful
   */
  @Override
  public boolean equals(Object o) {
    if (o == null) {
      return false;
    }

    if (!(o instanceof Span)) {
      return false;
    }

    Span span = (Span) o;

    if (getStart() != span.getStart()) {
      return false;
    }

    return getLength() == span.getLength();
  }

  /**
   * Represents the current object as a String.
   *
   * @return the string
   */
  @Override
  public String toString() {
    return "Span: " + getStart() + "-" + getEnd() + " Length: " + getLength();
  }

  /**
   * Generates a hash code of the current object.
   *
   * @return the int
   */
  @Override
  public int hashCode() {
    return toString().hashCode();
  }
}


text:
import { ActivatorBase } from './activator-base';
import { App } from '../components/app/app';
import { Config } from '../config/config';
import { DomController } from '../platform/dom-controller';
import { PointerCoordinates } from '../util/dom';
export declare class Activator implements ActivatorBase {
    protected app: App;
    private dom;
    protected _queue: HTMLElement[];
    protected _active: HTMLElement[];
    protected _activeDefer: Function;
    protected _clearDefer: Function;
    _css: string;
    activatedDelay: number;
    clearDelay: number;
    constructor(app: App, config: Config, dom: DomController);
    clickAction(ev: UIEvent, activatableEle: HTMLElement, startCoord: PointerCoordinates): void;
    downAction(ev: UIEvent, activatableEle: HTMLElement, startCoord: PointerCoordinates): void;
    upAction(ev: UIEvent, activatableEle: HTMLElement, startCoord: PointerCoordinates): void;
    _scheduleClear(): void;
    unscheduleClear(): void;
    clearState(animated: boolean): void;
    deactivate(animated: boolean): void;
    _clearDeferred(): void;
}


text:
'use strict';

/**
 * Module dependencies.
 */
var mongoose = require('mongoose'),
  Schema = mongoose.Schema;

/**
 * Instructor Schema
 */
var InstructorSchema = new Schema({
  created: {
    type: Date,
    default: Date.now
  },
  name: {
    type: String
  },
  role: {
    type: String,
    optional: true
  },
  locations: { // based array for multiple instances!
    type: Object,
    optional: true
  },
  bio: {
    type: String,
    optional: true
  },
  specialities: {
    type: [String],
    optional: true
  },
  image: { // url - provide default avatar
    type: String,
    optional: true
  },
  social: {
    type: Object,
    optional: true
  },
  user: {
    type: Schema.ObjectId,
    ref: 'User'
  }
});

mongoose.model('Instructor', InstructorSchema);


text:
<?php

namespace ZF\Doctrine\Audit\Persistence;

use Doctrine\Common\Persistence\ObjectManager;

interface ObjectManagerAwareInterface
{
    public function setObjectManager(ObjectManager $objectManager);
    public function getObjectManager(): ObjectManager;
}


text:
using System.Collections.Generic;

using Windows.Data.Xml.Dom;
using Windows.UI.Notifications;

using Vulpecula.Universal.BgTask;
using Vulpecula.Universal.Models.Timelines.Primitive;

namespace Vulpecula.Universal.Models.Notifications
{
    public static class ToastNotificationWrapper
    {
        public static ToastNotification PopToast(string title, string content, NotificationSounds sound = NotificationSounds.Default)
        {
            ToastNotificationManager.History.Clear();

            var notifySound = sound.ToString();
            if (notifySound.Contains("Call") || notifySound.Contains("Alarm"))
                notifySound = "Looping." + notifySound;
            var payload =
            $@"
<toast>
    <visual>
        <binding template='ToastGeneric'>
            <text>{title}</text>
            <text>{content}</text>
        </binding>
    </visual>
    <audio src='ms-winsoundevent:Notification.{notifySound}' />
</toast>";
            var xmlDoc = new XmlDocument();
            xmlDoc.LoadXml(payload);

            var notification = new ToastNotification(xmlDoc);
            ToastNotificationManager.CreateToastNotifier()
                                    .Show(notification);
            return notification;
        }

        // Vulpecula.Models.User がほしい
        public static ToastNotification PopQuickReplyToast(string title, StatusModel status, CroudiaAccount account, NotificationSounds sound = NotificationSounds.Default)
        {
            ToastNotificationManager.History.Clear();

            var notifySound = sound.ToString();
            if (notifySound.Contains("Call") || notifySound.Contains("Alarm"))
                notifySound = "Looping." + notifySound;
            var arguments = new[]
            {
                new KeyValuePair<string, object>("access_token", account.Croudia.AccessToken),
                new KeyValuePair<string, object>("in_reply_to_status_id", status.Id),
                new KeyValuePair<string, object>("in_reply_to_screen_name", status.User.ScreenName)
            };
            var payload =
            $@"
<toast activationType='background' launch='args'>
    <visual>
        <binding template='ToastGeneric'>
            <image placement='appLogoOverride' src='{account.User.ProfileImageUrlHttps}' />
            <text>{title}</text>
            <text>{status.Text}</text>
        </binding>
    </visual>
    <actions>
        <input id='status'
               type='text'
               title='Reply to @{account.User.ScreenName}'
               placeHolderContent='Hello!' />
        <action activationType='background'
                arguments='{QueryString.Query(arguments)}'
                content='Whisper' />
        <action activationType='system'
                arguments='dismiss'
                content='Dismiss' />
    </actions>
    <audio src='ms-winsoundevent:Notification.{notifySound}' />
</toast>";
            var xmlDoc = new XmlDocument();
            xmlDoc.LoadXml(payload);

            var notification = new ToastNotification(xmlDoc);
            ToastNotificationManager.CreateToastNotifier()
                                    .Show(notification);
            return notification;
        }
    }
}


text:
🔵 = currently working
🔴 = planned feature

**Provenance should be captured at all steps**

**Notification Manager**
* 🔴 For all status changes, a notification is created to alert the user of a change. The user can decide if they want an email notification for status changes.
* 🔴 A list of notifications is displayed with all passed steps.
* 🔴 The status of all current running jobs is displayed. All status changes go to the notification log.
* 🔴 Display of HPC global queue.

**Run Manager**
* 🔵 As a user, I should be able to create new run configurations. A run config consists of all the nessisary parameters to start a new run. Runs are broken into five catagories, Model Run, 🔴 Create Climatologies, 🔴 Archive and transfer, Diagnostic Run, and Publication.
* When runs complete, I should have access to and be able to share run performance information.
* Run configurations and status should be sharable between Dashboard users.
* 🔵 As a user, I can browse through all my created run configurations.
* 🔵 As a user, I can modify my run configs, 🔴 with the ability to undo modifications.
* 🔴 As a user with HPC resource access, I should be able to start new Model runs. A model run should give me feedback on its status in real time as the run progresses. When a Model run completes, I should have access to the output files in the Data Manager.
* 🔴 As a model is run, every 5 years climatologies are automatially computed and made available to the user. (triggering next step by default)
* 🔴 Raw output is copied to HPSS, and climos are transfered to analysis server.(triggering next step by default)
* 🔴 Once transfer is complete, diagnostics are computed.(triggering next step by default)
* 🔴 Climos published to ESGF after.(triggering next step by default)
* 🔴 diag output published to diagnostic viewer.
* 🔵 As a user, I should be able to start diagnostic runs on any model or observation data in the Data Manager.

**Data Manager**
* 🔴 As a user, I can import a provenance file to recreate mutations on datasets.
* 🔴 As a user, I can examine provenance files for all reproducability steps.
* 🔵 As a user, I should be able to both upload and download my custom datasets, catagorized as Diagnostic, Model, or Observation. Dataset should be importable from a local computer, a remote server (via URL), or through ESGF.
* 🔴 As a user with the ESGF publication role, I should be able to publish any dataset to ESGF.
* 🔴 As a user I should be able to create a sharable download link. Download URLs should be created for both individual datafiles as well as entire datasets. These links should be access controlled.
* 🔵 As a user, I should be able to browse through my available data.
* 🔴 As a user, I should be able to share my data with other Dashboard users.
* 🔴 As a user, I should be able to upload my diagnostic output to the diag_viewer, and view it via a link.
* 🔴 After a diagnostic is created, I should be able to import to the visualization panel, at the point where I can perform analysis. I should then be able to save as a new plot. Any changes to the plot and share them with other users.
* 🔴 As a user, I should be able to specify "favorite" diagnostic plot types which are displayed above others.

**Visualization**
* 🔴 As a user, I should be able to import any of my available data into the visualization panel.
* 🔴 As a user, I should have the same level of control over visualizations as a UVCDAT user.
* 🔴 Once a visualization is created, I should be able to download .png output as well as a script to replicated the visualization locally through UVCDAT.
* 🔴 As a user, I should be able to share my visualization configs with other Dashboard users.


text:
using content::BrowserThread;

namespace chromeos {

namespace {

// Time histogram suffix for profile image download.
const char kProfileDownloadReason[] = "OOBE";

}  // namespace

UserImageScreen::UserImageScreen(ScreenObserver* screen_observer,
                                 UserImageScreenActor* actor)
    : WizardScreen(screen_observer),
      actor_(actor),
      weak_factory_(this),
      accept_photo_after_decoding_(false),
      selected_image_(User::kInvalidImageIndex),
      profile_picture_enabled_(false),
      profile_picture_data_url_(content::kAboutBlankURL),
      profile_picture_absent_(false) {
  actor_->SetDelegate(this);
  SetProfilePictureEnabled(true);
}

UserImageScreen::~UserImageScreen() {
  if (actor_)
    actor_->SetDelegate(NULL);
  if (image_decoder_.get())
    image_decoder_->set_delegate(NULL);
}

void UserImageScreen::CheckCameraPresence() {
  CameraDetector::StartPresenceCheck(
      base::Bind(&UserImageScreen::OnCameraPresenceCheckDone,
                 weak_factory_.GetWeakPtr()));
}

void UserImageScreen::OnCameraPresenceCheckDone() {
  if (actor_) {
    actor_->SetCameraPresent(
        CameraDetector::camera_presence() == CameraDetector::kCameraPresent);
  }
}

void UserImageScreen::OnPhotoTaken(const std::string& raw_data) {
  DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
  user_photo_ = gfx::ImageSkia();
  if (image_decoder_.get())
    image_decoder_->set_delegate(NULL);
  image_decoder_ = new ImageDecoder(this, raw_data,
                                    ImageDecoder::DEFAULT_CODEC);
  scoped_refptr<base::MessageLoopProxy> task_runner =
      BrowserThread::GetMessageLoopProxyForThread(BrowserThread::UI);
  image_decoder_->Start(task_runner);
}

void UserImageScreen::OnImageDecoded(const ImageDecoder* decoder,
                                     const SkBitmap& decoded_image) {
  DCHECK_EQ(image_decoder_.get(), decoder);
  user_photo_ = gfx::ImageSkia::CreateFrom1xBitmap(decoded_image);
  if (accept_photo_after_decoding_)
    OnImageAccepted();
}

void UserImageScreen::OnDecodeImageFailed(const ImageDecoder* decoder) {
  NOTREACHED() << "Failed to decode PNG image from WebUI";
}

void UserImageScreen::OnImageSelected(const std::string& image_type,
                                      const std::string& image_url) {
  if (image_url.empty())
    return;
  int user_image_index = User::kInvalidImageIndex;
  if (image_type == "default" &&
      IsDefaultImageUrl(image_url, &user_image_index)) {
    selected_image_ = user_image_index;
  } else if (image_type == "camera") {
    selected_image_ = User::kExternalImageIndex;
  } else if (image_type == "profile") {
    selected_image_ = User::kProfileImageIndex;
  } else {
    NOTREACHED() << "Unexpected image type: " << image_type;
  }
}

void UserImageScreen::OnImageAccepted() {
  UserManager* user_manager = UserManager::Get();
  UserImageManager* image_manager = user_manager->GetUserImageManager();
  std::string user_id = GetUser()->email();
  int uma_index = 0;
  switch (selected_image_) {
    case User::kExternalImageIndex:
      // Photo decoding may not have been finished yet.
      if (user_photo_.isNull()) {
        accept_photo_after_decoding_ = true;
        return;
      }
      image_manager->
          SaveUserImage(user_id, UserImage::CreateAndEncode(user_photo_));
      uma_index = kHistogramImageFromCamera;
      break;
    case User::kProfileImageIndex:
      image_manager->SaveUserImageFromProfileImage(user_id);
      uma_index = kHistogramImageFromProfile;
      break;
    default:
      DCHECK(selected_image_ >= 0 && selected_image_ < kDefaultImagesCount);
      image_manager->SaveUserDefaultImageIndex(user_id, selected_image_);
      uma_index = GetDefaultImageHistogramValue(selected_image_);
      break;
  }
  UMA_HISTOGRAM_ENUMERATION("UserImage.FirstTimeChoice",
                            uma_index,
                            kHistogramImagesCount);
  get_screen_observer()->OnExit(ScreenObserver::USER_IMAGE_SELECTED);
}

void UserImageScreen::SetProfilePictureEnabled(bool profile_picture_enabled) {
  if (profile_picture_enabled_ == profile_picture_enabled)
    return;
  profile_picture_enabled_ = profile_picture_enabled;
  if (profile_picture_enabled) {
    registrar_.Add(this, chrome::NOTIFICATION_PROFILE_IMAGE_UPDATED,
        content::NotificationService::AllSources());
    registrar_.Add(this, chrome::NOTIFICATION_PROFILE_IMAGE_UPDATE_FAILED,
        content::NotificationService::AllSources());
  } else {
    registrar_.Remove(this, chrome::NOTIFICATION_PROFILE_IMAGE_UPDATED,
        content::NotificationService::AllSources());
    registrar_.Remove(this, chrome::NOTIFICATION_PROFILE_IMAGE_UPDATE_FAILED,
        content::NotificationService::AllSources());
  }
  if (actor_)
    actor_->SetProfilePictureEnabled(profile_picture_enabled);
}

void UserImageScreen::SetUserID(const std::string& user_id) {
  DCHECK(!user_id_.empty());
  user_id_ = user_id;
}

void UserImageScreen::PrepareToShow() {
  if (actor_)
    actor_->PrepareToShow();
}

const User* UserImageScreen::GetUser() {
  if (user_id_.empty())
    return UserManager::Get()->GetLoggedInUser();
  const User* user = UserManager::Get()->FindUser(user_id_);
  DCHECK(user);
  return user;
}

void UserImageScreen::Show() {
  if (!actor_)
    return;

  actor_->Show();
  actor_->SetProfilePictureEnabled(profile_picture_enabled_);

  selected_image_ = GetUser()->image_index();
  actor_->SelectImage(selected_image_);

  if (profile_picture_enabled_) {
    // Start fetching the profile image.
    UserManager::Get()->GetUserImageManager()->
        DownloadProfileImage(kProfileDownloadReason);
  }

  accessibility::MaybeSpeak(
      l10n_util::GetStringUTF8(IDS_OPTIONS_CHANGE_PICTURE_DIALOG_TEXT));
}

void UserImageScreen::Hide() {
  if (actor_)
    actor_->Hide();
}

std::string UserImageScreen::GetName() const {
  return WizardController::kUserImageScreenName;
}

void UserImageScreen::OnActorDestroyed(UserImageScreenActor* actor) {
  if (actor_ == actor)
    actor_ = NULL;
}

void UserImageScreen::Observe(int type,
                              const content::NotificationSource& source,
                              const content::NotificationDetails& details) {
  DCHECK(profile_picture_enabled_);
  switch (type) {
    case chrome::NOTIFICATION_PROFILE_IMAGE_UPDATED: {
      // We've got a new profile image.
      profile_picture_data_url_ = webui::GetBitmapDataUrl(
          *content::Details<const gfx::ImageSkia>(details).ptr()->bitmap());
      if (actor_)
        actor_->SendProfileImage(profile_picture_data_url_);
      break;
    }
    case chrome::NOTIFICATION_PROFILE_IMAGE_UPDATE_FAILED: {
      // User has a default profile image or fetching profile image has failed.
      profile_picture_absent_ = true;
      if (actor_)
        actor_->OnProfileImageAbsent();
      break;
    }
    default:
      NOTREACHED();
  }
}

bool UserImageScreen::profile_picture_absent() {
  return profile_picture_absent_;
}

int UserImageScreen::selected_image() {
  return selected_image_;
}

std::string UserImageScreen::profile_picture_data_url() {
  return profile_picture_data_url_;
}

}  // namespace chromeos


text:
namespace ApplicationInsights
{
	namespace core
	{
		class TELEMETRYCLIENT_API RemoteDependencyData : public Domain
		{
		private:
			int m_ver;
			Nullable<std::wstring> m_id;
			std::wstring m_name;
			DataPointType m_kind;
			double m_value;
			Nullable<int> m_count;
			Nullable<double> m_min;
			Nullable<double> m_max;
			Nullable<double> m_stdDev;
			DependencyKind m_dependencyKind;
			Nullable<bool> m_success;
			Nullable<bool> m_async;
			DependencySourceType m_dependencySource;
			std::wstring m_commandName;
			std::wstring m_dependencyTypeName;
			Nullable<std::wstring> m_parentId;
			std::map<std::wstring, std::wstring> m_properties;

		public:
			RemoteDependencyData();
			RemoteDependencyData(std::wstring envelopeName, std::wstring dataType);
			virtual ~RemoteDependencyData();

			const int& GetVer() const { return m_ver; }
			void SetVer(const int& value) { m_ver = value; }

			const Nullable<std::wstring>& GetId() const { return m_id; }
			void SetId(const Nullable<std::wstring>& value) { m_id = value; }

			const std::wstring& GetName() const { return m_name; }
			void SetName(const std::wstring& value) { m_name = value; }

			const DataPointType& GetKind() const { return m_kind; }
			void SetKind(const DataPointType& value) { m_kind = value; }

			const double& GetValue() const { return m_value; }
			void SetValue(const double& value) { m_value = value; }

			const Nullable<int>& GetCount() const { return m_count; }
			void SetCount(const Nullable<int>& value) { m_count = value; }

			const Nullable<double>& GetMin() const { return m_min; }
			void SetMin(const Nullable<double>& value) { m_min = value; }

			const Nullable<double>& GetMax() const { return m_max; }
			void SetMax(const Nullable<double>& value) { m_max = value; }

			const Nullable<double>& GetStdDev() const { return m_stdDev; }
			void SetStdDev(const Nullable<double>& value) { m_stdDev = value; }

			const DependencyKind& GetDependencyKind() const { return m_dependencyKind; }
			void SetDependencyKind(const DependencyKind& value) { m_dependencyKind = value; }

			const Nullable<bool>& GetSuccess() const { return m_success; }
			void SetSuccess(const Nullable<bool>& value) { m_success = value; }

			const Nullable<bool>& GetAsync() const { return m_async; }
			void SetAsync(const Nullable<bool>& value) { m_async = value; }

			const DependencySourceType& GetDependencySource() const { return m_dependencySource; }
			void SetDependencySource(const DependencySourceType& value) { m_dependencySource = value; }

			const std::wstring& GetCommandName() const { return m_commandName; }
			void SetCommandName(const std::wstring& value) { m_commandName = value; }

			const std::wstring& GetDependencyTypeName() const { return m_dependencyTypeName; }
			void SetDependencyTypeName(const std::wstring& value) { m_dependencyTypeName = value; }

			const Nullable<std::wstring>& GetParentId() const { return m_parentId; }
			void SetParentId(const Nullable<std::wstring>& value) { m_parentId = value; }

			const std::map<std::wstring, std::wstring>& GetProperties() const { return m_properties; }
			void SetProperties(const std::map<std::wstring, std::wstring>& value) { m_properties = value; }

			virtual void Serialize(Serializer& serializer) const;
		};
	}
}
#endif


text:
@interface IAPDataSecret : NSObject

+(IAPDataSecret *)sharedInstance;
@property (strong, nonatomic) NSString *bundleIdentifier;
@property (strong, nonatomic) NSString *bundleVersion;

@end


text:
using pb = global::Google.Protobuf;
using pbc = global::Google.Protobuf.Collections;
using pbr = global::Google.Protobuf.Reflection;
using scg = global::System.Collections.Generic;
namespace Google.Cloud.Retail.V2 {

  /// Holder for reflection information generated from google/cloud/retail/v2/promotion.proto
  public static partial class PromotionReflection {

    #region Descriptor
    /// File descriptor for google/cloud/retail/v2/promotion.proto
    public static pbr::FileDescriptor Descriptor {
      get { return descriptor; }
    }
    private static pbr::FileDescriptor descriptor;

    static PromotionReflection() {
      byte[] descriptorData = global::System.Convert.FromBase64String(
          string.Concat(
            "CiZnb29nbGUvY2xvdWQvcmV0YWlsL3YyL3Byb21vdGlvbi5wcm90bxIWZ29v",
            "Z2xlLmNsb3VkLnJldGFpbC52MiIhCglQcm9tb3Rpb24SFAoMcHJvbW90aW9u",
            "X2lkGAEgASgJQsMBChpjb20uZ29vZ2xlLmNsb3VkLnJldGFpbC52MkIOUHJv",
            "bW90aW9uUHJvdG9QAVo8Z29vZ2xlLmdvbGFuZy5vcmcvZ2VucHJvdG8vZ29v",
            "Z2xlYXBpcy9jbG91ZC9yZXRhaWwvdjI7cmV0YWlsogIGUkVUQUlMqgIWR29v",
            "Z2xlLkNsb3VkLlJldGFpbC5WMsoCFkdvb2dsZVxDbG91ZFxSZXRhaWxcVjLq",
            "AhlHb29nbGU6OkNsb3VkOjpSZXRhaWw6OlYyYgZwcm90bzM="));
      descriptor = pbr::FileDescriptor.FromGeneratedCode(descriptorData,
          new pbr::FileDescriptor[] { },
          new pbr::GeneratedClrTypeInfo(null, null, new pbr::GeneratedClrTypeInfo[] {
            new pbr::GeneratedClrTypeInfo(typeof(global::Google.Cloud.Retail.V2.Promotion), global::Google.Cloud.Retail.V2.Promotion.Parser, new[]{ "PromotionId" }, null, null, null, null)
          }));
    }
    #endregion

  }
  #region Messages
  ///
  /// Promotion information.
  ///
  public sealed partial class Promotion : pb::IMessage<Promotion>
  #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE
      , pb::IBufferMessage
  #endif
  {
    private static readonly pb::MessageParser<Promotion> _parser = new pb::MessageParser<Promotion>(() => new Promotion());
    private pb::UnknownFieldSet _unknownFields;
    [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
    [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
    public static pb::MessageParser<Promotion> Parser { get { return _parser; } }

    [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
    [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
    public static pbr::MessageDescriptor Descriptor {
      get { return global::Google.Cloud.Retail.V2.PromotionReflection.Descriptor.MessageTypes[0]; }
    }

    [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
    [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
    pbr::MessageDescriptor pb::IMessage.Descriptor {
      get { return Descriptor; }
    }

    [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
    [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
    public Promotion() {
      OnConstruction();
    }

    partial void OnConstruction();

    [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
    [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
    public Promotion(Promotion other) : this() {
      promotionId_ = other.promotionId_;
      _unknownFields = pb::UnknownFieldSet.Clone(other._unknownFields);
    }

    [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
    [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
    public Promotion Clone() {
      return new Promotion(this);
    }

    /// Field number for the "promotion_id" field.
    public const int PromotionIdFieldNumber = 1;
    private string promotionId_ = "";
    ///
    /// ID of the promotion. For example, "free gift".
    ///
    /// The value must be a UTF-8 encoded string with a length limit of 128
    /// characters, and match the pattern: `[a-zA-Z][a-zA-Z0-9_]*`. For example,
    /// id0LikeThis or ID_1_LIKE_THIS. Otherwise, an INVALID_ARGUMENT error is
    /// returned.
    ///
    /// Google Merchant Center property
    /// [promotion](https://support.google.com/merchants/answer/7050148).
    ///
    [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
    [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
    public string PromotionId {
      get { return promotionId_; }
      set {
        promotionId_ = pb::ProtoPreconditions.CheckNotNull(value, "value");
      }
    }

    [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
    [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
    public override bool Equals(object other) {
      return Equals(other as Promotion);
    }

    [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
    [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
    public bool Equals(Promotion other) {
      if (ReferenceEquals(other, null)) {
        return false;
      }
      if (ReferenceEquals(other, this)) {
        return true;
      }
      if (PromotionId != other.PromotionId) return false;
      return Equals(_unknownFields, other._unknownFields);
    }

    [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
    [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
    public override int GetHashCode() {
      int hash = 1;
      if (PromotionId.Length != 0) hash ^= PromotionId.GetHashCode();
      if (_unknownFields != null) {
        hash ^= _unknownFields.GetHashCode();
      }
      return hash;
    }

    [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
    [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
    public override string ToString() {
      return pb::JsonFormatter.ToDiagnosticString(this);
    }

    [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
    [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
    public void WriteTo(pb::CodedOutputStream output) {
    #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE
      output.WriteRawMessage(this);
    #else
      if (PromotionId.Length != 0) {
        output.WriteRawTag(10);
        output.WriteString(PromotionId);
      }
      if (_unknownFields != null) {
        _unknownFields.WriteTo(output);
      }
    #endif
    }

    #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE
    [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
    [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
    void pb::IBufferMessage.InternalWriteTo(ref pb::WriteContext output) {
      if (PromotionId.Length != 0) {
        output.WriteRawTag(10);
        output.WriteString(PromotionId);
      }
      if (_unknownFields != null) {
        _unknownFields.WriteTo(ref output);
      }
    }
    #endif

    [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
    [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
    public int CalculateSize() {
      int size = 0;
      if (PromotionId.Length != 0) {
        size += 1 + pb::CodedOutputStream.ComputeStringSize(PromotionId);
      }
      if (_unknownFields != null) {
        size += _unknownFields.CalculateSize();
      }
      return size;
    }

    [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
    [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
    public void MergeFrom(Promotion other) {
      if (other == null) {
        return;
      }
      if (other.PromotionId.Length != 0) {
        PromotionId = other.PromotionId;
      }
      _unknownFields = pb::UnknownFieldSet.MergeFrom(_unknownFields, other._unknownFields);
    }

    [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
    [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
    public void MergeFrom(pb::CodedInputStream input) {
    #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE
      input.ReadRawMessage(this);
    #else
      uint tag;
      while ((tag = input.ReadTag()) != 0) {
        switch(tag) {
          default:
            _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, input);
            break;
          case 10: {
            PromotionId = input.ReadString();
            break;
          }
        }
      }
    #endif
    }

    #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE
    [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
    [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
    void pb::IBufferMessage.InternalMergeFrom(ref pb::ParseContext input) {
      uint tag;
      while ((tag = input.ReadTag()) != 0) {
        switch(tag) {
          default:
            _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, ref input);
            break;
          case 10: {
            PromotionId = input.ReadString();
            break;
          }
        }
      }
    }
    #endif

  }

  #endregion

}

#endregion Designer generated code


text:
<?php

namespace wsl\rbac\models;

use Yii;
use yii\db\ActiveRecord;

/**
 * This is the model class for table "dp_admin_user_menu_relation".
 *
 * @property integer $user_id
 * @property integer $menu_id
 *
 * @property DpAdminMenu $menu
 * @property DpAdminUser $user
 */
class DpAdminUserMenuRelation extends ActiveRecord
{

    /**
     * @inheritdoc
     */
    public static function tableName()
    {
        return 'dp_admin_user_menu_relation';
    }

    /**
     * @inheritdoc
     */
    public function rules()
    {
        return [
            [['user_id', 'menu_id'], 'required'],
            [['user_id', 'menu_id'], 'integer']
        ];
    }

    /**
     * @inheritdoc
     */
    public function attributeLabels()
    {
        return [
            'user_id' => '用户ID',
            'menu_id' => '菜单ID',
        ];
    }

    /**
     * @return \yii\db\ActiveQuery
     */
    public function getMenu()
    {
        return $this->hasOne(DpAdminMenu::className(), ['menu_id' => 'menu_id']);
    }

    /**
     * @return \yii\db\ActiveQuery
     */
    public function getUser()
    {
        return $this->hasOne(DpAdminUser::className(), ['user_id' => 'user_id']);
    }

    /**
     * @inheritdoc
     * @return DpAdminUserMenuRelationQuery the active query used by this AR class.
     */
    public static function find()
    {
        return new DpAdminUserMenuRelationQuery(get_called_class());
    }

    /**
     * 删除指定用户id所有记录
     *
     * @param int $userId 用户id
     * @return int
     */
    public static function deleteByUserId($userId)
    {
        return static::deleteAll([
            'user_id' => $userId,
        ]);
    }

    /**
     * 获取指定用户的所有菜单id记录
     *
     * @param int $userId 用户id
     * @return array
     */
    public static function getAllMenuIdArrByUserId($userId)
    {
        $data = static::find()
            ->findByUserId($userId)
            ->asArray()
            ->all();

        $menuIdArr = [];
        foreach ($data as $item) {
            $menu = DpAdminMenu::find()
                ->findByMenuId($item['menu_id'])
                ->asArray()
                ->one();
            if ($menu) {
                $menuIdArr[] = $item['menu_id'];
            }
        }

        return $menuIdArr;
    }
}


text:
package br.com.caelum.financas.teste;

import javax.persistence.EntityManager;

import br.com.caelum.financas.modelo.Conta;
import br.com.caelum.financas.util.JPAUtil;

public class TesteEstadoJPA {

	public static void main(String[] args) {

		EntityManager em = new JPAUtil().getEntityManager();

		em.getTransaction().begin();

		Conta conta = em.find(Conta.class,19); // O find passado a classe e o id classe ref BD - Faz uma busca do id no BD
		System.out.println(conta.getTitular());

		//Novo código deixando em Managed e alterando o valor

		System.out.println(conta.getTitular());

        // Alterando o titular da conta
        conta.setTitular("Luiz Ferreira"); // Vejamos que foi alterado no BD para este novo valor.

        System.out.println(conta.getTitular());

		//

		em.getTransaction().commit();
		em.close();

	}

}


text:
package org.redisson.command;

import org.redisson.api.BatchOptions;
import org.redisson.api.BatchOptions.ExecutionMode;
import org.redisson.client.RedisConnection;
import org.redisson.client.codec.Codec;
import org.redisson.client.protocol.*;
import org.redisson.command.CommandBatchService.ConnectionEntry;
import org.redisson.command.CommandBatchService.Entry;
import org.redisson.connection.ConnectionManager;
import org.redisson.connection.MasterSlaveEntry;
import org.redisson.connection.NodeSource;
import org.redisson.connection.NodeSource.Redirect;
import org.redisson.liveobject.core.RedissonObjectBuilder;
import org.redisson.misc.LogHelper;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.CancellationException;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ConcurrentMap;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicInteger;

/**
 *
 * @author Nikita Koksharov
 *
 * @param <V> type of value
 * @param <R> type of returned value
 */
public class RedisQueuedBatchExecutor<V, R> extends BaseRedisBatchExecutor<V, R> {

    private final ConcurrentMap<MasterSlaveEntry, ConnectionEntry> connections;

    @SuppressWarnings("ParameterNumber")
    public RedisQueuedBatchExecutor(boolean readOnlyMode, NodeSource source, Codec codec, RedisCommand<V> command,
                                    Object[] params, CompletableFuture<R> mainPromise, boolean ignoreRedirect, ConnectionManager connectionManager,
                                    RedissonObjectBuilder objectBuilder, ConcurrentMap<MasterSlaveEntry, Entry> commands,
                                    ConcurrentMap<MasterSlaveEntry, ConnectionEntry> connections, BatchOptions options, AtomicInteger index,
                                    AtomicBoolean executed, RedissonObjectBuilder.ReferenceType referenceType,
                                    boolean noRetry) {
        super(readOnlyMode, source, codec, command, params, mainPromise, ignoreRedirect, connectionManager, objectBuilder,
                commands, options, index, executed, referenceType, noRetry);

        this.connections = connections;
    }

    @Override
    public void execute() {
        addBatchCommandData(null);

        if (!readOnlyMode && this.options.getExecutionMode() == ExecutionMode.REDIS_READ_ATOMIC) {
            throw new IllegalStateException("Data modification commands can't be used with queueStore=REDIS_READ_ATOMIC");
        }

        super.execute();
    }

    @Override
    protected void releaseConnection(CompletableFuture<R> attemptPromise, CompletableFuture<RedisConnection> connectionFuture) {
        if (RedisCommands.EXEC.getName().equals(command.getName())
                || RedisCommands.DISCARD.getName().equals(command.getName())) {
            super.releaseConnection(attemptPromise, connectionFuture);
        } else {
            connectionManager.getShutdownLatch().release();
        }
    }

    @Override
    protected void handleSuccess(CompletableFuture<R> promise, CompletableFuture<RedisConnection> connectionFuture, R res)
            throws ReflectiveOperationException {
        if (RedisCommands.EXEC.getName().equals(command.getName())) {
            super.handleSuccess(promise, connectionFuture, res);
            return;
        }
        if (RedisCommands.DISCARD.getName().equals(command.getName())) {
            super.handleSuccess(promise, connectionFuture, null);
            return;
        }

        BatchPromise<R> batchPromise = (BatchPromise<R>) promise;
        CompletableFuture sentPromise = batchPromise.getSentPromise();
        super.handleSuccess(sentPromise, connectionFuture, null);
    }

    @Override
    protected void handleError(CompletableFuture<RedisConnection> connectionFuture, Throwable cause) {
        if (mainPromise instanceof BatchPromise) {
            BatchPromise<R> batchPromise = (BatchPromise<R>) mainPromise;
            CompletableFuture sentPromise = batchPromise.getSentPromise();
            sentPromise.completeExceptionally(cause);
            mainPromise.completeExceptionally(cause);
            if (executed.compareAndSet(false, true)) {
                getNow(connectionFuture).forceFastReconnectAsync().whenComplete((res, e) -> {
                    RedisQueuedBatchExecutor.super.releaseConnection(mainPromise, connectionFuture);
                });
            }
            return;
        }

        super.handleError(connectionFuture, cause);
    }

    @Override
    protected void sendCommand(CompletableFuture<R> attemptPromise, RedisConnection connection) {
        MasterSlaveEntry msEntry = getEntry(source);
        ConnectionEntry connectionEntry = connections.get(msEntry);

        boolean syncSlaves = options.getSyncSlaves() > 0;

        if (source.getRedirect() == Redirect.ASK) {
            List<CommandData<?, ?>> list = new ArrayList<>(2);
            CompletableFuture<Void> promise = new CompletableFuture<>();
            list.add(new CommandData<>(promise, codec, RedisCommands.ASKING, new Object[]{}));
            if (connectionEntry.isFirstCommand()) {
                list.add(new CommandData<>(promise, codec, RedisCommands.MULTI, new Object[]{}));
                connectionEntry.setFirstCommand(false);
            }
            list.add(new CommandData<>(attemptPromise, codec, command, params));
            CompletableFuture<Void> main = new CompletableFuture<>();
            writeFuture = connection.send(new CommandsData(main, list, true, syncSlaves));
        } else {
            if (log.isDebugEnabled()) {
                log.debug("acquired connection for command {} and params {} from slot {} using node {}... {}",
                        command, LogHelper.toString(params), source, connection.getRedisClient().getAddr(), connection);
            }

            if (connectionEntry.isFirstCommand()) {
                List<CommandData<?, ?>> list = new ArrayList<>(2);
                list.add(new CommandData<>(new CompletableFuture<>(), codec, RedisCommands.MULTI, new Object[]{}));
                list.add(new CommandData<>(attemptPromise, codec, command, params));
                CompletableFuture<Void> main = new CompletableFuture<>();
                writeFuture = connection.send(new CommandsData(main, list, true, syncSlaves));
                connectionEntry.setFirstCommand(false);
            } else {
                if (RedisCommands.EXEC.getName().equals(command.getName())) {
                    Entry entry = commands.get(msEntry);

                    List<CommandData<?, ?>> list = new ArrayList<>();

                    if (options.isSkipResult()) {
                        list.add(new CommandData<>(new CompletableFuture<>(), codec, RedisCommands.CLIENT_REPLY, new Object[]{"OFF"}));
                    }

                    list.add(new CommandData<>(attemptPromise, codec, command, params));

                    if (options.isSkipResult()) {
                        list.add(new CommandData<>(new CompletableFuture<>(), codec, RedisCommands.CLIENT_REPLY, new Object[]{"ON"}));
                    }
                    if (options.getSyncSlaves() > 0) {
                        BatchCommandData<?, ?> waitCommand = new BatchCommandData(RedisCommands.WAIT,
                                new Object[] { this.options.getSyncSlaves(), this.options.getSyncTimeout() }, index.incrementAndGet());
                        list.add(waitCommand);
                        entry.getCommands().add(waitCommand);
                    }

                    CompletableFuture<Void> main = new CompletableFuture<>();
                    writeFuture = connection.send(new CommandsData(main, list, new ArrayList(entry.getCommands()),
                                options.isSkipResult(), false, true, syncSlaves));
                } else {
                    CompletableFuture<Void> main = new CompletableFuture<>();
                    List<CommandData<?, ?>> list = new ArrayList<>();
                    list.add(new CommandData<>(attemptPromise, codec, command, params));
                    writeFuture = connection.send(new CommandsData(main, list, true, syncSlaves));
                }
            }
        }
    }

    @Override
    protected CompletableFuture<RedisConnection> getConnection() {
        MasterSlaveEntry msEntry = getEntry(source);
        ConnectionEntry entry = connections.get(msEntry);
        if (entry == null) {
            entry = new ConnectionEntry();
            ConnectionEntry oldEntry = connections.putIfAbsent(msEntry, entry);
            if (oldEntry != null) {
                entry = oldEntry;
            }
        }

        if (entry.getConnectionFuture() != null) {
            return entry.getConnectionFuture();
        }

        synchronized (this) {
            if (entry.getConnectionFuture() != null) {
                return entry.getConnectionFuture();
            }

            CompletableFuture<RedisConnection> connectionFuture;
            if (this.options.getExecutionMode() == ExecutionMode.REDIS_WRITE_ATOMIC) {
                connectionFuture = connectionManager.connectionWriteOp(source, null);
            } else {
                connectionFuture = connectionManager.connectionReadOp(source, null);
            }
            connectionFuture.toCompletableFuture().join();
            entry.setConnectionFuture(connectionFuture);

            entry.setCancelCallback(() -> {
                handleError(connectionFuture, new CancellationException());
            });

            return connectionFuture;
        }
    }

}


text:
/* jshint asi:true */

'use strict'

var fs = require('fs')
var test = require('assertit')
var gutil = require('gulp-util')
var j140 = require('./index')

function plugin (file, onerror) {
  var stream = j140({
    place: 'world',
    user: {
      name: 'Charlike'
    }
  })
  stream.once('error', onerror)
  stream.write(file)
  return stream
}

test('should render file with locals', function (done) {
  var stream = plugin(new gutil.File({
    base: __dirname,
    path: __dirname + '/fixture.txt',
    contents: new Buffer('Hello #{place} and #{user.name}!')
  }), done)

  stream.once('data', function (file) {
    test.strictEqual(file.contents.toString(), 'Hello world and Charlike!')
    done()
  })
})

test('should error if stream', function (done) {
  plugin(new gutil.File({
    base: __dirname,
    path: __dirname + '/package.json',
    contents: fs.createReadStream('package.json')
  }), function (err) {
    test.strictEqual(err.message, 'Streaming not supported')
    done()
  })
})

test('should throw TypeError if `locals` not object', function (done) {
  function fixture () {
    j140('foo bar')
  }

  test.throws(fixture, TypeError)
  test.throws(fixture, /expect `locals` to be object/)
  done()
})


text:
package json

type Encoder struct{}

// AppendKey appends a new key to the output JSON.
func (e Encoder) AppendKey(dst []byte, key string) []byte {
	if dst[len(dst)-1] != '{' {
		dst = append(dst, ',')
	}
	return append(e.AppendString(dst, key), ':')
}


text:
from azure.identity import DefaultAzureCredential
from azure.mgmt.azurestackhci import AzureStackHCIClient

"""
# PREREQUISITES
    pip install azure-identity
    pip install azure-mgmt-azurestackhci
# USAGE
    python list_update_runs.py

    Before run the sample, please set the values of the client ID, tenant ID and client secret
    of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID,
    AZURE_CLIENT_SECRET. For more info about how to get the value, please see:
    https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal
"""

def main():
    client = AzureStackHCIClient(
        credential=DefaultAzureCredential(),
        subscription_id="b8d594e5-51f3-4c11-9c54-a7771b81c712",
    )

    response = client.update_runs.list(
        resource_group_name="testrg",
        cluster_name="testcluster",
        update_name="Microsoft4.2203.2.32",
    )
    for item in response:
        print(item)

# x-ms-original-file: specification/azurestackhci/resource-manager/Microsoft.AzureStackHCI/stable/2022-10-01/examples/ListUpdateRuns.json
if __name__ == "__main__":
    main()


text:
import url_manager
import html_parser
import html_outputer
import html_downloader
import mysql_inserter
import json_parser
import mysql.connector

class SpiderMain(object):

    def __init__(self):
        self.urls = url_manager.UrlManager()
        self.downloader = html_downloader.HtmlDownloader()
        self.html_parser = html_parser.HtmlParser()
        self.json_parser = json_parser.JsonParser()
        self.outputer = html_outputer.HtmlOutputer()
        conn = mysql.connector.connect(user='root', password='u6a3pwhe',
                                       database='dice_test')
        self.inserter = mysql_inserter.MySQLInserter(conn)
        self.duplicate_counter = self.inserter.duplicate_counter

    def craw(self, root_url):
        count = 0
        self.urls.add_new_url(root_url)
        while self.urls.has_new_url() or self.duplicate_counter <= 5:
            try:
                new_url = self.urls.get_new_url()
                print "Craw %d : %s" % (count, new_url)
                json_cont = self.downloader.download_json(new_url)

                data_dict, next_url = self.json_parser.parse(json_cont)

                for key in data_dict:
                    # TODO: html_downloader returns url, html_cont
                    real_url, html_cont = self.downloader.download(
                                        data_dict[key]['detailUrl'])
                    data_dict[key]['detailUrl'] = real_url
                    job_description = self.html_parser.parse(real_url,
                                                             html_cont)
                    data_dict[key]['jobDescription'] = job_description

                    if job_description is None:
                        continue

                    self.inserter.insert(key, data_dict[key]['jobTitle'],
                                         data_dict[key]['detailUrl'],
                                         data_dict[key]['company'],
                                         data_dict[key]['date'],
                                         data_dict[key]['jobDescription'])

                # the new urls should only be the nextURL
                if next_url is not None:
                    next_url = "http://service.dice.com" + next_url.encode(
                        'utf-8')
                    self.urls.add_new_url(next_url)

                count = count + 1
            except Exception as err:
                print "craw failed"
                print err
                raise err

        self.outputer.output_html()

if __name__ == "__main__":
    root_url = ("http://service.dice.com/api/rest/"
                "jobsearch/v1/simple.json?text=java&sort=1&page=4")
    obj_spider = SpiderMain()
    obj_spider.craw(root_url)


text:
from ..language import ast
from ..type import (GraphQLEnumType, GraphQLInputObjectType, GraphQLList,
                    GraphQLNonNull, GraphQLScalarType)

def value_from_ast(value_ast, type, variables=None):
    """Given a type and a value AST node known to match this type, build a
    runtime value."""
    if isinstance(type, GraphQLNonNull):
        # Note: we're not checking that the result of coerceValueAST is non-null.
        # We're assuming that this query has been validated and the value used here is of the correct type.
        return value_from_ast(value_ast, type.of_type, variables)

    if not value_ast:
        return None

    if isinstance(value_ast, ast.Variable):
        variable_name = value_ast.name.value
        if not variables or variable_name not in variables:
            return None

        # Note: we're not doing any checking that this variable is correct. We're assuming that this query
        # has been validated and the variable usage here is of the correct type.
        return variables[variable_name]

    if isinstance(type, GraphQLList):
        item_type = type.of_type
        if isinstance(value_ast, ast.ListValue):
            return [value_from_ast(item_ast, item_type, variables)
                    for item_ast in value_ast.values]

        else:
            return [value_from_ast(value_ast, item_type, variables)]

    if isinstance(type, GraphQLInputObjectType):
        fields = type.fields
        if not isinstance(value_ast, ast.ObjectValue):
            return None

        field_asts = {}

        for field in value_ast.fields:
            field_asts[field.name.value] = field

        obj = {}
        for field_name, field in fields.items():
            field_ast = field_asts.get(field_name)
            field_value_ast = None

            if field_ast:
                field_value_ast = field_ast.value

            field_value = value_from_ast(
                field_value_ast, field.type, variables
            )
            if field_value is None:
                field_value = field.default_value

            if field_value is not None:
                # We use out_name as the output name for the
                # dict if exists
                obj[field.out_name or field_name] = field_value

        return obj

    assert isinstance(type, (GraphQLScalarType, GraphQLEnumType)), \
        'Must be input type'

    return type.parse_literal(value_ast)


text:
package ru.job4j.map;

import org.junit.Test;

import java.util.Calendar;
import java.util.HashMap;
import java.util.Map;

/**
 * Class теста.
 * @author karetskiy
 * @since 22.05.2018
 * @version 2
 */
public class UserTest {

    /**
     * Проверяем пользователя.
     */
    @Test
    public void dontCoverEqualsAndHexCode() {

        Calendar birthday = Calendar.getInstance();
        User user1 = new User("man", 2, birthday);
        User user2 = new User("man", 2, birthday);

        Map<User, String> map = new HashMap<>();
        map.put(user1, "man");
        map.put(user2, "man");

        System.out.println(user1.equals(user2));
        System.out.println(map);
    }
}


text:
package expo.modules.notifications.notifications.interfaces;

/**
 * Interface of a singleton module responsible
 * for dispatching new remote message events to {@link NotificationListener}s.
 */
public interface NotificationManager {
  /**
   * Registers a {@link NotificationListener}.
   *
   * @param listener Listener to be notified of new message events.
   */
  void addListener(NotificationListener listener);

  /**
   * Unregisters a {@link NotificationListener}.
   *
   * @param listener Listener previously registered
   *                 with {@link NotificationManager#addListener(NotificationListener)}.
   */
  void removeListener(NotificationListener listener);
}


text:
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>io.github.gpein</groupId>
    <artifactId>jcache-jee7</artifactId>
    <version>1.1.2-SNAPSHOT</version>

    <packaging>jar</packaging>
    <name>JCache JEE7 :: ${project.artifactId} - ${project.packaging}</name>
    <description>JCache JEE7 provides support for JCache "JSR 107" in a Java EE 7 environment</description>
    <inceptionYear>2015</inceptionYear>
    <url>https://github.com/gpein/jcache-jee7</url>

    <licenses>
        <license>
            <name>Apache License, Version 2.0</name>
            <url>http://www.apache.org/licenses/LICENSE-2.0</url>
            <distribution>repo</distribution>
        </license>
    </licenses>

    <developers>
        <developer>
            <id>gpein</id>
            <name>Guillaume Pein</name>
            <email>guillaume.pein@gmail.com</email>
            <timezone>+1</timezone>
            <roles>
                <role>Java Developer</role>
            </roles>
        </developer>
    </developers>

    <scm>
        <connection>scm:git:ssh://git@github.com/gpein/jcache-jee7.git</connection>
        <developerConnection>scm:git:ssh://git@github.com/gpein/jcache-jee7.git</developerConnection>
        <url>http://github.com/gpein/jcache-jee7</url>
      <tag>HEAD</tag>
  </scm>

    <distributionManagement>
        <snapshotRepository>
            <id>ossrh</id>
            <url>https://oss.sonatype.org/content/repositories/snapshots</url>
        </snapshotRepository>
        <repository>
            <id>ossrh</id>
            <url>https://oss.sonatype.org/service/local/staging/deploy/maven2/</url>
        </repository>
    </distributionManagement>

    <properties>
        <java.version>1.8</java.version>

        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>

        <lib.cdi-api.version>1.1</lib.cdi-api.version>
        <lib.cache-api.version>1.0.0</lib.cache-api.version>
        <lib.hazelcast.version>3.6</lib.hazelcast.version>
        <lib.testng.version>6.8.7</lib.testng.version>
        <lib.weld-se-core.version>2.3.1.Final</lib.weld-se-core.version>
        <lib.deltaspike.version>1.5.1</lib.deltaspike.version>
        <lib.assertj-core.version>1.6.1</lib.assertj-core.version>
        <lib.jaxrs-api.version>2.0.1</lib.jaxrs-api.version>
        <lib.bootstrap.version>3.3.6</lib.bootstrap.version>
        <lib.jstl.version>1.2</lib.jstl.version>
        <lib.jquery.version>2.1.4</lib.jquery.version>
        <lib.javax.servlet-api.version>3.1.0</lib.javax.servlet-api.version>

        <plugin.jacoco-maven-plugin.version>0.7.5.201505241946</plugin.jacoco-maven-plugin.version>
        <plugin.maven-source-plugin.version>2.2.1</plugin.maven-source-plugin.version>
        <plugin.maven-javadoc-plugin.version>2.9.1</plugin.maven-javadoc-plugin.version>
        <plugin.maven-gpg-plugin.version>1.5</plugin.maven-gpg-plugin.version>
        <plugin.nexus-staging-maven-plugin.version>1.6.3</plugin.nexus-staging-maven-plugin.version>
        <plugin.maven-release-plugin.version>2.5.2</plugin.maven-release-plugin.version>
        <plugin.maven-compiler-plugin.version>3.3</plugin.maven-compiler-plugin.version>
    </properties>

    <build>
        <plugins>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-compiler-plugin</artifactId>
                <version>${plugin.maven-compiler-plugin.version}</version>
                <configuration>
                    <source>${java.version}</source>
                    <target>${java.version}</target>
                </configuration>
            </plugin>
            <plugin>
                <groupId>org.jacoco</groupId>
                <artifactId>jacoco-maven-plugin</artifactId>
                <version>${plugin.jacoco-maven-plugin.version}</version>
                <executions>
                    <execution>
                        <id>default-prepare-agent</id>
                        <goals>
                            <goal>prepare-agent</goal>
                        </goals>
                        <configuration>
                            <includes>
                                <include>io.github.gpein.jcache.*</include>
                            </includes>
                        </configuration>
                    </execution>
                    <execution>
                        <id>default-report</id>
                        <phase>prepare-package</phase>
                        <goals>
                            <goal>report</goal>
                        </goals>
                        <configuration>
                            <includes>
                                <include>io.github.gpein.jcache.*</include>
                            </includes>
                            <outputDirectory>${project.build.directory}/jacoco</outputDirectory>
                        </configuration>
                    </execution>
                </executions>
            </plugin>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-release-plugin</artifactId>
                <version>${plugin.maven-release-plugin.version}</version>
                <configuration>
                    <autoVersionSubmodules>true</autoVersionSubmodules>
                    <useReleaseProfile>false</useReleaseProfile>
                    <releaseProfiles>release</releaseProfiles>
                    <goals>deploy</goals>
                </configuration>
            </plugin>
        </plugins>
    </build>

    <profiles>
        <profile>
            <id>release</id>
            <activation>
                <activeByDefault>false</activeByDefault>
            </activation>
            <build>
                <plugins>
                    <plugin>
                        <groupId>org.apache.maven.plugins</groupId>
                        <artifactId>maven-source-plugin</artifactId>
                        <version>${plugin.maven-source-plugin.version}</version>
                        <executions>
                            <execution>
                                <id>attach-sources</id>
                                <goals>
                                    <goal>jar-no-fork</goal>
                                </goals>
                            </execution>
                        </executions>
                    </plugin>
                    <plugin>
                        <groupId>org.apache.maven.plugins</groupId>
                        <artifactId>maven-javadoc-plugin</artifactId>
                        <version>${plugin.maven-javadoc-plugin.version}</version>
                        <executions>
                            <execution>
                                <id>attach-javadocs</id>
                                <goals>
                                    <goal>jar</goal>
                                </goals>
                            </execution>
                        </executions>
                    </plugin>
                    <plugin>
                        <groupId>org.apache.maven.plugins</groupId>
                        <artifactId>maven-gpg-plugin</artifactId>
                        <version>${plugin.maven-gpg-plugin.version}</version>
                        <executions>
                            <execution>
                                <id>sign-artifacts</id>
                                <phase>verify</phase>
                                <goals>
                                    <goal>sign</goal>
                                </goals>
                            </execution>
                        </executions>
                    </plugin>
                    <plugin>
                        <groupId>org.sonatype.plugins</groupId>
                        <artifactId>nexus-staging-maven-plugin</artifactId>
                        <version>${plugin.nexus-staging-maven-plugin.version}</version>
                        <extensions>true</extensions>
                        <configuration>
                            <serverId>ossrh</serverId>
                            <nexusUrl>https://oss.sonatype.org/</nexusUrl>
                            <autoReleaseAfterClose>true</autoReleaseAfterClose>
                        </configuration>
                    </plugin>
                </plugins>
            </build>
        </profile>
    </profiles>

    <dependencies>
        <!-- provided-->
        <dependency>
            <groupId>javax.enterprise</groupId>
            <artifactId>cdi-api</artifactId>
            <version>${lib.cdi-api.version}</version>
            <scope>provided</scope>
        </dependency>
        <dependency>
            <groupId>javax.ws.rs</groupId>
            <artifactId>javax.ws.rs-api</artifactId>
            <version>${lib.jaxrs-api.version}</version>
            <scope>provided</scope>
        </dependency>
        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>jstl</artifactId>
            <version>${lib.jstl.version}</version>
            <scope>provided</scope>
        </dependency>
        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>javax.servlet-api</artifactId>
            <scope>provided</scope>
            <version>${lib.javax.servlet-api.version}</version>
        </dependency>

        <!-- compile -->
        <dependency>
            <groupId>javax.cache</groupId>
            <artifactId>cache-api</artifactId>
            <version>${lib.cache-api.version}</version>
        </dependency>
        <dependency>
            <groupId>org.jsr107.ri</groupId>
            <artifactId>cache-annotations-ri-cdi</artifactId>
            <version>${lib.cache-api.version}</version>
        </dependency>
        <dependency>
            <groupId>org.jsr107.ri</groupId>
            <artifactId>cache-annotations-ri-common</artifactId>
            <version>${lib.cache-api.version}</version>
        </dependency>
        <dependency>
            <groupId>com.hazelcast</groupId>
            <artifactId>hazelcast</artifactId>
            <version>${lib.hazelcast.version}</version>
        </dependency>
        <dependency>
            <groupId>org.webjars</groupId>
            <artifactId>bootstrap</artifactId>
            <version>${lib.bootstrap.version}</version>
        </dependency>
        <dependency>
            <groupId>org.webjars</groupId>
            <artifactId>jquery</artifactId>
            <version>${lib.jquery.version}</version>
        </dependency>

        <!-- test-->
        <dependency>
            <groupId>org.testng</groupId>
            <artifactId>testng</artifactId>
            <version>${lib.testng.version}</version>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>org.jboss.weld.se</groupId>
            <artifactId>weld-se-core</artifactId>
            <version>${lib.weld-se-core.version}</version>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>org.apache.deltaspike.core</groupId>
            <artifactId>deltaspike-core-api</artifactId>
            <version>${lib.deltaspike.version}</version>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>org.apache.deltaspike.core</groupId>
            <artifactId>deltaspike-core-impl</artifactId>
            <version>${lib.deltaspike.version}</version>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>org.assertj</groupId>
            <artifactId>assertj-core</artifactId>
            <version>${lib.assertj-core.version}</version>
            <scope>test</scope>
        </dependency>
    </dependencies>
</project>


text:
"""supervisorctl_restart_group -- perform a fast restart of a supervisor process group.

Usage: %s <group>

This script performs an xml rpc call to a supervisord server and requests a fast restart
of an entire process group.

The supervisord server must be configured to use the restarter plugin.
"""
import sys,socket,errno
import xmlrpclib
from supervisor.options import ClientOptions

class Controller(object):
  def __init__(self,options,stdout=sys.stdout,stderr=sys.stderr,stdin=sys.stdin):
    super(Controller,self).__init__()
    self.options = options
    self.stdout = stdout
    self.stderr = stderr
    self.stdin = stdin

  def output(self, *lines):
    lines = list(lines)
    for i,line in enumerate(lines):
      if isinstance(line,unicode):
        lines[i] = line.encode('utf-8')
    self.stdout.write('\n'.join(lines))
    self.stdout.write('\n')

  def output_error(self, *lines):
    lines = list(lines)
    for i,line in enumerate(lines):
      if isinstance(line,unicode):
        lines[i] = line.encode('utf-8')
    self.stderr.write('\n'.join(lines))
    self.stderr.write('\n')

  def get_server_proxy(self, namespace=None):
    proxy = self.options.getServerProxy()
    if namespace is None:
      return proxy
    return getattr(proxy,namespace)

  def get_restarter(self):
    return self.get_server_proxy('restarter')

  def upcheck(self):
    try:
      supervisor = self.get_server_proxy('supervisor')
      api = supervisor.getVersion() # deprecated
      from supervisor import rpcinterface
      if api != rpcinterface.API_VERSION:
        self.output(
            'Sorry, this version of supervisorctl expects to '
            'talk to a server with API version %s, but the '
            'remote version is %s.' % (rpcinterface.API_VERSION, api))
        return False
    except xmlrpclib.Fault, e:
      if e.faultCode == xmlrpc.Faults.UNKNOWN_METHOD:
        self.output(
            'Sorry, supervisord responded but did not recognize '
            'the supervisor namespace commands that supervisorctl '
            'uses to control it.  Please check that the '
            '[rpcinterface:supervisor] section is enabled in the '
            'configuration file (see sample.conf).')
        return False
      raise
    except socket.error, why:
      if why[0] == errno.ECONNREFUSED:
        self.output('%s refused connection' % self.options.serverurl)
        return False
      elif why[0] == errno.ENOENT:
        self.output('%s no such file' % self.options.serverurl)
        return False
      raise
    return True

def send_restart(group,restarter=None,options=None,ctl=None):
  try:
    result = restarter.restartProcessGroup(group)
  except xmlrpclib.Fault, e:
    ctl.output_error('%s: ERROR (%s)' % (group,e.faultString))
    sys.exit(2)
  except socket.error, e:
    if e[0] == errno.ECONNREFUSED:
      ctl.output_error('%s: refused connection' % options.serverurl)
    elif e[0] == errno.ENOENT:
      ctl.output_error('%s: no such file' % options.serverurl)
    else:
      raise
    sys.exit(1)
  else:
    return result

def main(args=None,options=None):
  if options is None:
    options = ClientOptions()
  options.realize(args,doc=__doc__)
  ctl = Controller(options)
  if len(options.args) != 1:
    ctl.output_error('Invalid number of arguments (expected 1, got %d)' % len(options.args))
    sys.exit(5)
  ctl.upcheck()

  group = options.args[0].strip()
  restarter = ctl.get_restarter()
  result = None

  while 1:
    try:
      result = send_restart(group,options=options,ctl=ctl,restarter=restarter)
    except xmlrpclib.ProtocolError,e:
      if e.errcode == 401:
        if options.interactive:
          from getpass import getpass
          ctl.output('Server requires authentication')
          username = raw_input('Username:')
          password = getpass(prompt='Password:')
          ctl.output('')
          options.username = username
          options.password = password
          continue
        else:
          options.usage('Server requires authentication')
      else:
        ctl.output_error('%s: protocol error (%s)' % (group,e))
        sys.exit(10)
    break

  if result:
    if isinstance(result,(list,tuple)):
      for e in result:
        ctl.output_error('ERROR (%s)' % e['text'])
      sys.exit(len(result))
    ctl.output('%s: restarted' % group)
  else:
    ctl.output('%s: unknown state, server did not send a response' % group)

if __name__ == '__main__':
  main(sys.argv[1:])


text:
package com.jrefinery.chart;

import java.awt.event.*;
import javax.swing.*;

/**
 * A frame for displaying a chart.
 */
public class JFreeChartFrame extends JFrame {

    /**
     * Constructs a frame for a chart.
     * @param title The frame title.
     * @param chart The chart.
     */
    public JFreeChartFrame(String title, JFreeChart chart) {
        this(title, chart, false);
    }

    /**
     * Constructs a frame for a chart.
     * @param title The frame title.
     * @param chart The chart.
     */
    public JFreeChartFrame(String title, JFreeChart chart, boolean scrollPane) {
        super(title);
        JFreeChartPanel content = new JFreeChartPanel(chart);
        if (scrollPane) {
            this.setContentPane(new JScrollPane(content));
        }
        else this.setContentPane(content);

    }

}


text:
<?php

/**
 * InvalidClassException.php
 *
 * @author David Yell <neon1024@gmail.com>
 */

namespace Proffer\Exception;

use Exception;

class InvalidClassException extends Exception
{

}


text:
<!--
  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. See accompanying LICENSE file.
-->

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
  <modelVersion>4.0.0</modelVersion>
  <parent>
    <groupId>jp.co.yahoo.dataplatform.mds</groupId>
    <artifactId>multiple-dimension-spread-base</artifactId>
    <version>0.8.11_hive-1.2.1000.2.6.4.0-91</version>
    <relativePath>../pom.xml</relativePath>
  </parent>

  <artifactId>multiple-dimension-spread-example</artifactId>
  <packaging>jar</packaging>
  <name>multiple dimension spread example</name>
  <description>Examples using Multiple-Dimension-Spread</description>

  <dependencies>
    <dependency>
      <groupId>jp.co.yahoo.dataplatform.mds</groupId>
      <artifactId>multiple-dimension-spread-common</artifactId>
      <version>${project.version}</version>
    </dependency>
    <dependency>
      <groupId>jp.co.yahoo.dataplatform.mds</groupId>
      <artifactId>multiple-dimension-spread-common</artifactId>
      <version>${project.version}</version>
      <classifier>tests</classifier>
      <scope>test</scope>
    </dependency>
    <dependency>
      <groupId>jp.co.yahoo.dataplatform.mds</groupId>
      <artifactId>multiple-dimension-spread-schema</artifactId>
      <version>${project.version}</version>
    </dependency>
    <dependency>
      <groupId>jp.co.yahoo.dataplatform.schema</groupId>
      <artifactId>schema-common</artifactId>
      <version>${schemalibVersion}</version>
    </dependency>
    <dependency>
      <groupId>jp.co.yahoo.dataplatform.config</groupId>
      <artifactId>dataplatform-common-config</artifactId>
      <version>${configlibVersion}</version>
    </dependency>
    <dependency>
      <groupId>com.fasterxml.jackson.core</groupId>
      <artifactId>jackson-databind</artifactId>
      <version>2.9.8</version>
      <optional>true</optional>
    </dependency>
    <dependency>
      <groupId>com.beust</groupId>
      <artifactId>jcommander</artifactId>
      <version>1.30</version>
      <scope>test</scope>
      <optional>true</optional>
    </dependency>
  </dependencies>

  <properties>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
  </properties>

  <build>
    <plugins>
      <plugin>
        <groupId>org.apache.rat</groupId>
        <artifactId>apache-rat-plugin</artifactId>
        <configuration>
          <excludes>
            <exclude>**/*.json</exclude>
            <exclude>src/main/resources/sample_json.txt</exclude>
            <exclude>src/main/resources/sample_expand_json.txt</exclude>
          </excludes>
        </configuration>
      </plugin>
    </plugins>
  </build>

</project>


text:
class Page < ActiveRecord::Base
  has_many :daily_timelines
  has_one :daily_trend
  has_one :monthly_trend
  has_many :daily_page_views, :order => "date"

  BOSSMan.application_id = APP_CONFIG['yahoo_boss_id']

  def normed_daily_pageviews(on_date, range=30)
    logger.debug("Date = #{on_date}")
    timeline = self.daily_timelines.where("on_date = ?", on_date).first
    @pageviews = timeline.pageviews.split("\002").map{ |x| x.to_i }
    @dates = timeline.dates.split("\002")
    date_view_hash = {}
    logger.debug("#{@dates.inspect}")

      @dates.each_with_index do |date, index|
      date_view_hash[date] = @pageviews[index]
    end
    logger.debug("#{date_view_hash.inspect}")
    sorted_pageviews = []
    date_view_hash.keys.sort.each { |key| sorted_pageviews << date_view_hash[key] }
    range = sorted_pageviews.length
    maxval = sorted_pageviews[-range,range].max
    normed_values = sorted_pageviews[-range,range].collect { |x| x * (110.0 / maxval)}
    return normed_values
  end

  def find_total_pageviews(on_date)
    timeline = self.daily_timelines.where("on_date = ?", on_date).first
    @pageviews = timeline.pageviews.split("\002").map{ |x| x.to_i }
    return @pageviews.inject(0,:+)
  end

  def linechart( on_date, fillcolor='8fc800', range=30)
    dataset = GC4R::API::GoogleChartDataset.new :data => self.normed_daily_pageviews(on_date,range),
      :color => '888888', :fill => ['B', fillcolor ,'0','0','0']
    # red => FF0000
    # lightblue => 76A4FB
    # green => 33FF00
    # darkblue => 0000FF
    data = GC4R::API::GoogleChartData.new :datasets => dataset , :min => 0, :max => 120
    # @chart = GoogleBarChart.new :width => 120, :height => 12
    @chart = GC4R::API::GoogleLineChart.new :width => 620, :height => 280
    @chart.data = data
    return @chart
  end

  def sparkline( on_date, fillcolor='8fc800', range=30)
    dataset = GC4R::API::GoogleChartDataset.new :data => self.normed_daily_pageviews(on_date,range),
      :color => '888888', :fill => ['B', fillcolor ,'0','0','0']
    # red => FF0000
    # lightblue => 76A4FB
    # green => 33FF00
    # darkblue => 0000FF
    data = GC4R::API::GoogleChartData.new :datasets => dataset , :min => 0, :max => 120
    # @chart = GoogleBarChart.new :width => 120, :height => 12
    @chart = GC4R::API::GoogleSparklinesChart.new :width => 120, :height => 15
    @chart.data = data
    return @chart
  end

  def sorted_dates(on_date)
   timeline = self.daily_timelines.where("on_date = ?", on_date).first
   rawdates = timeline.dates.split("\002")
   @data = []
   rawdates.each do |date|
     @data << DateTime.strptime( date.to_s, "%Y%m%d")
   end
   @data.sort
 end

 def date_pageview_array(on_date)
    timeline = self.daily_timelines.where("on_date = ?", on_date).first
    rawdates = timeline.dates.split("\002")
    pageviews = timeline.pageviews.split("\002").map{ |x| x.to_i }
    @data = []
    rawdates.each_with_index do |date, index|
      @data << [DateTime.strptime( date.to_s, "%Y%m%d").strftime('%D'), pageviews[index]]
    end
   return @data
 end

  def timeline(on_date)
    timeline = self.daily_timelines.where("on_date = ?", on_date).first
    rawdates = timeline.dates.split("\002")
    pageviews = timeline.pageviews.split("\002").map{ |x| x.to_i }

    @data ={}
    rawdates.each_with_index do |date, index|
      @data[DateTime.strptime( date.to_s, "%Y%m%d")] = {:wikipedia_page_views => pageviews[index]}
    end
    return @data
  end

  def sorted_dates_old
  @data = []
  self.daily_page_views.each do |dpv|
    @data << DateTime.strptime( dpv.date.to_s, "%Y%m%d")
  end
  @data.sort
  end

  def date_pageview_array_old
   @data = []
   self.daily_page_views.each do |dpv|
     @data << [DateTime.strptime( dpv.date.to_s, "%Y%m%d").strftime('%D'), dpv.pageviews]
   end
   return @data
 end

def timeline_old
  @data ={}
  self.daily_page_views.each do |dpv|
    @data[DateTime.strptime( dpv.date.to_s, "%Y%m%d")] = {:wikipedia_page_views => dpv.pageviews}
  end
  return @data
end

def normed_daily_pageviews_old( range=30)
  date_view_hash = {}
  self.daily_page_views.each do |dpv|
    date_view_hash[dpv.date] = dpv.pageviews
  end
  logger.debug("#{date_view_hash.inspect}")
  sorted_pageviews = []
  date_view_hash.keys.sort.each { |key| sorted_pageviews << date_view_hash[key] }
  logger.debug("#{sorted_pageviews.inspect}")
  maxval = sorted_pageviews[-range,range].max
  normed_values = sorted_pageviews[-range,range].collect { |x| x * (110.0 / maxval)}
  return normed_values
end

end


text:
@implementation MockBIHandlerTableView

#pragma mark - UIScrollViewDelegate methods

- (void)scrollViewWillEndDragging:(nonnull UIScrollView *)scrollView withVelocity:(CGPoint)velocity targetContentOffset:(inout nonnull CGPoint *)targetContentOffset {
    if (self.scrollViewWillEndDraggingCallback) {
        self.scrollViewWillEndDraggingCallback(scrollView, velocity, targetContentOffset);
    }
}

@end


text:
import {
  flatten,
  unique,
} from './util'

export function teamFormationPlanToString(plan) {
  return plan.teams.map(({goalDescriptor, teamSize, memberIds}) => {
    const memberIdPrefixes = memberIds.map(id => id.slice(0, 7))
    const goalDescriptorSuffix = goalDescriptor.split('/').pop()

    return `(${goalDescriptorSuffix}:${teamSize})[${memberIdPrefixes.sort() || ''}]`
  }).join(', ')
}

export function getAssignedMemberIds(teamFormationPlan) {
  return unique(flatten(
    teamFormationPlan.teams.map(({memberIds}) => memberIds)
  ))
}


text:
<?php

namespace Mackstar\Spout\Module\Di;

use Doctrine\Common\Cache\ApcCache;
use Doctrine\Common\Cache\FilesystemCache;
use Ray\Di\DiCompiler;
use Ray\Di\ProviderInterface;
use Ray\Di\Di\Inject;
use Ray\Di\Di\Named;

class DiCompilerProvider implements ProviderInterface
{
    /**
     * @var string
     */
    private $appName;

    /**
     * @var string
     */
    private $context;

    /**
     * @var string
     */
    private $tmpDir;

    /**
     * @var string
     */
    private $apps;

    /**
     * @var \Ray\Di\DiCompiler
     */
    private static $compiler;

    /**
     * @var \Ray\Di\AbstractModule[]
     */
    private static $module;

    /**
     * @param string $appName
     * @param mixed $context
     * @param string $tmpDir
     *
     * @Inject
     * @Named("appName=app_name,context=app_context,tmpDir=tmp_dir,apps=apps")
     */
    public function __construct($appName, $context, $tmpDir, $apps)
    {
        $this->appName = $appName;
        $this->context = $context;
        $this->tmpDir = $tmpDir;
        $this->apps = $apps;
    }

    /**
     * {@inheritdoc}
     * @return \Ray\Di\DiCompiler
     */
    public function get($extraCacheKey = '')
    {
        $contextKey = is_array($this->context)? implode('_', $this->context) : $this->context;
        $saveKey = $this->appName . $contextKey;
        if (isset(self::$compiler[$saveKey])) {
            return self::$compiler[$saveKey];
        }
        $apps = $this->apps;

        $moduleProvider = function () use ($saveKey, $apps) {
            // avoid infinite loop
            if (isset(self::$module[$saveKey])) {
                return self::$module[$saveKey];
            }
            $appModule = "{$this->appName}\Module\AppModule";
            self::$module[$saveKey] = new $appModule($this->context, $apps);

            return self::$module[$saveKey];
        };

        $cacheKey = $this->appName . $contextKey . $extraCacheKey;
        $cache = function_exists('apc_fetch')? new ApcCache : new FilesystemCache($this->tmpDir);
        self::$compiler[$saveKey] = $compiler = DiCompiler::create($moduleProvider, $cache, $cacheKey, $this->tmpDir);

        return $compiler;
    }
}


text:
/*
 * Orange angular-swagger-ui - v0.2.3
 *
 * (C) 2015 Orange, all right reserved
 * MIT Licensed
 */
angular
  .module('swaggerUi')
  .directive('swaggerUi', ['$injector', function($injector) {

    return {
      restrict: 'A',
      controller: 'swaggerUiController',
      templateUrl: 'common/directives/swagger-ui/swagger-ui.tpl.html',
      scope: {
        // Swagger descriptor URL (string, required)
        url: '=',
        // Swagger descriptor parser type (string, optional, default = "auto")
        // Built-in allowed values:
        // 		"auto": (default) parser is based on response Content-Type
        //		"json": force using JSON parser
        //
        //	More types could be defined by external modules
        parser: '@?',
        // Swagger descriptor loading indicator (variables, optional)
        loading: '=?',
        // Use permalinks? (boolean, optional, default = false)
        // If true and if using $routeProvider, should set 'reloadOnSearch: false' in route
        // configuration to avoid UI being rendered multiple times
        permalinks: '=?',
        // Display API explorer (boolean, optional, default = false)
        apiExplorer: '=?',
        // Error handler (function, optional)
        errorHandler: '=?',
        // Are Swagger descriptors loaded from trusted source only ? (boolean, optional, default = false)
        // If true, it avoids using ngSanitize but consider HTML as trusted so won't be cleaned
        trustedSources: '=?'
      },
      link: function(scope) {
        // check parameters
        if (scope.permalinks && $injector.has('$route')) {
          var $route = $injector.get('$route','swaggerUi');
          if ($route.current && $route.current.$$route && $route.current.$$route.reloadOnSearch) {
            console.warn('AngularSwaggerUI: when using permalinks you should set reloadOnSearch=false in your route config to avoid UI being rebuilt multiple times');
          }
        }
        if (!scope.trustedSources && !$injector.has('$sanitize')) {
          console.warn('AngularSwaggerUI: you must use ngSanitize OR set trusted-sources=true as directive param if swagger descriptor are loaded from trusted sources');
        }
      }
    };
  }])
  .controller('swaggerUiController', ['$scope', '$http', '$location', '$q', 'swaggerClient', 'swaggerModules', 'swagger2JsonParser',
    function($scope, $http, $location, $q, swaggerClient, swaggerModules, swagger2JsonParser) {

      var swagger;

      // WARNING authentication is not implemented, please use 'api-explorer-transform' directive's param to customize API calls

      // add default Swagger parser (JSON)
      swaggerModules.add(swaggerModules.PARSE, swagger2JsonParser);

      /**
       * Load Swagger descriptor
       */
      function loadSwagger(url, callback) {
        $scope.loading = true;
        var options = {
          method: 'GET',
          url: url
        };
        swaggerModules
          .execute(swaggerModules.BEFORE_LOAD, options)
          .then(function() {
            $http(options)
              .success(callback)
              .error(function(data, status) {
                onError({
                  code: status,
                  message: data
                });
              });
          })
          .catch(onError);
      }

      /**
       * Swagger descriptor has been loaded, launch parsing
       */
      function swaggerLoaded(swaggerType) {
        $scope.loading = false;
        var parseResult = {};
        // execute modules
        $scope.parser = $scope.parser || 'auto';
        swaggerModules
          .execute(swaggerModules.PARSE, $scope.parser, swaggerType, swagger, $scope.trustedSources, parseResult)
          .then(function(executed) {
            if (executed) {
              swaggerParsed(parseResult);
            } else {
              onError({
                code: 415,
                message: 'no parser found for Swagger descriptor of type ' + swaggerType + ' and version ' + swagger.swagger
              });
            }
          })
          .catch(onError);
      }

      /**
       * Swagger descriptor has parsed, launch display
       */
      function swaggerParsed(parseResult) {
        // execute modules
        swaggerModules
          .execute(swaggerModules.BEFORE_DISPLAY, parseResult)
          .then(function() {
            // display swagger UI
            $scope.infos = parseResult.infos;
            $scope.form = parseResult.form;
            $scope.resources = parseResult.resources;
          })
          .catch(onError);
      }

      function onError(error) {
        $scope.loading = false;
        if (typeof $scope.errorHandler === 'function') {
          $scope.errorHandler(error.message, error.code);
        } else {
          console.error(error.code, 'AngularSwaggerUI: ' + error.message);
        }
      }

      $scope.$watch('url', function(url) {
        //reset
        $scope.infos = {};
        $scope.resources = [];
        $scope.form = {};
        if (url && url !== '') {
          if ($scope.loading) {
            //TODO cancel current loading swagger
          }
          // load Swagger descriptor
          loadSwagger(url, function(data, status, headers) {
            swagger = data;
            // execute modules
            swaggerModules
              .execute(swaggerModules.BEFORE_PARSE, url, swagger)
              .then(function() {
                var contentType = headers()['content-type'] || 'application/json',
                  swaggerType = contentType.split(';')[0];

                swaggerLoaded(swaggerType);
              })
              .catch(onError);
          });
        }
      });

      /**
       * show all resource's operations as list or as expanded list
       */
      $scope.expand = function(resource, expandOperations) {
        resource.open = true;
        for (var i = 0, op = resource.operations, l = op.length; i < l; i++) {
          op[i].open = expandOperations;
        }
      };

      $scope.permalink = function(name) {
        if ($scope.permalinks) {
          $location.search('swagger', name);
        }
      };

      /**
       * sends a sample API request
       */
      $scope.submitExplorer = function(operation) {
        operation.loading = true;
        swaggerClient
          .send(swagger, operation, $scope.form[operation.id])
          .then(function(result) {
            operation.loading = false;
            operation.explorerResult = result;
          });
      };

    }
  ])
  .directive('fileInput', function() {
    // helper to be able to retrieve HTML5 File in ngModel from input
    return {
      restrict: 'A',
      require: 'ngModel',
      link: function(scope, element, attr, ngModel) {
        element.bind('change', function() {
          scope.$apply(function() {
            //TODO manage multiple files ?
            ngModel.$setViewValue(element[0].files[0]);
          });
        });
      }
    };
  });


text:
<?php

namespace Studiow\ValueObject\Test\Web;

use PHPUnit\Framework\TestCase;
use InvalidArgumentException;
use Studiow\ValueObject\Web\EmailAddress;

class EmailAddressTest extends TestCase
{
    public function testCreateObject()
    {
        $obj = new EmailAddress("test@example.com");
        $this->assertEquals("test@example.com", $obj->getValue());
    }

    public function testNormalizeInput()
    {
        $obj = new EmailAddress("TEST@example.com");
        $this->assertEquals("test@example.com", $obj->getValue());
    }

    public function testValidateInput()
    {
        $this->expectException(InvalidArgumentException::class);
        $obj = new EmailAddress("test-example.com");
    }
}


text:
package common_test

import (
	"fmt"
	"github.com/APTrust/exchange/partner_apps/common"
	"github.com/APTrust/exchange/util/fileutil"
	"github.com/stretchr/testify/assert"
	"github.com/stretchr/testify/require"
	"os"
	"path/filepath"
	"strings"
	"testing"
)

func TestLoadPartnerConfigGood(t *testing.T) {
	filePath, err := fileutil.RelativeToAbsPath(filepath.Join("testdata", "config", "partner_config_valid.conf"))
	require.Nil(t, err)
	partnerConfig, err := common.LoadPartnerConfig(filePath)
	require.Nil(t, err)
	assert.Equal(t, "123456789XYZ", partnerConfig.AwsAccessKeyId)
	assert.Equal(t, "THIS KEY INCLUDES SPACES AND DOES NOT NEED QUOTES", partnerConfig.AwsSecretAccessKey)

	assert.Equal(t, "aptrust.receiving.testbucket.edu", partnerConfig.ReceivingBucket)
	assert.Equal(t, "aptrust.restore.testbucket.edu", partnerConfig.RestorationBucket)
}

func TestLoadPartnerConfigWrongFileType(t *testing.T) {
	filePath, err := fileutil.RelativeToAbsPath(filepath.Join("testdata", "config", "intel_obj.json"))
	require.Nil(t, err)
	_, err = common.LoadPartnerConfig(filePath)
	require.NotNil(t, err)
}

func TestLoadPartnerConfigMissingFile(t *testing.T) {
	filePath, err := fileutil.RelativeToAbsPath(filepath.Join("testdata", "config", "_non_existent_file.conf_"))
	require.Nil(t, err)
	_, err = common.LoadPartnerConfig(filePath)
	require.NotNil(t, err)
}

func TestLoadAwsFromEnv(t *testing.T) {
	if os.Getenv("AWS_ACCESS_KEY_ID") == "" || os.Getenv("AWS_SECRET_ACCESS_KEY") == "" {
		fmt.Println("Skipping AWS env test. Env vars are not set.")
		return
	}
	filePath, err := fileutil.RelativeToAbsPath(filepath.Join("testdata", "config", "partner_config_invalid.conf"))
	require.Nil(t, err)

	partnerConfig, err := common.LoadPartnerConfig(filePath)
	require.Nil(t, err)

	if partnerConfig.AwsAccessKeyId != "" {
		t.Errorf("Test precondition is invalid. AwsAccessKeyId has a value.")
	}
	if partnerConfig.AwsSecretAccessKey != "" {
		t.Errorf("Test precondition is invalid. AwsSecretAccessKey has a value.")
	}
	partnerConfig.LoadAwsFromEnv()
	assert.NotEmpty(t, partnerConfig.AwsAccessKeyId)
	assert.NotEmpty(t, partnerConfig.AwsSecretAccessKey)
}

func TestLoadPartnerConfigBad(t *testing.T) {
	filePath, err := fileutil.RelativeToAbsPath(filepath.Join("testdata", "config", "partner_config_invalid.conf"))
	require.Nil(t, err)
	partnerConfig, err := common.LoadPartnerConfig(filePath)
	require.Nil(t, err)
	// Make sure we get warnings on unexpected settings and on
	// expected settings that are not there.
	warnings := partnerConfig.Warnings()
	assert.Equal(t, 7, len(warnings))
	assert.Equal(t, "Invalid setting: FavoriteTeam = The home team", warnings[0])
	assert.Equal(t, "Invalid setting: FavoriteFlavor = Green", warnings[1])
	assert.True(t, strings.HasPrefix(warnings[2], "AwsAccessKeyId"),
		"Did not get expected warning about invalid setting")
	assert.True(t, strings.HasPrefix(warnings[2], "AwsAccessKeyId"),
		"Did not get expected warning about missing AwsAccessKeyId")
	assert.True(t, strings.HasPrefix(warnings[3], "AwsSecretAccessKey is missing"),
		"Did not get expected warning about missing AwsSecretAccessKey")
	assert.True(t, strings.HasPrefix(warnings[4], "ReceivingBucket is missing"),
		"Did not get expected warning about missing ReceivingBucket")
	assert.True(t, strings.HasPrefix(warnings[5], "RestorationBucket is missing"),
		"Did not get expected warning about missing RestorationBucket")
	assert.True(t, strings.HasPrefix(warnings[6], "DownloadDir is missing"),
		"Did not get expected warning about missing DownloadDir")
}

func TestPartnerConfigValidate(t *testing.T) {
	partnerConfig := &common.PartnerConfig{
		AwsAccessKeyId:     "abc",
		AwsSecretAccessKey: "xyz",
		ReceivingBucket:    "aptrust.receiving.xyz.edu",
		RestorationBucket:  "aptrust.receiving.xyz.edu",
		DownloadDir:        "/home/josie/tmp",
	}

	// Clear these out for this test, so PartnerConfig can't read them.
	// We want to see that validation fails when these are missing.
	awsKey := os.Getenv("AWS_ACCESS_KEY_ID")
	awsSecret := os.Getenv("AWS_SECRET_ACCESS_KEY")
	os.Setenv("AWS_ACCESS_KEY_ID", "")
	os.Setenv("AWS_SECRET_ACCESS_KEY", "")
	// And make sure we restore them...
	defer os.Setenv("AWS_ACCESS_KEY_ID", awsKey)
	defer os.Setenv("AWS_SECRET_ACCESS_KEY", awsSecret)

	// Validation should fail on missing AWS credentials
	// and/or missing receiving bucket.
	partnerConfig.AwsAccessKeyId = ""
	err := partnerConfig.Validate()
	assert.NotNil(t, err, "Validation should have failed on missing Access Key")

	partnerConfig.AwsAccessKeyId = "abc"
	partnerConfig.AwsSecretAccessKey = ""
	err = partnerConfig.Validate()
	assert.NotNil(t, err, "Validation should have failed on missing Secret Key")

	partnerConfig.AwsSecretAccessKey = "xyz"
	partnerConfig.ReceivingBucket = ""
	err = partnerConfig.Validate()
	assert.NotNil(t, err, "Validation should have failed on missing Receiving Bucket")

	partnerConfig.ReceivingBucket = "123"
	partnerConfig.RestorationBucket = ""
	err = partnerConfig.Validate()
	assert.NotNil(t, err, "Validation should have failed on missing Restoration Bucket")

	partnerConfig.RestorationBucket = "blah"
	partnerConfig.DownloadDir = ""
	err = partnerConfig.Validate()
	assert.NotNil(t, err, "Validation should have failed on missing DownloadDir")
}