text:
require File.join(File.dirname(__FILE__), '../lib/helpers/require_helper')

require Bufs.lib 'grapher'
require Bufs.spec_helpers 'bufs_test_environments'

module MakeUserClasses
    @user1_id = "CouchUser001"
    @user2_id = "CouchUser002"
    @user3_id = "FileSysUser003"
    @user4_id = "FileSysUser004"
    node_class_id1 = "BufsInfoNode#{@user1_id}"
    node_class_id2 = "BufsInfoNode#{@user2_id}"
    node_class_id3 = "BufsFile#{@user3_id}"
    node_class_id4 = "BufsFile#{@user4_id}"
    node_env1 = CouchRestNodeHelpers.env_builder(node_class_id1, CouchDB, @user1_id)
    node_env2 = CouchRestNodeHelpers.env_builder(node_class_id2, CouchDB2, @user2_id)
    node_env3 = FileSystemNodeHelpers.env_builder(node_class_id3, FileSystem1, @user3_id)
    node_env4 = FileSystemNodeHelpers.env_builder(node_class_id4, FileSystem2, @user4_id)
    User1Class =  BufsNodeFactory.make(node_env1)
    User2Class =  BufsNodeFactory.make(node_env2)
    User3Class =  BufsNodeFactory.make(node_env3)
    User4Class =  BufsNodeFactory.make(node_env4)
end

module GrapherSpecHelpers
  include NodeHelpers
  include MakeUserClasses

  def data_for_simple_tree(user_class)
    nodes = []
    top = make_doc_no_attachment(user_class, :my_category => 'top')
    #top.__save
    child1_params = {:my_category => 'child1',
                     :parent_categories => ['top', 'just_a_label1']}
    child2_params = {:my_category => 'child2',
                     :parent_categories => ['top', 'just_a_label2']}
    child1 = make_doc_no_attachment(user_class, child1_params)
    child2 = make_doc_no_attachment(user_class, child2_params)
    #child1.__save
    #child2.__save
    nodes = [top, child1, child2]
  end

  def two_simple_trees(user_class)
    #tree1
    top1 = make_doc_no_attachment(user_class, :my_category => 'top1')
    #top1.__save
    child11_params = {:my_category => 'child11',
                     :parent_categories => ['top1', 'just_a_label11']}
    child12_params = {:my_category => 'child12',
                     :parent_categories => ['top1', 'just_a_label2']}
    child11 = make_doc_no_attachment(user_class, child11_params)
    child12 = make_doc_no_attachment(user_class, child12_params)
    #child11.__save
    #child12.__save
    #tree2
    top2 = make_doc_no_attachment(user_class, :my_category => 'top2')
    #top2.__save
    child21_params = {:my_category => 'child21',
                     :parent_categories => ['top2', 'just_a_label11']}
    child22_params = {:my_category => 'child22',
                     :parent_categories => ['top2', 'just_a_label2']}
    child21 = make_doc_no_attachment(user_class, child21_params)
    child22 = make_doc_no_attachment(user_class, child22_params)
    #child21.__save
    #child22.__save
    nodes = [top1, child21, top2, child12, child11, child22]
  end

  def two_simple_trees_with_link1(user_class)
    simple_trees = two_simple_trees(user_class)
    #create_link
    #between child12 and child22, specifically child12 would be a child of child22
    simple_trees[3].parent_categories_add 'child22'
    simple_trees
  end

  def two_simple_trees_with_inf_loop(user_class)
    looped_trees = two_simple_trees(user_class)
    looped_trees[0].parent_categories_add 'child22'
    looped_trees[2].parent_categories_add 'child11'
    looped_trees
  end

  def save_all(nodes)
    nodes.each do |node|
      node.__send__(:__save)
    end
  end
end

describe Grapher do
  include MakeUserClasses
  include GrapherSpecHelpers

  before(:each) do
    @user_classes = [User1Class, User2Class, User3Class, User4Class]
    @root_data = RootNode.new(:root, :root_data)
  end

  after(:each) do
    @user_classes.each {|uc| uc.destroy_all}
  end

  it "should initialize properly" do
    @user_classes.each do |user_class|
      #save to the persistence layer data to make a simple tree
      #not assigned to a variable because we'll pull it from the
      #persistence layer later
      save_all data_for_simple_tree(user_class)
    end
    #check initial conditions
    @user_classes.each do |user_class|
      tops = user_class.call_view(:my_category, 'top')
      tops.size.should == 1
      childs = user_class.call_view(:parent_categories, 'top')
      childs.size.should == 2
    end
    #test
    user_graph = {}
    keys = {:node_id_key => :my_category,
                :parent_key => :parent_categories }
    @user_classes.each do |user_class|
      nodes = user_class.all
      user_graph[user_class] = Grapher.new(nodes, keys, :tree, @root_data)
    end
    #verify results
    @user_classes.each do |user_class|
      my_tree = user_graph[user_class]
      my_tree.key.should == keys[:node_id_key]
      my_tree.parent_key.should == keys[:parent_key]
      my_tree.nodes_by_parent_cat.each do |parent_node_pair|
        parent_cat = parent_node_pair[0]
        parent_node_pair[1].node_parents.should include
        my_tree.nodes_by_name[parent_cat].node_name
      end
    end
  end

  it "should create a very simple tree" do
    #initial conditions
    @user_classes.each do |user_class|
      save_all data_for_simple_tree(user_class) #saved to model
    end
    #check initial conditions
    @user_classes.each do |user_class|
      tops = user_class.call_view(:my_category, 'top')
      tops.size.should == 1
      childs = user_class.call_view(:parent_categories, 'top')
      childs.size.should == 2
    end
    #test
    user_graph = {}
    @user_classes.each do |user_class|
      model_nodes = user_class.all
      model_nodes.size.should > 1

      keys = {:node_id_key => :my_category,
              :parent_key => :parent_categories}
      user_graph[user_class] = Grapher.new(model_nodes, keys, :tree, @root_data)
    end
    #verify results
    @user_classes.each do |user_class|
      #puts "User Class to build graph: #{user_class.inspect}"
      my_grapher = user_graph[user_class]
      tree = my_grapher.graph

      root_id =my_grapher.converted_root_node
      #puts "Root Nodes: #{root_id.inspect}"
      #puts "Working Tree: #{tree.vertices.map{|v| v.class.inspect}}"
      #puts "Verts: #{tree.vertices.map{|v| v.node_content.class.name}.inspect}"
      bfs = tree.bfs_iterator(root_id)
      #puts "BFS Tree size: #{bfs.vertices.map{|v| v.node_name.inspect}}"
      tree_order = []
      bfs.each {|v| tree_order << v}
      #tree_order.should == []
      tree_order[0].should == root_id
      tree_order[1].node_name.should == 'top'
      ['child1', 'child2'].should include tree_order[2].node_name
      ['child1', 'child2'].should include tree_order[2].node_name
      tree_order[2].node_name.should_not == tree_order[3].node_name
      tree_order[1].normal_descendants.map{|d| d.node_name}.sort.should == ['child1', 'child2']
    end
  end

  it "should create a two simple trees (connected by root)" do
    #initial conditions
    @user_classes.each do |user_class|
      save_all two_simple_trees(user_class) #saved to model
    end
    #check initial conditions
    @user_classes.each do |user_class|
      tops = user_class.call_view(:my_category, 'top1')
      tops.size.should == 1
      childs = user_class.call_view(:parent_categories, 'top1')
      childs.size.should == 2
      tops = user_class.call_view(:my_category, 'top2')
      tops.size.should == 1
      childs = user_class.call_view(:parent_categories, 'top2')
      childs.size.should == 2
    end
    #test
    user_graph = {}
    @user_classes.each do |user_class|
      model_nodes = user_class.all
      model_nodes.size.should > 1
      #root_data = {:tree_root_id => user_class.name,
      #             :tree_root_content => user_class}
      keys = {:node_id_key => :my_category,
              :parent_key => :parent_categories}
	    user_graph[user_class] = Grapher.new(model_nodes, keys, :tree, @root_data)
    end
    #verify results
    @user_classes.each do |user_class|
      my_grapher = user_graph[user_class]
      tree = my_grapher.graph
      root_nodes = tree.vertices.select{|v| v == my_grapher.converted_root_node}
      #raise "vertex not found for #{@root_data.class.name}. Verts: #{tree.vertices.map{|v| v.node_content.class.name}.inspect}"
      raise "Wrong number of root nodes: #{root_nodes.size}" unless root_nodes.size == 1
      root_node = root_nodes.first
      bfs = tree.bfs_iterator(root_node)
      tree_order = []
      bfs.each {|v| tree_order << v}
      tree_order[0].should == root_node
      tree_order[1].node_name.should == 'top1'
      tree_order[2].node_name.should == 'top2'
      tree_order[3].node_name.should == 'child11'
      tree_order[4].node_name.should == 'child12'
      tree_order[5].node_name.should == 'child21'
      tree_order[6].node_name.should == 'child22'
      tree_order[1].normal_descendants.map{|d| d.node_name}.sort.should == ['child11', 'child12']
      tree_order[2].normal_descendants.map{|d| d.node_name}.sort.should == ['child21', 'child22']
    end
  end

  it "should create a two simple trees with a single link" do
    #initial conditions
    @user_classes.each do |user_class|
      save_all two_simple_trees_with_link1(user_class) #saved to model
    end
    #check initial conditions
    @user_classes.each do |user_class|
      tops = user_class.call_view(:my_category, 'top1')
      tops.size.should == 1
      childs = user_class.call_view(:parent_categories, 'top1')
      childs.size.should == 2
      tops = user_class.call_view(:my_category, 'top2')
      tops.size.should == 1
      childs = user_class.call_view(:parent_categories, 'top2')
      childs.size.should == 2
      child12 = user_class.call_view(:my_category, 'child12').first
      child12.parent_categories.should include 'child22'
    end
    #test
    user_graph = {}
    @user_classes.each do |user_class|
      model_nodes = user_class.all
      model_nodes.size.should > 1
      root_data = {:tree_root_id => user_class.name,
                   :tree_root_content => user_class}
      keys = {:node_id_key => :my_category,
              :parent_key => :parent_categories}
      user_graph[user_class] = Grapher.new(model_nodes, keys, :tree, @root_data)
    end
    #verify results
    @user_classes.each do |user_class|
      my_grapher = user_graph[user_class]
      tree = my_grapher.graph
      root_nodes = tree.vertices.select{|v| v == my_grapher.converted_root_node}
      #raise "vertex not found for #{@root_data.class.name}. Verts: #{tree.vertices.map{|v| v.node_content.class.name}.inspect}"
      raise "Wrong number of root nodes: #{root_nodes.size}" unless root_nodes.size == 1
      root_node = root_nodes.first
      bfs = tree.bfs_iterator(root_node)
      tree_order = []
      bfs.each {|v| tree_order << v}
      tree_order[0].should == root_node
      tree_order[1].node_name.should == 'top1'
      tree_order[2].node_name.should == 'top2'
      tree_order[3].node_name.should == 'child11'
      tree_order[4].node_name.should == 'child12'
      tree_order[5].node_name.should == 'child21'
      tree_order[6].node_name.should == 'child22'
      tree_order[1].normal_descendants.map{|d| d.node_name}.sort.should == ['child11', 'child12']
      tree_order[2].normal_descendants.map{|d| d.node_name}.sort.should == ['child21', 'child22']
      tree_order[6].normal_descendants.map{|d| d.node_name}.should == []
      tree_order[6].linked_descendants.map{|d| d.node_name}.should == ['child12']
      normal_ds = []
      linked_ds = []
      #tree_order.map{|tw_node| normal_ds << tw_node.normal_descendants.map{|n| n.node_name} unless tw_node == :root}
      #normal_ds.should == 'blah'
      #tree_order.map{|tw_node| linked_ds << tw_node.linked_descendants.map{|n| n.node_name} unless tw_node == :root}
      #linked_ds.should == 'blah'
    end
  end

   it "should create a two simple trees with an infinitely looped link" do
    #initial conditions
    @user_classes.each do |user_class|
      save_all two_simple_trees_with_inf_loop(user_class) #saved to model
    end
    #check initial conditions
    @user_classes.each do |user_class|
      top1 = user_class.call_view(:my_category, 'top1')
      top1.size.should == 1
      child1 = user_class.call_view(:parent_categories, 'top1')
      child1.size.should == 2
      top2 = user_class.call_view(:my_category, 'top2')
      top2.size.should == 1
      child2 = user_class.call_view(:parent_categories, 'top2')
      child2.size.should == 2
      top1.first.parent_categories.should include 'child22'
      top2.first.parent_categories.should include 'child11'
    end
    #test
    user_tree = {}
    user_digraph = {}
    @user_classes.each do |user_class|
      model_nodes = user_class.all
      model_nodes.size.should > 1
      #root_data = {:tree_root_id => user_class.name,
      #             :tree_root_content => user_class}
      keys = {:node_id_key => :my_category,
              :parent_key => :parent_categories}
      user_tree[user_class] = Grapher.new(model_nodes, keys, :tree, @root_data)
    end
    #verify results
    @user_classes.each do |user_class|
      #rough verify of digraph

      my_grapher = user_tree[user_class]
      tree = my_grapher.graph
      root_nodes = tree.vertices.select{|v| v == my_grapher.converted_root_node}
      #raise "vertex not found for #{@root_data.class.name}. Verts: #{tree.vertices.map{|v| v.node_content.class.name}.inspect}"
      raise "Wrong number of root nodes: #{root_nodes.size}" unless root_nodes.size == 1
      root_node = root_nodes.first
      bfs = tree.bfs_iterator(root_node)
      tree_order = []
      bfs.each {|v| tree_order << v}
      tree_order[0].should == my_grapher.converted_root_node
      tree_order[1].node_name.should == 'top1'
      tree_order[2].node_name.should == 'top2'
      tree_order[3].node_name.should == 'child11'
      tree_order[4].node_name.should == 'child12'
      tree_order[5].node_name.should == 'child21'
      tree_order[6].node_name.should == 'child22'
      tree_order[1].normal_descendants.map{|d| d.node_name}.sort.should == ['child11', 'child12']
      tree_order[2].normal_descendants.map{|d| d.node_name}.sort.should == ['child21', 'child22']
      tree_order[6].normal_descendants.map{|d| d.node_name}.should == []
      tree_order[6].linked_descendants.map{|d| d.node_name}.should == ['top1']
      tree_order[3].normal_descendants.map{|d| d.node_name}.should == []
      tree_order[3].linked_descendants.map{|d| d.node_name}.should == ['top2']
      normal_ds = []
      linked_ds = []
      #tree_order.map{|tw_node| normal_ds << tw_node.normal_descendants.map{|n| n.node_name} unless tw_node == :root}
      #normal_ds.should == 'blah'
      #tree_order.map{|tw_node| linked_ds << tw_node.linked_descendants.map{|n| n.node_name} unless tw_node == :root}
      #linked_ds.should == 'blah'
    end
  end

   it "should create a directed graph with an infinitely looped link" do
    #initial conditions
    @user_classes.each do |user_class|
      save_all two_simple_trees_with_inf_loop(user_class) #saved to model
    end
    #check initial conditions
    @user_classes.each do |user_class|
      top1 = user_class.call_view(:my_category, 'top1')
      top1.size.should == 1
      child1 = user_class.call_view(:parent_categories, 'top1')
      child1.size.should == 2
      top2 = user_class.call_view(:my_category, 'top2')
      top2.size.should == 1
      child2 = user_class.call_view(:parent_categories, 'top2')
      child2.size.should == 2
      top1.first.parent_categories.should include 'child22'
      top2.first.parent_categories.should include 'child11'
    end
    #test
    user_digraph = {}
    @user_classes.each do |user_class|
      model_nodes = user_class.all
      model_nodes.size.should > 1
      #root_data = {:tree_root_id => user_class.name,
      #             :tree_root_content => user_class}
      keys = {:node_id_key => :my_category,
              :parent_key => :parent_categories}
      user_digraph[user_class] = Grapher.new(model_nodes, keys, :digraph, @root_data)
    end
    #verify results
    @user_classes.each do |user_class|
      #rough verify of digraph
      my_digraph = user_digraph[user_class]
      digraph = my_digraph.graph
      dg_node_names = digraph.vertices.map{|v| v.node_name}.sort
      dg_node_names.should == ['top1', 'child21', 'top2',
                                'child12', 'child11', 'child22'].sort
      digraph.acyclic?.should == false
      this_node = my_digraph.nodes_by_name['top1']
      nbrs = digraph.adjacent_vertices(this_node)
      nbrs.size.should == 2
      nbrs.each do |nbr_node|
        ['child11', 'child12'].should include nbr_node.node_name
      end
      this_node = my_digraph.nodes_by_name['top2']
      nbrs = digraph.adjacent_vertices(this_node)
      nbrs.size.should == 2
      nbrs.each do |nbr_node|
        ['child21', 'child22'].should include nbr_node.node_name
      end
      this_node = my_digraph.nodes_by_name['child22']
      nbrs = digraph.adjacent_vertices(this_node)
      nbrs.size.should == 1
      nbrs.each do |nbr_node|
        ['top1'].should include nbr_node.node_name
      end
      this_node = my_digraph.nodes_by_name['child11']
      nbrs = digraph.adjacent_vertices(this_node)
      nbrs.size.should == 1
      nbrs.each do |nbr_node|
        ['top2'].should include nbr_node.node_name
      end
      #dgbfs = digraph.bfs_iterator[top1_node]
      #dgbfs.attach_distance_map
    end
  end
end

describe Borg do
  include MakeUserClasses
  include GrapherSpecHelpers

  before(:each) do
    @user_classes = [User1Class, User2Class, User3Class, User4Class]
    #@root_data = RootNode.new(:root, :root_data)
    @keys = {:node_id_key => :my_category,
             :parent_key => :parent_categories}
  end

  after(:each) do
    @user_classes.each {|uc| uc.destroy_all}
  end

  it "should initialize properly" do
    @user_classes.each do |user_class|
      #save to the persistence layer data to make a simple tree
      #not assigned to a variable because we'll pull it from the
      #persistence layer later
      save_all data_for_simple_tree(user_class)
      tops = user_class.call_view(:my_category, 'top')
      tops.size.should == 1
      childs = user_class.call_view(:parent_categories, 'top')
      childs.size.should == 2
    end
    #test (not a full test, since Borg doesn't do much on init)
    @user_classes.each do |user_class|
      node_list = user_class.all
      borg = Borg.new(node_list, @keys)
    end
    #verify results
    #ok if it doesn't crash on initialization
    #the borg object may have attributes in the future
  end

  it "should borg.ify all descendant data for each node for a simple tree" do
    @user_classes.each do |user_class|
      #save to the persistence layer data to make a simple tree
      #not assigned to a variable because we'll pull it from the
      #persistence layer later
      save_all data_for_simple_tree(user_class)
      tops = user_class.call_view(:my_category, 'top')
      tops.size.should == 1
      childs = user_class.call_view(:parent_categories, 'top')
      childs.size.should == 2
    end
    #test and verify with empty data
    @user_classes.each do |user_class|
      node_list = user_class.all
      borg = Borg.new(node_list, @keys)
      top_node = user_class.call_view(:my_category, 'top').first
      desc_links = borg.ify(top_node, :links)
      desc_links.should == []
    end
    #add a link and test
    @user_classes.each do |user_class|
      select_category = 'child2'
      achild = user_class.call_view(:my_category, select_category).first
      achild.my_category.should == select_category
      achild.__set_userdata_key(:links, nil)
      new_link = {"http://www.google.com" => "Google"}
      achild.links_add(new_link)
      achild.__save
      achild_from_db = user_class.call_view(:my_category, select_category).first
      achild_from_db.links.should == new_link
      node_list = user_class.all
      borg = Borg.new(node_list, @keys)
      #Borg needs to refine the data better
      top_node = user_class.call_view(:my_category, 'top').first
      desc_node_data = borg.ify(top_node, :links)
      desc_node_data.size.should == 3
      all_links = []
      desc_node_data.each do |data|
        all_links << data.values
      end
      all_links.flatten!
      all_links.compact!
      all_links.first.should == new_link
    end

  end

end


text:
#ifndef _LINUX_MSDOS_FS_H
#define _LINUX_MSDOS_FS_H

#include <linux/magic.h>

/*
 * The MS-DOS filesystem constants/structures
 */
#include <asm/byteorder.h>

#define SECTOR_SIZE	512		/* sector size (bytes) */
#define SECTOR_BITS	9		/* log2(SECTOR_SIZE) */
#define MSDOS_DPB	(MSDOS_DPS)	/* dir entries per block */
#define MSDOS_DPB_BITS	4		/* log2(MSDOS_DPB) */
#define MSDOS_DPS	(SECTOR_SIZE / sizeof(struct msdos_dir_entry))
#define MSDOS_DPS_BITS	4		/* log2(MSDOS_DPS) */
#define CF_LE_W(v)	le16_to_cpu(v)
#define CF_LE_L(v)	le32_to_cpu(v)
#define CT_LE_W(v)	cpu_to_le16(v)
#define CT_LE_L(v)	cpu_to_le32(v)

#define MSDOS_ROOT_INO	1	/* == MINIX_ROOT_INO */
#define MSDOS_DIR_BITS	5	/* log2(sizeof(struct msdos_dir_entry)) */

/* directory limit */
#define FAT_MAX_DIR_ENTRIES	(65536)
#define FAT_MAX_DIR_SIZE	(FAT_MAX_DIR_ENTRIES << MSDOS_DIR_BITS)

#define ATTR_NONE	0	/* no attribute bits */
#define ATTR_RO		1	/* read-only */
#define ATTR_HIDDEN	2	/* hidden */
#define ATTR_SYS	4	/* system */
#define ATTR_VOLUME	8	/* volume label */
#define ATTR_DIR	16	/* directory */
#define ATTR_ARCH	32	/* archived */

/* attribute bits that are copied "as is" */
#define ATTR_UNUSED	(ATTR_VOLUME | ATTR_ARCH | ATTR_SYS | ATTR_HIDDEN)
/* bits that are used by the Windows 95/Windows NT extended FAT */
#define ATTR_EXT	(ATTR_RO | ATTR_HIDDEN | ATTR_SYS | ATTR_VOLUME)

#define CASE_LOWER_BASE	8	/* base is lower case */
#define CASE_LOWER_EXT	16	/* extension is lower case */

#define DELETED_FLAG	0xe5	/* marks file as deleted when in name[0] */
#define IS_FREE(n)	(!*(n) || *(n) == DELETED_FLAG)

/* valid file mode bits */
#define MSDOS_VALID_MODE (S_IFREG | S_IFDIR | S_IRWXU | S_IRWXG | S_IRWXO)
/* Convert attribute bits and a mask to the UNIX mode. */
#define MSDOS_MKMODE(a, m) (m & (a & ATTR_RO ? S_IRUGO|S_IXUGO : S_IRWXUGO))

#define MSDOS_NAME	11	/* maximum name length */
#define MSDOS_LONGNAME	256	/* maximum name length */
#define MSDOS_SLOTS	21	/* max # of slots for short and long names */
#define MSDOS_DOT	".          "	/* ".", padded to MSDOS_NAME chars */
#define MSDOS_DOTDOT	"..         "	/* "..", padded to MSDOS_NAME chars */

/* media of boot sector */
#define FAT_VALID_MEDIA(x)	((0xF8 <= (x) && (x) <= 0xFF) || (x) == 0xF0)
#define FAT_FIRST_ENT(s, x)	((MSDOS_SB(s)->fat_bits == 32 ? 0x0FFFFF00 : \
	MSDOS_SB(s)->fat_bits == 16 ? 0xFF00 : 0xF00) | (x))

/* start of data cluster's entry (number of reserved clusters) */
#define FAT_START_ENT	2

/* maximum number of clusters */
#define MAX_FAT12	0xFF4
#define MAX_FAT16	0xFFF4
#define MAX_FAT32	0x0FFFFFF6
#define MAX_FAT(s)	(MSDOS_SB(s)->fat_bits == 32 ? MAX_FAT32 : \
	MSDOS_SB(s)->fat_bits == 16 ? MAX_FAT16 : MAX_FAT12)

/* bad cluster mark */
#define BAD_FAT12	0xFF7
#define BAD_FAT16	0xFFF7
#define BAD_FAT32	0x0FFFFFF7

/* standard EOF */
#define EOF_FAT12	0xFFF
#define EOF_FAT16	0xFFFF
#define EOF_FAT32	0x0FFFFFFF

#define FAT_ENT_FREE	(0)
#define FAT_ENT_BAD	(BAD_FAT32)
#define FAT_ENT_EOF	(EOF_FAT32)

#define FAT_FSINFO_SIG1	0x41615252
#define FAT_FSINFO_SIG2	0x61417272
#define IS_FSINFO(x)	(le32_to_cpu((x)->signature1) == FAT_FSINFO_SIG1 \
			 && le32_to_cpu((x)->signature2) == FAT_FSINFO_SIG2)

/*
 * ioctl commands
 */
#define VFAT_IOCTL_READDIR_BOTH		_IOR('r', 1, struct dirent [2])
#define VFAT_IOCTL_READDIR_SHORT	_IOR('r', 2, struct dirent [2])
/* <linux/videotext.h> has used 0x72 ('r') in collision, so skip a few */
#define FAT_IOCTL_GET_ATTRIBUTES	_IOR('r', 0x10, __u32)
#define FAT_IOCTL_SET_ATTRIBUTES	_IOW('r', 0x11, __u32)

/*
 * vfat shortname flags
 */
#define VFAT_SFN_DISPLAY_LOWER	0x0001 /* convert to lowercase for display */
#define VFAT_SFN_DISPLAY_WIN95	0x0002 /* emulate win95 rule for display */
#define VFAT_SFN_DISPLAY_WINNT	0x0004 /* emulate winnt rule for display */
#define VFAT_SFN_CREATE_WIN95	0x0100 /* emulate win95 rule for create */
#define VFAT_SFN_CREATE_WINNT	0x0200 /* emulate winnt rule for create */

struct fat_boot_sector {
	__u8	ignored[3];	/* Boot strap short or near jump */
	__u8	system_id[8];	/* Name - can be used to special case
				   partition manager volumes */
	__u8	sector_size[2];	/* bytes per logical sector */
	__u8	sec_per_clus;	/* sectors/cluster */
	__le16	reserved;	/* reserved sectors */
	__u8	fats;		/* number of FATs */
	__u8	dir_entries[2];	/* root directory entries */
	__u8	sectors[2];	/* number of sectors */
	__u8	media;		/* media code */
	__le16	fat_length;	/* sectors/FAT */
	__le16	secs_track;	/* sectors per track */
	__le16	heads;		/* number of heads */
	__le32	hidden;		/* hidden sectors (unused) */
	__le32	total_sect;	/* number of sectors (if sectors == 0) */

	/* The following fields are only used by FAT32 */
	__le32	fat32_length;	/* sectors/FAT */
	__le16	flags;		/* bit 8: fat mirroring, low 4: active fat */
	__u8	version[2];	/* major, minor filesystem version */
	__le32	root_cluster;	/* first cluster in root directory */
	__le16	info_sector;	/* filesystem info sector */
	__le16	backup_boot;	/* backup boot sector */
	__le16	reserved2[6];	/* Unused */
};

struct fat_boot_fsinfo {
	__le32   signature1;	/* 0x41615252L */
	__le32   reserved1[120];	/* Nothing as far as I can tell */
	__le32   signature2;	/* 0x61417272L */
	__le32   free_clusters;	/* Free cluster count.  -1 if unknown */
	__le32   next_cluster;	/* Most recently allocated cluster */
	__le32   reserved2[4];
};

struct msdos_dir_entry {
	__u8	name[8],ext[3];	/* name and extension */
	__u8	attr;		/* attribute bits */
	__u8    lcase;		/* Case for base and extension */
	__u8	ctime_cs;	/* Creation time, centiseconds (0-199) */
	__le16	ctime;		/* Creation time */
	__le16	cdate;		/* Creation date */
	__le16	adate;		/* Last access date */
	__le16	starthi;	/* High 16 bits of cluster in FAT32 */
	__le16	time,date,start;/* time, date and first cluster */
	__le32	size;		/* file size (in bytes) */
};

/* Up to 13 characters of the name */
struct msdos_dir_slot {
	__u8    id;		/* sequence number for slot */
	__u8    name0_4[10];	/* first 5 characters in name */
	__u8    attr;		/* attribute byte */
	__u8    reserved;	/* always 0 */
	__u8    alias_checksum;	/* checksum for 8.3 alias */
	__u8    name5_10[12];	/* 6 more characters in name */
	__le16   start;		/* starting cluster number, 0 in long slots */
	__u8    name11_12[4];	/* last 2 characters in name */
};

struct fat_slot_info {
	loff_t i_pos;		/* on-disk position of directory entry */
	loff_t slot_off;	/* offset for slot or de start */
	int nr_slots;		/* number of slots + 1(de) in filename */
	struct msdos_dir_entry *de;
	struct buffer_head *bh;
};

#ifdef __KERNEL__

#include <linux/buffer_head.h>
#include <linux/string.h>
#include <linux/nls.h>
#include <linux/fs.h>
#include <linux/mutex.h>

struct fat_mount_options {
	uid_t fs_uid;
	gid_t fs_gid;
	unsigned short fs_fmask;
	unsigned short fs_dmask;
	unsigned short codepage;  /* Codepage for shortname conversions */
	char *iocharset;          /* Charset used for filename input/display */
	unsigned short shortname; /* flags for shortname display/create rule */
	unsigned char name_check; /* r = relaxed, n = normal, s = strict */
	unsigned quiet:1,         /* set = fake successful chmods and chowns */
		 showexec:1,      /* set = only set x bit for com/exe/bat */
		 sys_immutable:1, /* set = system files are immutable */
		 dotsOK:1,        /* set = hidden and system files are named '.filename' */
		 isvfat:1,        /* 0=no vfat long filename support, 1=vfat support */
		 utf8:1,	  /* Use of UTF-8 character set (Default) */
		 unicode_xlate:1, /* create escape sequences for unhandled Unicode */
		 numtail:1,       /* Does first alias have a numeric '~1' type tail? */
		 atari:1,         /* Use Atari GEMDOS variation of MS-DOS fs */
		 flush:1,	  /* write things quickly */
		 nocase:1,	  /* Does this need case conversion? 0=need case conversion*/
		 usefree:1;	  /* Use free_clusters for FAT32 */
};

#define FAT_HASH_BITS	8
#define FAT_HASH_SIZE	(1UL << FAT_HASH_BITS)
#define FAT_HASH_MASK	(FAT_HASH_SIZE-1)

/*
 * MS-DOS file system in-core superblock data
 */
struct msdos_sb_info {
	unsigned short sec_per_clus; /* sectors/cluster */
	unsigned short cluster_bits; /* log2(cluster_size) */
	unsigned int cluster_size;   /* cluster size */
	unsigned char fats,fat_bits; /* number of FATs, FAT bits (12 or 16) */
	unsigned short fat_start;
	unsigned long fat_length;    /* FAT start & length (sec.) */
	unsigned long dir_start;
	unsigned short dir_entries;  /* root dir start & entries */
	unsigned long data_start;    /* first data sector */
	unsigned long max_cluster;   /* maximum cluster number */
	unsigned long root_cluster;  /* first cluster of the root directory */
	unsigned long fsinfo_sector; /* sector number of FAT32 fsinfo */
	struct mutex fat_lock;
	unsigned int prev_free;      /* previously allocated cluster number */
	unsigned int free_clusters;  /* -1 if undefined */
	struct fat_mount_options options;
	struct nls_table *nls_disk;  /* Codepage used on disk */
	struct nls_table *nls_io;    /* Charset used for input and display */
	const void *dir_ops;		     /* Opaque; default directory operations */
	int dir_per_block;	     /* dir entries per block */
	int dir_per_block_bits;	     /* log2(dir_per_block) */

	int fatent_shift;
	struct fatent_operations *fatent_ops;

	spinlock_t inode_hash_lock;
	struct hlist_head inode_hashtable[FAT_HASH_SIZE];
};

#define FAT_CACHE_VALID	0	/* special case for valid cache */

/*
 * MS-DOS file system inode data in memory
 */
struct msdos_inode_info {
	spinlock_t cache_lru_lock;
	struct list_head cache_lru;
	int nr_caches;
	/* for avoiding the race between fat_free() and fat_get_cluster() */
	unsigned int cache_valid_id;

	loff_t mmu_private;
	int i_start;		/* first cluster or 0 */
	int i_logstart;		/* logical first cluster */
	int i_attrs;		/* unused attribute bits */
	loff_t i_pos;		/* on-disk position of directory entry or 0 */
	struct hlist_node i_fat_hash;	/* hash by i_location */
	struct inode vfs_inode;
};

static inline struct msdos_sb_info *MSDOS_SB(struct super_block *sb)
{
	return sb->s_fs_info;
}

static inline struct msdos_inode_info *MSDOS_I(struct inode *inode)
{
	return container_of(inode, struct msdos_inode_info, vfs_inode);
}

/* Return the FAT attribute byte for this inode */
static inline u8 fat_attr(struct inode *inode)
{
	return ((inode->i_mode & S_IWUGO) ? ATTR_NONE : ATTR_RO) |
		(S_ISDIR(inode->i_mode) ? ATTR_DIR : ATTR_NONE) |
		MSDOS_I(inode)->i_attrs;
}

static inline unsigned char fat_checksum(const __u8 *name)
{
	unsigned char s = name[0];
	s = (s<<7) + (s>>1) + name[1];	s = (s<<7) + (s>>1) + name[2];
	s = (s<<7) + (s>>1) + name[3];	s = (s<<7) + (s>>1) + name[4];
	s = (s<<7) + (s>>1) + name[5];	s = (s<<7) + (s>>1) + name[6];
	s = (s<<7) + (s>>1) + name[7];	s = (s<<7) + (s>>1) + name[8];
	s = (s<<7) + (s>>1) + name[9];	s = (s<<7) + (s>>1) + name[10];
	return s;
}

static inline sector_t fat_clus_to_blknr(struct msdos_sb_info *sbi, int clus)
{
	return ((sector_t)clus - FAT_START_ENT) * sbi->sec_per_clus
		+ sbi->data_start;
}

static inline void fat16_towchar(wchar_t *dst, const __u8 *src, size_t len)
{
#ifdef __BIG_ENDIAN
	while (len--) {
		*dst++ = src[0] | (src[1] << 8);
		src += 2;
	}
#else
	memcpy(dst, src, len * 2);
#endif
}

static inline void fatwchar_to16(__u8 *dst, const wchar_t *src, size_t len)
{
#ifdef __BIG_ENDIAN
	while (len--) {
		dst[0] = *src & 0x00FF;
		dst[1] = (*src & 0xFF00) >> 8;
		dst += 2;
		src++;
	}
#else
	memcpy(dst, src, len * 2);
#endif
}

/* fat/cache.c */
extern void fat_cache_inval_inode(struct inode *inode);
extern int fat_get_cluster(struct inode *inode, int cluster,
			   int *fclus, int *dclus);
extern int fat_bmap(struct inode *inode, sector_t sector, sector_t *phys,
		    unsigned long *mapped_blocks);

/* fat/dir.c */
extern const struct file_operations fat_dir_operations;
extern int fat_search_long(struct inode *inode, const unsigned char *name,
			   int name_len, struct fat_slot_info *sinfo);
extern int fat_dir_empty(struct inode *dir);
extern int fat_subdirs(struct inode *dir);
extern int fat_scan(struct inode *dir, const unsigned char *name,
		    struct fat_slot_info *sinfo);
extern int fat_get_dotdot_entry(struct inode *dir, struct buffer_head **bh,
				struct msdos_dir_entry **de, loff_t *i_pos);
extern int fat_alloc_new_dir(struct inode *dir, struct timespec *ts);
extern int fat_add_entries(struct inode *dir, void *slots, int nr_slots,
			   struct fat_slot_info *sinfo);
extern int fat_remove_entries(struct inode *dir, struct fat_slot_info *sinfo);

/* fat/fatent.c */
struct fat_entry {
	int entry;
	union {
		u8 *ent12_p[2];
		__le16 *ent16_p;
		__le32 *ent32_p;
	} u;
	int nr_bhs;
	struct buffer_head *bhs[2];
};

static inline void fatent_init(struct fat_entry *fatent)
{
	fatent->nr_bhs = 0;
	fatent->entry = 0;
	fatent->u.ent32_p = NULL;
	fatent->bhs[0] = fatent->bhs[1] = NULL;
}

static inline void fatent_set_entry(struct fat_entry *fatent, int entry)
{
	fatent->entry = entry;
	fatent->u.ent32_p = NULL;
}

static inline void fatent_brelse(struct fat_entry *fatent)
{
	int i;
	fatent->u.ent32_p = NULL;
	for (i = 0; i < fatent->nr_bhs; i++)
		brelse(fatent->bhs[i]);
	fatent->nr_bhs = 0;
	fatent->bhs[0] = fatent->bhs[1] = NULL;
}

extern void fat_ent_access_init(struct super_block *sb);
extern int fat_ent_read(struct inode *inode, struct fat_entry *fatent,
			int entry);
extern int fat_ent_write(struct inode *inode, struct fat_entry *fatent,
			 int new, int wait);
extern int fat_alloc_clusters(struct inode *inode, int *cluster,
			      int nr_cluster);
extern int fat_free_clusters(struct inode *inode, int cluster);
extern int fat_count_free_clusters(struct super_block *sb);

/* fat/file.c */
extern int fat_generic_ioctl(struct inode *inode, struct file *filp,
			     unsigned int cmd, unsigned long arg);
extern const struct file_operations fat_file_operations;
extern const struct inode_operations fat_file_inode_operations;
extern int fat_notify_change(struct dentry * dentry, struct iattr * attr);
extern void fat_truncate(struct inode *inode);
extern int fat_getattr(struct vfsmount *mnt, struct dentry *dentry,
		       struct kstat *stat);

/* fat/inode.c */
extern void fat_attach(struct inode *inode, loff_t i_pos);
extern void fat_detach(struct inode *inode);
extern struct inode *fat_iget(struct super_block *sb, loff_t i_pos);
extern struct inode *fat_build_inode(struct super_block *sb,
			struct msdos_dir_entry *de, loff_t i_pos);
extern int fat_sync_inode(struct inode *inode);
extern int fat_fill_super(struct super_block *sb, void *data, int silent,
			const struct inode_operations *fs_dir_inode_ops, int isvfat);

extern int fat_flush_inodes(struct super_block *sb, struct inode *i1,
		            struct inode *i2);
/* fat/misc.c */
extern void fat_fs_panic(struct super_block *s, const char *fmt, ...);
extern void fat_clusters_flush(struct super_block *sb);
extern int fat_chain_add(struct inode *inode, int new_dclus, int nr_cluster);
extern int date_dos2unix(unsigned short time, unsigned short date);
extern void fat_date_unix2dos(int unix_date, __le16 *time, __le16 *date);
extern int fat_sync_bhs(struct buffer_head **bhs, int nr_bhs);

int fat_cache_init(void);
void fat_cache_destroy(void);

#endif /* __KERNEL__ */

#endif

redpajama_set_name: RedPajamaGithub


text:
{% raw %}
  remove_circle{{ label }}: {{ name }}
{% endraw %}


text:
var events = require('events'),
    util = require('util');

/*
 * Main Button constructor
 * Process options
 * Tell the board to set it up
 */
var Button = function (options) {
  if (!options || !options.board) throw new Error('Must supply required options to Button');
  this.board = options.board;
  this.pin = options.pin || 13;
  this.down = false;
  this.board.pinMode(this.pin, 'in');
  var self = this;
  setInterval(function () {
    self.board.digitalRead(self.pin);
  }, 50);
  this.board.on('data', function (m) {
    m = m.slice(0, -1).split('::');
    if (m.length > 1 && m[0] == self.pin) {
      // 1 is up
      // 0 is down
      if (m[1] == '1' && self.down) {
        self.down = false;
        self.emit('up');
      }
      if (m[1] == '0' && !self.down) {
        self.down = true;
        self.emit('down');
      }
    }
  });
}

/*
 * EventEmitter, I choose you!
 */
util.inherits(Button, events.EventEmitter);

module.exports = Button;


text:
var keyMirror = require('keymirror');

module.exports = {

    ActionTypes: keyMirror({
        CREATE_RESOURCE: null,
        RECIEVE_RAW_CREATED_RESOURCE: null,
    }),

    PayloadSources: keyMirror({
        SERVER_ACTION: null,
        VIEW_ACTION: null,
    })

};


text:
using System;
using System.Globalization;

namespace Avalonia.Data.Converters
{
    /// <summary>
    /// A value converter which calls <see cref="string.Format(string, object)"/>
    /// </summary>
    public class StringFormatValueConverter : IValueConverter
    {
        /// <summary>
        /// Initializes a new instance of the <see cref="StringFormatValueConverter"/> class.
        /// </summary>
        /// <param name="format">The format string.</param>
        /// <param name="inner">
        /// An optional inner converter to be called before the format takes place.
        /// </param>
        public StringFormatValueConverter(string format, IValueConverter? inner)
        {
            Format = format ?? throw new ArgumentNullException(nameof(format));
            Inner = inner;
        }

        /// <summary>
        /// Gets an inner value converter which will be called before the string format takes place.
        /// </summary>
        public IValueConverter? Inner { get; }

        /// <summary>
        /// Gets the format string.
        /// </summary>
        public string Format { get; }

        /// <inheritdoc/>
        public object? Convert(object? value, Type targetType, object? parameter, CultureInfo culture)
        {
            value = Inner?.Convert(value, targetType, parameter, culture) ?? value;
            return string.Format(culture, Format, value);
        }

        /// <inheritdoc/>
        public object? ConvertBack(object? value, Type targetType, object? parameter, CultureInfo culture)
        {
            throw new NotSupportedException("Two way bindings are not supported with a string format");
        }
    }
}


text:
<?php
require_once dirname(__FILE__).'/config.php';
require_once dirname(__FILE__).'/../../uploadcare/lib/5.2/Uploadcare.php';

class ApiTest extends PHPUnit_Framework_TestCase
{
  /**
   * Setup test
   * @return void
   */
  public function setUp() {
  }

  /**
   * Tear down
   * @return void
   */
  public function tearDown() {
  }

  /**
   * Test for constants not to be misspelled
   */
  public function testConstantValid()
  {
    $this->assertTrue(API_TYPE_RAW == 'raw');
    $this->assertTrue(API_TYPE_ACCOUNT == 'account');
    $this->assertTrue(API_TYPE_STORE == 'store');
    $this->assertTrue(API_TYPE_FILES == 'files');
    $this->assertTrue(API_TYPE_FILE == 'file');

    $this->assertTrue(REQUEST_TYPE_POST == 'post');
    $this->assertTrue(REQUEST_TYPE_PUT == 'put');
    $this->assertTrue(REQUEST_TYPE_DELETE == 'delete');
    $this->assertTrue(REQUEST_TYPE_GET == 'get');
    $this->assertTrue(REQUEST_TYPE_HEAD == 'head');
    $this->assertTrue(REQUEST_TYPE_OPTIONS == 'options');

    $this->assertTrue(UC_PARAM_FILE_ID == 'file_id');
  }

  /**
   * This is just some simple test to check that classes are right.
   */
  public function testChildObjectsValid()
  {
    $api = new Uploadcare_Api(UC_PUBLIC_KEY, UC_SECRET_KEY);
    $this->assertTrue(get_class($api->widget) == 'Uploadcare_Widget');
    $this->assertTrue(get_class($api->uploader) == 'Uploadcare_Uploader');
  }

  /**
   * Is public key valid?
   */
  public function testPublicKeyValid()
  {
    $api = new Uploadcare_Api(UC_PUBLIC_KEY, UC_SECRET_KEY);
    $this->assertTrue($api->getPublicKey() == 'demopublickey', 'This is true');
  }

  /**
   * Test that getFilesList mehtod returns array
   * and each item of array is an object of Uploadcare_File class
   */
  public function testFileList()
  {
    $api = new Uploadcare_Api(UC_PUBLIC_KEY, UC_SECRET_KEY);
    $files = $api->getFileList();

    $this->assertTrue(is_array($files));
    foreach ($files as $file) {
      $this->assertTrue(get_class($file) == 'Uploadcare_File');
    }
  }

  /**
   * Test requests for exceptions to "raw" url
   */
  public function testRequestsRaw()
  {
    $api = new Uploadcare_Api(UC_PUBLIC_KEY, UC_SECRET_KEY);

    // this are request to https://api.uploadcare.com/ url.
    // no exceptions should be thrown
    try {
      $result = $api->request('GET', '/');
      $api->request('HEAD', '/');
      $api->request('OPTIONS', '/');
    } catch (Exception $e) {
      $this->fail('An unexpected exception thrown');
    }

    // let's check we have a "resources"
    $this->assertTrue(is_array($result->resources));

    // this are requests to https://api.uploadcare.com/ url.
    // But this requests are now allowed but this url and we must have an exception
    try {
      $api->request('POST', '/');
      $this->fail('We must get an exception but everything worked fine!');
    } catch (Exception $e) {
    }

    try {
      $api->request('PUT', '/');
      $this->fail('We must get an exception but everything worked fine!');
    } catch (Exception $e) {
    }

    try {
      $api->request('DELETE', '/');
      $this->fail('We must get an exception but everything worked fine!');
    } catch (Exception $e) {
    }
  }

  /**
   * Test requests to "account" url
   */
  public function testRequestsAccount()
  {
    $api = new Uploadcare_Api(UC_PUBLIC_KEY, UC_SECRET_KEY);

    // this are request to https://api.uploadcare.com/account/ url.
    // no exceptions should be thrown
    try {
      $result = $api->request('GET', '/account/');
      $api->request('HEAD', '/account/');
      $api->request('OPTIONS', '/account/');
    } catch (Exception $e) {
      $this->fail('An unexpected exception thrown');
    }

    // we have some data, let's check it
    $this->assertEquals($result->username, 'demo');
    $this->assertEquals($result->pub_key, 'demopublickey');
    $this->assertEquals($result->email, 'demo@uploadcare.com');

    // this are requests to https://api.uploadcare.com/account/ url.
    // But this requests are now allowed but this url and we must have an exception
    try {
      $api->request('POST', '/account/');
      $this->fail('We must get an exception but everything worked fine!');
    } catch (Exception $e) {
    }

    try {
      $api->request('PUT', '/account/');
      $this->fail('We must get an exception but everything worked fine!');
    } catch (Exception $e) {
    }

    try {
      $api->request('DELETE', '/account/');
      $this->fail('We must get an exception but everything worked fine!');
    } catch (Exception $e) {
    }
  }

  /**
   * Test request to "files"
   */
  public function testRequestsFiles()
  {
    $api = new Uploadcare_Api(UC_PUBLIC_KEY, UC_SECRET_KEY);

    // this are request to https://api.uploadcare.com/files/ url.
    // no exceptions should be thrown
    try {
      $result = $api->request('GET', '/files/');
      $api->request('HEAD', '/files/');
      $api->request('OPTIONS', '/files/');
    } catch (Exception $e) {
      $this->fail('An unexpected exception thrown');
    }

    // let's check we have an array of raw file data
    $this->assertTrue(is_array($result->results));
    $this->assertGreaterThan(0, count($result->results));
    $file_raw = (array)$result->results[0];
    $this->assertArrayHasKey('size', $file_raw);
    $this->assertArrayHasKey('upload_date', $file_raw);
    $this->assertArrayHasKey('is_image', $file_raw);
    $this->assertArrayHasKey('file_id', $file_raw);
    $this->assertArrayHasKey('original_filename', $file_raw);
    $this->assertArrayHasKey('mime_type', $file_raw);

    // this are requests to https://api.uploadcare.com/files/ url.
    // But this requests are now allowed but this url and we must have an exception
    try {
      $api->request('POST', '/files/');
      $this->fail('We must get an exception but everything worked fine!');
    } catch (Exception $e) {
    }

    try {
      $api->request('PUT', '/files/');
      $this->fail('We must get an exception but everything worked fine!');
    } catch (Exception $e) {
    }

    try {
      $api->request('DELETE', '/files/');
      $this->fail('We must get an exception but everything worked fine!');
    } catch (Exception $e) {
    }
  }

  /**
   * Let's check the file operations and check for correct urls
   */
  public function testFile()
  {
    $api = new Uploadcare_Api(UC_PUBLIC_KEY, UC_SECRET_KEY);
    $file = $api->getFile('4bd3a897-f489-4b9f-b643-961b1c9f657e');

    $this->assertEquals(get_class($file), 'Uploadcare_File');

    $this->assertEquals($file->getUrl(), 'https://ucarecdn.com/4bd3a897-f489-4b9f-b643-961b1c9f657e/');
    $this->assertEquals($file->resize(400, 400)->getUrl(), 'https://ucarecdn.com/4bd3a897-f489-4b9f-b643-961b1c9f657e/-/resize/400x400/');
    $this->assertEquals($file->resize(400, false)->getUrl(), 'https://ucarecdn.com/4bd3a897-f489-4b9f-b643-961b1c9f657e/-/resize/400x/');
    $this->assertEquals($file->resize(false, 400)->getUrl(), 'https://ucarecdn.com/4bd3a897-f489-4b9f-b643-961b1c9f657e/-/resize/x400/');

    $this->assertEquals($file->crop(400, 400)->getUrl(), 'https://ucarecdn.com/4bd3a897-f489-4b9f-b643-961b1c9f657e/-/crop/400x400/');
    $this->assertEquals($file->crop(400, 400, true)->getUrl(), 'https://ucarecdn.com/4bd3a897-f489-4b9f-b643-961b1c9f657e/-/crop/400x400/center/');
    $this->assertEquals($file->crop(400, 400, true, 'ff0000')->getUrl(), 'https://ucarecdn.com/4bd3a897-f489-4b9f-b643-961b1c9f657e/-/crop/400x400/center/ff0000/');
    $this->assertEquals($file->crop(400, 400, false, 'ff0000')->getUrl(), 'https://ucarecdn.com/4bd3a897-f489-4b9f-b643-961b1c9f657e/-/crop/400x400/ff0000/');

    $this->assertEquals($file->scaleCrop(400, 400)->getUrl(), 'https://ucarecdn.com/4bd3a897-f489-4b9f-b643-961b1c9f657e/-/scale_crop/400x400/');
    $this->assertEquals($file->scaleCrop(400, 400, true)->getUrl(), 'https://ucarecdn.com/4bd3a897-f489-4b9f-b643-961b1c9f657e/-/scale_crop/400x400/center/');

    $this->assertEquals($file->effect('flip')->getUrl(), 'https://ucarecdn.com/4bd3a897-f489-4b9f-b643-961b1c9f657e/-/effect/flip/');
    $this->assertEquals($file->effect('grayscale')->getUrl(), 'https://ucarecdn.com/4bd3a897-f489-4b9f-b643-961b1c9f657e/-/effect/grayscale/');
    $this->assertEquals($file->effect('invert')->getUrl(), 'https://ucarecdn.com/4bd3a897-f489-4b9f-b643-961b1c9f657e/-/effect/invert/');
    $this->assertEquals($file->effect('mirror')->getUrl(), 'https://ucarecdn.com/4bd3a897-f489-4b9f-b643-961b1c9f657e/-/effect/mirror/');

    $this->assertEquals($file->effect('flip')->effect('mirror')->getUrl(), 'https://ucarecdn.com/4bd3a897-f489-4b9f-b643-961b1c9f657e/-/effect/flip/-/effect/mirror/');
    $this->assertEquals($file->effect('mirror')->effect('flip')->getUrl(), 'https://ucarecdn.com/4bd3a897-f489-4b9f-b643-961b1c9f657e/-/effect/mirror/-/effect/flip/');

    $this->assertEquals($file->resize(400, 400)->scaleCrop(200, 200, true)->effect('mirror')->getUrl(), 'https://ucarecdn.com/4bd3a897-f489-4b9f-b643-961b1c9f657e/-/resize/400x400/-/scale_crop/200x200/center/-/effect/mirror/');
  }

  /**
   * Test uploading and deleting
   */
  public function testUploadAndDelete()
  {
    $api = new Uploadcare_Api(UC_PUBLIC_KEY, UC_SECRET_KEY);

    // upload form url
    try {
      $file = $api->uploader->fromUrl('http://www.baysflowers.co.nz/Images/tangerine-delight.jpg');
    } catch (Exception $e) {
      $this->fail('We get an unexpected exception trying to upload from url '.$e->getMessage());
    }
    $this->assertEquals(get_class($file), 'Uploadcare_File');
    try {
      $file->store();
    } catch (Exception $e) {
      $this->fail('We get an unexpected exception trying to store uploaded file from url'.$e->getMessage());
    }

    // upload from path
    try {
      $file = $api->uploader->fromPath(dirname(__FILE__).'/test.jpg');
    } catch (Exception $e) {
      $this->fail('We get an unexpected exception trying to upload from path');
    }
    try {
      $file->store();
    } catch (Exception $e) {
      $this->fail('We get an unexpected exception trying to store uploaded file from path'.$e->getMessage());
    }

    // upload from resource
    try {
      $fp = fopen(dirname(__FILE__).'/test.jpg', 'r');
      $file = $api->uploader->fromResource($fp);
    } catch (Exception $e) {
      $this->fail('We get an unexpected exception trying to upload from resource'.$e->getMessage());
    }
    try {
      $file->store();
    } catch (Exception $e) {
      $this->fail('We get an unexpected exception trying to store uploaded file from resource'.$e->getMessage());
    }

    // upload from raw
    try {
      $content = "This is some text I want to upload";
      $file = $api->uploader->fromContent($content, 'text/plain');
    } catch (Exception $e) {
      $this->fail('We get an unexpected exception trying to upload from contents'.$e->getMessage());
    }
    try {
      $file->store();
    } catch (Exception $e) {
      $this->fail('We get an unexpected exception trying to store uploaded file from contents'.$e->getMessage());
    }

    $text = file_get_contents($file->getUrl());
    $this->assertEquals($text, "This is some text I want to upload");

    // test file delete
    try {
      $file->delete();
    } catch (Exception $e) {
      $this->fail('We get an unexpected exception trying to delete file'.$e->getMessage());
    }
  }
}


text:
class TranslationForMerryCms < ActiveRecord::Migration
  def self.up
    Article.create_translation_table! :title => :string, :intro => :text, :content => :text, :permalink => :string
    Category.create_translation_table! :name => :string, :permalink => :string
  end

  def self.down
    Article.drop_translation_table!
    Category.drop_translation_table!
  end
end


text:
package org.opencb.datastore.mongodb;

import org.junit.After;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;

/**
 * Created by imedina on 27/03/14.
 */
public class MongoDataStoreManagerTest {

    private MongoDataStoreManager mongoDataStoreManager;
    private MongoDataStore mongoDataStore;

    @Before
    public void setUp() throws Exception {
        mongoDataStoreManager = new MongoDataStoreManager("127.0.0.1", 27017);
        mongoDataStore = mongoDataStoreManager.get("test", MongoDBConfiguration.builder().init().build());
    }

    @After
    public void tearDown() throws Exception {
        mongoDataStoreManager.close("test");
    }

    @Test
    public void testGet() throws Exception {
        Assert.assertTrue("MongoDB check connection to 'test' database failed", mongoDataStore.test());
    }
}


text:
const Gio = imports.gi.Gio;
const Lang = imports.lang;
const St = imports.gi.St;
const NMC = imports.gi.NMClient;
const NetworkManager = imports.gi.NetworkManager;
const Main = imports.ui.main;
const Mainloop = imports.mainloop;
const Panel = imports.ui.panel;
const PanelMenu = imports.ui.panelMenu;
const PopupMenu = imports.ui.popupMenu;
const Soup = imports.gi.Soup;

let iAvailable = false; //Is internet available?
let faceHappy = "face-smile-big-symbolic"; //Happy face is internet is Up
let faceSad = "face-crying-symbolic"; //Sad face is internet is Down

let macAddr = "00:00:00:00:00:00"; //Default MAC Address
let ipAddr = "0.0.0.0"; //Default IP Address
let eipAddr = "0.0.0.0"; //Default External Ip Address
let deviceType = "unknown"; //Default device type

let iDevAct = false; //Is Internet device ACTIVE?
let deviceStateChanged = true; //Has Internet device state changed?

let macItem; // MenuItem for MAC Adress
let ipItem; // MenuItem for IP Adress
let eipItem; // MenuItem for External Ip Adress
let typeItem; // MenuItem for device type

const PopUpMenu = new Lang.Class({
  Name: 'InternetWatcher.Menu',
  Extends: PanelMenu.Button,
  _init: function() {
    this.parent(0.0, _("InternetWatcher"));

    let hbox = new St.BoxLayout({
      style_class: 'panel-status-menu-box'
    });
    this.icon = new St.Icon({
      icon_name: faceHappy,
      style_class: 'system-status-icon'
    });

    hbox.add_child(this.icon);
    this.actor.add_child(hbox);
    macItem = new PopupMenu.PopupMenuItem("MAC: " + macAddr);
    ipItem = new PopupMenu.PopupMenuItem("IP: " + ipAddr);
    eipItem = new PopupMenu.PopupMenuItem("Ext IP: " + eipAddr);
    typeItem = new PopupMenu.PopupMenuItem("Type: " + deviceType);

    this.menu.addMenuItem(typeItem);
    this.menu.addMenuItem(macItem);
    this.menu.addMenuItem(ipItem);
    this.menu.addMenuItem(eipItem);

    this.client = NMC.Client.new();
    //Check every 2 seconds for device state changed
    this._update_handler = Mainloop.timeout_add_seconds(2, Lang.bind(this,
      function() {
        if (deviceStateChanged)
          this._getDeviceData(this.client);
        if (!iAvailable) {
          this._getEIP();
          this._updateEIP();
        }
        return true;
      }));
    //Check every 30 seconds for External IP Adress changed
    this._update_handler = Mainloop.timeout_add_seconds(30, Lang.bind(
      this,
      function() {
        this._getEIP();
        this._updateEIP();
        return true;
      }));

    this._network_monitor = Gio.network_monitor_get_default();
    this._network_monitor.connect('network-changed', Lang.bind(this, this
      ._onNetworkStateChanged));
  },
  // Update External Ip Adress
  _updateEIP: function() {
    if (eipItem.label.get_text() != eipAddr) {
      if (eipAddr == "0.0.0.0") {
        iAvailable = false;
        this._updateImage();
        eipItem.label.set_text("Ext IP: 0.0.0.0");
      } else {
        iAvailable = true;
        this._updateImage();
        eipItem.label.set_text("Ext IP: " + eipAddr);
      }
    }
  },
  // network-changed
  _onNetworkStateChanged: function() {
    deviceStateChanged = true;
  },
  // Update Menu View
  _showMenu: function(show) {
    if (show)
      this.actor.show();
    else
      this.actor.hide();
  },
  // Get External Ip Adress
  _getEIP: function() {
    if (iDevAct) {
      //URL to get External IP adress and parse using Soup
      var url = "http://ipv4.icanhazip.com/";
      var _httpSession = new Soup.SessionAsync();
      Soup.Session.prototype.add_feature.call(_httpSession, new Soup.ProxyResolverDefault());
      var request = Soup.Message.new('GET', url);
      _httpSession.queue_message(request, function(_httpSession, message) {
        eipAddr = request.response_body.data;
        if (eipAddr == null) {
          eipAddr = "0.0.0.0";
        }
      });
    }
  },
  // Get Device Data
  _getDeviceData: function(client) {
    let _devices = client.get_devices();
    for (let device of _devices) {
      let ipconf = device.get_ip4_config();
      let ifc = device.get_iface();
      if (ipconf != null && device.get_state() == NetworkManager.DeviceState
        .ACTIVATED) {
        let type = this._get_device_type(device.get_device_type());
        if (type == "ETHERNET" || type == "WIFI") {
          iDevAct = true;
          deviceType = type;
          ipAddr = this._decodeIp4(device.get_ip4_config().get_addresses()[
            0].get_address());
          macAddr = device.get_hw_address();
          deviceStateChanged = false;
          break;
        } else {
          iDevAct = false;
        }
      } else {
        iDevAct = false;
      }
    }
    this._updateData();
  },
  // Update device data
  _updateData: function() {
    if (iDevAct) {
      macItem.label.set_text("MAC: " + macAddr);
      ipItem.label.set_text("IP: " + ipAddr);
      typeItem.label.set_text("Type: " + deviceType);
    } else {
      macItem.label.set_text("MAC: " + "00:00:00:00:00:00");
      ipItem.label.set_text("IP: " + "0.0.0.0");
      eipItem.label.set_text("Ext IP: " + "0.0.0.0");
      typeItem.label.set_text("Type: " + "unknown");
      iAvailable = false;
      this._updateImage();
    }
  },
  // Update Image
  _updateImage: function() {
    if (iAvailable) { //If Internet is available
      this.icon.set_icon_name(faceHappy);
    } else { //If Internet is not available
      this.icon.set_icon_name(faceSad);
    }
  },
  // Get IP v4 fromat data
  _decodeIp4: function(num) {
    num = num >>> 0;
    let array = Uint8Array(4);
    array[0] = num;
    array[1] = num >> 8;
    array[2] = num >> 16;
    array[3] = num >> 24;

    return array[0] + '.' + array[1] + '.' + array[2] + '.' + array[3];
  },
  // Get devie type
  _get_device_type: function(device) {
    switch (device) {
      case NetworkManager.DeviceType.ETHERNET:
        return "ETHERNET";
      case NetworkManager.DeviceType.WIFI:
        return "WIFI";
      default:
        return "none";
    }
  }
});

let popUpMenu;
//Init function
function init() {
  popUpMenu = new PopUpMenu;
  Main.panel.addToStatusArea('internetWatcher', popUpMenu);
}
//on enable function
function enable() {
  popUpMenu._showMenu(true);
}
//on disable function
function disable() {
  popUpMenu._showMenu(false);
}


text:
import { NgModule } from '@angular/core';
import { CommonModule } from '@angular/common';
import { FormsModule } from '@angular/forms';

import { DirectivesModule } from '../../directives/directives.module';
import { CodeEditorComponent } from './code-editor.component';

@NgModule({
  declarations: [CodeEditorComponent],
  exports: [CodeEditorComponent],
  imports: [CommonModule, FormsModule, DirectivesModule]
})
export class CodeEditorModule {}


text:
@interface UIApplication (FrankAutomation)

- (NSArray*)FEX_windows;

@end


text:
using namespace std;

StringList::StringList()
{
}

void
StringList::addString(const string &s)
{
    strings_.push_back(s);
}

void
StringList::sort()
{
    std::sort(strings_.begin(), strings_.end());
}

vector<string>
StringList::possibleCompletions(const string &prefix)
{
    auto first = lower_bound(strings_.begin(), strings_.end(), prefix);
    auto last = upper_bound(strings_.begin(), strings_.end(), prefix,
            [](const string &a, const string &b) {
                return a < b.substr(0, a.size());
            });

    return vector<string>(first, last);
}


text:
// <reference path="../typings/tsd.d.ts" />

import {ServerService} from '../../rest/server';
import {Node} from '../../rest/server';

export class HostDetailController {
    private hostList: Array<Node>;
    private host: Node;
    private id: string;
    private tabList: any;
    private activeTab: number;

    //Services that are used in this class.
    static $inject: Array<string> = [
        '$routeParams',
        'ServerService'
    ];

    constructor(private routeParamsSvc: ng.route.IRouteParamsService,
        private serverService: ServerService) {
            this.hostList = [];
            this.tabList = {
                Overview: 1,
                Configuration: 2
            }
            this.activeTab = this.tabList.Overview;
            this.id = this.routeParamsSvc['id'];
            this.serverService.getList().then((hosts: Array<any>) => {
                this.hostList = _.filter(hosts, (host) => {
                    return host.state === 2; /* Only Active host will list down in drop-down list*/
                });
                this.host = _.find(hosts, (host) => {
                    return host.nodeid === this.id;
                });
                if(this.host.roles.indexOf('OSD') > -1) {
                    this.tabList.OSDs = 3
                }
                this.host.utilizations.networkusage.updatedat = new Date(this.host.utilizations.networkusage.updatedat.replace(/-/g,"/").split('.')[0]);
            });
    }

    public setTab(newTab: number) {
        this.activeTab = newTab;
    }

    public isSet(tabNum: number) {
        return this.activeTab === tabNum;
    }

}


text:
}
#schedule .clear{ clear:both; height: 0; line-height: 0;}
#schedule .sc_wrapper{
}
#schedule .sc_menu{
	width:100%;
	height:26px;
}
#schedule .sc_menu .sc_header_cell{
	float:left;
}
#schedule .sc_menu .sc_header{
	float:left;
	height:26px;
	position:relative;
	overflow:hidden;
}
#schedule .sc_menu .sc_header .sc_time{
	text-align:center;
	border-left:solid 1px #FFF;
	background:#333;
}
#schedule .sc_menu .sc_header_cell,
#schedule .sc_data{
	float:left;
	font-weight:bold;
	color:#FFFFFF;
	background:#333;
	position:relative;
}
#schedule .sc_menu .sc_header_scroll,
#schedule .sc_data .sc_data_scroll{
	position:absolute;
	left:0;
	top:0;
}
#schedule .sc_menu .sc_header_cell,
#schedule .sc_header .sc_time,
#schedule .sc_main_scroll .sc_time{
	color:#FFFFFF;
	padding:4px 0;
	line-height:18px;
	height:18px;
	display:block;
}
#schedule .sc_header .sc_time,
#schedule .sc_main_scroll .sc_time{
	float:left;
}
#schedule .sc_main_box,
#schedule .sc_data{
	max-height:500px;
	overflow:hidden;
}
#schedule .sc_main_box{
	float:left;
	overflow-x:auto;
	overflow-y:auto;
}
#schedule .sc_main_scroll{
}
#schedule .sc_main{
	position:relative;
}
#schedule .timeline{
	position:relative;
}
#schedule .sc_Bar{
	position:absolute;
	color:#FFF;
	background:#4f93d6;
	cursor:pointer;
	z-index:10;
	box-shadow: 2px 2px 4px #333;
	-moz-box-shadow: 2px 2px 4px #333;
	-webkit-box-shadow: 2px 2px 4px #333;
}
#schedule .ui-draggable-dragging,
#schedule .ui-resizeable{
	z-index:20;
}
#schedule .sc_Bar .head{
	display:block;
	padding:6px 8px 0;
	font-size:12px;
	height:16px;
	overflow:hidden;
}
#schedule .sc_Bar .text{
	display:block;
	padding:5px 15px 0;
	font-weight:bold;
	height:18px;
	overflow:hidden;
}
#schedule .timeline,
#schedule .sc_main .tb{
	border-bottom:solid 2px #666;
}
#schedule .sc_data .timeline{
	overflow:hidden;
}
#schedule .sc_data .timeline span{
	padding:10px;
	display:block;
}
#schedule .sc_data .timeline span.photo{
	float:left;
	width:36px;
	height:36px;
	padding:10px 0 10px 10px;
}
#schedule .sc_data .timeline span.title{
	float:left;
	padding:10px 0 10px 10px;
	width:92px;
}
#schedule .sc_main_scroll .sc_main{
}
#schedule .sc_main_scroll .sc_main .tl{
	float:left;
	height:100%;
	border-right:solid 1px #CCC;
}
#schedule .sc_main_scroll .sc_main .tl:hover{
	background:#F0F0F0;
}


text:
import { Component, OnInit } from '@angular/core';

@Component({
  selector: 'app-footer',
  templateUrl: './footer.component.html',
  styleUrls: ['./footer.component.scss']
})

export class FooterComponent {
  public links: any[] = [
    {
      name: 'GitHub',
      url: 'https://github.com/Libertual/api-client',
      icon: 'github',
    },
    {
      name: 'Issues',
      url: 'https://github.com/Libertual/api-client/issues',
      icon: 'bug',
    },
    {
      name: 'Tecnual',
      url: 'https://github.com/tecnual',
      icon: 'user',
    },
  ];

}


text:
package paw.io;

public class ConsoleOutputWriter {

    public void writeLine(String output){
        System.out.println(output);
    }

    public void writeLine(String format, Object... params){
        System.out.println(String.format(format, params));
    }

}


text:
// -*- c++ -*-
// Generated by gmmproc 2.47.3.1 -- DO NOT MODIFY!
#ifndef _ATKMM_DOCUMENT_P_H
#define _ATKMM_DOCUMENT_P_H

#include <glibmm/private/object_p.h>

#include <glibmm/private/interface_p.h>

namespace Atk
{

class Document_Class : public Glib::Interface_Class
{
public:
  typedef Document CppObjectType;
  typedef AtkDocument BaseObjectType;
  typedef AtkDocumentIface BaseClassType;
  typedef Glib::Interface_Class CppClassParent;

  friend class Document;

  const Glib::Interface_Class& init();

  static void iface_init_function(void* g_iface, void* iface_data);

  static Glib::ObjectBase* wrap_new(GObject*);

protected:

  //Callbacks (default signal handlers):
  //These will call the *_impl member methods, which will then call the existing default signal callbacks, if any.
  //You could prevent the original default signal handlers being called by overriding the *_impl method.

  //Callbacks (virtual functions):
  static const gchar* get_document_type_vfunc_callback(AtkDocument* self);
  static gpointer get_document_vfunc_callback(AtkDocument* self);
};

} // namespace Atk

#endif /* _ATKMM_DOCUMENT_P_H */