text:
package com.github.kmizu.code_exercise.problems

import org.scalatest._

class P34UnitSpec extends FlatSpec {
  val S = new P34
  import S._

  "P34#solveNaive" should "return true for the following input" in {
    assertResult(true)(solveNaive(13, Seq(1, 2, 4, 7)))
    assertResult(true)(solveNaive(9, Seq(1, 2, 4, 7)))
  }

  "P34#solve" should "return true for the following input" in {
    assertResult(true)(solve(13, Seq(1, 2, 4, 7)))
    assertResult(true)(solve(9, Seq(1, 2, 4, 7)))
  }
}


text:
<launch>
<rosparam command="load" file="$(find poli2_full_moveit)/config/sensors_realsense.yaml" />
</launch>

redpajama_set_name: RedPajamaGithub


text:
  max-height: 800px;
  overflow-y: auto;
  overflow-x: hidden;
}

#rejectedComp {
  max-height: 800px;
  overflow-y: auto;
  overflow-x: hidden;
}

#confirmedComp {
  max-height: 800px;
  overflow-y: auto;
  overflow-x: hidden;
}

#pending {
  max-height: 800px;
  overflow-y: auto;
  overflow-x: hidden;
}

#sentSmall {
  max-height: 500px;
  overflow-y: auto;
  overflow-x: hidden;
}

#rejectedSmallComp {
  max-height: 500px;
  overflow-y: auto;
  overflow-x: hidden;
}

#confirmedSmallComp {
  max-height: 500px;
  overflow-y: auto;
  overflow-x: hidden;
}

#pendingSmall {
  max-height: 500px;
  overflow-y: auto;
  overflow-x: hidden;
}

li.tab {
  cursor: hand;
  cursor: pointer;
}


text:
G51PRG - Introduction to Programming
====================================

Solutions for the University of Nottingham Introduction to Programming module, Autumn 2012/13. All solutions are written in standard GCC-compliant C.

The module webpage can be found at http://g51prg.cs.nott.ac.uk/.

Coursework Topics
-----------------

 1. Variables and Functions
 2. A very simple RSS Parser
 3. Files and Arrays: Finding the Largest Pair
 4. Word Lengths
 5. DisARMing ELF


text:
DAC Scanning Channels
#######################################

There is a generic interface to digital-to-analog scanning channels that are e.g. provided by :ref:`NiDAQmx`. It
allows you to configure the scan range, fixed position during the measurement, the sync settings and line, pixel and
frame clock.

The interface currently contains a hack to allow fast 2D scanning which will disappear as soon as it is included in
the main Imspector hardware control.

Devices providing such generic channels usually have sub-pages to their hardware configuration pages:

.. image:: /images/hardware/hwrdlg_dacs.png
   :width: 10 cm
   :align: center

and for the per-measurement settings a page that is added below the main configuration page of the device, usually
titled 'DACs'.

.. image:: /images/hardware/docdlg_dacs.png
   :width: 10 cm
   :align: center

Also, a Live Dialog is registered that allows adjustment and visual control of the scan range during the scan.

.. image:: /images/hardware/livedlg_dacs.png
   :width: 6 cm
   :align: center

If you right-click on the dialog a menu appears with the commands

*Maximum Range*
   Reset the scan range to its maximum.

   .. note::

      If you have hardware limits in place (see above) the maximum scan range is almost always invalid as it
      requires infinite acceleration before flyback (the linear range reaches the edge of the valid range and there
      is no space to de-accelerate slowly).

*Center actual scan area*
   Center the scan area inside the valid range

*Center origin*
   Center the origin

*Settings*
   Adjust settings (see below).

Its behaviour can be adjusted through the settings dialog

.. image:: /images/hardware/livedlg_dacs_settings.png
   :width: 6 cm
   :align: center


text:
<?php

namespace DMS\Service\Meetup\Response;

use Guzzle\Common\Collection;

class SingleResultResponseTest extends \PHPUnit_Framework_TestCase
{
    public function testSerialization()
    {
        $code = 200;

        $headers = new Collection(array(
            'Content-Type' => 'application/json',
        ));

        $content = json_encode(array(
            array('id' => 1),
            array('id' => 2),
        ));

        $response = new SingleResultResponse($code, $headers, $content);

        $serialized = serialize($response);

        $this->assertNotContains('data', $serialized);

        $unserialized = unserialize($serialized);

        $this->assertEquals($response->getData(), $unserialized->getData());

        $this->assertInternalType('array', $unserialized->getData());
    }
}


text:
//
//  BSKVOController.h
//
//  Created by Dan Wright on 4/2/16.
//  Copyright © 2016 Dan Wright. All rights reserved.
//

#import <Foundation/Foundation.h>

@class BSMutableKVOController;

@interface BSKVOController : NSObject

@property (nonatomic, readonly, weak) NSObject *observedObject;

- (instancetype)initWithObservedObject:(NSObject *)object;
- (void)invalidate;

- (void)keyPath:(NSString *)keyPath options:(NSKeyValueObservingOptions)options queue:(dispatch_queue_t)queue addObserver:(void (^)(id object, NSDictionary *changes))block;
- (void)keyPath:(NSString *)keyPath options:(NSKeyValueObservingOptions)options addObserver:(void (^)(id object, NSDictionary *changes))block;
- (void)keyPaths:(NSArray<NSString *> *)keyPaths options:(NSKeyValueObservingOptions)options addObserver:(void (^)(id object, NSDictionary *changes))block;

- (BOOL)isObservingKeyPath:(NSString *)keyPath;
- (void)removeKeyPath:(NSString *)keyPath;

- (void)bind:(NSString *)fromKeyPath to:(NSString *)toKeyPath nilValue:(NSObject *)nilValue;

+ (instancetype)observe:(NSObject *)object;
- (instancetype)observe:(NSString *)keyPath;

@end

@interface BSMutableKVOController : BSKVOController
@property (nonatomic, weak) NSObject *observedObject;
@end

@interface NSObject (BSKVO)
- (BSKVOController *)keyPath:(NSString *)keyPath controllerForObserver:(void (^)(id object, NSDictionary *changes))block;
@end

/*
 _kvoSelf = [BSKVOController observe:self];
 _kvoPlayer = [_kvoSelf observe:@"player"];
 _kvoPlayerItem = [_kvoPlayer observe:@"currentItem"];

 [_kvoSelf keyPath:@"player" options:0 addObserver:^(id object, NSDictionary *changes) {
	NSLog(@"player changed to %@", [object player]);
 }];

 [_kvoPlayer keyPath:@"currentItem" options:NSKeyValueObservingOptionsInitial addObserver:^(id object, NSDictionary *changes) {
	NSLog(@"currentItem changed to %@", [object currentItem];
 }];

 [_kvoPlayerItem keyPath:@"duration" options:NSKeyValueObservingOptionsInitial addObserver:^(id object, NSDictionary *changes) {
	NSLog(@"duration is %f",CMTimeGetSeconds(!object ? kCMTimeInvalid : [object duration]));
 }];

*/


text:
local function splitpackagepath()
   local str = package.path
   local t = {}
   local last_end = 1
   local s, e, cap = string.find(str, "(.-);", 1)
   while s do
      if s ~= 1 or cap ~= "" then
	 table.insert(t,cap)
      end
      last_end = e+1
      s, e, cap = string.find(str, "(.-);", last_end)
   end
   if last_end <= string.len(str) then
      cap = string.sub(str, last_end)
      table.insert(t, cap)
   end
   -- get package prefixes
   for i=1,#t do
      local s,p = t[i]:find('?')
      if s then t[i] = t[i]:sub(1,s-1) end
   end
   -- remove duplicates
   local t2 = {}
   for i=1,#t do
      local exists = false;
      for j=1,#t2 do if t[i] == t2[j] then
	    exists = true end;
      end
      if not exists then table.insert(t2, t[i]) end
   end
   return t2
end
local mdsearchpaths = splitpackagepath()

local knownpkg = {}

-- Lua 5.2 compatibility
local unpack = unpack or table.unpack
local loadstring = loadstring or load

dok.inline = {}

dok.colors = {
   none = '\27[0m',
   black = '\27[0;30m',
   red = '\27[0;31m',
   green = '\27[0;32m',
   yellow = '\27[0;33m',
   blue = '\27[0;34m',
   magenta = '\27[0;35m',
   cyan = '\27[0;36m',
   white = '\27[0;37m',
   Black = '\27[1;30m',
   Red = '\27[1;31m',
   Green = '\27[1;32m',
   Yellow = '\27[1;33m',
   Blue = '\27[1;34m',
   Magenta = '\27[1;35m',
   Cyan = '\27[1;36m',
   White = '\27[1;37m',
   _black = '\27[40m',
   _red = '\27[41m',
   _green = '\27[42m',
   _yellow = '\27[43m',
   _blue = '\27[44m',
   _magenta = '\27[45m',
   _cyan = '\27[46m',
   _white = '\27[47m'
}
local c = dok.colors

local style = {}
function dok.usecolors()
   style = {
      banner = '+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++',
      list = c.blue .. '> ' .. c.none,
      title = c.Magenta,
      pre = c.cyan,
      em = c.Black,
      bold = c.Black,
      img = c.red,
      link = c.red,
      code = c.green,
      error = c.Red,
      none = c.none
   }
end
function dok.dontusecolors()
   style = {
      banner = '+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++',
      list = '> ',
      title = '',
      pre = '',
      em = '',
      bold = '',
      img = '',
      link = '',
      code = '',
      error = '',
      none = ''
   }
end
dok.usecolors()

local function uncleanText(txt)
   txt = txt:gsub(''', "'")
   txt = txt:gsub('*', '%*')
   txt = txt:gsub('+', '%+')
   txt = txt:gsub('<', '<')
   txt = txt:gsub('>', '>')
   return txt
end

local function string2symbol(str)
   local str  = str:gsub(':','.')
   local ok, res = pcall(loadstring('local t = ' .. str .. '; return t'))
   if not ok then
      ok, res = pcall(loadstring('local t = _torchimport.' .. str .. '; return t'))
   end
   return res
end

local function maxcols(str, cols)
   cols = cols or 70
   local res = ''
   local k = 1
   local color = false
   for i = 1,#str do
      res = res .. str:sub(i,i)
      if str:sub(i,i) == '\27' then
         color = true
      elseif str:sub(i,i) == 'm' then
         color = false
      end
      if k == cols then
         if str:sub(i,i) == ' ' then
            res = res .. '\n'
            k = 1
         end
      elseif not color then
         k = k + 1
      end
      if str:sub(i,i) == '\n' then
         k = 1
      end
   end
   return res
end

function dok.stylize(html, package)
   local styled = html
   -- (0) useless white space
   styled = styled:gsub('^%s+','')
   -- (1) function title
   styled = styled:gsub('<h%d>(.-)</h%d>', function(title) return style.title .. title .. style.none .. '\n' end)
   -- (2) lists
   styled = styled:gsub('
(.-)
',
			function(list)
			   return list:gsub('
%s*(.-)%s*
%s*', style.list .. '%1\n')
			end
   )
   -- (3) code
   styled = styled:gsub('%s*%s*(.-)%s*%s*', style.code .. ' %1 ' .. style.none)
   styled = styled:gsub('%s*%s*(.-)%s*%s*', style.pre .. ' %1 ' .. style.none)

   -- (4) pre
   styled = styled:gsub('
(.-)
', style.pre .. '%1' .. style.none)

   -- (5) formatting
   styled = styled:gsub('(.-)', style.em .. '%1' .. style.none)
   styled = styled:gsub('(.-)', style.bold .. '%1' .. style.none)
   styled = styled:gsub('(.-)', style.bold .. '%1' .. style.none)
   styled = styled:gsub('//(.-)//', style.bold .. '%1' .. style.none)

   -- (6) links
   styled = styled:gsub('(.-)', style.none .. '%1' .. style.none)
   -- (7) images
   styled = styled:gsub('%s*',
			style.img .. 'image: file://'
			   .. paths.concat(package,'%1') -- OUCH DEBUG paths.install_dokmedia,
			   .. style.none .. '\n')
   -- (8) remove internal anchors
   styled = styled:gsub('', '')
   -- (-) paragraphs
   styled = styled:gsub('
', '\n')
   styled = styled:gsub('
', '')

   -- (-) special chars
   styled = uncleanText(styled)
   -- (-) max columns
   styled = maxcols(styled)
   -- (-) conclude
   styled = styled:gsub('%s*$','')

   return styled
end

local function adddok(...)
   local tt = {}
   local arg = {...}
   for i=1,#arg do
      table.insert(tt,arg[i])
   end
   return table.concat(tt,'\n')
end

--[[
   function dok.html2funcs(html, package)
   This is how this function works:
   It initializes the section to level-0 (which means a heading with <h0>).
   There cant be a html section higher than this, so root node.

   It looks first for an anchor, like this one:

   Once it found an anchor, it gets the name of the anchor, in this case it is nn.dok

   It also looks for headings, like this:

Neural Network Package

   The level of the heading is determined by <h[number]>

   It then sees if before the heading
 appeared and after the
   anchor () appeared, if any other lines were parsed. It records those
   lines in csection (just table.insert the lines) as a string.

   Now, continuing, the level is a number.
   It looks at if the current level is lower than the current csection's level
   (which means is it higher up the tree towards the root). If it is, it
   traverses up the tree until it finds the parent is one level above, so that
   it can insert the current node into the right level of the tree.

   Now, it creates this subsection (which depends on the anchor and heading-name.
   it inserts it into this tree appropriately.

   Then it keeps parsing lines until the lines are again either an anchor or
   a heading. Once this happens, the subsection is deemed to be traversed and sealed.

   Then finally it creates a table of functions that have a key of the anchor
   name, and a value of the parsed lines (after stylizing them). A small
   check is done to make sure that the anchor name starts with the package-name.

]]--
function dok.html2funcs(html, package)
   local sections = {level=0}
   local csection = sections
   local canchor
   local lines = {}
   for line in html:gmatch('[^\n\r]+') do
      local anchor = line:match('')
         or line:match('.-')
      local level, name = line:match('<h(%d)>(.*)</h%d>')
      if anchor then
         canchor = anchor
      elseif level and name then
         if #lines > 0 then
            table.insert(csection, table.concat(lines, '\n'))
            lines = {}
         end

         level = tonumber(level)
         if level <= csection.level then
            while level <= csection.level do
               csection = csection.parent
            end
         end

         local subsection = {level=level, parent=csection, name=name, anchor=canchor}
         table.insert(csection, subsection)
         csection = subsection

      elseif line:match('^%s+$') then
      else
         canchor = nil
         table.insert(lines, line)
      end
   end

   -- deal with remaining lines
   if #lines > 0 then
      table.insert(csection, table.concat(lines, '\n'))
      lines = {}
   end

   local function printsection(section, txt)
      if section.level > 0 and section.name then
         table.insert(txt, string.format('<h%d>%s</h%d>', section.level, section.name, section.level))
      end
      if section.anchor then
      end
      for i=1,#section do
         if type(section[i]) == 'string' then -- this is NOT a subsection. Do not include sub-sections in there.
            table.insert(txt, section[i])
         end
      end
   end

   local funcs = {}

   local function traversesection(section)
      if section.anchor then
         local txt = {}
         local key = string.lower(section.anchor):match(package .. '%.(.*)')
         if key then
            printsection(section, txt)
            txt = table.concat(txt, '\n')
            funcs[key] = adddok(funcs[key], dok.stylize(txt, package))
         end
      end
      for i=1,#section do
         if type(section[i]) == 'string' then
         else
            traversesection(section[i])
         end
      end
   end
   traversesection(sections)

   return funcs
end

local function packageiterator()
   local co = coroutine.create(
      function()
         local trees = mdsearchpaths
	 for _,tree in ipairs(trees) do
	    for file in paths.files(tree) do
	       if file ~= '.' and file ~= '..' then
		  coroutine.yield(file, paths.concat(tree, file))
	       end
	    end
         end
   end)

   return function()
      local code, res1, res2 = coroutine.resume(co)
      return res1, res2
   end
end

local function mditerator(path)
   local co = coroutine.create(
      function()
	 function iterate(path)
	    if path == '.' or path == '..' then
	    elseif paths.filep(path) then
	       if path:match('%.md$') then
		  coroutine.yield(path)
	       end
	    else
	       for file in paths.files(path) do
		  if file ~= '.' and file ~= '..' then
		     iterate(paths.concat(path, file))
		  end
	       end
	    end
	 end
	 iterate(path)
   end)

   return function()
      local code, res = coroutine.resume(co)
      return res
   end

end

function dok.refresh()
   for pkgname, path in packageiterator() do
      local pkgtbl = _G[pkgname] or package.loaded[pkgname]
      if pkgtbl and not knownpkg[pkgname] then
         knownpkg[pkgname] = true
         for file in mditerator(path) do
            local f = io.open(file)
            if f then
               local content = f:read('*all')
               local html = dok.markdown2html(content)
               local funcs = dok.html2funcs(html, pkgname)
               if type(pkgtbl) ~= 'table' and _G._torchimport then
                  -- unsafe import, use protected import
                  pkgtbl = _G._torchimport[pkgname]
               end
               if pkgtbl and type(pkgtbl) == 'table' then
                  -- level 0: the package itself
                  dok.inline[pkgtbl] = dok.inline[pkgtbl] or funcs['dok']
		     or funcs['reference.dok'] or funcs['overview.dok']
                  -- next levels
                  for key,symb in pairs(pkgtbl) do
                     -- level 1: global functions and objects
                     local entry = (key):lower()
                     if funcs[entry] or funcs[entry..'.dok'] then
                        local sym = string2symbol(pkgname .. '.' .. key)
                        dok.inline[sym] = adddok(funcs[entry..'.dok'],funcs[entry])
                     end
                     -- level 2: objects' methods
                     if type(pkgtbl[key]) == 'table' then
                        local entries = {}
                        for k,v in pairs(pkgtbl[key]) do
                           entries[k] = v
                        end
                        local mt = getmetatable(pkgtbl[key]) or {}
                        for k,v in pairs(mt) do
                           entries[k] = v
                        end
                        for subkey,subsymb in pairs(entries) do
                           local entry = (key .. '.' .. subkey):lower()
                           if funcs[entry] or funcs[entry..'.dok'] then
                              local sym = string2symbol(pkgname .. '.' .. key .. '.' .. subkey)
                              dok.inline[sym] = adddok(funcs[entry..'.dok'],funcs[entry])
                           end
                        end
                     end
                  end
               end
            end
         end
      end
   end
end

--------------------------------------------------------------------------------
-- help() is the main user-side function: prints help for any given
-- symbol that has an anchor defined in a .dok file.
--------------------------------------------------------------------------------
function dok.help(symbol, asstring)
   -- color detect
   if qtide then
      dok.dontusecolors()
   else
      dok.usecolors()
   end
   -- no symbol? global help
   if not symbol then
      print(style.banner)
      print(style.title .. 'help(symbol)' .. style.none
	       .. '\n\nget inline help on a specific symbol\n'
	       .. '\nto browse the complete html documentation, call: '
	       .. style.title .. 'browse()' .. style.none)
      print(style.banner)
      return
   end
   -- always refresh (takes time, but insures that
   -- we generate help for all packages loaded)
   dok.refresh()
   if type(symbol) == 'string' then
      symbol = string2symbol(symbol)
   end
   local inline = dok.inline[symbol]
   if asstring then
      return inline
   else
      if inline then
         print(style.banner)
         print(inline)
         print(style.banner)
      else
	 print('undocumented symbol')
      end
   end
end

rawset(_G, 'help', dok.help)

-- function to parse a package's markdown files in a different way than for help().
-- this function returns the package's markdown files names (without extension) along with their headings.
local function package_headings(pname)
   local out = {}
   for pkgname, path in packageiterator() do
      if pkgname == pname then
	 local pkgtbl = _G[pkgname] or package.loaded[pkgname]
	 if pkgtbl then
	    for file in mditerator(path) do
	       local basename = paths.basename(file)
	       basename = basename:sub(1,#basename-3) -- remove .md
	       local f = io.open(file)
	       if f then
		  local heading = 'Untitled'
		  local content = f:read('*all')
		  local html = dok.markdown2html(content)
		  -- find first heading
		  for line in html:gmatch('[^\n\r]+') do
		     local level, name = line:match('<h(%d)>(.*)</h%d>')
		     if level and name then
			heading = name
			break -- found the first heading, call it a day
		     end
		  end
		  f:close()
		  out[basename] = {heading, file}
	       end -- if f then
	    end -- for file in mditerator
	 end -- if pkgtbl
	 break;
      end -- if pkgname == pname
   end -- for pkgname, path in packageiterator()
   return out
end

--------------------------------------------------------------------------------
-- browse() is a function that triggers a manual viewer in command-line
--------------------------------------------------------------------------------
function dok.browse(package_name)
   print(style.banner)
   print('Inline Package Manual Browser')
   print(style.banner)
   print('To exit at any time, type q or exit')
   if not package_name then
      print('Enter package name to browse (example: torch):')
      local answer = io.read()
      package_name = answer
   end
   if package_name == 'exit' then return end
   local ok, p = pcall(function() require(package_name) end)
   if not ok then
      print('Package not found or failed to load:', package_name)
      return
   end

   dok.help(package_name)
   -- Approach 1:
   -- show all available anchors from this dok and ask user to enter page.

   -- Approach 2:
   -- show file-by-file. After Overview, traverse Each file, and get the file heading. Print it out.
   -- Ask user to enter next file they want to traverse-to. (in brackets you can give them hints).

   -- Let's hack Approach 2.
   local headings = package_headings(package_name)

   print('Sections:')
   local example
   local menu = ''
   for k,v in pairs(headings) do
      menu = menu .. '\t' .. v[1] .. ' [' .. k .. ']\n'
      example = k
   end
   assert(example, 'No more subsections for this package')
   while true do
      print(menu)
      print('Enter choice (Example: ' .. example .. ') or type exit. :')
      local k = io.read()
      if k == 'exit'  then return end
      if headings[k] then
	 local file = headings[k][2]
	 local f = io.open(file)
	 if f then
	    local content = f:read('*all')
	    local sd = require 'sundown'
	    local str = sd.renderASCII(content)
	    local tracker = 0
	    f:close()
	    local max_chars = 1000 -- now print this string conservatively, maybe 1000 characters at a time
	    while tracker <= #str do
	       print(str:sub(tracker, tracker + max_chars))
	       print('[enter] for more or press any character to exit')
	       local ans = io.read()
	       if ans ~= ''  then break; end
	       tracker = tracker + max_chars
	    end
	 end
      end
   end

end

rawset(_G, 'browse', dok.browse)

--------------------------------------------------------------------------------
-- standard usage function: used to display automated help for functions
--
-- @param funcname     function name
-- @param description  description of the function
-- @param example      usage example
-- @param ...          [optional] arguments
--------------------------------------------------------------------------------
function dok.usage(funcname, description, example, ...)
   local str = ''

   local help = help(string2symbol(funcname), true)
   if help then
      str = str .. help
   else
      str = str .. style.banner .. '\n'
      str = str .. style.title .. funcname .. style.none .. '\n'
      if description then
         str = str .. '\n' .. description .. '\n'
      end
   end

   str = str .. '\n' .. style.list .. 'usage:\n' .. style.pre

   -- named arguments:
   local args = {...}
   if args[1].tabled then
      args = args[1].tabled
   end
   if args[1].arg then
      str = str .. funcname .. '{\n'
      for i,param in ipairs(args) do
         local key
         if param.req then
            key = '    ' .. param.arg .. ' = ' .. param.type
         else
            key = '    [' .. param.arg .. ' = ' .. param.type .. ']'
         end
         -- align:
         while key:len() < 40 do
            key = key .. ' '
         end
         str = str .. key .. '-- ' .. param.help
         if param.default or param.default == false then
            str = str .. '  [default = ' .. tostring(param.default) .. ']'
         elseif param.defaulta then
            str = str .. '  [default == ' .. param.defaulta .. ']'
         end
         str = str.. '\n'
      end
      str = str .. '}\n'

      -- unnamed args:
   else
      local idx = 1
      while true do
         local param
         str = str .. funcname .. '(\n'
         while true do
            param = args[idx]
            idx = idx + 1
            if not param or param == '' then break end
            local key
            if param.req then
               key = '    ' .. param.type
            else
               key = '    [' .. param.type .. ']'
            end
            -- align:
            while key:len() < 40 do
               key = key .. ' '
            end
            str = str .. key .. '-- ' .. param.help .. '\n'
         end
         str = str .. ')\n'
         if not param then break end
      end
   end
   str = str .. style.none

   if example then
      str = str .. '\n' .. style.pre .. example .. style.none .. '\n'
   end

   str = str .. style.banner
   return str
end

--------------------------------------------------------------------------------
-- standard argument function: used to handle named arguments, and
-- display automated help for functions
--------------------------------------------------------------------------------
function dok.unpack(args, funcname, description, ...)
   -- put args in table
   local defs = {...}

   -- generate usage string as a closure:
   -- this way the function only gets called when an error occurs
   local fusage = function()
      local example
      if #defs > 1 then
	 example = funcname .. '{' .. defs[2].arg .. '=' .. defs[2].type .. ', '
	    .. defs[1].arg .. '=' .. defs[1].type .. '}\n'
	 example = example .. funcname .. '(' .. defs[1].type .. ',' .. ' ...)'
      end
      return dok.usage(funcname, description, example, {tabled=defs})
   end
   local usage = {}
   setmetatable(usage, {__tostring=fusage})

   -- get args
   local iargs = {}
   if args.__printhelp then
      print(usage)
      error('error')
   elseif #args == 1 and type(args[1]) == 'table' and #args[1] == 0
   and not (torch and torch.typename(args[1]) ~= nil) then
      -- named args
      iargs = args[1]
   else
      -- ordered args
      for i = 1,select('#',...) do
         iargs[defs[i].arg] = args[i]
      end
   end

   -- check/set arguments
   local dargs = {}
   for i = 1,#defs do
      local def = defs[i]
      -- is value requested ?
      if def.req and iargs[def.arg] == nil then
         print(style.error .. 'missing argument: ' .. def.arg .. style.none)
         print(usage)
         error('error')
      end
      -- get value or default
      dargs[def.arg] = iargs[def.arg]
      if dargs[def.arg] == nil then
         dargs[def.arg] = def.default
      end
      if dargs[def.arg] == nil and def.defaulta then
         dargs[def.arg] = dargs[def.defaulta]
      end
      dargs[i] = dargs[def.arg]
   end

   -- return usage too
   dargs.usage = usage

   -- stupid lua bug: we return all args by hand
   if dargs[65] then
      error('<dok.unpack> oups, cant deal with more than 64 arguments :-)')
   end

   -- return modified args
   return dargs,unpack(dargs)
end

--------------------------------------------------------------------------------
-- prints an error with nice formatting. If domain is provided, it is used as
-- following: <domain> msg
--------------------------------------------------------------------------------
function dok.error(message, domain)
   if domain then
      message = '<' .. domain .. '> ' .. message
   end
   local col_msg = style.error .. tostring(message) .. style.none
   error(col_msg)
end


text:
title: Docker on Ubuntu 14.04
updated: 2016-02-20 18:02
---

In order to get the latest version of docker (as opposed to the older version available in the default Ubuntu sources), follow those instructions [here](http://askubuntu.com/questions/472412/how-do-i-upgrade-docker).


text:
#include <linux/init.h>
#include <linux/bootmem.h>
#include <linux/initrd.h>
#include <asm/types.h>
#include <init.h>
#include <os.h>

/* Changed by uml_initrd_setup, which is a setup */
static char *initrd __initdata = NULL;
static int load_initrd(char *filename, void *buf, int size);

static int __init read_initrd(void)
{
	void *area;
	long long size;
	int err;

	if (initrd == NULL)
		return 0;

	err = os_file_size(initrd, &size);
	if (err)
		return 0;

	/*
	 * This is necessary because alloc_bootmem craps out if you
	 * ask for no memory.
	 */
	if (size == 0) {
		printk(KERN_ERR "\"%s\" is a zero-size initrd\n", initrd);
		return 0;
	}

	area = alloc_bootmem(size);
	if (area == NULL)
		return 0;

	if (load_initrd(initrd, area, size) == -1)
		return 0;

	initrd_start = (unsigned long) area;
	initrd_end = initrd_start + size;
	return 0;
}

__uml_postsetup(read_initrd);

static int __init uml_initrd_setup(char *line, int *add)
{
	initrd = line;
	return 0;
}

__uml_setup("initrd=", uml_initrd_setup,
"initrd=<initrd image>\n"
"    This is used to boot UML from an initrd image.  The argument is the\n"
"    name of the file containing the image.\n\n"
);

static int load_initrd(char *filename, void *buf, int size)
{
	int fd, n;

	fd = os_open_file(filename, of_read(OPENFLAGS()), 0);
	if (fd < 0) {
		printk(KERN_ERR "Opening '%s' failed - err = %d\n", filename,
		       -fd);
		return -1;
	}
	n = os_read_file(fd, buf, size);
	if (n != size) {
		printk(KERN_ERR "Read of %d bytes from '%s' failed, "
		       "err = %d\n", size,
		       filename, -n);
		return -1;
	}

	os_close_file(fd);
	return 0;
}


text:
**A set of tools to query/view Gerrit patch reviews and their Zuul status**
===========================================================================

Current set of tools:

- ``qgerrit`` -- to query different projects' Gerrit reviews based on a set of criteria/filters.

- ``cgerrit`` -- to view (in real time) Gerrit reviews on CLI.

- ``czuul`` -- to view Gerrit reviews' Zuul (a pipeline oriented project gating and automation system) status on CLI.

qgerrit
------------

Use ``qgerrit`` to query different projects' Gerrit reviews
based on a set of criteria/filters::

    $ qgerrit -u 'harlowja'
    $ qgerrit -h

    Usage: qgerrit [options]

    Options:
      -h, --help            show this help message and exit
      -l USER, --login=USER
                            connect to gerrit with USER
      -u USER, --user=USER  gather information on given USER
      -s STATUS, --status=STATUS
                            gather information on given status
      -m MESSAGE, --message=MESSAGE
                            filter on message
      -p PROJECT, --project=PROJECT
                            gather information on given project
      -b BRANCH, --branch=BRANCH
                            filter on branch
      -a APPROVAL, --approval=APPROVAL
                            filter on approval value min %n [default: no filter]
      -k FILE, --keyfile=FILE
                            gerrit ssh keyfile [default: attempt to use
                            local agent]
      -t SORT, --sort=SORT  sort order for results [default: createdOn]
      -n LIMIT, --limit=LIMIT
                            Limit the number of returned results. Note that this
                            limit is applied before sorting
      -d, --deps            Display results as a dependency tree
      -f FIELD, --field=FIELD
                            display field in results [default: 'approvals',
                            'branch', 'createdOn', 'lastUpdated', 'owner',
                            'project', 'status', 'subject', 'topic', 'url']

########
Examples
########

1. To enumerate all reviews requests for openstack/nova which touch a
   file with libvirt in the name::

    $ qgerrit \
      -l harlowja \
      -f url -f branch -f owner -f subject:100 \
      -f lastUpdated -f createdOn -f approvals \
      --sort createdOn \
      --project openstack/nova \
      libvirt

2. Show reviews for neutron which does not have any negative karma, as
   those reviews are going to be resubmitted any way::

    $ qgerrit -l harlowja -a c0,v0 neutron

(Thanks to Daniel Berrange for the above two examples)

cgerrit
------------

Use ``cgerrit`` to watch (in realtime) the reviews showing up (powered by
urwid_ and the gerrit_ libraries):

.. image:: https://github.com/harlowja/gerrit_view/raw/master/screenshots/screen1.png

::

    $ cgerrit
    $ cgerrit -h

    Usage: cgerrit [options]

    Options:
      -h, --help            show this help message and exit
      -u USER, --user=USER  gerrit user [default: harlowja]
      -s SERVER, --server=SERVER
                            gerrit server [default: review.openstack.org]
      -p PORT, --port=PORT  gerrit port [default: 29418]
      --prefetch=COUNT      prefetch amount [default: 50]
      -k FILE, --keyfile=FILE
                            gerrit ssh keyfile [default: attempt to use local
                            agent]
      --project=PROJECT     only show given projects reviews
      -v FILE, --verbose=FILE
                            run in verbose mode and log output to the given file
      -i COUNT, --items=COUNT
                            how many items to keep visible [default: 50]
      -r FILE, --record-file=FILE
                            record file to store past events (also used for
                            initial view population if provided)

##############
Keys supported
##############

* (S, s) - Change sort mode (default none)
* (q, Q, esc) - Quit
* (up, down, page up, page down) - Scroll up/down

########
Examples
########

1. To view reviews (real-time) for a specific project::

    $ cgerrit -u harlowja --project=openstack/neutron

2. To view reviews (real-time) for all projects::

    $ cgerrit -u harlowja

czuul
------------

Use ``czuul`` to watch the reviews zuul status (powered by
urwid_ and the requests_ libraries):

.. image:: https://github.com/harlowja/gerrit_view/raw/master/screenshots/screen2.png

::

    $ czuul
    $ czuul -h
    Usage: czuul [options]

    Options:
      -h, --help            show this help message and exit
      -s URL, --server=URL  zuul server [default:
                            http://zuul.openstack.org/status.json]
      --split-screens=SCREENS
                            split screen count [default: 3]
      -p PIPELINE, --pipeline=PIPELINE
                            only show given pipelines reviews
      -r SECONDS, --refresh=SECONDS
                            refresh every X seconds [default: 30]
      --project=PROJECT     only show given projects reviews
      --no-details          skip fetching each reviews details
      -v FILE, --verbose=FILE
                            run in verbose mode and log output to the given file
      --detail-remote=REMOTE_SERVER
                            fetch review remotes from this gerrit server [default:
                            https://review.openstack.org/]

##############
Keys supported
##############

* (R, r) - Force refresh
* (q, Q, esc) - Quit
* (up, down, page up, page down) - Scroll up/down
* (left, right) - Scroll left/right
* (enter) - show job details

########
Examples
########

1. To get details about a project::

    $ czuul --project "openstack/nova"

2. To track all OpenStack project details in one go::

    $ czuul --project "openstack/*"

.. _urwid: http://excess.org/urwid/
.. _gerrit: https://pypi.python.org/pypi/gerritlib
.. _requests: http://www.python-requests.org/


text:
package cn.edu.nju.dao.examDAO;

import cn.edu.nju.dao.DataException;
import cn.edu.nju.model.examModel.ExamScoreModel;
import cn.edu.nju.model.examModel.PaperModel;

import java.util.List;

/**
 * Created by Jiayiwu on 17/11/13.
 * Mail:wujiayi@lgdreamer.com
 * Change everywhere
 */
public interface IPaperDAO {

    void deletePaperById(int paperId) throws Exception;

    // return paper id
    int addPaper(PaperModel paper) throws Exception;

    void updateMarkOfPaper(int paperId, double mark) throws Exception;

    boolean doesSubmitPaper(int examId, String email);

    PaperModel getPaperModel(
            int examId, String email) throws DataException;

    List<Double> getStudentMarks(
            int examId) throws DataException;

    List<ExamScoreModel> getStudentScores(
            int examId, int courseId) throws DataException;

}


text:
class BaseDSL
  def initialize
    @hash = {}
  end

  def name(text)
    @name = text
  end

  def encrypted(text)
    @hash['encrypted'] = '1'

    begin
      instance_eval(Encryption.decrypt_object(text))
    rescue OpenSSL::Cipher::CipherError, Encryption::KeyMissingError
      puts "warning: unable to decrypt level #{@name}, skipping"
      return
    end
  end

  # returns 'xyz' from 'XyzDSL' subclasses
  def prefix()
    self.class.to_s.tap{|s| s.slice!('DSL')}.underscore
  end

  def self.parse_file(filename, name=nil)
    text = File.read(filename)
    parse(text, filename, name)
  end

  def self.parse(str, filename, name=nil)
    object = self.new
    object.name(name) if name.present?
    object.instance_eval(str.to_ascii, filename)
    [object.parse_output, object.i18n_hash]
  end

  # override in subclass
  def parse_output
    @hash
  end

  # after parse has been done, this function returns a hash of all the user-visible strings from this instance
  def i18n_hash
    # Filter out any entries with nil key or value
    hash = i18n_strings.select { |key, value| key && value }
    {"en" => { "data" => { prefix => hash}}}
  end

  # Implement in subclass
  def i18n_strings
  end

  def self.boolean(name)
    define_method(name) do |val|
      instance_variable_set "@#{name}", ActiveRecord::Type::Boolean.new.type_cast_from_database(val)
    end
  end

  def self.string(name)
    define_method(name) do |val|
      instance_variable_set "@#{name}", val
    end
  end

  def self.integer(name)
    define_method(name) do |val|
      instance_variable_set "@#{name}", ActiveRecord::Type::Integer.new.type_cast_from_database(val)
    end
  end
end


text:
#ifndef WEBSOCKETPP_EXTENSION_HPP
#define WEBSOCKETPP_EXTENSION_HPP

#include <websocketpp/common/cpp11.hpp>
#include <websocketpp/common/system_error.hpp>

#include <string>
#include <vector>

namespace websocketpp {

/**
 * Some generic information about extensions
 *
 * Each extension object has an implemented flag. It can be retrieved by calling
 * is_implemented(). This compile time flag indicates whether or not the object
 * in question actually implements the extension or if it is a placeholder stub
 *
 * Each extension object also has an enabled flag. It can be retrieved by
 * calling is_enabled(). This runtime flag indicates whether or not the
 * extension has been negotiated for this connection.
 */
namespace extensions {

namespace error {
enum value {
    /// Catch all
    general = 1,

    /// Extension disabled
    disabled
};

class category : public lib::error_category {
public:
    category() {}

    const char *name() const _WEBSOCKETPP_NOEXCEPT_TOKEN_ {
        return "websocketpp.extension";
    }

    std::string message(int value) const {
        switch(value) {
            case general:
                return "Generic extension error";
            case disabled:
                return "Use of methods from disabled extension";
            default:
                return "Unknown permessage-compress error";
        }
    }
};

inline const lib::error_category& get_category() {
    static category instance;
    return instance;
}

inline lib::error_code make_error_code(error::value e) {
    return lib::error_code(static_cast<int>(e), get_category());
}

} // namespace error
} // namespace extensions
} // namespace websocketpp

_WEBSOCKETPP_ERROR_CODE_ENUM_NS_START_
template<> struct is_error_code_enum
    <websocketpp::extensions::error::value>
{
    static const bool value = true;
};
_WEBSOCKETPP_ERROR_CODE_ENUM_NS_END_

#endif // WEBSOCKETPP_EXTENSION_HPP


text:
from mock import patch
from sphinx_testing import with_app
from blockdiag.utils.compat import u

import sys
if sys.version_info < (2, 7):
    import unittest2 as unittest
else:
    import unittest

class TestSphinxcontribBlockdiagErrors(unittest.TestCase):
    @with_app(srcdir='tests/docs/basic', write_docstring=True)
    def test_parse_error(self, app, status, warning):
        """
        .. blockdiag::

           { A -> B;
        """
        app.builder.build_all()
        self.assertIn('got unexpected token:', warning.getvalue())

    @with_app(srcdir='tests/docs/basic', confoverrides=dict(blockdiag_html_image_format='JPG'))
    def test_unknown_format_error(self, app, status, warning):
        app.builder.build_all()
        self.assertIn('unknown format: JPG', warning.getvalue())

    @with_app(srcdir='tests/docs/basic', confoverrides=dict(blockdiag_html_image_format='PDF'))
    def test_reportlab_not_found_error(self, app, status, warning):
        try:
            # unload reportlab and make loading it impossible
            sys.modules.pop('reportlab', None)
            path = sys.path
            sys.path = []

            app.builder.build_all()

            self.assertIn('Could not output PDF format. Install reportlab.',
                          warning.getvalue())
        finally:
            sys.path = path

    @with_app(srcdir='tests/docs/basic')
    @patch("blockdiag.utils.rst.nodes.blockdiag.processor.drawer.DiagramDraw")
    def test_rendering_error(self, app, status, warning, DiagramDraw):
        DiagramDraw.side_effect = RuntimeError("UNKNOWN ERROR!")
        app.builder.build_all()
        self.assertIn('UNKNOWN ERROR!', warning.getvalue())

    @with_app(srcdir='tests/docs/basic')
    @patch("sphinxcontrib.blockdiag.blockdiag.drawer.DiagramDraw.draw")
    def test_font_settings_error(self, app, status, warning, draw):
        draw.side_effect = UnicodeEncodeError("", u(""), 0, 0, "")
        app.builder.build_all()
        self.assertIn('UnicodeEncodeError caught (check your font settings)',
                      warning.getvalue())


text:
using System;
using System.Globalization;
using System.Text;
using Jint.Native.Number.Dtoa;
using Jint.Runtime;
using Jint.Runtime.Interop;

namespace Jint.Native.Number
{
    /// <summary>
    /// http://www.ecma-international.org/ecma-262/5.1/#sec-15.7.4
    /// </summary>
    public sealed class NumberPrototype : NumberInstance
    {
        private NumberPrototype(Engine engine)
            : base(engine)
        {
        }

        public static NumberPrototype CreatePrototypeObject(Engine engine, NumberConstructor numberConstructor)
        {
            var obj = new NumberPrototype(engine);
            obj.Prototype = engine.Object.PrototypeObject;
            obj.PrimitiveValue = 0;
            obj.Extensible = true;

            obj.FastAddProperty("constructor", numberConstructor, true, false, true);

            return obj;
        }

        public void Configure()
        {
            FastAddProperty("toString", new ClrFunctionInstance(Engine, ToNumberString), true, false, true);
            FastAddProperty("toLocaleString", new ClrFunctionInstance(Engine, ToLocaleString), true, false, true);
            FastAddProperty("valueOf", new ClrFunctionInstance(Engine, ValueOf), true, false, true);
            FastAddProperty("toFixed", new ClrFunctionInstance(Engine, ToFixed, 1), true, false, true);
            FastAddProperty("toExponential", new ClrFunctionInstance(Engine, ToExponential), true, false, true);
            FastAddProperty("toPrecision", new ClrFunctionInstance(Engine, ToPrecision), true, false, true);
        }

        private JsValue ToLocaleString(JsValue thisObject, JsValue[] arguments)
        {
            if (!thisObject.IsNumber() && (thisObject.TryCast<NumberInstance>() == null))
            {
                throw new JavaScriptException(Engine.TypeError);
            }

            var m = TypeConverter.ToNumber(thisObject);

            if (double.IsNaN(m))
            {
                return "NaN";
            }

            if (m.Equals(0))
            {
                return "0";
            }

            if (m < 0)
            {
                return "-" + ToNumberString(-m);
            }

            if (double.IsPositiveInfinity(m) || m >= double.MaxValue)
            {
                return "Infinity";
            }

            if (double.IsNegativeInfinity(m) || m <= -double.MaxValue)
            {
                return "-Infinity";
            }

            return m.ToString("n", Engine.Options.GetCulture());
        }

        private JsValue ValueOf(JsValue thisObj, JsValue[] arguments)
        {
            var number = thisObj.TryCast<NumberInstance>();
            if (number == null)
            {
                throw new JavaScriptException(Engine.TypeError);
            }

            return number.PrimitiveValue;
        }

        private const double Ten21 = 1e21;

        private JsValue ToFixed(JsValue thisObj, JsValue[] arguments)
        {
            var f = (int)TypeConverter.ToInteger(arguments.At(0, 0));
            if (f < 0 || f > 20)
            {
                throw new JavaScriptException(Engine.RangeError, "fractionDigits argument must be between 0 and 20");
            }

            var x = TypeConverter.ToNumber(thisObj);

            if (double.IsNaN(x))
            {
                return "NaN";
            }

            if (x >= Ten21)
            {
                return ToNumberString(x);
            }

            var l = (long) x; // extract integer part

            if (f == 0)
            {
                return l.ToString(CultureInfo.InvariantCulture);
            }

            var d = x - l;
            return l.ToString(CultureInfo.InvariantCulture) + d.ToString("." + new string('0', f), CultureInfo.InvariantCulture);
        }

        private JsValue ToExponential(JsValue thisObj, JsValue[] arguments)
        {
            var f = (int)TypeConverter.ToInteger(arguments.At(0, 16));
            if (f < 0 || f > 20)
            {
                throw new JavaScriptException(Engine.RangeError, "fractionDigits argument must be between 0 and 20");
            }

            var x = TypeConverter.ToNumber(thisObj);

            if (double.IsNaN(x))
            {
                return "NaN";
            }

            string format = System.String.Concat("#.", new System.String('0', f), "e+0");
            return x.ToString(format, CultureInfo.InvariantCulture);
        }

        private JsValue ToPrecision(JsValue thisObj, JsValue[] arguments)
        {
            var x = TypeConverter.ToNumber(thisObj);

            if (arguments.At(0) == Undefined.Instance)
            {
                return TypeConverter.ToString(x);
            }

            var p = TypeConverter.ToInteger(arguments.At(0));

            if (double.IsInfinity(x) || double.IsNaN(x))
            {
                return TypeConverter.ToString(x);
            }

            if (p < 1 || p > 21)
            {
                throw new JavaScriptException(Engine.RangeError, "precision must be between 1 and 21");
            }

            // Get the number of decimals
            string str = x.ToString("e23", CultureInfo.InvariantCulture);
            int decimals = str.IndexOfAny(new [] { '.', 'e' });
            decimals = decimals == -1 ? str.Length : decimals;

            p -= decimals;
            p = p < 1 ? 1 : p;

            return x.ToString("f" + p, CultureInfo.InvariantCulture);
        }

        private JsValue ToNumberString(JsValue thisObject, JsValue[] arguments)
        {
            if (!thisObject.IsNumber() && (thisObject.TryCast<NumberInstance>() == null))
            {
                throw new JavaScriptException(Engine.TypeError);
            }

            var radix = arguments.At(0) == JsValue.Undefined ? 10 : (int) TypeConverter.ToInteger(arguments.At(0));

            if (radix < 2 || radix > 36)
            {
                throw new JavaScriptException(Engine.RangeError, "radix must be between 2 and 36");
            }

            var x = TypeConverter.ToNumber(thisObject);

            if (double.IsNaN(x))
            {
                return "NaN";
            }

            if (x.Equals(0))
            {
                return "0";
            }

            if (double.IsPositiveInfinity(x) || x >= double.MaxValue)
            {
                return "Infinity";
            }

            if (x < 0)
            {
                return "-" + ToNumberString(-x, arguments);
            }

            if (radix == 10)
            {
                return ToNumberString(x);
            }

            var integer = (long) x;
            var fraction = x -  integer;

            string result = ToBase(integer, radix);
            if (!fraction.Equals(0))
            {
                result += "." + ToFractionBase(fraction, radix);
            }

            return result;
        }

        public static string ToBase(long n, int radix)
        {
            const string digits = "0123456789abcdefghijklmnopqrstuvwxyz";
            if (n == 0)
            {
                return "0";
            }

            var result = new StringBuilder();
            while (n > 0)
            {
                var digit = (int)(n % radix);
                n = n / radix;
                result.Insert(0, digits[digit].ToString());
            }

            return result.ToString();
        }

        public static string ToFractionBase(double n, int radix)
        {
            // based on the repeated multiplication method
            // http://www.mathpath.org/concepts/Num/frac.htm

            const string digits = "0123456789abcdefghijklmnopqrstuvwxyz";
            if (n.Equals(0))
            {
                return "0";
            }

            var result = new StringBuilder();
            while (n > 0 && result.Length < 50) // arbitrary limit
            {
                var c = n*radix;
                var d = (int) c;
                n = c - d;

                result.Append(digits[d].ToString());
            }

            return result.ToString();
        }

        public static string ToNumberString(double m)
        {
            if (double.IsNaN(m))
            {
                return "NaN";
            }

            if (m.Equals(0))
            {
                return "0";
            }

            if (double.IsPositiveInfinity(m) || m >= double.MaxValue)
            {
                return "Infinity";
            }

            if (m < 0)
            {
                return "-" + ToNumberString(-m);
            }

            // V8 FastDtoa can't convert all numbers, so try it first but
            // fall back to old DToA in case it fails
            var result = FastDtoa.NumberToString(m);
            if (result != null)
            {
                return result;
            }

            // s is all digits (significand)
            // k number of digits of s
            // n total of digits in fraction s*10^n-k=m
            // 123.4 s=1234, k=4, n=3
            // 1234000 s = 1234, k=4, n=7
            string s = null;
            var rFormat = m.ToString("r");
            if (rFormat.IndexOf("e", StringComparison.OrdinalIgnoreCase) == -1)
            {
                s = rFormat.Replace(".", "").TrimStart('0').TrimEnd('0');
            }

            const string format = "0.00000000000000000e0";
            var parts = m.ToString(format, CultureInfo.InvariantCulture).Split('e');
            if (s == null)
            {
                s = parts[0].TrimEnd('0').Replace(".", "");
            }

            var n = int.Parse(parts[1]) + 1;
            var k = s.Length;

            if (k <= n && n <= 21)
            {
                return s + new string('0', n - k);
            }

            if (0 < n && n <= 21)
            {
                return s.Substring(0, n) + '.' + s.Substring(n);
            }

            if (-6 < n && n <= 0)
            {
                return "0." + new string('0', -n) + s;
            }

            if (k == 1)
            {
                return s + "e" + (n - 1 < 0 ? "-" : "+") + System.Math.Abs(n - 1);
            }

            return s.Substring(0, 1) + "." + s.Substring(1) + "e" + (n - 1 < 0 ? "-" : "+") + System.Math.Abs(n - 1);
        }
    }
}


text:
title: Removing com.apple.quarantine
tags: [mac]
category: General
description: Troubleshooting weirdly specific mac permissions issues
---

Today I was working on a new Magento 1.x install. A new install workflow usually goes like this:

- Download a zip of the newest Magento 1.x release
- Extract the contents into the folder of choice
- Update `app/etc/local.xml` to point to the correct database
- Add a new virtual host in my vagrant box pointing to the Magento 1.x folder of choice
- Install as necessary

That usually works fine, but today I was running into some issues. Everything looked fine, but the virtual host was throwing up 403 forbidden errors, leading me to think that there was some sort of permissions issue. Following the reference guides, I ran the following to make sure:

~~~bash
find . -type f | xargs chmod 400
find . -type d | xargs chmod 500
find var/ media/ -type f | xargs chmod 600
find var/ media/ -type d | xargs chmod 700
chmod 700 includes
chmod 600 includes/config.php
~~~

After that, reloaded the page, and ... nothing. I then ran `ls -la` inside the folder of the Magento install to make sure the `chmod` changes occurred, and noticed:

~~~bash
---snip---
-rw-r--r--@   1 dstrunk  staff    2329 Oct 27  2015 index.php.sample
---snip---
~~~

What's that `@` symbol? I'd never seen that before. Looking it up, I found that the `@` symbol represents a file or directory that has extended attributes. If you run the command `xargs -l <filename>`, you will see these attributes in the form of a reverse domain name; something like `com.apple.attribute`.

In my case, all files in my unzipped directory contained the attribute `com.apple.quarantine`. This is a feature that flags the content as having come from a potentially untrustworthy source. That's all well and good, but how do we remove this attribute? Pretty simple, it turns out. Simply run the following within the folder you're looking to unquarantine:

~~~bash
xattr -dr com.apple.quarantine .
~~~

All that said, my issue ended up being an improperly configured Vagrant configuration... but that was a good learning experience :).


text:
import { enableLogger, expectWarn, expectNoWarn } from './../../../services/Logger.mock';
import { Header } from './Header';

describe('html.Header', () => {
  it('should work ', () => {
    const props = { type: 'Header', value: '...' };
    enableLogger(() => { Header({ props, context: {} }); });
    expectNoWarn();
  });
  it('not working without value', () => {
    const props = { type: 'Header' };
    Header({ props, context: {} });
    expectWarn();
  });
});


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
null

#### Original name
Dichotomyxa W.B. Kendr. et al.

### Remarks
null


text:
class SubHistoryTrans < ActiveRecord::Migration
  def self.up
    rename_column(:subscription_histories, :transaction, :order_transaction)
    change_column(:subscription_histories, :order_transaction, :string, {:limit => 50})
  end

  def self.down
    rename_column(:subscription_histories, :order_transaction, :transaction)
    change_column(:subscription_histories, :transaction, :string, {:limit => 50})
  end
end


text:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE html PUBLIC  "-//W3C//DTD XHTML 1.0 Transitional//EN"
  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

      <meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
      <meta name="keywords" content="W3C SVG 1.1 2nd Edition Test Suite"/>
      <meta name="description" content="W3C SVG 1.1 2nd Edition SVGWeb Test Suite"/>
      <title>
SVG 1.1 2nd Edition Test (svgweb): interact-order-02-b.svg
      </title>

      <link rel="prev" href="interact-order-01-b.html" />
      <link rel="index" href="index.html" />
      <link rel="next" href="interact-order-03-b.html" />

Specification link: 16.5 Processing order for user interface events

    interact-order-01-b ←
    index
    → interact-order-03-b

    Tests that contain the draft-watermark are under development and may be incorrectly testing a feature.

interact-order-02-b.svg

            SVG Image

            PNG Image

              <object data="../../svg/interact-order-02-b.svg" width="480" height="360" type="image/svg+xml">
FAIL

              </object>

      Operator Script

Click on the first circle, then the second, and lastly the new third circle.

    Pass Criteria

        Clicking on the first circle should change the circle from black to red.  Clicking
        on the second circle should take you to another SVG file titled "Hyperlink target for
        interact-order-02.svg.  Cliking on the circle in this SVG file should return you to the orginal
        two circles.

    Test Description

        Test event bubbling of event attributes, part b.

        The two circles test whether events are handled in the
        proper order. Events listeners and event attributes are processed
        before hyperlink processing, which is processed before text selection.

    interact-order-01-b ←
    index
    → interact-order-03-b


text:
//
//  HBMyRedPaperController.m
//  happyBycle
//
//  Created by Stephen on 2017/5/23.
//  Copyright © 2017年 wsl. All rights reserved.
//

#import "HBMyRedPaperController.h"

#import "HBRedPaperDetailController.h"
#import "HBRedPaperQuestionController.h"
#import "HBRedPaperStategyController.h"
@interface HBMyRedPaperController ()
@property (weak, nonatomic) IBOutlet UILabel *moneyLabel;
@property (weak, nonatomic) IBOutlet UILabel *moneyLabelDes;

@property (weak, nonatomic) IBOutlet UIButton *redpaperBt;
@property (weak, nonatomic) IBOutlet UIButton *outMonetyBt;

@property (weak, nonatomic) IBOutlet UIButton *questionBt;

@end

@implementation HBMyRedPaperController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.navigationItem.title=@"我的红包";

    UIButton *bt=[[UIButton alloc] initWithFrame:CGRectMake(0, 0, 80, 44)];
    [bt setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    bt.titleLabel.font=[UIFont systemFontOfSize:14];
    [bt setTitle:@"红包明细" forState:UIControlStateNormal];
    [bt addTarget:self action:@selector(redpaperDetailBtViewOnClick) forControlEvents:UIControlEventTouchUpInside];
    UIBarButtonItem *leftBar = [[UIBarButtonItem alloc]initWithCustomView:bt];

    self.navigationItem.rightBarButtonItem =leftBar;
}

#pragma -mark- 问题
//红包明细
-(void)redpaperDetailBtViewOnClick{
    HBRedPaperDetailController *detailVc=[[HBRedPaperDetailController alloc] init];
    [self.navigationController pushViewController:detailVc animated:YES];
}
//攻略
- (IBAction)redpaperBtOnClick:(UIButton *)sender {
    HBRedPaperStategyController *stategyVc=[[HBRedPaperStategyController alloc] init];
    [self.navigationController pushViewController:stategyVc animated:YES];
}
//提现
- (IBAction)outMoneyBtOnClick:(UIButton *)sender {
   // HBRedPaperDetailController *detailVc=[[HBRedPaperDetailController alloc] init];
   // [self.navigationController pushViewController:detailVc animated:YES];
}
//问题
- (IBAction)questionBtOnClick:(UIButton *)sender {
    HBRedPaperQuestionController *questionVc=[[HBRedPaperQuestionController alloc] init];
    [self.navigationController pushViewController:questionVc animated:YES];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end


text:
package org.apache.camel.dataformat.bindy;

import java.math.BigDecimal;
import java.math.BigInteger;
import java.util.Date;
import java.util.Locale;

import org.apache.camel.dataformat.bindy.annotation.DataField;
import org.apache.camel.dataformat.bindy.annotation.KeyValuePairField;
import org.apache.camel.dataformat.bindy.format.BigDecimalFormat;
import org.apache.camel.dataformat.bindy.format.BigIntegerFormat;
import org.apache.camel.dataformat.bindy.format.ByteFormat;
import org.apache.camel.dataformat.bindy.format.BytePatternFormat;
import org.apache.camel.dataformat.bindy.format.CharacterFormat;
import org.apache.camel.dataformat.bindy.format.DatePatternFormat;
import org.apache.camel.dataformat.bindy.format.DoubleFormat;
import org.apache.camel.dataformat.bindy.format.DoublePatternFormat;
import org.apache.camel.dataformat.bindy.format.EnumFormat;
import org.apache.camel.dataformat.bindy.format.FloatFormat;
import org.apache.camel.dataformat.bindy.format.FloatPatternFormat;
import org.apache.camel.dataformat.bindy.format.IntegerFormat;
import org.apache.camel.dataformat.bindy.format.IntegerPatternFormat;
import org.apache.camel.dataformat.bindy.format.LongFormat;
import org.apache.camel.dataformat.bindy.format.LongPatternFormat;
import org.apache.camel.dataformat.bindy.format.ShortFormat;
import org.apache.camel.dataformat.bindy.format.ShortPatternFormat;
import org.apache.camel.dataformat.bindy.format.StringFormat;
import org.apache.camel.util.ObjectHelper;

/**
 * Factory to return {@link Format} classes for a given type.
 */
public final class FormatFactory {

    private FormatFactory() {
    }

    /**
     * Retrieves the format to use for the given type
     *
     * @param clazz represents the type of the format (String, Integer, Byte)
     * @param pattern is the pattern to be used during the formatting of the data
     * @param locale optional locale for NumberFormat and DateFormat parsing.
     * @param precision optional scale for BigDecimal parsing.
     * @param impliedDecimalSeparator optional flag for floatign-point values
     * @return Format the formatter
     * @throws IllegalArgumentException if not suitable formatter is found
     */
    @SuppressWarnings("unchecked")
    private static Format<?> doGetFormat(Class<?> clazz, String pattern, String locale,
                                         String timezone, int precision, boolean impliedDecimalSeparator)
        throws Exception {
        if (clazz == byte.class || clazz == Byte.class) {
            return ObjectHelper.isNotEmpty(pattern)
                ? new BytePatternFormat(pattern, getLocale(locale))
                : new ByteFormat();
        } else if (clazz == short.class || clazz == Short.class) {
            return ObjectHelper.isNotEmpty(pattern)
                ? new ShortPatternFormat(pattern, getLocale(locale))
                : new ShortFormat();
        } else if (clazz == int.class || clazz == Integer.class) {
            return ObjectHelper.isNotEmpty(pattern)
                ? new IntegerPatternFormat(pattern, getLocale(locale))
                : new IntegerFormat();
        } else if (clazz == long.class || clazz == Long.class) {
            return ObjectHelper.isNotEmpty(pattern)
                ? new LongPatternFormat(pattern, getLocale(locale))
                : new LongFormat();
        } else if (clazz == float.class || clazz == Float.class) {
            return ObjectHelper.isNotEmpty(pattern)
                ? new FloatPatternFormat(pattern, getLocale(locale))
                : new FloatFormat(impliedDecimalSeparator, precision, getLocale(locale));
        } else if (clazz == double.class || clazz == Double.class) {
            return ObjectHelper.isNotEmpty(pattern)
                ? new DoublePatternFormat(pattern, getLocale(locale))
                : new DoubleFormat(impliedDecimalSeparator, precision, getLocale(locale));
        } else if (clazz == BigDecimal.class) {
            return new BigDecimalFormat(impliedDecimalSeparator, precision, getLocale(locale));
        } else if (clazz == BigInteger.class) {
            return new BigIntegerFormat();
        } else if (clazz == String.class) {
            return new StringFormat();
        } else if (clazz == Date.class) {
            return new DatePatternFormat(pattern, timezone, getLocale(locale));
        } else if (clazz == char.class || clazz == Character.class) {
            return new CharacterFormat();
        } else if (clazz.isEnum()) {
            return new EnumFormat(clazz);
        } else {
            throw new IllegalArgumentException("Can not find a suitable formatter for the type: " + clazz.getCanonicalName());
        }
    }

    /**
     * Retrieves the format to use for the given type
     *
     * @param clazz represents the type of the format (String, Integer, Byte)
     * @param locale optional locale for NumberFormat and DateFormat parsing.
     * @return Format the formatter
     * @throws IllegalArgumentException if not suitable formatter is found
     */
    public static Format<?> getFormat(Class<?> clazz, String locale, DataField data) throws Exception {
        String pattern = data.pattern();
        String timezone = data.timezone();
        int precision = data.precision();

        return doGetFormat(clazz, pattern, locale, timezone, precision, data.impliedDecimalSeparator());
    }

    /**
     * Retrieves the format to use for the given type
     *
     * @param clazz represents the type of the format (String, Integer, Byte)
     * @param locale optional locale for NumberFormat and DateFormat parsing.
     * @return Format the formatter
     * @throws IllegalArgumentException if not suitable formatter is found
     */
    public static Format<?> getFormat(Class<?> clazz, String locale, KeyValuePairField data) throws Exception {
        String pattern = data.pattern();
        String timezone = data.timezone();
        int precision = data.precision();

        return doGetFormat(clazz, pattern, locale, timezone, precision, data.impliedDecimalSeparator());
    }

    private static Locale getLocale(String locale) {
        Locale answer = null;
        if (locale != null && !(locale.length() == 0)) {
            String[] result = locale.split("-");
            if (result.length <= 2) {
                answer = result.length == 1 ? new Locale(result[0]) : new Locale(result[0], result[1]);
            }
        }
        return answer;
    }

}


text:
Need an account? Register here

    <form
        name="registerVm.registrationForm"
        ng-submit="registerVm.register()"
    >

            Your username will be publicly viewable by the entire Internet

        <input
            maxlength="50"
            name="username"
            ng-model="registerVm.username"
            placeholder="Username"
            required
            type="text"
        />

        <input
            maxlength="50"
            name="email"
            ng-model="registerVm.email"
            placeholder="Email"
            required
            type="email"
        />

        <input
            maxlength="50"
            name="password"
            ng-model="registerVm.password"
            placeholder="Password"
            required
            type="password"
        />

        <button ng-disabled="!registerVm.registrationForm.$valid">
             Submit
        </button>

Registration failed, please try again.

    </form>


text:
/*
 * Created on 14 Dec 2006
 */
package uk.org.ponder.rsf.template;

import java.util.Comparator;

/** Compares two XMLLumps for their relative order of appareance in a template */

public class XMLLumpComparator implements Comparator {
  private static final Comparator instance = new XMLLumpComparator();
  public static final Comparator instance() {
    return instance;
  }
  public int compare(Object o1, Object o2) {
    return ((XMLLump)o1).lumpindex - ((XMLLump)o2).lumpindex;
  }
}


text:
"""
:mod:`jedi.evaluate.imports` is here to resolve import statements and return
the modules/classes/functions/whatever, which they stand for. However there's
not any actual importing done. This module is about finding modules in the
filesystem. This can be quite tricky sometimes, because Python imports are not
always that simple.

This module uses imp for python up to 3.2 and importlib for python 3.3 on; the
correct implementation is delegated to _compatibility.

This module also supports import autocompletion, which means to complete
statements like ``from datetim`` (curser at the end would return ``datetime``).
"""
import os
import pkgutil
import sys
from itertools import chain

from jedi._compatibility import find_module, unicode
from jedi import common
from jedi import debug
from jedi import cache
from jedi.parser import fast
from jedi.parser import representation as pr
from jedi.evaluate import sys_path
from jedi.evaluate import helpers
from jedi import settings
from jedi.common import source_to_unicode
from jedi.evaluate import compiled
from jedi.evaluate.cache import memoize_default, NO_DEFAULT

class ModuleNotFound(Exception):
    pass

class ImportWrapper(pr.Base):
    """
    An ImportWrapper is the path of a `pr.Import` object.
    """
    class GlobalNamespace(object):
        def __init__(self):
            self.line_offset = 0

    GlobalNamespace = GlobalNamespace()

    def __init__(self, evaluator, import_stmt, is_like_search=False, kill_count=0,
                 direct_resolve=False, is_just_from=False):
        self._evaluator = evaluator
        self.import_stmt = import_stmt
        self.is_like_search = is_like_search
        self.direct_resolve = direct_resolve
        self.is_just_from = is_just_from

        self.is_partial_import = bool(max(0, kill_count))

        # rest is import_path resolution
        import_path = []
        if import_stmt.from_ns:
            import_path += import_stmt.from_ns.names
        if import_stmt.namespace:
            if self._is_nested_import() and not direct_resolve:
                import_path.append(import_stmt.namespace.names[0])
            else:
                import_path += import_stmt.namespace.names
        import_path = [str(name_part) for name_part in import_path]

        for i in range(kill_count + int(is_like_search)):
            if import_path:
                import_path.pop()

        module = import_stmt.get_parent_until()
        self._importer = get_importer(self._evaluator, tuple(import_path), module,
                                      import_stmt.relative_count)

    def __repr__(self):
        return '<%s: %s>' % (type(self).__name__, self.import_stmt)

    @property
    def import_path(self):
        return self._importer.import_path

    def get_defined_names(self, on_import_stmt=False):
        names = []
        for scope in self.follow():
            if scope is ImportWrapper.GlobalNamespace:
                if not self._is_relative_import():
                    names += self._get_module_names()

                if self._importer.file_path is not None:
                    path = os.path.abspath(self._importer.file_path)
                    for i in range(self.import_stmt.relative_count - 1):
                        path = os.path.dirname(path)
                    names += self._get_module_names([path])

                    if self._is_relative_import():
                        rel_path = self._importer.get_relative_path() + '/__init__.py'
                        if os.path.exists(rel_path):
                            m = load_module(rel_path)
                            names += m.get_defined_names()
            else:
                if on_import_stmt and isinstance(scope, pr.Module) \
                        and scope.path.endswith('__init__.py'):
                    pkg_path = os.path.dirname(scope.path)
                    paths = self._importer.namespace_packages(pkg_path, self.import_path)
                    names += self._get_module_names([pkg_path] + paths)
                if self.is_just_from:
                    # In the case of an import like `from x.` we don't need to
                    # add all the variables.
                    if ('os',) == self.import_path and not self._is_relative_import():
                        # os.path is a hardcoded exception, because it's a
                        # ``sys.modules`` modification.
                        names.append(self._generate_name('path'))
                    continue
                from jedi.evaluate import finder
                for s, scope_names in finder.get_names_of_scope(self._evaluator,
                                                                scope, include_builtin=False):
                    for n in scope_names:
                        if self.import_stmt.from_ns is None \
                                or self.is_partial_import:
                                # from_ns must be defined to access module
                                # values plus a partial import means that there
                                # is something after the import, which
                                # automatically implies that there must not be
                                # any non-module scope.
                                continue
                        names.append(n)
        return names

    def _generate_name(self, name):
        return helpers.FakeName(name, parent=self.import_stmt)

    def _get_module_names(self, search_path=None):
        """
        Get the names of all modules in the search_path. This means file names
        and not names defined in the files.
        """

        names = []
        # add builtin module names
        if search_path is None:
            names += [self._generate_name(name) for name in sys.builtin_module_names]

        if search_path is None:
            search_path = self._importer.sys_path_with_modifications()
        for module_loader, name, is_pkg in pkgutil.iter_modules(search_path):
            names.append(self._generate_name(name))
        return names

    def _is_nested_import(self):
        """
        This checks for the special case of nested imports, without aliases and
        from statement::

            import foo.bar
        """
        return not self.import_stmt.alias and not self.import_stmt.from_ns \
            and len(self.import_stmt.namespace.names) > 1 \
            and not self.direct_resolve

    def _get_nested_import(self, parent):
        """
        See documentation of `self._is_nested_import`.
        Generates an Import statement, that can be used to fake nested imports.
        """
        i = self.import_stmt
        # This is not an existing Import statement. Therefore, set position to
        # 0 (0 is not a valid line number).
        zero = (0, 0)
        names = [(unicode(name_part), name_part.start_pos)
                 for name_part in i.namespace.names[1:]]
        n = pr.Name(i._sub_module, names, zero, zero, self.import_stmt)
        new = pr.Import(i._sub_module, zero, zero, n)
        new.parent = parent
        debug.dbg('Generated a nested import: %s', new)
        return new

    def _is_relative_import(self):
        return bool(self.import_stmt.relative_count)

    def follow(self, is_goto=False):
        if self._evaluator.recursion_detector.push_stmt(self.import_stmt):
            # check recursion
            return []

        if self.import_path:
            try:
                scope, rest = self._importer.follow_file_system()
            except ModuleNotFound:
                debug.warning('Module not found: %s', self.import_stmt)
                return []

            scopes = [scope]
            scopes += remove_star_imports(self._evaluator, scope)

            # follow the rest of the import (not FS -> classes, functions)
            if len(rest) > 1 or rest and self.is_like_search:
                scopes = []
                if ('os', 'path') == self.import_path[:2] \
                        and not self._is_relative_import():
                    # This is a huge exception, we follow a nested import
                    # ``os.path``, because it's a very important one in Python
                    # that is being achieved by messing with ``sys.modules`` in
                    # ``os``.
                    scopes = self._evaluator.follow_path(iter(rest), [scope], scope)
            elif rest:
                if is_goto:
                    scopes = list(chain.from_iterable(
                        self._evaluator.find_types(s, rest[0], is_goto=True)
                        for s in scopes))
                else:
                    scopes = list(chain.from_iterable(
                        self._evaluator.follow_path(iter(rest), [s], s)
                        for s in scopes))

            if self._is_nested_import():
                scopes.append(self._get_nested_import(scope))
        else:
            scopes = [ImportWrapper.GlobalNamespace]
        debug.dbg('after import: %s', scopes)
        self._evaluator.recursion_detector.pop_stmt()
        return scopes

def get_importer(evaluator, import_path, module, level=0):
    """
    Checks the evaluator caches first, which resembles the ``sys.modules``
    cache and speeds up libraries like ``numpy``.
    """
    if level != 0:
        # Only absolute imports should be cached. Otherwise we have a mess.
        # TODO Maybe calculate the absolute import and save it here?
        return _Importer(evaluator, import_path, module, level)
    try:
        return evaluator.import_cache[import_path]
    except KeyError:
        importer = _Importer(evaluator, import_path, module, level)
        evaluator.import_cache[import_path] = importer
        return importer

class _Importer(object):
    def __init__(self, evaluator, import_path, module, level=0):
        """
        An implementation similar to ``__import__``. Use `follow_file_system`
        to actually follow the imports.

        *level* specifies whether to use absolute or relative imports. 0 (the
        default) means only perform absolute imports. Positive values for level
        indicate the number of parent directories to search relative to the
        directory of the module calling ``__import__()`` (see PEP 328 for the
        details).

        :param import_path: List of namespaces (strings).
        """
        debug.speed('import %s' % (import_path,))
        self._evaluator = evaluator
        self.import_path = import_path
        self.level = level
        self.module = module
        path = module.path
        # TODO abspath
        self.file_path = os.path.dirname(path) if path is not None else None

    def get_relative_path(self):
        path = self.file_path
        for i in range(self.level - 1):
            path = os.path.dirname(path)
        return path

    @memoize_default()
    def sys_path_with_modifications(self):
        # If you edit e.g. gunicorn, there will be imports like this:
        # `from gunicorn import something`. But gunicorn is not in the
        # sys.path. Therefore look if gunicorn is a parent directory, #56.
        in_path = []
        if self.import_path:
            parts = self.file_path.split(os.path.sep)
            for i, p in enumerate(parts):
                if p == self.import_path[0]:
                    new = os.path.sep.join(parts[:i])
                    in_path.append(new)

        return in_path + sys_path.sys_path_with_modifications(self.module)

    def follow(self, evaluator):
        scope, rest = self.follow_file_system()
        if rest:
            # follow the rest of the import (not FS -> classes, functions)
            return evaluator.follow_path(iter(rest), [scope], scope)
        return [scope]

    @memoize_default(NO_DEFAULT)
    def follow_file_system(self):
        if self.file_path:
            sys_path_mod = list(self.sys_path_with_modifications())
            if not self.module.has_explicit_absolute_import:
                # If the module explicitly asks for absolute imports,
                # there's probably a bogus local one.
                sys_path_mod.insert(0, self.file_path)

            # First the sys path is searched normally and if that doesn't
            # succeed, try to search the parent directories, because sometimes
            # Jedi doesn't recognize sys.path modifications (like py.test
            # stuff).
            old_path, temp_path = self.file_path, os.path.dirname(self.file_path)
            while old_path != temp_path:
                sys_path_mod.append(temp_path)
                old_path, temp_path = temp_path, os.path.dirname(temp_path)
        else:
            sys_path_mod = list(sys_path.get_sys_path())

        return self._follow_sys_path(sys_path_mod)

    def namespace_packages(self, found_path, import_path):
        """
        Returns a list of paths of possible ``pkgutil``/``pkg_resources``
        namespaces. If the package is no "namespace package", an empty list is
        returned.
        """
        def follow_path(directories, paths):
            try:
                directory = next(directories)
            except StopIteration:
                return paths
            else:
                deeper_paths = []
                for p in paths:
                    new = os.path.join(p, directory)
                    if os.path.isdir(new) and new != found_path:
                        deeper_paths.append(new)
                return follow_path(directories, deeper_paths)

        with open(os.path.join(found_path, '__init__.py'), 'rb') as f:
            content = common.source_to_unicode(f.read())
            # these are strings that need to be used for namespace packages,
            # the first one is ``pkgutil``, the second ``pkg_resources``.
            options = ('declare_namespace(__name__)', 'extend_path(__path__')
            if options[0] in content or options[1] in content:
                # It is a namespace, now try to find the rest of the modules.
                return follow_path(iter(import_path), sys.path)
        return []

    def _follow_sys_path(self, sys_path):
        """
        Find a module with a path (of the module, like usb.backend.libusb10).
        """
        def follow_str(ns_path, string):
            debug.dbg('follow_module %s %s', ns_path, string)
            path = None
            if ns_path:
                path = ns_path
            elif self.level > 0:  # is a relative import
                path = self.get_relative_path()

            if path is not None:
                importing = find_module(string, [path])
            else:
                debug.dbg('search_module %s %s', string, self.file_path)
                # Override the sys.path. It works only good that way.
                # Injecting the path directly into `find_module` did not work.
                sys.path, temp = sys_path, sys.path
                try:
                    importing = find_module(string)
                finally:
                    sys.path = temp

            return importing

        current_namespace = (None, None, None)
        # now execute those paths
        rest = []
        for i, s in enumerate(self.import_path):
            try:
                current_namespace = follow_str(current_namespace[1], s)
            except ImportError:
                _continue = False
                if self.level >= 1 and len(self.import_path) == 1:
                    # follow `from . import some_variable`
                    rel_path = self.get_relative_path()
                    with common.ignored(ImportError):
                        current_namespace = follow_str(rel_path, '__init__')
                elif current_namespace[2]:  # is a package
                    for n in self.namespace_packages(current_namespace[1],
                                                     self.import_path[:i]):
                        try:
                            current_namespace = follow_str(n, s)
                            if current_namespace[1]:
                                _continue = True
                                break
                        except ImportError:
                            pass

                if not _continue:
                    if current_namespace[1]:
                        rest = self.import_path[i:]
                        break
                    else:
                        raise ModuleNotFound('The module you searched has not been found')

        path = current_namespace[1]
        is_package_directory = current_namespace[2]

        f = None
        if is_package_directory or current_namespace[0]:
            # is a directory module
            if is_package_directory:
                path += '/__init__.py'
                with open(path, 'rb') as f:
                    source = f.read()
            else:
                source = current_namespace[0].read()
                current_namespace[0].close()
            return load_module(path, source), rest
        else:
            return load_module(name=path), rest

def strip_imports(evaluator, scopes):
    """
    Here we strip the imports - they don't get resolved necessarily.
    Really used anymore? Merge with remove_star_imports?
    """
    result = []
    for s in scopes:
        if isinstance(s, pr.Import):
            result += ImportWrapper(evaluator, s).follow()
        else:
            result.append(s)
    return result

@cache.cache_star_import
def remove_star_imports(evaluator, scope, ignored_modules=()):
    """
    Check a module for star imports::

        from module import *

    and follow these modules.
    """
    modules = strip_imports(evaluator, (i for i in scope.get_imports() if i.star))
    new = []
    for m in modules:
        if m not in ignored_modules:
            new += remove_star_imports(evaluator, m, modules)
    modules += new

    # Filter duplicate modules.
    return set(modules)

def load_module(path=None, source=None, name=None):
    def load(source):
        if path is not None and path.endswith('.py'):
            if source is None:
                with open(path, 'rb') as f:
                    source = f.read()
        else:
            return compiled.load_module(path, name)
        p = path or name
        p = fast.FastParser(common.source_to_unicode(source), p)
        cache.save_parser(path, name, p)
        return p.module

    cached = cache.load_parser(path, name)
    return load(source) if cached is None else cached.module

def get_modules_containing_name(mods, name):
    """
    Search a name in the directories of modules.
    """
    def check_python_file(path):
        try:
            return cache.parser_cache[path].parser.module
        except KeyError:
            try:
                return check_fs(path)
            except IOError:
                return None

    def check_fs(path):
        with open(path, 'rb') as f:
            source = source_to_unicode(f.read())
            if name in source:
                return load_module(path, source)

    # skip non python modules
    mods = set(m for m in mods if not isinstance(m, compiled.CompiledObject))
    mod_paths = set()
    for m in mods:
        mod_paths.add(m.path)
        yield m

    if settings.dynamic_params_for_other_modules:
        paths = set(settings.additional_dynamic_modules)
        for p in mod_paths:
            if p is not None:
                d = os.path.dirname(p)
                for entry in os.listdir(d):
                    if entry not in mod_paths:
                        if entry.endswith('.py'):
                            paths.add(d + os.path.sep + entry)

        for p in sorted(paths):
            # make testing easier, sort it - same results on every interpreter
            c = check_python_file(p)
            if c is not None and c not in mods:
                yield c


text:
Added a default value to the *limit* argument of the following commands:
- ***nexpose-get-assets***
- ***nexpose-search-assets***
- ***nexpose-get-sites***


text:
package main

// -----------------------------------------------------------------------------

// CallDef holds function call definition attributes
type CallDef struct {
	Cache uint32                 `json:"cache"` // uint32 : 0 to 4294967295
	Name  *string                `json:"nsp"`
	Proc  *string                `json:"proc"`
	Args  map[string]interface{} `json:"arg"`
	Age   int                    `json:"age"`
	Lang  *string                `json:"lang"`
	TZ    *string                `json:"tz"`
}


text:
/// <reference path='../../typings/browser.d.ts'/>

import * as React from "react";
import * as ReactDOM from "react-dom";
import { createStore } from "redux";
import { Provider } from "react-redux";

import Counter from "./counter";

let store = createStore(
    (state, action) => {
        switch (action.type) {
            case 'INCR':
                return { counter: state.counter + action.by };
            default:
                return state;
        }
    },
    { counter: 0 });

ReactDOM.render(
    <Provider store={store}>
        <Counter />
    </Provider>,
    document.getElementById("content"));


text:
package org.apereo.cas.ticket.support;

import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.annotation.JsonTypeInfo;
import org.apache.commons.lang3.builder.EqualsBuilder;
import org.apache.commons.lang3.builder.HashCodeBuilder;
import org.apereo.cas.ticket.TicketState;

/**
 * AlwaysExpiresExpirationPolicy always answers true when asked if a Ticket is
 * expired.
 *
 * @author Misagh Moayyed
 * @since 4.2
 */
@JsonTypeInfo(use = JsonTypeInfo.Id.CLASS, include = JsonTypeInfo.As.PROPERTY)
public class AlwaysExpiresExpirationPolicy extends AbstractCasExpirationPolicy {

    /**
     * Serializable Unique ID.
     */
    private static final long serialVersionUID = 3836547698242303540L;

    /**
     * Instantiates a new Always expires expiration policy.
     */
    public AlwaysExpiresExpirationPolicy() {
    }

    @Override
    public boolean isExpired(final TicketState ticketState) {
        return true;
    }

    @JsonIgnore
    @Override
    public Long getTimeToLive() {
        return 0L;
    }

    @JsonIgnore
    @Override
    public Long getTimeToIdle() {
        return 0L;
    }

    @Override
    public boolean equals(final Object obj) {
        if (obj == null) {
            return false;
        }
        if (obj == this) {
            return true;
        }
        if (obj.getClass() != getClass()) {
            return false;
        }
        return new EqualsBuilder().isEquals();
    }

    @Override
    public int hashCode() {
        return new HashCodeBuilder().toHashCode();
    }
}


text:
'use strict';

Object.defineProperty(exports, "__esModule", {
    value: true
});
exports.default = checkGitStatus;

var _chalk = require('chalk');

var _chalk2 = _interopRequireDefault(_chalk);

var _isGitClean = require('is-git-clean');

var _isGitClean2 = _interopRequireDefault(_isGitClean);

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }

function checkGitStatus(force) {
    let clean = false;
    let errorMessage = 'Unable to determine if git directory is clean';
    try {
        clean = _isGitClean2.default.sync(process.cwd());
        errorMessage = 'Git directory is not clean';
    } catch (err) {
        if (err && err.stderr && err.stderr.indexOf('Not a git repository') >= 0) {
            clean = true;
        }
    }

    if (!clean) {
        if (force) {
            console.log(`WARNING: ${errorMessage}. Forcibly continuing.`);
        } else {
            console.log(_chalk2.default.red(`\nERROR: ${errorMessage}. Refusing to continue.`));
            console.log('Ensure you have a backup of your tests or commit the latest changes before continuing.');
            console.log('You may use the --force flag to override this safety check.');
            process.exit(1);
        }
    }
}


text:
from ._compat import itervalues

_documents_registry = {}

def get_document(name, module=None):
    if module:
        name = '{0}.{1}'.format(module, name)
    return _documents_registry[name]

def put_document(name, document_cls, module=None):
    if module:
        name = '{0}.{1}'.format(module, name)
    _documents_registry[name] = document_cls

def remove_document(name, module=None):
    if module:
        name = '{0}.{1}'.format(module, name)
    del _documents_registry[name]

def iter_documents():
    return itervalues(_documents_registry)

def clear():
    _documents_registry.clear()


text: Solutions for [LeetCode OJ](https://leetcode.com/).


text:
//
// This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, vJAXB 2.1.10 in JDK 6
// See http://java.sun.com/xml/jaxb
// Any modifications to this file will be lost upon recompilation of the source schema.
// Generated on: 2010.10.30 at 09:30:35 AM EDT
//

package jaxb;

import javax.xml.bind.annotation.XmlEnum;
import javax.xml.bind.annotation.XmlType;

/**
 *
Java class for fx_sampler_filter_common.
 *
 *
The following schema fragment specifies the expected content contained within this class.
 *

 *

 * <simpleType name="fx_sampler_filter_common">
 *   <restriction base="{http://www.w3.org/2001/XMLSchema}NMTOKEN">
 *     <enumeration value="NONE"/>
 *     <enumeration value="NEAREST"/>
 *     <enumeration value="LINEAR"/>
 *     <enumeration value="NEAREST_MIPMAP_NEAREST"/>
 *     <enumeration value="LINEAR_MIPMAP_NEAREST"/>
 *     <enumeration value="NEAREST_MIPMAP_LINEAR"/>
 *     <enumeration value="LINEAR_MIPMAP_LINEAR"/>
 *   </restriction>
 * </simpleType>
 *

 *
 */
@XmlType(name = "fx_sampler_filter_common")
@XmlEnum
public enum FxSamplerFilterCommon {

    NONE,
    NEAREST,
    LINEAR,
    NEAREST_MIPMAP_NEAREST,
    LINEAR_MIPMAP_NEAREST,
    NEAREST_MIPMAP_LINEAR,
    LINEAR_MIPMAP_LINEAR;

    public String value() {
        return name();
    }

    public static FxSamplerFilterCommon fromValue(String v) {
        return valueOf(v);
    }

}


text:
define(['./module'], function (services) {
    'use strict';
    services.factory("AgenciaService",["Restangular",
        function(Restangular){

            var baseUrl = "agencias";

            return {
                crear: function(agencia) {
                    return Restangular.all(baseUrl).post(agencia);
                },
                getAgencia: function(idAgencia) {
                    return Restangular.one(baseUrl+"/"+idAgencia).get();
                }

            }
        }])
});