Fixed version of https://gist.github.com/260184
337751
def humanize_size(number)
      return nil if number.nil?

      if number.to_i < 1024
        unit = number > 1 ? 'Bytes' : 'Byte'
      else
        max_exp  = STORAGE_UNITS.size - 1
        number   = Float(number)
        exponent = (Math.log(number) / Math.log(1024)).to_i # Convert to base 1024
        exponent = max_exp if exponent > max_exp # we need this to avoid overflow for the highest unit
        number  /= 1024**exponent
        unit = STORAGE_UNITS[exponent]
      end

      '%n %u'.gsub(/%n/, number.to_i.to_s).gsub(/%u/, unit)
    end
1313284
function fixBrokenCode(text)
  {
    // make sure we ignore `&shy;` - which gets inserted
    // by the forum's code formatter
    text = text.replace(/\u00AD/g,'');
    // replace quotes that get auto-replaced by Google Docs and other editors
    text = text.replace(/[\u201c\u201d]/g,'"');
    text = text.replace(/[\u2018\u2019]/g,'\'');

    return text;
  }
946190
function githubRepo (options) {
  try {
    const url = options.data.root.package.repository.url
    const match = url.match(/.*?(:\/\/|@)github\.com[/:](.*?)(#.*?)?$/)
    if (match) {
      return match[2].replace(/\.git$/, '')
    } else {
      return null
    }
  } catch (e) {
    // No repositor-url exists
    return null
  }
}
164788
def _download_gist(self):
        """"""
        parts = parse.urlparse(self.url)
        url = "https://gist.github.com" + parts.path + "/raw"
        return self._download_raw(url)
325992
def patch(html, user_content=False):
    
    # FUTURE: Remove this once GitHub API renders task lists
    # https://github.com/isaacs/github/issues/309
    if not user_content:
        html = INCOMPLETE_TASK_RE.sub(INCOMPLETE_TASK_SUB, html)
        html = COMPLETE_TASK_RE.sub(COMPLETE_TASK_SUB, html)

    # FUTURE: Remove this once GitHub API fixes the header bug
    # https://github.com/joeyespo/grip/issues/244
    html = HEADER_PATCH_RE.sub(HEADER_PATCH_SUB, html)

    return html
117599
function calculateVersion(officialRelease, callback) {
    var version = require('./package.json').version;

    if (officialRelease) {
        callback(version);
    } else {
        git.short(function (str) {
            callback(version + '+' + str);
        });
    }
}
490181
def _make_gist(contents, description='', filename='data.geojson'):
    
    ghapi = github3.GitHub()
    files = {filename: {'content': contents}}
    gist = ghapi.create_gist(description, files)

    return gist
428604
function parseVersion(str) {
  var match = /git version ([0-9\.]+)/.exec(str);

  if (match) {
    return match[1];
  } else {
    throw new Error('Unable to parse version response', str);
  }
}
1327125
function conventionalGithubReleaser (auth, changelogOpts, context, gitRawCommitsOpts, parserOpts, writerOpts, userCb) {
  if (!auth) {
    throw new Error('Expected an auth object')
  }

  const promises = []

  const changelogArgs = [changelogOpts, context, gitRawCommitsOpts, parserOpts, writerOpts].map(function (arg) {
    if (typeof arg === 'function') {
      userCb = arg
      return {}
    }
    return arg || {}
  })

  if (!userCb) {
    throw new Error('Expected an callback')
  }

  changelogOpts = changelogArgs[0]
  context = changelogArgs[1]
  gitRawCommitsOpts = changelogArgs[2]
  parserOpts = changelogArgs[3]
  writerOpts = changelogArgs[4]

  changelogOpts = merge({
    transform: transform,
    releaseCount: 1
  }, changelogOpts)

  writerOpts.includeDetails = true

  // ignore the default header partial
  writerOpts.headerPartial = writerOpts.headerPartial || ''

  Q.nfcall(gitSemverTags)
    .then(function (tags) {
      if (!tags || !tags.length) {
        setImmediate(userCb, new Error('No semver tags found'))
        return
      }

      const releaseCount = changelogOpts.releaseCount
      if (releaseCount !== 0) {
        gitRawCommitsOpts = assign({
          from: tags[releaseCount]
        }, gitRawCommitsOpts)
      }

      gitRawCommitsOpts.to = gitRawCommitsOpts.to || tags[0]

      conventionalChangelog(changelogOpts, context, gitRawCommitsOpts, parserOpts, writerOpts)
        .on('error', function (err) {
          userCb(err)
        })
        .pipe(through.obj(function (chunk, enc, cb) {
          if (!chunk.keyCommit || !chunk.keyCommit.version) {
            cb()
            return
          }

          const url = `repos/${context.owner}/${context.repository}/releases`
          const options = {
            endpoint: auth.url,
            body: {
              body: chunk.log,
              draft: changelogOpts.draft || false,
              name: changelogOpts.name || chunk.keyCommit.version,
              prerelease: semver.parse(chunk.keyCommit.version).prerelease.length > 0,
              tag_name: chunk.keyCommit.version,
              target_commitish: changelogOpts.targetCommitish
            }
          }
          debug(`posting %o to the following URL - ${url}`, options)

          // Set auth after debug output so that we don't print auth token to console.
          options.token = auth.token

          promises.push(ghGot(url, options))

          cb()
        }, function () {
          Q.all(promises)
            .then(function (responses) {
              userCb(null, responses)
            })
            .catch(function (err) {
              userCb(err)
            })
        }))
    })
    .catch(function (err) {
      userCb(err)
    })
}
1035423
function gitVersionInfo(baseVer = '0.1.0') {
  const current = new Semver(baseVer);
  const identifier = current.prerelease[0] || 'beta';
  const prompt = [];
  const types = {
    major: 'major',
    minor: 'minor',
    patch: 'patch',
    premajor: 'pre-release major',
    preminor: 'pre-release minor',
    prepatch: 'pre-relase patch',
    prerelease: 'pre-release'
  };

  Object.keys(types).forEach(releaseType => {
    const newVer = Semver.inc(current.version, releaseType, releaseType.startsWith('pre') ? identifier : '');

    prompt.push({
      value: newVer,
      name: `${types[releaseType]} (${newVer})`
    });
  });

  return {
    current: current.version,
    prompt
  };
}
280318
function(args) {
    var mode = (args && args['mode']) || 'update';
    return map(function(code, filename) {
        var lines = code.toString().split("\n");
        var gists = {};
        var currentGist = null;
        var lineNo = 0;
        lines.forEach(function(line) {
            if (line.indexOf("// startgist:") > -1 || line.indexOf("# startgist:") > -1) {
                if (currentGist) {
                    throw new PluginError(PLUGIN_NAME, filename + ":" + lineNo + ": Unexpected startgist: a previous gist was not closed");
                }
                currentGist = {
                    "id": line.split(":")[1].trim(),
                    "filename": line.split(":")[2].trim(),
                    "lines": []
                };
            } else if (line.indexOf("// endgist") > -1 || line.indexOf("# endgist") > -1) {
                if (!currentGist) {
                    throw new PluginError(PLUGIN_NAME, filename + ":" + lineNo + " Unexpected endgist: missing startgist earlier");
                }
                if (!gists[currentGist.id]) {
                    gists[currentGist.id] = {};
                }
                gists[currentGist.id][currentGist.filename] = {
                    'content': leftAlign(currentGist.lines).join("\n")
                };
                currentGist = null;
            } else if (currentGist && line.indexOf("gisthide") == -1) {
                currentGist.lines.push(line);
            }
            lineNo += 1;
        });
        if (currentGist) {
            throw new PluginError(PLUGIN_NAME, "Reached end of file but gist is still open");
        }
        if (mode == 'create') {
            return fs.read(getUserHome() + '/.gistauth', 'b').then(function (auth) {
                return Q.all(Object.keys(gists).map(function(id) {
                    return create(auth, gists[id]);
                }));
            }).done();
        } else if (mode == 'update') {
            return fs.read(getUserHome() + '/.gistauth', 'b').then(function (auth) {
                return Q.all(Object.keys(gists).map(function(id) {
                    return patch(auth, id, gists[id]);
                }));
            }).done();
        } else {
            gutil.log('Gist mock: ', gists);
        }
    });
}
188932
function compareDottedVersion(v1, v2) {
  const parts1 = /([0-9.]+)(.*)$/.exec(v1)
  const parts2 = /([0-9.]+)(.*)$/.exec(v2)
  if (parts1 != null && parts2 != null) {
    const numbers1 = parts1[1]
    const numbers2 = parts2[1]
    const distinguisher1 = parts1[2]
    const distinguisher2 = parts2[2]
    const numlist1 = numbers1.split('.').map(e => +e)
    const numlist2 = numbers2.split('.').map(e => +e)
    const cmp = listCompare(numlist1, numlist2)
    if (cmp !== 0) {
      return cmp
    } else {
      return distinguisher1 < distinguisher2
        ? -1
        : distinguisher1 > distinguisher2
        ? 1
        : 0
    }
  }
  return v1 < v2 ? -1 : v1 > v2 ? 1 : 0
}
1296403
function () {
		var version = 0;

		if ( this.chrome ) {
			version = navigator.userAgent.replace( /(.*chrome\/|safari.*)/gi, "" );
		}
		else if ( this.firefox ) {
			version = navigator.userAgent.replace( /(.*firefox\/)/gi, "" );
		}
		else if ( this.ie ) {
			version = navigator.userAgent.replace(/(.*msie|;.*)/gi, "");
		}
		else if ( this.opera ) {
			version = navigator.userAgent.replace( /(.*version\/|\(.*)/gi, "" );
		}
		else if ( this.safari ) {
			version = navigator.userAgent.replace( /(.*version\/|safari.*)/gi, "" );
		}
		else {
			version = navigator.appVersion || "0";
		}

		version = number.parse( string.trim( version ) );

		if ( isNaN( version ) ) {
			version = 0;
		}

		if ( this.ie && document.documentMode && document.documentMode < version ) {
			version = document.documentMode;
		}

		return version;
	}
1194410
function ensureGagarinVersionsMatch(pathToApp, verbose) {

  var pathToMeteorPackages = path.join(pathToApp, '.meteor', 'packages');
  var nodeModuleVersion    = require('../../package.json').version;

  return new Promise(function (resolve, reject) {

    utils.getGagarinPackageVersion(pathToApp).then(function (packageVersion) {

      if (packageVersion === nodeModuleVersion) {
        logs.system("node module and smart package versions match, " + packageVersion);
        return resolve();
      }

      tools.getReleaseVersion(pathToApp).then(function (meteorReleaseVersion) {

        if (meteorReleaseVersion < "0.9.0") {
          // really, we can do nothing about package version
          // without a decent package management system
          logs.system("meteor version is too old to automatically fix package version");
          return resolve();
        }

        logs.system("meteor add anti:gagarin@=" + nodeModuleVersion);

        var meteor = spawn('meteor', [ 'add', 'anti:gagarin@=' + nodeModuleVersion ], {

          stdio: verbose ? 'inherit' : 'ignore', cwd: pathToApp
        });

        /*
        meteor.stdout.on('data', function (data) {
          if (!verbose) {
            return;
          }
          process.stdout.write(chalk.gray(stripAnsi(data)));
        });
        */

        meteor.on('error', reject);

        meteor.on('exit', function (code) {
          if (code > 0) {
            return reject(new Error('meteor exited with code ' + code));
          }
          logs.system("anti:gagarin is now in version " + nodeModuleVersion);
          resolve();
        });

      }).catch(reject);

    }).catch(reject);

  }); // Promise
}
1063130
function(str){
        var versionArray = str.split(",");//replace with regex
        return {
            "raw":str,
            "major":parseInt(versionArray[0].split(" ")[1], 10),
            "minor":parseInt(versionArray[1], 10),
            "revision":parseInt(versionArray[2], 10),
            "revisionStr":versionArray[2]
        };
    }
866139
function glitch ( params ) {
	params = sanitizeInput( params );

	let inputFn;
	let outputFn;

	const worker = new Worker( URL.createObjectURL(new Blob(["function isImageData ( imageData ) {\n\treturn (\n\t\timageData && \n\t\ttypeof imageData.width === 'number' &&\n\t\ttypeof imageData.height === 'number' &&\n\t\timageData.data &&\n\t\ttypeof imageData.data.length === 'number' &&\n\t\ttypeof imageData.data === 'object'\n\t);\n}\n\nconst base64Chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/';\nconst base64Map = base64Chars.split( '' );\nconst reversedBase64Map = { };\n\nbase64Map.forEach( ( val, key ) => { reversedBase64Map[val] = key; } );\n\nvar maps = {\n\tbase64Map,\n\treversedBase64Map\n};\n\nconst reversedBase64Map$1 = maps.reversedBase64Map;\n\n// https://github.com/mutaphysis/smackmyglitchupjs/blob/master/glitch.html\n// base64 is 2^6, byte is 2^8, every 4 base64 values create three bytes\nfunction base64ToByteArray ( base64URL ) {\t\n\tconst result = [ ];\n\tlet prev;\n\n\tconst srcURL = base64URL.replace( 'data:image/jpeg;base64,', '' );\n\n\tfor ( var i = 0, len = srcURL.length; i < len; i++ ) {\n\t\tconst char = srcURL[ i ];\n\t\tconst currentChar = reversedBase64Map$1[ srcURL[ i ] ];\n\t\tconst digitNum = i % 4;\n\n\t\tswitch ( digitNum ) {\n\t\t\t// case 0: first digit - do nothing, not enough info to work with\n\t\t\tcase 1: // second digit\n\t\t\t\tresult.push( prev << 2 | currentChar >> 4 );\n\t\t\t\tbreak;\n\t\t\t\n\t\t\tcase 2: // third digit\n\t\t\t\tresult.push( ( prev & 0x0f ) << 4 | currentChar >> 2 );\n\t\t\t\tbreak;\n\t\t\t\n\t\t\tcase 3: // fourth digit\n\t\t\t\tresult.push( ( prev & 3 ) << 6 | currentChar );\n\t\t\t\tbreak;\n\t\t}\n\n\t\tprev = currentChar;\n\t}\n\n\treturn result;\n}\n\n// http://stackoverflow.com/a/10424014/229189\n\nfunction jpgHeaderLength ( byteArr ) {\n\tlet result = 417;\n\n\t// https://en.wikipedia.org/wiki/JPEG#Syntax_and_structure\n\t// looks for the first occurence of 0xFF, 0xDA in the byteArray\n\t// which is the start of scan\n\tfor ( let i = 0, len = byteArr.length; i < len; i++ ) {\n\t\tif ( byteArr[i] === 0xFF && byteArr[i + 1] === 0xDA ) {\n\t\t\tresult = i + 2;\n\t\t\tbreak;\n\t\t}\n\t}\n\n\treturn result;\n}\n\nfunction glitchByteArray ( byteArray, seed, amount, iterationCount ) {\n\tconst headerLength = jpgHeaderLength( byteArray );\n\tconst maxIndex = byteArray.length - headerLength - 4;\n\n\tconst amountPercent = amount / 100;\n\tconst seedPercent   = seed / 100;\n\n\tfor ( var iterationIndex = 0; iterationIndex < iterationCount; iterationIndex++ ) {\n\t\tconst minPixelIndex = ( maxIndex / iterationCount * iterationIndex ) | 0;\n\t\tconst maxPixelIndex = ( maxIndex / iterationCount * ( iterationIndex + 1 ) ) | 0;\n\t\t\n\t\tconst delta = maxPixelIndex - minPixelIndex;\n\t\tlet pixelIndex = ( minPixelIndex + delta * seedPercent ) | 0;\n\n\t\tif ( pixelIndex > maxIndex ) {\n\t\t\tpixelIndex = maxIndex;\n\t\t}\n\n\t\tconst indexInByteArray = ~~( headerLength + pixelIndex );\n\n\t\tbyteArray[indexInByteArray] = ~~( amountPercent * 256 );\n\t}\n\n\treturn byteArray;\n}\n\nconst base64Map$1 = maps.base64Map;\n\nfunction byteArrayToBase64 ( byteArray ) {\n\tconst result = [ 'data:image/jpeg;base64,' ];\n\tlet byteNum;\n\tlet previousByte;\n\n\tfor ( let i = 0, len = byteArray.length; i < len; i++ ) {\n\t\tconst currentByte = byteArray[i];\n\t\tbyteNum = i % 3;\n\n\t\tswitch ( byteNum ) {\n\t\t\tcase 0: // first byte\n\t\t\t\tresult.push( base64Map$1[ currentByte >> 2 ] );\n\t\t\t\tbreak;\n\t\t\tcase 1: // second byte\n\t\t\t\tresult.push( base64Map$1[( previousByte & 3 ) << 4 | ( currentByte >> 4 )] );\n\t\t\t\tbreak;\n\t\t\tcase 2: // third byte\n\t\t\t\tresult.push( base64Map$1[( previousByte & 0x0f ) << 2 | ( currentByte >> 6 )] );\n\t\t\t\tresult.push( base64Map$1[currentByte & 0x3f] );\n\t\t\t\tbreak;\n\t\t}\n\n\t\tpreviousByte = currentByte;\n\t}\n\n\tif ( byteNum === 0 ) {\n\t\tresult.push( base64Map$1[( previousByte & 3 ) << 4] );\n\t\tresult.push( '==' );\n\t} else {\n\t\tif ( byteNum === 1 ) {\n\t\t\tresult.push( base64Map$1[( previousByte & 0x0f ) << 2] );\n\t\t\tresult.push( '=' );\n\t\t}\n\t}\n\n\treturn result.join( '' );\n}\n\nfunction glitchImageData ( imageData, base64URL, params ) {\n\tif ( isImageData( imageData ) ) {\n\t\tconst byteArray = base64ToByteArray( base64URL );\n\t\tconst glitchedByteArray = glitchByteArray( byteArray, params.seed, params.amount, params.iterations );\n\t\tconst glitchedBase64URL = byteArrayToBase64( glitchedByteArray );\n\t\treturn glitchedBase64URL;\n\t} else {\n\t\tthrow new Error( 'glitchImageData: imageData seems to be corrupt.' );\n\t\treturn;\n\t}\n}\n\nonmessage = msg => {\n\tconst imageData = msg.data.imageData;\n\tconst params = msg.data.params;\n\tconst base64URL = msg.data.base64URL;\n\n\tif ( imageData && base64URL && params ) {\n\t\ttry {\n\t\t\t// phantomjs seems to have some memory loss so we need to make sure\n\t\t\tif ( typeof imageData.width === 'undefined' && typeof msg.data.imageDataWidth === 'number' ) {\n\t\t\t\timageData.width = msg.data.imageDataWidth;\n\t\t\t}\n\n\t\t\tif ( typeof imageData.height === 'undefined' && typeof msg.data.imageDataHeight === 'number' ) {\n\t\t\t\timageData.height = msg.data.imageDataHeight;\n\t\t\t}\n\n\t\t\tconst glitchedBase64URL = glitchImageData( imageData, base64URL, params );\n\t\t\tsuccess( glitchedBase64URL );\n\n\t\t} catch ( err ) {\n\t\t\tfail( err );\n\t\t}\n\n\t} else {\n\t\tif ( msg.data.imageData ) {\n\t\t\tfail( 'Parameters are missing.' );\n\t\t} else {\n\t\t\tfail( 'ImageData is missing.' );\n\t\t}\n\t}\n\t\n\tself.close();\n};\n\nfunction fail ( err ) {\n\tself.postMessage( { err: err.message || err } );\n}\n\nfunction success ( base64URL ) {\n\tself.postMessage( { base64URL: base64URL } );\n}\n"],{type:'text/javascript'})) );
	
	const api = { getParams, getInput, getOutput };
	const inputMethods = { fromImageData, fromImage };
	const outputMethods = { toImage, toDataURL, toImageData };

	function getParams () {
		return params;
	}

	function getInput () {
		const result = objectAssign( { }, api );

		if ( ! inputFn ) {
			objectAssign( result, inputMethods );
		}

		return result;
	}

	function getOutput () {
		const result = objectAssign( { }, api );

		if ( ! outputFn ) {
			objectAssign( result, outputMethods );
		}

		return result;
	}

	function noTransform ( x ) { return x; }

	function fromImage ( inputOptions ) { return setInput( imageToImageData, inputOptions ); }
	function fromImageData ( inputOptions ) { return setInput( noTransform, inputOptions ); }

	function toDataURL ( outputOptions ) { return setOutput( noTransform ); }
	function toImage ( outputOptions ) { return setOutput( base64URLToImage, outputOptions, true ); }
	function toImageData ( outputOptions ) { return setOutput( base64URLToImageData, outputOptions, true ); }

	function setInput ( fn, inputOptions, canResolve ) {		
		inputFn = () => {
			return new Promise( ( resolve, reject ) => {
				if ( canResolve ) {
					fn( inputOptions, resolve, reject );
				} else {
					if ( fn === noTransform ) {
						resolve( inputOptions );
					} else {
						try {
							resolve( fn( inputOptions, resolve, reject ) );
						} catch ( err ) {
							reject( err );
						}
					}
				}
			} );
		};

		if ( isReady() ) {
			return getResult();
		} else {
			return getOutput();
		}
	}

	function setOutput ( fn, outputOptions, canResolve ) {
		outputFn = base64URL => {
			return new Promise( ( resolve, reject ) => {
				if ( canResolve ) {
					fn( base64URL, outputOptions, resolve, reject );
				} else {
					if ( fn === noTransform ) {
						resolve( base64URL );
					} else {
						fn( base64URL, outputOptions )
							.then( resolve, reject );
					}
				}
			} );
		};

		if ( isReady() ) {
			return getResult();
		} else {
			return getInput();
		}
	}

	function isReady () {
		return inputFn && outputFn;
	}

	function getResult () {
		return new Promise( ( resolve, reject ) => {
			inputFn()
				.then( imageData => {
					return glitch( imageData, params );
				}, reject )
				.then( base64URL => {
					outputFn( base64URL )
						.then( resolve, reject );
				}, reject );
		} );
	}

	function glitch ( imageData, params ) {
		return new Promise( ( resolve, reject ) => {
			imageDataToBase64( imageData, params.quality )
				.then( base64URL => {
					return glitchInWorker( imageData, base64URL, params );
				}, reject )
				.then( resolve, reject );
		} );
	}

	function glitchInWorker ( imageData, base64URL, params ) {
		return new Promise( ( resolve, reject ) => {
			worker.addEventListener( 'message', event => {
				if ( event.data && event.data.base64URL ) {
					resolve( event.data.base64URL );
				} else {
					if ( event.data && event.data.err ) {
						reject( event.data.err );
					} else {
						reject( event );
					}
				}
			} );

			worker.postMessage( {
				params: params,
				base64URL: base64URL,
				imageData: imageData,

				// phantomjs tends to forget about those two
				// so we send them separately
				imageDataWidth: imageData.width,
				imageDataHeight: imageData.height
			} );
		} );
	}

	return getInput();
}
770871
function gitHubRelease() {
			rbot.log.info('Releasing ' + commit.versionTag + ' via ' + options.gitHostname);
			// GitHub Release API will not remove the tag when removing a
			// release
			github.releaseAndUploadAsset(distAssets, coopt.regexLines, commit, tmpltData.name, chgLogRtn
					|| commit.message, options, rollCall, rollbackTag, function() {
				rollCall.then(publish);
			});
		}