text:
<?php
# @author Jesus A. Domingo
# @license MIT <http://noodlehaus.mit-license.org>

# config settings
function config($name, $info = null) {

  $data = &$GLOBALS['noodlehaus\dispatch']['config'];

  if (func_num_args() === 1) {

    # value fetch
    if (is_string($name)) {
      return isset($data[$name]) ? $data[$name] : null;
    }

    # multi-key/nested value setting
    if (is_array($name)) {

      $k = array_keys($name);
      $n = count($k);

      if (count(array_filter($k, 'is_string')) == $n) {
        $data = array_replace_recursive($data, $name);
        return;
      }

      throw new InvalidArgumentException(
        "Associative array expected as first argument",
        500
      );
    }
  }

  return ($data[$name] = $info);
}

# wrapper for htmlentities()
function ent() {
  return call_user_func_array('htmlentities', func_get_args());
}

# wrapper for urlencode()
function url($str) {
  return urlencode($str);
}

# php template loader
function phtml($__n, $__v = [], $__l = 'layout') {

  # if we have templates set, use it as view base path
  if (($__d = config('templates')) !== null) {
    $__n = "{$__d}/{$__n}";
  }

  # extract locals (__v), require template (__n)
  extract($__v, EXTR_SKIP);
  ob_start();
  require "{$__n}.phtml";
  $__b = ob_get_clean();

  # if we have a layout file, render it
  if (!empty($__l) && is_string($__l)) {
    $__b = phtml($__l, ['body' => $__b] + $__v, null);
  }

  return $__b;
}

# returns hash containing args as keys, mapped to '' as values
function blanks() {
  return array_fill_keys(func_get_args(), '');
}

# returns the best-guess remote address
function ip() {

  if (isset($_SERVER['HTTP_CLIENT_IP'])) {
    return $_SERVER['HTTP_CLIENT_IP'];
  }

  if (isset($_SERVER['HTTP_X_FORWARDED_FOR'])) {
    return $_SERVER['HTTP_X_FORWARDED_FOR'];
  }

  return $_SERVER['REMOTE_ADDR'];
}

# in-request store for values
function stash($name = null, $value = null) {

  $data = &$GLOBALS['noodlehaus\dispatch']['stash'];
  $argc = func_num_args();

  # value fetch
  if ($argc === 1) {
    return isset($data[$name]) ? $data[$name] : null;
  }

  # stash reset
  if ($argc === 0) {
    return ($data = []);
  }

  # value assignment
  return ($data[$name] = $value);
}

# returns the value for an http request header, or sets an http
# response header (maps to php's header function)
function headers() {

  $headers = &$GLOBALS['noodlehaus\dispatch']['request_headers'];

  $argc = func_num_args();
  $argv = func_get_args();

  # error case
  if ($argc < 1) {
    throw new BadFunctionCallException(
      'Invalid number of arguments.',
      500
    );
  }

  # fetch case
  if ($argc === 1) {

    # first call, prime it
    if (!count($headers)) {

      # if we're not in CLI, use it
      if (function_exists('getallheaders')) {
        $headers = array_change_key_case(getallheaders());
      } else {

        # manual header extraction (CLI + test)
        $special = ['CONTENT_LENGTH', 'CONTENT_MD5', 'CONTENT_TYPE'];

        # get the rest of the headers out
        foreach ($_SERVER as $name => $data) {
          if (0 === strpos($name, 'HTTP_')) {
            $name = strtolower(str_replace('_', '-', substr($name, 5)));
            $headers[$name] = $data;
          } else if (in_array($name, $special)) {
            $name = strtolower(str_replace('_', '-', $name));
            $headers[$name] = $data;
          }
        }
      }
    }

    # normalize the input then try to fetch
    $name = strtolower(array_shift($argv));

    return isset($headers[$name]) ? $headers[$name] : null;
  }

  # remove first item, replace new head with name + value
  $argv[0] = array_shift($argv).': '.$argv[0];

  # header set call, forward it to header()
  return call_user_func_array('header', $argv);
}

# accessor for $_COOKIE when fetching values, or maps directly
# to setcookie() when setting values.
function cookies() {

  $argc = func_num_args();
  $argv = func_get_args();

  # cookie fetch, get from $_COOKIE, or null
  if ($argc == 1) {
    return isset($_COOKIE[$argv[0]]) ? $_COOKIE[$argv[0]] : null;
  }

  # set, just map to setcookie()
  return call_user_func_array('setcookie', $argv);
}

# accessor for $_SESSION
function session($name, $value = null) {

  # session var set
  if (func_num_args() == 2) {
    return ($_SESSION[$name] = $value);
  }

  # session var get
  return isset($_SESSION[$name]) ? $_SESSION[$name] : null;
}

# accessor for $_FILES, also consolidates array file uploads, but when using
# the files, be sure to use either is_uploaded_file() or move_uploaded_file()
# to ensure validity of file targets
function attachments($name) {

  static $cache = [];

  # return cached copy
  if (isset($cache[$name])) {
    return $cache[$name];
  }

  if (!isset($_FILES[$name])) {
    return null;
  }

  # single-file attachment (no need to cache)
  if (!is_array($_FILES[$name]['name'])) {
    return $_FILES[$name];
  }

  # attachment is an array
  $result = [];

  # consolidate file info
  foreach ($_FILES[$name] as $k1 => $v1)
    foreach ($v1 as $k2 => $v2)
      $result[$k2][$k1] = $v2;

  # cache and return array uploads
  return ($cache[$name] = $result);
}

# read in raw request body
function input($load = false, $pipe = 'php://input') {

  static $cache = null;

  # if called before, just return previous data
  if ($cache) {
    return $cache;
  }

  # do a best guess
  $content_type = (
    isset($_SERVER['HTTP_CONTENT_TYPE']) ?
    $_SERVER['HTTP_CONTENT_TYPE'] :
    $_SERVER['CONTENT_TYPE']
  );

  # try to load everything
  if ($load) {

    $content = file_get_contents($pipe);
    $content_type = preg_split('/ ?; ?/', $content_type);

    # type-content tuple
    return [$content_type, $content];
  }

  # create a temp file with the data
  $path = tempnam(sys_get_temp_dir(), 'disp-');
  $temp = fopen($path, 'w');
  $data = fopen($pipe, 'r');

  stream_copy_to_stream($data, $temp);

  fclose($temp);
  fclose($data);

  # type-path tuple
  return [$content_type, $path];
}

# prints out no-cache headers
function nocache() {

  $stamp = gmdate('D, d M Y H:i:s', $_SERVER['REQUEST_TIME']).' GMT';

  # dump no-cache headers
  header('Expires: Tue, 13 Mar 1979 18:00:00 GMT');
  header('Last-Modified: '.$stamp);
  header('Cache-Control: no-store, no-cache, must-revalidate');
  header('Cache-Control: post-check=0, pre-check=0', false);
  header('Pragma: no-cache');
}

# maps directly to json_encode, but renders JSON headers as well
function json() {

  $json = call_user_func_array('json_encode', func_get_args());
  $err = json_last_error();

  # trigger a user error for failed encodings
  if ($err !== JSON_ERROR_NONE) {
    throw new RuntimeException(
      "JSON encoding failed [{$err}].",
      500
    );
  }

  header('Content-type: application/json');
  print $json;
}

# shortcut for http_response_code()
function status($code) {
  return http_response_code($code);
}

# shortcut for dumping a redirect header (no longer exits)
function redirect($path, $code = 302, $halt = false) {
  header("Location: {$path}", true, $code);
  $halt && exit;
}

# function for mapping actions to routes
function map() {

  $argv = func_get_args();
  $data = &$GLOBALS['noodlehaus\dispatch']['routes'];

  # try to figure out how we were called
  switch (count($argv)) {

    # complete params (method, path, handler)
    case 3:
      foreach ((array) $argv[0] as $verb) {
        $data['explicit'][strtoupper($verb)][] = [
          '/'.trim($argv[1], '/'),
          $argv[2]
        ];
      }
      break;

    # either (path, handler) or (code, handler)
    case 2:
      $argv[0] = (array) $argv[0];
      if (ctype_digit($argv[0][0])) {
        foreach ($argv[0] as $code)
          $data['errors'][intval($code)] = $argv[1];
      } else {
        foreach ($argv[0] as $path)
          $data['any'][] = ['/'.trim($path, '/'), $argv[1]];
      }
      break;

    # any method and any path (just one for this, replace ref)
    case 1:
      $data['all'] = $argv[0];
      break;

    # everything else
    default:
      throw new BadFunctionCallException(
        'Invalid number of arguments.',
        500
      );
  }
}

# hooks actions to route symbols
function hook($name, $func) {
  $GLOBALS['noodlehaus\dispatch']['routes']['hooks'][$name] = $func;
}

# triggers an HTTP error code and invokes any mapped error handlers
function error() {

  $argc = func_num_args();
  $argv = func_get_args();

  if (!$argc) {
    throw new BadFunctionCallException(
      'Invalid number of arguments.',
      500
    );
  }

  $code = $argv[0];
  $data = &$GLOBALS['noodlehaus\dispatch']['routes'];

  $func = (
    isset($data['errors'][$code]) ?
    $data['errors'][$code] :
    function ($code) { return http_response_code($code); }
  );

  http_response_code($code);

  return call_user_func_array($func, $argv);
}

# dispatches the current request against our handlers/actions
function dispatch() {

  $argv = func_get_args();
  $data = &$GLOBALS['noodlehaus\dispatch']['routes'];

  $path = parse_url($_SERVER['REQUEST_URI'], PHP_URL_PATH);
  $path = trim($path, '/');

  # strip url from request URI
  if ($base = config('url')) {
    $base = trim(parse_url($base, PHP_URL_PATH), '/');
    $path = preg_replace('@^'.preg_quote($base).'@', '', $path);
  }

  # if no rewrite, strip router file from request URI
  if ($stub = config('router')) {
    $path = preg_replace(
      '@^/?'.preg_quote(trim($stub, '/')).'@i',
      '',
      $path
    );
  }

  $path = trim($path, '/');
  $verb = strtoupper($_SERVER['REQUEST_METHOD']);

  # for POST requests, check for method override header or _method
  if ($verb == 'POST') {
    if (isset($_SERVER['HTTP_X_HTTP_METHOD_OVERRIDE'])) {
      $verb = strtoupper($_SERVER['HTTP_X_HTTP_METHOD_OVERRIDE']);
    } else {
      $verb = isset($_POST['_method']) ? strtoupper($_POST['_method']) : $verb;
    }
  }

  # set any mapping as base, then append exp_mapping if any
  $maps = $data['any'];
  if (isset($data['explicit'][$verb])) {
    $maps = array_merge($data['explicit'][$verb], $maps);
  }

  $rexp = null;
  $func = null;
  $vals = null;

  # replace named params (support regex formats)
  $rxcb = function ($matches) {
    if (isset($matches[3])) {
      return "(?<{$matches[1]}>{$matches[3]})";
    }
    return "(?<{$matches[1]}>[^/]+)";
  };

  # try to see if we have any matching route
  foreach ($maps as $temp) {

    list($rexp, $call) = $temp;

    $rexp = trim($rexp, '/');
    $rexp = preg_replace_callback('@\{([^:]+)(:(.+))?\}@U', $rxcb, $rexp);

    if (!preg_match('@^'.$rexp.'$@', $path, $vals)) {
      continue;
    }

    $func = $call;
    break;
  }

  # valid handler, try to parse out route symbol values
  if ($func && is_callable($func)) {

    # remove top group from vals
    array_shift($vals);

    # extract route symbols and run the hook()s
    if ($vals) {

      # extract any route symbol values
      $toks = array_filter(array_keys($vals), 'is_string');
      $vals = array_map('urldecode', array_intersect_key(
        $vals,
        array_flip($toks)
      ));

      # if we have symbol hooks, run them
      if (count($data['hooks'])) {

        foreach ($vals as $key => $val) {

          if (!isset($data['hooks'][$key])) {
            continue;
          }

          $hook = $data['hooks'][$key];

          $vals[$key] = call_user_func_array(
            $hook,
            array_merge((array) $val, $argv)
          );
        }
      }

      # insert symbol values before dispatch() args
      array_unshift($argv, $vals);
    }

  } else {

    # no matching handler, try to use 'all', or 404
    if (is_callable($data['all'])) {
      $func = $data['all'];
    } else {
      $func = 'error';
      array_unshift($argv, 404);
    }

  }

  return call_user_func_array($func, $argv);
}

# state (routes, handlers, etc)
$GLOBALS['noodlehaus\dispatch'] = [
  'config' => [],
  'stash' => [],
  'request_headers' => [],
  'routes' => [
    'all' => null,
    'any' => [],
    'hooks' => [],
    'explicit' => [],
    'errors' => []
  ]
];


text:
package memorymanagement;

// The FunctionArrayMemory which will provide a way to manage the memory of java Lambdas.
// See ByteArrayMemory for applications.

public final class FunctionArrayMemory {

	// encapsulate data access behind functions for value safety.

	private static byte _1 = 1;
	private static byte _2 = 2;
	private static byte _3= 3;
	private static byte _4 = 4;
	private static byte _5 = 5;
	private static byte _6 = 6;
	private static byte _7 = 7;
	private static byte _8 = 8;
	private static byte _9 = 9;
	private static byte _10 = 10;
	private static byte _11 = 11;
	private static byte _12 = 12;
	private static byte _13 = 13;
	private static byte _14 = 14;
	private static byte _15 = 15;
	private static byte _16 = 16;

	private Object[] objects = new Object[Integer.MAX_VALUE];

	static public class Ref{
		private int ref;
		public Ref(int offsetReference){
			ref = offsetReference;
		}
	}

	public int alloc(int size){
		int sizePlus1 = size++;
		int freeSlots = 0;
		int start = 0;
		int end = 0;
		for (int i=0;i<Integer.MAX_VALUE;++i){
			if (objects[i]!=null){
				freeSlots++;
				if (freeSlots==sizePlus1){
					end = i;
					objects[start]=new Ref(end);
					return start;
				}
			} else {
				freeSlots = 0;
				start = i;
			}
		}
		throw new IllegalStateException("cannot alloc, not enough space");
	}

	public void free(int offsetReference){
		Object o = objects[offsetReference];
		if (o instanceof Ref){
			Ref r = (Ref)o;
			for (int i=1;i<=r.ref;++i){
				free(offsetReference+i);
			}
		}
		objects[offsetReference] = null;
	}

	public <T> void set(int offsetReference, int fieldId, Class<T> clazz, T object){
		if (!clazz.isInstance(object)){
			throw new IllegalStateException("not expected instance");
		}
		objects[offsetReference+fieldId] = object;
	}

	public <T> T get(int offsetReference, int fieldId, Class<T> clazz){
		return (T) objects[offsetReference+fieldId];
	}

}

redpajama_set_name: RedPajamaGithub


text:
package prob057.insert.interval;

import utils.interval.Interval;

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

/**
 *  Modified by yanya04 on 5/16/2018.
 */
public class Solution {

    /*
      [1,2]     [3,5]   [6,8]
              [   ]
    */
    public List<Interval> insert(List<Interval> intervals, Interval newInterval) {
        List<Interval> res = new ArrayList<>();
        int index = 0;
        // add before
        while(index < intervals.size() && intervals.get(index).end < newInterval.start) res.add(intervals.get(index ++));

        int start = newInterval.start, end = newInterval.end;
        while(index < intervals.size() && intervals.get(index).start <= newInterval.end ){
            start = Math.min(intervals.get(index).start, start);
            end = Math.max(intervals.get(index).end, end);
            index ++;
        }
        res.add(new Interval(start, end));
        while(index < intervals.size()) res.add(intervals.get(index ++));
        return res;
    }
}


text:
package de.johmat.myjojox.utils.log.entryprocessors;

import de.johmat.myjojox.utils.log.ILogPostEntryProcessor;
import de.johmat.myjojox.utils.log.LogEntry;

/**
 *
 * @author MyJojoX
 *
 * @version 1.0
 */
public class LogTagPostProcessor implements ILogPostEntryProcessor {

	@Override
	public String[] process(String in, LogEntry entry) {
		return new String[] {"" + entry.getLvl().getTag() + " " + in};
	}

}


text:
<project name="Google FeedServer" default="server" basedir=".">

  <property file="build.properties"/>
  <property file="conf/database/dbConfig.properties"/>

  <property name="app.name" value="feedserver"/>
  <property name="build.home" value="${basedir}/build"/>
  <property name="dist.home" value="${basedir}/dist"/>
  <property name="src.home" value="${basedir}/src/java"/>
  <property name="conf.home" value="${basedir}/conf"/>
  <property name="web.home" value="${basedir}/web"/>
  <property name="lib.home" value="${basedir}/lib"/>
  <property name="resources" value="resources" />
  <property name="log4jConfigFile" value="${resources}/clientTool/log4j.properties" />

  <!-- Client Properties -->
  <property name="client.version" value="2.0"/>
  <property name="client.jarfile"
      value="${dist.home}/google-feedserver-java-client-${client.version}.jar"/>

  <property name="client.tools.version" value="2.0.6"/>
  <property name="clienttools.zip" value="${dist.home}/google-feedserver-clienttools-${client.tools.version}.zip"/>
  <property name="clienttools.temp.dir" value="${dist.home}/temp" />
  <property name="fsct.scripts.dir" value="${resources}/clientTool" />
  <property name="fsct.temp.dir" value="${dist.home}/fsct" />
  <!-- End Client Properties -->

  <path id="compile.resources">
    <fileset dir="src/resources" includes="**/*" />
  </path>

  <path id="classpath">
    <fileset dir="${lib.home}" includes="**/*.jar"/>
  </path>

  <target name="server" depends="jetty"
     description="The default Jetty-based build, with conditional Tomcat."/>

  <target name="jetty" description="Compile and build jar file">
    <antcall target="jar"/>
  </target>

  <target name="clean" description="Delete old build and dist directories">
    <delete dir="${build.home}"/>
    <delete dir="${dist.home}"/>
  </target>

  <target name="compile" description="Compile Java sources">
    <mkdir dir="${build.home}"/>
    <javac srcdir="${src.home}" destdir="${build.home}" classpathref="classpath"
        debug="true" debuglevel="lines,vars,source">
    </javac>
  </target>

  <target name="javadoc" depends="compile"
   description="Create Javadoc API documentation">
    <mkdir dir="${dist.home}/docs/api"/>
    <javadoc sourcepath="${src.home}" destdir="${dist.home}/docs/api" classpathref="classpath"
        packagenames="*">
    </javadoc>
  </target>

  <!-- Client targets -->

  <target name="client" depends="compile">
    <tstamp/>
    <mkdir dir="${dist.home}"/>
    <jar jarfile="${client.jarfile}">
      <fileset dir="${build.home}">
        <include name="com/google/feedserver/client/**"/>
        <include name="com/google/feedserver/tools/**"/>
        <include name="com/google/feedserver/util/**"/>
      </fileset>
      <manifest>
        <attribute name="Implementation-Title" value="Google Feedserver Client"/>
        <attribute name="Implementation-Version" value="${version} ${TODAY}"/>
        <attribute name="Implementation-Vendor" value="Google"/>
        <attribute name="Main-Class" value="com.google.feedserver.tools.FeedServerClientTool"/>
      </manifest>
    </jar>
  </target>

  <target name="client-source-distro" depends="client">
    <mkdir dir="${dist.home}"/>
    <tar destfile="${dist.home}/google-feedserver-java-client-${client.version}-src.tar.gz"
        longfile="gnu" compression="gzip" excludes="tmp/**, third-party/*/docs/**">
      <tarfileset dir=".">
        <include name="build.xml"/>
        <include name="src/java/com/google/feedserver/client/**"/>
        <include name="src/java/com/google/feedserver/tools/**"/>
        <include name="src/java/com/google/feedserver/util/**"/>
        <include name="lib/commons-*/**"/>
        <include name="lib/guice-*/**"/>
        <include name="lib/gdata-*/**"/>
      </tarfileset>
    </tar>
  </target>

  <!-- Start of Jetty targets -->
  <target name="jar" depends="compile" description="Build a jar file for Jetty">
    <mkdir dir="${dist.home}"/>
    <jar destfile="${dist.home}/feedserver.jar" basedir="${build.home}">
      <manifest>
        <attribute name="Main-Class"
            value="com.google.feedserver.server.jetty.StartFeedServerWithJetty"/>
      </manifest>
    </jar>
  </target>
  <!-- End of Jetty targets -->

  <!-- Start of Tomcat targets -->
  <target name="tomcat" depends="checkIfPropsFileExists,tomcat-all"
     description="Run Tomcat tasks only if the catalina.home property is detected.">
  </target>

  <!-- for tomcat target, checks to make sure the build.properties file exists -->
  <target name="checkIfPropsFileExists" unless="catalina.home" >
    <fail message="build.properties file is missing. 'tomcat' target NOT built.
        please check the wiki page at http://code.google.com/p/google-feedserver/wiki/DeveloperSetup"/>
  </target>

  <target name="tomcat-all" depends="clean,tomcat-path,war,undeploy,deploy" if="catalina.home"
      description="Set paths, then compile and build war file"/>

  <target name="tomcat-path">
    <!-- Paths for compiling Tomcat needed for catalina deployment tasks -->
    <path id="catalina.classpath">
      <!-- Include all elements that Tomcat exposes to applications -->
      <fileset dir="${catalina.home}/bin">
        <include name="*.jar"/>
      </fileset>
      <pathelement location="${catalina.home}/lib"/>
      <fileset dir="${catalina.home}/lib">
        <include name="*.jar"/>
      </fileset>
    </path>

    <!-- declare catalina deployment tasks -->
    <taskdef name="deploy" classname="org.apache.catalina.ant.DeployTask"
        classpathref="catalina.classpath"/>
    <taskdef name="reload" classname="org.apache.catalina.ant.ReloadTask"
        classpathref="catalina.classpath"/>
    <taskdef name="undeploy" classname="org.apache.catalina.ant.UndeployTask"
        classpathref="catalina.classpath"/>
  </target>

  <!-- Build a war file for Tomcat -->
  <target name="war" depends="compile,javadoc"
      description="Create binary distribution">
    <copydir dest="${dist.home}/conf/conf" src="${conf.home}"
        description="Copy the conf folder as is under dist/conf and then bundle it with war">
    </copydir>
    <replace dir="${dist.home}/conf/conf" value="conf/database/dbConfig.properties"
        description="Append 'conf' to the path of 'dbConfig.properties' so that it can be found when deployed in Tomcat">
      <include name="**/sqlmap.xml"/>
      <replacetoken><![CDATA[database/dbConfig.properties]]></replacetoken>
    </replace>
    <!-- Create application WAR file -->
    <war destfile="${dist.home}/${app.name}.war" webxml="${web.home}/WEB-INF/web.xml">
      <fileset dir="${web.home}" excludes="WEB-INF/**"/>
      <fileset dir="${dist.home}/docs"/>
      <classes dir="${dist.home}/conf"/>
      <classes dir="${build.home}"/>
      <lib dir="${lib.home}" excludes="servlet-api.jar"/>
    </war>
  </target>

  <!-- undeploy the app, if it already exists -->
  <target name="undeploy" depends="tomcat-path,checkIfDeployed" if="dir.exists">
    <echo message="App ${app.name} exists. undeploying it"/>
    <!-- use the Tomcat manager app to undeploy -->
    <echo message="Undeploying from ${url.manager}"/>
      <undeploy url="${url.manager}"
          username="${manager.username}"
          password="${manager.password}"
          path="/${app.name}"/>
    <!-- the manager app does not delete the directory for us -->
    <delete dir="${catalina.home}/webapps/${app.name}"/>
  </target>

  <!-- checks to make sure the dir exists - so that undeploy won't fail -->
  <target name="checkIfDeployed">
    <condition property="dir.exists">
      <available file="${catalina.home}/webapps/${app.name}" type="dir"/>
    </condition>
  </target>

  <target name="deploy" depends="tomcat-path" if="catalina.home"
      description="deploy application to servlet container">

    <echo message="Deploying to ${url.manager}"/>
    <deploy url="${url.manager}" username="${manager.username}" password="${manager.password}"
        path="/${app.name}" war="${dist.home}/${app.name}.war"/>
  </target>

  <!-- End of Tomcat targets -->

  <!-- Start of Testing-related stuff -->
  <property name="testSrc.home" value="${basedir}/tests/java"/>
  <property name="testClasses.home" value="${build.home}/testClasses/"/>
  <property name="testOutput.home" value="${build.home}/testOutput"/>
  <property name="testLib.home" value="${basedir}/tests/lib"/>
  <property name="junit.jar" location="${testLib.home}/junit-4.4.jar"/>

  <path id="classpath.test">
    <pathelement location="${testClasses.home}" />
    <pathelement location="${dist.home}/feedserver.jar" />
    <pathelement location="${conf.home}" />
    <fileset dir="${lib.home}">
      <include name="**/*.jar"/>
    </fileset>
    <fileset dir="${testLib.home}">
      <include name="**/*.jar"/>
    </fileset>
  </path>

  <target name="test" depends="cleanTests,compileTests">
    <mkdir dir="${testOutput.home}"/>
    <junit haltonfailure="no" printsummary="yes">
      <classpath refid="classpath.test"/>
      <formatter type="plain" usefile="true" />
      <batchtest todir="${testOutput.home}">
        <fileset dir="${testSrc.home}">
          <include name="**/*Test.java"/>
        </fileset>
      </batchtest>
    </junit>
  </target>

  <target name="compileTests" depends="cleanTests" description="Compile Tests">
    <mkdir dir="${testClasses.home}"/>
    <javac srcdir="${testSrc.home}" destdir="${testClasses.home}" classpathref="classpath.test"
        debug="true" debuglevel="lines,vars,source">
    </javac>
  </target>

  <target name="cleanTests" description="Delete old build and dist directories">
    <delete dir="${testClasses.home}"/>
    <delete dir="${testOutput.home}"/>
  </target>
  <!-- End of Testing-related stuff -->

  <!-- Testing -->
  <target name="createDb" description="Creates a the database tables required for the feed. It may
      be populated with data as well if the SQL file has SQL commnads for the same">
    <sql driver="${JDBC.Driver}" password="${JDBC.Password}" url="${JDBC.ConnectionURL}"
        userid="${JDBC.Username}" src="${sqlFilePath}" print="yes" output="db_output.txt">
      <classpath>
        <pathelement location="lib/${JDBC.Jar}"/>
      </classpath>
    </sql>
  </target>

  <!-- Target to create a zip of client tools which includes FSCT binaries and scripts -->
  <target name="client-tools-distro" depends="client" description="Creates a zip of client tools which includes FSCT binaries and scripts">
    <mkdir dir="${clienttools.temp.dir}" />
    <mkdir dir="${clienttools.temp.dir}/dist" />
    <mkdir dir="${clienttools.temp.dir}/lib" />
    <mkdir dir="${clienttools.temp.dir}/bin" />
    <copy file="${fsct.scripts.dir}/README" todir="${clienttools.temp.dir}"/>
    <copy file="${log4jConfigFile}" todir="${clienttools.temp.dir}/bin"/>
    <copy file="${client.jarfile}" todir="${clienttools.temp.dir}/dist"></copy>
    <copy todir="${clienttools.temp.dir}/lib">
       <fileset dir="${lib.home}" includes="commons-beanutils-core-*.jar"></fileset>
       <fileset dir="${lib.home}" includes="commons-beanutils-*.jar"></fileset>
       <fileset dir="${lib.home}" includes="commons-cli-*.jar"></fileset>
       <fileset dir="${lib.home}" includes="commons-collections-*.jar"></fileset>
       <fileset dir="${lib.home}" includes="commons-lang-*.jar"></fileset>
       <fileset dir="${lib.home}" includes="commons-logging-*.jar"></fileset>
       <fileset dir="${lib.home}" includes="gdata-*.jar"></fileset>
       <fileset dir="${lib.home}" includes="google-collect-*.jar"></fileset>
       <fileset dir="${lib.home}" includes="log4j-*.jar"></fileset>
    </copy>
    <copy todir="${clienttools.temp.dir}/bin">
       <fileset dir="${fsct.scripts.dir}" includes="**" excludes="README">
       </fileset>
    </copy>

    <replace dir="${dist.home}/temp/bin" value="FSCT_BASE_DIR=.."
                          description="Change the base dir to be one level up">
       <include name="**/setupEnv.sh"/>
       <replacetoken><![CDATA[FSCT_BASE_DIR=../..]]></replacetoken>
    </replace>
    <replace dir="${dist.home}/temp/bin" value="FSCT_BASE_DIR=.."
                                  description="Change the base dir to be one level up">
       <include name="**/setupEnv.bat"/>
       <replacetoken><![CDATA[FSCT_BASE_DIR=..\..]]></replacetoken>
    </replace>
    <zip destfile="${clienttools.zip}" basedir="${clienttools.temp.dir}"></zip>

    <delete dir="${clienttools.temp.dir}" />

  </target>

  <target name="fsct" depends="client" description="Creates fsct distribution">
    <mkdir dir="${fsct.temp.dir}" />
    <mkdir dir="${fsct.temp.dir}/dist" />
    <mkdir dir="${fsct.temp.dir}/lib" />
    <copy file="${fsct.scripts.dir}/fsct" todir="${fsct.temp.dir}"/>
    <copy file="${fsct.scripts.dir}/fsct.bat" todir="${fsct.temp.dir}"/>
    <copy file="${fsct.scripts.dir}/log4j.properties" todir="${fsct.temp.dir}"/>
    <copy file="${dist.home}/google-feedserver-java-client-2.0.jar" todir="${fsct.temp.dir}/dist" />
    <copy file="${lib.home}/commons-beanutils-1.8.0.jar" todir="${fsct.temp.dir}/lib" />
    <copy file="${lib.home}/commons-beanutils-core-1.8.0.jar" todir="${fsct.temp.dir}/lib" />
    <copy file="${lib.home}/commons-cli-1.1.jar" todir="${fsct.temp.dir}/lib" />
    <copy file="${lib.home}/commons-collections-3.2.1.jar" todir="${fsct.temp.dir}/lib" />
    <copy file="${lib.home}/commons-lang-2.4.jar" todir="${fsct.temp.dir}/lib" />
    <copy file="${lib.home}/commons-logging-1.0.4.jar" todir="${fsct.temp.dir}/lib" />
    <copy file="${lib.home}/gdata-client-1.0.jar" todir="${fsct.temp.dir}/lib" />
    <copy file="${lib.home}/gdata-core-1.0.jar" todir="${fsct.temp.dir}/lib" />
    <copy file="${lib.home}/google-collect-1.0-rc1.jar" todir="${fsct.temp.dir}/lib" />
    <copy file="${lib.home}/jline-0.9.94.jar" todir="${fsct.temp.dir}/lib" />
    <copy file="${lib.home}/log4j-1.2.14.jar" todir="${fsct.temp.dir}/lib" />
    <zip destfile="${dist.home}/fsct.zip" basedir="${fsct.temp.dir}/.." includes="fsct/**"/>
    <delete dir="${fsct.temp.dir}" />
  </target>

</project>


text:
// Copyright 2015 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

package org.chromium.chrome.browser.signin;

import android.accounts.Account;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.provider.Settings;

import org.chromium.base.CalledByNative;
import org.chromium.base.ThreadUtils;
import org.chromium.chrome.browser.preferences.Preferences;
import org.chromium.chrome.browser.profiles.Profile;
import org.chromium.chrome.browser.profiles.ProfileAccountManagementMetrics;

/**
 * Stub entry points and implementation interface for the account management fragment delegate.
 */
public class AccountManagementScreenHelper {
    private static AccountManagementFragmentDelegate sDelegate;

    /*
     * TODO(guohui): add all Gaia service types.
     * Enum for the Gaia service types, must match GAIAServiceType in
     * signin_header_helper.h
     */
    public static final int GAIA_SERVICE_TYPE_SIGNUP = 5;

    private static final String EXTRA_ACCOUNT_TYPES = "account_types";
    private static final String EXTRA_VALUE_GOOGLE_ACCOUNTS = "com.google";

    /**
     * An account management screen delegate interface.
     */
    public interface AccountManagementFragmentDelegate {
        /**
         * Opens an incognito tab.
         * @param activity Fragment activity
         */
        void openIncognitoTab(Activity activity);

        /**
         * Opens a sign out dialog.
         * @param activity Fragment activity.
         */
        void openSignOutDialog(Activity activity);

        /**
         * Opens the sync customization preferences fragment.
         * @param activity A preferences activity
         * @param account An account to customize
         */
        void openSyncCustomizationFragment(Preferences activity, Account account);
    }

    /**
     * Sets the account management fragment delegate.
     * @param delegate An implementation of AccountManagementFragmentDelegate interface
     */
    public static void setDelegate(AccountManagementFragmentDelegate delegate) {
        ThreadUtils.assertOnUiThread();
        sDelegate = delegate;
    }

    /**
     * @return An instance of the account management fragment delegate, or null.
     */
    public static AccountManagementFragmentDelegate getDelegate() {
        return sDelegate;
    }

    @CalledByNative
    private static void openAccountManagementScreen(
            Context applicationContext, Profile profile, int gaiaServiceType) {
        ThreadUtils.assertOnUiThread();

        if (gaiaServiceType == GAIA_SERVICE_TYPE_SIGNUP) {
            openAndroidAccountCreationScreen(applicationContext);
            return;
        }

        if (sDelegate == null) return;
        AccountManagementFragment.openAccountManagementScreen(
                applicationContext, profile, gaiaServiceType);
    }

    /**
     * Opens the Android account manager for adding or creating a Google account.
     * @param applicationContext
     */
    private static void openAndroidAccountCreationScreen(
            Context applicationContext) {
        logEvent(ProfileAccountManagementMetrics.DIRECT_ADD_ACCOUNT, GAIA_SERVICE_TYPE_SIGNUP);

        Intent createAccountIntent = new Intent(Settings.ACTION_ADD_ACCOUNT);
        createAccountIntent.putExtra(
                EXTRA_ACCOUNT_TYPES, new String[]{EXTRA_VALUE_GOOGLE_ACCOUNTS});
        createAccountIntent.setFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT
                | Intent.FLAG_ACTIVITY_SINGLE_TOP | Intent.FLAG_ACTIVITY_NEW_TASK
                | Intent.FLAG_ACTIVITY_CLEAR_TOP);

        applicationContext.startActivity(createAccountIntent);
    }

    /**
     * Log a UMA event for a given metric and a signin type.
     * @param metric One of ProfileAccountManagementMetrics constants.
     * @param gaiaServiceType A signin::GAIAServiceType.
     */
    public static void logEvent(int metric, int gaiaServiceType) {
        nativeLogEvent(metric, gaiaServiceType);
    }

    // Native methods.
    private static native void nativeLogEvent(int metric, int gaiaServiceType);
}


text:
{% extends 'healthtracker/base.html' %}

{% block title %}
    Fitster - Food Details - {{ request.report.name }}
{% endblock %}

{% block content %}

{{ request.report.name }}

        <form class="form-group"
              action="{% url 'healthtracker:fooddetails' request.ndbno %}"
              method="post">
          {% csrf_token %}

Add Food

<input type="text"
                          name="date"
                          class="form-control"
                          id="datepicker"
                          placeholder="Select date..."
                          required="">

          Quantity
          <input type="number"
                 min="0"
                 id="quantity"
                 name="quantity"
                 class="form-control"
                 placeholder="Enter quantity..."
                 autofocus=""
                 required="">
          <input type="hidden"
                 name="itemname"
                 value="{{ request.report.name }}">

          <select class="form-control"
                  name="unitmodifier">
            {% for measure in request.measures %}
            <option value="{{ measure.label }}|{{ measure.eqv }}">{{ measure.label }}</option>
            {% empty %}
            <option value="none">Units</option>
            {% endfor %}
          </select>

          <button class="btn btn-lg btn-primary btn-block"
                  type="submit">Add</button>
        </form>

Nutrient Info

            {% if request.report %}

                Nutrient Name
                Value(per 100g of food)

            {% endif %}

              {% for nutrient in request.report.nutrients %}

                  {{ nutrient.name }}

                  {{ nutrient.value }}{{ nutrient.unit }}

              {% empty %}
              Sorry, no results found.
              {% endfor %}

{% endblock %}


text:
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license.
package com.intellij.openapi.editor.impl.view;

import com.intellij.diagnostic.Dumpable;
import com.intellij.ide.ui.UISettings;
import com.intellij.openapi.Disposable;
import com.intellij.openapi.application.ApplicationManager;
import com.intellij.openapi.diagnostic.Logger;
import com.intellij.openapi.editor.CustomFoldRegion;
import com.intellij.openapi.editor.FoldRegion;
import com.intellij.openapi.editor.LogicalPosition;
import com.intellij.openapi.editor.VisualPosition;
import com.intellij.openapi.editor.colors.EditorFontType;
import com.intellij.openapi.editor.event.VisibleAreaEvent;
import com.intellij.openapi.editor.event.VisibleAreaListener;
import com.intellij.openapi.editor.ex.DocumentEx;
import com.intellij.openapi.editor.ex.EditorSettingsExternalizable;
import com.intellij.openapi.editor.ex.util.EditorUtil;
import com.intellij.openapi.editor.impl.DocumentImpl;
import com.intellij.openapi.editor.impl.EditorImpl;
import com.intellij.openapi.editor.impl.FontInfo;
import com.intellij.openapi.editor.impl.TextDrawingCallback;
import com.intellij.openapi.editor.markup.TextAttributes;
import com.intellij.openapi.util.Disposer;
import com.intellij.openapi.util.Key;
import com.intellij.openapi.util.registry.Registry;
import com.intellij.openapi.util.text.StringUtil;
import com.intellij.util.concurrency.annotations.RequiresEdt;
import org.intellij.lang.annotations.JdkConstants;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.TestOnly;

import java.awt.*;
import java.awt.event.HierarchyEvent;
import java.awt.event.HierarchyListener;
import java.awt.font.FontRenderContext;
import java.awt.font.LineMetrics;
import java.awt.geom.AffineTransform;
import java.awt.geom.Point2D;
import java.text.Bidi;

/**
 * A facade for components responsible for drawing editor contents, managing editor size
 * and coordinate conversions (offset <-> logical position <-> visual position <-> x,y).
 *

 * Also contains a cache of several font-related quantities (line height, space width, etc).
 */
public final class EditorView implements TextDrawingCallback, Disposable, Dumpable, HierarchyListener, VisibleAreaListener {
  private static final Logger LOG = Logger.getInstance(EditorView.class);
  private static final Key<LineLayout> FOLD_REGION_TEXT_LAYOUT = Key.create("text.layout");

  private final EditorImpl myEditor;
  private final DocumentEx myDocument;
  private final EditorPainter myPainter;
  private final EditorCoordinateMapper myMapper;
  private final EditorSizeManager mySizeManager;
  private final TextLayoutCache myTextLayoutCache;
  private final LogicalPositionCache myLogicalPositionCache;
  private final CharWidthCache myCharWidthCache;
  private final TabFragment myTabFragment;

  private FontRenderContext myFontRenderContext; // guarded by myLock
  private String myPrefixText; // accessed only in EDT
  private LineLayout myPrefixLayout; // guarded by myLock
  private TextAttributes myPrefixAttributes; // accessed only in EDT
  private int myBidiFlags; // accessed only in EDT

  private float myPlainSpaceWidth; // guarded by myLock
  private int myLineHeight; // guarded by myLock
  private int myDescent; // guarded by myLock
  private int myCharHeight; // guarded by myLock
  private float myMaxCharWidth; // guarded by myLock
  private int myCapHeight; // guarded by myLock
  private int myTabSize; // guarded by myLock
  private int myTopOverhang; //guarded by myLock
  private int myBottomOverhang; //guarded by myLock

  private final Object myLock = new Object();

  public EditorView(@NotNull EditorImpl editor) {
    myEditor = editor;
    myDocument = editor.getDocument();

    myPainter = new EditorPainter(this);
    myMapper = new EditorCoordinateMapper(this);
    mySizeManager = new EditorSizeManager(this);
    myTextLayoutCache = new TextLayoutCache(this);
    myLogicalPositionCache = new LogicalPositionCache(this);
    myCharWidthCache = new CharWidthCache(this);
    myTabFragment = new TabFragment(this);

    myEditor.getContentComponent().addHierarchyListener(this);
    myEditor.getScrollingModel().addVisibleAreaListener(this);

    Disposer.register(this, myLogicalPositionCache);
    Disposer.register(this, myTextLayoutCache);
    Disposer.register(this, mySizeManager);
  }

  EditorImpl getEditor() {
    return myEditor;
  }

  FontRenderContext getFontRenderContext() {
    synchronized (myLock) {
      return myFontRenderContext;
    }
  }

  EditorSizeManager getSizeManager() {
    return mySizeManager;
  }

  TextLayoutCache getTextLayoutCache() {
    return myTextLayoutCache;
  }

  TabFragment getTabFragment() {
    return myTabFragment;
  }

  LogicalPositionCache getLogicalPositionCache() {
    return myLogicalPositionCache;
  }

  float getRightAlignmentLineStartX(int visualLine) {
    return myMapper.getRightAlignmentLineStartX(visualLine);
  }

  int getRightAlignmentMarginX() {
    return myMapper.getRightAlignmentMarginX();
  }

  @Override
  public void dispose() {
    myEditor.getScrollingModel().removeVisibleAreaListener(this);
    myEditor.getContentComponent().removeHierarchyListener(this);
  }

  @Override
  public void hierarchyChanged(HierarchyEvent e) {
    if ((e.getChangeFlags() & HierarchyEvent.SHOWING_CHANGED) != 0 && e.getComponent().isShowing()) {
      checkFontRenderContext(null);
    }
  }

  @Override
  public void visibleAreaChanged(@NotNull VisibleAreaEvent e) {
    checkFontRenderContext(null);
  }

  public int yToVisualLine(int y) {
    assertIsDispatchThread();
    assertNotInBulkMode();
    return myMapper.yToVisualLine(y);
  }

  public int visualLineToY(int line) {
    assertIsDispatchThread();
    assertNotInBulkMode();
    return myMapper.visualLineToY(line);
  }

  public int[] visualLineToYRange(int line) {
    assertIsDispatchThread();
    assertNotInBulkMode();
    return myMapper.visualLineToYRange(line);
  }

  public @NotNull LogicalPosition offsetToLogicalPosition(int offset) {
    assertIsReadAccess();
    return myMapper.offsetToLogicalPosition(offset);
  }

  public int logicalPositionToOffset(@NotNull LogicalPosition pos) {
    assertIsReadAccess();
    return myMapper.logicalPositionToOffset(pos);
  }

  public @NotNull VisualPosition logicalToVisualPosition(@NotNull LogicalPosition pos, boolean beforeSoftWrap) {
    assertIsDispatchThread();
    assertNotInBulkMode();
    myEditor.getSoftWrapModel().prepareToMapping();
    return myMapper.logicalToVisualPosition(pos, beforeSoftWrap);
  }

  public @NotNull LogicalPosition visualToLogicalPosition(@NotNull VisualPosition pos) {
    assertIsDispatchThread();
    assertNotInBulkMode();
    myEditor.getSoftWrapModel().prepareToMapping();
    return myMapper.visualToLogicalPosition(pos);
  }

  public @NotNull VisualPosition offsetToVisualPosition(int offset, boolean leanTowardsLargerOffsets, boolean beforeSoftWrap) {
    assertIsDispatchThread();
    assertNotInBulkMode();
    myEditor.getSoftWrapModel().prepareToMapping();
    return myMapper.offsetToVisualPosition(offset, leanTowardsLargerOffsets, beforeSoftWrap);
  }

  public int visualPositionToOffset(VisualPosition visualPosition) {
    assertIsDispatchThread();
    assertNotInBulkMode();
    myEditor.getSoftWrapModel().prepareToMapping();
    return myMapper.visualPositionToOffset(visualPosition);
  }

  public int offsetToVisualLine(int offset, boolean beforeSoftWrap) {
    assertIsDispatchThread();
    assertNotInBulkMode();
    myEditor.getSoftWrapModel().prepareToMapping();
    return myMapper.offsetToVisualLine(offset, beforeSoftWrap);
  }

  public int visualLineToOffset(int visualLine) {
    assertIsDispatchThread();
    assertNotInBulkMode();
    myEditor.getSoftWrapModel().prepareToMapping();
    return myMapper.visualLineToOffset(visualLine);
  }

  public @NotNull VisualPosition xyToVisualPosition(@NotNull Point2D p) {
    assertIsDispatchThread();
    assertNotInBulkMode();
    myEditor.getSoftWrapModel().prepareToMapping();
    return myMapper.xyToVisualPosition(p);
  }

  public @NotNull Point2D visualPositionToXY(@NotNull VisualPosition pos) {
    assertIsDispatchThread();
    assertNotInBulkMode();
    myEditor.getSoftWrapModel().prepareToMapping();
    return myMapper.visualPositionToXY(pos);
  }

  public @NotNull Point2D offsetToXY(int offset, boolean leanTowardsLargerOffsets, boolean beforeSoftWrap) {
    assertIsDispatchThread();
    assertNotInBulkMode();
    myEditor.getSoftWrapModel().prepareToMapping();
    return myMapper.offsetToXY(offset, leanTowardsLargerOffsets, beforeSoftWrap);
  }

  public void setPrefix(String prefixText, TextAttributes attributes) {
    assertIsDispatchThread();
    myPrefixText = prefixText;
    synchronized (myLock) {
      myPrefixLayout = prefixText == null || prefixText.isEmpty() ? null :
                       LineLayout.create(this, prefixText, attributes.getFontType());
    }
    myPrefixAttributes = attributes;
    mySizeManager.invalidateRange(0, 0);
  }

  public float getPrefixTextWidthInPixels() {
    LineLayout layout = getPrefixLayout();
    return layout == null ? 0 : layout.getWidth();
  }

  LineLayout getPrefixLayout() {
    synchronized (myLock) {
      FoldRegion[] topLevelRegions = myEditor.getFoldingModel().fetchTopLevel();
      if (topLevelRegions != null && topLevelRegions.length > 0) {
        FoldRegion firstRegion = topLevelRegions[0];
        if (firstRegion instanceof CustomFoldRegion && firstRegion.getStartOffset() == 0) {
          return null; // prefix is hidden
        }
      }
      return myPrefixLayout;
    }
  }

  TextAttributes getPrefixAttributes() {
    return myPrefixAttributes;
  }

  public void paint(Graphics2D g) {
    assertIsDispatchThread();
    myEditor.getSoftWrapModel().prepareToMapping();
    checkFontRenderContext(g.getFontRenderContext());
    myPainter.paint(g);
  }

  public void repaintCarets() {
    assertIsDispatchThread();
    myPainter.repaintCarets();
  }

  public @NotNull Dimension getPreferredSize() {
    assertIsDispatchThread();
    assert !myEditor.isPurePaintingMode();
    myEditor.getSoftWrapModel().prepareToMapping();
    return mySizeManager.getPreferredSize();
  }

  /**
   * Returns preferred pixel width of the lines in range.
   *

   * This method is currently used only with "idea.true.smooth.scrolling" experimental option.
   *
   * @param beginLine begin visual line (inclusive)
   * @param endLine   end visual line (exclusive), may be greater than the actual number of lines
   * @return preferred pixel width
   */
  public int getPreferredWidth(int beginLine, int endLine) {
    assertIsDispatchThread();
    assert !myEditor.isPurePaintingMode();
    myEditor.getSoftWrapModel().prepareToMapping();
    return mySizeManager.getPreferredWidth(beginLine, endLine);
  }

  public int getPreferredHeight() {
    assertIsDispatchThread();
    assert !myEditor.isPurePaintingMode();
    myEditor.getSoftWrapModel().prepareToMapping();
    return mySizeManager.getPreferredHeight();
  }

  public int getMaxWidthInRange(int startOffset, int endOffset) {
    assertIsDispatchThread();
    int startVisualLine = offsetToVisualLine(startOffset, false);
    int endVisualLine = offsetToVisualLine(endOffset, true);
    return getMaxTextWidthInLineRange(startVisualLine, endVisualLine) + getInsets().left;
  }

  /**
   * If {@code quickEvaluationListener} is provided, quick approximate size evaluation becomes enabled, listener will be invoked
   * if approximation will in fact be used during width calculation.
   */
  int getMaxTextWidthInLineRange(int startVisualLine, int endVisualLine) {
    myEditor.getSoftWrapModel().prepareToMapping();
    int maxWidth = 0;
    VisualLinesIterator iterator = new VisualLinesIterator(myEditor, startVisualLine);
    while (!iterator.atEnd() && iterator.getVisualLine() <= endVisualLine) {
      int width = mySizeManager.getVisualLineWidth(iterator, false);
      maxWidth = Math.max(maxWidth, width);
      iterator.advance();
    }
    return maxWidth;
  }

  @RequiresEdt
  public void reinitSettings() {
    synchronized (myLock) {
      myPlainSpaceWidth = -1;
      myTabSize = -1;
      setFontRenderContext(null);
    }
    myBidiFlags = switch (EditorSettingsExternalizable.getInstance().getBidiTextDirection()) {
      case LTR -> Bidi.DIRECTION_LEFT_TO_RIGHT;
      case RTL -> Bidi.DIRECTION_RIGHT_TO_LEFT;
      default -> Bidi.DIRECTION_DEFAULT_LEFT_TO_RIGHT;
    };
    myLogicalPositionCache.reset(false);
    myTextLayoutCache.resetToDocumentSize(false);
    invalidateFoldRegionLayouts();
    myCharWidthCache.clear();
    setPrefix(myPrefixText, myPrefixAttributes); // recreate prefix layout
    mySizeManager.reset();
  }

  public void invalidateRange(int startOffset, int endOffset, boolean invalidateSize) {
    assertIsDispatchThread();
    int textLength = myDocument.getTextLength();
    if (startOffset > endOffset || startOffset >= textLength || endOffset < 0) {
      return;
    }
    int startLine = myDocument.getLineNumber(Math.max(0, startOffset));
    int endLine = myDocument.getLineNumber(Math.min(textLength, endOffset));
    myTextLayoutCache.invalidateLines(startLine, endLine);
    if (invalidateSize) {
      mySizeManager.invalidateRange(startOffset, endOffset);
    }
  }

  /**
   * Invoked when document might have changed, but no notifications were sent (for a hacky document in EditorTextFieldCellRenderer)
   */
  public void reset() {
    assertIsDispatchThread();
    myLogicalPositionCache.reset(true);
    myTextLayoutCache.resetToDocumentSize(true);
    mySizeManager.reset();
  }

  public boolean isRtlLocation(@NotNull VisualPosition visualPosition) {
    assertIsDispatchThread();
    if (myDocument.getTextLength() == 0) return false;
    LogicalPosition logicalPosition = visualToLogicalPosition(visualPosition);
    int offset = logicalPositionToOffset(logicalPosition);
    if (!logicalPosition.equals(offsetToLogicalPosition(offset))) return false; // virtual space
    if (myEditor.getSoftWrapModel().getSoftWrap(offset) != null) {
      VisualPosition beforeWrapPosition = offsetToVisualPosition(offset, true, true);
      if (visualPosition.line == beforeWrapPosition.line &&
          (visualPosition.column > beforeWrapPosition.column ||
           visualPosition.column == beforeWrapPosition.column && visualPosition.leansRight)) {
        return false;
      }
      VisualPosition afterWrapPosition = offsetToVisualPosition(offset, false, false);
      if (visualPosition.line == afterWrapPosition.line &&
          (visualPosition.column < afterWrapPosition.column ||
           visualPosition.column == afterWrapPosition.column && !visualPosition.leansRight)) {
        return false;
      }
    }
    int line = myDocument.getLineNumber(offset);
    LineLayout layout = myTextLayoutCache.getLineLayout(line);
    return layout.isRtlLocation(offset - myDocument.getLineStartOffset(line), logicalPosition.leansForward);
  }

  public boolean isAtBidiRunBoundary(@NotNull VisualPosition visualPosition) {
    assertIsDispatchThread();
    int offset = visualPositionToOffset(visualPosition);
    int otherSideOffset = visualPositionToOffset(visualPosition.leanRight(!visualPosition.leansRight));
    return offset != otherSideOffset;
  }

  /**
   * Offset of nearest boundary (not equal to {@code offset}) on the same line is returned. {@code -1} is returned if
   * corresponding boundary is not found.
   */
  public int findNearestDirectionBoundary(int offset, boolean lookForward) {
    assertIsDispatchThread();
    int textLength = myDocument.getTextLength();
    if (textLength == 0 || offset < 0 || offset > textLength) return -1;
    int line = myDocument.getLineNumber(offset);
    LineLayout layout = myTextLayoutCache.getLineLayout(line);
    int lineStartOffset = myDocument.getLineStartOffset(line);
    int relativeOffset = layout.findNearestDirectionBoundary(offset - lineStartOffset, lookForward);
    return relativeOffset < 0 ? -1 : lineStartOffset + relativeOffset;
  }

  public float getPlainSpaceWidth() {
    synchronized (myLock) {
      initMetricsIfNeeded();
      return myPlainSpaceWidth;
    }
  }

  public int getNominalLineHeight() {
    synchronized (myLock) {
      initMetricsIfNeeded();
      return myLineHeight + myTopOverhang + myBottomOverhang;
    }
  }

  public int getLineHeight() {
    synchronized (myLock) {
      initMetricsIfNeeded();
      return myLineHeight;
    }
  }

  private float getVerticalScalingFactor() {
    if (myEditor.isOneLineMode()) return 1;
    float lineSpacing = myEditor.getColorsScheme().getLineSpacing();
    return lineSpacing > 0 ? lineSpacing : 1;
  }

  public int getDescent() {
    synchronized (myLock) {
      return myDescent;
    }
  }

  public int getCharHeight() {
    synchronized (myLock) {
      initMetricsIfNeeded();
      return myCharHeight;
    }
  }

  float getMaxCharWidth() {
    synchronized (myLock) {
      initMetricsIfNeeded();
      return myMaxCharWidth;
    }
  }

  public int getAscent() {
    synchronized (myLock) {
      initMetricsIfNeeded();
      return myLineHeight - myDescent;
    }
  }

  int getCapHeight() {
    synchronized (myLock) {
      initMetricsIfNeeded();
      return myCapHeight;
    }
  }

  public int getTopOverhang() {
    synchronized (myLock) {
      initMetricsIfNeeded();
      return myTopOverhang;
    }
  }

  public int getBottomOverhang() {
    synchronized (myLock) {
      initMetricsIfNeeded();
      return myBottomOverhang;
    }
  }

  // guarded by myLock
  private void initMetricsIfNeeded() {
    if (myPlainSpaceWidth >= 0) return;

    Font font = myEditor.getColorsScheme().getFont(EditorFontType.PLAIN);
    FontMetrics fm = FontInfo.getFontMetrics(font, myFontRenderContext);

    float width = FontLayoutService.getInstance().charWidth2D(fm, ' ');
    myPlainSpaceWidth = width > 0 ? width : 1;

    myCharHeight = FontLayoutService.getInstance().charWidth(fm, 'a');

    float verticalScalingFactor = getVerticalScalingFactor();

    int fontMetricsHeight = FontLayoutService.getInstance().getHeight(fm);
    int lineHeight;
    if (Registry.is("editor.text.xcode.vertical.spacing")) {
      //Here we approximate line calculation to the variant used in Xcode 9 editor
      LineMetrics metrics = font.getLineMetrics("", myFontRenderContext);

      double height = Math.ceil(metrics.getHeight()) + metrics.getLeading();
      double delta = verticalScalingFactor - 1;
      int spacing;
      if (Math.round((height * delta) / 2) <= 1) {
        spacing = delta > 0 ? 2 : 0;
      }
      else {
        spacing = ((int)Math.ceil((height * delta) / 2)) * 2;
      }
      lineHeight = (int)Math.ceil(height) + spacing;
    }
    else if (Registry.is("editor.text.vertical.spacing.correct.rounding")) {
      if (verticalScalingFactor == 1f) {
        lineHeight = fontMetricsHeight;
      }
      else {
        Font scaledFont = font.deriveFont(font.getSize() * verticalScalingFactor);
        FontMetrics scaledMetrics = FontInfo.getFontMetrics(scaledFont, myFontRenderContext);
        lineHeight = FontLayoutService.getInstance().getHeight(scaledMetrics);
      }
    }
    else {
      lineHeight = (int)Math.ceil(fontMetricsHeight * verticalScalingFactor);
    }
    myLineHeight = Math.max(1, lineHeight);
    int descent = FontLayoutService.getInstance().getDescent(fm);
    myDescent = descent + (myLineHeight - fontMetricsHeight) / 2;
    myTopOverhang = fontMetricsHeight - myLineHeight + myDescent - descent;
    myBottomOverhang = descent - myDescent;

    // assuming that bold italic 'W' gives a good approximation of font's widest character
    FontMetrics fmBI = FontInfo.getFontMetrics(myEditor.getColorsScheme().getFont(EditorFontType.BOLD_ITALIC), myFontRenderContext);
    myMaxCharWidth = FontLayoutService.getInstance().charWidth2D(fmBI, 'W');

    myCapHeight = (int)font.createGlyphVector(myFontRenderContext, "H").getVisualBounds().getHeight();
  }

  public int getTabSize() {
    synchronized (myLock) {
      if (myTabSize < 0) {
        myTabSize = EditorUtil.getTabSize(myEditor);
      }
      return myTabSize;
    }
  }

  // guarded by myLock
  private boolean setFontRenderContext(FontRenderContext context) {
    FontRenderContext contextToSet = context == null ? FontInfo.getFontRenderContext(myEditor.getContentComponent()) : context;
    if (areEqualContexts(myFontRenderContext, contextToSet)) return false;

    AffineTransform transform = contextToSet.getTransform();
    if (transform.getDeterminant() == 0) {
      LOG.error("Incorrect transform in FontRenderContext" + (context == null ? " obtained from component" : "") + ": " + transform);
      contextToSet = new FontRenderContext(new AffineTransform(),
                                           contextToSet.getAntiAliasingHint(), contextToSet.getFractionalMetricsHint());
    }

    Object fmHint = UISettings.getEditorFractionalMetricsHint();
    myFontRenderContext = contextToSet.getFractionalMetricsHint() == fmHint
                          ? contextToSet
                          : new FontRenderContext(contextToSet.getTransform(),
                                                  contextToSet.getAntiAliasingHint(),
                                                  fmHint);
    return true;
  }

  private void checkFontRenderContext(FontRenderContext context) {
    boolean contextUpdated = false;
    synchronized (myLock) {
      if (setFontRenderContext(context)) {
        myPlainSpaceWidth = -1;
        contextUpdated = true;
      }
    }
    if (contextUpdated) {
      myTextLayoutCache.resetToDocumentSize(false);
      invalidateFoldRegionLayouts();
      myCharWidthCache.clear();
      myEditor.getFoldingModel().updateCachedOffsets();
    }
  }

  private static boolean areEqualContexts(FontRenderContext c1, FontRenderContext c2) {
    if (c1 == c2) return true;
    if (c1 == null || c2 == null) return false;
    // We ignore fractional metrics aspect of contexts, because we it's not changing during editor's lifecycle.
    // And it has different values for component graphics (ON/OFF) and component's font metrics (DEFAULT), causing
    // unnecessary layout cache resets.
    return c1.getTransform().equals(c2.getTransform()) && c1.getAntiAliasingHint().equals(c2.getAntiAliasingHint());
  }

  public int offsetToVisualColumnInFoldRegion(@NotNull FoldRegion region, int offset, boolean leanTowardsLargerOffsets) {
    if (offset < 0 || offset == 0 && !leanTowardsLargerOffsets) return 0;
    String text = region.getPlaceholderText();
    if (offset > text.length()) {
      offset = text.length();
      leanTowardsLargerOffsets = true;
    }
    int logicalColumn = LogicalPositionCache.calcColumn(text, 0, 0, offset, getTabSize());
    int maxColumn = 0;
    for (LineLayout.VisualFragment fragment : getFoldRegionLayout(region).getFragmentsInVisualOrder(0)) {
      int startLC = fragment.getStartLogicalColumn();
      int endLC = fragment.getEndLogicalColumn();
      if (logicalColumn > startLC && logicalColumn < endLC ||
          logicalColumn == startLC && leanTowardsLargerOffsets ||
          logicalColumn == endLC && !leanTowardsLargerOffsets) {
        return fragment.logicalToVisualColumn(logicalColumn);
      }
      maxColumn = fragment.getEndVisualColumn();
    }
    return maxColumn;
  }

  public int visualColumnToOffsetInFoldRegion(@NotNull FoldRegion region, int visualColumn, boolean leansRight) {
    if (visualColumn < 0 || visualColumn == 0 && !leansRight) return 0;
    String text = region.getPlaceholderText();
    for (LineLayout.VisualFragment fragment : getFoldRegionLayout(region).getFragmentsInVisualOrder(0)) {
      int startVC = fragment.getStartVisualColumn();
      int endVC = fragment.getEndVisualColumn();
      if (visualColumn > startVC && visualColumn < endVC ||
          visualColumn == startVC && leansRight ||
          visualColumn == endVC && !leansRight) {
        int logicalColumn = fragment.visualToLogicalColumn(visualColumn);
        return LogicalPositionCache.calcOffset(text, logicalColumn, 0, 0, text.length(), getTabSize());
      }
    }
    return text.length();
  }

  LineLayout getFoldRegionLayout(FoldRegion foldRegion) {
    LineLayout layout = foldRegion.getUserData(FOLD_REGION_TEXT_LAYOUT);
    if (layout == null) {
      TextAttributes placeholderAttributes = myEditor.getFoldingModel().getPlaceholderAttributes();
      layout = LineLayout.create(this, StringUtil.replace(foldRegion.getPlaceholderText(), "\n", " "),
                              placeholderAttributes == null ? Font.PLAIN : placeholderAttributes.getFontType());
      foldRegion.putUserData(FOLD_REGION_TEXT_LAYOUT, layout);
    }
    return layout;
  }

  private void invalidateFoldRegionLayouts() {
    for (FoldRegion region : myEditor.getFoldingModel().getAllFoldRegions()) {
      invalidateFoldRegionLayout(region);
    }
  }

  public void invalidateFoldRegionLayout(FoldRegion region) {
    region.putUserData(FOLD_REGION_TEXT_LAYOUT, null);
  }

  float getCodePointWidth(int codePoint, @JdkConstants.FontStyle int fontStyle) {
    return myCharWidthCache.getCodePointWidth(codePoint, fontStyle);
  }

  Insets getInsets() {
    return myEditor.getContentComponent().getInsets();
  }

  int getBidiFlags() {
    return myBidiFlags;
  }

  private static void assertIsDispatchThread() {
    ApplicationManager.getApplication().assertIsDispatchThread();
  }

  private static void assertIsReadAccess() {
    ApplicationManager.getApplication().assertReadAccessAllowed();
  }

  @Override
  public void drawChars(@NotNull Graphics g, char @NotNull [] data, int start, int end, int x, int y, @NotNull Color color, @NotNull FontInfo fontInfo) {
    myPainter.drawChars(g, data, start, end, x, y, color, fontInfo);
  }

  @Override
  public @NotNull String dumpState() {
    String prefixText = myPrefixText;
    TextAttributes prefixAttributes = myPrefixAttributes;
    synchronized (myLock) {
      return "[prefix text: " + prefixText +
             ", prefix attributes: " + prefixAttributes +
             ", space width: " + myPlainSpaceWidth +
             ", line height: " + myLineHeight +
             ", descent: " + myDescent +
             ", char height: " + myCharHeight +
             ", max char width: " + myMaxCharWidth +
             ", tab size: " + myTabSize +
             " ,size manager: " + mySizeManager.dumpState() +
             " ,logical position cache: " + myLogicalPositionCache.dumpState() +
             "]";
    }
  }

  @TestOnly
  public void validateState() {
    myLogicalPositionCache.validateState();
    mySizeManager.validateState();
  }

  private void assertNotInBulkMode() {
    if (myDocument instanceof DocumentImpl) {
      ((DocumentImpl)myDocument).assertNotInBulkUpdate();
    }
    else if (myDocument.isInBulkUpdate()) {
      throw new IllegalStateException("Current operation is not permitted in bulk mode");
    }
    if (myEditor.getInlayModel().isInBatchMode()) {
      throw new IllegalStateException("Current operation is not permitted during batch inlay update");
    }
  }
}


text:
require 'amazon/coral/handler'

module Amazon
  module Coral

    # Preloads identity information into request objects.  Useful if all
    # requests through a client will utilize the same identity.
    class IdentityHandler < Handler

      # Instantiates an IdentityHandler with a hash of identity attributes
      # to be contributed to the request's identity.  Attributes specified
      # here will not override those explicitly associated with a request.
      def initialize(attributes)
        @attributes = attributes.to_hash
      end

      def before(job)
        identity = job.request[:identity]

        # for each shared identity attribute, set it on the request's
        # identity IFF no attribute with that key is already present
        @attributes.each { |k,v|
          identity[k] = v unless identity.has_key?(k)
        }
      end
    end
  end
end


text:
<?php

require_once("lib/REST_Service/curl_rest_service_class.inc.php");
require_once("exceptions/ServiceException.class.php");

class DomaintoolsAPIConfiguration {

	/**
	 * Server Host
	 */
	protected $host;

	/**
	 * Server Port
	 */
	protected $port;

	/**
	 * Sub URL (version)
	 */
	protected $subUrl;

	/**
	 * Complete URL
	 */
	protected $baseUrl;

	/**
	 * Domaintools API Username
	 */
	protected $username;

	/**
	 * Domaintools API Password
	 */
	protected $password;

	/**
	 * (Boolean) force to secure authentication
	 */
	protected $secureAuth;

	/**
	 * Default return type (json/xml/html)
	 */
	protected $returnType;

	/**
	 * transport type (curl, etc.)
	 */
	protected $transportType;

	/**
	 * Object in charge of calling the API
	 */
	protected $transport;

	/**
	 * default config file path
	 */
	protected $defaultConfigPath;

	/**
	 * default configuration
	 * (that will be use to complete if necessary)
	 */
	protected $defaultConfig = array(
        'username'       => '',
        'key'            => '',
        'host'           => 'api.domaintools.com',
        'port'           => '80',
        'version'        => 'v1',
        'secure_auth'    => true,
        'return_type'    => 'json',
        'transport_type' => 'curl',
        'content_type'   => 'application/json'
    );

  /**
   * Construct of the class and initiliaze with default values (if no config given)
   * @param mixed $ini_resource
   */
	public function __construct($ini_resource = '') {

        $this->defaultConfigPath = __DIR__.'/api.ini';

        if(empty($ini_resource)) $ini_resource = $this->defaultConfigPath;

        if(!is_array($ini_resource)) {
            if(!file_exists($ini_resource)) {
                throw new ServiceException(ServiceException::INVALID_CONFIG_PATH);
            }
            $config = parse_ini_file($ini_resource);
        }
        elseif(is_array($ini_resource)) {
            $config = $ini_resource;
        }
        $this->init($config);
    }

  /**
   * Initialize the configuration Object
   * @param array $config - Associative array for configuration
   */
    protected function init($config = array()) {

        $config                         = $this->validateParams($config);

        $this->host 			        = $config['host'];
        $this->port						= $config['port'];
        $this->subUrl					= $config['version'];
        $this->username					= $config['username'];
        $this->password					= $config['key'];
        $this->secureAuth               = $config['secure_auth'];
        $this->returnType				= $config['return_type'];
        $this->contentType				= $config['content_type'];
        $this->transportType            = $config['transport_type'];

        $this->baseUrl					= 'http://'.$this->host.':'.$this->port.'/'.$this->subUrl;

        $className                      = ucfirst($this->transportType).'RestService';
        $this->transport                = RESTServiceAbstract::factory($className, array($this->contentType));

    }

    /**
     * Validate options from a given array
     * Merge with the default configuration
     * @param array $config - Associative array for configuration
     * @return array $config cleaned up
     */
    protected function validateParams($config) {

        $config = array_merge($this->defaultConfig, $config);

        /*if(empty($config['username'])) {
            throw new ServiceException(ServiceException::EMPTY_API_USERNAME);
        }

        if(empty($config['key'])) {
            throw new ServiceException(ServiceException::EMPTY_API_KEY);
        }*/

        try {
            $class = new ReflectionClass($config['transport_type'].'RestService');
        }
        catch(ReflectionException $e) {
            throw new ReflectionException(ServiceException::TRANSPORT_NOT_FOUND);
        }

        if(!$class->implementsInterface('RestServiceInterface')) {
            $config['transport_type'] = $this->defaultConfig['transport_type'];
        }

        return $config;
    }
    /**
     * global getter
     */
    public function get($var) {
        return $this->$var;
    }

    /**
     * global setter
     */
    public function set($var,$val) {
        $this->$var = $val;
        return $this;
    }
}


text:
package cn.sixlab.sixtools.site.update;

import cn.sixlab.sixtools.dao.base.BaseController;
import javafx.event.ActionEvent;
import javafx.fxml.Initializable;
import javafx.scene.control.Button;
import javafx.scene.control.Label;
import javafx.scene.web.WebView;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.net.URL;
import java.util.ResourceBundle;

/**
 * TODO
 *
 * @author 六楼的雨/Patrick Root
 * @date 2015/6/22 19:30
 */
public class SiteUpdateController extends BaseController implements Initializable {
    private static Logger logger = LoggerFactory.getLogger(SiteUpdateController.class);
    public static SiteUpdateController self;

    public WebView leftText;
    public WebView rightText;
    public Label tipsLabel;

    @Override
    public void initialize(URL location, ResourceBundle resources) {
        self = this;
    }

    public void itemClick(ActionEvent event) {
        Button btn = (Button) event.getTarget();
        String id = btn.getId();

        Crawler crawler = Crawler.init(id);

        String leftHtml = crawler.fetchOld();
        String rightHtml = crawler.fetchNew();
        leftText.getEngine().loadContent(leftHtml);
        rightText.getEngine().loadContent(rightHtml);
    }
}


text:
require 'stamina_test'
module Stamina
  module Dsl
    class CoreTest < StaminaTest
      include Stamina::Dsl

      def test_assert
        assert_nothing_raised{ assert(true, "no error") }
        assert_raise(Stamina::AssertionError){ assert(false, "an error") }
      end

    end
  end
end


text:
#ifndef QUICKSTEP_EXPRESSIONS_STREAM_GENERATOR_GENERATOR_FUNCTION_FACTORY_HPP_
#define QUICKSTEP_EXPRESSIONS_STREAM_GENERATOR_GENERATOR_FUNCTION_FACTORY_HPP_

#include <map>
#include <string>

#include "utility/Macros.hpp"

namespace quickstep {

class GeneratorFunction;
class GeneratorFunctionHandle;

namespace serialization { class GeneratorFunctionHandle; }

/** \addtogroup Expressions
 *  @{
 */

/**
 * @brief Singleton factory class that provides access to the various concrete
 *        implementations of GeneratorFunction.
 *
 * @note Generator functions are used for generating tables. A generator
 *       function takes a list of constant arguments at query compile time,
 *       and populates a table at query run time. See the documentation in
 *       GeneratorFunction.hpp for a detailed description and for how to
 *       implement a new generator function.
 **/
class GeneratorFunctionFactory {
 public:
  /**
   * @brief Singleton instance of the GeneratorFunctionFactory class.
   * @return A const reference to the singleton instance of the
   *         GeneratorFunctionFactory class.
   */
  static const GeneratorFunctionFactory& Instance();

  /**
   * @brief Get a particular GeneratorFunction by its name.
   *
   * @param name The name of the desired GeneratorFunction.
   * @return A pointer to the GeneratorFunction specified by name, or NULL if
   *         name does not match any known GeneratorFunction.
   **/
  const GeneratorFunction* getByName(const std::string &name) const;

  /**
   * @brief Reconstruct a particular GeneratorFunctionHandle by its protobuf
   *        message.
   *
   * @param proto A serialized protocol buffer representation of the
   *        GeneratorFunctionHandle.
   * @return A new GeneratorFunctionHandle object constructed from the protobuf
   *         message. Caller is responsible for deleting the returned object.
   */
  GeneratorFunctionHandle* reconstructFromProto(
      const serialization::GeneratorFunctionHandle &proto) const;

 private:
  /**
   * @brief Constructor. All the implemented generator functions should be
   *        registered into GeneratorFunctionFactory inside the constructor.
   */
  GeneratorFunctionFactory();

  std::map<std::string, const GeneratorFunction *> func_map_;

  DISALLOW_COPY_AND_ASSIGN(GeneratorFunctionFactory);
};

/** @} */

}  // namespace quickstep

#endif  // QUICKSTEP_EXPRESSIONS_STREAM_GENERATOR_GENERATOR_FUNCTION_FACTORY_HPP_


text:
import json
import logging
from django.template.loader import render_to_string
from django import template
from newsroom.models import Article, WetellBulletin
from django.template.loader import render_to_string

logger = logging.getLogger("django")

register = template.Library()

@register.simple_tag
def contains_class(field, cls):
    if 'class' in field.widget.attrs:
        if cls in field.widget.attrs['class']:
            return True
    return False

@register.simple_tag
def visible_btn(pk, field):
    pk = int(pk)
    article = Article.objects.get(pk=pk)
    if 'data-not' in field.widget.attrs: # data-not only has to exist for negation
        op = lambda x: not x
    else:
        op = lambda x: x
    if 'data-visible' in field.widget.attrs:
        attr = getattr(article, field.widget.attrs['data-visible'])
        if callable(attr):
            return op(attr())
        return op(attr)
    return op(True) # Default is visible

@register.simple_tag
def display_btn(field, start_html, end_html, cls):
    result = start_html
    result += "<button id='" + field.html_name + "' class='" + cls + "'>" + field.label + "</button>"
    result += end_html
    return result

def wetell_text(bulletin, intro_only=False):
    try:
        context = json.loads(bulletin.data)
    except Exception as e:
        msg = "Error converting bulletin data" + str(e)
        logger.error(msg)
        return

    context['published'] = bulletin.published
    if intro_only:
        return context['intro']
    else:
        text = render_to_string('newsroom/wetell.html', context)
    return text

@register.simple_tag
def wetell_by_pk(pk, intro_only=True):
    try:
        bulletin = WetellBulletin.objects.get(pk=pk)
    except WetellBulletin.DoesNotExist:
        logger.error("Wetell bulletin not found")
        return ""

    return wetell_text(bulletin, intro_only)

@register.simple_tag
def wetell():
    try:
        bulletin = WetellBulletin.objects.latest('published')
    except WetellBulletin.DoesNotExist:
        logger.error("Wetell bulletin not found")
        return

    return wetell_text(bulletin)


text:
#include "testutil.hpp"
#include "testutil_unity.hpp"

#include <stdlib.h>
#include <string.h>

SETUP_TEARDOWN_TESTCONTEXT

// SHALL receive incoming messages from its peers using a fair-queuing
// strategy.
void test_fair_queue_in (const char *bind_address)
{
    char connect_address[MAX_SOCKET_STRING];
    void *receiver = test_context_socket (ZMQ_ROUTER);

    int timeout = 250;
    TEST_ASSERT_SUCCESS_ERRNO (
      zmq_setsockopt (receiver, ZMQ_RCVTIMEO, &timeout, sizeof (int)));

    TEST_ASSERT_SUCCESS_ERRNO (zmq_bind (receiver, bind_address));
    size_t len = MAX_SOCKET_STRING;
    TEST_ASSERT_SUCCESS_ERRNO (
      zmq_getsockopt (receiver, ZMQ_LAST_ENDPOINT, connect_address, &len));

    const unsigned char services = 5;
    void *senders[services];
    for (unsigned char peer = 0; peer < services; ++peer) {
        senders[peer] = test_context_socket (ZMQ_DEALER);

        TEST_ASSERT_SUCCESS_ERRNO (
          zmq_setsockopt (senders[peer], ZMQ_RCVTIMEO, &timeout, sizeof (int)));

        char *str = strdup ("A");
        str[0] += peer;
        TEST_ASSERT_SUCCESS_ERRNO (
          zmq_setsockopt (senders[peer], ZMQ_ROUTING_ID, str, 2));
        free (str);

        TEST_ASSERT_SUCCESS_ERRNO (
          zmq_connect (senders[peer], connect_address));
    }

    msleep (SETTLE_TIME);

    zmq_msg_t msg;
    TEST_ASSERT_SUCCESS_ERRNO (zmq_msg_init (&msg));

    s_send_seq (senders[0], "M", SEQ_END);
    s_recv_seq (receiver, "A", "M", SEQ_END);

    s_send_seq (senders[0], "M", SEQ_END);
    s_recv_seq (receiver, "A", "M", SEQ_END);

    int sum = 0;

    // send N requests
    for (unsigned char peer = 0; peer < services; ++peer) {
        s_send_seq (senders[peer], "M", SEQ_END);
        sum += 'A' + peer;
    }

    TEST_ASSERT_EQUAL_INT (services * 'A' + services * (services - 1) / 2, sum);

    // handle N requests
    for (unsigned char peer = 0; peer < services; ++peer) {
        TEST_ASSERT_EQUAL_INT (
          2, TEST_ASSERT_SUCCESS_ERRNO (zmq_msg_recv (&msg, receiver, 0)));
        const char *id = static_cast<const char *> (zmq_msg_data (&msg));
        sum -= id[0];

        s_recv_seq (receiver, "M", SEQ_END);
    }

    TEST_ASSERT_EQUAL_INT (0, sum);

    TEST_ASSERT_SUCCESS_ERRNO (zmq_msg_close (&msg));

    test_context_socket_close_zero_linger (receiver);

    for (size_t peer = 0; peer < services; ++peer)
        test_context_socket_close_zero_linger (senders[peer]);

    // Wait for disconnects.
    msleep (SETTLE_TIME);
}

// SHALL create a double queue when a peer connects to it. If this peer
// disconnects, the ROUTER socket SHALL destroy its double queue and SHALL
// discard any messages it contains.
void test_destroy_queue_on_disconnect (const char *bind_address)
{
    void *a = test_context_socket (ZMQ_ROUTER);

    int enabled = 1;
    TEST_ASSERT_SUCCESS_ERRNO (
      zmq_setsockopt (a, ZMQ_ROUTER_MANDATORY, &enabled, sizeof (enabled)));

    TEST_ASSERT_SUCCESS_ERRNO (zmq_bind (a, bind_address));
    size_t len = MAX_SOCKET_STRING;
    char connect_address[MAX_SOCKET_STRING];
    TEST_ASSERT_SUCCESS_ERRNO (
      zmq_getsockopt (a, ZMQ_LAST_ENDPOINT, connect_address, &len));

    void *b = test_context_socket (ZMQ_DEALER);

    TEST_ASSERT_SUCCESS_ERRNO (zmq_setsockopt (b, ZMQ_ROUTING_ID, "B", 2));

    TEST_ASSERT_SUCCESS_ERRNO (zmq_connect (b, connect_address));

    // Wait for connection.
    msleep (SETTLE_TIME);

    // Send a message in both directions
    s_send_seq (a, "B", "ABC", SEQ_END);
    s_send_seq (b, "DEF", SEQ_END);

    TEST_ASSERT_SUCCESS_ERRNO (zmq_disconnect (b, connect_address));

    // Disconnect may take time and need command processing.
    zmq_pollitem_t poller[2] = {{a, 0, 0, 0}, {b, 0, 0, 0}};
    TEST_ASSERT_SUCCESS_ERRNO (zmq_poll (poller, 2, 100));
    TEST_ASSERT_SUCCESS_ERRNO (zmq_poll (poller, 2, 100));

    // No messages should be available, sending should fail.
    zmq_msg_t msg;
    zmq_msg_init (&msg);

    TEST_ASSERT_FAILURE_ERRNO (
      EHOSTUNREACH, zmq_send (a, "B", 2, ZMQ_SNDMORE | ZMQ_DONTWAIT));

    TEST_ASSERT_FAILURE_ERRNO (EAGAIN, zmq_msg_recv (&msg, a, ZMQ_DONTWAIT));

    // After a reconnect of B, the messages should still be gone
    TEST_ASSERT_SUCCESS_ERRNO (zmq_connect (b, connect_address));

    TEST_ASSERT_FAILURE_ERRNO (EAGAIN, zmq_msg_recv (&msg, a, ZMQ_DONTWAIT));

    TEST_ASSERT_FAILURE_ERRNO (EAGAIN, zmq_msg_recv (&msg, b, ZMQ_DONTWAIT));

    TEST_ASSERT_SUCCESS_ERRNO (zmq_msg_close (&msg));

    test_context_socket_close_zero_linger (a);
    test_context_socket_close_zero_linger (b);

    // Wait for disconnects.
    msleep (SETTLE_TIME);
}

#define TEST_SUITE(name, bind_address)                                         \
    void test_fair_queue_in_##name () { test_fair_queue_in (bind_address); }   \
    void test_destroy_queue_on_disconnect_##name ()                            \
    {                                                                          \
        test_destroy_queue_on_disconnect (bind_address);                       \
    }

TEST_SUITE (inproc, "inproc://a")
TEST_SUITE (tcp, "tcp://127.0.0.1:*")

int main ()
{
    setup_test_environment ();

    UNITY_BEGIN ();
    RUN_TEST (test_fair_queue_in_tcp);
    RUN_TEST (test_fair_queue_in_inproc);
    // TODO commented out until libzmq implements this properly
    // RUN_TEST (test_destroy_queue_on_disconnect_tcp);
    // RUN_TEST (test_destroy_queue_on_disconnect_inproc);
    return UNITY_END ();
}


text:
describe 'any data is_null comparison' do

  def any_data_is_null( type, value )
    value = value || 'NULL'
    sql = <<-SQL
      DECLARE
         result boolean;
      BEGIN
         result := #{type}( #{value} ).is_null();
         :x := CASE WHEN result THEN 1 WHEN NOT result THEN 0 END;
      END;
    SQL
    cursor = plsql.connection.parse(sql).bind_param(":x", nil, :data_type => 'NUMBER', :in_out => 'OUT')
    cursor.exec
    result = cursor[":x"].nil? ? nil : cursor[":x"]==1
    cursor.close
    result
  end

  it 'returns true when any_data value is NULL' do
    expect( any_data_is_null( 'any_data_number', NULL ) ).to eq true
  end

  it 'returns false when any_data value is not NULL' do
    expect( any_data_is_null( 'any_data_number', 1 ) ).to eq false
  end

end


text:
<!DOCTYPE html>

<title>Workmanship An Industrial Category Flat Bootstrap Responsive Website Template | Single :: w3layouts</title>

<meta name="viewport" content="width=device-width, initial-scale=1">
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<meta name="keywords" content="Workmanship Responsive web template, Bootstrap Web Templates, Flat Web Templates, Android Compatible web template,
Smartphone Compatible web template, free webdesigns for Nokia, Samsung, LG, SonyEricsson, Motorola web design" />

<link href="css/bootstrap.css" rel="stylesheet" type="text/css" media="all" />
<link href="css/style.css" rel="stylesheet" type="text/css" media="all" />
<link href="css/font-awesome.min.css" rel="stylesheet" type="text/css" media="all">

<link href='//fonts.googleapis.com/css?family=Montserrat:400,700' rel='stylesheet' type='text/css'>
<link href="//fonts.googleapis.com/css?family=Roboto+Condensed" rel="stylesheet">

					  <button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#bs-example-navbar-collapse-1">
						Toggle navigation

					  </button>

Workmanship The Real Industry

Home

About

								Pages

Font Icons

Typo

Gallery

Contact Us

						     <form action="#" method="post">
								<input type="search" name="Search" value="Search" onfocus="this.value = '';" onblur="if (this.value == '') {this.value = 'Search';}" required="">
								<input type="submit" value=" ">
							</form>

Contrary wipopular belief,Lorem Ipsum is not simply

Published on October 3

8 Comments

Contrary wipopular belief,Lorem Ipsum is not simply
						random text It has roots in a piece of
						classical Latin literature from
						Donec rutrum congue leo eget malesuada.Curabitur non nulla sit amet
						nisl tempus convallis quis ac lactus.Sed porttitor lactus nibh.Proin
						eget tortor risus.Nulla porttitor accumsan tincidunt.Nulla
						porttitoraccumsan tincidunt.
						Curabitur aliquet quam id dui posuere blandit.
						Nulla Quis lorum nisl tempus convallis quis ac lactus.Sed porttitorlactus nibh
						eget tortor risus.Nulla porttitor accumsan tincidunt.
						Contrary wipopular belief,Lorem Ipsum is not simply
						random text It has roots in a piece of
						classical Latin literature from
						Donec rutrum congue leo eget malesuada.Curabitur non nulla sit amet
						nisl tempus convallis quis ac lactus.Sed porttitor lactus nibh.Proin
						eget tortor risus.Nulla porttitor accumsan tincidunt.Nulla
						porttitoraccumsan tincidunt.

User

Porttitor

5 Tags

Tincidunt

Comments

Simmy

					  Cras sit amet nibh libero, in gravida nulla. Nulla vel metus
					  scelerisque ante sollicitudin commodo. Cras purus odio,
					  vestibulum in vulputate at, tempus viverra turpis.
					  Reply

Sandra Rickon

					  Cras sit amet nibh libero, in gravida nulla. Nulla vel metus
					  scelerisque ante sollicitudin commodo. Cras purus odio,
					  vestibulum in vulputate at, tempus viverra turpis.
					  Reply

Jhon Willium

					  Cras sit amet nibh libero, in gravida nulla. Nulla vel metus
					  scelerisque ante sollicitudin commodo. Cras purus odio,
					  vestibulum in vulputate at, tempus viverra turpis.
					  Reply

Leave a Comments Here

			    <form action="#" method="post">
					<input type="text" name="text" placeholder="Name" required=" ">
					<input type="text" name="email" placeholder="Email" required=" ">
					<input type="text" name="website" placeholder="Website" required=" ">
					<textarea name="message" placeholder="Meassage" required=" "></textarea>
					<input type="submit" value="Leave A Comment">

				</form>

Workmanship

mail@example.com

+2 000 222 1111

Navigation

Home

About us

Services

Typo

Contact

Support

Photo Gallery

Help Center

Lemollisollis

Newsletter

It was popularised in the 1960s with the release Ipsum.

					 <form action="#" method="post">
							<input type="text" class="text" value="Enter Email" onfocus="this.value = '';" onblur="if (this.value == '') {this.value = 'Enter Email';}">
							<input type="submit" value="Go">
				     </form>

Copyright © 2017 Workmanship. All Rights Reserved | Design By W3layouts


text:
package com.datastax.oss.driver.internal.core.session;

import com.datastax.oss.driver.api.core.config.DefaultDriverOption;
import com.datastax.oss.driver.api.core.config.DriverConfig;
import com.datastax.oss.driver.api.core.connection.BusyConnectionException;
import com.datastax.oss.driver.api.core.session.throttling.RequestThrottler;
import com.datastax.oss.driver.internal.core.adminrequest.AdminResult;
import com.datastax.oss.driver.internal.core.adminrequest.AdminRow;
import com.datastax.oss.driver.internal.core.adminrequest.ThrottledAdminRequestHandler;
import com.datastax.oss.driver.internal.core.channel.DriverChannel;
import com.datastax.oss.driver.internal.core.context.InternalDriverContext;
import com.datastax.oss.driver.internal.core.cql.CqlRequestHandler;
import com.datastax.oss.driver.internal.core.metrics.SessionMetricUpdater;
import com.datastax.oss.driver.internal.core.pool.ChannelPool;
import com.datastax.oss.driver.internal.core.util.concurrent.CompletableFutures;
import com.datastax.oss.driver.internal.core.util.concurrent.RunOrSchedule;
import com.datastax.oss.driver.shaded.guava.common.annotations.VisibleForTesting;
import com.datastax.oss.protocol.internal.Message;
import com.datastax.oss.protocol.internal.request.Prepare;
import com.datastax.oss.protocol.internal.request.Query;
import com.datastax.oss.protocol.internal.util.Bytes;
import io.netty.util.concurrent.EventExecutor;
import java.nio.ByteBuffer;
import java.time.Duration;
import java.util.ArrayDeque;
import java.util.Collections;
import java.util.HashSet;
import java.util.Map;
import java.util.Queue;
import java.util.Set;
import java.util.concurrent.CompletionStage;
import net.jcip.annotations.ThreadSafe;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * Ensures that a newly added or restarted node knows all the prepared statements created from this
 * driver instance.
 *
 *
See the comments in {@code reference.conf} for more explanations about this process. If any
 * prepare request fail, we ignore the error because it will be retried on the fly (see {@link
 * CqlRequestHandler}).
 *
 *
Logically this code belongs to {@link DefaultSession}, but it was extracted for modularity and
 * testability.
 */
@ThreadSafe
class ReprepareOnUp {

  private static final Logger LOG = LoggerFactory.getLogger(ReprepareOnUp.class);
  private static final Query QUERY_SERVER_IDS =
      new Query("SELECT prepared_id FROM system.prepared_statements");

  private final String logPrefix;
  private final ChannelPool pool;
  private final EventExecutor adminExecutor;
  private final Map<ByteBuffer, RepreparePayload> repreparePayloads;
  private final Runnable whenPrepared;
  private final boolean checkSystemTable;
  private final int maxStatements;
  private final int maxParallelism;
  private final Duration timeout;
  private final RequestThrottler throttler;
  private final SessionMetricUpdater metricUpdater;

  // After the constructor, everything happens on adminExecutor, so these fields do not need any
  // synchronization.
  private Set<ByteBuffer> serverKnownIds;
  private Queue<RepreparePayload> toReprepare;
  private int runningWorkers;

  ReprepareOnUp(
      String logPrefix,
      ChannelPool pool,
      EventExecutor adminExecutor,
      Map<ByteBuffer, RepreparePayload> repreparePayloads,
      InternalDriverContext context,
      Runnable whenPrepared) {

    this.logPrefix = logPrefix;
    this.pool = pool;
    this.adminExecutor = adminExecutor;
    this.repreparePayloads = repreparePayloads;
    this.whenPrepared = whenPrepared;
    this.throttler = context.getRequestThrottler();

    DriverConfig config = context.getConfig();
    this.checkSystemTable =
        config.getDefaultProfile().getBoolean(DefaultDriverOption.REPREPARE_CHECK_SYSTEM_TABLE);
    this.timeout = config.getDefaultProfile().getDuration(DefaultDriverOption.REPREPARE_TIMEOUT);
    this.maxStatements =
        config.getDefaultProfile().getInt(DefaultDriverOption.REPREPARE_MAX_STATEMENTS);
    this.maxParallelism =
        config.getDefaultProfile().getInt(DefaultDriverOption.REPREPARE_MAX_PARALLELISM);

    this.metricUpdater = context.getMetricsFactory().getSessionUpdater();
  }

  void start() {
    if (repreparePayloads.isEmpty()) {
      LOG.debug("[{}] No statements to reprepare, done", logPrefix);
      whenPrepared.run();
    } else {
      // Check log level because ConcurrentMap.size is not a constant operation
      if (LOG.isDebugEnabled()) {
        LOG.debug(
            "[{}] {} statements to reprepare on newly added/up node",
            logPrefix,
            repreparePayloads.size());
      }
      if (checkSystemTable) {
        LOG.debug("[{}] Checking which statements the server knows about", logPrefix);
        queryAsync(QUERY_SERVER_IDS, Collections.emptyMap(), "QUERY system.prepared_statements")
            .whenCompleteAsync(this::gatherServerIds, adminExecutor);
      } else {
        LOG.debug(
            "[{}] {} is disabled, repreparing directly",
            logPrefix,
            DefaultDriverOption.REPREPARE_CHECK_SYSTEM_TABLE.getPath());
        RunOrSchedule.on(
            adminExecutor,
            () -> {
              serverKnownIds = Collections.emptySet();
              gatherPayloadsToReprepare();
            });
      }
    }
  }

  private void gatherServerIds(AdminResult rows, Throwable error) {
    assert adminExecutor.inEventLoop();
    if (serverKnownIds == null) {
      serverKnownIds = new HashSet<>();
    }
    if (error != null) {
      LOG.debug(
          "[{}] Error querying system.prepared_statements ({}), proceeding without server ids",
          logPrefix,
          error.toString());
      gatherPayloadsToReprepare();
    } else {
      for (AdminRow row : rows) {
        serverKnownIds.add(row.getByteBuffer("prepared_id"));
      }
      if (rows.hasNextPage()) {
        LOG.debug("[{}] system.prepared_statements has more pages", logPrefix);
        rows.nextPage().whenCompleteAsync(this::gatherServerIds, adminExecutor);
      } else {
        LOG.debug("[{}] Gathered {} server ids, proceeding", logPrefix, serverKnownIds.size());
        gatherPayloadsToReprepare();
      }
    }
  }

  private void gatherPayloadsToReprepare() {
    assert adminExecutor.inEventLoop();
    toReprepare = new ArrayDeque<>();
    for (RepreparePayload payload : repreparePayloads.values()) {
      if (serverKnownIds.contains(payload.id)) {
        LOG.trace(
            "[{}] Skipping statement {} because it is already known to the server",
            logPrefix,
            Bytes.toHexString(payload.id));
      } else {
        if (maxStatements > 0 && toReprepare.size() == maxStatements) {
          LOG.debug(
              "[{}] Limiting number of statements to reprepare to {} as configured, "
                  + "but there are more",
              logPrefix,
              maxStatements);
          break;
        } else {
          toReprepare.add(payload);
        }
      }
    }
    if (toReprepare.isEmpty()) {
      LOG.debug(
          "[{}] No statements to reprepare that are not known by the server already, done",
          logPrefix);
      whenPrepared.run();
    } else {
      startWorkers();
    }
  }

  private void startWorkers() {
    assert adminExecutor.inEventLoop();
    runningWorkers = Math.min(maxParallelism, toReprepare.size());
    LOG.debug(
        "[{}] Repreparing {} statements with {} parallel workers",
        logPrefix,
        toReprepare.size(),
        runningWorkers);
    for (int i = 0; i < runningWorkers; i++) {
      startWorker();
    }
  }

  private void startWorker() {
    assert adminExecutor.inEventLoop();
    if (toReprepare.isEmpty()) {
      runningWorkers -= 1;
      if (runningWorkers == 0) {
        LOG.debug("[{}] All workers finished, done", logPrefix);
        whenPrepared.run();
      }
    } else {
      RepreparePayload payload = toReprepare.poll();
      prepareAsync(
              new Prepare(
                  payload.query, (payload.keyspace == null ? null : payload.keyspace.asInternal())),
              payload.customPayload)
          .handleAsync(
              (result, error) -> {
                // Don't log, AdminRequestHandler does already
                startWorker();
                return null;
              },
              adminExecutor);
    }
  }

  @VisibleForTesting
  protected CompletionStage<AdminResult> queryAsync(
      Message message, Map<String, ByteBuffer> customPayload, String debugString) {
    DriverChannel channel = pool.next();
    if (channel == null) {
      return CompletableFutures.failedFuture(
          new BusyConnectionException("Found no channel to execute reprepare query"));
    } else {
      ThrottledAdminRequestHandler<AdminResult> reprepareHandler =
          ThrottledAdminRequestHandler.query(
              channel,
              false,
              message,
              customPayload,
              timeout,
              throttler,
              metricUpdater,
              logPrefix,
              debugString);
      return reprepareHandler.start();
    }
  }

  @VisibleForTesting
  protected CompletionStage<ByteBuffer> prepareAsync(
      Message message, Map<String, ByteBuffer> customPayload) {
    DriverChannel channel = pool.next();
    if (channel == null) {
      return CompletableFutures.failedFuture(
          new BusyConnectionException("Found no channel to execute reprepare query"));
    } else {
      ThrottledAdminRequestHandler<ByteBuffer> reprepareHandler =
          ThrottledAdminRequestHandler.prepare(
              channel, false, message, customPayload, timeout, throttler, metricUpdater, logPrefix);
      return reprepareHandler.start();
    }
  }
}


text:
from ethel.wrappers.desktop_file_validate import parse_desktop_file_validate

STRINGS = [
    ('gsm.desktop: warning: value "GSM" for key "Comment" in group '
         '"Desktop Entry" looks redundant with value "GSM" of key "Name"',
    "warning"),

    ('gsm.desktop: error: value "AWESOME" for string list key "OnlyShowIn" '
        'in group "Desktop Entry" does not have a semicolon (\';\') as '
        'trailing character',
     "error"),

    ('polkit.desktop: warning: value "polkit" for key "Comment" in group '
        '"Desktop Entry" looks redundant with value "polkit" of key "Name"',
     "warning"),

    ('screensaver.desktop: warning: value "GSS" for key "Comment" in group '
        '"Desktop Entry" looks redundant with value "GSS" of key "Name"',
     "warning"),

    ('screensaver.desktop: error: value "AWESOME" for string list key '
        '"OnlyShowIn" in group "Desktop Entry" does not have a semicolon '
        '(\';\') as trailing character',
     "error"),

    ('sound.desktop: warning: value "GSA" for key "Comment" in group '
        '"Desktop Entry" looks redundant with value "GSA" of key "Name"',
     "warning"),
    ('update-notifier.desktop: warning: key "Encoding" in group '
            '"Desktop Entry" is deprecated',
     "warning"),
    ('xfce4.desktop: warning: value "XSM" for key "Comment" in group '
            '"Desktop Entry" looks redundant with value "XSM" of key "Name"',
     "warning"),
    ('xfce4.desktop: error: value "FLUXBOX" for string list key "OnlyShowIn" '
            'in group "Desktop Entry" does not have a semicolon (\';\') '
            'as trailing character',
     "error"),
    ('xfce4-settings-helper-autostart.desktop: error: required key "Type" in '
            'group "Desktop Entry" is not present',
     "error"),
    ('xfce4-settings-helper-autostart.desktop: error: required key "Name" in '
            'group "Desktop Entry" is not present',
     "error"),
]

def test_desktop_file_validate():
    for string, expected in STRINGS:
        issue = next(parse_desktop_file_validate([string]))
        assert issue.severity == expected


text:
#include <QDebug>
#include <QMessageBox>
#include <QFileDialog>

#include <fstream>

//####################################################################################
Editor::Editor(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::Editor)
{
    ui->setupUi(this);
}
//-----------------------------------------------------------------------------------
Editor::~Editor()
{
    delete ui;
}
//-----------------------------------------------------------------------------------
void Editor::on_action_LOAD_triggered()
{
    QFileDialog dialog {this};
    dialog.setFileMode(QFileDialog::ExistingFile);
    dialog.setViewMode(QFileDialog::List);
    dialog.setOption(QFileDialog::DontUseCustomDirectoryIcons);
    dialog.setNameFilter("Text (*.mu *.txt)");
    dialog.exec();
    auto files = dialog.selectedFiles();
    if (files.isEmpty())
        return;

    auto fileName = files[0];

    std::ifstream reader (fileName.toStdString(), std::ios_base::binary);

    if (!reader.good()) {
        QMessageBox::warning(this, "IO Error", "Could not load the file specified", QMessageBox::Ok, QMessageBox::Ok);
        return;
    }

    std::string data;
    do {
        char buffer[4096];
        reader.read(buffer, 4096);
        data.append(buffer, reader.gcount());
    } while (reader.gcount() == 4096);

    qDebug() << QString::fromStdString(data);
    builder_.loadMarkup(data);
    builder_.generateUiElements(ui->viewPort->layout());
}
//####################################################################################


text:
layout: post
category: podcast
title: "FKI0030 Temporary Redirect"
date: 2018-08-07 10:00:00+02:00
recording_date: 2018-07-25 21:00:00+02:00
file_url: "https://s3.eu-central-1.amazonaws.com/feinkost-intenet/fki0030.mp3"
file_duration: "00:59:40"
file_size: 43149588
permalink: /:title
redirect_from: /podcast/2018/08/07/fki0030.html
podcast_guid: http://www.feinkost-internet.de/podcast/2018/08/07/fki0030.html
team:
- josa
- robert
- stefan
---

Frei nach dem Motto _Wer anderen eine Grube gräbt, sollte nicht mit Bratwürsten werfen_ konzentriert sich auch diese Folge auf das Schwerpunkt Thema diese Woche: Internet und Neue Medien die es bereits seit 20 Jahren gibt. Werdet schnell Zeitzeuge bevor es jemand anderes bezeugt.

__Neue Challenge:__ Kalt duschen & 16 Stunden fasten pro Tag.

### Themen
- Thomas zahnt & Josa ist zurück
- Josa kehrt zurück (Merke: guter Titel für ein schwäbischen Thriller)
  - Minimalismus
  - Dinge die man nicht braucht entsorgen
  - Nachbarschaft
  - Drucken in der Cloud
- Sascha Baron Cohan: Who's America
- [Trump Baby in London](https://twitter.com/TrumpBabyUK/status/1017777049786822657)
- DSGVO für die DSGVO vor der DSGVO für die DSGVO
- Küchenstudios sind böse
- Robert kauft eine Küche
  - Traumküchen definieren
- Hubers Mancave
  - you don't know jack werbung
- Richtig ernähren mit Stefan. Ja. Mit Stefan.

### Picks
- Nicht updaten
- Beta Systeme updaten
- [Bitwig Studio](https://www.bitwig.com/en/home.html)