text:
/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/*
 * AboutBox.java
 *
 * Created on 06-Jun-2011, 23:37:15
 */

package org.twak.siteplan.campskeleton;

import java.awt.Dialog;
import java.awt.Dialog.ModalExclusionType;
import java.awt.Graphics;
import java.awt.image.BufferedImage;
import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Scanner;
import java.util.logging.Level;
import java.util.logging.Logger;

import javax.swing.SwingUtilities;

import org.twak.utils.ImageU;
import org.twak.utils.WebU;
import org.twak.utils.ui.ImageComponent;
import org.twak.utils.ui.WindowManager;

/**
 *
 * @author twak
 */
public class AboutBox extends javax.swing.JFrame {

    /** Creates new form AboutBox */
    public AboutBox() {
        try {
            initComponents();
            BufferedReader br = new BufferedReader(new InputStreamReader(getClass().
            		getResourceAsStream("/org/twak/siteplan/resources/help.txt")));
            StringBuffer sb = new StringBuffer();
            while (br.ready()) {
                sb.append(br.readLine()+"\n");
            }
            logoBox.image = ImageU.cacheResource.get( "/org/twak/siteplan/resources/icon256.png" );
            helpTextBox.setText(sb.toString());
            setSize(getPreferredSize());
            WindowManager.register(this);
            setVisible(true);
            setModalExclusionType(ModalExclusionType.APPLICATION_EXCLUDE);

            SwingUtilities.invokeLater( new Runnable() {

				@Override
				public void run() {
					jScrollPane1.getVerticalScrollBar().setValue( 0 );
				}
			} );

        } catch (Throwable ex) {
            ex.printStackTrace();
        }
    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jButton1 = new javax.swing.JButton();
        jScrollPane1 = new javax.swing.JScrollPane();
        helpTextBox = new javax.swing.JTextPane();
        logoBox = new ImageComponent();

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);

        jButton1.setText("online help");
        jButton1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton1ActionPerformed(evt);
            }
        });

        helpTextBox.setEditable(false);
        helpTextBox.setText("The contents of the help file will be shown here\n\nhello 2");
        jScrollPane1.setViewportView(helpTextBox);

        javax.swing.GroupLayout logoBoxLayout = new javax.swing.GroupLayout(logoBox);
        logoBox.setLayout(logoBoxLayout);
        logoBoxLayout.setHorizontalGroup(
            logoBoxLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGap(0, 281, Short.MAX_VALUE)
        );
        logoBoxLayout.setVerticalGroup(
            logoBoxLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGap(0, 233, Short.MAX_VALUE)
        );

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                    .addComponent(jScrollPane1, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, 283, Short.MAX_VALUE)
                    .addComponent(logoBox, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addComponent(jButton1, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, 283, Short.MAX_VALUE))
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(logoBox, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 195, Short.MAX_VALUE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(jButton1)
                .addContainerGap())
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed
        WebU.showBrowser("https://github.com/twak/siteplan/blob/wiki/Help.md");
    }//GEN-LAST:event_jButton1ActionPerformed

    /**
    * @param args the command line arguments
    */
    public static void main(String args[]) {
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new AboutBox().setVisible(true);
            }
        });
    }

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JTextPane helpTextBox;
    private javax.swing.JButton jButton1;
    private javax.swing.JScrollPane jScrollPane1;
    private ImageComponent logoBox;
    // End of variables declaration//GEN-END:variables

}


text:
package co.cask.cdap.proto.id;

import co.cask.cdap.proto.Id;
import co.cask.cdap.proto.ProgramType;
import co.cask.cdap.proto.element.EntityType;

import java.util.Arrays;
import java.util.Collections;
import java.util.Iterator;
import java.util.Objects;

/**
 * Uniquely identifies a flowlet.
 */
public class FlowletId extends NamespacedEntityId implements ParentedId<ProgramId> {
  private final String application;
  private final String version;
  private final String flow;
  private final String flowlet;
  private transient Integer hashCode;

  public FlowletId(String namespace, String application, String flow, String flowlet) {
    this(new ApplicationId(namespace, application), flow, flowlet);
  }

  public FlowletId(ApplicationId appId, String flow, String flowlet) {
    super(appId.getNamespace(), EntityType.FLOWLET);
    if (flow == null) {
      throw new NullPointerException("Flow cannot be null");
    }
    if (flowlet == null) {
      throw new NullPointerException("Flowlet cannot be null");
    }
    this.application = appId.getApplication();
    this.version = appId.getVersion();
    this.flow = flow;
    this.flowlet = flowlet;
  }

  public String getApplication() {
    return application;
  }

  public String getVersion() {
    return version;
  }

  public String getFlow() {
    return flow;
  }

  public String getFlowlet() {
    return flowlet;
  }

  @Override
  public String getEntityName() {
    return getFlowlet();
  }

  @Override
  public ProgramId getParent() {
    return new ProgramId(new ApplicationId(getNamespace(), getApplication(), getVersion()),
                         ProgramType.FLOW, getFlow());
  }

  @Override
  public boolean equals(Object o) {
    if (!super.equals(o)) {
      return false;
    }
    FlowletId flowletId = (FlowletId) o;
    return Objects.equals(getParent(), flowletId.getParent()) &&
      Objects.equals(flowlet, flowletId.flowlet);
  }

  @Override
  public int hashCode() {
    Integer hashCode = this.hashCode;
    if (hashCode == null) {
      this.hashCode = hashCode = Objects.hash(super.hashCode(), getNamespace(), getApplication(), getVersion(),
                                              getFlow(), flowlet);
    }
    return hashCode;
  }

  public FlowletQueueId queue(String queue) {
    // Note: FlowletQueueId is not versioned
    return new FlowletQueueId(getNamespace(), getApplication(), getFlow(), flowlet, queue);
  }

  @SuppressWarnings("unused")
  public static FlowletId fromIdParts(Iterable<String> idString) {
    Iterator<String> iterator = idString.iterator();
    return new FlowletId(
      new ApplicationId(next(iterator, "namespace"), next(iterator, "application"), next(iterator, "version")),
      next(iterator, "flow"), nextAndEnd(iterator, "flowlet"));
  }

  @Override
  protected Iterable<String> toIdParts() {
    return Collections.unmodifiableList(Arrays.asList(getNamespace(), getApplication(), getVersion(),
                                                      getFlow(), flowlet));
  }

  @Override
  public Id.Flow.Flowlet toId() {
    return Id.Flow.Flowlet.from(Id.Application.from(getNamespace(), getApplication()), getFlow(), flowlet);
  }

  public static FlowletId fromString(String string) {
    return EntityId.fromString(string, FlowletId.class);
  }
}

redpajama_set_name: RedPajamaGithub


text:
Finds the first index of the specified element in a list.
### Time complexity
    worst:   O(n)
    average: O(n)
    best:    O(n)


text:
package framework.opengl;

public class OpenglTextureUnit {
	public String textureName;
	public int[] textureGL_ID;
	public int height;
	public int width;
}


text:
ACCEPTED

#### According to
Integrated Taxonomic Information System

#### Published in
null

#### Original name
Aspilia reticulata Baker

### Remarks
null


text:
import { PropTypes } from 'react';
import includes from 'lodash/includes';

import { SCREEN_SIZES, LARGER_SCREEN_SIZES, SCREEN_ORIENTATIONS } from '../util/constants';
import createWrapperComponent from '../util/create-wrapper-component';
import styles from './_styles.scss';

export const ShowForScreenSize = createWrapperComponent({
  displayName: 'ShowForScreenSize',
  styles,
  propTypes: {
    screenSize: PropTypes.oneOf(SCREEN_SIZES).isRequired,
  },
  mapProps: ({ screenSize, ...props }) => ({
    props,
    classNames: {
      [`show-for-${screenSize}`]: includes(LARGER_SCREEN_SIZES, screenSize),
    },
  }),
});

export const ShowOnlyForScreenSize = createWrapperComponent({
  displayName: 'ShowOnlyForScreenSize',
  styles,
  propTypes: {
    screenSize: PropTypes.oneOf(SCREEN_SIZES).isRequired,
  },
  mapProps: ({ screenSize, ...props }) => ({
    props,
    classNames: {
      [`show-for-${screenSize}-only`]: includes(SCREEN_SIZES, screenSize),
    },
  }),
});

export const HideForScreenSize = createWrapperComponent({
  displayName: 'HideForScreenSize',
  styles,
  propTypes: {
    screenSize: PropTypes.oneOf(SCREEN_SIZES).isRequired,
  },
  mapProps: ({ screenSize, ...props }) => ({
    props,
    classNames: {
      hide: !includes(LARGER_SCREEN_SIZES, screenSize) && includes(SCREEN_SIZES, screenSize),
      [`hide-for-${screenSize}`]: includes(LARGER_SCREEN_SIZES, screenSize),
    },
  }),
});

export const HideOnlyForScreenSize = createWrapperComponent({
  displayName: 'HideOnlyForScreenSize',
  styles,
  propTypes: {
    screenSize: PropTypes.oneOf(SCREEN_SIZES).isRequired,
  },
  mapProps: ({ screenSize, ...props }) => ({
    props,
    classNames: {
      [`hide-for-${screenSize}-only`]: includes(SCREEN_SIZES, screenSize),
    },
  }),
});

export const Hide = createWrapperComponent({
  displayName: 'Hide',
  styles,
  mapProps: props => ({
    props,
    classNames: 'hide',
  }),
});

export const Invisible = createWrapperComponent({
  displayName: 'Invisible',
  styles,
  mapProps: props => ({
    props,
    classNames: 'invisible',
  }),
});

export const ShowForScreenOrientation = createWrapperComponent({
  displayName: 'ShowForScreenOrientation',
  styles,
  propTypes: {
    screenOrientation: PropTypes.oneOf(SCREEN_ORIENTATIONS).isRequired,
  },
  mapProps: ({ screenOrientation, ...props }) => ({
    props,
    classNames: {
      [`show-for-${screenOrientation}`]: includes(SCREEN_ORIENTATIONS, screenOrientation),
    },
  }),
});

export const HideForScreenOrientation = createWrapperComponent({
  displayName: 'HideForScreenOrientation',
  styles,
  propTypes: {
    screenOrientation: PropTypes.oneOf(SCREEN_ORIENTATIONS).isRequired,
  },
  mapProps: ({ screenOrientation, ...props }) => ({
    props,
    classNames: {
      [`hide-for-${screenOrientation}`]: includes(SCREEN_ORIENTATIONS, screenOrientation),
    },
  }),
});

export const ShowForScreenReader = createWrapperComponent({
  displayName: 'ShowForScreenReader',
  styles,
  mapProps: props => ({
    props,
    classNames: 'show-for-sr',
  }),
});

export const HideForScreenReader = createWrapperComponent({
  displayName: 'HideForScreenReader',
  styles,
  mapProps: props => ({
    props: { ...props, 'aria-hidden': true },
  }),
});

export const ShowOnFocus = createWrapperComponent({
  displayName: 'ShowOnFocus',
  styles,
  mapProps: props => ({
    props,
    classNames: 'show-on-focus',
  }),
});

export const Visibility = {
  ShowForScreenSize,
  ShowOnlyForScreenSize,
  HideForScreenSize,
  HideOnlyForScreenSize,
  Hide,
  Invisible,
  ShowForScreenOrientation,
  HideForScreenOrientation,
  ShowForScreenReader,
  HideForScreenReader,
  ShowOnFocus,
};

export default Visibility;


text:
package org.smartx.summer.config.register.impl;

import com.alibaba.fastjson.serializer.SerializerFeature;
import com.alibaba.fastjson.support.config.FastJsonConfig;
import com.alibaba.fastjson.support.spring.FastJsonHttpMessageConverter4;

import org.smartx.summer.config.register.MessageConvertersRegister;
import org.springframework.http.MediaType;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.stereotype.Component;

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

/**
 * <p> 默认fastjson消息converter </p>
 *
 * <b>Creation Time:</b> 2016年10月28日
 *
 * @author binglin
 * @since summer 0.1
 */
@Component
public class DefaultFastJsonMessageConverterRegister implements MessageConvertersRegister {
    @Override
    public void registry(List<HttpMessageConverter<?>> converters) {
        FastJsonHttpMessageConverter4 fastJsonHttpMessageConverter = new FastJsonHttpMessageConverter4();
        ArrayList<MediaType> arrayList = new ArrayList<MediaType>() {{
            add(MediaType.APPLICATION_JSON_UTF8);
            add(MediaType.valueOf("text/html;charset=UTF-8"));
            add(MediaType.MULTIPART_FORM_DATA);
        }};
        fastJsonHttpMessageConverter.setSupportedMediaTypes(arrayList);
        FastJsonConfig fastJsonConfig = new FastJsonConfig();
        fastJsonConfig.setSerializerFeatures(SerializerFeature.QuoteFieldNames,
                SerializerFeature.DisableCircularReferenceDetect);
        fastJsonHttpMessageConverter.setFastJsonConfig(fastJsonConfig);
        converters.add(0, fastJsonHttpMessageConverter);
    }
}


text:
class Browser;
class CustomDrawButton;
class GtkThemeService;
class GURL;
class PermissionSelector;
class Profile;
class TabContents;
class WebsiteSettings;

namespace content {
struct SSLStatus;
}

// GTK implementation of the website settings UI.
class WebsiteSettingsPopupGtk : public WebsiteSettingsUI,
                                public PermissionSelectorObserver,
                                public BubbleDelegateGtk,
                                public content::NotificationObserver {
 public:
  // Creates a |WebsiteSettingsPopupGtk| and displays the UI. The |url|
  // contains the omnibox URL of the currently active tab, |parent| contains
  // the currently active window, |profile| contains the currently active
  // profile and |ssl| contains the |SSLStatus| of the connection to the
  // website in the currently active tab that is wrapped by the
  // |tab_contents|.
  static void Show(gfx::NativeWindow parent,
                   Profile* profile,
                   TabContents* tab_contents,
                   const GURL& url,
                   const content::SSLStatus& ssl);

  virtual ~WebsiteSettingsPopupGtk();

 private:
  WebsiteSettingsPopupGtk(gfx::NativeWindow parent,
                          Profile* profile,
                          TabContents* tab_contents,
                          const GURL& url,
                          const content::SSLStatus& ssl);

  // WebsiteSettingsUI implementations.
  virtual void SetCookieInfo(const CookieInfoList& cookie_info_list) OVERRIDE;
  virtual void SetPermissionInfo(
      const PermissionInfoList& permission_info_list) OVERRIDE;
  virtual void SetIdentityInfo(const IdentityInfo& identity_info) OVERRIDE;
  virtual void SetFirstVisit(const string16& first_visit) OVERRIDE;
  virtual void SetSelectedTab(WebsiteSettingsUI::TabId tab_id) OVERRIDE;

  // PermissionSelectorObserver implementations.
  virtual void OnPermissionChanged(PermissionSelector* selector) OVERRIDE;

  // BubbleDelegateGtk implementation.
  virtual void BubbleClosing(BubbleGtk* bubble, bool closed_by_escape) OVERRIDE;

  // content::NotificationObserver implementation.
  virtual void Observe(int type,
                       const content::NotificationSource& source,
                       const content::NotificationDetails& details) OVERRIDE;

  // Layouts the different sections retrieved from the model.
  void InitContents();

  // Creates a tab for the tabstrip with label indicated by |ids|. This tab
  // is not used in GTK theme mode.
  GtkWidget* BuildTab(int ids);

  // Gives the index in the notebook for the given tab widget.
  int TabstripButtonToTabIndex(GtkWidget* tab);

  // Callbacks for the link buttons.
  CHROMEGTK_CALLBACK_1(WebsiteSettingsPopupGtk, gboolean,
                       OnTabButtonPress, GdkEvent*);
  CHROMEGTK_CALLBACK_1(WebsiteSettingsPopupGtk, gboolean,
                       OnTabExpose, GdkEventExpose*);
  CHROMEGTK_CALLBACK_1(WebsiteSettingsPopupGtk, gboolean,
                       OnTabstripExpose, GdkEventExpose*);
  CHROMEGTK_CALLBACK_0(WebsiteSettingsPopupGtk, void, OnCookiesLinkClicked);
  CHROMEGTK_CALLBACK_0(WebsiteSettingsPopupGtk, void, OnViewCertLinkClicked);
  CHROMEGTK_CALLBACK_0(WebsiteSettingsPopupGtk, void, OnCloseButtonClicked);
  CHROMEGTK_CALLBACK_0(WebsiteSettingsPopupGtk, void, OnHelpLinkClicked);

  // Parent window.
  GtkWindow* parent_;

  // The container that contains the content of the popup.
  GtkWidget* contents_;

  // The widget relative to which the popup is positioned.
  GtkWidget* anchor_;

  // Provides colors and stuff.
  GtkThemeService* theme_service_;

  // The popup bubble container.
  BubbleGtk* bubble_;

  Profile* profile_;

  TabContents* tab_contents_;

  // The browser object of the current window. This is needed to open the
  // settings page in a new tab.
  Browser* browser_;

  // For secure connection |cert_id_| is set to the ID of the server
  // certificate. For non secure connections |cert_id_| is 0.
  int cert_id_;

  // Container for the popup header content.
  GtkWidget* header_box_;

  // Close button for the bubble.
  scoped_ptr<CustomDrawButton> close_button_;

  // Container for the cookies and site data section content.
  GtkWidget* cookies_section_contents_;

  // Container for the permissions section content.
  GtkWidget* permissions_section_contents_;

  // Container for the remote host (website) identity section of the connection
  // tab.
  GtkWidget* identity_contents_;

  // Container for the connection section of the connection tab.
  GtkWidget* connection_contents_;

  // Container for the information about the first visit date of the website.
  GtkWidget* first_visit_contents_;

  // The widget that wraps the tabstrip.
  GtkWidget* tabstrip_alignment_;

  // The widget that contains the tabs display on the popup.
  GtkWidget* notebook_;

  // The UI translates user actions to specific events and forwards them to the
  // |presenter_|. The |presenter_| handles these events and updates the UI.
  scoped_ptr<WebsiteSettings> presenter_;

  // The permission selectors that allow the user to change individual
  // permissions.
  ScopedVector<PermissionSelector> selectors_;

  content::NotificationRegistrar registrar_;

  DISALLOW_COPY_AND_ASSIGN(WebsiteSettingsPopupGtk);
};

#endif  // CHROME_BROWSER_UI_GTK_WEBSITE_SETTINGS_WEBSITE_SETTINGS_POPUP_GTK_H_


text:
if Rails.application.config.respond_to?(:assets)
  Rails.application.config.assets.precompile << 'refinery_core_manifest.js'
end


text:
<!DOCTYPE html>

    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <meta name="description" content="Sci blog jekyll theme">
    <meta name="author" content="AIR RAYA Group">
    <link href='/MyBlog/img/favicon.ico' type='image/icon' rel='shortcut icon'/>

    <title>泽民博客 | Jekyll theme</title>

    <link rel="stylesheet" href="/MyBlog/css/bootstrap.min.css" integrity="sha384-1q8mTJOASx8j1Au+a5WDVnPi2lkFfwwEAa8hDDdjZlpLegxhjVME1fgjWPGmkzs7" crossorigin="anonymous">
    <link rel="stylesheet" href="/MyBlog/css/font-awesome.min.css">
    <link href="/MyBlog/css/simple-sidebar.css" rel="stylesheet">
	<link href="/MyBlog/css/classic-10_7.css" rel="stylesheet" type="text/css">

    <link href="/MyBlog/css/style.css" rel="stylesheet">
    <link href="/MyBlog/css/pygments.css" rel="stylesheet">

 <link href="/MyBlog/css/front.css" rel="stylesheet" type="text/css">
 <link href="/MyBlog/css/Josefin_Slab.css" rel="stylesheet" type="text/css">
<link href="/MyBlog/css/Architects_Daughter.css" rel="stylesheet" type="text/css">
<link href="/MyBlog/css/Schoolbell.css" rel="stylesheet" type="text/css">
<link href="/MyBlog/css/Codystar.css" rel="stylesheet" type="text/css">

<link href="/MyBlog/css/calendar/common.css" type="text/css"  rel="stylesheet">

    <link rel="stylesheet" href="/MyBlog/katex/katex.css">

                        Home

                    About

                    Services

                    Portfolio

                    Events

                    Blog

                    FAQ

                    Contact

                        泽民博客
                        ☰ Menu

Dockerhub+Github构建kubernetes私有镜像仓库

 by 夏泽民 <time datetime="2021-04-04T00:00:00+08:00" itemprop="datePublished"> Apr 4, 2021</time>

https://github.com/mpriscella/k8s-actions

https://github.com/balchua/microk8s-actions

部分kubernets镜像存放在google镜像仓库中,由于无法访问外网,这里可以使用Docker Hub的自动构建功能将google镜像构建到个人dockerhub仓库中。

https://blog.csdn.net/networken/article/details/85215714

https://github.com/mritd/gcr

https://github.com/mritd/docker-library

https://www.jianshu.com/p/5a911f20d93e

https://www.docker.com/

                Category k8s

<link rel="stylesheet" href="/MyBlog/css/default.css">


text:
package org.swddsw.codebaseanalyzer;

import org.swddsw.codebaseanalyzer.api.ApiAdapter;
import org.swddsw.codebaseanalyzer.api.ApiException;
import org.swddsw.codebaseanalyzer.graph.GraphAdapter;
import org.swddsw.codebaseanalyzer.graph.GraphProcessingException;
import org.swddsw.codebaseanalyzer.model.Project;
import java.util.List;

final public class ProjectMapper {

    private GraphAdapter graphAdapter;

    private ApiAdapter apiAdapter;

    private OutputWriter outputWriter;

    private List<Project> projects;

    public ProjectMapper(GraphAdapter graphAdapter, ApiAdapter apiAdapter, OutputWriter outputWriter) {
        this.graphAdapter = graphAdapter;
        this.apiAdapter = apiAdapter;
        this.outputWriter = outputWriter;
    }

    public void reset() {
        try {
            outputWriter.outputMessage("Purging Neo4j Database...");
            graphAdapter.purge();
            outputWriter.outputMessage("Done");
        } catch (GraphProcessingException e) {
            outputWriter.outputMessage("GRAPH-PROCESSING-ERROR: " + e.getMessage());
        }
    }

    public void mapProjects() {
        try {
            if (projects == null) {
                projects = apiAdapter.getProjects();
            }

            outputWriter.outputMessage("Mapping projects");
            for (Project project : projects) {
                graphAdapter.addProject(project);
                outputWriter.outputProgress();
            }
            outputWriter.outputMessage("\nDone");
        } catch (ApiException e) {
            outputWriter.outputMessage("API-ERROR: " + e.getMessage());
        } catch (GraphProcessingException e) {
            outputWriter.outputMessage("GRAPH-PROCESSING-ERROR: " + e.getMessage());
        }
    }

    public void mapTickets() {
        outputWriter.outputMessage("Mapping tickets");
        for (Project project : projects) {
            outputWriter.outputProgress();
        }
        outputWriter.outputMessage("\nDone");
    }
}


text:
package utils

import (
	"crypto/md5"
	"encoding/hex"
	"fmt"
	"io"
	"io/ioutil"
	"math"
	"os"
	"path"

	"github.com/theduke/go-apperror"
)

func AbsPath(p string) (string, apperror.Error) {
	if !path.IsAbs(p) {
		wd, err := os.Getwd()
		if err != nil {
			return "", apperror.Wrap(err, "get_wd_error")
		}
		p = path.Clean(path.Join(wd, p))
	}

	return p, nil
}

func FileExists(path string) (bool, apperror.Error) {
	f, err := os.Open(path)
	if err != nil {
		if os.IsNotExist(err) {
			return false, nil
		} else {
			return false, apperror.Wrap(err, "file_read_error")
		}
	}
	f.Close()

	return true, nil
}

func ReadFile(path string) ([]byte, apperror.Error) {
	f, err := os.Open(path)
	if err != nil {
		return nil, apperror.Wrap(err, "file_open_error",
			fmt.Sprintf("Could not open file at %v", path))
	}

	content, err := ioutil.ReadAll(f)
	if err != nil {
		return nil, apperror.Wrap(err, "file_read_error",
			fmt.Sprintf("Could not read file at %v", path))
	}

	return content, nil
}

func WriteFile(p string, content []byte, createDir bool) apperror.Error {
	if createDir {
		dir, err := AbsPath(path.Dir(p))
		if err != nil {
			return err
		}

		if dir != "" {
			if err := os.MkdirAll(dir, 0777); err != nil {
				return apperror.Wrap(err, "mkdir_error")
			}
		}
	}

	f, err := os.Create(p)
	if err != nil {
		return apperror.Wrap(err, "file_create_error")
	}
	defer f.Close()

	if _, err := f.Write(content); err != nil {
		return apperror.Wrap(err, "file_write_error")
	}

	return nil
}

func CopyFile(sourcePath, targetPath string) apperror.Error {
	source, err := os.Open(sourcePath)
	if err != nil {
		return apperror.Wrap(err, "file_open_error",
			fmt.Sprintf("Could not open file at %v", sourcePath))
	}
	defer source.Close()

	target, err := os.Open(targetPath)
	if err != nil {
		return apperror.Wrap(err, "file_open_error",
			fmt.Sprintf("Could not open file at %v", targetPath))
	}
	defer target.Close()

	if _, err := io.Copy(target, source); err != nil {
		return apperror.Wrap(err, "file_copy_error", fmt.Sprintf("Could not copy file from %v to %v", sourcePath, targetPath))
	}

	return nil
}

// Write contents to a tmp file and return the path to the file.
func WriteTmpFile(content []byte, name string) (string, apperror.Error) {
	uuid := UUIdv4()

	if name == "" {
		name = uuid
	} else if name[0] == '.' {
		name = uuid + name
	}

	p := path.Join(os.TempDir(), "tmpfiles", name)
	if err := WriteFile(p, content, true); err != nil {
		return "", err
	}

	return p, nil
}

func ListFiles(path string) ([]string, apperror.Error) {
	dir, err := os.Open(path)
	if err != nil {
		return nil, apperror.Wrap(err, "open_dir_error")
	}
	defer dir.Close()

	items, err := dir.Readdir(-1)
	if err != nil {
		return nil, apperror.Wrap(err, "read_error")
	}

	files := make([]string, 0)
	for _, item := range items {
		if !item.IsDir() {
			files = append(files, item.Name())
		}
	}

	return files, nil
}

func BuildFileMD5Hash(path string) (string, apperror.Error) {
	file, err := os.Open(path)
	if err != nil {
		return "", apperror.Wrap(err, "file_open_error")
	}
	defer file.Close()

	// calculate the file size
	info, _ := file.Stat()
	filesize := info.Size()
	var filechunk float64 = 8192
	blocks := uint64(math.Ceil(float64(filesize) / filechunk))

	hash := md5.New()

	for i := uint64(0); i < blocks; i++ {
		blocksize := int(math.Min(filechunk, float64(filesize-int64(i*uint64(filechunk)))))
		buf := make([]byte, blocksize)

		_, err := file.Read(buf)
		if err != nil {
			return "", apperror.Wrap(err, "file_read_error")
		}

		io.WriteString(hash, string(buf)) // append into the hash
	}

	return hex.EncodeToString(hash.Sum(nil)), nil
}


text:
<?php

namespace Oro\Bundle\HelpBundle;

use Symfony\Component\HttpKernel\Bundle\Bundle;
use Symfony\Component\DependencyInjection\ContainerBuilder;

class OroHelpBundle extends Bundle
{
    /**
     * {@inheritdoc}
     */
    public function build(ContainerBuilder $container)
    {
    }
}


text:
import sys
import os
import platform
import numpy as np
import matplotlib.pyplot as plt

import flopy

#Set name of MODFLOW exe
#  assumes executable is in users path statement
version = 'mf2005'
exe_name = 'mf2005'
if platform.system() == 'Windows':
    exe_name = 'mf2005.exe'
mfexe = exe_name

#Set the paths
loadpth = os.path.join('..', 'data', 'secp')
modelpth = os.path.join('data')

#make sure modelpth directory exists
if not os.path.exists(modelpth):
    os.makedirs(modelpth)

ml = flopy.modflow.Modflow.load('secp.nam', model_ws=loadpth,
                                exe_name=exe_name, version=version, verbose=True)
ml.change_model_ws(new_pth=modelpth)
ml.write_input()

print '...end'


text:
from __future__ import unicode_literals

from django.db import models, migrations

class Migration(migrations.Migration):

    dependencies = [
    ]

    operations = [
        migrations.CreateModel(
            name='BlogPost',
            fields=[
                ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),
                ('title', models.CharField(max_length=255, verbose_name='title')),
                ('lead', models.TextField(verbose_name='lead')),
                ('body', models.TextField(verbose_name='body')),
            ],
            options={
                'verbose_name': 'blog post',
                'verbose_name_plural': 'blog posts',
            },
            bases=(models.Model,),
        ),
    ]


text:
package repository

import (
	"encoding/json"
	"fmt"
	"io"
	"io/ioutil"
	"net/http"
	"os"
	"path"
	"strconv"
	"strings"
	"time"

	"github.com/appc/docker2aci/lib/common"
	"github.com/appc/docker2aci/lib/types"
	"github.com/appc/docker2aci/lib/util"
	"github.com/appc/spec/schema"
	"github.com/coreos/ioprogress"
)

const (
	defaultIndexURL = "registry-1.docker.io"
)

type v2Manifest struct {
	Name     string `json:"name"`
	Tag      string `json:"tag"`
	FSLayers []struct {
		BlobSum string `json:"blobSum"`
	} `json:"fsLayers"`
	History []struct {
		V1Compatibility string `json:"v1Compatibility"`
	} `json:"history"`
	Signature []byte `json:"signature"`
}

func (rb *RepositoryBackend) getImageInfoV2(dockerURL *types.ParsedDockerURL) ([]string, *types.ParsedDockerURL, error) {
	manifest, layers, err := rb.getManifestV2(dockerURL)
	if err != nil {
		return nil, nil, err
	}

	rb.imageManifests[*dockerURL] = *manifest

	return layers, dockerURL, nil
}

func (rb *RepositoryBackend) buildACIV2(layerNumber int, layerID string, dockerURL *types.ParsedDockerURL, outputDir string, tmpBaseDir string, curPwl []string, compression common.Compression) (string, *schema.ImageManifest, error) {
	manifest := rb.imageManifests[*dockerURL]

	layerIndex, err := getLayerIndex(layerID, manifest)
	if err != nil {
		return "", nil, err
	}

	if len(manifest.History) <= layerIndex {
		return "", nil, fmt.Errorf("history not found for layer %s", layerID)
	}

	layerData := types.DockerImageData{}
	if err := json.Unmarshal([]byte(manifest.History[layerIndex].V1Compatibility), &layerData); err != nil {
		return "", nil, fmt.Errorf("error unmarshaling layer data: %v", err)
	}

	tmpDir, err := ioutil.TempDir(tmpBaseDir, "docker2aci-")
	if err != nil {
		return "", nil, fmt.Errorf("error creating dir: %v", err)
	}
	defer os.RemoveAll(tmpDir)

	layerFile, err := rb.getLayerV2(layerID, dockerURL, tmpDir)
	if err != nil {
		return "", nil, fmt.Errorf("error getting the remote layer: %v", err)
	}
	defer layerFile.Close()

	util.Debug("Generating layer ACI...")
	aciPath, aciManifest, err := common.GenerateACI(layerNumber, layerData, dockerURL, outputDir, layerFile, curPwl, compression)
	if err != nil {
		return "", nil, fmt.Errorf("error generating ACI: %v", err)
	}

	return aciPath, aciManifest, nil
}

func (rb *RepositoryBackend) getManifestV2(dockerURL *types.ParsedDockerURL) (*v2Manifest, []string, error) {
	url := rb.schema + path.Join(dockerURL.IndexURL, "v2", dockerURL.ImageName, "manifests", dockerURL.Tag)

	req, err := http.NewRequest("GET", url, nil)
	if err != nil {
		return nil, nil, err
	}

	rb.setBasicAuth(req)

	res, err := rb.makeRequest(req, dockerURL.ImageName)
	if err != nil {
		return nil, nil, err
	}
	defer res.Body.Close()

	if res.StatusCode != http.StatusOK {
		return nil, nil, fmt.Errorf("unexpected http code: %d, URL: %s", res.StatusCode, req.URL)
	}

	manblob, err := ioutil.ReadAll(res.Body)
	if err != nil {
		return nil, nil, err
	}

	manifest := &v2Manifest{}

	err = json.Unmarshal(manblob, manifest)
	if err != nil {
		return nil, nil, err
	}

	if manifest.Name != dockerURL.ImageName {
		return nil, nil, fmt.Errorf("name doesn't match what was requested, expected: %s, downloaded: %s", dockerURL.ImageName, manifest.Name)
	}

	if manifest.Tag != dockerURL.Tag {
		return nil, nil, fmt.Errorf("tag doesn't match what was requested, expected: %s, downloaded: %s", dockerURL.Tag, manifest.Tag)
	}

	//TODO: verify signature here

	layers := make([]string, len(manifest.FSLayers))

	for i, layer := range manifest.FSLayers {
		layers[i] = layer.BlobSum
	}

	return manifest, layers, nil
}

func getLayerIndex(layerID string, manifest v2Manifest) (int, error) {
	for i, layer := range manifest.FSLayers {
		if layer.BlobSum == layerID {
			return i, nil
		}
	}
	return -1, fmt.Errorf("layer not found in manifest: %s", layerID)
}

func (rb *RepositoryBackend) getLayerV2(layerID string, dockerURL *types.ParsedDockerURL, tmpDir string) (*os.File, error) {
	url := rb.schema + path.Join(dockerURL.IndexURL, "v2", dockerURL.ImageName, "blobs", layerID)
	req, err := http.NewRequest("GET", url, nil)
	if err != nil {
		return nil, err
	}

	rb.setBasicAuth(req)

	res, err := rb.makeRequest(req, dockerURL.ImageName)
	if err != nil {
		return nil, err
	}
	defer res.Body.Close()

	if res.StatusCode != 200 {
		return nil, fmt.Errorf("HTTP code: %d. URL: %s", res.StatusCode, req.URL)
	}

	var in io.Reader
	in = res.Body

	if hdr := res.Header.Get("Content-Length"); hdr != "" {
		imgSize, err := strconv.ParseInt(hdr, 10, 64)
		if err != nil {
			return nil, err
		}

		prefix := "Downloading " + layerID[:18]
		fmtBytesSize := 18
		barSize := int64(80 - len(prefix) - fmtBytesSize)
		bar := ioprogress.DrawTextFormatBarForW(barSize, os.Stderr)
		fmtfunc := func(progress, total int64) string {
			return fmt.Sprintf(
				"%s: %s %s",
				prefix,
				bar(progress, total),
				ioprogress.DrawTextFormatBytes(progress, total),
			)
		}
		in = &ioprogress.Reader{
			Reader:       res.Body,
			Size:         imgSize,
			DrawFunc:     ioprogress.DrawTerminalf(os.Stderr, fmtfunc),
			DrawInterval: 500 * time.Millisecond,
		}
	}

	layerFile, err := ioutil.TempFile(tmpDir, "dockerlayer-")
	if err != nil {
		return nil, err
	}

	_, err = io.Copy(layerFile, in)
	if err != nil {
		return nil, err
	}

	if err := layerFile.Sync(); err != nil {
		return nil, err
	}

	return layerFile, nil
}

func (rb *RepositoryBackend) makeRequest(req *http.Request, repo string) (*http.Response, error) {
	setBearerHeader := false
	hostAuthTokens, ok := rb.hostsV2AuthTokens[req.URL.Host]
	if ok {
		authToken, ok := hostAuthTokens[repo]
		if ok {
			req.Header.Set("Authorization", "Bearer "+authToken)
			setBearerHeader = true
		}
	}

	client := &http.Client{}
	res, err := client.Do(req)
	if err != nil {
		return nil, err
	}

	if res.StatusCode == http.StatusUnauthorized && setBearerHeader {
		return res, err
	}

	hdr := res.Header.Get("www-authenticate")
	if res.StatusCode != http.StatusUnauthorized || hdr == "" {
		return res, err
	}

	tokens := strings.Split(hdr, " ")
	if len(tokens) != 2 || strings.ToLower(tokens[0]) != "bearer" {
		return res, err
	}

	res.Body.Close()

	tokens = strings.Split(tokens[1], ",")

	var realm, service, scope string
	for _, token := range tokens {
		if strings.HasPrefix(token, "realm") {
			realm = strings.Trim(token[len("realm="):], "\"")
		}
		if strings.HasPrefix(token, "service") {
			service = strings.Trim(token[len("service="):], "\"")
		}
		if strings.HasPrefix(token, "scope") {
			scope = strings.Trim(token[len("scope="):], "\"")
		}
	}

	if realm == "" {
		return nil, fmt.Errorf("missing realm in bearer auth challenge")
	}
	if service == "" {
		return nil, fmt.Errorf("missing service in bearer auth challenge")
	}
	// The scope can be empty if we're not getting a token for a specific repo
	if scope == "" && repo != "" {
		return nil, fmt.Errorf("missing scope in bearer auth challenge")
	}

	authReq, err := http.NewRequest("GET", realm, nil)
	if err != nil {
		return nil, err
	}

	getParams := authReq.URL.Query()
	getParams.Add("service", service)
	if scope != "" {
		getParams.Add("scope", scope)
	}
	authReq.URL.RawQuery = getParams.Encode()

	rb.setBasicAuth(authReq)

	res, err = client.Do(authReq)
	if err != nil {
		return nil, err
	}
	defer res.Body.Close()

	switch res.StatusCode {
	case http.StatusUnauthorized:
		return nil, fmt.Errorf("unable to retrieve auth token: 401 unauthorized")
	case http.StatusOK:
		break
	default:
		return nil, fmt.Errorf("unexpected http code: %d, URL: %s", res.StatusCode, authReq.URL)
	}

	tokenBlob, err := ioutil.ReadAll(res.Body)
	if err != nil {
		return nil, err
	}

	tokenStruct := struct {
		Token string `json:"token"`
	}{}

	err = json.Unmarshal(tokenBlob, &tokenStruct)
	if err != nil {
		return nil, err
	}

	hostAuthTokens, ok = rb.hostsV2AuthTokens[req.URL.Host]
	if !ok {
		hostAuthTokens = make(map[string]string)
		rb.hostsV2AuthTokens[req.URL.Host] = hostAuthTokens
	}

	hostAuthTokens[repo] = tokenStruct.Token

	return rb.makeRequest(req, repo)
}

func (rb *RepositoryBackend) setBasicAuth(req *http.Request) {
	if rb.username != "" && rb.password != "" {
		req.SetBasicAuth(rb.username, rb.password)
	}
}


text:
#include <aws/pinpoint-email/model/EmailContent.h>
#include <aws/core/utils/json/JsonSerializer.h>

#include <utility>

using namespace Aws::Utils::Json;
using namespace Aws::Utils;

namespace Aws
{
namespace PinpointEmail
{
namespace Model
{

EmailContent::EmailContent() :
    m_simpleHasBeenSet(false),
    m_rawHasBeenSet(false),
    m_templateHasBeenSet(false)
{
}

EmailContent::EmailContent(JsonView jsonValue) :
    m_simpleHasBeenSet(false),
    m_rawHasBeenSet(false),
    m_templateHasBeenSet(false)
{
  *this = jsonValue;
}

EmailContent& EmailContent::operator =(JsonView jsonValue)
{
  if(jsonValue.ValueExists("Simple"))
  {
    m_simple = jsonValue.GetObject("Simple");

    m_simpleHasBeenSet = true;
  }

  if(jsonValue.ValueExists("Raw"))
  {
    m_raw = jsonValue.GetObject("Raw");

    m_rawHasBeenSet = true;
  }

  if(jsonValue.ValueExists("Template"))
  {
    m_template = jsonValue.GetObject("Template");

    m_templateHasBeenSet = true;
  }

  return *this;
}

JsonValue EmailContent::Jsonize() const
{
  JsonValue payload;

  if(m_simpleHasBeenSet)
  {
   payload.WithObject("Simple", m_simple.Jsonize());

  }

  if(m_rawHasBeenSet)
  {
   payload.WithObject("Raw", m_raw.Jsonize());

  }

  if(m_templateHasBeenSet)
  {
   payload.WithObject("Template", m_template.Jsonize());

  }

  return payload;
}

} // namespace Model
} // namespace PinpointEmail
} // namespace Aws


text:
<?php
namespace CCBundle\Form;

use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\OptionsResolver\OptionsResolver;
use Symfony\Component\Form\Extension\Core\Type\EmailType;
use Symfony\Component\Form\Extension\Core\Type\TextType;
use Symfony\Component\Form\Extension\Core\Type\ChoiceType;
use Symfony\Component\Form\Extension\Core\Type\SubmitType;
use Symfony\Component\Form\Extension\Core\Type\ResetType;
use Symfony\Bridge\Doctrine\Form\Type\EntityType;

class SuperProfileUserForm extends AbstractType
{
    public function getName()
    {
        return 'superProfileUser';
    }

    public function buildForm(FormBuilderInterface $builder, array $options)
    {

        $builder
            ->add('id', TextType::class, array('disabled' => true))
            ->add('username', TextType::class)
            ->add('email', EmailType::class)
            ->add('emailHTML',ChoiceType::class, array(
                        'choices' => array('HTML' => true, 'plain' => false),
                        'expanded' => true,
                        'empty_data'  => true,
                    ))
            ->add('isConfirm',ChoiceType::class, array(
                        'choices' => array('да' => true, 'нет' => false),
                        'expanded' => true,
                        'empty_data'  => true,
                    ))
            ->add('isActive',ChoiceType::class, array(
                        'choices' => array('да' => true, 'нет' => false),
                        'expanded' => true,
                        'empty_data'  => true,
                    ))

             ->add('userRoles', EntityType::class, array(
                    'class' => 'CCBundle:Role',
                    'choice_label' => 'name',
                    'property_path' => 'userRoles',
                    'multiple' => true,
                    'expanded' => true,
                ))

            ->add('createdAt', TextType::class)
            ->add('firstname', TextType::class)
            ->add('secondname', TextType::class)
            ->add('middlename', TextType::class)
            ->add('save', SubmitType::class)
            ->add('delete', SubmitType::class)
            ->add('reset', ResetType::class)
            ;
    }

    public function configureOptions(OptionsResolver $resolver)
    {
        $resolver->setDefaults(array('data_class' => 'CCBundle\Entity\User'
                                        ));
    }
}


text:
package org.gradle.caching.internal.controller.operations;

import org.gradle.caching.internal.operations.BuildCacheRemoteStoreBuildOperationType;

public class StoreOperationResult implements BuildCacheRemoteStoreBuildOperationType.Result {

    public static final BuildCacheRemoteStoreBuildOperationType.Result STORED = new StoreOperationResult(true);
    public static final BuildCacheRemoteStoreBuildOperationType.Result NOT_STORED = new StoreOperationResult(false);

    private final boolean stored;

    private StoreOperationResult(boolean stored) {
        this.stored = stored;
    }

    @Override
    public boolean isStored() {
        return stored;
    }
}


text:
package com.lukasdietrich.lambdatra.reaction.http;

import io.netty.buffer.ByteBuf;
import io.netty.handler.codec.http.FullHttpRequest;
import io.netty.handler.codec.http.HttpHeaders.Names;
import io.netty.handler.codec.http.HttpRequest;
import io.netty.handler.codec.http.QueryStringDecoder;
import io.netty.handler.codec.http.cookie.Cookie;
import io.netty.handler.codec.http.cookie.ServerCookieDecoder;
import io.netty.handler.codec.http.multipart.DefaultHttpDataFactory;
import io.netty.handler.codec.http.multipart.HttpPostRequestDecoder;

import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.Set;

import com.lukasdietrich.lambdatra.session.SessionStore;

/**
 * Wraps {@link HttpRequest} into a simpler class
 * and combines it with access to parsed url query
 * and parameters.
 *
 * @author Lukas Dietrich
 *
 */
public final class WrappedRequest<S> {

	private FullHttpRequest req;
	private QueryStringDecoder query;

	private Map<String, String> params;
	private Map<String, Cookie> cookies;
	private SessionStore<S> sessions;

	public WrappedRequest(FullHttpRequest req, Map<String, String> params, SessionStore<S> sessions) {
		this.req = req;
		this.params = params;
		this.query = new QueryStringDecoder(req.getUri());
		this.cookies = new HashMap<>();
		this.sessions = sessions;

		{
			getHeader(Names.COOKIE).ifPresent(header -> {
				for (Cookie c : ServerCookieDecoder.LAX.decode(header)) {
					cookies.put(c.name(), c);
				}
			});
		}
	}

	/**
	 * Returns an {@link Optional} of a header by key
	 *
	 * @param key header name
	 * @return header value
	 */
	public Optional<String> getHeader(String key) {
		return Optional.ofNullable(req.headers().get(key));
	}

	/**
	 * Returns an {@link Optional} of a parameter by key
	 *
	 * @param key parameter name
	 * @return parameter value
	 */
	public Optional<String> getParam(String key) {
		return Optional.ofNullable(params.get(key));
	}

	/**
	 * Returns an {@link Optional} of a querystring value by key
	 *
	 * @param key query name
	 * @return query value
	 */
	public Optional<List<String>> getQuery(String key) {
		return Optional.ofNullable(query.parameters().get(key));
	}

	/**
	 * Creates a {@link HttpPostRequestDecoder} of the request body.
	 *
	 * @return a {@link HttpPostRequestDecoder}
	 */
	public HttpPostRequestDecoder parseBody() {
		return new HttpPostRequestDecoder(new DefaultHttpDataFactory(Short.MAX_VALUE), req);
	}

	/**
	 * Returns the raw body
	 *
	 * @return request body
	 */
	public ByteBuf getBody() {
		return req.content();
	}

	/**
	 * Returns an {@link Optional} of the session
	 *
	 * @return session value
	 */
	public Optional<S> getSession() {
		Optional<Cookie> cookie = getSessionId();

		return (cookie.isPresent())
				? sessions.getSession(cookie.get().value())
				: Optional.empty();
	}

	/**
	 * Returns an {@link Optional} of the session cookie
	 *
	 * @return session id
	 */
	protected Optional<Cookie> getSessionId() {
		return getCookie(sessions.getCookieKey());
	}

	/**
	 * Returns a {@link Set} of {@link Cookie}s.
	 *
	 * @deprecated use {@link #getCookie(String)} instead
	 * @return set of of cookies
	 */
	public Set<Cookie> getCookies() {
		return new HashSet<>(cookies.values());
	}

	/**
	 * Returns an {@link Optional} of a {@link Cookie} by key
	 *
	 * @param key name of {@link Cookie}
	 * @return a cookie
	 */
	public Optional<Cookie> getCookie(String key) {
		return Optional.ofNullable(cookies.get(key));
	}

	/**
	 * Returns the request path omitting the query part.
	 *

	 * (eg.: "http://example.com /this/is/the/path ?this=is&not")
	 *
	 * @return the requested path
	 */
	public String getPath()  {
		return query.path();
	}

}


text:
@ECHO OFF
del *.nupkg
..\packages\NuGet.CommandLine.3.3.0\tools\NuGet.exe pack Weakly.nuspec -Symbols
pause


text:
package com.zifangsky.OnlineFriend.servlet.article;

import java.io.IOException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.zifangsky.OnlineFriend.model.article.Article;
import com.zifangsky.OnlineFriend.util.DbConn;
import com.zifangsky.OnlineFriend.util.StringUtil;

public class HandleArticleShowContent extends HttpServlet{
	public void init(ServletConfig config)throws ServletException{
		super.init(config);
	}

	public void doGet(HttpServletRequest request,HttpServletResponse response)throws ServletException,IOException{
		//查看文章不需要登录
		continueDoGet(request,response);
	}

	private void continueDoGet(HttpServletRequest request, HttpServletResponse response)throws ServletException,IOException{
		request.setCharacterEncoding("utf-8");
		response.setCharacterEncoding("utf-8");

		String articleId = StringUtil.xssEncode(request.getParameter("id"));
		Article article = new Article();
		request.setAttribute("article", article);

		Connection connection = DbConn.getConnection();
		try {
			PreparedStatement pStatement = connection.prepareStatement("select id,title,author,content from article where id=?");
			pStatement.setString(1, articleId);
			ResultSet resultSet = pStatement.executeQuery();
			if(resultSet.next()){
				article.setId(resultSet.getInt(1));
				article.setTitle(resultSet.getString(2));
				article.setAuthor(resultSet.getString(3));
				article.setContent(resultSet.getString(4));
			}
			pStatement.close();
			connection.close();
		} catch (Exception e) {

		}

		RequestDispatcher dispatcher = request.getRequestDispatcher("article/showArticle.jsp");
		dispatcher.forward(request, response);
	}
}


text:
package org.bdgenomics.adam.projections

import org.bdgenomics.formats.avro.Genotype

object GenotypeField extends FieldEnumeration(Genotype.SCHEMA$) {

  val variant, contigName, start, end, variantCallingAnnotations, sampleId, sampleDescription, processingDescription, alleles, referenceReadDepth, alternateReadDepth, readDepth, genotypeQuality, genotypeLikelihoods, splitFromMultiAllelic, isPhased, phaseSetId, phaseQuality = SchemaValue
}


text:
import struct
import socket

from netlink import *

NETLINK_ROUTE           = 0
NETLINK_UNUSED          = 1
NETLINK_USERSOCK        = 2
NETLINK_FIREWALL        = 3
NETLINK_SOCK_DIAG       = 4
NETLINK_NFLOG           = 5
NETLINK_XFRM            = 6
NETLINK_SELINUX         = 7
NETLINK_ISCSI           = 8
NETLINK_AUDIT           = 9
NETLINK_FIB_LOOKUP      = 10
NETLINK_CONNECTOR       = 11
NETLINK_NETFILTER       = 12
NETLINK_IP6_FW          = 13
NETLINK_DNRTMSG         = 14
NETLINK_KOBJECT_UEVENT  = 15
NETLINK_GENERIC         = 16
NETLINK_SCSITRANSPORT   = 18
NETLINK_ECRYPTFS        = 19
NETLINK_RDMA            = 20
NETLINK_CRYPTO          = 21
NETLINK_INET_DIAG = NETLINK_SOCK_DIAG

class Connection(object):
    '''
    Base class that establishes a netlink connection with the kernel.
    '''
    def __init__(self, family):
        self.family = family
        self.conn = socket.socket(socket.AF_NETLINK, socket.SOCK_RAW, family)
        self.conn.setsockopt(socket.SOL_SOCKET, socket.SO_SNDBUF, 65536)
        self.conn.setsockopt(socket.SOL_SOCKET, socket.SO_RCVBUF, 65536)
        self.conn.bind((0, 0))

    def send(self, msg):
        self.conn.send(msg)

    def recv(self):
        return self.conn.recv(65536)

# Genetlink Controller command and attribute values
CTRL_CMD_UNSPEC         = 0
CTRL_CMD_NEWFAMILY      = 1
CTRL_CMD_DELFAMILY      = 2
CTRL_CMD_GETFAMILY      = 3
CTRL_CMD_NEWOPS         = 4
CTRL_CMD_DELOPS         = 5
CTRL_CMD_GETOPS         = 6
CTRL_CMD_NEWMCAST_GRP   = 7
CTRL_CMD_DELCAST_GRP    = 8
CTRL_CMD_GETMCAST_GRP   = 9
__CTRL_CMD_MAX          = 10

TASKSTATS_GENL_VERSION = 0x1

GENL_HDRLEN = struct.calcsize('BBxx')

class Genlmsg(object):
    '''
    Generic netlink message container, this class is to encapsulate the fields
    of struct genlmsghdr.

    struct genlmsghdr {
        __u8 cmd;
        __u8 version;
        __u16 reserved;
    };

    the `.pack()` method returns a binary c-formatted string of the generic
    netlink header and its associated payload.

    @param cmd :: the generic netlink command.
    @type  cmd :: int

    @param nlattr :: Nlattr object containing the attributes for the call.
    @type  nlattr :: Nlattr Class Object

    @param version :: the generic netlink version of the interface (defaults to
                      taskstats)
    @type  version :: int
    '''
    def __init__(self, cmd, nlattr, version=TASKSTATS_GENL_VERSION):
        self.cmd = cmd
        self.version = version
        self.nlattr = nlattr
        self.payload = self.nlattr.pack()
        self.genlen = GENL_HDRLEN + self.nlattr.nla_len

    def pack(self):
        genlhdr = struct.pack('BBxx', self.cmd, self.version)
        return genlhdr + self.payload

class Controller(Connection):
    '''
    Controller class that establishes a generic netlink connection with
    family of the supplied 'genl_name'.
    '''
    def __init__(self, genl_name):
        super(Controller, self).__init__(NETLINK_GENERIC)
        self.genl_name = genl_name
        self.genlhdr = Genlmsg(CTRL_CMD_GETFAMILY, Nlattr(CTRL_ATTR_FAMILY_NAME,
                                                                self.genl_name))
        self.attrs = dict()
        self.pid = os.getpid()
        self.fam_id = self.get_family_id

    @property
    def get_family_id(self):
        nlmsg = Nlmsg(GENL_ID_CTRL, self.pid, self.genlhdr).pack()
        self.send(nlmsg)
        family_id_reply = self.recv()
        parse_response(self, family_id_reply)
        return struct.unpack('I', self.attrs[CTRL_ATTR_FAMILY_ID])[0]


text:
package springfox.documentation.service;

public class ClientCredentialsGrant extends CredentialsGrant {

    public ClientCredentialsGrant(String tokenUrl) {
        super("application", tokenUrl);
    }

}


text:
package org.apache.hadoop.hive.ql.exec.vector.expressions;

// used to set the double precision constant argument to function (e.g. a constant base)
public interface ISetDoubleArg {
  void setArg(double d);
}


text:
module CheckAnswers
  class MultiAnswer < Answer
    def to_partial_path
      'multi_answer_row'
    end
  end
end


text:
require 'helper'
require 'tempfile'

module SSHKit
  module Backend
    class TestNetssh < UnitTest

      def backend
        @backend ||= Netssh
      end

      def test_net_ssh_configuration_options
        backend.configure do |ssh|
          ssh.pty = true
          ssh.connection_timeout = 30
          ssh.ssh_options = {
            keys: %w(/home/user/.ssh/id_rsa),
            forward_agent: false,
            auth_methods: %w(publickey password)
          }
        end

        assert_equal 30, backend.config.connection_timeout
        assert_equal true, backend.config.pty

        assert_equal %w(/home/user/.ssh/id_rsa),  backend.config.ssh_options[:keys]
        assert_equal false,                       backend.config.ssh_options[:forward_agent]
        assert_equal %w(publickey password),      backend.config.ssh_options[:auth_methods]
        assert_instance_of backend::KnownHosts,   backend.config.ssh_options[:known_hosts]
      end

      def test_netssh_ext
        assert_includes  Net::SSH::Config.default_files, "#{Dir.pwd}/.ssh/config"
      end

      def test_transfer_summarizer
        netssh = Netssh.new(Host.new('fake'))

        summarizer = netssh.send(:transfer_summarizer,'Transferring')

        [
         [1,    1000, :debug, 'Transferring afile 0.1%'],
         [1,    100,  :debug, 'Transferring afile 1.0%'],
         [99,   1000, :debug, 'Transferring afile 9.9%'],
         [15,   100,  :info,  'Transferring afile 15.0%'],
         [1,    3,    :info,  'Transferring afile 33.33%'],
         [0,    1,    :debug, 'Transferring afile 0.0%'],
         [1,    2,    :info,  'Transferring afile 50.0%'],
         [0,    0,    :warn,  'percentage 0/0'],
         [1023, 343,  :info,  'Transferring'],
        ].each do |transferred,total,method,substring|
          netssh.expects(method).with { |msg| msg.include?(substring) }
          summarizer.call(nil,'afile',transferred,total)
        end
      end

      if Net::SSH::Version::CURRENT >= Net::SSH::Version[3, 1, 0]
        def test_known_hosts_for_when_all_hosts_are_recognized
          perform_known_hosts_test("github")
        end

        def test_known_hosts_for_when_an_host_hash_is_recognized
          perform_known_hosts_test("github_hash")
        end
      end

      private

      def perform_known_hosts_test(hostfile)
        source = File.join(File.dirname(__FILE__), '../../known_hosts', hostfile)
        kh = Netssh::KnownHosts.new
        keys = kh.search_for('github.com', user_known_hosts_file: source, global_known_hosts_file: Tempfile.new('sshkit-test').path)

        assert_instance_of ::Net::SSH::HostKeys, keys
        assert_equal(1, keys.count)
        keys.each do |key|
          assert_equal("ssh-rsa", key.ssh_type)
        end
      end
    end
  end
end


text:
export default (store) => ({
  path: '/login',
  /*  Async getComponent is only invoked when route matches   */
  getComponent (nextState, cb) {
    /*  Webpack - use 'require.ensure' to create a split point
        and embed an async module loader (jsonp) when bundling   */
    require.ensure([], (require) => {
      /*  Webpack - use require callback to define
          dependencies for bundling   */
      const Login = require('./containers/LoginContainer').default

      /*  Return getComponent   */
      cb(null, Login)

    /* Webpack named bundle   */
    }, 'login')
  }
})


text:
//ACTIVE_ACCOUNT must be an object of type Account
//REPORT_COUNT must be of type theCounter( mailCount )
//LAST_MAIL must be of type theLastMail( sender, subject, date )
//FAIL( ACTIVE_ACCOUNT ) is called on errors
//DONE( ACTIVE_ACCOUNT ) is called on finished communication
//public commands are void checkMail() and void kill()
//please call kill() on removing

function kwasiImapClient( ACTIVE_ACCOUNT, REPORT_COUNT, LAST_MAIL, FAIL, DONE ) {
	var serverConnection;
	var state = "";
	var stateCount = 0;
	var ready = true;
	var timeoutCounter;
	var retryTimer;

	function debug( STRING ) {
		_debug( "kwasiImapClient : " + STRING );
	}

	this.checkMail = function() {
		debug( "checkMail()" );

		this.kill();
		connect();
	};

	this.kill = function() {
		debug( "kill()" );

		if ( !ready ) {
			cancel();
		}

		clearTimeout( retryTimer );
	};

	function retry() {
		debug( "retry()" );

		if ( ACTIVE_ACCOUNT.newLine == "\r\n" ) {
			debug( "communication error. retrying with different line ending" );
			cancel();
			ACTIVE_ACCOUNT.newLine = "\n";
			retryTimer = setTimeout( connect, 5000 );
		} else {
			ACTIVE_ACCOUNT.newLine = "\r\n";
			cancel();
			DONE( ACTIVE_ACCOUNT );
			FAIL( ACTIVE_ACCOUNT );
		}
	}

	function failure() {
		logout();
		ACTIVE_ACCOUNT.newLine = "\n";
		FAIL( ACTIVE_ACCOUNT );
	}

	function forceDisconnect() {
		ACTIVE_ACCOUNT.newLine = "\n";
		cancel();
		DONE( ACTIVE_ACCOUNT );
		FAIL( ACTIVE_ACCOUNT );
	}

	function connect() {
		debug( "connect()" );

		//timeoutCounter = setTimeout( retry, 30000 );
		stateCount = 0;
		state = "";
		ready = false;

		if ( ACTIVE_ACCOUNT.SSLEnabled ) {
			debug( "/usr/bin/openssl s_client -connect " + ACTIVE_ACCOUNT.Hostname + ":" + ACTIVE_ACCOUNT.PortNumber );
			serverConnection = widget.system( "/usr/bin/openssl s_client -connect " + ACTIVE_ACCOUNT.Hostname + ":" + ACTIVE_ACCOUNT.PortNumber, imapEndHandler );
		} else {
			debug( "/usr/bin/nc " + ACTIVE_ACCOUNT.Hostname + " " + ACTIVE_ACCOUNT.PortNumber );
			serverConnection = widget.system( "/usr/bin/nc " + ACTIVE_ACCOUNT.Hostname + " " + ACTIVE_ACCOUNT.PortNumber, imapEndHandler );
		}

		serverConnection.onreaderror = errorHandler;
		serverConnection.onreadoutput = imapHandler;
		timeoutCounter = setTimeout( retry, 5000 );
	}

	function login() {
		debug( "login()" );

		stateCount = 1;
		state = "";
		//debug( "sending : a01 LOGIN " + ACTIVE_ACCOUNT.Username + " " + ACTIVE_ACCOUNT.Password );
		var userName = ACTIVE_ACCOUNT.Username;
		userName = userName.replace( new RegExp( "\\\\", "g" ), "\\\\" );
		userName = userName.replace( new RegExp( "\\\"", "g" ), "\\\"" );
		var passWord = ACTIVE_ACCOUNT.Password;
		passWord = passWord.replace( new RegExp( "\\\\", "g" ), "\\\\" );
		passWord = passWord.replace( new RegExp( "\\\"", "g" ), "\\\"" );
		debug( "sending : a01 LOGIN \"" + userName + "\" \"PASSWORD\"" );
		serverConnection.write( "a01 LOGIN \"" + userName + "\" \"" + passWord + "\"" + ACTIVE_ACCOUNT.newLine );
		timeoutCounter = setTimeout( retry, 5000 );
	}

	function cramMD5() {
		debug( "cramMD5()" );

		stateCount = 2;
		state = "";
		debug( "sending : a01 AUTHENTICATE CRAM-MD5" );
		serverConnection.write( "a01 AUTHENTICATE CRAM-MD5" + ACTIVE_ACCOUNT.newLine );
		timeoutCounter = setTimeout( retry, 5000 );
	}

	function cramMD5Response( SERVER_RESPONSE ) {
		debug( "cramMD5Response()" );

		stateCount = 3;
		state = "";
		var clientResponse = btoa( ACTIVE_ACCOUNT.Username + " " + hex_hmac_md5( ACTIVE_ACCOUNT.Password, SERVER_RESPONSE ) );
		debug( "sending : " + clientResponse );
		serverConnection.write( clientResponse + ACTIVE_ACCOUNT.newLine );
		timeoutCounter = setTimeout( retry, 5000 );
	}

	function select() {
		debug( "select()" );

		stateCount = 4;
		state = "";
		debug( "sending : a02 SELECT \"INBOX\"" );
		serverConnection.write( "a02 SELECT \"INBOX\"" + ACTIVE_ACCOUNT.newLine );
		timeoutCounter = setTimeout( retry, 5000 );
	}

	function fetch() {
		debug( "fetch()" );

		stateCount = 5;
		state = "";
		debug( "sending : a03 FETCH 1:* (UID FLAGS)" );
		serverConnection.write( "a03 FETCH 1:* (UID FLAGS)" + ACTIVE_ACCOUNT.newLine );
		timeoutCounter = setTimeout( failure, 10000 );
	}

	function fetchHeader( MESSAGE ) {
		debug( "fetchHeader( " + MESSAGE + " )" );

		stateCount = 6;
		state = "";
		debug( "sending : a04 FETCH " + MESSAGE + " RFC822.HEADER" );
		serverConnection.write( "a04 FETCH " + MESSAGE + " RFC822.HEADER" + ACTIVE_ACCOUNT.newLine );
		timeoutCounter = setTimeout( failure, 10000 );
	}

	function logout() {
		debug( "logout()" );

		stateCount = 7;
		state = "";
		debug( "sending : a05 LOGOUT" );
		serverConnection.write( "a05 LOGOUT" + ACTIVE_ACCOUNT.newLine );
		timeoutCounter = setTimeout( failure, 10000 );
	}

    function postLogout() {
		debug( "postLogout()" );

		stateCount = 8;
		state = "";
		debug( ACTIVE_ACCOUNT.newLine );
		serverConnection.write( ACTIVE_ACCOUNT.newLine );
		timeoutCounter = setTimeout( failure, 10000 );
	}

	function cancel() {
		debug( "cancel()" );

		serverConnection.cancel();
		ready = true;
		clearTimeout( timeoutCounter );
	}

	function imapEndHandler( RESULT ) {
		debug( "imapEndHandler( " + RESULT + " )" );

		ready = true;
		clearTimeout( timeoutCounter );

		if ( stateCount < 7 ) {
			FAIL( ACTIVE_ACCOUNT );
		} else {
			DONE( ACTIVE_ACCOUNT );
		}
	}

	function errorHandler( RESULT ) {
		debug( "errorHandler( " + RESULT + " )" );
	}

	function imapHandler( RESULT ) {
		debug( "imapHandler( RESULT )" );
		debug( "imapHandler : " + stateCount );

		clearTimeout( timeoutCounter );
/*
		if ( stateCount < 4 ) {
			timeoutCounter = setTimeout( retry, 5000 );
		} else {
			timeoutCounter = setTimeout( failure, 10000 );
		}
*/
		switch ( stateCount ) {
			case 0:	connectHandler( RESULT );
					break;
			case 1:	loginHandler( RESULT );
					break;
			case 2: cramMD5Handler( RESULT );
					break;
			case 3: cramMD5ResponseHandler( RESULT );
					break;
			case 4:	selectHandler( RESULT );
					break;
			case 5:	fetchHandler( RESULT );
					break;
			case 6:	fetchHeaderHandler( RESULT );
					break;
			case 7:	logoutHandler( RESULT );
					break;
            case 8:	postLogoutHandler( RESULT );
					break;
			default:
		}
	}

	function connectHandler( RESULT ) {
		debug( "connectHandler( " + RESULT + " )" );
		state += RESULT;

		if ( state.indexOf( "* OK" ) != -1 ) {
			debug( "connectHandler : we are connected" );

			if ( ACTIVE_ACCOUNT.AuthenticationScheme == "CRAM-MD5" ) {
				cramMD5();
			} else {
				login();
			}
		}
	}

	function loginHandler( RESULT ) {
		debug( "loginHandler( " + RESULT + " )" );
		state += RESULT;

		if ( ( state.indexOf( "a01 BAD" ) != -1 ) || ( state.indexOf( "* BAD" ) != -1 ) ) {
			retry();
		} else if ( state.indexOf( "a01 NO" ) != -1 ) {
			debug( "we are unable to login" );
			retry();
			//failure();
		}

		if ( state.indexOf( "a01 OK" ) != -1 ) {
			debug( "loginHandler : we are connected" );
			select();
		}
	}

	function cramMD5Handler( RESULT ) {
		debug( "cramMD5Handler( " + RESULT + " )" );
		state += RESULT;

		if ( ( state.indexOf( "a01 BAD" ) != -1 ) || ( state.indexOf( "* BAD" ) != -1 ) ) {
			retry();
		} else if ( state.indexOf( "a01 NO" ) != -1 ) {
			debug( "we are unable to cram-md5" );
			retry();
			//failure();
		}

		if ( state.indexOf( "+ " ) != -1 ) {
            var str = state.split( " " )[1];
            str = str.replace( new RegExp( "[^A-Za-z0-9/=\\+]", "g" ), "" );
			cramMD5Response( atob( str ) );
		} else {
			debug( "no CRAM-MD5 ?" );
			failure();
		}
	}

	function cramMD5ResponseHandler( RESULT ) {
		debug( "cramMD5ResponseHandler : " + RESULT );
		state += RESULT;

		if ( ( state.indexOf( "a01 BAD" ) != -1 ) || ( state.indexOf( "a01 NO" ) != -1 )  || ( state.indexOf( "* BAD" ) != -1 ) ) {
			debug( "we are unable to cram-md5" );
			failure();
		}

		if ( state.indexOf( "a01 OK" ) != -1 ) {
			debug( "cramMD5ResponseHandler : okay" );
			select();
		}
	}

	function selectHandler( RESULT ) {
		debug( "selectHandler( " + RESULT + " )" );
		state += RESULT;

		if ( ( state.indexOf( "a02 BAD" ) != -1 ) || ( state.indexOf( "a02 NO" ) != -1 ) ) {
			debug( "we are unable to select" );
			failure();
		}

		if ( state.indexOf( "a02 OK" ) != -1 ) {
			debug( "selectHandler : successfull selected" );
			var exists = parseInt( state.match( /^\s*\*\s*(\d*)\s*EXISTS/m )[1] );
			//var recent = parseInt( state.match( /^\s*\*\s*(\d*)\s*RECENT/m )[1] );

			if ( exists > 0 ) {
				fetch();
			} else {
				REPORT_COUNT( 0 );
				logout();
			}
		}
	}

	function fetchHandler( RESULT ) {
		debug( "fetchHandler( " + RESULT + " )" );
		state += RESULT;

		if ( ( state.indexOf( "a03 BAD" ) != -1 ) || ( state.indexOf( "a03 NO" ) != -1 ) ) {
			debug( "we are unable to fetch" );
			failure();
		}

		if ( state.indexOf( "a03 OK" ) != -1 ) {
			debug( "fetchHandler : successfull fetched" );
			state = state.replace(/\r/g, '' );
			var splittedState = state.split( '\n' );
			var newMails = 0;

			for ( var i = 0; i < splittedState.length; i++ ) {
				if ( ( splittedState[i].indexOf( "UID" ) != -1 ) && ( splittedState[i].indexOf( "\\Seen" ) == -1 ) && ( splittedState[i].indexOf( "\\Deleted" ) == -1 ) ) {
					newMails++;
				}
			}

			debug( "fetchHandler : reporting " + newMails + " new mails" );
			REPORT_COUNT( newMails );

			if ( newMails > 0 ) {
				/* the most recent message is the one with no \seen, no \deleted and highest UID */
				state = state.replace(/\r/g, '' );
				var temp = state.split( '\n' );
				var latestMailID = 0;
				var latestMail = 0;

				for ( var i = 0; i < temp.length; i++ ) {
					if ( ( temp[i].indexOf( "\\Seen" ) == -1 ) && ( temp[i].indexOf( "\\Deleted" ) == -1 ) ) {
						if ( parseInt( temp[i].split( "UID " )[1] ) > latestMailID ) {
							latestMailID = parseInt( temp[i].split( "UID " )[1] );
							latestMail = parseInt( temp[i].split( "* " )[1] );
							debug( latestMailID + " - " + latestMail );
						}
					}
				}

				debug( "fetchHandler : try to fetch " + latestMail );
				fetchHeader( latestMail );
			} else {
				//LAST_MAIL( null, null, null );
				logout();
			}
		}
	}

	function fetchHeaderHandler( RESULT ) {
		debug( "fetchHeaderHandler( " + RESULT + " )" );
		state += RESULT;

		if ( ( state.indexOf( "a04 BAD" ) != -1 ) || ( state.indexOf( "a04 NO" ) != -1 ) ) {
			debug( "we are unable to fetch the Header" );
			failure();
		}

		if ( state.indexOf( "a04 OK" ) != -1 ) {
			debug( "fetchHeaderHandler : successfull fetched" );
			state = state.replace(/\r/g, '' );
			state = state.replace(/\n\s/g, ' ' );
			debug(state);
			//From: jim panse <jimpanse@example.com>
			//from: "Jim Panse" <jimpanse@example.com>
			//FROM: jimpanse@example.com (Jim Panse)
			//FROM: jimpanse@example.com
			var from = state.match( new RegExp( "(?:^From:\\s*(?:\\\"?\\s*(.*?)\\s*\\\"?)\\s*(?:<(.*)>)\\s*$)|(?:^From:\\s*(.*?)\\s*\\((.*)\\)\\s*$)|(?:^From:\\s*(.*?)\\s*$)", "mi" ) );
			var subject = state.match( /^Subject:\s*(.*)$/mi );
			var date = state.match( /^Date:\s*(.*)$/mi );

			if ( !date ) {
				date = state.match( /^Delivery-date:\s*(.*)$/mi );
			}

			debug( from );

			/*
			ranking
			1
			2 if 1.length == 0
			4
			3 if 4.length == 0
			5
			*/

			if ( from ) {
				debug( from );

				if ( from[1] != undefined ) {
					if ( from[1].length != 0 ) {
						from = from[1];
					} else {
						from = from[2];
					}
				} else {
					if ( from[4] != undefined ) {
						if ( from[4].length != 0 ) {
							from = from[4];
						} else {
							from = from[3];
						}
					} else {
						if ( from[5] != undefined ) {
							from = from[5];
						} else {
							from = "-";
						}
					}
				}
			} else {
				from = "-";
			}

			debug( from );

			if ( ( subject ) && ( subject.length > 1 ) && ( subject[0].indexOf( "\n" ) == -1 ) ) {
				subject = subject[1];
			} else {
				subject = "-";
			}

			if ( ( date ) && ( date.length > 1 ) && ( date[0].indexOf( "\n" ) == -1 ) ) {
				date = date[1];
			} else {
				date = "-";
			}

			debug( "eMail from : " + from + "\nSubject : " + subject + "\nReceived on : " + date );
			LAST_MAIL( from, subject, date );
			logout();
		}
	}

	function logoutHandler( RESULT ) {
		debug( "logoutHandler( " + RESULT + " )" );
		state += RESULT;

		if ( ( state.indexOf( "a05 BAD" ) != -1 ) || ( state.indexOf( "a05 NO" ) != -1 ) ) {
			debug( "unable to logout" );
			forceDisconnect();
		}

		if ( state.indexOf( "* BYE" ) != -1 ) {
			debug( "logoutHandler : we are out" );
            timeoutCounter = setTimeout( postLogout, 5000 );
		}
	}

    function postLogoutHandler( RESULT ) {
		debug( "postLogoutHandler( " + RESULT + " )" );
		state += RESULT;

        timeoutCounter = setTimeout( forceDisconnect, 5000 );
	}
}


text:
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE struts PUBLIC
	"-//Apache Software Foundation//DTD Struts Configuration 2.5//EN"
	"http://struts.apache.org/dtds/struts-2.5.dtd">
<struts>

  <constant name="struts.enable.DynamicMethodInvocation" value="false"/>
  <constant name="struts.devMode" value="false"/>
  <constant name="struts.custom.i18n.resources" value="package" />

</struts>


text:
var gulp = require('gulp')
,		isTravis = process.env.TRAVIS || false
,		hint = require('gulp-jshint')
,		stylus = require('gulp-stylus')
,		rename = require('gulp-rename')
,		stylish = require('jshint-stylish')
,		plato = require('gulp-plato')
,		uglify = require('gulp-uglify')
,		minifyCss = require('gulp-minify-css')
,		concat = require('gulp-concat')
,		sourcemaps = require('gulp-sourcemaps')
,		Server = require('karma').Server
,   plumber = require('gulp-plumber')
,   babel = require('gulp-babel')
,   runSequence = require('run-sequence')
,		paths = {
    src: ['./src/**/*.js','!**/*Spec.js'],
    stylus: ['./src/index.styl'],
    dist: ['./dist/']
  };

/**
* Minifica o CSS escrito com stylus, renomeia e coloca no dir. dist.
*/
gulp.task('minify-css',function(){
  return gulp.src(paths.stylus)
  .pipe(stylus())
  .pipe(rename('gumga.min.css'))
  .pipe(minifyCss())
  .pipe(gulp.dest('./dist'))
})

/**
* Minifica o JS, renomeia e coloca no dir. dist.
*/
gulp.task('minify-js',function(){
  return gulp.src(paths.src)
  .pipe(plumber())
  .pipe(babel())
  .pipe(concat('gumga.min.js'))
  .pipe(uglify())
  .pipe(gulp.dest('dist/'));
})

/**
* Executa o JSHint em cima dos arquivos Javascript.
*/
gulp.task('hint',function(){
  return gulp.src(paths.src)
  .pipe(hint())
  .pipe(hint.reporter(stylish))
})

/**
* Executa os testes unitários.
*/
gulp.task('tests',function(done){
  var config = {
    configFile: __dirname + '/karma.conf.js',
    singleRun: isTravis
  };
  var server = new Server(config,done);
  server.start();
})
/**
* Reporta complexidade do código.
*/
gulp.task('plato', function () {
  return gulp.src(paths.src)
  .pipe(plato('report', {
    jshint: {
      options: {
        strict: true
      }
    },
    complexity: {
      trycatch: true
    }
  }));
});

/**
* Usado para desenvolvimento,
* reexecuta as minificações CSS e JS a cada alteração.
*/
gulp.task('dev',['minify-js','minify-css'],function(){
  gulp.watch(paths.src,['minify-js']);
  gulp.watch(paths.stylus,['minify-css'])
});

/**
* Usado para desenvolvimento,
* reexecuta a minificação JS e os testes a cada alteração.
*/
gulp.task('tdd',function(){
  gulp.watch('./src/**/*.js', runSequence('minify-js','tests'));
});

gulp.task('js-watch', function(){
  gulp.watch(['./src/**/*.js','./index.html'], ['minify-js'])
})

/**
* Reporta cobertura de testes e complexidade do código.
*/
gulp.task('report',['plato']);

/**
* Valida qualidade do código com JSHint, executa os testes
* unitários e faz o report de cobertura e complexidade.
*/
gulp.task('ci-validate',['hint','tests']);

/**
* Executa as validações, minifica o CSS, JS e gera documentação.
*/
gulp.task('ci-build',['tests']);


text:
package voltric.clustering.multidimensional.mbc;

public class LearnDAGnoOverlapNoFeature {
}


text:
#include <assert.h>
#include <stdlib.h>

#include <dom/html/html_frame_element.h>

#include "html/html_document.h"
#include "html/html_frame_element.h"

#include "core/node.h"
#include "core/attr.h"
#include "utils/utils.h"

static struct dom_element_protected_vtable _protect_vtable = {
	{
		DOM_NODE_PROTECT_VTABLE_HTML_FRAME_ELEMENT
	},
	DOM_HTML_FRAME_ELEMENT_PROTECT_VTABLE
};

/**
 * Create a dom_html_frame_element object
 *
 * \param doc  The document object
 * \param ele  The returned element object
 * \return DOM_NO_ERR on success, appropriate dom_exception on failure.
 */
dom_exception _dom_html_frame_element_create(struct dom_html_document *doc,
		dom_string *namespace, dom_string *prefix,
		struct dom_html_frame_element **ele)
{
	struct dom_node_internal *node;

	*ele = malloc(sizeof(dom_html_frame_element));
	if (*ele == NULL)
		return DOM_NO_MEM_ERR;

	/* Set up vtables */
	node = (struct dom_node_internal *) *ele;
	node->base.vtable = &_dom_html_element_vtable;
	node->vtable = &_protect_vtable;

	return _dom_html_frame_element_initialise(doc, namespace, prefix, *ele);
}

/**
 * Initialise a dom_html_frame_element object
 *
 * \param doc  The document object
 * \param ele  The dom_html_frame_element object
 * \return DOM_NO_ERR on success, appropriate dom_exception on failure.
 */
dom_exception _dom_html_frame_element_initialise(struct dom_html_document *doc,
		dom_string *namespace, dom_string *prefix,
		struct dom_html_frame_element *ele)
{
	return _dom_html_element_initialise(doc, &ele->base,
					    doc->memoised[hds_FRAME],
					    namespace, prefix);
}

/**
 * Finalise a dom_html_frame_element object
 *
 * \param ele  The dom_html_frame_element object
 */
void _dom_html_frame_element_finalise(struct dom_html_frame_element *ele)
{
	_dom_html_element_finalise(&ele->base);
}

/**
 * Destroy a dom_html_frame_element object
 *
 * \param ele  The dom_html_frame_element object
 */
void _dom_html_frame_element_destroy(struct dom_html_frame_element *ele)
{
	_dom_html_frame_element_finalise(ele);
	free(ele);
}

/**
 * Get the no_resize property
 *
 * \param ele       The dom_html_frame_element object
 * \param no_resize  The status
 * \return DOM_NO_ERR on success, appropriate dom_exception on failure.
 */
dom_exception dom_html_frame_element_get_no_resize(dom_html_frame_element *ele,
		                bool *no_resize)
{
	        return dom_html_element_get_bool_property(&ele->base, "noresize",
				                        SLEN("noresize"), no_resize);
}

/**
 * Set the no_resize property
 *
 * \param ele       The dom_html_frame_element object
 * \param no_resize  The status
 * \return DOM_NO_ERR on success, appropriate dom_exception on failure.
 */
dom_exception dom_html_frame_element_set_no_resize(dom_html_frame_element *ele,
		                bool no_resize)
{
	        return dom_html_element_set_bool_property(&ele->base, "noresize",
				                        SLEN("noresize"), no_resize);
}

/*------------------------------------------------------------------------*/
/* The protected virtual functions */

/* The virtual function used to parse attribute value, see src/core/element.c
 * for detail */
dom_exception _dom_html_frame_element_parse_attribute(dom_element *ele,
		dom_string *name, dom_string *value,
		dom_string **parsed)
{
	UNUSED(ele);
	UNUSED(name);

	dom_string_ref(value);
	*parsed = value;

	return DOM_NO_ERR;
}

/* The virtual destroy function, see src/core/node.c for detail */
void _dom_virtual_html_frame_element_destroy(dom_node_internal *node)
{
	_dom_html_frame_element_destroy((struct dom_html_frame_element *) node);
}

/* The virtual copy function, see src/core/node.c for detail */
dom_exception _dom_html_frame_element_copy(dom_node_internal *old,
		                dom_node_internal **copy)
{
	        return _dom_html_element_copy(old, copy);
}

/*-----------------------------------------------------------------------*/
/* API functions */

#define SIMPLE_GET(attr)						\
	dom_exception dom_html_frame_element_get_##attr(		\
		dom_html_frame_element *element,			\
		dom_string **attr)					\
	{								\
		dom_exception ret;					\
		dom_string *_memo_##attr;				\
									\
		_memo_##attr =						\
			((struct dom_html_document *)			\
			 ((struct dom_node_internal *)element)->owner)->\
			memoised[hds_##attr];				\
									\
		ret = dom_element_get_attribute(element, _memo_##attr, attr); \
									\
		return ret;						\
	}
#define SIMPLE_SET(attr)						\
dom_exception dom_html_frame_element_set_##attr(			\
		dom_html_frame_element *element,			\
		dom_string *attr)					\
	{								\
		dom_exception ret;					\
		dom_string *_memo_##attr;				\
									\
		_memo_##attr =						\
			((struct dom_html_document *)			\
			 ((struct dom_node_internal *)element)->owner)->\
			memoised[hds_##attr];				\
									\
		ret = dom_element_set_attribute(element, _memo_##attr, attr); \
									\
		return ret;						\
	}

#define SIMPLE_GET_SET(attr) SIMPLE_GET(attr) SIMPLE_SET(attr)

SIMPLE_GET_SET(long_desc);
SIMPLE_GET_SET(name);
SIMPLE_GET_SET(src);
SIMPLE_GET_SET(frame_border);
SIMPLE_GET_SET(margin_width);
SIMPLE_GET_SET(margin_height);
SIMPLE_GET_SET(scrolling);

dom_exception dom_html_frame_element_get_content_document(
		dom_html_frame_element *ele,
		dom_document **content_document)
{
	/* We don't support creating documents
	   from within here */
	UNUSED(ele);
	UNUSED(content_document);
	return DOM_NOT_SUPPORTED_ERR;
}


text:
<?php
require_once("../includes/initialize.php");

//init code
$photo_object = new Photograph();
$admin_user_object = new AdminUser();
$bus_personnel_object = new BusPersonnel();

$route_object = new BusRoute();
$bus_object = new Bus();
$bus_bus_personnel_object = new BusBusPersonnel();

//check login
if ($session->is_logged_in()){

	if ($session->object_type == 5){

		$session->message("The requested page is for use by Bus Personnel only. ");
		redirect_to("index.php");

	} else if ($session->object_type == 4) {
		//bus personnel

		$user = $bus_personnel_object->find_by_id($_SESSION['id']);
		$profile_picture = $photo_object->get_profile_picture($session->object_type, $user->id);

		if ($user->role == 1 || $user->role == 4 || $user->role == 5){
			//bus_personnel that is logged in is an owner (role is 1 (Owner), 4 (Owner + Driver) or 5 (Owner + Conductor))
			$buses = $bus_bus_personnel_object->get_buses_for_personnel($user->id);
		} else if ($user->role == 2 || $user->role == 3) {
			//bus_personnel that is logged in is not an owner

			$buses = $bus_bus_personnel_object->get_buses_for_personnel($user->id);
		}

	} else {
		//everyone else

		$session->message("Error! You do not have sufficient priviledges to view the requested page. ");
		redirect_to("index.php");
	}

} else {
	//not logged in... GTFO!

	$session->message("Error! You must login to view the requested page. ");
	redirect_to("login.php");
}

?>

<!DOCTYPE html>

    <title>Buses List · <?php echo WEB_APP_NAME; ?></title>
    <?php require_once('../includes/layouts/header_admin.php');?>

      <?php require_once('../includes/layouts/navbar_admin.php');?>

List of Buses

        <?php

        if(!empty($session->message)){

        	echo '
';
        	echo '<button type="button" class="close" data-dismiss="alert">×</button>';
        	//echo '
';
        	echo $session->message;
        	//echo '
';
        	echo '
';
        }

        ?>

		        Route Number
		        Registration Number
		        Name (Optional)
		        <?php if ($user->role == 1 || $user->role == 4 || $user->role == 5){ ?>

		        <?php } ?>

        	<?php foreach($buses as $bus){ ?>

	        		<a href="admin_read_update_route.php?routeid=<?php echo $route_object->find_by_id($bus_object->find_by_id($bus->bus_id)->route_id)->id; ?>" class="btn btn-info btn-bloc"><?php echo $route_object->find_by_id($bus_object->find_by_id($bus->bus_id)->route_id)->route_number; ?>
	        		<a href="admin_read_update_bus.php?busid=<?php echo $bus->bus_id; ?>" class="btn btn-warning btn-bloc"><?php echo $bus_object->find_by_id($bus->bus_id)->reg_number; ?>
	        		<?php if (!empty($bus_object->find_by_id($bus->bus_id)->name)) {echo $bus_object->find_by_id($bus->bus_id)->name;} ?>
	        		<?php if ($user->role == 1 || $user->role == 4 || $user->role == 5){ ?>
	        		<a href="admin_read_update_bus.php?busid=<?php echo $bus->bus_id; ?>" class="btn btn-warning btn-block"> Edit
	        		<?php } ?>

        	<?php } ?>

    <?php require_once('../includes/layouts/footer_admin.php');?>

    <?php require_once('../includes/layouts/scripts_admin.php');?>


text:
		{% for highlight in nuggets %}

						{{ highlight.text }}

					{{ highlight.theme }}
					 |
					{{ highlight.author_name }}
					 |
					{{ highlight.created_at_pretty }}

						remove
						 |
						context

		{% endfor %}


text:
//
// This file is part of nuBASIC
// Copyright (c) Antonino Calderone (antonino.calderone@gmail.com)
// All rights reserved.
// Licensed under the MIT License.
// See COPYING file in the project root for full license information.
//

/* -------------------------------------------------------------------------- */

#ifndef __NU_EXPR_PARSER_H__
#define __NU_EXPR_PARSER_H__

/* -------------------------------------------------------------------------- */

#include "nu_exception.h"
#include "nu_expr_any.h"
#include "nu_expr_tknzr.h"
#include "nu_proc_scope.h"
#include "nu_token_list.h"
#include "nu_var_scope.h"

#include <list>

/* -------------------------------------------------------------------------- */

namespace nu {

/* -------------------------------------------------------------------------- */

class expr_parser_t {
public:
    //! ctors
    expr_parser_t() = default;
    expr_parser_t(const expr_parser_t&) = delete;
    expr_parser_t& operator=(const expr_parser_t&) = delete;

    //! Creates an expression using tokens got by a given tokenizer
    expr_any_t::handle_t compile(expr_tknzr_t& tknzr);

    //! Creates an expression using a given token-list
    expr_any_t::handle_t compile(token_list_t tl, size_t expr_pos);

protected:
    static variant_t::type_t get_type(const token_t& t);

    expr_any_t::handle_t parse_operand(token_list_t& tl);

    bool parse_operator(token_list_t& tl, std::string& value);

    expr_any_t::handle_t parse(
        token_list_t& tl, expr_any_t::handle_t first_param = nullptr);

    static void reduce_brackets(token_list_t& rtl);
    static void convert_subscription_brackets(token_list_t& rtl);
    static void fix_real_numbers(token_list_t& rtl);

    // There are expressions which begin with '-' operator (e.g. -<exp>)
    // which need to be transformed into 0-<exp> in order to
    // be process correctly later
    static void fix_minus_prefixed_expressions(token_list_t& rtl);
};

/* -------------------------------------------------------------------------- */
}

/* -------------------------------------------------------------------------- */

#endif // __NU_EXPR_PARSER_H__


text:
- **Maven POM file :** This is a Required field. Provide relative path from the repo root to the Maven POM .xml file. [Click here to know more about POM] (https://maven.apache.org/guides/introduction/introduction-to-the-pom.html)

- **Options :** Specify any Maven options you want to use

- **Goal(s) :** In most cases, set this to `package` to compile your code and package it into a .war file. If you leave this argument blank, the build will fail. [Click here to know more about Maven Build Lifecycle](https://maven.apache.org/guides/introduction/introduction-to-the-lifecycle.html)

#### JUnit Test Results
Use the next three options to manage your JUnit test results in VSTS

- **Publish to VSTS/TFS :** Select this option to publish JUnit Test results produced by the Maven build to Visual Studio Team Services/TFS. Each test result file matching `Test Results Files` will be published as a test run in VSTS/TFS.

- **Test Results Files :** This option will appear if you select the above option. Here, provide Test results files path. Wildcards can be used. For example, `**/TEST-*.xml` for all xml files whose name starts with `TEST-."`. Defaults to `$(System.DefaultWorkingDirectory)`

- **Test Run Title :** This option will appear if you select the `Publish to VSTS/TFS` option. Here provide a name for the Test Run

#### Code Coverage
Use the next options to manage your code coverage options. If your Build file already has Code Coverage enabled, you can ignore this section and use the Publish Code Coverage task to upload results to TFS/VSTS

- **CodeCoverage Tool :** Select the code coverage tool you want to use. Currently JaCoCo and Cobertura are supported. [Click here](http://eclemma.org/jacoco/trunk/doc/maven.html) to know more about Jacoco and [Click here](http://www.mojohaus.org/cobertura-maven-plugin/index.html) to know more about Cobertura.

- **Class Inclusion/Exclusion Filters :** This option is enabled only when you select one tool in the above option. Provide a
comma separated list of filters to include or exclude classes from collecting code coverage. For example: +:com.*,+:org.*,-:my.app*.*.
- **Class Files Directories :** This option is enabled only when you select JaCoCo as code coverage tool. This field is required for a multi module project. Specify comma separated list of relative paths from Maven POM file to directories containing class files, archive files(jar, war etc.). Code coverage is reported for class files present in the directories. For example: target/classes,target/testClasses.

- **Source Files Directories :** This option is enabled only when you select JaCoCo as code coverage tool. This field is required for a multi module project. Specify comma separated list of relative paths from Maven POM file to source directories. Code coverage reports will use these to highlight source code. For example: src/java,src/Test.

#### Advanced
Use the next options to manage your `JAVA_HOME` attribute by JDK Version and Path

- **Set JAVA_HOME by :** Select to set `JAVA_HOME` either by providing a path or let VSTS set the `JAVA_HOME` based on JDK version choosen. By default it is set to `JDK Version`

- **JDK Version :** Here provide the PATH to `JAVA_HOME` if you want to set it by path or select the appropriate JDK verision.

- **JDK Architecture :** Select the approriate JDK Architecture. By default it is set to `x86`

#### Code Analysis

- **Run SonarQube Analysis :** You can choose to run SonarQube analysis after executing the current goals. 'install' or 'package' goals should be executed first. To know more about this option [click here](https://blogs.msdn.com/b/visualstudioalm/archive/2015/10/08/the-maven-build-task-now-simplifies-sonarqube-analysis.aspx)

- **Run Checkstyle :** You can choose to run the Checkstyle static code analysis tool, which checks the compliance of your source code with coding rules. You will receive a code analysis report with the number of violations detected, as well as the original report files if there were any violations.

- **Run PMD :** You can choose to run the PMD static code analysis tool, which examines your source code for possible bugs. You will receive a code analysis report with the number of violations detected, as well as the original report files if there were any violations.

- **Run FindBugs :** You can choose to run the FindBugs static code analysis tool, which examines the bytecode of your program for possible bugs. You will receive a code analysis report with the number of violations detected, as well as the original report files if there were any violations.


text:
require 'spec_helper'

module Refinery
  module Stylesheets
    describe StylesheetsHelper do
      describe "#css_for_refinery" do
        let!(:stylesheet1) { Factory :stylesheet }
        let!(:stylesheet2) { Factory :stylesheet }

        it "should return all paths for custom stylesheets" do
          helper.css_for_refinery.should match stylesheet_link_tag(raw("/stylesheets/stylesheets/#{stylesheet1.to_param}"))
          helper.css_for_refinery.should match stylesheet_link_tag(raw("/stylesheets/stylesheets/#{stylesheet2.to_param}"))
        end
      end
    end
  end
end


text:
package org.openntf.domino.nsfdata.structs;

/**
 * (editods.h)
 *
 * @since Lotus Notes/Domino 5.0
 *
 */
public enum RepeatType {
	UNDEFINED, ONCE, VERT, HORIZ, BOTH, SIZE, CENTER
}


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Free.Dolphin.Core
{
    public class ControllerAuthAttribute : Attribute
    {

    }
}


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using MiningRigRentalsApi.Converters;
using Newtonsoft.Json;

namespace MiningRigRentalsApi.ObjectModel
{
	public class RentalDetails
	{
		public uint id;
		public uint rigid;
		public string name;
		[JsonProperty("start_time")]
		[JsonConverter(typeof(PhpDateTimeConverter))]
		public DateTime starttime;
		public string renter;
		public string region;
		public string type;
		public RentalHashrate hashrate;
		public double price;
		public uint length;
		public string status;
		public double? left;
	}

	public class RentalHashrate
	{
		public ulong advertised;
		public string average;
		[JsonProperty("5min")]
		public double min5;
		[JsonProperty("30min")]
		public double min30;
		[JsonProperty("60min")]
		public double min60;
	}
}


text:
<?php
  include_once('../form_products_dependent/form_products_dependent.php');
?>


text:
package org.sfs.validate;

import com.google.common.base.Optional;
import io.vertx.core.json.JsonObject;
import org.sfs.util.HttpRequestValidationException;
import org.sfs.vo.PersistentObject;
import org.sfs.vo.TransientVersion;
import rx.functions.Func1;

import static java.lang.String.format;
import static java.net.HttpURLConnection.HTTP_NOT_FOUND;

public class ValidatePersistentObjectVersionExists implements Func1<PersistentObject, TransientVersion> {

    private final long version;

    public ValidatePersistentObjectVersionExists(long version) {
        this.version = version;
    }

    @Override
    public TransientVersion call(PersistentObject persistentObject) {
        Optional<TransientVersion> found = persistentObject.getVersion(version);
        if (!found.isPresent()) {

            JsonObject jsonObject = new JsonObject()
                    .put("message", format("Version %d does not exist", version));

            throw new HttpRequestValidationException(HTTP_NOT_FOUND, jsonObject);
        }
        return found.get();
    }
}


text:
package org.apache.oodt.cas.curation.util;

//JDK imports
import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

//OODT imports
import org.apache.oodt.cas.curation.service.CurationServiceConfig;
import org.apache.oodt.cas.curation.config.CuratorConfMetKeys;
import org.apache.oodt.security.sso.AbstractWebBasedSingleSignOn;
import org.apache.oodt.security.sso.SingleSignOnFactory;

/**
 *
 * Utilities for configuring the {@link AbstractWebBasedSingleSignOn} for use
 * in the CAS curator webapp.
 *
 * @author mattmann
 * @version $Revision$
 *
 */
public class SSOUtils implements CuratorConfMetKeys {

  public static AbstractWebBasedSingleSignOn getWebSingleSignOn(
      ServletContext context, HttpServletRequest req, HttpServletResponse res) {
    AbstractWebBasedSingleSignOn sso = SingleSignOnFactory
        .getWebBasedSingleSignOn(context.getInitParameter(SSO_IMPL_CLASS));
    sso.setReq(req);
    sso.setRes(res);
    return sso;
  }

  public static AbstractWebBasedSingleSignOn getWebSingleSignOn(
      CurationServiceConfig cfg, HttpServletRequest req, HttpServletResponse res) {
    AbstractWebBasedSingleSignOn sso = SingleSignOnFactory
        .getWebBasedSingleSignOn(cfg.getParameter(SSO_IMPL_CLASS));
    sso.setReq(req);
    sso.setRes(res);
    return sso;
  }
}


text:
module.exports = function tap (selector, x, y, tapCount, touchCount, duration, callback) {

    if(arguments.length === 2 && typeof x === 'function') {
        callback = x;
        x = null;
    } else if(arguments.length === 3 && typeof y === 'function') {
        callback = y;
        y = null;
    } else if(arguments.length === 4 && typeof tapCount === 'function') {
        callback = tapCount;
        tapCount = null;
    } else if(arguments.length === 5 && typeof touchCount === 'function') {
        callback = touchCount;
        touchCount = null;
    } else if(arguments.length === 6 && typeof duration === 'function') {
        callback = duration;
        duration = null;
    }

    if(typeof selector === 'string' && selector !== '') {

        this.element(selector, function(err,res) {

            if(err === null && res.value) {

                if(this.desiredCapabilities.browserName || this.desiredCapabilities.app === 'safari') {

                    this.elementIdLocation(res.value.ELEMENT, function(errLocation,location) {
                        this.elementIdSize(res.value.ELEMENT, function(errSize,size) {

                            location = location.value;
                            size     = size.value;

                            if(!errLocation && !errSize) {

                                this.scroll(0, location.y - 100)
                                    .touchTap(tapCount, touchCount, duration, location.x + (size.width / 2), 100 + (size.height / 2), null, callback)
                                    .pause(250);

                            } else {

                                if(typeof callback === 'function') {
                                    /* istanbul ignore next */
                                    callback([errLocation,errSize]);
                                }

                            }

                        });
                    });

                } else {

                    this.touchTap(tapCount, touchCount, duration, x, y, res.value.ELEMENT, callback);

                }

            } else {

                if(typeof callback === 'function') {
                    /* istanbul ignore next */
                    callback(err,res);
                }

            }

        });

    } else {

        this.touchTap(tapCount, touchCount, duration, x, y, null, callback);

    }

};


text:
require 'mspec/utils/version'

module StringSymbolAdapter
  def convert_name(name)
    version = SpecVersion.new(RUBY_VERSION) <=> "1.9"
    version < 0 ? name.to_s : name.to_sym
  end
end