text:
<?xml version="1.0"?>
<!DOCTYPE tsung SYSTEM "/usr/share/tsung/tsung-1.0.dtd">
<tsung loglevel="debug" dumptraffic="true">

  <clients>
    <client host="localhost" use_controller_vm="false"/>
    <client host="localhost" use_controller_vm="false"/>
    <client host="localhost" use_controller_vm="false"/>
    <client host="localhost" use_controller_vm="false"/>
  </clients>

  <!-- Server side setup -->
  <servers>
    <server host="127.0.0.1" port="{{port}}" type="tcp"/>
  </servers>

  <monitoring>
    <monitor host="localhost"/>
  </monitoring>

  <load duration="{{70 * multiplicator}}" unit="second">

    <user session="{{sql}}-create-schema" start_time="0" unit="minute"></user>

    <arrivalphase phase="1" duration="{{5 * multiplicator}}" unit="second">
      <users maxnumber="0" interarrival="1" unit="minute"></users>
    </arrivalphase>

    <arrivalphase phase="2" duration="{{15 * multiplicator}}" unit="second">
      <session_setup name="{{sql}}-workload-fill" probability="100"/>
      <session_setup name="{{sql}}-workload-test" probability="0"/>
      <users arrivalrate="100" unit="second"></users>
    </arrivalphase>

    <arrivalphase phase="3" duration="{{5 * multiplicator}}" unit="second">
      <users maxnumber="0" interarrival="1" unit="minute"></users>
    </arrivalphase>

    <user session="{{sql}}-migrate-schema" start_time="{{40 * multiplicator}}" unit="second"></user>
    <arrivalphase phase="4" duration="{{45 * multiplicator}}" unit="second">
      <session_setup name="{{sql}}-workload-fill" probability="0"/>
      <session_setup name="{{sql}}-workload-test" probability="100"/>
      <users arrivalrate="50" unit="second"></users>
    </arrivalphase>

    <user session="{{sql}}-drop-schema" start_time="{{69 * multiplicator}}" unit="second"></user>

  </load>

  <sessions>

    <session probability="0" name="{{sql}}-create-schema" type="ts_{{sql}}">
      <request>
        <{{sql}} type="connect" database="{{database}}" username="{{user}}" />
      </request>
      <request>
        <{{sql}} type="authenticate" database="{{database}}" username="{{user}}" password="{{password}}" />
      </request>
      <request>
        <{{sql}} type="sql">CREATE DATABASE test_{{testname}}</{{sql}}>
      </request>
      <request>
        <{{sql}} type="close"></{{sql}}>
      </request>
      <request>
        <{{sql}} type="connect" database="test_{{testname}}" username="{{user}}" />
      </request>
      <request>
        <{{sql}} type="authenticate" database="test_{{testname}}" username="{{user}}" password="{{password}}" />
      </request>
      {% for statement in schema %}
      <request>
        <{{sql}} type="sql">{{ statement }}</{{sql}}>
      </request>
      {% endfor %}
      <request>
        <{{sql}} type="close"></{{sql}}>
      </request>
    </session>

    <session probability="0" name="{{sql}}-migrate-schema" type="ts_{{sql}}">
      <request>
        <{{sql}} type="connect" database="test_{{testname}}" username="{{user}}" />
      </request>
      <request>
        <{{sql}} type="authenticate" database="test_{{testname}}" username="{{user}}" password="{{password}}" />
      </request>
      {% for statement in migration %}
      <request>
        <{{sql}} type="sql">{{ statement }}</{{sql}}>
      </request>
      {% endfor %}
      <request>
        <{{sql}} type="close"></{{sql}}>
      </request>
    </session>

    <session probability="0" name="{{sql}}-drop-schema" type="ts_{{sql}}">
      <request>
        <{{sql}} type="connect" database="{{database}}" username="{{user}}" />
      </request>
      <request>
        <{{sql}} type="authenticate" database="{{database}}" username="{{user}}" password="{{password}}" />
      </request>
      <request tag="drop">
        <{{sql}} type="sql">DROP DATABASE test_{{testname}}</{{sql}}>
      </request>
      <request>
        <{{sql}} type="close"></{{sql}}>
      </request>
    </session>

    <session probability="0" name="{{sql}}-workload-fill" type="ts_{{sql}}">
      <setdynvars sourcetype="erlang" callback="ts_user_server:get_unique_id">
	<var name="id1" />
      </setdynvars>
      <setdynvars sourcetype="erlang" callback="ts_user_server:get_unique_id">
	<var name="id2" />
      </setdynvars>
      <setdynvars sourcetype="random_number" start="1" end="99999999">
	<var name="int1" />
      </setdynvars>
      <setdynvars sourcetype="random_number" start="1" end="99999999">
	<var name="int2" />
      </setdynvars>
      <setdynvars sourcetype="random_number" start="0" end="99">
	<var name="int3" />
      </setdynvars>
      <setdynvars sourcetype="random_string" length="30">
	<var name="str1" />
      </setdynvars>
      <setdynvars sourcetype="random_string" length="10">
	<var name="str2" />
      </setdynvars>
      <setdynvars sourcetype="random_string" length="10">
	<var name="str3" />
      </setdynvars>
      <request>
        <{{sql}} type="connect" database="test_{{testname}}" username="{{user}}" />
      </request>
      <request>
        <{{sql}} type="authenticate" database="test_{{testname}}" username="{{user}}" password="{{password}}" />
      </request>
      {% for statement in workload_fill %}
      <request subst="true">
        <{{sql}} type="sql">{{ statement }}</{{sql}}>
      </request>
      {% endfor %}
      <request>
        <{{sql}} type="close"></{{sql}}>
      </request>
  </session>

    <session probability="100" name="{{sql}}-workload-test" type="ts_{{sql}}">
      <setdynvars sourcetype="erlang" callback="ts_user_server:get_unique_id">
	<var name="id1" />
      </setdynvars>
      <setdynvars sourcetype="erlang" callback="ts_user_server:get_unique_id">
	<var name="id2" />
      </setdynvars>
      <setdynvars sourcetype="random_number" start="1" end="99999999">
	<var name="int1" />
      </setdynvars>
      <setdynvars sourcetype="random_number" start="1" end="99999999">
	<var name="int2" />
      </setdynvars>
      <setdynvars sourcetype="random_number" start="0" end="99">
	<var name="int3" />
      </setdynvars>
      <setdynvars sourcetype="random_string" length="30">
	<var name="str1" />
      </setdynvars>
      <setdynvars sourcetype="random_string" length="10">
	<var name="str2" />
      </setdynvars>
      <setdynvars sourcetype="random_string" length="10">
	<var name="str3" />
      </setdynvars>
      <request>
        <{{sql}} type="connect" database="test_{{testname}}" username="{{user}}" />
      </request>
      <request>
        <{{sql}} type="authenticate" database="test_{{testname}}" username="{{user}}" password="{{password}}" />
      </request>
      {% for statement in workload_test %}
      <request subst="true">
        <{{sql}} type="sql">{{ statement }}</{{sql}}>
      </request>
      <thinktime value="0.1" random="true"></thinktime>
      {% endfor %}
      <request>
        <{{sql}} type="close"></{{sql}}>
      </request>
  </session>
 </sessions>
</tsung>


text: search_result['2721']=["topic_0000000000000680_props--.html","MasterBadgesPersonDto Properties",""];

redpajama_set_name: RedPajamaGithub


text:
ACCUMULO_INSTANCE=${ACCUMULO_INSTANCE:=smac1}
ACCUMULO_ROOT_PASSWORD=${ACCUMULO_ROOT_PASSWORD:=smacword}
ACCUMULO_JDWP=${ACCUMULO_JDWP:=true}
ACCUMULO_NUM_TSERVERS=${ACCUMULO_NUM_TSERVERS:=1}
ACCUMULO_INIT_SCRIPT=${ACCUMULO_INIT_SCRIPT:=/smac-bin/config-sample.sh}
ACCUMULO_START_SHELL=${ACCUMULO_START_SHELL:=false}
ACCUMULO_SHUTDOWN_PORT=${ACCUMULO_SHUTDOWN_PORT:=4446}
if [ "${EXISTING_ZOOKEEPERS}x" == "x" ]; then
    EXISTING_ZOOKEEPERS=${EXISTING_ZOOKEEPERS}
else
    ZOOKEEPER_PORT=${ZOOKEEPER_PORT:=21821}
fi
LOG4J_CONFIG=${LOG4J_CONFIG:=/smac-bin/smac_logger.xml}
TSERV_CLIENTPORT=${TSERV_CLIENTPORT:='9997-9998'}
ACCUMULO_MONITOR_PORT=${ACCUMULO_MONITOR_PORT:=9995}


text:
package com.twotoasters.jobschedulerexample;

import android.app.job.JobParameters;
import android.app.job.JobService;
import android.os.AsyncTask;
import android.util.Log;

public class MyJobService extends JobService {
    static final String TAG = MyJobService.class.getSimpleName();

    private UpdateAppsAsyncTask updateTask = new UpdateAppsAsyncTask();

    @Override
    public boolean onStartJob(JobParameters params) {
        // Note: this is preformed on the main thread.
        Log.d(TAG, "onStartJob id=" + params.getJobId());
        updateTask.execute(params);

        return true;
    }

    // Stopping jobs if our job requires change.

    @Override
    public boolean onStopJob(JobParameters params) {
        // Note: return true to reschedule this job.

        Log.d(TAG, "onStopJob id=" + params.getJobId());
        boolean shouldReschedule = updateTask.stopJob(params);

        return shouldReschedule;
    }

    private class UpdateAppsAsyncTask extends AsyncTask<JobParameters, Void, JobParameters[]> {

        @Override
        protected JobParameters[] doInBackground(JobParameters... params) {

            // Do updating and stopping logical here.
            Log.d(TAG, "Updating apps in the background");
            return params;
        }

        @Override
        protected void onPostExecute(JobParameters[] result) {
            for (JobParameters params : result) {
                if (!hasJobBeenStopped(params)) {
                    Log.d(TAG, "finishing job with id=" + params.getJobId());
                    jobFinished(params, false);
                }
            }
        }

        private boolean hasJobBeenStopped(JobParameters params) {
            // Logic for checking stop.
            return false;
        }

        public boolean stopJob(JobParameters params) {
            Log.d(TAG, "stopJob id=" + params.getJobId());
            // Logic for stopping a job. return true if job should be rescheduled.
            return false;
        }

    }
}


text:
ADB=$ANDROID_HOME/platform-tools/adb

# This is a wrapper for adb.  If there are multiple devices / emulators, this script will prompt for which device to use

# Then it'll pass whatever commands to that specific device or emulator.

# Run adb devices once, in event adb hasn't been started yet
BLAH=$($ADB devices)

# Grab the IDs of all the connected devices / emulators
IDS=($($ADB devices | sed '1,1d' | sed '$d' | cut -f 1 | sort))
NUMIDS=${#IDS[@]}

# Check for number of connected devices / emulators
if [[ 0 -eq "$NUMIDS" ]]; then
  # No IDs, exit
  $ADB $@
  exit 0;
elif [[ 1 -eq "$NUMIDS" ]]; then
  # Just one device / emulator
  $ADB $@
  exit 0;
elif [[ "devices" == $1  ]]; then
  $ADB $@;
  exit 0;
elif [[ "-s" == $1 ]]; then
  $ADB $@;
  exit 0;
fi

# If we got here, there are multiple devices, need to get information then prompt user for which device/emulator to uninstall from

# Grab the model name for each device / emulator
declare -a MODEL_NAMES
for (( x=0; x < $NUMIDS; x++ )); do
  MODEL_NAMES[x]=$($ADB devices | grep ${IDS[$x]} | cut -f 1 | xargs -I $ $ADB -s $ shell cat /system/build.prop | grep "ro.product.model" | cut -d "=" -f 2 | tr -d ' \r\t\n')
done

# Grab the platform version for each device / emulator
declare -a PLATFORM_VERSIONS
for (( x=0; x < $NUMIDS; x++ )); do
  PLATFORM_VERSIONS[x]=$($ADB devices | grep ${IDS[$x]} | cut -f 1 | xargs -I $ $ADB -s $ shell cat /system/build.prop | grep "ro.build.version.release" | cut -d "=" -f 2 | tr -d ' \r\t\n')
done

echo "Multiple devices detected, please select one"
for (( x=0; x < $NUMIDS; x++ )); do
  echo -e "$[x+1]: ${IDS[x]}\t\t${PLATFORM_VERSIONS[x]}\t\t${MODEL_NAMES[x]}"
done
echo -n "> "
read USER_CHOICE

# Validate user entered a number
if [[ $USER_CHOICE =~ ^[0-9]+$ ]]; then
  echo "executing following command:"
  echo "    adb -s ${IDS[$USER_CHOICE-1]} $@"
  $ADB -s ${IDS[$USER_CHOICE-1]} $@
else
  echo "You must enter a number"
fi


text:
require 'spec_helper'
require 'nokogiri'
require 'pathname'

describe "Search engine sitemaps", :feature do
  include XmlHelpers

  it "produces a valid sitemap" do
    run_site 'dummy' do
      set :url_root, 'http://example.com'
      activate :search_engine_sitemap
      ignore '/ignored.html'
    end

    visit '/sitemap.xml'

    schema = Pathname(__dir__) + '../../sitemap.xsd'
    doc = Nokogiri::XML(last_response.body)
    expect(doc).to validate_against_schema(schema)

    expect(doc).to contain_node('url').with_children(
      'loc'        => 'http://example.com/home.html',
      'priority'   => '0.5',
      'changefreq' => 'monthly'
    )

    expect(doc).to contain_node('url').with_children(
      'loc'        => 'http://example.com/about.html',
      'priority'   => '0.2',
      'changefreq' => 'monthly'
    )

    expect(doc).to contain_node('url').with_children(
      'loc'        => 'http://example.com/blog.html',
      'priority'   => '0.5',
      'changefreq' => 'daily'
    )

    expect(doc.to_s).not_to include('http://example.com/ignored.html')
    expect(doc.to_s).not_to include('http://example.com/ignored-in-frontmatter.html')
  end

  it "works with directory indexes" do
    run_site 'dummy' do
      set :url_root, 'http://example.com'
      activate :directory_indexes
      activate :search_engine_sitemap

      ignore '/ignored.html'
    end

    visit '/sitemap.xml'
    doc = Nokogiri::XML(last_response.body)

    expect(doc).to contain_node('url').with_children(
      'loc'        => 'http://example.com/home/',
      'priority'   => '0.5',
      'changefreq' => 'monthly'
    )

    expect(doc).to contain_node('url').with_children(
      'loc'        => 'http://example.com/about/',
      'priority'   => '0.2',
      'changefreq' => 'monthly'
    )

    expect(doc).to contain_node('url').with_children(
      'loc'        => 'http://example.com/blog/',
      'priority'   => '0.5',
      'changefreq' => 'daily'
    )

    expect(doc.to_s).not_to include('http://example.com/ignored/')
    expect(doc.to_s).not_to include('http://example.com/ignored-in-frontmatter/')
  end

  it "supports custom URL processing" do
    run_site 'dummy' do
      set :url_root, 'http://example.com'
      activate :directory_indexes
      activate :search_engine_sitemap, process_url: ->(url) { url.upcase }
    end

    visit '/sitemap.xml'
    doc = Nokogiri::XML(last_response.body)

    expect(doc).to contain_node('url').with_children(
    'loc'        => 'HTTP://EXAMPLE.COM/HOME/',
    'priority'   => '0.5',
    'changefreq' => 'monthly'
    )
  end

  it "ignores resources based on exclude_if result" do
    run_site 'dummy' do
      set :url_root, 'http://example.com'
      activate :search_engine_sitemap,
        exclude_if: ->(resource) { resource.data.ignored_by_proc }

      ignore '/ignored.html'
    end

    visit '/sitemap.xml'
    doc = Nokogiri::XML(last_response.body)

    expect(doc.to_s).not_to include('http://example.com/ignored-by-proc.html')
  end
end


text:
require 'test_helper'

describe Kashmir do

  module DSLTesting
    class Recipe < OpenStruct
      include Kashmir

      representations do
        rep(:num_steps)
        rep(:title)
        rep(:chef)
        rep(:ingredients)
      end
    end

    class Chef < OpenStruct
      include Kashmir

      representations do
        rep(:full_name)
      end

      def full_name
        "#{first_name} #{last_name}"
      end
    end

    class SimpleRecipeRepresenter
      include Kashmir::Dsl

      prop :num_steps
      prop :title
    end

    class ChefRepresenter
      include Kashmir::Dsl

      prop :full_name
    end

    class RecipeWithChefRepresenter
      include Kashmir::Dsl

      prop :title
      embed :chef, ChefRepresenter
    end
  end

  before do
    @chef    = DSLTesting::Chef.new(first_name: 'Netto', last_name: 'Farah')
    @brisket = DSLTesting::Recipe.new(title: 'BBQ Brisket', num_steps: 2, chef: @chef)
  end

  it 'translates to representation definitions' do
    definitions = DSLTesting::SimpleRecipeRepresenter.definitions
    assert_equal definitions, [:num_steps, :title]
  end

  it 'generates the same representations as hardcoded definitions' do
    cooked_brisket = @brisket.represent([:num_steps, :title])
    assert_equal cooked_brisket, { title: 'BBQ Brisket', num_steps: 2 }
    assert_equal cooked_brisket, @brisket.represent(DSLTesting::SimpleRecipeRepresenter.definitions)
  end

  it 'generates nested representations' do
    brisket_with_chef = @brisket.represent([:title, { :chef => [:full_name] }])
    assert_equal brisket_with_chef, {
      title: 'BBQ Brisket',
      chef: {
        full_name: 'Netto Farah'
      }
    }

    assert_equal brisket_with_chef, @brisket.represent(DSLTesting::RecipeWithChefRepresenter.definitions)
  end

  describe 'Nested inline representations' do

    module DSLTesting
      class RecipeWithInlineChefRepresenter
        include Kashmir::Dsl

        prop :title

        inline :chef do
          prop :full_name
        end
      end

      class Ingredient < OpenStruct
        include Kashmir

        representations do
          rep(:name)
          rep(:quantity)
        end
      end
    end

    it 'generates nested representations' do
      brisket_with_chef = @brisket.represent([:title, { :chef => [:full_name] }])
      assert_equal brisket_with_chef, {
        title: 'BBQ Brisket',
        chef: {
          full_name: 'Netto Farah'
        }
      }

      assert_equal brisket_with_chef, @brisket.represent(DSLTesting::RecipeWithInlineChefRepresenter.definitions)
    end
  end

  describe 'Collections' do
    module DSLTesting
      class RecipeWithIngredientsRepresenter
        include Kashmir::Dsl

        prop :title

        inline :ingredients do
          prop :name
          prop :quantity
        end
      end
    end

    it 'generates nested collections' do
      @brisket.ingredients = [
        DSLTesting::Ingredient.new(name: 'Beef', quantity: '8oz'),
        DSLTesting::Ingredient.new(name: 'BBQ Sauce', quantity: 'plenty!'),
      ]

      cooked_brisket = {
        title: 'BBQ Brisket',
        ingredients: [
          { name: 'Beef', quantity: '8oz' },
          { name: 'BBQ Sauce', quantity: 'plenty!' }
        ]
      }

      assert_equal cooked_brisket, @brisket.represent(DSLTesting::RecipeWithIngredientsRepresenter.definitions)
    end
  end

  describe "Kashmir.props" do

    module DSLTesting

      class MultiPropRecipeRepresenter
        include Kashmir::Dsl

        props :num_steps, :title
      end
    end

    it 'allows the client to specify many props at once' do
      definitions = DSLTesting::MultiPropRecipeRepresenter.definitions
      assert_equal definitions, [:num_steps, :title]
    end
  end
end


text:
package pro.taskana.task.internal;

import java.time.Instant;
import java.util.List;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import pro.taskana.common.api.TaskanaRole;
import pro.taskana.common.api.exceptions.ConcurrencyException;
import pro.taskana.common.api.exceptions.InvalidArgumentException;
import pro.taskana.common.api.exceptions.NotAuthorizedException;
import pro.taskana.common.api.exceptions.SystemException;
import pro.taskana.common.internal.InternalTaskanaEngine;
import pro.taskana.common.internal.util.IdGenerator;
import pro.taskana.task.api.exceptions.MismatchedTaskCommentCreatorException;
import pro.taskana.task.api.exceptions.TaskCommentNotFoundException;
import pro.taskana.task.api.exceptions.TaskNotFoundException;
import pro.taskana.task.api.models.TaskComment;
import pro.taskana.task.internal.models.TaskCommentImpl;
import pro.taskana.user.api.models.User;
import pro.taskana.user.internal.UserMapper;

class TaskCommentServiceImpl {

  private static final Logger LOGGER = LoggerFactory.getLogger(TaskCommentServiceImpl.class);

  private final InternalTaskanaEngine taskanaEngine;
  private final TaskServiceImpl taskService;
  private final TaskCommentMapper taskCommentMapper;
  private final UserMapper userMapper;

  TaskCommentServiceImpl(
      InternalTaskanaEngine taskanaEngine,
      TaskCommentMapper taskCommentMapper,
      UserMapper userMapper,
      TaskServiceImpl taskService) {
    this.taskanaEngine = taskanaEngine;
    this.taskService = taskService;
    this.taskCommentMapper = taskCommentMapper;
    this.userMapper = userMapper;
  }

  TaskComment newTaskComment(String taskId) {

    TaskCommentImpl taskComment = new TaskCommentImpl();
    taskComment.setTaskId(taskId);

    return taskComment;
  }

  TaskComment updateTaskComment(TaskComment taskCommentToUpdate)
      throws NotAuthorizedException, ConcurrencyException, TaskCommentNotFoundException,
          TaskNotFoundException, InvalidArgumentException {

    String userId = taskanaEngine.getEngine().getCurrentUserContext().getUserid();

    TaskCommentImpl taskCommentImplToUpdate = (TaskCommentImpl) taskCommentToUpdate;

    try {

      taskanaEngine.openConnection();

      TaskComment originalTaskComment = getTaskComment(taskCommentImplToUpdate.getId());

      if (originalTaskComment.getCreator().equals(userId)
              && taskCommentImplToUpdate.getCreator().equals(originalTaskComment.getCreator())
          || taskanaEngine.getEngine().isUserInRole(TaskanaRole.ADMIN)
          || taskanaEngine.getEngine().isUserInRole(TaskanaRole.TASK_ADMIN)) {

        checkModifiedHasNotChanged(originalTaskComment, taskCommentImplToUpdate);

        taskCommentImplToUpdate.setModified(Instant.now());

        taskCommentMapper.update(taskCommentImplToUpdate);

        if (LOGGER.isDebugEnabled()) {
          LOGGER.debug(
              "Method updateTaskComment() updated taskComment '{}' for user '{}'.",
              taskCommentImplToUpdate.getId(),
              userId);
        }

      } else {
        throw new MismatchedTaskCommentCreatorException(userId, taskCommentImplToUpdate.getId());
      }
    } finally {
      taskanaEngine.returnConnection();
    }

    return taskCommentImplToUpdate;
  }

  TaskComment createTaskComment(TaskComment taskCommentToCreate)
      throws NotAuthorizedException, TaskNotFoundException, InvalidArgumentException {

    TaskCommentImpl taskCommentImplToCreate = (TaskCommentImpl) taskCommentToCreate;

    try {

      taskanaEngine.openConnection();

      taskService.getTask(taskCommentImplToCreate.getTaskId());

      validateNoneExistingTaskCommentId(taskCommentImplToCreate.getId());

      initDefaultTaskCommentValues(taskCommentImplToCreate);

      taskCommentMapper.insert(taskCommentImplToCreate);

    } finally {
      taskanaEngine.returnConnection();
    }

    return taskCommentImplToCreate;
  }

  void deleteTaskComment(String taskCommentId)
      throws NotAuthorizedException, TaskCommentNotFoundException, TaskNotFoundException,
          InvalidArgumentException {

    String userId = taskanaEngine.getEngine().getCurrentUserContext().getUserid();

    try {

      taskanaEngine.openConnection();

      TaskComment taskCommentToDelete = getTaskComment(taskCommentId);

      if (taskCommentToDelete.getCreator().equals(userId)
          || taskanaEngine.getEngine().isUserInRole(TaskanaRole.ADMIN)
          || taskanaEngine.getEngine().isUserInRole(TaskanaRole.TASK_ADMIN)) {

        taskCommentMapper.delete(taskCommentId);

        if (LOGGER.isDebugEnabled()) {
          LOGGER.debug("taskComment {} deleted", taskCommentToDelete.getId());
        }

      } else {
        throw new MismatchedTaskCommentCreatorException(userId, taskCommentToDelete.getId());
      }

    } finally {
      taskanaEngine.returnConnection();
    }
  }

  List<TaskComment> getTaskComments(String taskId)
      throws NotAuthorizedException, TaskNotFoundException {

    try {

      taskanaEngine.openConnection();

      taskService.getTask(taskId);

      List<TaskComment> taskComments = taskService.createTaskCommentQuery().taskIdIn(taskId).list();

      if (taskComments.isEmpty() && LOGGER.isDebugEnabled()) {
        LOGGER.debug("getTaskComments() found no comments for the provided taskId");
      }

      return taskComments;

    } finally {
      taskanaEngine.returnConnection();
    }
  }

  TaskComment getTaskComment(String taskCommentId)
      throws TaskCommentNotFoundException, NotAuthorizedException, TaskNotFoundException,
          InvalidArgumentException {

    TaskCommentImpl result;

    verifyTaskCommentIdIsNotNullOrEmpty(taskCommentId);

    try {

      taskanaEngine.openConnection();

      result = taskCommentMapper.findById(taskCommentId);

      if (result == null) {
        throw new TaskCommentNotFoundException(taskCommentId);
      }

      taskService.getTask(result.getTaskId());

      if (taskanaEngine.getEngine().getConfiguration().getAddAdditionalUserInfo()) {
        User creator = userMapper.findById(result.getCreator());
        if (creator != null) {
          result.setCreatorFullName(creator.getFullName());
        }
      }

      return result;

    } finally {
      taskanaEngine.returnConnection();
    }
  }

  private void checkModifiedHasNotChanged(
      TaskComment oldTaskComment, TaskComment taskCommentImplToUpdate) throws ConcurrencyException {

    if (!oldTaskComment.getModified().equals(taskCommentImplToUpdate.getModified())) {
      throw new ConcurrencyException(taskCommentImplToUpdate.getId());
    }
  }

  private void initDefaultTaskCommentValues(TaskCommentImpl taskCommentImplToCreate) {

    Instant now = Instant.now();

    taskCommentImplToCreate.setId(
        IdGenerator.generateWithPrefix(IdGenerator.ID_PREFIX_TASK_COMMENT));
    taskCommentImplToCreate.setModified(now);
    taskCommentImplToCreate.setCreated(now);

    String creator = taskanaEngine.getEngine().getCurrentUserContext().getUserid();
    if (taskanaEngine.getEngine().getConfiguration().isSecurityEnabled() && creator == null) {
      throw new SystemException(
          "TaskanaSecurity is enabled, but the current UserId is"
              + " NULL while creating a TaskComment.");
    }
    taskCommentImplToCreate.setCreator(creator);
  }

  private void validateNoneExistingTaskCommentId(String taskCommentId)
      throws InvalidArgumentException {

    if (taskCommentId != null && !taskCommentId.equals("")) {
      throw new InvalidArgumentException(
          String.format(
              "taskCommentId must be null/empty for creation, but found %s", taskCommentId));
    }
  }

  private void verifyTaskCommentIdIsNotNullOrEmpty(String taskCommentId)
      throws InvalidArgumentException {

    if (taskCommentId == null || taskCommentId.isEmpty()) {
      throw new InvalidArgumentException(
          "taskCommentId must not be null/empty for retrieval/deletion");
    }
  }
}


text:
.. _objects-description:

Objects Description
===================

.. _DashboardStatsCriteria-model:

:class:`DashboardStatsCriteria`
-------------------------------

To configure criteria for dashboard graphs

    **Attributes**:

        * ``criteria_name`` - Unique word .
        * ``criteria_fix_mapping`` - JSON data key-value pairs.
        * ``dynamic_criteria_field_name`` - Dynamic criteria field.
        * ``criteria_dynamic_mapping`` - JSON data key-value pairs.
        * ``created_date`` - record created date.
        * ``updated_date`` - record updated date.

    **Name of DB table**: dash_stats_criteria

.. _DashboardStats-model:

:class:`DashboardStats`
-----------------------

To configure graphs for dashboard

    **Attributes**:

        * ``graph_key`` - unique graph name.
        * ``graph_title`` - graph title.
        * ``model_app_name`` - App name of model.
        * ``model_name`` - model name.
        * ``date_field_name`` - Date field of model_name.
        * ``criteria`` - many-to-many relationship.
        * ``is_visible`` - enable/disable.
        * ``created_date`` - record created date.
        * ``updated_date`` - record updated date.

    **Name of DB table**: dashboard_stats


text:
import datetime
import logging
import time

try:
    from lmfit import Model, Parameters, minimize, report_ci, report_fit
except ImportError as e:
    logging.warning(
        "Could not import lmfit. This is needed " "for fitting (run pip install lmfit)."
    )
    logging.debug(e)

import math

import matplotlib.pyplot as plt
import numpy as np
import pandas as pd

from cellpy import cellreader

# TODO: (28.05.2017 jepe) Docstrings are missing!!!!!!!! - AU: fix!

# some utility functions

# TODO: (05.10.2019 jepe) This function is slow due to use of loops. Should fix it.
def select_ocv_points(
    cellpydata,
    cycles=None,
    selection_method="martin",
    number_of_points=5,
    interval=10,
    relative_voltage=False,
    report_times=False,
    direction="both",
    return_times=False,
):

    """Select points from the ocvrlx steps.

    Args:
        cellpydata: ``CellpyCell-object``
        cycles: list of cycle numbers to process (optional)
        selection_method ('martin' | 'fixed_times'): criteria for selecting points ('martin': select first and last, and
            then last/2, last/2/2 etc. until you have reached the wanted number of points; 'fixed_times': select first,
            and then same interval between each subsequent point).
        number_of_points: number of points you want.
        interval: interval between each point (in use only for methods
            where interval makes sense). If it is a list, then
            number_of_points will be calculated as len(interval) + 1 (and
            override the set number_of_points).
        relative_voltage: set to True if you would like the voltage to be
            relative to the voltage before starting the ocv rlx step.
            Defaults to False. Remark that for the initial rxl step (when
            you just have put your cell on the tester) does not have any
            prior voltage. The relative voltage will then be versus the
            first measurement point.
        report_times: also report the ocv rlx total time if True (defaults
            to False)
        direction ("up", "down" or "both"): select "up" if you would like
            to process only the ocv rlx steps where the voltage is relaxing
            upwards and vice versa. Defaults to "both".
        return_times (bool): return a DataFrame with information about times.

    Returns:
        ``pandas.DataFrame`` (and another ``pandas.DataFrame`` if return_times is True)

    """

    # TODO @jepe: refactor and use col names directly from HeadersNormal instead:

    t0 = time.time()
    if cycles is None:
        cycles = cellpydata.get_cycle_numbers()
    else:
        if not isinstance(cycles, (list, tuple)):
            cycles = [cycles]

    if not isinstance(interval, (list, tuple)):
        interval = [float(interval) for _ in range(number_of_points - 1)]

    ocv_rlx_id = "ocvrlx"

    step_table = cellpydata.data.steps
    dfdata = cellpydata.data.raw

    ocv_steps = step_table.loc[step_table["cycle"].isin(cycles), :]

    ocv_steps = ocv_steps.loc[ocv_steps.type.str.startswith(ocv_rlx_id, na=False), :]

    t1 = time.time() - t0

    if selection_method in ["fixed_times", "fixed_points", "selected_times"]:
        number_of_points = len(interval) + 1

    headers2 = []
    for j in range(number_of_points):
        n = str(j).zfill(2)
        headers2.append(f"point_{n}")

    t2 = time.time() - t0
    # doing an iteration (thought I didnt have to, but...) (fix later)

    results_list = list()
    info_dict = {"cycle": [], "dt": [], "dv": [], "step": [], "type": [], "method": []}

    iter_range = number_of_points - 1
    if selection_method == "martin":
        iter_range -= 1

    # very slow:
    for index, row in ocv_steps.iterrows():

        # voltage
        first, last, delta = (
            row["voltage_first"],
            row["voltage_last"],
            row["voltage_delta"],
        )

        voltage_reference = 0.0

        if relative_voltage:
            if index > 0:
                reference_row = step_table.iloc[index - 1, :]
                voltage_reference = reference_row["voltage_last"]

            else:
                voltage_reference = first
                logging.warning("STEP 0: Using first point as ref voltage")

        # time
        start, end, duration = (
            row["step_time_first"],
            row["step_time_last"],
            row["step_time_delta"],
        )

        cycle, step = (row["cycle"], row["step"])
        info = row["type"]

        v_df = dfdata.loc[
            (dfdata["cycle_index"] == cycle) & (dfdata["step_index"] == step),
            ["step_time", "voltage"],
        ]

        poi = []

        _end = end
        _start = start

        t = datetime.timedelta(seconds=round(end - start, 0))

        info_dict["method"].append(selection_method)
        info_dict["cycle"].append(cycle)
        info_dict["step"].append(step)
        info_dict["type"].append(info)
        info_dict["dt"].append(t)
        info_dict["dv"].append(first - last)

        if report_times:
            print(f"Cycle {cycle}:", end=" ")
            print(f"dt = {str(t)}, dv = {first-last:6.3f}")

        for i, j in enumerate(range(max(1, iter_range))):
            if selection_method == "martin":
                # logging.debug("using the 'martin'-method")
                _end = _end / 2.0
                poi.append(_end)

            elif selection_method == "fixed_times":
                logging.debug(f"using fixed times with interval {interval[i]}")
                _start = _start + interval[i]
                logging.debug(f"time: {_start}")
                poi.append(_start)
            else:
                # more methods to come?
                logging.info("this method is not implemented")
                return None

        if selection_method == "martin":
            poi.reverse()

        df_poi = pd.DataFrame({"step_time": poi})
        df_poi["voltage"] = np.nan

        v_df = v_df.append(df_poi, ignore_index=True)
        v_df = v_df.sort_values("step_time").reset_index(drop=True)
        v_df["new"] = v_df["voltage"].interpolate()

        voi = []
        for p in poi:
            _v = v_df.loc[v_df["step_time"].isin([p]), "new"].values
            _v = _v - voltage_reference
            voi.append(_v[0])

        poi.insert(0, start)
        voi.insert(0, first - voltage_reference)
        if selection_method == "martin":
            poi.append(end)
            voi.append(last - voltage_reference)

        d1 = {"cycle": cycle}
        d2 = {h: [v] for h, v in zip(headers2, voi)}
        d = {**d1, **d2}
        result = pd.DataFrame(d)
        result["step"] = step
        result["type"] = info
        results_list.append(result)

        if "t0" not in info_dict:
            for i, p in enumerate(poi):
                info_dict[f"t{i}"] = [p]
        else:
            for i, p in enumerate(poi):
                info_dict[f"t{i}"].append(p)

    t3 = time.time() - t0

    final = pd.concat(results_list)  # pretty slow

    t4 = time.time() - t0

    if direction == "down":
        final = final.loc[final["type"] == "ocvrlx_down", :]
    elif direction == "up":
        final = final.loc[final["type"] == "ocvrlx_up", :]

    final = final.reset_index(drop=True)

    # print(f"t1: {t1}\nt2: {t2-t1}\nt3: {t3-t2-t1}\nt4: {t4-t3-t2-t1}\n")

    if not return_times:
        return final

    else:
        try:
            info_pd = pd.DataFrame(info_dict)
        except Exception as e:
            logging.info("could not create dataframe with time information")
            logging.info(e)
            info_pd = None
        return final, info_pd

class MultiCycleOcvFit(object):
    def __init__(self, cellpydata, cycles, circuits=3):
        """Object for performing fitting of multiple cycles.

        Args:
            cellpydata: ``CellpyCell-object``
            cycles (list): cycles to fit.
            circuits (int): number of circuits to use in fitting.
        """
        self.cycles = cycles
        self.data = cellpydata
        self.circuits = circuits

        self.fit_cycles = []
        self.result = []
        self.best_fit_data = []
        self.best_fit_parameters = []
        self.best_fit_parameters_translated = []

    def set_data(self, cellpydata):
        """Sets the CellpyCell."""

        self.data = cellpydata

    def set_cycles(self, cycles):
        """Sets the cycles."""

        self.cycles = cycles

    def run_fitting(self, direction="up", weighted=True):
        """

        Args:
            direction ('up' | 'down'): what type of ocv relaxation to fit
            weighted (bool): use weighted fitting.

        Returns:
            None

        """

        # TODO @jepe: refactor and use col names directly from HeadersNormal instead:

        ocv_fitter = OcvFit()
        ocv_fitter.set_circuits(self.circuits)
        time_voltage = self.data.get_ocv(direction=direction, cycles=self.cycles[0])
        time = time_voltage.step_time
        voltage = time_voltage.voltage
        if voltage is not None and time is not None:
            ocv_fitter.set_data(time, voltage)
        else:
            ocv_fitter.set_data([0, 1, 2, 3], [2, 2, 2, 2])

        try:
            ocv_fitter.create_model()
        except AttributeError as e:
            print(e)
            return

        for cycle in self.cycles:
            print("Fitting cycle " + str(cycle))
            time_voltage = self.data.get_ocv(direction=direction, cycles=cycle)
            time = time_voltage.step_time
            voltage = time_voltage.voltage

            if voltage is not None:
                step_table = self.data.data.steps
                hdr = self.data.headers_step_table
                if direction == "up":
                    end_voltage = step_table[
                        (step_table["cycle"] == cycle)
                        & (step_table["type"].isin(["discharge"]))
                    ][hdr.voltage + "_last"].values[0]
                    end_current = step_table[
                        (step_table["cycle"] == cycle)
                        & (step_table["type"].isin(["discharge"]))
                    ][hdr.current + "_last"].values[0]
                    ocv_fitter.set_zero_voltage(end_voltage)
                    ocv_fitter.set_zero_current(end_current)
                elif direction == "down":
                    end_voltage = step_table[
                        (step_table["cycle"] == cycle)
                        & (step_table["type"].isin(["charge"]))
                    ][hdr.voltage + "_last"].values[0]
                    end_current = step_table[
                        (step_table["cycle"] == cycle)
                        & (step_table["type"].isin(["charge"]))
                    ][hdr.current + "_last"].values[0]
                    ocv_fitter.set_zero_voltage(end_voltage)
                    ocv_fitter.set_zero_current(end_current)

                ocv_fitter.set_data(time, voltage)
                if weighted:
                    ocv_fitter.set_weights_power_law()
                ocv_fitter.run_fit()

                self.fit_cycles.append(cycle)
                self.result.append(ocv_fitter.get_result())
                self.best_fit_parameters.append(ocv_fitter.get_best_fit_parameters())
                self.best_fit_parameters_translated.append(
                    ocv_fitter.get_best_fit_parameters_translated()
                )
                self.best_fit_data.append(ocv_fitter.get_best_fit_data())

    def get_best_fit_data(self):
        """Returns the best fit data."""
        return self.best_fit_data

    def get_best_fit_parameters(self):
        """Returns parameters for the best fit."""
        return self.best_fit_parameters

    def get_best_fit_parameters_translated(self):
        """Returns the parameters in 'real units' for the best fit."""
        return self.best_fit_parameters_translated

    def get_best_fit_parameters_grouped(self):
        """Returns a dictionary of the best fit."""
        result_dict = dict()
        result_dict["ocv"] = [
            parameters["ocv"] for parameters in self.best_fit_parameters
        ]

        for i in range(self.circuits):
            result_dict["t" + str(i)] = [
                parameters["t" + str(i)] for parameters in self.best_fit_parameters
            ]
            result_dict["w" + str(i)] = [
                parameters["w" + str(i)] for parameters in self.best_fit_parameters
            ]
        return result_dict

    def get_best_fit_parameters_translated_grouped(self):
        """Returns the parameters as a dictionary of the 'real units'
        for the best fit."""
        result_dict = dict()
        result_dict["ocv"] = [
            parameters["ocv"] for parameters in self.best_fit_parameters_translated
        ]
        result_dict["ir"] = [
            parameters["ir"] for parameters in self.best_fit_parameters_translated
        ]

        for i in range(self.circuits):
            result_dict["r" + str(i)] = [
                parameters["r" + str(i)]
                for parameters in self.best_fit_parameters_translated
            ]
            result_dict["c" + str(i)] = [
                parameters["c" + str(i)]
                for parameters in self.best_fit_parameters_translated
            ]
        return result_dict

    def get_fit_cycles(self):
        """Returns the fit cycles"""
        return self.fit_cycles

    def plot_summary(self, cycles=None):
        """Convenience function for plotting the summary of the fit"""
        if cycles is None:
            cycles = [0]
        fig1 = plt.figure()
        ax1 = fig1.add_subplot(221)
        ax1.set_title("Fit")
        ax2 = fig1.add_subplot(222)
        ax2.set_title("OCV")
        ax3 = fig1.add_subplot(223)
        ax3.set_title("Tau")
        ax3.set_yscale("log")
        ax4 = fig1.add_subplot(224)
        ax4.set_title("Voltage Impact")

        plot_data = self.get_best_fit_data()
        for cycle in cycles:
            ax1.plot(plot_data[cycle][0], plot_data[cycle][1])
            ax1.plot(plot_data[cycle][0], plot_data[cycle][2])

        plot_data = self.get_best_fit_parameters_grouped()

        for i in range(self.circuits):
            ax3.plot(self.get_fit_cycles(), plot_data["t" + str(i)])
            ax4.plot(self.get_fit_cycles(), plot_data["w" + str(i)])

        ax2.plot(self.get_fit_cycles(), plot_data["ocv"])

    def plot_summary_translated(self):
        """Convenience function for plotting the summary of the
        fit (translated)"""

        fig2 = plt.figure()
        ax1 = fig2.add_subplot(221)
        ax1.set_title("OCV (V)")
        ax2 = fig2.add_subplot(222)
        ax2.set_title("IR (Ohm)")
        ax3 = fig2.add_subplot(223)
        ax3.set_title("Resistances (Ohm)")
        ax4 = fig2.add_subplot(224)
        ax4.set_title("Capacitances (F)")
        ax4.set_yscale("log")

        plot_data = self.get_best_fit_parameters_translated_grouped()
        print(plot_data["ocv"])
        print(plot_data["ir"])
        print(plot_data["r0"])

        ax1.plot(self.get_fit_cycles(), plot_data["ocv"])
        ax2.plot(self.get_fit_cycles(), plot_data["ir"])

        for i in range(self.circuits):
            ax3.plot(self.get_fit_cycles(), plot_data["r" + str(i)])
            ax4.plot(self.get_fit_cycles(), plot_data["c" + str(i)])

        plt.show()

class OcvFit(object):
    """Class for fitting open circuit relaxation data."""

    def __init__(self, zero_current=0.1, zero_voltage=0.05):
        self.data = None
        self.weights = None
        self.time = []
        self.voltage = []
        self.steps = ""
        self.circuits = 3
        self.zero_current = zero_current
        self.zero_voltage = zero_voltage

        self.model = None
        self.params = Parameters()

        self.result = None
        self.best_fit_data = dict()
        self.best_fit_parameters = dict()

    def set_cellpydata(self, cellpydata, cycle):
        """Performing fit of the OCV steps in the cycles set by set_cycles()
        from the data set by set_data()

        r is found by calculating v0 / i_start --> err(r)= err(v0) + err(i_start).

        c is found from using tau / r --> err(c) = err(r) + err(tau).

        Args:
            cellpydata (CellpyCell): data object from cellreader
            cycle (int): cycle number to get from CellpyCell object

        Returns:
            None

        """
        self.data = cellpydata
        self.steps = self.data.data  # hope it works...
        time_voltage = self.data.get_ocv(direction="up", cycles=cycle)
        time = time_voltage.step_time
        voltage = time_voltage.voltage

        self.time = np.array(time)
        self.voltage = np.array(voltage)

    def set_data(self, time, voltage):
        self.time = np.array(time)
        self.voltage = np.array(voltage)

    def set_zero_current(self, zero_current):
        self.zero_current = zero_current

    def set_zero_voltage(self, zero_voltage):
        self.zero_voltage = zero_voltage

    def set_circuits(self, circuits):
        self.circuits = circuits

    def set_weights(self, weights):
        self.weights = weights

    def reset_weights(self):
        self.weights = None

    def set_weights_power_law(self, prefactor=1, power=-2, zero_level=1):
        if self.voltage is not None:
            self.weights = [
                prefactor * pow(time + 1, power) + zero_level for time in self.time
            ]
        else:
            raise NotImplementedError("Data is not set. Set data using set_data().")

    def create_model(self):
        params = Parameters()
        params.add("ocv", value=self.voltage[-1], min=0, max=10)
        taus = [math.pow(10, i) for i in range(self.circuits)]
        weights = np.zeros(self.circuits)

        params.add("t0", value=taus[0], min=0.01)
        params.add("w0", value=weights[0])

        for i in range(1, self.circuits):
            params.add("delta" + str(i), value=taus[i] - taus[i - 1], min=0.0)
            params.add("t" + str(i), expr="delta" + str(i) + "+t" + str(i - 1))
            params.add("w" + str(i), value=weights[i])
        for i in range(self.circuits, 5):
            params.add("t" + str(i), value=1, vary=False)
            params.add("w" + str(i), value=0, vary=False)

        self.params = params
        self.model = Model(self._model)

    @staticmethod
    def _model(time, ocv, t0, w0, t1, w1, t2, w2, t3, w3, t4, w4):
        # Calculates a voltage profile for the given
        # time array for a given set of parameters
        model = ocv
        model = (
            model
            + w0 * np.exp(-time / t0)
            + w1 * np.exp(-time / t1)
            + w2 * np.exp(-time / t2)
            + w3 * np.exp(-time / t3)
            + w4 * np.exp(-time / t4)
        )

        return model

    def fit_model(self):

        if self.model is not None:
            self.result = self.model.fit(
                self.voltage, weights=self.weights, time=self.time, params=self.params
            )
        else:
            raise NotImplementedError(
                "Model is not created. Set model using create_model()."
            )

        self.best_fit_parameters = self.result.best_values
        self.best_fit_data = [self.time, self.voltage, self.result.best_fit]

    def run_fit(self):
        """Performing fit of the OCV steps in the cycles set by set_cycles()
        from the data set by set_data()

        r is found by calculating v0 / i_start --> err(r)= err(v0) + err(i_start).

        c is found from using tau / r --> err(c) = err(r) + err(tau).

        The resulting best fit parameters are stored in self.result for the given cycles.

        Returns:
            None

        """

        # Check if data is set
        if self.time is []:
            self.result = []
            return

        try:
            self.fit_model()
        except ValueError as e:
            print(e)
        except AttributeError as e:
            print(e)

    def get_result(self):
        return self.result

    def get_best_fit_data(self):
        return self.best_fit_data

    def get_best_fit_parameters(self):
        return self.best_fit_parameters

    def get_best_fit_parameters_translated(self):
        result_dict = dict()
        result_dict["ocv"] = self.best_fit_parameters["ocv"]
        result_dict["ir"] = (
            -(
                (
                    self.best_fit_parameters["ocv"]
                    + self.best_fit_parameters["w0"]
                    + self.best_fit_parameters["w1"]
                    + self.best_fit_parameters["w2"]
                    + self.best_fit_parameters["w3"]
                    + self.best_fit_parameters["w4"]
                )
                - self.zero_voltage
            )
            / self.zero_current
        )

        for i in range(self.circuits):
            result_dict["r" + str(i)] = (
                self.best_fit_parameters["w" + str(i)] / self.zero_current
            )
            result_dict["c" + str(i)] = (
                self.best_fit_parameters["t" + str(i)] / result_dict["r" + str(i)]
            )

        return result_dict

def _main():
    import os

    import matplotlib.pyplot as plt

    from cellpy import cellreader

    print(50 * "=")
    print("FITTING OCV ROUTINES - TEST")
    print(50 * "-")

    # filename(s) and folders etc
    resfilename = "20160809_TF7_A1_04_cc_02.res"
    resfilename = "20160216_snx001_01_cc_01.res"
    resfilename = "20160216_snx001_02_cc_01.res"
    resfilename = "20170310_snx002_03_cc_01.res"
    # resfilename = "20160306_snx001_09_cc_01.res"
    # resfilename = "20150501_TF7_A1_01_cc_01.res"
    resfilename = "20160805_test001_45_cc_01.res"
    resfilename = "20160306_snx001_07_cc_02.res"
    resfilename = "20160306_snx001_08_cc_02.res"
    resfilename = "20160306_snx001_10_cc_01.res"

    single_cell = False

    datafolder_in = r"..\data_ex"
    datafolder_out = r"..\outdata"

    # parameters about the run (mass (mg))
    mass = 0.982

    # cycles to test
    cycles = [i * 10 for i in range(1, 10)]
    cycles = [i * 1 for i in range(1, 100)]
    print(50 * "-")
    print("Loading data")
    print(50 * "-")

    print("loading file", end=" ")
    print(resfilename)

    # Loading dataframe
    d = cellreader.CellpyCell()
    # noinspection PyDeprecation
    d.from_raw(os.path.join(datafolder_in, resfilename))
    d.set_mass(mass)
    d.make_step_table()

    if single_cell:
        # Sending data to ocv_fit object and running fit
        ocv_fit = OcvFit()
        ocv_fit.set_cellpydata(d, 1)
        ocv_fit.set_circuits(4)
        ocv_fit.create_model()
        ocv_fit.run_fit()

        fig1 = plt.figure()
        fig1.suptitle("Fit")
        ax1 = fig1.add_subplot(111)

        plot_data = ocv_fit.get_best_fit_data()
        ax1.plot(plot_data[0], plot_data[1])
        ax1.plot(plot_data[0], plot_data[2])

        plt.show()

    else:
        ocv_fit = MultiCycleOcvFit(d, cycles, circuits=3)
        ocv_fit.run_fitting(direction="up")
        ocv_fit.plot_summary([0])
        ocv_fit.plot_summary_translated()

        # # Printing best fit parameters
        # for best_fit_parameters in ocv_fit.get_best_fit_parameters():
        #     print 50 * '-'
        #     print best_fit_parameters

if __name__ == "__main__":
    print("ocv-rlx".center(80, "="))
    _main()


text:
using JetBrains.Annotations;
using Txt.Core;
using Txt.ABNF;

namespace Hls.EXT_X_STREAM_INF
{
    public sealed class ExtStreamInfLexer : CompositeLexer<Concatenation, ExtStreamInf>
    {
        public ExtStreamInfLexer([NotNull] ILexer<Concatenation> innerLexer)
            : base(innerLexer)
        {
        }
    }
}


text:
package org.carewebframework.vista.api.domain;

import static org.junit.Assert.assertEquals;

import java.net.URISyntaxException;

import org.carewebframework.api.domain.DomainFactoryRegistry;
import org.carewebframework.api.test.CommonTest;
import org.carewebframework.vista.api.property.PropertyDefinition;

import org.junit.Test;

public class JsonTest extends CommonTest {

    @Test
    public void test() throws URISyntaxException {
        PropertyDefinition def = DomainFactoryRegistry.fetchObject(PropertyDefinition.class, "1");
        assertEquals("1", def.getId().getIdPart());
    }

}


text:
const readline = require('readline')
const style = require('./style')

/**
 * Terminal interaction
 *
 * @param {string|array} questions
 * @param {string} [customStyle='cyan'] style
 * @returns
 */
function prompt (questions, customStyle = 'cyan') {
  const rl = readline.createInterface({
    input: process.stdin,
    output: process.stdout,
    prompt: 'OHAI> '
  })
  const prompts = typeof questions === 'string' ? [questions] : questions
  let index = 0
  const answers = []
  const get = () => {
    rl.setPrompt(style[customStyle](prompts[index]))
    rl.prompt()
    index++
  }
  get()

  return new Promise(resolve => {
    rl
      .on('line', answer => {
        answers.push(answer)
        if (index === prompts.length) {
          return rl.close()
        }
        get()
      })
      .on('close', () => {
        resolve(prompts.length > 1 ? answers : answers[0])
      })
  })
}

module.exports = {
  prompt
}


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
  "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
    <title>Jasmine Spec Runner</title>

 <link rel="stylesheet" type="text/css" href="jasmine.css">
  <script type="text/javascript" src="jasmine.js"></script>
  <script type="text/javascript" src="jasmine-html.js"></script>
  <script type="text/javascript" src="../../TestFiles/Jasmine/jasmine-ddescribe-iit.js"></script>
  <script type="text/javascript" src="jasmine-ddescribe.js"></script>

  <script type="text/javascript">
      (function () {
          var jasmineEnv = jasmine.getEnv();
          jasmineEnv.updateInterval = 1000;

          var htmlReporter = new jasmine.HtmlReporter();

          jasmineEnv.addReporter(htmlReporter);

          jasmineEnv.specFilter = function (spec) {
              return htmlReporter.specFilter(spec);
          };

          var currentWindowOnload = window.onload;

          window.onload = function () {

              if (currentWindowOnload) {
                  currentWindowOnload();
              }

              jasmineEnv.execute();
          };

      })();
  </script>

</head>

<body>
</body>
</html>


text:
package com.consol.citrus.integration.variables;

import com.consol.citrus.annotations.CitrusXmlTest;
import com.consol.citrus.testng.spring.TestNGCitrusSpringSupport;
import org.testng.annotations.Test;

/**
 * Test the use of property loader with global variables and general variable support.
 * Global variables are loaded in advance to this test. Variables are printed within this test
 * to show that global property loader works fine.
 *
 * @author Philipp Komninos
 * @since 2010
 */
public class GlobalVariablesIT extends TestNGCitrusSpringSupport {
    @Test
    @CitrusXmlTest
    public void GlobalVariablesIT() {}
}


text:
package gov.nasa.arc.spife.ui.timeline.model;

import java.util.Date;

import javax.measure.quantity.Duration;

import org.eclipse.emf.common.notify.Notification;
import org.eclipse.emf.common.notify.impl.AdapterImpl;
import org.eclipse.emf.edit.provider.ChangeNotifier;
import org.eclipse.emf.edit.provider.IChangeNotifier;
import org.eclipse.emf.edit.provider.IDisposable;
import org.eclipse.emf.edit.provider.INotifyChangedListener;
import org.jscience.physics.amount.Amount;

public abstract class TemporalProvider extends AdapterImpl implements IChangeNotifier, IDisposable {

	private final IChangeNotifier notifier = new ChangeNotifier();

	public abstract Date getStartTime(Object object);

	public abstract Amount<Duration> getDuration(Object object);

	@Override
	public void addListener(INotifyChangedListener notifyChangedListener) {
		notifier.addListener(notifyChangedListener);
	}

	@Override
	public void fireNotifyChanged(Notification notification) {
		notifier.fireNotifyChanged(notification);
	}

	@Override
	public void removeListener(INotifyChangedListener notifyChangedListener) {
		notifier.removeListener(notifyChangedListener);
	}

	@Override
	public void dispose() {
		// no default implementation
	}

}


text:
function SchemaCompiler(builder) {
  this.builder = builder;
  this.initCompiler();
}

function buildTable(type) {
  return function(tableName, fn) {
    var TableBuilder = this.client.TableBuilder;
    var sql = new TableBuilder(type, tableName, fn).toSQL();
    for (var i = 0, l = sql.length; i < l; i++) {
      this.sequence.push(sql[i]);
    }
  };
}

SchemaCompiler.prototype.createTable = buildTable('create');
SchemaCompiler.prototype.alterTable  = buildTable('alter');
SchemaCompiler.prototype.dropTable = function(tableName) {
  this.pushQuery('drop table ' + this.formatter.wrap(tableName));
};
SchemaCompiler.prototype.dropTableIfExists = function(tableName) {
  this.pushQuery('drop table if exists ' + this.formatter.wrap(tableName));
};
SchemaCompiler.prototype.toSQL = function() {
  var sequence = this.builder._sequence;
  for (var i = 0, l = sequence.length; i < l; i++) {
    var query = sequence[i];
    this[query.method].apply(this, query.args);
  }
  return this.sequence;
};
SchemaCompiler.prototype.raw = function(sql, bindings) {
  this.sequence.push(new this.client.Raw(sql, bindings).toSQL());
};

module.exports = SchemaCompiler;


text:
#ifndef	_LINUX_PAGE_H_
#define _LINUX_PAGE_H_

#include <linux/types.h>

#include <sys/param.h>

#include <vm/vm.h>
#include <vm/vm_page.h>

#define page	vm_page

#define	virt_to_page(x)	PHYS_TO_VM_PAGE(vtophys((x)))

#define	clear_page(page)		memset((page), 0, PAGE_SIZE)
#define	pgprot_noncached(prot)		VM_MEMATTR_UNCACHEABLE
#define	pgprot_writecombine(prot)	VM_MEMATTR_WRITE_COMBINING

#undef	PAGE_MASK
#define	PAGE_MASK	(~(PAGE_SIZE-1))

#endif	/* _LINUX_PAGE_H_ */


text:
{{define "page"}}
<!DOCTYPE html>

  <meta charset="UTF-8">
  {{if .MobileFriendly}}
    <meta name="viewport" content="width=device-width, initial-scale=1">
  {{end}}
  <title>{{block "title" .Arguments}}Prow{{ end }}</title>
  <link rel="stylesheet" type="text/css" href="/static/style.css">
  <link rel="stylesheet" type="text/css" href="/static/extensions/style.css">
  <link href="https://fonts.googleapis.com/css?family=Roboto:400,700" rel="stylesheet">
  <link rel="stylesheet" href="https://fonts.googleapis.com/icon?family=Material+Icons">
  <link rel="stylesheet" href="https://code.getmdl.io/1.3.0/material.indigo-pink.min.css">

  {{block "scripts" .Arguments}}{{end}}

      {{block "pageTitle" .Arguments}}{{template "title" .}}{{end}}

    Prow Dashboard

      Prow Status
      {{ if sections.PR }}
        PR Status
      {{ end }}
      Command Help
      {{ if sections.Tide }}
        Tide Status
      {{ end }}
      Plugins
      Documentation open_in_new

      {{deckVersion}}

    {{block "content" .Arguments}}{{end}}

{{block "extra content" .Arguments}}{{end}}

  <button class="mdl-snackbar__action" type="button"></button>

{{end}}


text:
package com.ogoutay.robomocki3.activities;

import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.widget.TextView;

import com.ogoutay.robomocki3.R;
import com.ogoutay.robomocki3.interfaces.ManagerCallback;
import com.ogoutay.robomocki3.managers.ExampleManager;

/**
 * Just a regular {@link android.app.Activity} for reflection/mock purpose
 */
public class MainActivity extends AppCompatActivity implements ManagerCallback {

    public final static String TAG = "MainActivity";

    private TextView mTextView;

    private final ExampleManager mExampleManager = new ExampleManager();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        mTextView = findViewById(R.id.textView);
    }

    @Override
    protected void onResume() {
        super.onResume();

        mTextView.setText(mExampleManager.getServiceName());
        mExampleManager.fetchVisibility(this);
        mExampleManager.setString(TAG);
    }

    @Override
    public void onVisibilityFetched(int visibility) {
        mTextView.setVisibility(visibility);
    }

}


text:
<?php

    if (!class_exists('DOPBSPTranslationTextTools')){
        class DOPBSPTranslationTextTools{
            /*
             * Constructor
             */
            function __construct(){
                /*
                 * Initialize tools text.
                 */
                add_filter('dopbsp_filter_translation_text', array(&$this, 'tools'));
                add_filter('dopbsp_filter_translation_text', array(&$this, 'toolsHelp'));

                add_filter('dopbsp_filter_translation_text', array(&$this, 'toolsRepairCalendarsSettings'));
                add_filter('dopbsp_filter_translation_text', array(&$this, 'toolsRepairDatabaseText'));
                add_filter('dopbsp_filter_translation_text', array(&$this, 'toolsRepairSearchSettings'));
            }

            /*
             * Tools text.
             *
             * @param lang (array): current translation
             *
             * @return array with updated translation
             */
            function tools($text){
                array_push($text, array('key' => 'PARENT_TOOLS',
                                        'parent' => '',
                                        'text' => 'Tools'));

                array_push($text, array('key' => 'TOOLS_TITLE',
                                        'parent' => 'PARENT_TOOLS',
                                        'text' => 'Tools'));

                return $text;
            }

            /*
             * Tools help text.
             *
             * @param lang (array): current translation
             *
             * @return array with updated translation
             */
            function toolsHelp($text){
                array_push($text, array('key' => 'PARENT_TOOLS_HELP',
                                        'parent' => '',
                                        'text' => 'Tools - Help'));

                array_push($text, array('key' => 'TOOLS_HELP',
                                        'parent' => 'PARENT_TOOLS_HELP',
                                        'text' => 'Tools to help you with some of the booking system needs.'));

                return $text;
            }

            /*
             * Tools repair calendars settings text.
             *
             * @param lang (array): current translation
             *
             * @return array with updated translation
             */
            function toolsRepairCalendarsSettings($text){
                array_push($text, array('key' => 'PARENT_TOOLS_REPAIR_CALENDARS_SETTINGS',
                                        'parent' => '',
                                        'text' => 'Tools - Repair calendars settings'));

                array_push($text, array('key' => 'TOOLS_REPAIR_CALENDARS_SETTINGS_TITLE',
                                        'parent' => 'PARENT_TOOLS_REPAIR_CALENDARS_SETTINGS',
                                        'text' => 'Repair calendars settings'));

                array_push($text, array('key' => 'TOOLS_REPAIR_CALENDARS_SETTINGS_CONFIRMATION',
                                        'parent' => 'PARENT_TOOLS_REPAIR_CALENDARS_SETTINGS',
                                        'text' => 'Are you sure you want to start calendars settings repairs?'));
                array_push($text, array('key' => 'TOOLS_REPAIR_CALENDARS_SETTINGS_REPAIRING',
                                        'parent' => 'PARENT_TOOLS_REPAIR_CALENDARS_SETTINGS',
                                        'text' => 'Repairing calendars settings ...'));
                array_push($text, array('key' => 'TOOLS_REPAIR_CALENDARS_SETTINGS_SUCCESS',
                                        'parent' => 'PARENT_TOOLS_REPAIR_CALENDARS_SETTINGS',
                                        'text' => 'The settings have been repaired.'));

                array_push($text, array('key' => 'TOOLS_REPAIR_CALENDARS_SETTINGS_CALENDARS',
                                        'parent' => 'PARENT_TOOLS_REPAIR_CALENDARS_SETTINGS',
                                        'text' => 'Calendars'));
                array_push($text, array('key' => 'TOOLS_REPAIR_CALENDARS_SETTINGS_SETTINGS_DATABASE',
                                        'parent' => 'PARENT_TOOLS_REPAIR_CALENDARS_SETTINGS',
                                        'text' => 'Settings database'));
                array_push($text, array('key' => 'TOOLS_REPAIR_CALENDARS_SETTINGS_NOTIFICATIONS_DATABASE',
                                        'parent' => 'PARENT_TOOLS_REPAIR_CALENDARS_SETTINGS',
                                        'text' => 'Notifications database'));
                array_push($text, array('key' => 'TOOLS_REPAIR_CALENDARS_SETTINGS_PAYMENT_DATABASE',
                                        'parent' => 'PARENT_TOOLS_REPAIR_CALENDARS_SETTINGS',
                                        'text' => 'Payment database'));

                array_push($text, array('key' => 'TOOLS_REPAIR_CALENDARS_SETTINGS_UNCHANGED',
                                        'parent' => 'PARENT_TOOLS_REPAIR_CALENDARS_SETTINGS',
                                        'text' => 'Unchanged'));
                array_push($text, array('key' => 'TOOLS_REPAIR_CALENDARS_SETTINGS_REPAIRED',
                                        'parent' => 'PARENT_TOOLS_REPAIR_CALENDARS_SETTINGS',
                                        'text' => 'Repaired'));

                return $text;
            }

            /*
             * Tools repair database & text text.
             *
             * @param lang (array): current translation
             *
             * @return array with updated translation
             */
            function toolsRepairDatabaseText($text){
                array_push($text, array('key' => 'PARENT_TOOLS_REPAIR_DATABASE_TEXT',
                                        'parent' => '',
                                        'text' => 'Tools - Repair database & text'));

                array_push($text, array('key' => 'TOOLS_REPAIR_DATABASE_TEXT_TITLE',
                                        'parent' => 'PARENT_TOOLS_REPAIR_DATABASE_TEXT',
                                        'text' => 'Repair database & text'));

                array_push($text, array('key' => 'TOOLS_REPAIR_DATABASE_TEXT_CONFIRMATION',
                                        'parent' => 'PARENT_TOOLS_REPAIR_DATABASE_TEXT',
                                        'text' => 'Are you sure you want to verify the database & the text and repair them if needed?'));
                array_push($text, array('key' => 'TOOLS_REPAIR_DATABASE_TEXT_REPAIRING',
                                        'parent' => 'PARENT_TOOLS_REPAIR_DATABASE_TEXT',
                                        'text' => 'Verifying and repairing the database & the text ...'));
                array_push($text, array('key' => 'TOOLS_REPAIR_DATABASE_TEXT_SUCCESS',
                                        'parent' => 'PARENT_TOOLS_REPAIR_DATABASE_TEXT',
                                        'text' => 'The database & the text have been verified and repaired. The page will redirect shortly to Dashboard.'));

                return $text;
            }

            /*
             * Tools repair search settings text.
             *
             * @param lang (array): current translation
             *
             * @return array with updated translation
             */
            function toolsRepairSearchSettings($text){
                array_push($text, array('key' => 'PARENT_TOOLS_REPAIR_SEARCH_SETTINGS',
                                        'parent' => '',
                                        'text' => 'Tools - Repair search settings'));

                array_push($text, array('key' => 'TOOLS_REPAIR_SEARCH_SETTINGS_TITLE',
                                        'parent' => 'PARENT_TOOLS_REPAIR_SEARCH_SETTINGS',
                                        'text' => 'Repair search settings'));

                array_push($text, array('key' => 'TOOLS_REPAIR_SEARCH_SETTINGS_CONFIRMATION',
                                        'parent' => 'PARENT_TOOLS_REPAIR_SEARCH_SETTINGS',
                                        'text' => 'Are you sure you want to start search settings repairs?'));
                array_push($text, array('key' => 'TOOLS_REPAIR_SEARCH_SETTINGS_REPAIRING',
                                        'parent' => 'PARENT_TOOLS_REPAIR_SEARCH_SETTINGS',
                                        'text' => 'Repairing search settings ...'));
                array_push($text, array('key' => 'TOOLS_REPAIR_SEARCH_SETTINGS_SUCCESS',
                                        'parent' => 'PARENT_TOOLS_REPAIR_SEARCH_SETTINGS',
                                        'text' => 'The settings have been repaired.'));

                array_push($text, array('key' => 'TOOLS_REPAIR_SEARCH_SETTINGS_SEARCHES',
                                        'parent' => 'PARENT_TOOLS_REPAIR_SEARCH_SETTINGS',
                                        'text' => 'Searches'));
                array_push($text, array('key' => 'TOOLS_REPAIR_SEARCH_SETTINGS_SETTINGS_DATABASE',
                                        'parent' => 'PARENT_TOOLS_REPAIR_SEARCH_SETTINGS',
                                        'text' => 'Settings database'));

                array_push($text, array('key' => 'TOOLS_REPAIR_SEARCH_SETTINGS_UNCHANGED',
                                        'parent' => 'PARENT_TOOLS_REPAIR_SEARCH_SETTINGS',
                                        'text' => 'Unchanged'));
                array_push($text, array('key' => 'TOOLS_REPAIR_SEARCH_SETTINGS_REPAIRED',
                                        'parent' => 'PARENT_TOOLS_REPAIR_SEARCH_SETTINGS',
                                        'text' => 'Repaired'));

                return $text;
            }
        }
    }


text:
require 'spec_helper'

describe Hashie::Extensions::Mash::SafeAssignment do
  class MashWithSafeAssignment < Hashie::Mash
    include Hashie::Extensions::Mash::SafeAssignment

    private

    def my_own_private
      :hello!
    end
  end

  context 'when included in Mash' do
    subject { MashWithSafeAssignment.new }

    context 'when not attempting to override a method' do
      it 'assigns just fine' do
        expect do
          subject.blabla = 'Test'
          subject.blabla = 'Test'
        end.to_not raise_error
      end
    end

    context 'when attempting to override a method' do
      it 'raises an error' do
        expect { subject.zip = 'Test' }.to raise_error(ArgumentError)
      end
    end

    context 'when attempting to override a private method' do
      it 'raises an error' do
        expect { subject.my_own_private = 'Test' }.to raise_error(ArgumentError)
      end
    end

    context 'when attempting to initialize with predefined method' do
      it 'raises an error' do
        expect { MashWithSafeAssignment.new(zip: true) }.to raise_error(ArgumentError)
      end
    end

    context 'when setting as a hash key' do
      it 'still raises if conflicts with a method' do
        expect { subject[:zip] = 'Test' }.to raise_error(ArgumentError)
      end
    end
  end
end


text:
package org.fckfaces.component.html;

import java.io.IOException;

import javax.faces.component.html.HtmlInputTextarea;
import javax.faces.context.ExternalContext;
import javax.faces.context.FacesContext;
import javax.faces.context.ResponseWriter;

import org.apache.commons.lang.StringUtils;
import org.fckfaces.taglib.html.FCKFaceEditorTag;
import org.fckfaces.util.Util;

/**
 *
 * @author srecinto
 *
 */
public class FCKFaceEditor extends HtmlInputTextarea {
	public static final String CUSTOM_CONFIGURATION_PATH = "org.fckfaces.CUSTOM_CONFIGURATIONS_PATH";
	public static final String COMPONENT_FAMILY = "org.fckfaces.FCKFacesFamily";
	private String toolbarSet;
	private String height;
	private String width;

	/**
	 *
	 */
	public String getComponentType() {
		return FCKFaceEditorTag.COMPONENT_TYPE;
	}

	/**
	 *
	 */
	public String getRendererType() {
		return FCKFaceEditorTag.RENDERER_TYPE;
	}

	/**
	 * Moved to encode end so that the inline java script will run after the textArea was rendered before this script is run
	 * @param context
	 * @throws IOException
	 */
	public void encodeEnd(FacesContext context) throws IOException {
		super.encodeEnd(context);

		ResponseWriter writer = context.getResponseWriter();

		//Initial Configuration
		final ExternalContext external = context.getExternalContext();
		String cstConfigPathParam = external.getInitParameter(CUSTOM_CONFIGURATION_PATH);

		//Initial JS link
		writer.startElement("script", this.getParent());
		writer.writeAttribute("type", "text/javascript", null);
		writer.writeAttribute("src", Util.internalPath("/FCKeditor/fckeditor.js"), null);
		writer.endElement("script");

		writer.startElement("script", this.getParent());

		String toolBar = "Default";
		if(StringUtils.isNotBlank(toolbarSet)) {
			toolBar = toolbarSet;
		}

		String heightJS = "";
		String widthJS = "";
		String configPathJS = "";

		if(StringUtils.isNotBlank(height)) {
			heightJS = "oFCKeditor.Height = '" + height + "';\r\n";
		}

		if(StringUtils.isNotBlank(width)) {
			widthJS = "oFCKeditor.Width = '" + width + "';\r\n";
		}

		if (StringUtils.isNotBlank(cstConfigPathParam) ) {
			cstConfigPathParam = Util.externalPath(cstConfigPathParam);
			configPathJS = "   oFCKeditor.Config['CustomConfigurationsPath']='"+cstConfigPathParam+"';\r\n";
		}

		String js =
		"function applyEditor" + this.getId() +"() {" +
		"	var sBasePath = '" + Util.internalPath("/FCKeditor/") + "';\r\n" +
		"	var sTextAreaName = '" + this.getClientId(context) + "';\r\n" +
		"	var oFCKeditor = new FCKeditor( sTextAreaName ) ;\r\n" +
		configPathJS +
		"	oFCKeditor.BasePath	= sBasePath ;\r\n" +
		"	oFCKeditor.ToolbarSet='" + toolBar + "';\r\n" +
		heightJS +
		widthJS +
		"	oFCKeditor.ReplaceTextarea(); \r\n" +
		"	var oTextbox = document.getElementById(sTextAreaName);\r\n" +
		"	if(oTextbox.hasChildNodes()) {\r\n" +
		"		var oTextNode;\r\n" +
		"		var oParentNode = oTextbox.parentNode;\r\n" +
		"		if(oTextbox.childNodes.length > 1) {\r\n" +
		"			for(var i = 0; i < oTextbox.childNodes.length; i++) {\r\n" +
		"				if(oTextbox.childNodes.item(i).nodeType != 3 ) { //Not a Text node\r\n" +
		"					oParentNode.appendChild(oTextbox.removeChild(oTextbox.childNodes.item(i)));\r\n" +
		"					i = i - 1;\r\n" +
		"				}\r\n" +
		"			}\r\n" +
		"		}\r\n" +
		"	}\r\n" +
		"}" +
		"applyEditor" + this.getId() +"();";

		writer.writeText(js, null);
		writer.endElement("script");
	}

	/**
	 *
	 * @return
	 */
	public String getFamily() {
		return COMPONENT_FAMILY;
	}

	public Object saveState(FacesContext context) {
		Object values[] = new Object[2];
		values[0] = super.saveState(context);
		values[1] = toolbarSet;

		return values;
	}

	public void restoreState(FacesContext context, Object state) {
		Object values[] = (Object[]) state;
		super.restoreState(context, values[0]);
		this.toolbarSet = (String)values[1];
	}

	public String getToolbarSet() {
		return toolbarSet;
	}

	public void setToolbarSet(String toolbarSet) {
		this.toolbarSet = toolbarSet;
	}

	public String getHeight() {
		return height;
	}

	public void setHeight(String height) {
		this.height = height;
	}

	public String getWidth() {
		return width;
	}

	public void setWidth(String width) {
		this.width = width;
	}
}


text:
gitalias() {
  local the_type
  the_type=$(type "$LBUFFER")

  if [[ $the_type =~ 'alias for git' ]]; then
    zle _expand_alias
  fi
  zle self-insert
}

zle -N gitalias

# space expands all aliases, including global
bindkey -M emacs " " gitalias
bindkey -M viins " " gitalias

# control-space to make a normal space
bindkey -M emacs "^ " magic-space
bindkey -M viins "^ " magic-space

# normal space during searches
bindkey -M isearch " " magic-space


text:
package libcore.base;

public final class Objects {
    private Objects() {}

    /**
     * Returns true if two possibly-null objects are equal.
     */
    public static boolean equal(Object a, Object b) {
        return a == b || (a != null && a.equals(b));
    }
}


text:
 Back

DVT Prophylaxis

Is there a high bleeding risk?

Frank intracranial bleeding

Incomplete SCI with perispinal bleeding

Active major bleeding or very high bleeding risk

Yes

Mechanical thromboprophylaxis only.

If high bleeding risk resolves, add LMWH

No

Begin LMWH (40 mg sc daily) +/- mechanical prophylaxis acutely.

In the inpatient rehabilitation phase, can choose LMWH, warfarin (INR 2-3), or direct oral anticoagulant.

Continue thromboprophylaxis at least 8 weeks and while admitted to inpatient rehabilitation.

Chronic SCI patients should receive thromboprophylaxis during time period of increased risk.

Do not routinely screen with Doppler ultrasound for clinically inapparent DVT on admission to rehabilitation.

References

Consortium for spinal cord medicine. Prevention of venous thromboembolism in individuals with spinal cord injury. Clinical practice guidelines, Paralyzed veterans of America 2016(3rd edition).

Kirshblum S, Nieves J, Clark D, Gonzalez P, Cuccurullo SJ, Luciano L. Physical Medicine and Rehabilitation Board Review. Cuccurullo SJ LJ, editor. 3 rd ed. New York, NY: Demos Medical; 2015. Chapter 7, Spinal cord injuries. p.551-620.


text:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
           "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<meta http-equiv="Content-Type" content="text/html; charset=UTF-8"/>
<title>Coverage Report Classes</title>
<link title="Style" type="text/css" rel="stylesheet" href="css/main.css"/>

All Packages

Classes

App (0%)

Page (46%)

PageFetchListener (N/A)

PageFetcher (91%)

PageFetcherPool (40%)

SiteMap (0%)

UriParser (90%)

WebCrawler (100%)


text:
static NSString *const LOGGER_SECTION = @"AllPackageSettingsMigrator";
static NSString *const LOGGER_ERROR = @"Error";
static NSString *const LOGGER_ROLLBACK = @"Rollback";

typedef NSArray *(^LazyPackagePathsGetterBlock)();

@interface AllPackageSettingsMigrator ()

@property (nonatomic, strong) NSMutableArray *packageSettingsCreated;
@property (nonatomic, strong) NSMutableArray *packageSettingsMigrators;
@property (nonatomic) NSUInteger migrationVersionTarget;
@property (nonatomic, strong) NSArray *packagePaths;
@property (nonatomic, strong) MigrationLogger *logger;
@property (nonatomic, copy) LazyPackagePathsGetterBlock packagePathGetterBlock;

@end

@implementation AllPackageSettingsMigrator

- (instancetype)initWithMigratorData:(MigratorData *)migratorData toVersion:(NSUInteger)toVersion
{
    NSAssert(migratorData != nil, @"migratorData must be set");

    return [self initWithPackagePathsGetterBlock:^NSArray *
    {
        ProjectSettings *projectSettings = [[ProjectSettings alloc] initWithFilepath:migratorData.projectSettingsPath];
        if (!projectSettings)
        {
            return nil;
        }

        NSMutableArray *packagePaths = [NSMutableArray array];
        for (NSMutableDictionary *resourcePathDict in projectSettings.packages)
        {
            NSString *fullPackagePath = [projectSettings fullPathForPackageDict:resourcePathDict];
            [packagePaths addObject:fullPackagePath];
        }
        return packagePaths;
    } toVersion:toVersion];
}

- (instancetype)initWithPackagePathsGetterBlock:(LazyPackagePathsGetterBlock)block toVersion:(NSUInteger)toVersion
{
    NSAssert(block != nil, @"block must not be nil");

    self = [super init];

    if (self)
    {
        self.packagePathGetterBlock = block;
        self.migrationVersionTarget = toVersion;
        self.packageSettingsCreated = [NSMutableArray array];
        self.packageSettingsMigrators = [NSMutableArray array];
    }

    return self;
}

- (instancetype)initWithPackagePaths:(NSArray *)packagePaths toVersion:(NSUInteger)toVersion
{
    return [self initWithPackagePathsGetterBlock:^NSArray * {
        return packagePaths;
    } toVersion:toVersion];
}

- (NSArray *)packagePaths
{
    if (!_packagePaths)
    {
        _packagePaths = _packagePathGetterBlock();
    }

    return _packagePaths;
}

- (void)setLogger:(MigrationLogger *)migrationLogger
{
    _logger = migrationLogger;
}

- (BOOL)isMigrationRequired
{
    return [self missingPackageSettings]
           || [self packagesNeedMigration];
}

- (BOOL)packagesNeedMigration
{
    for (NSString *packagePath in self.packagePaths)
    {
        NSString *fullPackagePath = [packagePath stringByAppendingPathComponent:PACKAGE_PUBLISH_SETTINGS_FILE_NAME];
        PackageSettingsMigrator *packageSettingsMigrator = [[PackageSettingsMigrator alloc] initWithFilepath:fullPackagePath toVersion:_migrationVersionTarget];

        if ([packageSettingsMigrator isMigrationRequired])
        {
            return YES;
        }
    }
    return NO;
}

- (BOOL)missingPackageSettings
{
    for (NSString *packagePath in self.packagePaths)
    {
        NSString *fullPackagePath = [packagePath stringByAppendingPathComponent:PACKAGE_PUBLISH_SETTINGS_FILE_NAME];
        NSFileManager *fileManager = [NSFileManager defaultManager];
        if (![fileManager fileExistsAtPath:fullPackagePath])
        {
            return YES;
        }
    }
    return NO;
}

- (BOOL)migrateWithError:(NSError **)error
{
    if (![self isMigrationRequired])
    {
        return YES;
    }

    [_logger log:@"Starting..." section:@[LOGGER_SECTION]];

    if (![self addMissingPackageSettingsWithError:error])
    {
        return NO;
    }

    if (![self migrateAllPackageSettingsWithError:error])
    {
        return NO;
    }

    [_logger log:@"Finished successfully!" section:@[LOGGER_SECTION]];

    return YES;
}

- (BOOL)migrateAllPackageSettingsWithError:(NSError **)error
{
    for (NSString *packagePath in self.packagePaths)
    {
        NSString *fullPackagePath = [packagePath stringByAppendingPathComponent:PACKAGE_PUBLISH_SETTINGS_FILE_NAME];
        PackageSettingsMigrator *packageSettingsMigrator = [[PackageSettingsMigrator alloc] initWithFilepath:fullPackagePath toVersion:_migrationVersionTarget];
        [_packageSettingsMigrators addObject:packageSettingsMigrator];

        if (![packageSettingsMigrator migrateWithError:error])
        {
            return NO;
        }
    }
    return YES;
}

- (BOOL)addMissingPackageSettingsWithError:(NSError **)error
{
    for (NSString *packagePath in self.packagePaths)
    {
        NSString *fullSettingsPath = [packagePath stringByAppendingPathComponent:PACKAGE_PUBLISH_SETTINGS_FILE_NAME];
        NSFileManager *fileManager = [NSFileManager defaultManager];
        if ([fileManager fileExistsAtPath:fullSettingsPath])
        {
            continue;
        }

        RMPackage *package = [[RMPackage alloc] init];
        package.dirPath = packagePath;

        PackageSettings *packageSettings = [[PackageSettings alloc] initWithPackage:package];
        packageSettings.mainProjectResolutions.resolution_4x = YES;

        if (![packageSettings store])
        {
            [NSError setNewErrorWithErrorPointer:error
                                            code:SBProjectMigrationError
                                         message:[NSString stringWithFormat:@"Could not create default package settings file for package \"%@\"", packagePath]];

            [_logger log:@"Creating missing Package.plist failed." section:@[LOGGER_SECTION, LOGGER_ERROR]];

            return NO;
        }

        [_logger log:[NSString stringWithFormat:@"Creating missing Package.plist file at package '%@'", fullSettingsPath] section:@[LOGGER_SECTION]];

        [_packageSettingsCreated addObject:packageSettings];
    }
    return YES;
}

- (void)rollback
{
    [_logger log:@"Starting..." section:@[LOGGER_SECTION, LOGGER_ROLLBACK]];
    for (id<MigratorProtocol>migrator in _packageSettingsMigrators)
    {
        [migrator rollback];
    }

    NSFileManager *fileManager = [NSFileManager defaultManager];
    for (PackageSettings *packageSettings in _packageSettingsCreated)
    {
        NSError *error;
        if (![fileManager removeItemAtPath:packageSettings.fullPath error:&error])
        {
            [_logger log:[NSString stringWithFormat:@"Could not remove package settings: '%@' : %@", packageSettings.fullPath, error] section:@[LOGGER_SECTION, LOGGER_ROLLBACK, LOGGER_ERROR]];
        }
    }

    [_logger log:@"Finished" section:@[LOGGER_SECTION, LOGGER_ROLLBACK]];
}

- (void)tidyUp
{
    for (id<MigratorProtocol>migrator in _packageSettingsMigrators)
    {
        if ([migrator respondsToSelector:@selector(tidyUp)])
        {
            [migrator tidyUp];
        }
    }
}

@end


text:
ACCEPTED

#### According to
The Catalogue of Life, 3rd January 2011

#### Published in
Dansk bot. Ark. 8(no. 3): 21 (1933)

#### Original name
Agaricus myomyces Pers., 1794

### Remarks
null


text:
<?php

namespace MegaCastingBundle\Entity;

use Doctrine\ORM\Mapping as ORM;

/**
 * Abonnement
 *
 * @ORM\Table("abonnement")
 * @ORM\Entity(repositoryClass="MegaCastingBundle\Repository\AbonnementRepository")
 */

class Abonnement
{
    /**
     * @var integer
     *
     * @ORM\Column(name="id", type="integer")
     * @ORM\Id
     * @ORM\GeneratedValue(strategy="AUTO")
     */
    private $id;

    /**
     * @var \DateTime
     *
     * @ORM\Column(name="dateSouscription", type="datetime")
     */
    private $dateSouscription;

    /**
     * @var integer
     *
     * @ORM\Column(name="restant", type="integer")
     */
    private $restant;

    /**
     * @ORM\ManyToOne(targetEntity="TypeAbonnement", inversedBy="abonnements", cascade={"persist"})
     * @ORM\JoinColumn(nullable=true)
     */
    private $typeAbonnement;

    /**
     * @ORM\ManyToOne(targetEntity="Utilisateur", inversedBy="abonnements", cascade={"persist"})
     * @ORM\JoinColumn(nullable=false)
     */
    private $utilisateur;

    /**
     * Get id
     *
     * @return integer
     */
    public function getId()
    {
        return $this->id;
    }

    /**
     * Set restant
     *
     * @param integer $restant
     * @return Abonnement
     */
    public function setRestant($restant)
    {
        $this->restant = $restant;

        return $this;
    }

    /**
     * Get restant
     *
     * @return integer
     */
    public function getRestant()
    {
        return $this->restant;
    }

    /**
     * Set typeAbonnement
     *
     * @param \MegaCastingBundle\Entity\TypeAbonnement $typeAbonnement
     * @return Abonnement
     */
    public function setTypeAbonnement(\MegaCastingBundle\Entity\TypeAbonnement $typeAbonnement = null)
    {
        $this->typeAbonnement = $typeAbonnement;

        return $this;
    }

    /**
     * Get typeAbonnement
     *
     * @return \MegaCastingBundle\Entity\TypeAbonnement
     */
    public function getTypeAbonnement()
    {
        return $this->typeAbonnement;
    }

    /**
     * Set dateSouscription
     *
     * @param \DateTime $dateSouscription
     * @return Abonnement
     */
    public function setDateSouscription($dateSouscription)
    {
        $this->dateSouscription = $dateSouscription;

        return $this;
    }

    /**
     * Get dateSouscription
     *
     * @return \DateTime
     */
    public function getDateSouscription()
    {
        return $this->dateSouscription;
    }

    /**
     * Set utilisateur
     *
     * @param \MegaCastingBundle\Entity\Utilisateur $utilisateur
     * @return Abonnement
     */
    public function setUtilisateur(\MegaCastingBundle\Entity\Utilisateur $utilisateur)
    {
        $this->utilisateur = $utilisateur;

        return $this;
    }

    /**
     * Get utilisateur
     *
     * @return \MegaCastingBundle\Entity\Utilisateur
     */
    public function getUtilisateur()
    {
        return $this->utilisateur;
    }
}


text:
/*global eyeballApp, Exos*/

eyeballApp.factory('exos',function() {

    return {
        enable : Exos.enable
    };

});


text:
package io.github.actorish4j;

import io.github.actorish4j.internal.ActorishUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.Objects;
import java.util.Optional;
import java.util.Queue;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.CompletionStage;
import java.util.concurrent.RejectedExecutionException;
import java.util.function.Consumer;

/**
 * TaskEnqueuer is the {@link Enqueuer} that polls and executes async tasks {@link AsyncRunnable} one by one
 *

 * TaskEnqueuer guarantees that
 *

 Async tasks will be executed in the order of their arrival
 *
 Async tasks will NEVER run concurrently i.e. next AsyncRunnable will wait for the completion of the CompletionStage of the previous AsyncRunnable
 *

 *

 * TaskEnqueuer can be used as the direct replacement for the single-threaded ExecutorService, if you tasks are asynchronous computations.

 * This class doesn't follow ExecutorService submit()/execute() API deliberately because it can be misused for blocking tasks.
 */
@SuppressWarnings("WeakerAccess")
public final class TaskEnqueuer extends Enqueuer<AsyncRunnable> {
	private static final Logger log = LoggerFactory.getLogger(TaskEnqueuer.class);
	private final RejectsListener rejectsListener;

	public static Conf newConf() {
		return new Conf();
	}

	public TaskEnqueuer(Conf config) {
		super(config);
		this.rejectsListener = config.rejectsListener;
	}

	public TaskEnqueuer() {
		this(defaultConfig);
	}

	/**
	 * This constructor form can save you a few lines of code: you don't need to create configuration object yourself.
	 */
	public TaskEnqueuer(Consumer<Conf> configInit) {
		this(ActorishUtil.with(newConf(), configInit));
	}

	/**
	 * Be careful this method will throw RejectedExecutionException, if queue overflows
	 *
	 * @see Enqueuer#offer(Object)   if you want boolean result instead of RejectedExecutionException
	 * @see #offerCall(AsyncCallable)  if your task has some usefull result of its execution
	 */
	public void mustOffer(AsyncRunnable task) throws RejectedExecutionException {
		if (!offer(task)) {
			callRejectListener();
			throw new RejectedExecutionException(toString());
		}
	}

	/**
	 * @return Optional.empty if queue overflow.
	 */
	@SuppressWarnings("WeakerAccess")
	public <V> Optional<CompletionStage<V>> offerCall(AsyncCallable<V> ac) {
		CompletableFuture<V> result = new CompletableFuture<>();
		AsyncRunnable t = () -> {
			try {
				CompletionStage<V> acResult = ac.callAsync();
				acResult.whenComplete((value, ex) -> {
					if (ex == null) {
						result.complete(value);
					} else {
						result.completeExceptionally(ex);
					}
				});
				return acResult;
			} catch (Exception e) {
				result.completeExceptionally(e);
				return ActorishUtil.doneFuture;
			}
		};
		return offer(t) ? Optional.of(result) : Optional.empty();
	}

	/**
	 * Be careful this method will throw RejectedExecutionException, if queue overflows
	 *
	 * @see #offerCall(AsyncCallable)  if you don't like exceptions.
	 */
	public <V> CompletionStage<V> mustOfferCall(AsyncCallable<V> ac) throws RejectedExecutionException {
		return offerCall(ac).orElseThrow(() -> {
			callRejectListener();
			return new RejectedExecutionException(toString());
		});
	}

	private void callRejectListener() {
		try {
			rejectsListener.onReject(associatedId());
		} catch (Exception ex) {
			log.debug("RejectsListener should never throw exceptions", ex);
		}
	}

	/**
	 * internal method, todo: exclude from docs.
	 */
	@Override
	protected CompletionStage<?> pollAsync(Queue<AsyncRunnable> queue) {
		AsyncRunnable task = queue.poll();
		return task != null ? task.runAsync() : null;
	}

	/**
	 * This hook may be helpful if you need to count how many times RejectedExecutionException was thrown
	 * in mustOffer-methods of {@link TaskEnqueuer}.
	 */
	@FunctionalInterface
	public interface RejectsListener {

		void onReject(Object id);
	}

	private static final RejectsListener emptyListener = id -> {
	};

	private static final Conf defaultConfig = new Conf();
	/**
	 * {@inheritDoc}
	 */
	public static class Conf extends Enqueuer.Conf {
		private RejectsListener rejectsListener = emptyListener;

		/**
		 * For logging/monitoring usage only.
		 */
		public void setRejectsListener(RejectsListener rejectsListener) {
			this.rejectsListener = Objects.requireNonNull(rejectsListener);
		}
	}
}


text:
/*    */ package com.hundsun.network.gates.qingbo.biz.dao.ibatis.auction;
/*    */
/*    */ import com.hundsun.network.gates.luosi.common.base.BaseDAO;
/*    */ import com.hundsun.network.gates.luosi.common.enums.EnumAuctionBidderBidStatus;
/*    */ import com.hundsun.network.gates.luosi.common.enums.EnumBidPriceAuditStatus;
/*    */ import com.hundsun.network.gates.luosi.common.enums.EnumBidPriceStatus;
/*    */ import com.hundsun.network.gates.qingbo.biz.dao.auction.AuctionFreeBidCoreDAO;
/*    */ import com.hundsun.network.gates.qingbo.biz.domain.auction.AuctionFreeBid;
/*    */ import java.util.HashMap;
/*    */ import java.util.List;
/*    */ import java.util.Map;
/*    */ import org.springframework.orm.ibatis.SqlMapClientTemplate;
/*    */ import org.springframework.stereotype.Repository;
/*    */
/*    */ @Repository("auctionFreeBidCoreDAO")
/*    */ public class AuctionFreeBidCoreDAOImpl extends BaseDAO
/*    */   implements AuctionFreeBidCoreDAO
/*    */ {
/*    */   public void insert(AuctionFreeBid record)
/*    */   {
/* 21 */     getSqlMapClientTemplate().insert("AUCTION_FREE_BID_CORE.insert", record);
/*    */   }
/*    */
/*    */   public AuctionFreeBid selectByPrimaryKey(Long id)
/*    */   {
/* 26 */     return (AuctionFreeBid)getSqlMapClientTemplate().queryForObject("AUCTION_FREE_BID_CORE.selectByPrimaryKey", id);
/*    */   }
/*    */
/*    */   public List<AuctionFreeBid> selectLastFreeBid(String projectCode, Long priceDirection)
/*    */   {
/* 36 */     Map paraMap = new HashMap();
/* 37 */     paraMap.put("bidStatus", EnumAuctionBidderBidStatus.A.getValue());
/* 38 */     paraMap.put("projectCode", projectCode);
/* 39 */     paraMap.put("checkStatus", EnumBidPriceAuditStatus.PASS.getValue());
/* 40 */     paraMap.put("status", EnumBidPriceStatus.EFFECTIVE.getValue());
/* 41 */     String priceOrder = "desc";
/* 42 */     if ((priceDirection != null) && (priceDirection.longValue() < 0L)) {
/* 43 */       priceOrder = "asc";
/*    */     }
/* 45 */     paraMap.put("priceOrder", priceOrder);
/* 46 */     return getSqlMapClientTemplate().queryForList("AUCTION_FREE_BID_CORE.selectLastFreeBid", paraMap);
/*    */   }
/*    */
/*    */   public void insertHisFromFreeBidByProjectCode(String projectCode)
/*    */   {
/* 54 */     Map paraMap = new HashMap();
/* 55 */     paraMap.put("projectCode", projectCode);
/* 56 */     getSqlMapClientTemplate().insert("AUCTION_FREE_BID_CORE.insertHisFromFreeBidByProjectCode", paraMap);
/*    */   }
/*    */
/*    */   public int deleteByProjectCode(String projectCode)
/*    */   {
/* 64 */     return getSqlMapClientTemplate().delete("AUCTION_FREE_BID_CORE.deleteByProjectCode", projectCode);
/*    */   }
/*    */ }

/* Location:           E:\__安装归档\linquan-20161112\deploy16\qingbo\webroot\WEB-INF\classes\
 * Qualified Name:     com.hundsun.network.gates.qingbo.biz.dao.ibatis.auction.AuctionFreeBidCoreDAOImpl
 * JD-Core Version:    0.6.0
 */