text:
/* ============ */
/* = DC Reset = */
/* ============ */
.DC-search-embed div, .DC-search-embed span, .DC-search-embed a {
  margin: 0;
  padding: 0;
  border: 0;
  outline: 0;
  font-weight: inherit;
  font-style: inherit;
  font-size: 100%;
  font-family: inherit;
  vertical-align: baseline;
}

.DC-search-embed .DC-document-list a,
.DC-search-embed .DC-document-list a:link,
.DC-search-embed .DC-document-list a:visited,
.DC-search-embed .DC-document-list a:active {
  color: #555599;
  text-decoration: underline;
}

.DC-search-embed .DC-hidden {
  visibility: hidden;
}

.DC-search-embed .DC-quiet-link {
  white-space: nowrap;
  cursor: pointer;
  color: #808080;
  text-decoration: none;
}
  .DC-search-embed .DC-quiet-link:hover {
    color: #000;
    text-decoration: underline;
  }

.DC-search-embed a,
.DC-search-embed a:hover,
.DC-search-embed .DC-document-list a:hover,
.DC-search-embed .DC-paginator a:hover {
  background-color: transparent;
}
/* ========================== */
/* = Search Embed Workspace = */
/* ========================== */

.DC-search-embed {
  clear: both;
  overflow: hidden;
  font: 16px/20px Helvetica,Arial;
  margin: 12px 0;
}

.DC-search-embed .DC-no-results {
  position: relative;
  margin: 0 0 32px 24px;
  padding: 0 0 0 75px;
  height: 77px;
  font-size: 14px;
  color: #333;
}
  .DC-search-embed .DC-no-results .DC-icon {
    position: absolute;
    top: 10px; left: 0px;
  }
  .DC-search-embed .DC-explanation {
    padding-top: 30px;
  }

.DC-search-embed .DC-document-list {
  overflow: hidden;
}

.DC-search-embed .DC-interface {
 font-family: "Lucida Grande","Lucida Sans Unicode", Helvetica, Arial;
}

.DC-search-embed.DC-unselectable {
  -webkit-user-select: none;
  -moz-user-select: none;
  user-select: none;
}

.DC-search-embed .DC-title {
  font-size: 24px;
  margin: 6px 0 18px;
  font-weight: bold;
  text-align: center;
}

/* ========== */
/* = Search = */
/* ========== */

.DC-search-embed .DC-search {
  margin: 0 0 15px;
}
.DC-search-embed .DC-text-input {
  position: relative;
  height: 30px;
  background: transparent url(/images/search_embed/embed/text_input_large_left.png) no-repeat center left;
}
  .DC-search-embed .DC-text-input .DC-placeholder {
    position: absolute;
    cursor: text;
    left: 1px;
    top: 5px;
    color: #c0c0c0;
    font-size: 13px;
    line-height: 18px;
  }
  .DC-search-embed .DC-text-input input {
    display: block;
    border: none;
    outline: none;
    margin: 0;
    padding: 4px;
    background: transparent;
    font-size: 16px;
    line-height: 18px;
    width: 100%;
    color: #000;
    font-size: 13px;
    font-family: "Lucida Grande","Lucida Sans Unicode",Helvetica,Arial,sans-serif !important;
    width: 100%;
  }
  .DC-search-embed .DC-text-input.DC-search {
    height: 28px;
    background: transparent;
    border: 2px solid #ccc;
    border-radius: 16px; -webkit-border-radius: 16px; -moz-border-radius: 16px;
    background-color: #fafafa;
    -webkit-box-shadow: inset 0px 0px 3px #ccc;
    -moz-box-shadow: inset 0px 0px 3px #ccc;
    box-shadow: inset 0px 0px 3px #ccc;
  }
    .DC-search-embed .DC-search-embed .DC-text-input.DC-search:focus {
      border-color: #acf;
      -webkit-box-shadow: inset 0px 0px 3px #acf;
      -moz-box-shadow: inset 0px 0px 3px #acf;
      box-shadow: inset 0px 0px 3px #acf;
    }
    .DC-search-embed .DC-text-input .DC-search-inner {
      position: relative;
      margin: 0 28px;
    }
      .DC-search-embed .DC-text-input.DC-search input {
        width: 100%;
        height: 18px;
        padding: 5px 0;
      }
        .DC-search-embed .DC-text-input.DC-search input:-moz-placeholder {
          color: #808080;
        }
        .DC-search-embed .DC-text-input.DC-search:focus input {
          color: #000;
        }
    .DC-search-embed .DC-text-input .DC-search-glyph {
      position: absolute;
      left: 10px; top: 8px;
    }
    .DC-search-embed .DC-text-input .DC-cancel-search {
      position: absolute;
      right: 9px; top: 8px;
    }
      .DC-search-embed.DC-query-original .DC-cancel-search {
        display: none;
      }

/* ================== */
/* = Document Tiles = */
/* ================== */

.DC-search-embed .DC-document-tile {
  display: block;
  float: left;
  width: 230px;
  border: 1px solid transparent;
  height: 86px;
  margin: 0 15px 0 0;
  padding: 0 0 15px 80px;
  position: relative;
  overflow: hidden;
  outline: none;
}
  .DC-search-embed .DC-document-list a.DC-document-tile {
    text-decoration: none;
  }
  .DC-search-embed .DC-document-tile:hover {
    cursor: pointer;
  }
  .DC-search-embed .DC-document-thumbnail {
    position: absolute;
    left: 3px;
    top: 3px;
    margin: 0 6px 4px 0;
    width: 70px;
    height: 85px;
  }
    .DC-search-embed .DC-document-thumbnail img {
      border: 1px solid #aaa;
      width: 60px;
      height: 75px;
      margin: 0; padding: 1px;
      background-color: #fff;
      float: none;
    }
    .DC-search-embed .DC-document-tile:hover .DC-document-thumbnail img {
      border-color: #808080;
    }
  .DC-search-embed .DC-document-thumbnail-select {
    position: absolute;
    margin: 0 6px 4px 0;
    background-color: #e0e0e0;
    width: 63px;
    height: 78px;
    left: 6px;
    top: 6px;
  }
    .DC-search-embed .DC-document-tile:hover .DC-document-thumbnail-select {
    background-color: #c7c7c7;
    }
  .DC-search-embed .DC-document-title {
    color: #000;
    font-size: 14px;
    font-weight: bold;
    line-height: 17px;
    margin: 2px 0 2px 0;
  }
    .DC-search-embed .DC-document-tile:hover .DC-document-title {
      text-decoration: underline;
    }
  .DC-search-embed .DC-document-description {
    color: #333;
    font-family: Georgia;
    font-size: 12px;
    line-height: 14px;
    overflow: hidden;
    height: 44px;
  }
    .DC-search-embed .DC-show-organization .DC-document-description {
      height: 30px;
    }
  .DC-search-embed .DC-document-organization {
    color: #808080;
    font-size: 10px;
    line-height: 12px;
    margin: 4px 0 0 0;
  }
  .DC-search-embed .DC-document-tile .DC-icon-lock {
    display: none;
  }
    .DC-search-embed .DC-document-tile.DC-document-private .DC-icon-lock {
      display: block;
      float: right;
      margin-left: 4px;
    }

/* ============= */
/* = Paginator = */
/* ============= */

.DC-search-embed .DC-arrow {
  font-size: 17px;
  line-height: 11px;
  position: relative;
  display: inline-block;
  cursor: pointer;
  top: 2px;
}
  .DC-search-embed .DC-arrow:hover {
    color: #000;
  }
  .DC-search-embed .DC-arrow.DC-arrow-left {
    padding-right: 4px;
  }
  .DC-search-embed .DC-arrow.DC-arrowright {
    padding-left: 4px;
  }

.DC-search-embed .DC-paginator {
  padding: 6px 0 0;
  margin: 0;
  font-size: 11px;
  line-height: 18px;
  height: 18px;
  color: #808080;
  border-top: 1px solid #ccc;
  position: relative;
}
  .DC-search-embed .DC-paginator a img {
    border: none;
    float: none;
  }
  .DC-search-embed .DC-paginator .DC-paginator-description {
    position: absolute;
    left: 0;
    top: 6px;
    white-space: nowrap;
  }
    .DC-search-embed .DC-paginator .DC-paginator-range {
      font-weight: bold;
    }
  .DC-search-embed .DC-paginator .DC-paginator-enumeration {
    position: absolute;
    width: 200px;
    left: 50%;
    margin-left: -50px;
    text-align: left;
    height: 20px;
  }
    .DC-search-embed.DC-skinny-width .DC-paginator .DC-paginator-enumeration {
      right: 0;
      left: auto;
      width: auto;
    }
    .DC-search-embed .DC-paginator .DC-page-current {
      font-weight: bold;
    }
      .DC-search-embed .DC-paginator.DC-is-editing .DC-page-current {
        display: none;
      }
    .DC-search-embed .DC-paginator .DC-page-edit {
      display: none;
      position: relative;
      width: 18px;
      font-size: 11px;
      height: 16px;
      text-align: center;
      color: #808080;
      padding: 0;
      border: 1px solid #C0C0C0
    }
      .DC-search-embed .DC-paginator.DC-is-editing .DC-page-edit {
        display: inline;
      }
      .DC-search-embed .DC-paginator .DC-page-edit:focus {
        color: #000;
      }
  .DC-search-embed .DC-paginator .DC-logo {
    position: absolute;
    right: 0; top: 4px;
    width: 105px; height: 19px;
    background: url(/images/search_embed/embed/dc_inline_logo.png);
  }
    .DC-search-embed.DC-skinny-width .DC-paginator .DC-logo {
      display: none;
    }

/* ========= */
/* = Icons = */
/* ========= */

.DC-search-embed .DC-icon.DC-search-glyph {
  width: 12px; height: 12px;
  background-image: url(/images/search_embed/embed/search_glyph.png);
}
  .DC-search-embed .DC-icon.DC-search-glyph.DC-spinner {
    width: 16px;
    height: 16px;
    left: 7px;
    top: 6px;
    background-image: url(/images/search_embed/embed/spinner_circle.gif);
  }

.DC-search-embed .DC-icon.DC-cancel-search {
  width: 11px; height: 11px;
  background-position: center 0;
  background-image: url(/images/search_embed/embed/cancel_search.png);
  cursor: pointer;
}
  .DC-search-embed .DC-icon.DC-cancel-search:hover {
    background-position: center -11px;
  }
.DC-icon.DC-document {
  width: 60px;
  height: 75px;
  background-image: url(/images/search_embed/embed/generic.png);
  border: 0;
}
.DC-icon.DC-icon-lock {
  background: transparent url(/images/search_embed/embed/lock.png) no-repeat 0 0;
  width: 18px;
  height: 18px;
}

/* ================= */
/* = Embed Preview = */
/* ================= */

.DC-embed-preview {
  width: 900px;
  margin: 50px auto;
}
  .DC-embed-preview .DC-search-embed {
    margin: 50px 0;
  }


text:
package com.github.gwt.user.client.ui.events;

import com.google.gwt.event.shared.EventHandler;
import com.google.gwt.event.shared.GwtEvent;

/**
 * Represents drill down event.
 *
 * @author Rinat Enikeev (rinat.enikeev[at]gmail[dot]com)
 * @version %I%, %G%
 * @since 1.0
 */
public class DrillDownEvent<T> extends GwtEvent<DrillDownEvent.Handler<T>> {
    public static Type<Handler<?>> TYPE = new Type<Handler<?>>();

    public interface Handler<T> extends EventHandler {
        void onEvent(DrillDownEvent<T> event);
    }

    public T getInfo() {
        return info;
    }

    private final T info;

    protected DrillDownEvent(T info) {
        this.info = info;
    }

    @Override
    @SuppressWarnings("unchecked")
    public Type<Handler<T>> getAssociatedType() {
        return (Type) TYPE;
    }

    @Override
    protected void dispatch(Handler<T> handler) {
        handler.onEvent(this);
    }

    public static <T> void fire(HasDrillDownHandlers<T> source) {
        if (TYPE != null) {
            DrillDownEvent<T> event = new DrillDownEvent<T>(null);
            source.fireEvent(event);
        }
    }

    public static <T> void fire(HasDrillDownHandlers<T> source, T object) {
        if (TYPE != null) {
            DrillDownEvent<T> event = new DrillDownEvent<T>(object);
            source.fireEvent(event);
        }
    }
}

redpajama_set_name: RedPajamaGithub


text:
import React from "react"

import { DumbComponent } from "../../Components"
import MenuItem from "./MenuItem"

export default class Menu extends DumbComponent {
    render() {

        var items = [
            <MenuItem title="What's new" />,
            <MenuItem title="Rooms" />,
            <MenuItem title="Events" />,
            <MenuItem title="Playlists" />,
            <MenuItem title="Chat" />
        ].map(function(item) {
           return (

                    {item}

           );
        });

        return (

                {items}

        );
    }
}


text:
using System.Runtime.InteropServices;
using Spect.Net.VsPackage.Vsx;

namespace Spect.Net.VsPackage.CustomEditors.VfddEditor
{
    /// <summary>
    /// Editor factory class for the ROM viewer
    /// </summary>
    [Guid(FACTORY_ID)]
    public class VfddEditorFactory : EditorFactoryBase<VfddEditorPane>
    {
        public const string FACTORY_ID = "7D994DE6-374C-4A84-9EB0-E2CE2434C1A6";
        public const string EXTENSION = ".vfdd";
    }
}


text:
package com.bitmap.monochrome;

/**
 * Created by sf on 2017/8/28.
 */

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;

import android.os.AsyncTask;
import android.os.Environment;
import android.app.ProgressDialog;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.util.Log;
import android.widget.Toast;

public class BitmapConvertor{

  private int mDataWidth;
  private byte mRawBitmapData[];
  private byte[] mDataArray;
  private static final String TAG = "BitmapConvertor";
  private ProgressDialog mPd;
  private Context mContext;
  private int mWidth, mHeight;
  private String mStatus;
  private String mFileName;

  public BitmapConvertor(Context context) {
    // TODO Auto-generated constructor stub
    mContext = context;
  }

  /**
   * Converts the input image to 1bpp-monochrome bitmap
   * @param inputBitmap : Bitmpa to be converted
   * @param fileName : Save-As filename
   * @return :  Returns a String. Success when the file is saved on memory card or error.
   */
  public String convertBitmap(Bitmap inputBitmap, String fileName){

    mWidth = inputBitmap.getWidth();
    mHeight = inputBitmap.getHeight();
    mFileName = fileName;
    mDataWidth=((mWidth+31)/32)*4*8;
    mDataArray = new byte[(mDataWidth * mHeight)];
    mRawBitmapData = new byte[(mDataWidth * mHeight) / 8];
    //ConvertInBackground convert = new ConvertInBackground();
    //convert.execute(inputBitmap);
        convertArgbToGrayscale(inputBitmap, mWidth, mHeight);
        createRawMonochromeData();
        mStatus = saveImage(mFileName, mWidth, mHeight);
    return mStatus;

  }

  private void convertArgbToGrayscale(Bitmap bmpOriginal, int width, int height){
    int pixel;
    int k = 0;
    int B=0,G=0,R=0;
    try{
      for(int x = 0; x < height; x++) {
        for(int y = 0; y < width; y++, k++) {
          // get one pixel color
          pixel = bmpOriginal.getPixel(y, x);

          // retrieve color of all channels
          R = Color.red(pixel);
          G = Color.green(pixel);
          B = Color.blue(pixel);
          // take conversion up to one single value by calculating pixel intensity.
          R = G = B = (int)(0.299 * R + 0.587 * G + 0.114 * B);
          // set new pixel color to output bitmap
          if (R < 128) {
            mDataArray[k] = 0;
          } else {
            mDataArray[k] = 1;
          }
        }
        if(mDataWidth>width){
          for(int p=width;p<mDataWidth;p++,k++){
            mDataArray[k]=0;
          }
        }
      }
    }catch (Exception e) {
      // TODO: handle exception
      Log.e(TAG, e.toString());
    }
  }

  private void createRawMonochromeData(){
    int length = 0;
    for (int i = 0; i < mDataArray.length; i = i + 8) {

      byte first = mDataArray[i];
      for (int j = 1; j < 8; j++) {

        byte second = (byte) ((first << 1) | mDataArray[i + j]);
        first = second;
      }
      mRawBitmapData[length] = first;

      length++;
    }
  }

  private String saveImage(String fileName, int width, int height) {
    FileOutputStream fileOutputStream;
    BMPFile bmpFile = new BMPFile();
    File file = new File( fileName  );
    try {
      file.createNewFile();
      fileOutputStream = new FileOutputStream(file);
    } catch (IOException e) {
      // TODO Auto-generated catch block
      //e.printStackTrace();
      Log.e(TAG, e.toString());
      return "Memory Access Denied";
    }
    bmpFile.saveBitmap(fileOutputStream, mRawBitmapData, width, height);
    return "Success";
  }

  //class ConvertInBackground extends AsyncTask<Bitmap, String, Void>{
  //
  //  @Override
  //  protected Void doInBackground(Bitmap... params) {
  //    // TODO Auto-generated method stub
  //    convertArgbToGrayscale(params[0], mWidth, mHeight);
  //    createRawMonochromeData();
  //    mStatus = saveImage(mFileName, mWidth, mHeight);
  //    return null;
  //  }
  //
  //
  //  @Override
  //  protected void onPostExecute(Void result) {
  //    // TODO Auto-generated method stub
  //    mPd.dismiss();
  //    Toast.makeText(mContext, "Monochrome bitmap created successfully. Please check in sdcard", Toast.LENGTH_LONG).show();
  //  }
  //
  //
  //  @Override
  //  protected void onPreExecute() {
  //    // TODO Auto-generated method stub
  //    mPd= ProgressDialog.show(mContext, "Converting Image", "Please Wait", true, false, null);
  //  }
  //
  //
  //
  //}
}


text:
local string_format = string.format

local actor = tengine.actor

local ERROR_MSG = tengine.ERROR_MSG

local p = tengine.p

local ps = require("framework").player_status

local player =  require('game.player')

local lobby = require('game.lobby')

local  _M = {}

function _M.command(account)
    local _player = player.find(account)
    if _player then
        return
    end

    local _table_id = player:table()
    if _table_id ~= 0 then
        local _table = lobby:table(_table_id)
        if _table then
            _table:on_offline(player)
        end
    else
        _player:set_status(ps.PLAYER_STATUS_NULL, 0, 0)
    end

end

return _M


text:
/*
 * Copyright (c) 2015 Spotify AB
 *
 * Licensed under the Apache License, Version 2.0 (the "License"); you may not
 * use this file except in compliance with the License. You may obtain a copy of
 * the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
 * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
 * License for the specific language governing permissions and limitations under
 * the License.
 */
package com.spotify.missinglink.datamodel;

import io.norberg.automatter.AutoMatter;
import java.util.Map;

@AutoMatter
public interface Artifact {

  /** "Name" of artifact, for example a directory path or jar file or something else symbolic. */
  ArtifactName name();

  /** Map of classname to class object. Names are com/foo/bar/Baz. Returned map is immutable. */
  Map<ClassTypeDescriptor, DeclaredClass> classes();
}


text:
function obj = fromList(obj, W, H)
%FROMLIST Reshape a list of spectra into the given shape
% c2 = c1.FROMLIST(width, height) attempts to restructure the
% (W * H) x 1 x Bands Cube c1 into an Width x Height x Bands cube c2.
% The order is the reverse of
% If the given dimensions do not match the Cube area or if the
% Cube data has width greater than 1, an error will be thrown.
%
% See also: TOLIST, MASK, UNMASK

assert(obj.Height == obj.Area, ...
    'Cube:NotAList', 'Cube data must be columnwise ordered list of spectra.');
assert(W * H == obj.Area, ...
    'Cube:InvalidArea', ...
    'Given width and height (%d x %d = %d) do not match the number of spectra (%d)', ...
    W, H, W*H, obj.Area);

obj = obj.unmask(true(H, W));
% History will be added by unmask
end


text:
enable_filetransfer() {
moni call -v .gorfx.SetupOfferType "\
	offerType: 'http://gndms.zib.de/ORQTypes/FileTransfer'; \
	orqType: '{http://gndms.zib.de/c3grid/types}FileTransferORQT'; \
	resType: '{http://gndms.zib.de/c3grid/types}FileTransferResultT'; \
	calcFactory: de.zib.gndms.logic.model.gorfx.FileTransferORQFactory; \
	taskActionFactory: de.zib.gndms.logic.model.gorfx.FileTransferActionFactory; \
	mode:'$MODE'"
}


text:
package com.orientechnologies.orient.test.internal.index;

import java.util.Random;
import java.util.Set;

import org.testng.Assert;
import org.testng.annotations.Test;

import com.orientechnologies.common.collection.OCompositeKey;
import com.orientechnologies.common.test.SpeedTestMonoThread;
import com.orientechnologies.orient.core.db.document.ODatabaseDocumentTx;
import com.orientechnologies.orient.core.index.ODocumentFieldsHashSet;
import com.orientechnologies.orient.core.index.OIndex;
import com.orientechnologies.orient.core.metadata.schema.OClass;
import com.orientechnologies.orient.core.metadata.schema.OSchema;
import com.orientechnologies.orient.core.metadata.schema.OType;
import com.orientechnologies.orient.core.record.impl.ODocument;

public class PartialSearchIndexSpeedTest extends SpeedTestMonoThread {
  private ODatabaseDocumentTx database = new ODatabaseDocumentTx("local:partialSearchIndexSpeedTest");

  public PartialSearchIndexSpeedTest() {
    super(1000);
  }

  @Override
  @Test(enabled = false)
  public void cycle() throws Exception {
    int start = (new Random()).nextInt(10);
    final OIndex index = database.getMetadata().getIndexManager().getIndex("testIndex");

    final Set<ODocument> result = new ODocumentFieldsHashSet();

    index.getEntriesMajor(new OCompositeKey(start), true, new OIndex.IndexEntriesResultListener() {
			@Override
			public boolean addResult(ODocument entry) {
				result.add(entry);
				return result.size() < 100;
			}
		});

    Assert.assertEquals(result.size(), 100);
  }

  @Override
  @Test(enabled = false)
  public void init() throws Exception {
    if (!database.exists()) {
      database.create();

      final OSchema schema = database.getMetadata().getSchema();
      final OClass testClass = schema.createClass("IndexTest");
      testClass.createProperty("f1", OType.INTEGER);
      testClass.createProperty("f2", OType.INTEGER);

      testClass.createIndex("testIndex", OClass.INDEX_TYPE.UNIQUE, "f1", "f2");

      schema.save();

      final ODocument document = new ODocument();
      for (int i = 0; i < 10; i++) {
        for (int j = 0; j < 500000; j++) {
          document.reset();

          document.setClassName("IndexTest");
          document.field("f1", i);
          document.field("f2", j);

          document.save();
        }
      }
    } else {
      database.open("admin", "admin");
    }
  }
}


text:
require "labs-deployer/version"
require 'thor'
require 'bundler'
require 'bundler/setup'
require 'berkshelf/thor'
require 'fileutils'
require 'digest/md5'
require 'mime/types'
require 'berkshelf/cli'
require 's3'
require 'labs-deployer/config'
class Solo < Thor

  Berkshelf::Config.new

  desc "package", "package and deploy a cookbook"

  def package
    @config = VoxeoLabs::Config.new(Dir.pwd)
    #get_dependencies
    pkg = package_files
    upload_cookbooks(pkg)
  end

  private

  def get_dependencies()
    say "Gathering cookbook dependencies", :green
    FileUtils.rm_rf("/tmp/cookbooks")
    invoke("berkshelf:install", [], path: "/tmp/cookbooks", berksfile: "./Berksfile")
  end

  def package_files
    say "== Packaging cookbook", :green
    `cd /tmp; tar zcf #{get_cookbook_name}.#{get_cookbook_version}.tgz ./cookbooks`
    return "/tmp/#{get_cookbook_name}.#{get_cookbook_version}.tgz"
  end

  def upload_cookbooks(file)
    service = S3::Service.new({
                                :access_key_id     =>  @config.aws_key, #Chef::Config[:knife][:aws_access_key_id],
                                :secret_access_key =>  @config.aws_secret #@Chef::Config[:knife][:aws_secret_access_key]
    })
    bucket = service.buckets.find(@config.bucket_name)
    say "== Uploading cookbook [#{file}]", :green

    ## Only upload files, we're not interested in directories
    if File.file?(file)
      remote_file = "#{get_folder_name}/#{file.split("/")[-1]}"

      begin
        obj = bucket.objects.find_first(remote_file)
        if yes? "This cookbook version already exists, do you want to overwrite it ?", :red
          say "== Ok, we'll overwrite it", :green
        else
          say "== Ok, exiting", :green
          exit 0
        end
      rescue
        obj = nil
      end

      say "== Uploading #{file} to #{get_folder_name}", :green
      obj = bucket.objects.build(remote_file)
      obj.content = open(file)
      obj.content_type = MIME::Types.type_for(file).to_s
      obj.save

    end
    say "== Done syncing #{file.split('/')[-1]}",:green
  end

  def get_cookbook_version
    IO.read(Berkshelf.find_metadata).match(/^version.*/).to_s.split('"')[1]
  end

  def get_folder_name
    if @config.project_name
      return @config.project_name
    else
      get_cookbook_name
    end
  end

  def get_cookbook_name
    name = IO.read(Berkshelf.find_metadata).match(/^name.*/).to_s.split('"')[1]
    if name.nil?
      return Dir.pwd.split("/")[-1]
    else
      return name
    end

  end

end


text:
package ch.ninecode.sim

import ch.ninecode.gl.GLMNode
import ch.ninecode.net.LoadFlowNode

/**
 * Vertex data.
 *
 * @param id                 TopologicalNode mRID.
 * @param nominal_voltage    Node voltage (V).
 * @param equipment          ConductingEquipment mRID.
 * @param world_position     The (x,y) coordinates of the PositionPoint of the ConductingEquipment in world coordinates, or null if none.
 * @param schematic_position The (x,y) coordinates of the PositionPoint of the ConductingEquipment in schematic coordinates, or null if none.
 * @param players            Players attached to this node - if any.
 * @param recorders          Recorders attached to this node - if any.
 */
case class SimulationNode
(
    override val id: String,
    override val nominal_voltage: Double,
    equipment: String,
    world_position: Iterable[(Double, Double)] = Seq(),
    schematic_position: Iterable[(Double, Double)] = Seq(),
    players: Iterable[SimulationPlayer] = Seq(),
    recorders: Iterable[SimulationRecorder] = Seq()
)
    extends LoadFlowNode(
        id,
        nominal_voltage
    )
        with GLMNode
{
    override def toString: String = s"$id $equipment (${nominal_voltage}V)"
}


text:
namespace fm
{
	class UUID
	{
	public:
		static std::string Generate(const std::string& inString);

	private:
	};
}


text:
<?php
    $con=mysqli_connect("localhost","root","","db_catalogo");

    // consulta SQL
    $query = mysqli_query($con, 'SELECT * FROM `video` WHERE  id=1');
    $escrever = mysqli_fetch_array($query);
?>


text:
<?php

//include_once dirname(__FILE__) . "/../Utilitymespace Weathermap\Plugins\Datasources;
namespace Weathermap\Plugins\Datasources;

use Weathermap\Core\MapUtility;
use Weathermap\Core\Map;
use Weathermap\Core\MapDataItem;

/**
 * Get data from Cacti's dsstats plugin database
 *
 * @package Weathermap\Plugins\Datasources
 */
class CactiDSStats extends Base
{

    public function __construct()
    {
        parent::__construct();

        $this->regexpsHandled = array(
            '/^dsstats:([a-z]+):(\d+):([\-a-zA-Z0-9_]+):([\-a-zA-Z0-9_]+)$/',
            '/^dsstats:(\d+):([\-a-zA-Z0-9_]+):([\-a-zA-Z0-9_]+)$/'
        );

        $this->name = "CactiDSStats";
    }

    public function init(&$map)
    {
        if ($map->context == 'cacti') {
            if (!function_exists('db_fetch_assoc')) {
                MapUtility::debug("ReadData DSStats: Cacti database library not found. [DSSTATS001]\n");
                return false;
            }

            $dsstatsRunning = false;

            MapUtility::debug("ReadData DSStats: Checking for 1.x integrated...\n");
            if (function_exists("read_config_option")) {
                if (read_config_option("dsstats_enable") == "on") {
                    $dsstatsRunning = true;
                    MapUtility::debug("ReadData DSStats: Found 1.x integrated DSStats\n");
                } else {
                    MapUtility::debug("ReadData DSStats: No 1.x integrated DSStats\n");
                }
            }

            if (!$dsstatsRunning) {
                MapUtility::debug("ReadData DSStats: Checking for 0.8.8 plugin...\n");
                if (function_exists("api_plugin_is_enabled")) {
                    if (api_plugin_is_enabled('dsstats')) {
                        MapUtility::debug("ReadData DSStats: DSStats plugin enabled. [DSSTATS002B]\n");
                        $dsstatsRunning = true;
                    } else {
                        MapUtility::debug("ReadData DSStats: DSStats plugin NOT enabled. [DSSTATS002B]\n");
                    }
                }
            }

            if (!$dsstatsRunning) {
                return false;
            }

            $sql = "show tables";
            $result = db_fetch_assoc($sql);
            $tables = array();

            foreach ($result as $index => $arr) {
                foreach ($arr as $t) {
                    $tables[] = $t;
                }
            }

            if (!in_array('data_source_stats_hourly_last', $tables)) {
                MapUtility::debug('ReadData DSStats: data_source_stats_hourly_last database table not found. [DSSTATS003]\n');
                return false;
            }

            return true;
        }

        return false;
    }

    # dsstats:<datatype>:<local_data_id>:<rrd_name_in>:<rrd_name_out>

    // Actually read data from a data source, and return it
    // returns a 3-part array (invalue, outvalue and datavalid time_t)
    // invalue and outvalue should be -1,-1 if there is no valid data
    // data_time is intended to allow more informed graphing in the future

    /**
     * @param string $targetString
     * @param Map $map
     * @param MapDataItem $mapItem
     * @return array
     */
    public function readData($targetString, &$map, &$mapItem)
    {
        $this->data[IN] = null;
        $this->data[OUT] = null;
        $pdo = weathermap_get_pdo();

        $localDataId = null;
        $dsNames = array(IN => "traffic_in", OUT => "traffic_out");

        $inBandwidth = null;
        $outBandwidth = null;

        $table = "";
        $keyfield = "rrd_name";
        $datatype = "";
        $field = "";

        if (preg_match('/^dsstats:(\d+):([\-a-zA-Z0-9_]+):([\-a-zA-Z0-9_]+)$/', $targetString, $matches)) {
            $localDataId = $matches[1];
            $dsNames[IN] = $matches[2];
            $dsNames[OUT] = $matches[3];

            $datatype = "last";

            if ($map->getHint("dsstats_default_type") != '') {
                $datatype = $map->getHint("dsstats_default_type");
                MapUtility::debug("Default datatype changed to " . $datatype . ".\n");
            }
        } elseif (preg_match('/^dsstats:([a-z]+):(\d+):([\-a-zA-Z0-9_]+):([\-a-zA-Z0-9_]+)$/', $targetString, $matches)) {
            $dsNames[IN] = $matches[3];
            $dsNames[OUT] = $matches[4];
            $datatype = $matches[1];
            $localDataId = $matches[2];
        }

        if (substr($datatype, 0, 5) == "daily") {
            $table = "data_source_stats_daily";
        }
        if (substr($datatype, 0, 6) == "weekly") {
            $table = "data_source_stats_weekly";
        }
        if (substr($datatype, 0, 7) == "monthly") {
            $table = "data_source_stats_monthly";
        }
        if (substr($datatype, 0, 6) == "hourly") {
            $table = "data_source_stats_hourly";
        }
        if (substr($datatype, 0, 6) == "yearly") {
            $table = "data_source_stats_yearly";
        }

        if (substr($datatype, -7) == "average") {
            $field = "average";
        }
        if (substr($datatype, -4) == "peak") {
            $field = "peak";
        }

        if ($datatype == "last") {
            $field = "calculated";
            $table = "data_source_stats_hourly_last";
        }

        if ($datatype == "wm") {
            $field = "last_calc";
            $table = "weathermap_data";
            $keyfield = "data_source_name";
        }

        if ($table != "" and $field != "") {
            $SQL = sprintf(
                "select %s as name, %s as result from %s where local_data_id=%d and (%s=%s or %s=%s)",
                $keyfield,
                $field,
                $table,
                $localDataId,
                $keyfield,
                $pdo->quote($dsNames[IN]),
                $keyfield,
                $pdo->quote($dsNames[OUT])
            );

            $results = \db_fetch_assoc($SQL);
            if (count($results) > 0) {
                foreach ($results as $result) {
                    foreach (array(IN, OUT) as $dir) {
                        if (($dsNames[$dir] == $result['name']) && ($result['result'] != -90909090909) && ($result['result'] != 'U')) {
                            $this->data[$dir] = $result['result'];
                        }
                    }
                }
            }

            if ($datatype == 'wm' && ($this->data[IN] == null || $this->data[OUT] == null)) {
                MapUtility::debug("Didn't get data for 'wm' source. Inserting new tasks for next poller cycle\n");
                // insert the required details into weathermap_data, so it will be picked up next time
                $SQL = sprintf(
                    "select data_template_data.data_source_path as path from data_template_data,data_template_rrd where data_template_data.local_data_id=data_template_rrd.local_data_id and data_template_rrd.local_data_id=%d",
                    $localDataId
                );
                $result = \db_fetch_row($SQL);
                if (count($result) > 0) {
                    $databaseRRDName = $result['path'];
                    MapUtility::debug("Filename is $databaseRRDName");
                    foreach (array(IN, OUT) as $dir) {
                        if ($this->data[$dir] === null) {
                            $statement = $pdo->prepare("insert into weathermap_data (rrdfile, data_source_name, sequence, local_data_id) values (?,?,?,?)");
                            $statement->execute(array($databaseRRDName, $dsNames[$dir], 0, $localDataId));
                        }
                    }
                } else {
                    MapUtility::warn("DSStats ReadData: Failed to find a filename for DS id $localDataId [WMDSTATS01]");
                }
            }
        }

        // fill all that other information (ifSpeed, etc)
        // (but only if it's not switched off!)
        if (($map->getHint("dsstats_no_cacti_extras") === null) && $localDataId > 0) {
            updateCactiData($mapItem, $localDataId);
        }

        return $this->returnData();
    }
}

// vim:ts=4:sw=4:


text:
<?php

namespace garethp\ews\API\Type;

/**
 * Class representing ContactsFolderType
 *
 *
 * XSD Type: ContactsFolderType
 *
 * @method string getSharingEffectiveRights()
 * @method ContactsFolderType setSharingEffectiveRights(string $sharingEffectiveRights)
 * @method PermissionSetType getPermissionSet()
 * @method ContactsFolderType setPermissionSet(PermissionSetType $permissionSet)
 */
class ContactsFolderType extends BaseFolderType
{

    /**
     * @var string
     */
    protected $sharingEffectiveRights = null;

    /**
     * @var \garethp\ews\API\Type\PermissionSetType
     */
    protected $permissionSet = null;
}


text:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Reflection;

namespace Solar
{
    public partial class AboutForm : Form
    {
        /// <summary>
        /// Class constructor
        /// </summary>
        public AboutForm()
        {
            InitializeComponent();
            PopulateForm();

        } // AboutForm

        /// <summary>
        /// Populates all labels for the about form
        /// </summary>
        private void PopulateForm()
        {
            // reference to the executing assembly
            Assembly app = Assembly.GetExecutingAssembly();

            // get assembly info in useable chunks
            AssemblyCopyrightAttribute copyright = (AssemblyCopyrightAttribute)app.GetCustomAttributes(typeof(AssemblyCopyrightAttribute), false)[0];
            AssemblyCompanyAttribute company = (AssemblyCompanyAttribute)app.GetCustomAttributes(typeof(AssemblyCompanyAttribute), false)[0];
            AssemblyDescriptionAttribute description = (AssemblyDescriptionAttribute)app.GetCustomAttributes(typeof(AssemblyDescriptionAttribute), false)[0];
            Version verTemp = Version.Parse(ProductVersion);

            // format version number for user disply
            String strVersion = verTemp.Major + "." + verTemp.Minor + "." + verTemp.Build % 100;

            this.Text = String.Format("About {0}", Model.Instance.PROGRAM_NAME);

            m_lblTitle.Text = String.Format("{0}", Model.Instance.PROGRAM_NAME);
            m_lblVersion.Text = String.Format("Version: {0}", strVersion);
            m_lblCompany.Text = company.Company.ToString();
            m_lbCopyright.Text = String.Format("{0} All Rights Reserved", copyright.Copyright.ToString());
            m_tbDescription.Text = description.Description.ToString();

        } // PopulateForm

        /// <summary>
        /// Quit the form
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void Close(object sender, EventArgs e)
        {
            this.Close();

        } // Quit

    } // AboutForm Class

} // Solar Namespace


text:
package sjm.examples.engine;

import sjm.engine.*;

/**
 * This class shows the construction of a couple of facts.
 *
 * @author Steven J. Metsker
 *
 * @version 1.0
 */
public class ShowFacts {
/**
 * Shows the construction of a couple of facts.
 */
public static void main(String[] args) {
	Fact d = new Fact(
		"city",
		new Fact[]{
			new Fact("denver"),
			new Fact(new Integer(5280))});

	Fact j = new Fact(
		"city", "jacksonville", new Integer(8));

	System.out.println(d + "\n" + j);
}
}


text:
// ///////////////////////////////////////////////////////////////////////////////////////////
//  Description:     UploadLogResult
//  Author:          Ben Moore
//  Created date:    14/05/2015
//  Copyright:       Donky Networks Ltd 2015
// ///////////////////////////////////////////////////////////////////////////////////////////

namespace Donky.Core.Services.Diagnostics
{
	internal class UploadLogResult
	{
		public bool AlwaysSubmitErrors { get; set; }
	}
}


text:
/* TEMPLATE GENERATED TESTCASE FILE
Filename: CWE369_Divide_by_Zero__float_rand_12.c
Label Definition File: CWE369_Divide_by_Zero__float.label.xml
Template File: sources-sinks-12.tmpl.c
*/
/*
 * @description
 * CWE: 369 Divide by Zero
 * BadSource: rand Set data to result of RAND32(), which may be zero
 * GoodSource: A hardcoded non-zero number (two)
 * Sinks:
 *    GoodSink: Check value of or near zero before dividing
 *    BadSink : Divide a constant by data
 * Flow Variant: 12 Control flow: if(globalReturnsTrueOrFalse())
 *
 * */

#include "std_testcase.h"

#include <math.h>

#ifndef OMITBAD

void CWE369_Divide_by_Zero__float_rand_12_bad()
{
    float data;
    /* Initialize data */
    data = 0.0F;
    if(globalReturnsTrueOrFalse())
    {
        /* POTENTIAL FLAW: Use a random number that could possibly equal zero */
        data = (float)RAND32();
    }
    else
    {
        /* FIX: Use a hardcoded number that won't a divide by zero */
        data = 2.0F;
    }
    if(globalReturnsTrueOrFalse())
    {
        {
            /* POTENTIAL FLAW: Possibly divide by zero */
            int result = (int)(100.0 / data);
            printIntLine(result);
        }
    }
    else
    {
        /* FIX: Check for value of or near zero before dividing */
        if(fabs(data) > 0.000001)
        {
            int result = (int)(100.0 / data);
            printIntLine(result);
        }
        else
        {
            printLine("This would result in a divide by zero");
        }
    }
}

#endif /* OMITBAD */

#ifndef OMITGOOD

/* goodB2G() - use badsource and goodsink by changing the first "if" so that
   both branches use the BadSource and the second "if" so that both branches
   use the GoodSink */
static void goodB2G()
{
    float data;
    /* Initialize data */
    data = 0.0F;
    if(globalReturnsTrueOrFalse())
    {
        /* POTENTIAL FLAW: Use a random number that could possibly equal zero */
        data = (float)RAND32();
    }
    else
    {
        /* POTENTIAL FLAW: Use a random number that could possibly equal zero */
        data = (float)RAND32();
    }
    if(globalReturnsTrueOrFalse())
    {
        /* FIX: Check for value of or near zero before dividing */
        if(fabs(data) > 0.000001)
        {
            int result = (int)(100.0 / data);
            printIntLine(result);
        }
        else
        {
            printLine("This would result in a divide by zero");
        }
    }
    else
    {
        /* FIX: Check for value of or near zero before dividing */
        if(fabs(data) > 0.000001)
        {
            int result = (int)(100.0 / data);
            printIntLine(result);
        }
        else
        {
            printLine("This would result in a divide by zero");
        }
    }
}

/* goodG2B() - use goodsource and badsink by changing the first "if" so that
   both branches use the GoodSource and the second "if" so that both branches
   use the BadSink */
static void goodG2B()
{
    float data;
    /* Initialize data */
    data = 0.0F;
    if(globalReturnsTrueOrFalse())
    {
        /* FIX: Use a hardcoded number that won't a divide by zero */
        data = 2.0F;
    }
    else
    {
        /* FIX: Use a hardcoded number that won't a divide by zero */
        data = 2.0F;
    }
    if(globalReturnsTrueOrFalse())
    {
        {
            /* POTENTIAL FLAW: Possibly divide by zero */
            int result = (int)(100.0 / data);
            printIntLine(result);
        }
    }
    else
    {
        {
            /* POTENTIAL FLAW: Possibly divide by zero */
            int result = (int)(100.0 / data);
            printIntLine(result);
        }
    }
}

void CWE369_Divide_by_Zero__float_rand_12_good()
{
    goodB2G();
    goodG2B();
}

#endif /* OMITGOOD */

/* Below is the main(). It is only used when building this testcase on
   its own for testing or for building a binary to use in testing binary
   analysis tools. It is not used when compiling all the testcases as one
   application, which is how source code analysis tools are tested. */

#ifdef INCLUDEMAIN

int main(int argc, char * argv[])
{
    /* seed randomness */
    srand( (unsigned)time(NULL) );
#ifndef OMITGOOD
    printLine("Calling good()...");
    CWE369_Divide_by_Zero__float_rand_12_good();
    printLine("Finished good()");
#endif /* OMITGOOD */
#ifndef OMITBAD
    printLine("Calling bad()...");
    CWE369_Divide_by_Zero__float_rand_12_bad();
    printLine("Finished bad()");
#endif /* OMITBAD */
    return 0;
}

#endif


text:
The API mirrors the CLI except you must provide a `stream` for logging, and it does not attempt to auto-portfind. You can also pass in transforms and plugins as an object, like so:

```js
var budo = require('budo')
var babelify = require('babelify')

budo('./src/index.js', {
  live: true,             //live reload
  transform: babelify,    //ES6 transpiling
  stream: process.stdout, //log to stdout
  port: 8000              //use this port
}).on('connnect', function(ev) {
  //...
})
```

#### `b = budo(entry[, opts])`

Spins up a new instance of `budo`, where `entry` is a path or or array of paths.

The options are the same as CLI, except that the API does not attempt auto portfinding, and does not print to stdout. You can specify a `stream` option to print to.

The return value is an event emitter.

#### `b.on('exit')`

Called when the server is closed.

#### `b.on('error')`

Called on a fatal error, like not being able to create the server.

#### `b.on('connect')`

Called once the budo server connects. The callback is passed an `event` object that looks like this:

```js
{
  uri: 'http://localhost:9966/',  //served URI
  serve: 'bundle/entry%20file.js' //the URL path for our entry file
  dir: 'app',                     //the working directory being served
  host: 'localhost',              //defaults to localhost
  port: 9966                      //the port we're running on
}
```

#### `b.on('update')`

This event is triggered when the bundle changes. It is passed the following:

```(urlPath, src)```

Where `urlPath` is the served name (e.g. `bundle%20file.js`) and `src` is the new contents of the bundle.

#### `b.on('reload')`

If live reload is enabled (i.e. through `live` or `live-plugin`), this event will be triggered after the LiveReload has been sent. The parameter is `file`, the file path being submitted to the LiveReload server.

#### `b.on('watch')`

If file watching is enabled (i.e. through `live` or `live-plugin`), this event will be triggered after HTML and CSS files have changed. The parameters will be `(eventType, file)` where `eventType` could be "add", "change", "unlink", etc.

#### `b.reload(path)`

If live reload is enabled (i.e. through `live` or `live-plugin`), this will send a LiveReload event to the given path and then trigger the `"reload"` event.

#### `b.live([opt])`

If `live` and `live-plugin` were not specified, you can manually enable the LiveReload server with the specified options object: `port` (default 35729) and `host` (default to the `host` argument provided to budo, or `localhost`). You can also specify `plugin: true` if you do not want the LiveReload snippet injected into the HTML.

#### `b.watch([globs, chokidarOpts])`

If `live` and `live-plugin` were not specified, you can manually enabe [chokidar's](https://github.com/paulmillr/chokidar) file watching with the specified `globs` (array or string) and options.

`globs` defaults to watching `**/*.{html,css}`. `chokidarOpts` defaults to the options passed to the budo constructor.

Example of using `live()` and `watch()` together. This will only trigger LiveReload on CSS updates.

```js
var budo = require('budo')
var path = require('path')
var app = budo('index.js')

app
  //listen to CSS changes
  .watch('*.css', { interval: 300, usePolling: true })
  //start LiveReload server
  .live()
  //handle file events
  .on('watch', function(type, file) {
    //tell LiveReload to inject some CSS
    if (path.extname(file) === '.css')
      app.reload(file)
  })
```

# build tools

Budo doesn't need a Grunt or Gulp specific plugin to work, but you may choose to wrap it within your favourite task runner for consistency. A simple case might look like this:

```js
var gulp = require('gulp')
var budo = require('budo')

//start our local development server
gulp.task('dev', function(cb) {
  budo('index.js')
    .on('connect', function(ev) {
      console.log("Server started at "+ev.uri)
    })
    .on('exit', cb)
})
```

Now running `gulp dev` will spin up a server on 9966, spawn watchify, and incrementally rebundle during development. It will stub out an `index.html` and serve the browserified contents of `index.js`.

#### integrations

- [gulp](https://github.com/mattdesl/budo-gulp-starter)
- [npm scripts](https://gist.github.com/mattdesl/b6990e7c7221c9cc05aa)
- [LiveReactLoad](https://gist.github.com/mattdesl/2aa5b45ed1f230635a04)


text:
export const SET_CELL_VALUE = 'SET_CELL_VALUE';
export const CLEAR_CELL = 'CLEAR_CELL';
export const SHOW_HINT = 'SHOW_HINT';


text:
<?php

namespace Innmind\AppBundle\Command\Server;

use Symfony\Bundle\FrameworkBundle\Command\ContainerAwareCommand;
use Symfony\Component\Console\Input\InputArgument;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Output\OutputInterface;
use Innmind\AppBundle\Entity\Server;

class AddCommand extends ContainerAwareCommand
{
    protected function configure()
    {
        $this
            ->setName('innmind:server:add')
            ->setDescription('Register a new server allowed to talk to the innmind app')
            ->addArgument(
                'name',
                InputArgument::REQUIRED,
                'Server name (work as an alias)'
            )
            ->addArgument(
                'host',
                InputArgument::REQUIRED,
                'Server host'
            )
            ->addArgument(
                'type',
                InputArgument::REQUIRED,
                'The job being done on this server'
            );
    }

    protected function execute(InputInterface $input, OutputInterface $output)
    {
        $entity = new Server;
        $entity
            ->setName($input->getArgument('name'))
            ->setHost($input->getArgument('host'))
            ->setType($input->getArgument('type'));

        $errors = $this
            ->getContainer()
            ->get('validator')
            ->validate($entity);

        if ($errors->count() > 0) {
            foreach ($errors as $error) {
                $output->writeln(sprintf(
                    '<error>%s</error>',
                    (string) $error
                ));
            }
            return;
        }

        $em = $this
            ->getContainer()
            ->get('doctrine')
            ->getManager();

        $em->persist($entity);
        $em->flush();

        $output->writeln(sprintf(
            '<info>Entity created (id=%s)</info>',
            $entity->getId()
        ));
    }
}


text:
describe('Unit : event Feed Plugin widget.feed.controller.js', function () {
    var WidgetEvent, scope, $rootScope, $controller, Buildfire, ActionItems, TAG_NAMES, STATUS_CODE, LAYOUTS, STATUS_MESSAGES, CONTENT_TYPE, q;
    beforeEach(module('eventsFeedPluginWidget'));
    var editor;
    beforeEach(inject(function (_$rootScope_, _$q_, _$controller_, _TAG_NAMES_, _STATUS_CODE_, _LAYOUTS_, _STATUS_MESSAGES_) {
        $rootScope = _$rootScope_;
        q = _$q_;
        scope = $rootScope.$new();
        $controller = _$controller_;
        TAG_NAMES = _TAG_NAMES_;
        STATUS_CODE = _STATUS_CODE_;
        STATUS_MESSAGES = _STATUS_MESSAGES_;
        LAYOUTS = _LAYOUTS_;
        Buildfire = {
            components: {
                carousel: {
                    editor: function (name) {
                        return {}
                    },
                    viewer: function (name) {
                        return {}
                    }
                }
            }
        };
        ActionItems = jasmine.createSpyObj('ActionItems', ['showDialog']);
        Buildfire.components.carousel = jasmine.createSpyObj('Buildfire.components.carousel', ['editor','onAddItems']);

    }));

    beforeEach(function () {
        WidgetEvent = $controller('WidgetEventCtrl', {
            $scope: scope,
            $q: q,
            Buildfire: Buildfire,
            TAG_NAMES: TAG_NAMES,
            ActionItems: ActionItems,
            STATUS_CODE: STATUS_CODE,
            CONTENT_TYPE: CONTENT_TYPE,
            LAYOUTS: LAYOUTS
        });
    });
    var options = {width:"100px", height:"100px"};
    var url;
    describe('Units: units should be Defined', function () {
     });

    describe('$destroy', function() {
        it('should invoke when get $destroy', function() {
            $rootScope.$broadcast('$destroy');
        });
    });

    describe('WidgetEvent.cropImage invike', function() {
        it('It should invoke when it call', function() {
            WidgetEvent.cropImage(url,options)
        });

        it('It should invoke if options.height is true', function() {
            expect(options.height).toEqual("100px")
        });

        it('It should invoke if options.width is true', function() {
            expect(options.width).toEqual("100px")
        });
    });

    describe('Carousel:LOADED', function() {options
        it('should invoke when get Carousel:LOADED', function() {
            $rootScope.$broadcast('Carousel:LOADED');
        });
    });

})
;


text:
class CreateStoreFromPreferences < ActiveRecord::Migration
  class Store < ActiveRecord::Base
    self.table_name = 'spree_stores'
  end
  def change
    preference_store = Spree::Preferences::Store.instance
    if store = Store.where(default: true).first
      store.meta_description = preference_store.get('spree/app_configuration/default_meta_description') {}
      store.meta_keywords    = preference_store.get('spree/app_configuration/default_meta_keywords') {}
      store.seo_title        = preference_store.get('spree/app_configuration/default_seo_title') {}
      store.save!
    else
      # we set defaults for the things we now require
      Store.new do |s|
        s.name = preference_store.get 'spree/app_configuration/site_name' do
          'Sample Store'
        end
        s.url = preference_store.get 'spree/app_configuration/site_url' do
          'example.com'
        end
        s.mail_from_address = preference_store.get 'spree/app_configuration/mails_from' do
          'store@example.com'
        end

        s.meta_description = preference_store.get('spree/app_configuration/default_meta_description') {}
        s.meta_keywords    = preference_store.get('spree/app_configuration/default_meta_keywords') {}
        s.seo_title        = preference_store.get('spree/app_configuration/default_seo_title') {}
        s.default_currency = preference_store.get('spree/app_configuration/currency') {}
        s.code             = 'spree'
        s.default          = true
      end.save!
    end
  end
end


text:
<div id="hustle-appearance-icons-style" class="sui-box-settings-row"<?php if ( $is_empty ) echo ' style="display: none;"'; ?>>

		<?php esc_html_e( 'Icons Style', 'wordpress-popup' ); ?>
		<?php esc_html_e( 'Choose the style for your social icons as per your need.', 'wordpress-popup' ); ?>

					<input
						type="radio"
						name="icon_style"
						data-attribute="icon_style"
						value="flat"
						id="hustle-social-icon--default"
						{{ _.checked( 'flat' === icon_style, true) }}
					/>

					<?php esc_html_e( 'Default', 'wordpress-popup' ); ?>

					<input
						type="radio"
						name="icon_style"
						data-attribute="icon_style"
						value="outline"
						id="hustle-social-icon--outlined"
						{{ _.checked( 'outline' === icon_style, true) }}
					/>

					<?php esc_html_e( 'Outlined', 'wordpress-popup' ); ?>

					<input
						type="radio"
						name="icon_style"
						data-attribute="icon_style"
						value="rounded"
						id="hustle-social-icon--circle"
						{{ _.checked( 'rounded' === icon_style, true) }}
					/>

					<?php esc_html_e( 'Circle', 'wordpress-popup' ); ?>

					<input
						type="radio"
						name="icon_style"
						data-attribute="icon_style"
						value="squared"
						id="hustle-social-icon--square"
						{{ _.checked( 'squared' === icon_style, true) }}
					/>

					<?php esc_html_e( 'Square', 'wordpress-popup' ); ?>


text:
// Licensed to eXtensoft LLC under one or more agreements.
// eXtensoft LLC licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.

namespace XF.Common.Wcf
{
    using System;
    using System.Data;
    using System.ServiceModel;

    [ServiceContract(Namespace = "http://eXtensoft/xf/schemas/2017/09")]
    [ServiceKnownType(typeof(Ping))]
    [ServiceKnownType(typeof(TypedItem))]
    [ServiceKnownType(typeof(Criterion))]
    [ServiceKnownType(typeof(ApplicationContext))]
    [ServiceKnownType(typeof(DataTable))]
    [ServiceKnownType(typeof(DateTimeOffset))]
    public interface IRpcDataPacketService
    {

        [OperationContract]
        DataPacket ExecuteRpc(DataPacket item);

    }
}


text:
Tambah Data Parameter

                    <?php echo $this->session->userdata('message') <> '' ? $this->session->userdata('message') : ''; ?>

                   <form action="<?php echo $action; ?>" method="post">

                                Jenis <?php echo form_error('jenis') ?>
                                <input type="text" class="form-control" name="jenis" id="jenis" placeholder="Jenis" readonly="" value="<?php echo $jenis; ?>" />

                                Denda <?php echo form_error('denda') ?>
                                <input type="text" onkeypress="return runScript(event)" class="form-control" name="denda" id="denda" placeholder="Denda" value="<?php echo $denda; ?>" />

                                Durasi <?php echo form_error('durasi') ?>
                                <input type="text" onkeypress="return runScript(event)" class="form-control" name="durasi" id="durasi" placeholder="Durasi" value="<?php echo $durasi; ?>" />

                            <input type="hidden" name="id_parameter" value="<?php echo $id_parameter; ?>" />
                            <button type="submit" class="btn btn-primary"><?php echo $button ?></button>
                            <a href="<?php echo site_url('parameter') ?>" class="btn btn-default">Cancel
                        </form>


text:
<?php
defined('BASEPATH') OR exit('No direct script access allowed');

/**
 * Some class description here...
 *
 * @package     KAWANI
 * @subpackage  subpackage
 * @category    category
 * @author      joseph.gono@systemantech.com
 * @link        http://systemantech.com
 */
class Attachment_types extends MY_Controller {

	private $active_menu = 'Administration';

	function __construct()
	{
		parent::__construct();
		$this->load->library('audit_trail');
		$this->load->model(['attachment_type_model']);
	}

	function index()
	{
		$attachment_types = $this->attachment_type_model->get_details('get_many_by', ['attachment_types.active_status' => 1]);

		$this->data = array(
			'page_header' => 'Attachment Types Management',
			'attachment_types' => $attachment_types,
			'active_menu' => $this->active_menu,
		);
		$this->load_view('pages/attachment_type-lists');
	}

	public function add()
	{

		$this->data = array(
			'page_header' => 'Attachment Types Management',
			'active_menu' => $this->active_menu,
		);

		$attachment_types = $this->attachment_type_model->get_details('get_all', ['attachment_types.active_status' => 1]);
		$data = remove_unknown_field($this->input->post(), $this->form_validation->get_field_names('attachment_type_add'));
		// dump($data);exit;
		$this->form_validation->set_data($data);

		if ($this->form_validation->run('attachment_type_add') == TRUE)
		{
			// $this->session->set_flashdata('log_parameters', [
			// 	'action_mode' => 0,
			// 	'perm_key' 	  => 'add_attachment_type',
			// 	'old_data'	  => NULL,
			// 	'new_data'    => $data
			// ]);

			$attachment_type_id = $this->attachment_type_model->insert($data);

			if ( ! $attachment_type_id) {
				$this->session->set_flashdata('failed', 'Failed to add new attachment_type.');
				redirect('attachment_types');
			} else {
				$this->session->set_flashdata('success', 'Successfully added new attachment_type.');
				redirect('attachment_types');
			}
		}
		$this->load_view('forms/attachment_type-add');
	}

	function details($id)
	{
		$attachment_type = $this->attachment_type_model->get_attachment_type_by(['attachment_types.id' => $id]);
		$site 			 = $this->site_model->get_many_site_by(['sites.attachment_type_id' => $id]);
		$sites 			 = $this->site_model->get_many_site_by(['sites.attachment_type_id' => $id]);
		$employee_infos  = $this->employee_info_model->get_employee_info_data(['departments.id' => $id]);

		$this->data = array(
			'page_header'    => 'Attachment Types Details',
			'attachment_type'=> $attachment_type,
			'sites' 		 => $site,
			'sites' 		 => $sites,
			'employee_infos' => $employee_infos,
			'active_menu' 	 => $this->active_menu,
		);
		$this->load_view('pages/attachment_type-detail');
	}

	function edit($id)
	{
		// get specific attachment_type based on the id
		$attachment_type = $this->attachment_type_model->get_attachment_type_by(['attachment_types.id' => $id]);
		// get all company records where status is equal to active
		$companies = $this->company_model->get_many_by(['active_status' => 1]);

		if ( ! $this->ion_auth_acl->has_permission('edit_attachment_type'))
		{
			$this->session->set_flashdata('failed', 'You have no permission to access this module');
			redirect('/', 'refresh');
		}

        $attachment_type_data = $this->attachment_type_model->get_attachment_type_by(['attachment_types.id' => $id]);

		$this->data = array(
			'page_header' => 'Attachment Types Management',
			'attachment_type' 	  => $attachment_type,
			'attachment_type_data' => $attachment_type_data,
			'companies'	  => $companies,
			'active_menu' => $this->active_menu,
		);

		$attachment_types = $this->attachment_type_model->get_attachment_type_all();
		$data = remove_unknown_field($this->input->post(), $this->form_validation->get_field_names('attachment_type_edit'));

		$this->form_validation->set_data($data);

		if ($this->form_validation->run('attachment_type_edit') == TRUE)
		{
			$this->session->set_flashdata('log_parameters', [
				'action_mode' => 1,
				'perm_key'    => 'edit_attachment_type',
				'old_data'    => $attachment_type_data,
				'new_data'    => $data
			]);

			$attachment_type_id = $this->attachment_type_model->update($id, $data);

			if ( ! $attachment_type_id) {
				$this->session->set_flashdata('failed', 'Failed to update attachment_type.');
				redirect('attachment_types');
			} else {
				$this->session->set_flashdata('success', 'Attachment Types successfully updated!');
				redirect('attachment_types');
			}
		}
		$this->load_view('forms/attachment_type-edit');
	}

    public function edit_confirmation($id)
    {
        $edit_attachment_type = $this->attachment_type_model->get_by(['id' => $id]);
        $data['edit_attachment_type'] = $edit_attachment_type;

        $this->load->view('modals/modal-update-attachment_type', $data);
    }

    public function update_status($id)
    {
        $attachment_type_data = $this->attachment_type_model->get_by(['id' => $id]);
        $data['attachment_type_data'] = $attachment_type_data;

        $post = $this->input->post();

        if (isset($post['mode']))
        {
            $result = FALSE;

            if ($post['mode'] == 'De-activate')
            {
				$old_data = 1;
				$new_data = 0;
                $result = $this->attachment_type_model->update($id, ['active_status' => 0]);
            }
            if ($post['mode'] == 'Activate')
            {
				$old_data = 0;
				$new_data = 1;
                $result = $this->attachment_type_model->update($id, ['active_status' => 1]);
            }

			$this->session->set_flashdata('log_parameters', [
				'action_mode' => 6,
				'perm_key'    => 'update_attachment_type_status',
				'old_data'    => $old_data,
				'new_data'    => $new_data
			]);

            if ($result)
            {
                 $this->session->set_flashdata('message', $attachment_type_data['name'].' successfully '.$post['mode'].'d!');
                 redirect('attachment_types');
            }
            else
            {
                $this->session->set_flashdata('failed', 'Unable to '.$post['mode'].' '.$attachment_type_data['name'].'!');
                redirect('attachment_types');
            }
        }
        else
        {
            $this->load->view('modals/modal-update-attachment_type-status', $data);
        }
    }
}


text:
require 'spec_helper'

describe Post::LocationsAccessor do
  it "will only persist when record is saved" do
    p = Post.create!(:uid => 'post:a.b.c')
    p.paths = ['a.not.persisted']
    q = Post.find(p.id)
    expect(q.paths.to_a).to eq ["a.b.c"]
  end

  it "can put a post in a path persist it" do
    p = Post.create!(:uid => 'post:a.b.c')
    expect(p.paths.to_a).to eq ['a.b.c']
    p.paths << 'a.ping.pong'
    p.save!
    q = Post.find(p.id)
    expect(p.paths.to_a).to include "a.ping.pong"
  end

  it "can be instantiatet from json without persisting the paths as a side effect" do
    p = Post.create!(:uid => 'post:a.b.c')
    p.paths = ['only.in.json']
    # Convert to json, but don't save
    json = p.to_json
    # Save with different paths
    p.paths = ['anton.kaanan', 'ranveig.banan']
    p.save!
    # Double check that the new set was persisted
    z = Post.find(p.id)
    expect(z.paths.to_a.sort).to eq ['a.b.c', 'anton.kaanan', 'ranveig.banan'].sort
    # Reheat model from json with stale path data
    q = Post.instantiate(JSON.parse(json)['post'])
    # Check that we got the old path in the stale model
    expect(q.paths.to_a).to eq ['only.in.json']
    # Check that reloading or loading the model from scratch will not include the stale path
    r = Post.find(p.id)
    expect(r.paths.to_a.sort).not_to include 'only.in.json'
    q.reload
    expect(q.paths.to_a.sort).not_to include 'only.in.json'
  end
end


text:
sap.ui.define(['ol', 'sap/ui/core/Element'],
    function(ol, Element) {
        "use strict";
        var Source = Element.extend("incentergy.ol.source.Source", {
            metadata: {
                library: "incentergy.ol",
                "abstract": true,
            },
            constructor: function() {
                var me = this;
                this.pMapSet = new Promise(function(resolve, reject) {
                    me.fnMapSet = resolve;
                });
                Element.apply(this, arguments);
            },
            setParent: function(oParent) {
                var me = this;
                var retVal = Element.prototype.setParent.apply(this, arguments);
                oParent.mapSet().then(function() {
                    me.fnMapSet();
                });
                return retVal;
            },
            mapSet: function() {
                return this.pMapSet;
            },
            getExtent: function() {
                if (this._source) {
                    return this._source.getExtent();
                }
            }
        });
        return Source;
    }, /* bExport= */ true);


text:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN"
    "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">

<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<meta name="generator" content="AsciiDoc 8.2.5" />

<title>git-fsck(1)</title>

git-fsck(1) Manual Page

NAME

git-fsck -
   Verifies the connectivity and validity of the objects in the database

SYNOPSIS

git fsck [--tags] [--root] [--unreachable] [--cache] [--no-reflogs]
         [--[no-]full] [--strict] [--verbose] [--lost-found] [<object>*]

DESCRIPTION

Verifies the connectivity and validity of the objects in the database.

OPTIONS

<object>

        An object to treat as the head of an unreachability trace.

If no objects are given, git fsck defaults to using the
index file, all SHA1 references in .git/refs/*, and all reflogs (unless
--no-reflogs is given) as heads.

--unreachable

        Print out objects that exist but that aren't readable from any
        of the reference nodes.

--root

        Report root nodes.

--tags

        Report tags.

--cache

        Consider any object recorded in the index also as a head node for
        an unreachability trace.

--no-reflogs

        Do not consider commits that are referenced only by an
        entry in a reflog to be reachable.  This option is meant
        only to search for commits that used to be in a ref, but
        now aren't, but are still in that corresponding reflog.

--full

        Check not just objects in GIT_OBJECT_DIRECTORY
        ($GIT_DIR/objects), but also the ones found in alternate
        object pools listed in GIT_ALTERNATE_OBJECT_DIRECTORIES
        or $GIT_DIR/objects/info/alternates,
        and in packed git archives found in $GIT_DIR/objects/pack
        and corresponding pack subdirectories in alternate
        object pools.  This is now default; you can turn it off
        with --no-full.

--strict

        Enable more strict checking, namely to catch a file mode
        recorded with g+w bit set, which was created by older
        versions of git.  Existing repositories, including the
        Linux kernel, git itself, and sparse repository have old
        objects that triggers this check, but it is recommended
        to check new projects with this flag.

--verbose

        Be chatty.

--lost-found

        Write dangling objects into .git/lost-found/commit/ or
        .git/lost-found/other/, depending on type.  If the object is
        a blob, the contents are written into the file, rather than
        its object name.

It tests SHA1 and general object sanity, and it does full tracking of
the resulting reachability and everything else. It prints out any
corruption it finds (missing or bad objects), and if you use the
--unreachable flag it will also print out objects that exist but
that aren't readable from any of the specified head nodes.

So for example

<tt>git fsck --unreachable HEAD \
        $(git for-each-ref --format="%(objectname)" refs/heads)</tt>

will do quite a _lot_ of verification on the tree. There are a few
extra validity tests to be added (make sure that tree objects are
sorted properly etc), but on the whole if git fsck is happy, you
do have a valid tree.

Any corrupt objects you will have to find in backups or other archives
(i.e., you can just remove them and do an rsync with some other site in
the hopes that somebody else has the object you have corrupted).

Of course, "valid tree" doesn't mean that it wasn't generated by some
evil person, and the end result might be crap. git is a revision
tracking system, not a quality assurance system ;)

Extracted Diagnostics

expect dangling commits - potential heads - due to lack of head information

        You haven't specified any nodes as heads so it won't be
        possible to differentiate between un-parented commits and
        root nodes.

missing sha1 directory <dir>

        The directory holding the sha1 objects is missing.

unreachable <type> <object>

        The <type> object <object>, isn't actually referred to directly
        or indirectly in any of the trees or commits seen. This can
        mean that there's another root node that you're not specifying
        or that the tree is corrupt. If you haven't missed a root node
        then you might as well delete unreachable nodes since they
        can't be used.

missing <type> <object>

        The <type> object <object>, is referred to but isn't present in
        the database.

dangling <type> <object>

        The <type> object <object>, is present in the database but never
        directly used. A dangling commit could be a root node.

warning: git-fsck: tree <tree> has full pathnames in it

        And it shouldn't…

sha1 mismatch <object>

        The database has an object who's sha1 doesn't match the
        database value.
        This indicates a serious data integrity problem.

Environment Variables

GIT_OBJECT_DIRECTORY

        used to specify the object database root (usually $GIT_DIR/objects)

GIT_INDEX_FILE

        used to specify the index file of the index

GIT_ALTERNATE_OBJECT_DIRECTORIES

        used to specify additional object database roots (usually unset)

Author

Written by Linus Torvalds <torvalds@osdl.org>

Documentation

Documentation by David Greaves, Junio C Hamano and the git-list <git@vger.kernel.org>.

GIT

Part of the git(1) suite

Last updated 2010-09-18 23:56:44 UTC


text:
<?php

namespace Stripe;

/**
 * Base class for Stripe test cases, provides some utility methods for creating
 * objects.
 */
class TestCase extends \PHPUnit_Framework_TestCase
{
    const API_KEY = 'tGN0bIwXnHdwOa85VABjPdSn8nWY7G7I';

    private $mock;

    protected static function authorizeFromEnv()
    {
        $apiKey = getenv('STRIPE_API_KEY');
        if (!$apiKey) {
            $apiKey = self::API_KEY;
        }

        Stripe::setApiKey($apiKey);
    }

    protected function setUp()
    {
        ApiRequestor::setHttpClient(HttpClient\CurlClient::instance());
        $this->mock = null;
        $this->call = 0;
    }

    protected function mockRequest($method, $path, $params = array(), $return = array('id' => 'myId'))
    {
        $mock = $this->setUpMockRequest();
        $mock->expects($this->at($this->call++))
             ->method('request')
             ->with(strtolower($method), 'https://api.stripe.com' . $path, $this->anything(), $params, false)
             ->willReturn(array(json_encode($return), 200, array()));
    }

    private function setUpMockRequest()
    {
        if (!$this->mock) {
            self::authorizeFromEnv();
            $this->mock = $this->getMock('\Stripe\HttpClient\ClientInterface');
            ApiRequestor::setHttpClient($this->mock);
        }
        return $this->mock;
    }

    /**
     * Create a valid test charge.
     */
    protected static function createTestCharge(array $attributes = array())
    {
        self::authorizeFromEnv();

        return Charge::create(
            $attributes + array(
                'amount' => 2000,
                'currency' => 'usd',
                'description' => 'Charge for test@example.com',
                'card' => array(
                    'number' => '4242424242424242',
                    'exp_month' => 5,
                    'exp_year' => date('Y') + 3,
                ),
            )
        );
    }

    /**
     * Create a valid test charge.
     */
    protected static function createTestTransfer(array $attributes = array())
    {
        self::authorizeFromEnv();

        $recipient = self::createTestRecipient();

        return Transfer::create(
            $attributes + array(
                'amount' => 2000,
                'currency' => 'usd',
                'description' => 'Transfer to test@example.com',
                'recipient' => $recipient->id
            )
        );
    }

    /**
     * Create a valid test customer.
     */
    protected static function createTestCustomer(array $attributes = array())
    {
        self::authorizeFromEnv();

        return Customer::create(
            $attributes + array(
                'card' => array(
                    'number' => '4242424242424242',
                    'exp_month' => 5,
                    'exp_year' => date('Y') + 3,
                ),
            )
        );
    }

    /**
     * Create a valid test recipient
     */
    protected static function createTestRecipient(array $attributes = array())
    {
        self::authorizeFromEnv();

        return Recipient::create(
            $attributes + array(
                'name' => 'PHP Test',
                'type' => 'individual',
                'tax_id' => '000000000',
                'bank_account' => array(
                    'country'    => 'US',
                    'routing_number' => '110000000',
                    'account_number'  => '000123456789'
                ),
            )
        );
    }

    /**
     * Create a test account
     */
    protected static function createTestAccount(array $attributes = array())
    {
        self::authorizeFromEnv();

        return Account::create(
            $attributes + array(
                'managed' => false,
                'country' => 'US',
                'email' => self::generateRandomEmail(),
            )
        );
    }

    /**
     * Verify that a plan with a given ID exists, or create a new one if it does
     * not.
     */
    protected static function retrieveOrCreatePlan($id)
    {
        self::authorizeFromEnv();

        try {
            $plan = Plan::retrieve($id);
        } catch (Error\InvalidRequest $exception) {
            $plan = Plan::create(
                array(
                    'id' => $id,
                    'amount' => 0,
                    'currency' => 'usd',
                    'interval' => 'month',
                    'name' => 'Gold Test Plan',
                )
            );
        }
    }

    /**
     * Verify that a coupon with a given ID exists, or create a new one if it
     * does not.
     */
    protected static function retrieveOrCreateCoupon($id)
    {
        self::authorizeFromEnv();

        try {
            $coupon = Coupon::retrieve($id);
        } catch (Error\InvalidRequest $exception) {
            $coupon = Coupon::create(
                array(
                    'id' => $id,
                    'duration' => 'forever',
                    'percent_off' => 25,
                )
            );
        }
    }

    /**
     * Genereate a semi-random string
     */
    protected static function generateRandomString($length = 24)
    {
        $characters = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTU';
        $charactersLength = strlen($characters);
        $randomString = '';
        for ($i = 0; $i < $length; $i++) {
            $randomString .= $characters[rand(0, $charactersLength - 1)];
        }
        return $randomString;
    }

    /**
     * Generate a semi-random email.
     */
    protected static function generateRandomEmail($domain = 'bar.com')
    {
        return self::generateRandomString().'@'.$domain;
    }

    protected static function createTestBitcoinReceiver($email)
    {
        $receiver = BitcoinReceiver::create(
            array(
                'amount' => 100,
                'currency' => 'usd',
                'description' => 'some details',
                'email' => $email
            )
        );
        return $receiver;
    }
}


text:
package com.github.laboo.lwes.websocketserver;

import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.google.common.net.InetAddresses;

import java.util.*;

/**
 * Created by mlibucha on 5/9/15.
 */

@JsonIgnoreProperties({"events", "clients"})
public class ClientConfig {
    public static String BATCH_SIZE_KEY = "batchSize";
    public static String MAX_SECS_KEY = "maxSecs";
    public static String IP_KEY = "ip";
    public static String PORT_KEY = "port";
    public static String REQUESTS_KEY = "requests";
    public static String FILTERS_KEY = "filters";
    public static int DEFAULT_BATCH_SIZE = 100;
    public static int DEFAULT_MAX_SECS = 60;

    int batchSize;
    int maxSecs;
    String ip;
    int port;
    List<Filter> filters = new ArrayList<>();
    Map<String, List<String>> requests;
    Set<Client> clients = new HashSet<Client>();

    private ClientConfig(String ip,
                         int port,
                         int batchSize,
                         int maxSecs,
                         List<Filter> filters,
                         Map<String, List<String>> requests) {
        this.ip = ip;
        this.port = port;
        this.batchSize = batchSize;
        this.maxSecs = maxSecs;
        this.filters = filters;
        this.requests = requests;
    }

    public int getBatchSize() {
        return batchSize;
    }

    public int getMaxSecs() {
        return maxSecs;
    }

    public void setBatchSize(int batchSize) {
        this.batchSize = batchSize;
    }

    public void setMaxSecs(int maxSecs) {
        this.maxSecs = maxSecs;
    }

    public String getIp() {
        return ip;
    }

    public void setIp(String ip) {
        this.ip = ip;
    }

    public int getPort() {
        return port;
    }

    public void setPort(int port) {
        this.port = port;
    }

    public List<Filter> getFilters() {
        return filters;
    }

    public void setFilters(List<Filter> filters) {
        this.filters = filters;
    }

    public void setRequests(Map<String, List<String>> requests) {
        this.requests = requests;
    }

    public Map<String,List<String>> getRequests() {
        return this.requests;
    }

    public String getChannel() {
        return this.ip + ":" + this.port;
    }

    public void addClient(Client client) {
        this.clients.add(client);
    }

    public boolean removeClient(Client client) {
        return this.clients.remove(client);
    }

    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (o == null || getClass() != o.getClass()) return false;
        ClientConfig that = (ClientConfig) o;
        if (port != that.port) return false;
        if (!ip.equals(that.ip)) return false;
        if (filters.size() != that.filters.size()) return false;
        for (int i = 0; i < filters.size(); i++) {
            if (!filters.get(i).equals(that.filters.get(i))) return false;
        }
        if (requests.size() != that.requests.size()) return false;
        for (Map.Entry<String, List<String>> entry : requests.entrySet()) {
            if (that.requests.get(entry.getKey()) == null) return false;
            for (String str : entry.getValue()) {
                if (!that.requests.get(entry.getKey()).contains(str)) {
                    return false;
                }
            }
        }
        return true;
    }

    @Override
    public int hashCode() {
        int result = ip.hashCode();
        result = 31 * result + port;
        for (Filter filter : filters) {
            result = 31 * filter.hashCode();
        }
        for (Map.Entry<String,List<String>> entry : requests.entrySet()) {
            result = 31 * result + entry.getKey().hashCode();
            for (String str : entry.getValue()) {
                result = 31 * result + str.hashCode(); // XXX
            }
        }
        return result;
    }

    @Override
    public String toString() {
        StringBuilder sb = new StringBuilder();
        sb.append("{");
        sb.append("channel:");
        sb.append(this.getChannel());
        sb.append(" filters:[");
        if (filters != null) {
            for (Filter f : filters) {
                sb.append(f);
            }
        }
        sb.append("]");
        sb.append(" requests:");
        if (requests != null) {
            for (Map.Entry<String, List<String>> entry : requests.entrySet()) {
                sb.append(" ");
                if (entry.getKey().length() == 0) {
                    sb.append("*");
                } else {
                    sb.append(entry.getKey());
                }
                sb.append("=>[");
                boolean first = true;
                for (String attr : entry.getValue()) {
                    if (first) {
                        first = false;
                    } else {
                        sb.append(",");
                    }
                    sb.append(attr);
                }
                sb.append("]");
            }
        }
        sb.append("}");
        return sb.toString();
    }

    public static ClientConfig build(String json) throws Exception {
        ObjectMapper mapper = new ObjectMapper();
        mapper.configure(JsonParser.Feature.ALLOW_SINGLE_QUOTES, true);
        Map<String,Object> config = mapper.readValue(json, Map.class);

        int batchSize = DEFAULT_BATCH_SIZE;
        int maxSecs = DEFAULT_MAX_SECS;
        String ip = null;
        Map<String, List<String>> requests = new HashMap<>();
        List<Filter> filters = new ArrayList<>();

        Integer port = null;

        try {
            Object obj = config.get(BATCH_SIZE_KEY);
            if (obj != null) {
                batchSize = (Integer) obj;
            }
        } catch (ClassCastException cce) {
            throw new IllegalArgumentException(BATCH_SIZE_KEY + " must be of type integer");
        }

        try {
            Object obj = config.get(MAX_SECS_KEY);
            if (obj != null) {
                maxSecs = (Integer) obj;
            }
        } catch (ClassCastException cce) {
            throw new IllegalArgumentException(MAX_SECS_KEY + " must be of type integer");
        }

        try {
            port = (Integer) config.get(PORT_KEY);
        } catch (ClassCastException cce) {
            throw new IllegalArgumentException(PORT_KEY + " must be of type integer");
        }
        if (port == null) {
            throw new IllegalArgumentException(PORT_KEY + " must be specified");
        }

        try {
            ip = (String) config.get(IP_KEY);
        } catch (ClassCastException cce) {
            throw new IllegalArgumentException(IP_KEY + " must be of type string");
        }
        if (ip == null) {
            throw new IllegalArgumentException(IP_KEY + " must be specified");
        }
        try {
            InetAddresses.forString(ip);
        } catch (IllegalArgumentException e) {
            throw new IllegalArgumentException(ip + " is not a valid IP address");
        }

        try {
            requests = (Map) config.get(REQUESTS_KEY);
        } catch (ClassCastException cce) {
            String msg = REQUESTS_KEY + " must be of type (JSON) object";
            throw new IllegalArgumentException(REQUESTS_KEY + " must be of type (JSON) object");
        }

        if (requests == null) {
            throw new IllegalArgumentException(REQUESTS_KEY + " must be specified");
        }

        try {
            Map<String, List<String>> r = (Map<String, List<String>>) config.get(REQUESTS_KEY);
            for (Map.Entry<String, List<String>> entry : r.entrySet()) {
                for (String entry2 : entry.getValue()) {
                    // pass
                }
            }
        } catch (ClassCastException cce) {
            throw new IllegalArgumentException(REQUESTS_KEY + " must be of type (JSON) object, string to list of string");
        }

        try {

            Object obj = config.get(FILTERS_KEY);
            if (obj != null) {
                if (!(obj instanceof List)) {
                    throw new IllegalArgumentException(FILTERS_KEY + " must be a list of objects");
                }

                List<Object> olist = (List<Object>) obj;
                for (Object o: olist) {
                    if (!(o instanceof Map)) {
                        throw new IllegalArgumentException(FILTERS_KEY + " list must contain object types");
                    }
                    Map map = (Map) o;
                    filters.add(new Filter((String) map.get("name"),
                            (String) map.get("attribute"),
                            (String) map.get("value")));
                }
            }
        } catch (ClassCastException cce) {
            throw new IllegalArgumentException(FILTERS_KEY + " must be of type object");
        }

        return new ClientConfig(
                ip,
                port,
                batchSize,
                maxSecs,
                filters,
                requests
        );
    }
}


text:
API: `Redirect` (component)
===========================

Configures a redirect for a path in your route declarations.

Props
-----

### `from`

The path you want to redirect from, including dynamic segments.

### `to`

The `name` of the route you want to redirect to.

Example
-------

```xml
<!--
  lets say we want to change from `/profile/123` to `/about/123`
  and redirect `/get-in-touch` to `/contact`
-->
<Routes>
  <Route handler={App}>
    <Route name="contact" handler={Contact}/>
    <Route name="about-user" path="about/:userId" handler={UserProfile}/>
  </Route>

  <Redirect from="get-in-touch" to="contact" />
  <Redirect from="profile/:userId" to="about-user" />
</Routes>
```

Note that the `<Redirect/>` can be placed anywhere in the route
hierarchy, if you'd prefer the redirects to be next to their respective
routes.

```xml
<Routes>
  <Route handler={App}>
    <Route name="contact" handler={Contact}/>
    <Redirect from="get-in-touch" to="contact" />
  </Route>
</Routes>
```


text:
function verifyInterface(name, instance, attributes) {
    assert_true(name in self,
                name + ' should be an defined type');
    if (instance) {
        assert_true(instance instanceof self[name],
                    instance + ' should be an instance of ' + name);
        Object.keys(attributes || {}).forEach(function(attribute) {
            var type = attributes[attribute];
            assert_true(attribute in instance,
                        attribute + ' should be an attribute of ' + name);
            assert_equals(typeof instance[attribute], type,
                          attribute + ' should be of type ' + type);
        });
    }
}


text:
'use strict';

const assert = require('chai').assert;
const Tile = require('../../src/lib/Tile.js');

describe('Tile', function() {
  describe('#constructor', function () {
    it('should return initial params', function () {
      let tile = new Tile(0, 1, 2, 3);
      assert.equal(tile.x, 0);
      assert.equal(tile.y, 1);
      assert.equal(tile.width, 2);
      assert.equal(tile.height, 3);
    });
  });

  describe('#top', function () {
    it('should return same value as y', function () {
      let tile = new Tile(3, 4, 5, 6);
      assert.equal(tile.y, tile.top);
    });
  });

  describe('#right', function () {
    it('should calculate correct value', function () {
      let tile = new Tile(2, 4, 8, 16);
      assert.equal(9, tile.right);
    });
  });

  describe('#bottom', function () {
    it('should calculate correct value', function () {
      let tile = new Tile(3, 6, 12, 24);
      assert.equal(29, tile.bottom);
    });
  });

  describe('#left', function () {
    it('should return same value as x', function () {
      let tile = new Tile(3, 4, 5, 6);
      assert.equal(tile.x, tile.left);
    });
  });
});


text:
class MemoryInternalsUI : public content::WebUIController {
 public:
  explicit MemoryInternalsUI(content::WebUI* web_ui);
  ~MemoryInternalsUI() override;

 private:
  DISALLOW_COPY_AND_ASSIGN(MemoryInternalsUI);
};

#endif  // CHROME_BROWSER_UI_WEBUI_MEMORY_INTERNALS_UI_H_


text:
if [ -z "$1" ]
    then
        echo "Specify release version as first argument"
	exit 0
fi

if [ -z "$2" ]
    then
        echo "Specify development version as second argument"
        exit 0
fi

RELEASEVERSION=${1}
DEVELOPMENTVERSION=${2}

echo "Releasing with version: $RELEASEVERSION"

mvn versions:set -DnewVersion=$RELEASEVERSION
git add .
git commit -m "poms for release version $RELEASEVERSION"
git push origin master
git tag -a v$RELEASEVERSION -m "tag v$RELEASEVERSION"
git push --tags
mvn clean gpg:sign deploy -Dgpg.executable=gpg2 -s ~/.m2/settings.xml
mvn versions:set -DnewVersion $DEVELOPMENTVERSION
git add .
git commit -m "poms for development version $DEVELOPMENTVERSION"
git push origin master


text:
import hashlib

#make a hash for a directory
def make_namehash(filename):
  h=hashlib.sha256()
  h.update(filename);
  return h.hexdigest();

#make a hash for a file
def make_filehash(path):

  file_object=open(path, 'rb')

  h=hashlib.sha256()
  file_object.seek(0)

  while True:
     chunksize=4096
     data = file_object.read(chunksize)
     if not data:
        break
     h.update(data_to_string(data))

  file_object.close()
  return h.hexdigest()

def data_to_string(data):
  if isinstance(data, str):
    return data
  elif isinstance(data, unicode):
    return data.encode("utf-8")
  else:
    return str(data)


text: module.exports = require('./lib/iostreams');


text:
<?php
namespace Bun\Core\Router;

use Bun\Core\Config\ConfigAwareInterface;
use Bun\Core\Config\ConfigInterface;
use Bun\Core\Exception\NotFoundException;
use Bun\Core\Http\RequestAwareInterface;
use Bun\Core\Http\RequestInterface;

/**
 * Class Router
 *
 * @package Bun\Core\Router
 */
class Router implements RouterInterface, ConfigAwareInterface, RequestAwareInterface
{
    /** @var ConfigInterface */
    protected $config;
    /** @var RequestInterface */
    protected $request;
    /** @var array */
    protected $routes = array();

    protected $methods = array(
        'GET',
        'POST',
        'PUT',
        'DELETE'
    );

    /**
     *
     */
    public function __construct()
    {
    }

    /**
     * @param ConfigInterface $config
     */
    public function setConfig(ConfigInterface $config)
    {
        $this->config = $config;
    }

    /**
     * @param RequestInterface $request
     */
    public function setRequest(RequestInterface $request)
    {
        $this->request = $request;
    }

    /**
     * @return RoutingResult
     * @throws RoutingException
     */
    public function route()
    {
        if ($this->request->isConsole()) {
            return $this->routeTool();
        }

        $routes = $this->config->get('router');
        $uri = explode('?', $this->request->uri());
        $uri = $uri[0];
        $routesUris = array_keys($routes);

        $routingResult = new RoutingResult();
        $matchedRoute = in_array($uri, $routesUris) ?
            $matchedRoute = $routes[$uri] :
            $matchedRoute = $this->match($routes);

        if ($matchedRoute) {
            $routingResult
                ->setControllerClass($matchedRoute['controller'])
                ->setActionName(isset($matchedRoute['action']) ?
                        $matchedRoute['action'] :
                        self::DEFAULT_ROUTING_ACTION
                )
                ->setActionParams(isset($matchedRoute['params']) ?
                        $matchedRoute['params'] :
                        array()
                );

            return $routingResult;
        }

        throw new RoutingException(
            'Unable to match route for: ' . $this->request->method() . ': ' . $uri
        );
    }

    /**
     * @return RoutingResult
     * @throws RoutingException
     */
    protected function routeTool()
    {
        $toolsConfig = $this->config->get('tool');
        $requestArgs = $this->request->getConsoleArgs();
        $requestTool = isset($requestArgs[1]) ? $requestArgs[1] : 'bun.tool';
        $toolParts = explode(':', $requestTool);
        $toolName = $toolParts[0];
        $toolAction = isset($toolParts[1]) ? $toolParts[1] : 'index';
        $toolParams = array_slice($toolParts, 2);

        if (is_array($toolsConfig) && isset($toolsConfig[$toolName])) {
            $toolControllerClass = $toolsConfig[$toolName];
            if (class_exists($toolControllerClass)) {
                $routingResult = new RoutingResult();
                $routingResult
                    ->setControllerClass($toolControllerClass)
                    ->setActionName($toolAction)
                    ->setActionParams($toolParams);

                return $routingResult;
            }
        }

        throw new RoutingException('Requested tool: ' . $toolName . ' could not be found');
    }

    /**
     * @param array $routes
     * @return bool|array
     */
    protected function match($routes)
    {
        $uri = explode('?', $this->request->uri());
        $uri = $uri[0];
        $method = $this->request->method();
        $routesUri = array_keys($routes);
        $matchedRoute = false;
        foreach ($routesUri as $routeUri) {
            if (strpos($routeUri, ':') !== false) {
                $routeMethods = isset($routes[$routeUri]['method']) ?
                    $routes[$routeUri]['method'] :
                    $this->methods;
                $regexRouteUri = str_replace('/', '\\/', $routeUri);
                $regexRouteUri = '/' . preg_replace('/:(\w+)/', '\w+', $regexRouteUri) . '$/';
                if (preg_match($regexRouteUri, $uri, $matches) && in_array($method, $routeMethods)) {
                    $matchedRoute = $routes[$routeUri];
                    preg_match_all('/:\w+/', $routeUri, $routeParams);
                    preg_match_all('/\w+/', $routeUri, $routeParts);
                    preg_match_all('/\w+/', $uri, $uriParts);
                    $actionParams = array();
                    foreach ($routeParts[0] as $key => $paramName) {
                        if (in_array(':' . $paramName, $routeParams[0])) {
                            $actionParams[$paramName] = isset($uriParts[0][$key]) ?
                                $uriParts[0][$key] :
                                null;
                        }
                    }
                    $matchedRoute['params'] = $actionParams;

                    break;
                }
            }
        }

        return $matchedRoute;
    }
}


text:
package org.panteleyev.money.backend.controller;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import static org.panteleyev.money.backend.WebmoneyApplication.UI_ROOT;

@Controller
@RequestMapping(UI_ROOT)
public class UiController {
}


text:
<template name="shoppingCart">

      {{> totalBox}}

        <button class="ui fluid small positive button proceed-to-checkout">
          {{_ 'proceed_to_checkout'}}
        </button>

        <button class="ui fluid small blue button continue-shopping">
          {{_ 'continue_shopping'}}
        </button>

        <button class="ui fluid small negative button clearCart">
          {{_ 'clear_cart'}}
        </button>

    {{#each cartitems}}

{{productName}}

            <input type="number" value="{{qty}}" min="1" max="9" class="shop-cart-input-qty">
            <button class="ui red small button floated right removeCartItem">X</button>

            {{currency productPrice}}

    {{else}}

                {{_ 'empty_cart'}}

    {{/each}}

</template>