code stringlengths 3 1.05M | repo_name stringlengths 4 116 | path stringlengths 4 991 | language stringclasses 9
values | license stringclasses 15
values | size int32 3 1.05M |
|---|---|---|---|---|---|
<?php
// This file is part of Moodle - http://moodle.org/
//
// Moodle is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// Moodle is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with Moodle. If not, see <http://www.gnu.org/licenses/>.
/**
* This file contains the definition for the grading table which subclassses easy_table
*
* @package mod_assign
* @copyright 2012 NetSpot {@link http://www.netspot.com.au}
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
defined('MOODLE_INTERNAL') || die();
require_once($CFG->libdir.'/tablelib.php');
require_once($CFG->libdir.'/gradelib.php');
require_once($CFG->dirroot.'/mod/assign/locallib.php');
/**
* Extends table_sql to provide a table of assignment submissions
*
* @package mod_assign
* @copyright 2012 NetSpot {@link http://www.netspot.com.au}
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
class assign_grading_table extends table_sql implements renderable {
/** @var assign $assignment */
private $assignment = null;
/** @var int $perpage */
private $perpage = 10;
/** @var int $rownum (global index of current row in table) */
private $rownum = -1;
/** @var renderer_base for getting output */
private $output = null;
/** @var stdClass gradinginfo */
private $gradinginfo = null;
/** @var int $tablemaxrows */
private $tablemaxrows = 10000;
/** @var boolean $quickgrading */
private $quickgrading = false;
/** @var boolean $hasgrantextension - Only do the capability check once for the entire table */
private $hasgrantextension = false;
/** @var boolean $hasgrade - Only do the capability check once for the entire table */
private $hasgrade = false;
/** @var array $groupsubmissions - A static cache of group submissions */
private $groupsubmissions = array();
/** @var array $submissiongroups - A static cache of submission groups */
private $submissiongroups = array();
/** @var string $plugingradingbatchoperations - List of plugin supported batch operations */
public $plugingradingbatchoperations = array();
/** @var array $plugincache - A cache of plugin lookups to match a column name to a plugin efficiently */
private $plugincache = array();
/** @var array $scale - A list of the keys and descriptions for the custom scale */
private $scale = null;
/**
* overridden constructor keeps a reference to the assignment class that is displaying this table
*
* @param assign $assignment The assignment class
* @param int $perpage how many per page
* @param string $filter The current filter
* @param int $rowoffset For showing a subsequent page of results
* @param bool $quickgrading Is this table wrapped in a quickgrading form?
* @param string $downloadfilename
*/
public function __construct(assign $assignment,
$perpage,
$filter,
$rowoffset,
$quickgrading,
$downloadfilename = null) {
global $CFG, $PAGE, $DB, $USER;
parent::__construct('mod_assign_grading');
$this->assignment = $assignment;
// Check permissions up front.
$this->hasgrantextension = has_capability('mod/assign:grantextension',
$this->assignment->get_context());
$this->hasgrade = $this->assignment->can_grade();
// Check if we have the elevated view capablities to see the blind details.
$this->hasviewblind = has_capability('mod/assign:viewblinddetails',
$this->assignment->get_context());
foreach ($assignment->get_feedback_plugins() as $plugin) {
if ($plugin->is_visible() && $plugin->is_enabled()) {
foreach ($plugin->get_grading_batch_operations() as $action => $description) {
if (empty($this->plugingradingbatchoperations)) {
$this->plugingradingbatchoperations[$plugin->get_type()] = array();
}
$this->plugingradingbatchoperations[$plugin->get_type()][$action] = $description;
}
}
}
$this->perpage = $perpage;
$this->quickgrading = $quickgrading && $this->hasgrade;
$this->output = $PAGE->get_renderer('mod_assign');
$urlparams = array('action'=>'grading', 'id'=>$assignment->get_course_module()->id);
$url = new moodle_url($CFG->wwwroot . '/mod/assign/view.php', $urlparams);
$this->define_baseurl($url);
// Do some business - then set the sql.
$currentgroup = groups_get_activity_group($assignment->get_course_module(), true);
if ($rowoffset) {
$this->rownum = $rowoffset - 1;
}
$users = array_keys( $assignment->list_participants($currentgroup, true));
if (count($users) == 0) {
// Insert a record that will never match to the sql is still valid.
$users[] = -1;
}
$params = array();
$params['assignmentid1'] = (int)$this->assignment->get_instance()->id;
$params['assignmentid2'] = (int)$this->assignment->get_instance()->id;
$params['assignmentid3'] = (int)$this->assignment->get_instance()->id;
$extrauserfields = get_extra_user_fields($this->assignment->get_context());
$fields = user_picture::fields('u', $extrauserfields) . ', ';
$fields .= 'u.id as userid, ';
$fields .= 's.status as status, ';
$fields .= 's.id as submissionid, ';
$fields .= 's.timecreated as firstsubmission, ';
$fields .= 's.timemodified as timesubmitted, ';
$fields .= 's.attemptnumber as attemptnumber, ';
$fields .= 'g.id as gradeid, ';
$fields .= 'g.grade as grade, ';
$fields .= 'g.timemodified as timemarked, ';
$fields .= 'g.timecreated as firstmarked, ';
$fields .= 'uf.mailed as mailed, ';
$fields .= 'uf.locked as locked, ';
$fields .= 'uf.extensionduedate as extensionduedate, ';
$fields .= 'uf.workflowstate as workflowstate, ';
$fields .= 'uf.allocatedmarker as allocatedmarker ';
$from = '{user} u
LEFT JOIN {assign_submission} s
ON u.id = s.userid
AND s.assignment = :assignmentid1
AND s.latest = 1
LEFT JOIN {assign_grades} g
ON u.id = g.userid
AND g.assignment = :assignmentid2 ';
// For group submissions we don't immediately create an entry in the assign_submission table for each user,
// instead the userid is set to 0. In this case we use a different query to retrieve the grade for the user.
if ($this->assignment->get_instance()->teamsubmission) {
$params['assignmentid4'] = (int) $this->assignment->get_instance()->id;
$grademaxattempt = 'SELECT mxg.userid, MAX(mxg.attemptnumber) AS maxattempt
FROM {assign_grades} mxg
WHERE mxg.assignment = :assignmentid4
GROUP BY mxg.userid';
$from .= 'LEFT JOIN (' . $grademaxattempt . ') gmx
ON u.id = gmx.userid
AND g.attemptnumber = gmx.maxattempt ';
} else {
$from .= 'AND g.attemptnumber = s.attemptnumber ';
}
$from .= 'LEFT JOIN {assign_user_flags} uf
ON u.id = uf.userid
AND uf.assignment = :assignmentid3';
$userparams = array();
$userindex = 0;
list($userwhere, $userparams) = $DB->get_in_or_equal($users, SQL_PARAMS_NAMED, 'user');
$where = 'u.id ' . $userwhere;
$params = array_merge($params, $userparams);
// The filters do not make sense when there are no submissions, so do not apply them.
if ($this->assignment->is_any_submission_plugin_enabled()) {
if ($filter == ASSIGN_FILTER_SUBMITTED) {
$where .= ' AND (s.timemodified IS NOT NULL AND
s.status = :submitted) ';
$params['submitted'] = ASSIGN_SUBMISSION_STATUS_SUBMITTED;
} else if ($filter == ASSIGN_FILTER_NOT_SUBMITTED) {
$where .= ' AND (s.timemodified IS NULL OR s.status != :submitted) ';
$params['submitted'] = ASSIGN_SUBMISSION_STATUS_SUBMITTED;
} else if ($filter == ASSIGN_FILTER_REQUIRE_GRADING) {
$where .= ' AND (s.timemodified IS NOT NULL AND
s.status = :submitted AND
(s.timemodified > g.timemodified OR g.timemodified IS NULL))';
$params['submitted'] = ASSIGN_SUBMISSION_STATUS_SUBMITTED;
} else if (strpos($filter, ASSIGN_FILTER_SINGLE_USER) === 0) {
$userfilter = (int) array_pop(explode('=', $filter));
$where .= ' AND (u.id = :userid)';
$params['userid'] = $userfilter;
}
}
if ($this->assignment->get_instance()->markingworkflow &&
$this->assignment->get_instance()->markingallocation) {
if (has_capability('mod/assign:manageallocations', $this->assignment->get_context())) {
// Check to see if marker filter is set.
$markerfilter = (int)get_user_preferences('assign_markerfilter', '');
if (!empty($markerfilter)) {
if ($markerfilter == ASSIGN_MARKER_FILTER_NO_MARKER) {
$where .= ' AND (uf.allocatedmarker IS NULL OR uf.allocatedmarker = 0)';
} else {
$where .= ' AND uf.allocatedmarker = :markerid';
$params['markerid'] = $markerfilter;
}
}
} else { // Only show users allocated to this marker.
$where .= ' AND uf.allocatedmarker = :markerid';
$params['markerid'] = $USER->id;
}
}
if ($this->assignment->get_instance()->markingworkflow) {
$workflowstates = $this->assignment->get_marking_workflow_states_for_current_user();
if (!empty($workflowstates)) {
$workflowfilter = get_user_preferences('assign_workflowfilter', '');
if ($workflowfilter == ASSIGN_MARKING_WORKFLOW_STATE_NOTMARKED) {
$where .= ' AND (uf.workflowstate = :workflowstate OR uf.workflowstate IS NULL OR '.
$DB->sql_isempty('assign_user_flags', 'workflowstate', true, true).')';
$params['workflowstate'] = $workflowfilter;
} else if (array_key_exists($workflowfilter, $workflowstates)) {
$where .= ' AND uf.workflowstate = :workflowstate';
$params['workflowstate'] = $workflowfilter;
}
}
}
$this->set_sql($fields, $from, $where, $params);
if ($downloadfilename) {
$this->is_downloading('csv', $downloadfilename);
}
$columns = array();
$headers = array();
// Select.
if (!$this->is_downloading() && $this->hasgrade) {
$columns[] = 'select';
$headers[] = get_string('select') .
'<div class="selectall"><label class="accesshide" for="selectall">' . get_string('selectall') . '</label>
<input type="checkbox" id="selectall" name="selectall" title="' . get_string('selectall') . '"/></div>';
}
// User picture.
if ($this->hasviewblind || !$this->assignment->is_blind_marking()) {
if (!$this->is_downloading()) {
$columns[] = 'picture';
$headers[] = get_string('pictureofuser');
} else {
$columns[] = 'recordid';
$headers[] = get_string('recordid', 'assign');
}
// Fullname.
$columns[] = 'fullname';
$headers[] = get_string('fullname');
foreach ($extrauserfields as $extrafield) {
$columns[] = $extrafield;
$headers[] = get_user_field_name($extrafield);
}
} else {
// Record ID.
$columns[] = 'recordid';
$headers[] = get_string('recordid', 'assign');
}
// Submission status.
if ($assignment->is_any_submission_plugin_enabled()) {
$columns[] = 'status';
$headers[] = get_string('status', 'assign');
} else if ($this->assignment->get_instance()->markingworkflow) {
$columns[] = 'workflowstate';
$headers[] = get_string('status', 'assign');
}
// Team submission columns.
if ($assignment->get_instance()->teamsubmission) {
$columns[] = 'team';
$headers[] = get_string('submissionteam', 'assign');
}
// Allocated marker.
if ($this->assignment->get_instance()->markingworkflow &&
$this->assignment->get_instance()->markingallocation &&
has_capability('mod/assign:manageallocations', $this->assignment->get_context())) {
// Add a column for the allocated marker.
$columns[] = 'allocatedmarker';
$headers[] = get_string('marker', 'assign');
}
// Grade.
$columns[] = 'grade';
$headers[] = get_string('grade');
if ($this->is_downloading()) {
if ($this->assignment->get_instance()->grade >= 0) {
$columns[] = 'grademax';
$headers[] = get_string('maxgrade', 'assign');
} else {
// This is a custom scale.
$columns[] = 'scale';
$headers[] = get_string('scale', 'assign');
}
if ($this->assignment->get_instance()->markingworkflow) {
// Add a column for the marking workflow state.
$columns[] = 'workflowstate';
$headers[] = get_string('markingworkflowstate', 'assign');
}
// Add a column for the list of valid marking workflow states.
$columns[] = 'gradecanbechanged';
$headers[] = get_string('gradecanbechanged', 'assign');
}
if (!$this->is_downloading() && $this->hasgrade) {
// We have to call this column userid so we can use userid as a default sortable column.
$columns[] = 'userid';
$headers[] = get_string('edit');
}
// Submission plugins.
if ($assignment->is_any_submission_plugin_enabled()) {
$columns[] = 'timesubmitted';
$headers[] = get_string('lastmodifiedsubmission', 'assign');
foreach ($this->assignment->get_submission_plugins() as $plugin) {
if ($this->is_downloading()) {
if ($plugin->is_visible() && $plugin->is_enabled()) {
foreach ($plugin->get_editor_fields() as $field => $description) {
$index = 'plugin' . count($this->plugincache);
$this->plugincache[$index] = array($plugin, $field);
$columns[] = $index;
$headers[] = $plugin->get_name();
}
}
} else {
if ($plugin->is_visible() && $plugin->is_enabled() && $plugin->has_user_summary()) {
$index = 'plugin' . count($this->plugincache);
$this->plugincache[$index] = array($plugin);
$columns[] = $index;
$headers[] = $plugin->get_name();
}
}
}
}
// Time marked.
$columns[] = 'timemarked';
$headers[] = get_string('lastmodifiedgrade', 'assign');
// Feedback plugins.
foreach ($this->assignment->get_feedback_plugins() as $plugin) {
if ($this->is_downloading()) {
if ($plugin->is_visible() && $plugin->is_enabled()) {
foreach ($plugin->get_editor_fields() as $field => $description) {
$index = 'plugin' . count($this->plugincache);
$this->plugincache[$index] = array($plugin, $field);
$columns[] = $index;
$headers[] = $description;
}
}
} else if ($plugin->is_visible() && $plugin->is_enabled() && $plugin->has_user_summary()) {
$index = 'plugin' . count($this->plugincache);
$this->plugincache[$index] = array($plugin);
$columns[] = $index;
$headers[] = $plugin->get_name();
}
}
// Exclude 'Final grade' column in downloaded grading worksheets.
if (!$this->is_downloading()) {
// Final grade.
$columns[] = 'finalgrade';
$headers[] = get_string('finalgrade', 'grades');
}
// Load the grading info for all users.
$this->gradinginfo = grade_get_grades($this->assignment->get_course()->id,
'mod',
'assign',
$this->assignment->get_instance()->id,
$users);
if (!empty($CFG->enableoutcomes) && !empty($this->gradinginfo->outcomes)) {
$columns[] = 'outcomes';
$headers[] = get_string('outcomes', 'grades');
}
// Set the columns.
$this->define_columns($columns);
$this->define_headers($headers);
foreach ($extrauserfields as $extrafield) {
$this->column_class($extrafield, $extrafield);
}
// We require at least one unique column for the sort.
$this->sortable(true, 'userid');
$this->no_sorting('recordid');
$this->no_sorting('finalgrade');
$this->no_sorting('userid');
$this->no_sorting('select');
$this->no_sorting('outcomes');
if ($assignment->get_instance()->teamsubmission) {
$this->no_sorting('team');
}
$plugincolumnindex = 0;
foreach ($this->assignment->get_submission_plugins() as $plugin) {
if ($plugin->is_visible() && $plugin->is_enabled() && $plugin->has_user_summary()) {
$submissionpluginindex = 'plugin' . $plugincolumnindex++;
$this->no_sorting($submissionpluginindex);
}
}
foreach ($this->assignment->get_feedback_plugins() as $plugin) {
if ($plugin->is_visible() && $plugin->is_enabled() && $plugin->has_user_summary()) {
$feedbackpluginindex = 'plugin' . $plugincolumnindex++;
$this->no_sorting($feedbackpluginindex);
}
}
// When there is no data we still want the column headers printed in the csv file.
if ($this->is_downloading()) {
$this->start_output();
}
}
/**
* Before adding each row to the table make sure rownum is incremented.
*
* @param array $row row of data from db used to make one row of the table.
* @return array one row for the table
*/
public function format_row($row) {
if ($this->rownum < 0) {
$this->rownum = $this->currpage * $this->pagesize;
} else {
$this->rownum += 1;
}
return parent::format_row($row);
}
/**
* Add a column with an ID that uniquely identifies this user in this assignment.
*
* @param stdClass $row
* @return string
*/
public function col_recordid(stdClass $row) {
return get_string('hiddenuser', 'assign') .
$this->assignment->get_uniqueid_for_user($row->userid);
}
/**
* Add the userid to the row class so it can be updated via ajax.
*
* @param stdClass $row The row of data
* @return string The row class
*/
public function get_row_class($row) {
return 'user' . $row->userid;
}
/**
* Return the number of rows to display on a single page.
*
* @return int The number of rows per page
*/
public function get_rows_per_page() {
return $this->perpage;
}
/**
* list current marking workflow state
*
* @param stdClass $row
* @return string
*/
public function col_workflowstatus(stdClass $row) {
$o = '';
$gradingdisabled = $this->assignment->grading_disabled($row->id);
// The function in the assignment keeps a static cache of this list of states.
$workflowstates = $this->assignment->get_marking_workflow_states_for_current_user();
$workflowstate = $row->workflowstate;
if (empty($workflowstate)) {
$workflowstate = ASSIGN_MARKING_WORKFLOW_STATE_NOTMARKED;
}
if ($this->quickgrading && !$gradingdisabled) {
$notmarked = get_string('markingworkflowstatenotmarked', 'assign');
$name = 'quickgrade_' . $row->id . '_workflowstate';
$o .= html_writer::select($workflowstates, $name, $workflowstate, array('' => $notmarked));
// Check if this user is a marker that can't manage allocations and doesn't have the marker column added.
if ($this->assignment->get_instance()->markingworkflow &&
$this->assignment->get_instance()->markingallocation &&
!has_capability('mod/assign:manageallocations', $this->assignment->get_context())) {
$name = 'quickgrade_' . $row->id . '_allocatedmarker';
$o .= html_writer::empty_tag('input', array('type' => 'hidden', 'name' => $name,
'value' => $row->allocatedmarker));
}
} else {
$o .= $this->output->container(get_string('markingworkflowstate' . $workflowstate, 'assign'), $workflowstate);
}
return $o;
}
/**
* For download only - list current marking workflow state
*
* @param stdClass $row - The row of data
* @return string The current marking workflow state
*/
public function col_workflowstate($row) {
$state = $row->workflowstate;
if (empty($state)) {
$state = ASSIGN_MARKING_WORKFLOW_STATE_NOTMARKED;
}
return get_string('markingworkflowstate' . $state, 'assign');
}
/**
* list current marker
*
* @param stdClass $row - The row of data
* @return id the user->id of the marker.
*/
public function col_allocatedmarker(stdClass $row) {
static $markers = null;
static $markerlist = array();
if ($markers === null) {
list($sort, $params) = users_order_by_sql();
$markers = get_users_by_capability($this->assignment->get_context(), 'mod/assign:grade', '', $sort);
$markerlist[0] = get_string('choosemarker', 'assign');
foreach ($markers as $marker) {
$markerlist[$marker->id] = fullname($marker);
}
}
if (empty($markerlist)) {
// TODO: add some form of notification here that no markers are available.
return '';
}
if ($this->is_downloading()) {
if (isset($markers[$row->allocatedmarker])) {
return fullname($markers[$row->allocatedmarker]);
} else {
return '';
}
}
if ($this->quickgrading && has_capability('mod/assign:manageallocations', $this->assignment->get_context()) &&
(empty($row->workflowstate) ||
$row->workflowstate == ASSIGN_MARKING_WORKFLOW_STATE_INMARKING ||
$row->workflowstate == ASSIGN_MARKING_WORKFLOW_STATE_NOTMARKED)) {
$name = 'quickgrade_' . $row->id . '_allocatedmarker';
return html_writer::select($markerlist, $name, $row->allocatedmarker, false);
} else if (!empty($row->allocatedmarker)) {
$output = '';
if ($this->quickgrading) { // Add hidden field for quickgrading page.
$name = 'quickgrade_' . $row->id . '_allocatedmarker';
$output .= html_writer::empty_tag('input', array('type'=>'hidden', 'name'=>$name, 'value'=>$row->allocatedmarker));
}
$output .= $markerlist[$row->allocatedmarker];
return $output;
}
}
/**
* For download only - list all the valid options for this custom scale.
*
* @param stdClass $row - The row of data
* @return string A list of valid options for the current scale
*/
public function col_scale($row) {
global $DB;
if (empty($this->scale)) {
$dbparams = array('id'=>-($this->assignment->get_instance()->grade));
$this->scale = $DB->get_record('scale', $dbparams);
}
if (!empty($this->scale->scale)) {
return implode("\n", explode(',', $this->scale->scale));
}
return '';
}
/**
* Display a grade with scales etc.
*
* @param string $grade
* @param boolean $editable
* @param int $userid The user id of the user this grade belongs to
* @param int $modified Timestamp showing when the grade was last modified
* @return string The formatted grade
*/
public function display_grade($grade, $editable, $userid, $modified) {
if ($this->is_downloading()) {
if ($this->assignment->get_instance()->grade >= 0) {
if ($grade == -1 || $grade === null) {
return '';
}
return format_float($grade, 2);
} else {
// This is a custom scale.
$scale = $this->assignment->display_grade($grade, false);
if ($scale == '-') {
$scale = '';
}
return $scale;
}
}
return $this->assignment->display_grade($grade, $editable, $userid, $modified);
}
/**
* Get the team info for this user.
*
* @param stdClass $row
* @return string The team name
*/
public function col_team(stdClass $row) {
$submission = false;
$group = false;
$this->get_group_and_submission($row->id, $group, $submission, -1);
if ($group) {
return $group->name;
}
return get_string('defaultteam', 'assign');
}
/**
* Use a static cache to try and reduce DB calls.
*
* @param int $userid The user id for this submission
* @param int $group The groupid (returned)
* @param stdClass|false $submission The stdClass submission or false (returned)
* @param int $attemptnumber Return a specific attempt number (-1 for latest)
*/
protected function get_group_and_submission($userid, &$group, &$submission, $attemptnumber) {
$group = false;
if (isset($this->submissiongroups[$userid])) {
$group = $this->submissiongroups[$userid];
} else {
$group = $this->assignment->get_submission_group($userid, false);
$this->submissiongroups[$userid] = $group;
}
$groupid = 0;
if ($group) {
$groupid = $group->id;
}
// Static cache is keyed by groupid and attemptnumber.
// We may need both the latest and previous attempt in the same page.
if (isset($this->groupsubmissions[$groupid . ':' . $attemptnumber])) {
$submission = $this->groupsubmissions[$groupid . ':' . $attemptnumber];
} else {
$submission = $this->assignment->get_group_submission($userid, $groupid, false, $attemptnumber);
$this->groupsubmissions[$groupid . ':' . $attemptnumber] = $submission;
}
}
/**
* Format a list of outcomes.
*
* @param stdClass $row
* @return string
*/
public function col_outcomes(stdClass $row) {
$outcomes = '';
foreach ($this->gradinginfo->outcomes as $index => $outcome) {
$options = make_grades_menu(-$outcome->scaleid);
$options[0] = get_string('nooutcome', 'grades');
if ($this->quickgrading && !($outcome->grades[$row->userid]->locked)) {
$select = '<select name="outcome_' . $index . '_' . $row->userid . '" class="quickgrade">';
foreach ($options as $optionindex => $optionvalue) {
$selected = '';
if ($outcome->grades[$row->userid]->grade == $optionindex) {
$selected = 'selected="selected"';
}
$select .= '<option value="' . $optionindex . '"' . $selected . '>' . $optionvalue . '</option>';
}
$select .= '</select>';
$outcomes .= $this->output->container($outcome->name . ': ' . $select, 'outcome');
} else {
$name = $outcome->name . ': ' . $options[$outcome->grades[$row->userid]->grade];
if ($this->is_downloading()) {
$outcomes .= $name;
} else {
$outcomes .= $this->output->container($name, 'outcome');
}
}
}
return $outcomes;
}
/**
* Format a user picture for display.
*
* @param stdClass $row
* @return string
*/
public function col_picture(stdClass $row) {
return $this->output->user_picture($row);
}
/**
* Format a user record for display (link to profile).
*
* @param stdClass $row
* @return string
*/
public function col_fullname($row) {
if (!$this->is_downloading()) {
$courseid = $this->assignment->get_course()->id;
$link= new moodle_url('/user/view.php', array('id' =>$row->id, 'course'=>$courseid));
$fullname = $this->output->action_link($link, $this->assignment->fullname($row));
} else {
$fullname = $this->assignment->fullname($row);
}
if (!$this->assignment->is_active_user($row->id)) {
$suspendedstring = get_string('userenrolmentsuspended', 'grades');
$fullname .= ' ' . html_writer::empty_tag('img', array('src' => $this->output->pix_url('i/enrolmentsuspended'),
'title' => $suspendedstring, 'alt' => $suspendedstring, 'class' => 'usersuspendedicon'));
$fullname = html_writer::tag('span', $fullname, array('class' => 'usersuspended'));
}
return $fullname;
}
/**
* Insert a checkbox for selecting the current row for batch operations.
*
* @param stdClass $row
* @return string
*/
public function col_select(stdClass $row) {
$selectcol = '<label class="accesshide" for="selectuser_' . $row->userid . '">';
$selectcol .= get_string('selectuser', 'assign', $this->assignment->fullname($row));
$selectcol .= '</label>';
$selectcol .= '<input type="checkbox"
id="selectuser_' . $row->userid . '"
name="selectedusers"
value="' . $row->userid . '"/>';
$selectcol .= '<input type="hidden"
name="grademodified_' . $row->userid . '"
value="' . $row->timemarked . '"/>';
return $selectcol;
}
/**
* Return a users grades from the listing of all grade data for this assignment.
*
* @param int $userid
* @return mixed stdClass or false
*/
private function get_gradebook_data_for_user($userid) {
if (isset($this->gradinginfo->items[0]) && $this->gradinginfo->items[0]->grades[$userid]) {
return $this->gradinginfo->items[0]->grades[$userid];
}
return false;
}
/**
* Format a column of data for display.
*
* @param stdClass $row
* @return string
*/
public function col_gradecanbechanged(stdClass $row) {
$gradingdisabled = $this->assignment->grading_disabled($row->id);
if ($gradingdisabled) {
return get_string('no');
} else {
return get_string('yes');
}
}
/**
* Format a column of data for display
*
* @param stdClass $row
* @return string
*/
public function col_grademax(stdClass $row) {
return format_float($this->assignment->get_instance()->grade, 2);
}
/**
* Format a column of data for display.
*
* @param stdClass $row
* @return string
*/
public function col_grade(stdClass $row) {
$o = '';
$link = '';
$separator = $this->output->spacer(array(), true);
$grade = '';
$gradingdisabled = $this->assignment->grading_disabled($row->id);
if (!$this->is_downloading() && $this->hasgrade) {
$name = $this->assignment->fullname($row);
$icon = $this->output->pix_icon('gradefeedback',
get_string('gradeuser', 'assign', $name),
'mod_assign');
$urlparams = array('id' => $this->assignment->get_course_module()->id,
'rownum'=>$this->rownum,
'action'=>'grade');
$url = new moodle_url('/mod/assign/view.php', $urlparams);
$link = $this->output->action_link($url, $icon);
$grade .= $link . $separator;
}
$grade .= $this->display_grade($row->grade,
$this->quickgrading && !$gradingdisabled,
$row->userid,
$row->timemarked);
return $grade;
}
/**
* Format a column of data for display.
*
* @param stdClass $row
* @return string
*/
public function col_finalgrade(stdClass $row) {
$o = '';
$grade = $this->get_gradebook_data_for_user($row->userid);
if ($grade) {
$o = $this->display_grade($grade->grade, false, $row->userid, $row->timemarked);
}
return $o;
}
/**
* Format a column of data for display.
*
* @param stdClass $row
* @return string
*/
public function col_timemarked(stdClass $row) {
$o = '-';
if ($row->timemarked && $row->grade !== null && $row->grade >= 0) {
$o = userdate($row->timemarked);
}
if ($row->timemarked && $this->is_downloading()) {
// Force it for downloads as it affects import.
$o = userdate($row->timemarked);
}
return $o;
}
/**
* Format a column of data for display.
*
* @param stdClass $row
* @return string
*/
public function col_timesubmitted(stdClass $row) {
$o = '-';
$group = false;
$submission = false;
$this->get_group_and_submission($row->id, $group, $submission, -1);
if ($submission && $submission->timemodified && $submission->status != ASSIGN_SUBMISSION_STATUS_NEW) {
$o = userdate($submission->timemodified);
} else if ($row->timesubmitted) {
$o = userdate($row->timesubmitted);
}
return $o;
}
/**
* Format a column of data for display
*
* @param stdClass $row
* @return string
*/
public function col_status(stdClass $row) {
$o = '';
$instance = $this->assignment->get_instance();
$due = $instance->duedate;
if ($row->extensionduedate) {
$due = $row->extensionduedate;
}
$group = false;
$submission = false;
$this->get_group_and_submission($row->id, $group, $submission, -1);
if ($submission) {
$timesubmitted = $submission->timemodified;
$status = $submission->status;
} else {
$timesubmitted = $row->timesubmitted;
$status = $row->status;
}
if ($this->assignment->is_any_submission_plugin_enabled()) {
$o .= $this->output->container(get_string('submissionstatus_' . $status, 'assign'),
array('class'=>'submissionstatus' .$status));
if ($due && $timesubmitted > $due) {
$usertime = format_time($timesubmitted - $due);
$latemessage = get_string('submittedlateshort',
'assign',
$usertime);
$o .= $this->output->container($latemessage, 'latesubmission');
}
if ($row->locked) {
$lockedstr = get_string('submissionslockedshort', 'assign');
$o .= $this->output->container($lockedstr, 'lockedsubmission');
}
// Add status of "grading", use markflow if enabled.
if ($instance->markingworkflow) {
$o .= $this->col_workflowstatus($row);
} else if ($row->grade !== null && $row->grade >= 0) {
$o .= $this->output->container(get_string('graded', 'assign'), 'submissiongraded');
} else if (!$timesubmitted) {
$now = time();
if ($due && ($now > $due)) {
$overduestr = get_string('overdue', 'assign', format_time($now - $due));
$o .= $this->output->container($overduestr, 'overduesubmission');
}
}
if ($row->extensionduedate) {
$userdate = userdate($row->extensionduedate);
$extensionstr = get_string('userextensiondate', 'assign', $userdate);
$o .= $this->output->container($extensionstr, 'extensiondate');
}
}
if ($this->is_downloading()) {
$o = strip_tags(str_replace('</div>', "\n", $o));
}
return $o;
}
/**
* Format a column of data for display.
*
* @param stdClass $row
* @return string
*/
public function col_userid(stdClass $row) {
global $USER;
$edit = '';
$actions = array();
$urlparams = array('id'=>$this->assignment->get_course_module()->id,
'rownum'=>$this->rownum,
'action'=>'grade');
$url = new moodle_url('/mod/assign/view.php', $urlparams);
$noimage = null;
if (!$row->grade) {
$description = get_string('grade');
} else {
$description = get_string('updategrade', 'assign');
}
$actions['grade'] = new action_menu_link_secondary(
$url,
$noimage,
$description
);
// Everything we need is in the row.
$submission = $row;
$flags = $row;
if ($this->assignment->get_instance()->teamsubmission) {
// Use the cache for this.
$submission = false;
$group = false;
$this->get_group_and_submission($row->id, $group, $submission, -1);
}
$submissionsopen = $this->assignment->submissions_open($row->id,
true,
$submission,
$flags,
$this->gradinginfo);
$caneditsubmission = $this->assignment->can_edit_submission($row->id, $USER->id);
// Hide for offline assignments.
if ($this->assignment->is_any_submission_plugin_enabled()) {
if (!$row->status ||
$row->status == ASSIGN_SUBMISSION_STATUS_DRAFT ||
!$this->assignment->get_instance()->submissiondrafts) {
if (!$row->locked) {
$urlparams = array('id' => $this->assignment->get_course_module()->id,
'userid'=>$row->id,
'action'=>'lock',
'sesskey'=>sesskey(),
'page'=>$this->currpage);
$url = new moodle_url('/mod/assign/view.php', $urlparams);
$description = get_string('preventsubmissionsshort', 'assign');
$actions['lock'] = new action_menu_link_secondary(
$url,
$noimage,
$description
);
} else {
$urlparams = array('id' => $this->assignment->get_course_module()->id,
'userid'=>$row->id,
'action'=>'unlock',
'sesskey'=>sesskey(),
'page'=>$this->currpage);
$url = new moodle_url('/mod/assign/view.php', $urlparams);
$description = get_string('allowsubmissionsshort', 'assign');
$actions['unlock'] = new action_menu_link_secondary(
$url,
$noimage,
$description
);
}
}
if (($this->assignment->get_instance()->duedate ||
$this->assignment->get_instance()->cutoffdate) &&
$this->hasgrantextension) {
$urlparams = array('id' => $this->assignment->get_course_module()->id,
'userid'=>$row->id,
'action'=>'grantextension',
'sesskey'=>sesskey(),
'page'=>$this->currpage);
$url = new moodle_url('/mod/assign/view.php', $urlparams);
$description = get_string('grantextension', 'assign');
$actions['grantextension'] = new action_menu_link_secondary(
$url,
$noimage,
$description
);
}
if ($submissionsopen &&
$USER->id != $row->id &&
$caneditsubmission) {
$urlparams = array('id' => $this->assignment->get_course_module()->id,
'userid'=>$row->id,
'action'=>'editsubmission',
'sesskey'=>sesskey(),
'page'=>$this->currpage);
$url = new moodle_url('/mod/assign/view.php', $urlparams);
$description = get_string('editsubmission', 'assign');
$actions['editsubmission'] = new action_menu_link_secondary(
$url,
$noimage,
$description
);
}
}
if ($row->status == ASSIGN_SUBMISSION_STATUS_SUBMITTED &&
$this->assignment->get_instance()->submissiondrafts) {
$urlparams = array('id' => $this->assignment->get_course_module()->id,
'userid'=>$row->id,
'action'=>'reverttodraft',
'sesskey'=>sesskey(),
'page'=>$this->currpage);
$url = new moodle_url('/mod/assign/view.php', $urlparams);
$description = get_string('reverttodraftshort', 'assign');
$actions['reverttodraft'] = new action_menu_link_secondary(
$url,
$noimage,
$description
);
}
if ($row->status == ASSIGN_SUBMISSION_STATUS_DRAFT &&
$this->assignment->get_instance()->submissiondrafts &&
$caneditsubmission &&
$submissionsopen &&
$row->id != $USER->id) {
$urlparams = array('id' => $this->assignment->get_course_module()->id,
'userid'=>$row->id,
'action'=>'submitotherforgrading',
'sesskey'=>sesskey(),
'page'=>$this->currpage);
$url = new moodle_url('/mod/assign/view.php', $urlparams);
$description = get_string('submitforgrading', 'assign');
$actions['submitforgrading'] = new action_menu_link_secondary(
$url,
$noimage,
$description
);
}
$ismanual = $this->assignment->get_instance()->attemptreopenmethod == ASSIGN_ATTEMPT_REOPEN_METHOD_MANUAL;
$hassubmission = !empty($row->status);
$notreopened = $hassubmission && $row->status != ASSIGN_SUBMISSION_STATUS_REOPENED;
$isunlimited = $this->assignment->get_instance()->maxattempts == ASSIGN_UNLIMITED_ATTEMPTS;
$hasattempts = $isunlimited || $row->attemptnumber < $this->assignment->get_instance()->maxattempts - 1;
if ($ismanual && $hassubmission && $notreopened && $hasattempts) {
$urlparams = array('id' => $this->assignment->get_course_module()->id,
'userid'=>$row->id,
'action'=>'addattempt',
'sesskey'=>sesskey(),
'page'=>$this->currpage);
$url = new moodle_url('/mod/assign/view.php', $urlparams);
$description = get_string('addattempt', 'assign');
$actions['addattempt'] = new action_menu_link_secondary(
$url,
$noimage,
$description
);
}
$menu = new action_menu();
$menu->set_owner_selector('.gradingtable-actionmenu');
$menu->set_alignment(action_menu::TL, action_menu::BL);
$menu->set_constraint('.gradingtable > .no-overflow');
$menu->set_menu_trigger(get_string('edit'));
foreach ($actions as $action) {
$menu->add($action);
}
// Prioritise the menu ahead of all other actions.
$menu->prioritise = true;
$edit .= $this->output->render($menu);
return $edit;
}
/**
* Write the plugin summary with an optional link to view the full feedback/submission.
*
* @param assign_plugin $plugin Submission plugin or feedback plugin
* @param stdClass $item Submission or grade
* @param string $returnaction The return action to pass to the
* view_submission page (the current page)
* @param string $returnparams The return params to pass to the view_submission
* page (the current page)
* @return string The summary with an optional link
*/
private function format_plugin_summary_with_link(assign_plugin $plugin,
stdClass $item,
$returnaction,
$returnparams) {
$link = '';
$showviewlink = false;
$summary = $plugin->view_summary($item, $showviewlink);
$separator = '';
if ($showviewlink) {
$viewstr = get_string('view' . substr($plugin->get_subtype(), strlen('assign')), 'assign');
$icon = $this->output->pix_icon('t/preview', $viewstr);
$urlparams = array('id' => $this->assignment->get_course_module()->id,
'sid'=>$item->id,
'gid'=>$item->id,
'plugin'=>$plugin->get_type(),
'action'=>'viewplugin' . $plugin->get_subtype(),
'returnaction'=>$returnaction,
'returnparams'=>http_build_query($returnparams));
$url = new moodle_url('/mod/assign/view.php', $urlparams);
$link = $this->output->action_link($url, $icon);
$separator = $this->output->spacer(array(), true);
}
return $link . $separator . $summary;
}
/**
* Format the submission and feedback columns.
*
* @param string $colname The column name
* @param stdClass $row The submission row
* @return mixed string or NULL
*/
public function other_cols($colname, $row) {
// For extra user fields the result is already in $row.
if (empty($this->plugincache[$colname])) {
return $row->$colname;
}
// This must be a plugin field.
$plugincache = $this->plugincache[$colname];
$plugin = $plugincache[0];
$field = null;
if (isset($plugincache[1])) {
$field = $plugincache[1];
}
if ($plugin->is_visible() && $plugin->is_enabled()) {
if ($plugin->get_subtype() == 'assignsubmission') {
if ($this->assignment->get_instance()->teamsubmission) {
$group = false;
$submission = false;
$this->get_group_and_submission($row->id, $group, $submission, -1);
if ($submission) {
if ($submission->status == ASSIGN_SUBMISSION_STATUS_REOPENED) {
// For a newly reopened submission - we want to show the previous submission in the table.
$this->get_group_and_submission($row->id, $group, $submission, $submission->attemptnumber-1);
}
if (isset($field)) {
return $plugin->get_editor_text($field, $submission->id);
}
return $this->format_plugin_summary_with_link($plugin,
$submission,
'grading',
array());
}
} else if ($row->submissionid) {
if ($row->status == ASSIGN_SUBMISSION_STATUS_REOPENED) {
// For a newly reopened submission - we want to show the previous submission in the table.
$submission = $this->assignment->get_user_submission($row->userid, false, $row->attemptnumber - 1);
} else {
$submission = new stdClass();
$submission->id = $row->submissionid;
$submission->timecreated = $row->firstsubmission;
$submission->timemodified = $row->timesubmitted;
$submission->assignment = $this->assignment->get_instance()->id;
$submission->userid = $row->userid;
$submission->attemptnumber = $row->attemptnumber;
}
// Field is used for only for import/export and refers the the fieldname for the text editor.
if (isset($field)) {
return $plugin->get_editor_text($field, $submission->id);
}
return $this->format_plugin_summary_with_link($plugin,
$submission,
'grading',
array());
}
} else {
$grade = null;
if (isset($field)) {
return $plugin->get_editor_text($field, $row->gradeid);
}
if ($row->gradeid) {
$grade = new stdClass();
$grade->id = $row->gradeid;
$grade->timecreated = $row->firstmarked;
$grade->timemodified = $row->timemarked;
$grade->assignment = $this->assignment->get_instance()->id;
$grade->userid = $row->userid;
$grade->grade = $row->grade;
$grade->mailed = $row->mailed;
$grade->attemptnumber = $row->attemptnumber;
}
if ($this->quickgrading && $plugin->supports_quickgrading()) {
return $plugin->get_quickgrading_html($row->userid, $grade);
} else if ($grade) {
return $this->format_plugin_summary_with_link($plugin,
$grade,
'grading',
array());
}
}
}
return '';
}
/**
* Using the current filtering and sorting - load all rows and return a single column from them.
*
* @param string $columnname The name of the raw column data
* @return array of data
*/
public function get_column_data($columnname) {
$this->setup();
$this->currpage = 0;
$this->query_db($this->tablemaxrows);
$result = array();
foreach ($this->rawdata as $row) {
$result[] = $row->$columnname;
}
return $result;
}
/**
* Return things to the renderer.
*
* @return string the assignment name
*/
public function get_assignment_name() {
return $this->assignment->get_instance()->name;
}
/**
* Return things to the renderer.
*
* @return int the course module id
*/
public function get_course_module_id() {
return $this->assignment->get_course_module()->id;
}
/**
* Return things to the renderer.
*
* @return int the course id
*/
public function get_course_id() {
return $this->assignment->get_course()->id;
}
/**
* Return things to the renderer.
*
* @return stdClass The course context
*/
public function get_course_context() {
return $this->assignment->get_course_context();
}
/**
* Return things to the renderer.
*
* @return bool Does this assignment accept submissions
*/
public function submissions_enabled() {
return $this->assignment->is_any_submission_plugin_enabled();
}
/**
* Return things to the renderer.
*
* @return bool Can this user view all grades (the gradebook)
*/
public function can_view_all_grades() {
$context = $this->assignment->get_course_context();
return has_capability('gradereport/grader:view', $context) &&
has_capability('moodle/grade:viewall', $context);
}
/**
* Override the table show_hide_link to not show for select column.
*
* @param string $column the column name, index into various names.
* @param int $index numerical index of the column.
* @return string HTML fragment.
*/
protected function show_hide_link($column, $index) {
if ($index > 0 || !$this->hasgrade) {
return parent::show_hide_link($column, $index);
}
return '';
}
}
| joseaomedes/moodle2 | mod/assign/gradingtable.php | PHP | gpl-3.0 | 56,634 |
"use strict";
tutao.provide('tutao.entity.sys.System');
/**
* @constructor
* @param {Object=} data The json data to store in this entity.
*/
tutao.entity.sys.System = function(data) {
if (data) {
this.updateData(data);
} else {
this.__format = "0";
this.__id = null;
this.__permissions = null;
this._lastInvoiceNbr = null;
this._freeCustomerInfos = null;
this._freeGroup = null;
this._invoiceStatusIndex = null;
this._premiumCustomerInfos = null;
this._premiumGroup = null;
this._registrationDataList = null;
this._starterCustomerInfos = null;
this._starterGroup = null;
this._streamCustomerInfos = null;
this._streamGroup = null;
this._systemAdminGroup = null;
this._systemCustomer = null;
this._systemCustomerInfo = null;
this._systemUserGroup = null;
}
this._entityHelper = new tutao.entity.EntityHelper(this);
this.prototype = tutao.entity.sys.System.prototype;
};
/**
* Updates the data of this entity.
* @param {Object=} data The json data to store in this entity.
*/
tutao.entity.sys.System.prototype.updateData = function(data) {
this.__format = data._format;
this.__id = data._id;
this.__permissions = data._permissions;
this._lastInvoiceNbr = data.lastInvoiceNbr;
this._freeCustomerInfos = data.freeCustomerInfos;
this._freeGroup = data.freeGroup;
this._invoiceStatusIndex = data.invoiceStatusIndex;
this._premiumCustomerInfos = data.premiumCustomerInfos;
this._premiumGroup = data.premiumGroup;
this._registrationDataList = data.registrationDataList;
this._starterCustomerInfos = data.starterCustomerInfos;
this._starterGroup = data.starterGroup;
this._streamCustomerInfos = data.streamCustomerInfos;
this._streamGroup = data.streamGroup;
this._systemAdminGroup = data.systemAdminGroup;
this._systemCustomer = data.systemCustomer;
this._systemCustomerInfo = data.systemCustomerInfo;
this._systemUserGroup = data.systemUserGroup;
};
/**
* The version of the model this type belongs to.
* @const
*/
tutao.entity.sys.System.MODEL_VERSION = '9';
/**
* The url path to the resource.
* @const
*/
tutao.entity.sys.System.PATH = '/rest/sys/system';
/**
* The id of the root instance reference.
* @const
*/
tutao.entity.sys.System.ROOT_INSTANCE_ID = 'A3N5cwAAsQ';
/**
* The generated id type flag.
* @const
*/
tutao.entity.sys.System.GENERATED_ID = true;
/**
* The encrypted flag.
* @const
*/
tutao.entity.sys.System.prototype.ENCRYPTED = false;
/**
* Provides the data of this instances as an object that can be converted to json.
* @return {Object} The json object.
*/
tutao.entity.sys.System.prototype.toJsonData = function() {
return {
_format: this.__format,
_id: this.__id,
_permissions: this.__permissions,
lastInvoiceNbr: this._lastInvoiceNbr,
freeCustomerInfos: this._freeCustomerInfos,
freeGroup: this._freeGroup,
invoiceStatusIndex: this._invoiceStatusIndex,
premiumCustomerInfos: this._premiumCustomerInfos,
premiumGroup: this._premiumGroup,
registrationDataList: this._registrationDataList,
starterCustomerInfos: this._starterCustomerInfos,
starterGroup: this._starterGroup,
streamCustomerInfos: this._streamCustomerInfos,
streamGroup: this._streamGroup,
systemAdminGroup: this._systemAdminGroup,
systemCustomer: this._systemCustomer,
systemCustomerInfo: this._systemCustomerInfo,
systemUserGroup: this._systemUserGroup
};
};
/**
* The id of the System type.
*/
tutao.entity.sys.System.prototype.TYPE_ID = 177;
/**
* The id of the lastInvoiceNbr attribute.
*/
tutao.entity.sys.System.prototype.LASTINVOICENBR_ATTRIBUTE_ID = 591;
/**
* The id of the freeCustomerInfos attribute.
*/
tutao.entity.sys.System.prototype.FREECUSTOMERINFOS_ATTRIBUTE_ID = 183;
/**
* The id of the freeGroup attribute.
*/
tutao.entity.sys.System.prototype.FREEGROUP_ATTRIBUTE_ID = 191;
/**
* The id of the invoiceStatusIndex attribute.
*/
tutao.entity.sys.System.prototype.INVOICESTATUSINDEX_ATTRIBUTE_ID = 829;
/**
* The id of the premiumCustomerInfos attribute.
*/
tutao.entity.sys.System.prototype.PREMIUMCUSTOMERINFOS_ATTRIBUTE_ID = 185;
/**
* The id of the premiumGroup attribute.
*/
tutao.entity.sys.System.prototype.PREMIUMGROUP_ATTRIBUTE_ID = 190;
/**
* The id of the registrationDataList attribute.
*/
tutao.entity.sys.System.prototype.REGISTRATIONDATALIST_ATTRIBUTE_ID = 194;
/**
* The id of the starterCustomerInfos attribute.
*/
tutao.entity.sys.System.prototype.STARTERCUSTOMERINFOS_ATTRIBUTE_ID = 184;
/**
* The id of the starterGroup attribute.
*/
tutao.entity.sys.System.prototype.STARTERGROUP_ATTRIBUTE_ID = 192;
/**
* The id of the streamCustomerInfos attribute.
*/
tutao.entity.sys.System.prototype.STREAMCUSTOMERINFOS_ATTRIBUTE_ID = 186;
/**
* The id of the streamGroup attribute.
*/
tutao.entity.sys.System.prototype.STREAMGROUP_ATTRIBUTE_ID = 193;
/**
* The id of the systemAdminGroup attribute.
*/
tutao.entity.sys.System.prototype.SYSTEMADMINGROUP_ATTRIBUTE_ID = 189;
/**
* The id of the systemCustomer attribute.
*/
tutao.entity.sys.System.prototype.SYSTEMCUSTOMER_ATTRIBUTE_ID = 187;
/**
* The id of the systemCustomerInfo attribute.
*/
tutao.entity.sys.System.prototype.SYSTEMCUSTOMERINFO_ATTRIBUTE_ID = 182;
/**
* The id of the systemUserGroup attribute.
*/
tutao.entity.sys.System.prototype.SYSTEMUSERGROUP_ATTRIBUTE_ID = 188;
/**
* Provides the id of this System.
* @return {string} The id of this System.
*/
tutao.entity.sys.System.prototype.getId = function() {
return this.__id;
};
/**
* Sets the format of this System.
* @param {string} format The format of this System.
*/
tutao.entity.sys.System.prototype.setFormat = function(format) {
this.__format = format;
return this;
};
/**
* Provides the format of this System.
* @return {string} The format of this System.
*/
tutao.entity.sys.System.prototype.getFormat = function() {
return this.__format;
};
/**
* Sets the permissions of this System.
* @param {string} permissions The permissions of this System.
*/
tutao.entity.sys.System.prototype.setPermissions = function(permissions) {
this.__permissions = permissions;
return this;
};
/**
* Provides the permissions of this System.
* @return {string} The permissions of this System.
*/
tutao.entity.sys.System.prototype.getPermissions = function() {
return this.__permissions;
};
/**
* Sets the lastInvoiceNbr of this System.
* @param {string} lastInvoiceNbr The lastInvoiceNbr of this System.
*/
tutao.entity.sys.System.prototype.setLastInvoiceNbr = function(lastInvoiceNbr) {
this._lastInvoiceNbr = lastInvoiceNbr;
return this;
};
/**
* Provides the lastInvoiceNbr of this System.
* @return {string} The lastInvoiceNbr of this System.
*/
tutao.entity.sys.System.prototype.getLastInvoiceNbr = function() {
return this._lastInvoiceNbr;
};
/**
* Sets the freeCustomerInfos of this System.
* @param {string} freeCustomerInfos The freeCustomerInfos of this System.
*/
tutao.entity.sys.System.prototype.setFreeCustomerInfos = function(freeCustomerInfos) {
this._freeCustomerInfos = freeCustomerInfos;
return this;
};
/**
* Provides the freeCustomerInfos of this System.
* @return {string} The freeCustomerInfos of this System.
*/
tutao.entity.sys.System.prototype.getFreeCustomerInfos = function() {
return this._freeCustomerInfos;
};
/**
* Sets the freeGroup of this System.
* @param {string} freeGroup The freeGroup of this System.
*/
tutao.entity.sys.System.prototype.setFreeGroup = function(freeGroup) {
this._freeGroup = freeGroup;
return this;
};
/**
* Provides the freeGroup of this System.
* @return {string} The freeGroup of this System.
*/
tutao.entity.sys.System.prototype.getFreeGroup = function() {
return this._freeGroup;
};
/**
* Loads the freeGroup of this System.
* @return {Promise.<tutao.entity.sys.Group>} Resolves to the loaded freeGroup of this System or an exception if the loading failed.
*/
tutao.entity.sys.System.prototype.loadFreeGroup = function() {
return tutao.entity.sys.Group.load(this._freeGroup);
};
/**
* Sets the invoiceStatusIndex of this System.
* @param {string} invoiceStatusIndex The invoiceStatusIndex of this System.
*/
tutao.entity.sys.System.prototype.setInvoiceStatusIndex = function(invoiceStatusIndex) {
this._invoiceStatusIndex = invoiceStatusIndex;
return this;
};
/**
* Provides the invoiceStatusIndex of this System.
* @return {string} The invoiceStatusIndex of this System.
*/
tutao.entity.sys.System.prototype.getInvoiceStatusIndex = function() {
return this._invoiceStatusIndex;
};
/**
* Loads the invoiceStatusIndex of this System.
* @return {Promise.<tutao.entity.sys.InvoiceStatusIndex>} Resolves to the loaded invoiceStatusIndex of this System or an exception if the loading failed.
*/
tutao.entity.sys.System.prototype.loadInvoiceStatusIndex = function() {
return tutao.entity.sys.InvoiceStatusIndex.load(this._invoiceStatusIndex);
};
/**
* Sets the premiumCustomerInfos of this System.
* @param {string} premiumCustomerInfos The premiumCustomerInfos of this System.
*/
tutao.entity.sys.System.prototype.setPremiumCustomerInfos = function(premiumCustomerInfos) {
this._premiumCustomerInfos = premiumCustomerInfos;
return this;
};
/**
* Provides the premiumCustomerInfos of this System.
* @return {string} The premiumCustomerInfos of this System.
*/
tutao.entity.sys.System.prototype.getPremiumCustomerInfos = function() {
return this._premiumCustomerInfos;
};
/**
* Sets the premiumGroup of this System.
* @param {string} premiumGroup The premiumGroup of this System.
*/
tutao.entity.sys.System.prototype.setPremiumGroup = function(premiumGroup) {
this._premiumGroup = premiumGroup;
return this;
};
/**
* Provides the premiumGroup of this System.
* @return {string} The premiumGroup of this System.
*/
tutao.entity.sys.System.prototype.getPremiumGroup = function() {
return this._premiumGroup;
};
/**
* Loads the premiumGroup of this System.
* @return {Promise.<tutao.entity.sys.Group>} Resolves to the loaded premiumGroup of this System or an exception if the loading failed.
*/
tutao.entity.sys.System.prototype.loadPremiumGroup = function() {
return tutao.entity.sys.Group.load(this._premiumGroup);
};
/**
* Sets the registrationDataList of this System.
* @param {string} registrationDataList The registrationDataList of this System.
*/
tutao.entity.sys.System.prototype.setRegistrationDataList = function(registrationDataList) {
this._registrationDataList = registrationDataList;
return this;
};
/**
* Provides the registrationDataList of this System.
* @return {string} The registrationDataList of this System.
*/
tutao.entity.sys.System.prototype.getRegistrationDataList = function() {
return this._registrationDataList;
};
/**
* Sets the starterCustomerInfos of this System.
* @param {string} starterCustomerInfos The starterCustomerInfos of this System.
*/
tutao.entity.sys.System.prototype.setStarterCustomerInfos = function(starterCustomerInfos) {
this._starterCustomerInfos = starterCustomerInfos;
return this;
};
/**
* Provides the starterCustomerInfos of this System.
* @return {string} The starterCustomerInfos of this System.
*/
tutao.entity.sys.System.prototype.getStarterCustomerInfos = function() {
return this._starterCustomerInfos;
};
/**
* Sets the starterGroup of this System.
* @param {string} starterGroup The starterGroup of this System.
*/
tutao.entity.sys.System.prototype.setStarterGroup = function(starterGroup) {
this._starterGroup = starterGroup;
return this;
};
/**
* Provides the starterGroup of this System.
* @return {string} The starterGroup of this System.
*/
tutao.entity.sys.System.prototype.getStarterGroup = function() {
return this._starterGroup;
};
/**
* Loads the starterGroup of this System.
* @return {Promise.<tutao.entity.sys.Group>} Resolves to the loaded starterGroup of this System or an exception if the loading failed.
*/
tutao.entity.sys.System.prototype.loadStarterGroup = function() {
return tutao.entity.sys.Group.load(this._starterGroup);
};
/**
* Sets the streamCustomerInfos of this System.
* @param {string} streamCustomerInfos The streamCustomerInfos of this System.
*/
tutao.entity.sys.System.prototype.setStreamCustomerInfos = function(streamCustomerInfos) {
this._streamCustomerInfos = streamCustomerInfos;
return this;
};
/**
* Provides the streamCustomerInfos of this System.
* @return {string} The streamCustomerInfos of this System.
*/
tutao.entity.sys.System.prototype.getStreamCustomerInfos = function() {
return this._streamCustomerInfos;
};
/**
* Sets the streamGroup of this System.
* @param {string} streamGroup The streamGroup of this System.
*/
tutao.entity.sys.System.prototype.setStreamGroup = function(streamGroup) {
this._streamGroup = streamGroup;
return this;
};
/**
* Provides the streamGroup of this System.
* @return {string} The streamGroup of this System.
*/
tutao.entity.sys.System.prototype.getStreamGroup = function() {
return this._streamGroup;
};
/**
* Loads the streamGroup of this System.
* @return {Promise.<tutao.entity.sys.Group>} Resolves to the loaded streamGroup of this System or an exception if the loading failed.
*/
tutao.entity.sys.System.prototype.loadStreamGroup = function() {
return tutao.entity.sys.Group.load(this._streamGroup);
};
/**
* Sets the systemAdminGroup of this System.
* @param {string} systemAdminGroup The systemAdminGroup of this System.
*/
tutao.entity.sys.System.prototype.setSystemAdminGroup = function(systemAdminGroup) {
this._systemAdminGroup = systemAdminGroup;
return this;
};
/**
* Provides the systemAdminGroup of this System.
* @return {string} The systemAdminGroup of this System.
*/
tutao.entity.sys.System.prototype.getSystemAdminGroup = function() {
return this._systemAdminGroup;
};
/**
* Loads the systemAdminGroup of this System.
* @return {Promise.<tutao.entity.sys.Group>} Resolves to the loaded systemAdminGroup of this System or an exception if the loading failed.
*/
tutao.entity.sys.System.prototype.loadSystemAdminGroup = function() {
return tutao.entity.sys.Group.load(this._systemAdminGroup);
};
/**
* Sets the systemCustomer of this System.
* @param {string} systemCustomer The systemCustomer of this System.
*/
tutao.entity.sys.System.prototype.setSystemCustomer = function(systemCustomer) {
this._systemCustomer = systemCustomer;
return this;
};
/**
* Provides the systemCustomer of this System.
* @return {string} The systemCustomer of this System.
*/
tutao.entity.sys.System.prototype.getSystemCustomer = function() {
return this._systemCustomer;
};
/**
* Loads the systemCustomer of this System.
* @return {Promise.<tutao.entity.sys.Customer>} Resolves to the loaded systemCustomer of this System or an exception if the loading failed.
*/
tutao.entity.sys.System.prototype.loadSystemCustomer = function() {
return tutao.entity.sys.Customer.load(this._systemCustomer);
};
/**
* Sets the systemCustomerInfo of this System.
* @param {string} systemCustomerInfo The systemCustomerInfo of this System.
*/
tutao.entity.sys.System.prototype.setSystemCustomerInfo = function(systemCustomerInfo) {
this._systemCustomerInfo = systemCustomerInfo;
return this;
};
/**
* Provides the systemCustomerInfo of this System.
* @return {string} The systemCustomerInfo of this System.
*/
tutao.entity.sys.System.prototype.getSystemCustomerInfo = function() {
return this._systemCustomerInfo;
};
/**
* Sets the systemUserGroup of this System.
* @param {string} systemUserGroup The systemUserGroup of this System.
*/
tutao.entity.sys.System.prototype.setSystemUserGroup = function(systemUserGroup) {
this._systemUserGroup = systemUserGroup;
return this;
};
/**
* Provides the systemUserGroup of this System.
* @return {string} The systemUserGroup of this System.
*/
tutao.entity.sys.System.prototype.getSystemUserGroup = function() {
return this._systemUserGroup;
};
/**
* Loads the systemUserGroup of this System.
* @return {Promise.<tutao.entity.sys.Group>} Resolves to the loaded systemUserGroup of this System or an exception if the loading failed.
*/
tutao.entity.sys.System.prototype.loadSystemUserGroup = function() {
return tutao.entity.sys.Group.load(this._systemUserGroup);
};
/**
* Loads a System from the server.
* @param {string} id The id of the System.
* @return {Promise.<tutao.entity.sys.System>} Resolves to the System or an exception if the loading failed.
*/
tutao.entity.sys.System.load = function(id) {
return tutao.locator.entityRestClient.getElement(tutao.entity.sys.System, tutao.entity.sys.System.PATH, id, null, {"v" : 9}, tutao.entity.EntityHelper.createAuthHeaders()).then(function(entity) {
return entity;
});
};
/**
* Loads multiple Systems from the server.
* @param {Array.<string>} ids The ids of the Systems to load.
* @return {Promise.<Array.<tutao.entity.sys.System>>} Resolves to an array of System or rejects with an exception if the loading failed.
*/
tutao.entity.sys.System.loadMultiple = function(ids) {
return tutao.locator.entityRestClient.getElements(tutao.entity.sys.System, tutao.entity.sys.System.PATH, ids, {"v": 9}, tutao.entity.EntityHelper.createAuthHeaders()).then(function(entities) {
return entities;
});
};
/**
* Register a function that is called as soon as any attribute of the entity has changed. If this listener
* was already registered it is not registered again.
* @param {function(Object,*=)} listener. The listener function. When called it gets the entity and the given id as arguments.
* @param {*=} id. An optional value that is just passed-through to the listener.
*/
tutao.entity.sys.System.prototype.registerObserver = function(listener, id) {
this._entityHelper.registerObserver(listener, id);
};
/**
* Removes a registered listener function if it was registered before.
* @param {function(Object)} listener. The listener to unregister.
*/
tutao.entity.sys.System.prototype.unregisterObserver = function(listener) {
this._entityHelper.unregisterObserver(listener);
};
/**
* Provides the entity helper of this entity.
* @return {tutao.entity.EntityHelper} The entity helper.
*/
tutao.entity.sys.System.prototype.getEntityHelper = function() {
return this._entityHelper;
};
| msoftware/tutanota-1 | web/js/generated/entity/sys/System.js | JavaScript | gpl-3.0 | 18,395 |
//functions for manipulating the HBC stub by giantpune
#include <string.h>
#include <ogcsys.h>
#include <malloc.h>
#include <stdio.h>
#include "lstub.h"
#include "gecko.h"
#include "wad/nandtitle.h"
extern const u8 stub_bin[];
extern const u32 stub_bin_size;
static char* determineStubTIDLocation()
{
u32 *stubID = (u32*) 0x80001818;
//HBC stub 1.0.6 and lower, and stub.bin
if (stubID[0] == 0x480004c1 && stubID[1] == 0x480004f5)
return (char *) 0x800024C6;
//HBC stub changed @ version 1.0.7. this file was last updated for HBC 1.0.8
else if (stubID[0] == 0x48000859 && stubID[1] == 0x4800088d) return (char *) 0x8000286A;
//hexdump( stubID, 0x20 );
return NULL;
}
s32 Set_Stub(u64 reqID)
{
if (NandTitles.IndexOf(reqID) < 0) return WII_EINSTALL;
char *stub = determineStubTIDLocation();
if (!stub) return -68;
stub[0] = TITLE_7( reqID );
stub[1] = TITLE_6( reqID );
stub[8] = TITLE_5( reqID );
stub[9] = TITLE_4( reqID );
stub[4] = TITLE_3( reqID );
stub[5] = TITLE_2( reqID );
stub[12] = TITLE_1( reqID );
stub[13] = ((u8) (reqID));
DCFlushRange(stub, 0x10);
return 1;
}
s32 Set_Stub_Split(u32 type, const char* reqID)
{
const u32 lower = ((u32)reqID[0] << 24) |
((u32)reqID[1] << 16) |
((u32)reqID[2] << 8) |
((u32)reqID[3]);
u64 reqID64 = TITLE_ID( type, lower );
return Set_Stub(reqID64);
}
void loadStub()
{
char *stubLoc = (char *) 0x80001800;
memcpy(stubLoc, stub_bin, stub_bin_size);
DCFlushRange(stubLoc, stub_bin_size);
}
u64 getStubDest()
{
if (!hbcStubAvailable()) return 0;
char ret[8];
u64 retu = 0;
char *stub = determineStubTIDLocation();
if (!stub) return 0;
ret[0] = stub[0];
ret[1] = stub[1];
ret[2] = stub[8];
ret[3] = stub[9];
ret[4] = stub[4];
ret[5] = stub[5];
ret[6] = stub[12];
ret[7] = stub[13];
memcpy(&retu, ret, 8);
return retu;
}
u8 hbcStubAvailable()
{
char * sig = (char *) 0x80001804;
return (strncmp(sig, "STUBHAXX", 8) == 0);
}
| SuperrSonic/ULGX-ICON-VIEW | source/lstub.cpp | C++ | gpl-3.0 | 1,960 |
<?php
/**
* This file is part of OXID eShop Community Edition.
*
* OXID eShop Community Edition is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* OXID eShop Community Edition is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with OXID eShop Community Edition. If not, see <http://www.gnu.org/licenses/>.
*
* @link http://www.oxid-esales.com
* @copyright (C) OXID eSales AG 2003-2017
* @version OXID eShop CE
*/
/**
* Module files validator class.
*
* @internal Do not make a module extension for this class.
* @see http://oxidforge.org/en/core-oxid-eshop-classes-must-not-be-extended.html
*/
class oxModuleFilesValidator implements oxIModuleValidator
{
/**
* Missing module files list.
*
* @var array
*/
private $_aMissingFiles = array();
/**
* Shop directory where modules are stored.
*
* @var string
*/
private $_sPathToModuleDirectory = null;
/**
* Gets path to module directory.
*
* @return string
*/
public function getPathToModuleDirectory()
{
if (is_null($this->_sPathToModuleDirectory)) {
$this->setPathToModuleDirectory(oxRegistry::getConfig()->getModulesDir());
}
return $this->_sPathToModuleDirectory;
}
/**
* Sets path to module directory.
*
* @param string $sPathToModuleDirectory
*/
public function setPathToModuleDirectory($sPathToModuleDirectory)
{
$this->_sPathToModuleDirectory = $sPathToModuleDirectory;
}
/**
* Validates module files.
* Return true if module files exists.
* Return false if at least one module file does not exist.
*
* @param oxModule $oModule object to validate metadata.
*
* @return bool
*/
public function validate(oxModule $oModule)
{
$this->_resetMissingFiles();
$blModuleValid = $this->_allModuleExtensionsExists($oModule);
$blModuleValid = $this->_allModuleFilesExists($oModule) && $blModuleValid;
return $blModuleValid;
}
/**
* Get missing files which result to invalid module.
*
* @return array
*/
public function getMissingFiles()
{
return $this->_aMissingFiles;
}
/**
* Resets missing files array.
*/
protected function _resetMissingFiles()
{
$this->_aMissingFiles = array();
}
/**
* Return true if all module files which extends shop class exists.
*
* @param oxModule $oModule object to validate metadata.
*
* @return bool
*/
protected function _allModuleExtensionsExists($oModule)
{
$aModuleExtendedFiles = $oModule->getExtensions();
$blAllModuleExtensionsExists = $this->_allFilesExists($aModuleExtendedFiles, true, 'extensions');
return $blAllModuleExtensionsExists;
}
/**
* Return true if all module independent PHP files exist.
*
* @param oxModule $oModule object to validate metadata.
*
* @return mixed
*/
protected function _allModuleFilesExists($oModule)
{
$aModuleExtendedFiles = $oModule->getFiles();
$blAllModuleFilesExists = $this->_allFilesExists($aModuleExtendedFiles);
return $blAllModuleFilesExists;
}
/**
* Return true if all requested file exists.
*
* @param array $aModuleExtendedFiles of files which must exist.
* @param bool $blAddExtension if add .php extension to checked files.
* @param string $sListName if add .php extension to checked files.
*
* @return bool
*/
private function _allFilesExists($aModuleExtendedFiles, $blAddExtension = false, $sListName = 'files')
{
$blAllModuleFilesExists = true;
foreach ($aModuleExtendedFiles as $sModuleName => $sModulePath) {
$sPathToModuleDirectory = $this->getPathToModuleDirectory();
$sPathToModuleDirectory = $this->_addDirectorySeparatorAtTheEndIfNeeded($sPathToModuleDirectory);
$sExtPath = $sPathToModuleDirectory . $sModulePath;
if ($blAddExtension) {
$sExtPath .= '.php';
}
if (!file_exists($sExtPath)) {
$blAllModuleFilesExists = false;
$this->_aMissingFiles[$sListName][$sModuleName] = $sModulePath;
}
}
return $blAllModuleFilesExists;
}
/**
* Check if path has directory separator at the end. Add it if needed.
*
* @param strig $sPathToModuleDirectory Module directory pat
*
* @return string
*/
private function _addDirectorySeparatorAtTheEndIfNeeded($sPathToModuleDirectory)
{
if (substr($sPathToModuleDirectory, -1) != DIRECTORY_SEPARATOR) {
$sPathToModuleDirectory .= DIRECTORY_SEPARATOR;
return $sPathToModuleDirectory;
}
return $sPathToModuleDirectory;
}
}
| benzzdan/greeenpeach4 | core/oxmodulefilesvalidator.php | PHP | gpl-3.0 | 5,400 |
#!/usr/bin/env python
#
# This file is part of the pebil project.
#
# Copyright (c) 2010, University of California Regents
# All rights reserved.
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
#
# Counter for a folder
# /pmaclabs/icepic/ti10_round1_icepic_large_0256/processed_trace
# Executable:
# AvgCacheCalc.py
#
# This will calculate the Average of Cache hits for a series of processed metasim files.
#
#
# Usage:
#
# A number of arguments are needed. The arguments determine how to select the set of files to process
# and whether to compute the average across all files or not.
#
# Either sysid or taskid is required
# sysid - calculates a single average for all files with the same sysid
# - use with --sysid option to speciy which sysid to use.
# - for file icepic_large_0256_0127.sysid44, the sysid is 44
#
# taskid - prints an average for each file with the same task id (ie 1 set of averages for for each sysid found)
# - use with --taskid option to specify the task id
# - for file icepic_large_0256_0127.sysid44, the taskid is 0127
#
#
# app icepic,hycom,..."
# dataset large, standard..."
# cpu_count 256,1024,... input will be padded with 0s to 4 digits
# Optional:
# dir - current dir is used if these argument is not given
# As an example take the folder:
# /pmaclabs/ti10/ti10_round1_icepic_large_0256/processed_trace
#
#
# SysID mode:
#mattl@trebek[21]$ ./AvgCacheCalc.py --app icepic --dataset large --cpu_count 1024 --sysid 99 --dir /pmaclabs/ti10/ti10_round1_icepic_large_1024/processed_trace/
# #
# Reading files from: /pmaclabs/ti10/ti10_round1_icepic_large_1024/processed_trace/
# Averaging for all files like icepic_large_1024*.sysid99
# Number of files: 1024
# Cache 1 average %= 98.365459015 incl(98.365459015)
# Cache 2 average %= 0.000974823792366 incl(98.3654743948)
# Cache 3 average %= 0.0 incl(98.3654743948)
#
#
# TaskID:
# mattl@trebek[20]$ ./AvgCacheCalc.py --app icepic --dataset large --cpu_count 1024 --taskid 125 --dir /pmaclabs/ti10/ti10_round1_icepic_large_1024/processed_trace/
#
# Reading files from: /pmaclabs/ti10/ti10_round1_icepic_large_1024/processed_trace/
# Averaging for all files like icepic_large_1024_0125*
# Number of files: 32
# sysid0 99.5021899287
# sysid3 98.3544410843 98.4873748354
# sysid4 99.0521953314 99.0939555641
# sysid21 98.2867244765 98.496093132
# sysid22 98.8836107446 99.0731860899 99.5543906444
# sysid23 98.086753753 98.4952485239
# sysid44 98.8836107446 99.0772427056 99.5790751053
# sysid54 96.785672042 99.0781143074
# sysid64 98.3544410843 98.4789295449 98.4817196019
# sysid67 74.5078816751
# sysid68 23.7552154266
# sysid69 30.5848561276
# sysid70 33.5335710304
# sysid71 37.710498373
# sysid72 98.2910942185 98.2910942244 98.2910942244
# sysid73 98.3544410843 98.4789295449 98.49290069
# sysid74 98.3544410843 98.4789295449 98.4887431283
# sysid75 98.9182843857 99.0849451175 99.5487031836
# sysid77 98.086753753 98.4769519456 98.4956922971
# sysid78 98.9182843857 99.0849451175 99.1358601016
# sysid81 98.2910942185 98.2910942244 98.2910942244
# sysid82 98.2910942185 98.2910942244 98.2910942244
# sysid96 98.3544410843 98.4789295449 98.4928364694
# sysid97 98.3544410843 98.4789295449 98.492618417
# sysid98 98.2910942185 98.2910942244 98.2910942244
# sysid99 98.2910942185 98.2910942244 98.2910942244
# sysid100 98.3544410843 98.4789295449 98.4884141107
# sysid101 98.3544410843 98.4789295449 98.4884425654
# sysid102 98.2910942185 98.2910942244 98.2910942244
# sysid103 98.2910942185 98.2910942244 98.2910942244
# sysid104 98.086753753 98.4769519456 98.5007917366
# sysid105 98.086753753 98.4769519456 98.4966562518
import sys, os, glob, re
# function for getting average for a single file
# used by sysid argument
def getAvgSingle(fileNameGetAvg):
"""calcuates the average cache hits for a file"""
#print "TESTING:: file:", fileNameGetAvg
#this part is from counter_mikey.py
try:
traceFile = open(fileNameGetAvg, 'r')
fileLines = traceFile.readlines()
traceFile.close()
except IOError:
print "Warning: file" + traceFile, "not found"
exit()
#Process file
#count the lines, track each line in a list
everyLine = []
totalMisses = []
totalAccesses = []
myLine = fileLines[0].split()
cLevel = len(myLine)-3
#print "TESTING:: cLevel=", cLevel
for i in range(0,cLevel,1):
totalMisses.append(0)
totalAccesses.append(0)
if cLevel < 1 or cLevel > 3:
print "FATAL: Expected 1, 2 or 3 cache levels"
exit()
idx = 1
for myLine in fileLines:
# tokenize the line and verify that we get the correct number of tokens
myLine = myLine.split()
if cLevel != len(myLine)-3:
print "FATAL: expected " + cLevel + " hit rates on line " + str(idx)
exit()
# ascribe each token to an aptly-named variable
#blockid = long(myLine[0]) ###ASK MIKEY - needed?###
#fpCount = long(myLine[1]) ###ASK MIKEY - needed?###
memCount = long(myLine[2])
inclRate = []
for i in range(0,len(totalMisses),1):
inclRate.append(float(myLine[i+3]))
#print "myLine[", i+3, "]= ", myLine[i+3]
# convert each inclusive hit rate to an exclusive rate
exclRate = [inclRate[0]]
for i in range(1,len(inclRate),1):
thisRate = float(inclRate[i])
prevRate = float(inclRate[i-1])
if prevRate < 100.0:
exclRate.append(100.0*float(thisRate - prevRate)/(100.0 - prevRate))
else:
exclRate.append(float(0.0))
blockAccesses = []
blockMisses = []
blockAccesses.append(memCount)
## blockHits[n] stores the number of memory accesses that make it to cache level N
for i in range(0,len(totalMisses)-1,1):
blockMisses.append((blockAccesses[i]*(float(100.0)-exclRate[i]))/float(100.0))
# print "block L" + str(i+1) + " misses: " + str(blockMisses[i])
blockAccesses.append(blockMisses[i])
# print "block L" + str(i+2) + " accesses: " + str(blockAccesses[i+1])
blockMisses.append(blockAccesses[cLevel-1]*((100.0-exclRate[cLevel-1])/100.0))
# print "block L" + str(cLevel) + " misses: " + str(blockMisses[cLevel-1])
for i in range(0,len(totalMisses),1):
totalMisses[i] += blockMisses[i]
totalAccesses[i] += blockAccesses[i]
totalHits = 0
cacheValues = []
for i in range(0,len(totalMisses),1):
levelHits = (totalAccesses[i] - totalMisses[i])
totalHits += levelHits
#assign values to tuple and return
cacheValues.append((levelHits)/(totalAccesses[i])*100)
cacheValues.append(100*totalHits/totalAccesses[0])
#print "Cache " + str(i+1) + " average %= " + str((levelHits)/(totalAccesses[i])*100) + " incl(" + str(100*totalHits/totalAccesses[0]) + ")"
#print "cacheValues:", cacheValues
return cacheValues
# function for getting average for a single file
# used by taskid argument
# printType: 1 = taskid prints ex: taskid0001
# printType: 2 = sysid pritns sysid72
def printAvgSingle(fileNamepAvg, printType):
#print "Avg for file:", fileNamepAvg
fileidx = fileNamepAvg.rfind("/")
shortfileName = fileNamepAvg[fileidx+1:]
#print "TESTING: FileName:", shortfileName
# get the sysid# for printing later
try:
sysidname = shortfileName[shortfileName.index('.')+1:]
taskidname = shortfileName[shortfileName.index('.')-4:shortfileName.index('.')]
#print "TESTING: sysidname=", sysidname
except ValueError:
print "ERROR: Invalid filename no '.' found in filename:", shortfileName
exit()
except IndexError: #If file has '.' as last char, this could error
print "Error: Invalid location of . in filename. this shouldn't happen-", shortfileName
exit()
#lifted from counter_mikey.py
try:
traceFile = open(fileNamepAvg, 'r')
except IOError, NameError:
print "ERROR: can't find that file: " + fileNamepAvg
exit()
#Process file
#count the lines, track each line in a list
everyLine = []
fileLines = traceFile.readlines()
traceFile.close()
myLine = fileLines[0].split()
cLevel = len(myLine)-3
totalMisses = []
totalAccesses = []
for i in range(0,cLevel,1):
totalMisses.append(0)
totalAccesses.append(0)
####validate cLevel 4,5, or 6 is expected
#print "TESTING: This file has", cLevel, "cache level(s)"
##print "Eachline has", len(myLines), "columns"
if cLevel < 1 or cLevel > 3:
print "ERROR: Expected 1, 2, or 3 cache levels"
exit()
#### create if, else for cLevel = 4,5,6
idx = 1
for myLine in fileLines:
# tokenize the line and verify that we get the correct number of tokens
myLine = myLine.split()
if cLevel != len(myLine)-3:
print "ERROR: expected " + cLevel + " hit rates on line " + str(idx)
# ascribe each token to an aptly-named variable
blockid = long(myLine[0])
fpCount = long(myLine[1])
memCount = long(myLine[2])
inclRate = []
for i in range(0,len(totalMisses),1):
inclRate.append(float(myLine[i+3]))
# convert each inclusive hit rate to an exclusive rate
exclRate = [inclRate[0]]
for i in range(1,len(inclRate),1):
thisRate = float(inclRate[i])
prevRate = float(inclRate[i-1])
if prevRate < 100.0:
exclRate.append(100.0*float(thisRate - prevRate)/(100.0 - prevRate))
else:
exclRate.append(float(0.0))
# print str(myLine) + ' -> ',
# print str(blockid) + '\t' + str(fpCount) + '\t' + str(memCount),
# for i in range(0,len(exclRate),1):
# print '\t' + str(exclRate[i]),
# print ''
blockAccesses = []
blockMisses = []
blockAccesses.append(memCount)
# print "block L1 accesses: " + str(blockAccesses[0])
## blockHits[n] stores the number of memory accesses that make it to cache level N
for i in range(0,len(totalMisses)-1,1):
blockMisses.append((blockAccesses[i]*(float(100.0)-exclRate[i]))/float(100.0))
# print "block L" + str(i+1) + " misses: " + str(blockMisses[i])
blockAccesses.append(blockMisses[i])
# print "block L" + str(i+2) + " accesses: " + str(blockAccesses[i+1])
blockMisses.append(blockAccesses[cLevel-1]*((100.0-exclRate[cLevel-1])/100.0))
# print "block L" + str(cLevel) + " misses: " + str(blockMisses[cLevel-1])
for i in range(0,len(totalMisses),1):
totalMisses[i] += blockMisses[i]
totalAccesses[i] += blockAccesses[i]
# if printType == 1:
# print "taskid" + str(taskidname),
# if printType == 2:
# print sysidname.rjust(8),
print shortfileName,
totalHits = 0
for i in range(0,len(totalMisses),1):
levelHits = (totalAccesses[i] - totalMisses[i])
totalHits += levelHits
#print "Cache " + str(i+1) + " average %= " + str((levelHits)/(totalAccesses[i])*100) + " incl(" + str(100*totalHits/totalAccesses[0]) + ")"
print str(100*totalHits/totalAccesses[0]).ljust(13),
print ""
# used to sort list of files in natural or numeric order
def sort_nicely( l ):
""" Sort the given list in the way that humans expect.
"""
def convert(text):
if text.isdigit():
return int(text)
else:
return text
##convert = lambda text: int(text) if text.isdigit() else text
alphanum_key = lambda key: [ convert(c) for c in re.split('([0-9]+)', key) ]
l.sort( key=alphanum_key )
#prints a usage error message and exits
def errorMsg():
print
print "Usage : ./AvgCacheCalc.py\n"
print "required:"
print "\t--app string; eg icepic,hycom,..."
print "\t--dataset string; eg large, standard..."
print "\t--cpu_count int; eg 256,1024,...\n"
print "One of these two are required:"
print "\t--taskid int; eg 0001"
print "\t--sysid int; 1, 2, or 3 chars - 75\n"
print "optional"
print "\t--dir string; eg /pmaclabs/ti10/ti10_icepic_standard_0128/processed_trace/ [default=.]"
exit()
diridx = -1
sysidx = -1
taskidx = -1
sysidindexerr = 0
taskidindexerr = 0
try:
#check for sysid
sysidx = sys.argv.index("--sysid")
#print "past sysidx ValueError"
#print "sysidx=", sysidx
if sysidx != -1:
sysid = sys.argv[sysidx+1]
#print "sysid=", sysid
except IndexError:
print "TESTING: IndexError:No --sysid argument. ->pass"
sysidindexerr = 1
pass
except ValueError:
#print "TESTING: ValueError --sysid ->pass"
# sysid may not be needed, taskid maybe used
pass
try:
# check for taskid
taskidx = sys.argv.index("--taskid")
task = sys.argv[taskidx+1]
# pad task with 0s if needed
while len(task) < 4:
task = "0"+task
#print "TESTING:task=", task
#print "taskidx=", taskidx
#print "taskid=", task
except IndexError:
print "TESTING: IndexError: No --taskid argument. ->pass"
taskidindexerr = 1
pass
except ValueError:
#print "TESTING: ValueError --taskid ->pass"
pass
# if neither sysid or taskid is used, error
if sysidx == -1 and taskidx == -1:
print "Either --sysid or --taskid required - neither used"
errorMsg()
# if both sysid and taskid are used, error
if sysidx != -1 and taskidx != -1:
print "Either --sysid or --taskid required - both used"
errorMsg()
# check to make sure sys or task value was given
# needed because we skipped this check before
#print "Testing: sysidx and taskidx sysidx=", sysidx," taskidx=", taskidx
if sysidx != -1 and sysidindexerr == 1: # we are using sysid and there was a no value after
print "No --sysid value given, please provide argument\n"
errorMsg()
if taskidx != -1 and taskidindexerr == 1: # we are using taskid and there was a no value after
print "No --taskid value given, please provide argument\n"
errorMsg()
# check for dir
# not required, uses current dir
try:
diridx = sys.argv.index("--dir")
except ValueError:
#print"no dir->ok"
pass # if --dir is not used, current dir willbe used
try:
if diridx == -1:
dirRead = os.getcwd() #use currend dir if none given
#print "TESTING: current dir used dir=", dirRead
else:
dirRead = sys.argv[diridx+1]
#print "TESTING: input used ***WHAT ABOUT SLASH AT END*** dir=", dirRead
#pad a '/' to the end of the directory
if dirRead[-1] != '/':
dirRead = dirRead + '/'
except IndexError:
print "No --dir value given, please provide argument\n"
errorMsg()
except ValueError:
print "TESTING:Error with --dir argument, see usage below\n"
errorMsg()
try:
#check for app
appidx = sys.argv.index("--app")
appname = sys.argv[appidx+1]
#print "app=", appname
except IndexError:
print "No --app value given, please provide argument\n"
errorMsg()
except ValueError:
print "Error with --app argument, see usage below\n"
errorMsg()
try:
#check for dataset
datasetidx = sys.argv.index("--dataset")
datasetname = sys.argv[datasetidx+1]
#print "dataset=", datasetname
except IndexError:
print "No --dataset value given, please provide argument\n"
errorMsg()
except ValueError:
print "Error with --dataset argument, see usage below\n"
errorMsg()
try:
#check for cpu_count
cpuidx = sys.argv.index("--cpu_count")
cpu = sys.argv[cpuidx+1]
#print "cpu=", cpu
#print "cpu type:", type(cpu)
cpulen = len(cpu)
if cpulen > 4: # error if more than 4 digits
print "ERROR: cpu_count cannot be greater than 4 digits"
exit()
if cpulen < 4: # pad with 0 if less than 4 digits
#print "TESTING: cpulen:", cpulen, "needs to be 4"
while len(cpu) < 4:
cpu = "0"+cpu
cpulen = len(cpu)
except IndexError:
print "No --cpu_count value given, please provide argument\n"
errorMsg()
except ValueError:
print "Error with --cpu_count argument, see usage below\n"
errorMsg()
fileName = appname+"_"+datasetname+"_"+cpu
# print "filename:", fileName
# print "dirRead:", dirRead
print
print "Reading files from: ", dirRead
#gets the list of files with a matching sysid value
if taskidx == -1: #use sysid
print "Averaging for all files like "+fileName+"*.sysid"+sysid
fileList = glob.glob(dirRead+fileName+"*.sysid"+sysid)
#or gets the list of files with the taskid value
elif sysidx == -1: #use taskid
print "Averaging for all files like "+fileName+"_"+task+"*"
#print dirRead+fileName+"_"+task+".*"
fileList = glob.glob(dirRead+fileName+"_"+task+".*")
else:
print "ERROR: No one should get here either taskid or sysid should have been validated"
errorMsg()
#for i in range(len(fileList)):
# print "TESTING:filelist[", i, "]=",fileList[i]
#sort the list of files
#fileList.sort()
#sort numerically
sort_nicely(fileList)
#print "fileList[0]:", fileList[0]
#print "fileList type:", type(fileList)
# Catch if there are no files matching the request
if len(fileList) == 0:
print "ERROR: No files match input...exiting"
exit()
print "Number of files: ", len(fileList)
#print "This may take a moment"
if taskidx == -1: #use sysid
dirAvg = []
# goes through each file and collects all the averages
# inclusive and exclusive for Caches 1-3 (if 2 and 3 are present)
for i in range(0, len(fileList)):
dirAvg.append(getAvgSingle(fileList[i]))
printAvgSingle(fileList[i],1)
print "\n *** Averaged Hit rates ***"
print fileName+"*.sysid"+sysid,
numCache = len(dirAvg[0])
totalCache = [0,0,0,0,0,0]
#print "TESTING:numcache for avg of files is:", numCache
#print "TESTING:dirAvg[0]=", dirAvg[0]
#print "TESTING:len(dirAvg[0])=", len(dirAvg[0])
#print "TESTING:len(dirAvg)=", len(dirAvg)
#print "TESTING:numCache range= ", range(numCache)
#calcute averages for the folder
for i in range(len(dirAvg)):
#if len(dirAvg[i]) > 4:
#print "TESTING:dirAvg[",i,"][4]=", dirAvg[i][4]
for j in range(numCache):
#print "::j=",j,"dirAvg[",i,"][",j,"]= ", dirAvg[i][j]
totalCache[j] = totalCache[j]+dirAvg[i][j]
#print values of the cache
for i in range(0, len(totalCache), 2):
if totalCache[i+1] !=0:
print totalCache[i+1]/len(dirAvg),
#print "excl", totalCache[i]/len(dirAvg)
#print "Cache " + str((i/2)+1) + " average %= " + str(totalCache[i]/len(dirAvg)) + " incl(" + str(totalCache[i+1]/len(dirAvg)) + ")"
elif sysidx == -1: #use taskid
for i in range(0, len(fileList)):
printAvgSingle(fileList[i],2)
| DoNotUseThisCodeJUSTFORKS/PEBIL | scripts/AvgCacheCalc.py | Python | gpl-3.0 | 18,915 |
/****************************************************************************
**
** Copyright (C) 2016 The Qt Company Ltd.
** Contact: https://www.qt.io/licensing/
**
** This file is part of Qt Creator.
**
** Commercial License Usage
** Licensees holding valid commercial Qt licenses may use this file in
** accordance with the commercial license agreement provided with the
** Software or, alternatively, in accordance with the terms contained in
** a written agreement between you and The Qt Company. For licensing terms
** and conditions see https://www.qt.io/terms-conditions. For further
** information use the contact form at https://www.qt.io/contact-us.
**
** GNU General Public License Usage
** Alternatively, this file may be used under the terms of the GNU
** General Public License version 3 as published by the Free Software
** Foundation with exceptions as appearing in the file LICENSE.GPL3-EXCEPT
** included in the packaging of this file. Please review the following
** information to ensure the GNU General Public License requirements will
** be met: https://www.gnu.org/licenses/gpl-3.0.html.
**
****************************************************************************/
#include "remotelinuxenvironmentaspect.h"
#include "remotelinuxenvironmentaspectwidget.h"
#include <utils/algorithm.h>
namespace RemoteLinux {
const char DISPLAY_KEY[] = "DISPLAY";
const char VERSION_KEY[] = "RemoteLinux.EnvironmentAspect.Version";
const int ENVIRONMENTASPECT_VERSION = 1; // Version was introduced in 4.3 with the value 1
static bool displayAlreadySet(const Utils::EnvironmentItems &changes)
{
return Utils::contains(changes, [](const Utils::EnvironmentItem &item) {
return item.name == DISPLAY_KEY;
});
}
RemoteLinuxEnvironmentAspect::RemoteLinuxEnvironmentAspect(ProjectExplorer::Target *target)
{
addSupportedBaseEnvironment(tr("Clean Environment"), {});
addPreferredBaseEnvironment(tr("System Environment"), [this] { return m_remoteEnvironment; });
setConfigWidgetCreator([this, target] {
return new RemoteLinuxEnvironmentAspectWidget(this, target);
});
}
void RemoteLinuxEnvironmentAspect::setRemoteEnvironment(const Utils::Environment &env)
{
if (env != m_remoteEnvironment) {
m_remoteEnvironment = env;
emit environmentChanged();
}
}
QString RemoteLinuxEnvironmentAspect::userEnvironmentChangesAsString() const
{
QString env;
QString placeHolder = QLatin1String("%1=%2 ");
foreach (const Utils::EnvironmentItem &item, userEnvironmentChanges())
env.append(placeHolder.arg(item.name, item.value));
return env.mid(0, env.size() - 1);
}
void RemoteLinuxEnvironmentAspect::fromMap(const QVariantMap &map)
{
ProjectExplorer::EnvironmentAspect::fromMap(map);
const auto version = map.value(QLatin1String(VERSION_KEY), 0).toInt();
if (version == 0) {
// In Qt Creator versions prior to 4.3 RemoteLinux included DISPLAY=:0.0 in the base
// environment, if DISPLAY was not set. In order to keep existing projects expecting
// that working, add the DISPLAY setting to user changes in them. New projects will
// have version 1 and will not get DISPLAY set.
auto changes = userEnvironmentChanges();
if (!displayAlreadySet(changes)) {
changes.append(Utils::EnvironmentItem(QLatin1String(DISPLAY_KEY), QLatin1String(":0.0")));
setUserEnvironmentChanges(changes);
}
}
}
void RemoteLinuxEnvironmentAspect::toMap(QVariantMap &map) const
{
ProjectExplorer::EnvironmentAspect::toMap(map);
map.insert(QLatin1String(VERSION_KEY), ENVIRONMENTASPECT_VERSION);
}
} // namespace RemoteLinux
| qtproject/qt-creator | src/plugins/remotelinux/remotelinuxenvironmentaspect.cpp | C++ | gpl-3.0 | 3,689 |
// Copyright (c) Aura development team - Licensed under GNU GPL
// For more information, see license file in the main folder
using Aura.Data;
using Aura.Data.Database;
using Aura.Shared.Database;
using Aura.Shared.Mabi.Const;
using Aura.Shared.Util;
using MySql.Data.MySqlClient;
using System;
using System.Collections.Generic;
using System.IO;
namespace Aura.Login.Database
{
public class LoginDb : AuraDb
{
/// <summary>
/// Checks whether the SQL update file has already been applied.
/// </summary>
/// <param name="updateFile"></param>
/// <returns></returns>
public bool CheckUpdate(string updateFile)
{
using (var conn = this.Connection)
using (var mc = new MySqlCommand("SELECT * FROM `updates` WHERE `path` = @path", conn))
{
mc.Parameters.AddWithValue("@path", updateFile);
using (var reader = mc.ExecuteReader())
return reader.Read();
}
}
/// <summary>
/// Executes SQL update file.
/// </summary>
/// <param name="updateFile"></param>
public void RunUpdate(string updateFile)
{
try
{
using (var conn = this.Connection)
{
// Run update
using (var cmd = new MySqlCommand(File.ReadAllText(Path.Combine("sql", updateFile)), conn))
cmd.ExecuteNonQuery();
// Log update
using (var cmd = new InsertCommand("INSERT INTO `updates` {0}", conn))
{
cmd.Set("path", updateFile);
cmd.Execute();
}
Log.Info("Successfully applied '{0}'.", updateFile);
}
}
catch (Exception ex)
{
Log.Error("RunUpdate: Failed to run '{0}': {1}", updateFile, ex.Message);
CliUtil.Exit(1);
}
}
/// <summary>
/// Returns account or null if account doesn't exist.
/// </summary>
/// <param name="accountId"></param>
/// <returns></returns>
public Account GetAccount(string accountId)
{
using (var conn = this.Connection)
using (var mc = new MySqlCommand("SELECT * FROM `accounts` WHERE `accountId` = @accountId", conn))
{
mc.Parameters.AddWithValue("@accountId", accountId);
using (var reader = mc.ExecuteReader())
{
if (!reader.Read())
return null;
var account = new Account();
account.Name = reader.GetStringSafe("accountId");
account.Password = reader.GetStringSafe("password");
account.SecondaryPassword = reader.GetStringSafe("secondaryPassword");
account.SessionKey = reader.GetInt64("sessionKey");
account.BannedExpiration = reader.GetDateTimeSafe("banExpiration");
account.BannedReason = reader.GetStringSafe("banReason");
return account;
}
}
}
/// <summary>
/// Updates secondary password.
/// </summary>
/// <param name="account"></param>
public void UpdateAccountSecondaryPassword(Account account)
{
using (var conn = this.Connection)
using (var mc = new MySqlCommand("UPDATE `accounts` SET `secondaryPassword` = @secondaryPassword WHERE `accountId` = @accountId", conn))
{
mc.Parameters.AddWithValue("@accountId", account.Name);
mc.Parameters.AddWithValue("@secondaryPassword", account.SecondaryPassword);
mc.ExecuteNonQuery();
}
}
/// <summary>
/// Sets new randomized session key for the account and returns it.
/// </summary>
/// <param name="accountId"></param>
/// <returns></returns>
public long CreateSession(string accountId)
{
using (var conn = this.Connection)
using (var mc = new MySqlCommand("UPDATE `accounts` SET `sessionKey` = @sessionKey WHERE `accountId` = @accountId", conn))
{
var sessionKey = RandomProvider.Get().NextInt64();
mc.Parameters.AddWithValue("@accountId", accountId);
mc.Parameters.AddWithValue("@sessionKey", sessionKey);
mc.ExecuteNonQuery();
return sessionKey;
}
}
/// <summary>
/// Updates lastLogin and loggedIn from the account.
/// </summary>
/// <param name="account"></param>
public void UpdateAccount(Account account)
{
using (var conn = this.Connection)
using (var cmd = new UpdateCommand("UPDATE `accounts` SET `lastLogin` = @lastLogin, `loggedIn` = @loggedIn WHERE `accountId` = @accountId", conn))
{
cmd.Set("accountId", account.Name);
cmd.Set("lastLogin", account.LastLogin);
cmd.Set("loggedIn", account.LoggedIn);
cmd.Execute();
}
}
/// <summary>
/// Returns all character cards present for this account.
/// </summary>
/// <param name="accountId"></param>
/// <returns></returns>
public List<Card> GetCharacterCards(string accountId)
{
using (var conn = this.Connection)
using (var mc = new MySqlCommand("SELECT `cardId`, `type` FROM `cards` WHERE `accountId` = @accountId AND race = 0 AND !`isGift`", conn))
{
mc.Parameters.AddWithValue("@accountId", accountId);
var result = new List<Card>();
using (var reader = mc.ExecuteReader())
{
while (reader.Read())
{
var card = new Card();
card.Id = reader.GetInt64("cardId");
card.Type = reader.GetInt32("type");
result.Add(card);
}
}
return result;
}
}
/// <summary>
/// Returns all pet and partner cards present for this account.
/// </summary>
/// <param name="accountId"></param>
/// <returns></returns>
public List<Card> GetPetCards(string accountId)
{
using (var conn = this.Connection)
using (var mc = new MySqlCommand("SELECT `cardId`, `type`, `race` FROM `cards` WHERE `accountId` = @accountId AND race > 0 AND !`isGift`", conn))
{
mc.Parameters.AddWithValue("@accountId", accountId);
var result = new List<Card>();
using (var reader = mc.ExecuteReader())
{
while (reader.Read())
{
var card = new Card();
card.Id = reader.GetInt64("cardId");
card.Type = reader.GetInt32("type");
card.Race = reader.GetInt32("race");
result.Add(card);
}
}
return result;
}
}
/// <summary>
/// Returns all gifts present for this account.
/// </summary>
/// <param name="accountId"></param>
/// <returns></returns>
public List<Gift> GetGifts(string accountId)
{
using (var conn = this.Connection)
using (var mc = new MySqlCommand("SELECT * FROM `cards` WHERE `accountId` = @accountId AND `isGift`", conn))
{
mc.Parameters.AddWithValue("@accountId", accountId);
var result = new List<Gift>();
using (var reader = mc.ExecuteReader())
{
while (reader.Read())
{
var gift = new Gift();
gift.Id = reader.GetInt64("cardId");
gift.Type = reader.GetInt32("type");
gift.Race = reader.GetInt32("race");
gift.Message = reader.GetStringSafe("message");
gift.Sender = reader.GetStringSafe("sender");
gift.SenderServer = reader.GetStringSafe("senderServer");
gift.Receiver = reader.GetStringSafe("receiver");
gift.ReceiverServer = reader.GetStringSafe("receiverServer");
gift.Added = reader.GetDateTimeSafe("added");
result.Add(gift);
}
}
return result;
}
}
/// <summary>
/// Returns a list of all characters on this account.
/// </summary>
/// <param name="accountId"></param>
/// <returns></returns>
public List<Character> GetCharacters(string accountId)
{
using (var conn = this.Connection)
{
var result = new List<Character>();
this.GetCharacters(accountId, "characters", CharacterType.Character, ref result, conn);
return result;
}
}
/// <summary>
/// Returns a list of all pets/partners on this account.
/// </summary>
/// <param name="accountId"></param>
/// <returns></returns>
public List<Character> GetPetsAndPartners(string accountId)
{
using (var conn = this.Connection)
{
var result = new List<Character>();
this.GetCharacters(accountId, "pets", CharacterType.Pet, ref result, conn);
this.GetCharacters(accountId, "partners", CharacterType.Partner, ref result, conn);
return result;
}
}
/// <summary>
/// Queries characters/pets/partners and adds them to result.
/// </summary>
/// <param name="accountId"></param>
/// <param name="table"></param>
/// <param name="primary"></param>
/// <param name="type"></param>
/// <param name="result"></param>
/// <param name="conn"></param>
private void GetCharacters(string accountId, string table, CharacterType type, ref List<Character> result, MySqlConnection conn)
{
using (var mc = new MySqlCommand(
"SELECT * " +
"FROM `" + table + "` AS c " +
"INNER JOIN `creatures` AS cr ON c.creatureId = cr.creatureId " +
"WHERE `accountId` = @accountId "
, conn))
{
mc.Parameters.AddWithValue("@accountId", accountId);
using (var reader = mc.ExecuteReader())
{
while (reader.Read())
{
var character = new Character();
character.EntityId = reader.GetInt64("entityId");
character.CreatureId = reader.GetInt64("creatureId");
character.Name = reader.GetStringSafe("name");
character.Server = reader.GetStringSafe("server");
character.Race = reader.GetInt32("race");
character.DeletionTime = reader.GetDateTimeSafe("deletionTime");
character.SkinColor = reader.GetByte("skinColor");
character.EyeType = reader.GetInt16("eyeType");
character.EyeColor = reader.GetByte("eyeColor");
character.MouthType = reader.GetByte("mouthType");
character.State = (CreatureStates)reader.GetUInt32("state");
character.Height = reader.GetFloat("height");
character.Weight = reader.GetFloat("weight");
character.Upper = reader.GetFloat("upper");
character.Lower = reader.GetInt32("lower");
character.Color1 = reader.GetUInt32("color1");
character.Color2 = reader.GetUInt32("color2");
character.Color3 = reader.GetUInt32("color3");
result.Add(character);
}
}
}
}
/// <summary>
/// Returns list of all visible items on creature.
/// </summary>
/// <param name="creatureId"></param>
/// <returns></returns>
public List<Item> GetEquipment(long creatureId)
{
using (var conn = this.Connection)
using (var mc = new MySqlCommand("SELECT * FROM `items` WHERE `creatureId` = @creatureId", conn))
{
mc.Parameters.AddWithValue("@creatureId", creatureId);
var result = new List<Item>();
using (var reader = mc.ExecuteReader())
{
while (reader.Read())
{
var item = new Item();
item.Id = reader.GetInt64("entityId");
item.Info.Id = reader.GetInt32("itemId");
item.Info.Pocket = (Pocket)reader.GetByte("pocket");
item.Info.Color1 = reader.GetUInt32("color1");
item.Info.Color2 = reader.GetUInt32("color2");
item.Info.Color3 = reader.GetUInt32("color3");
item.Info.State = reader.GetByte("state");
if (item.IsVisible)
result.Add(item);
}
}
return result;
}
}
/// <summary>
/// Creates creature:character combination for the account.
/// Returns false if either failed, true on success.
/// character's ids are set to the new ids.
/// </summary>
/// <param name="accountId"></param>
/// <param name="character"></param>
/// <param name="items"></param>
/// <returns></returns>
public bool CreateCharacter(string accountId, Character character, List<Item> items)
{
return this.Create("characters", accountId, character, items);
}
/// <summary>
/// Creates creature:pet combination for the account.
/// Returns false if either failed, true on success.
/// pet's ids are set to the new ids.
/// </summary>
/// <param name="accountId"></param>
/// <param name="pet"></param>
/// <returns></returns>
public bool CreatePet(string accountId, Character pet)
{
return this.Create("pets", accountId, pet, null);
}
/// <summary>
/// Creates creature:partner combination for the account.
/// Returns false if either failed, true on success.
/// partner's ids are set to the new ids.
/// </summary>
/// <param name="accountId"></param>
/// <param name="partner"></param>
/// <param name="items"></param>
/// <returns></returns>
public bool CreatePartner(string accountId, Character partner, List<Item> items)
{
return this.Create("partners", accountId, partner, items);
}
/// <summary>
/// Creates creature:x combination for the account.
/// Returns false if either failed, true on success.
/// character's ids are set to the new ids.
/// </summary>
/// <param name="table"></param>
/// <param name="accountId"></param>
/// <param name="character"></param>
/// <param name="items"></param>
/// <returns></returns>
private bool Create(string table, string accountId, Character character, List<Item> items)
{
using (var conn = this.Connection)
using (var transaction = conn.BeginTransaction())
{
try
{
// Creature
character.CreatureId = this.CreateCreature(character, conn, transaction);
// Character
using (var cmd = new InsertCommand("INSERT INTO `" + table + "` {0}", conn, transaction))
{
cmd.Set("accountId", accountId);
cmd.Set("creatureId", character.CreatureId);
cmd.Execute();
character.EntityId = cmd.LastId;
}
// Items
if (items != null)
this.AddItems(character.CreatureId, items, conn, transaction);
transaction.Commit();
return true;
}
catch (Exception ex)
{
character.EntityId = character.CreatureId = 0;
Log.Exception(ex);
return false;
}
}
}
/// <summary>
/// Creatures creature based on character and returns its id.
/// </summary>
/// <param name="creature"></param>
/// <param name="conn"></param>
/// <param name="transaction"></param>
/// <returns></returns>
private long CreateCreature(Character creature, MySqlConnection conn, MySqlTransaction transaction)
{
using (var cmd = new InsertCommand("INSERT INTO `creatures` {0}", conn, transaction))
{
cmd.Set("server", creature.Server);
cmd.Set("name", creature.Name);
cmd.Set("age", creature.Age);
cmd.Set("race", creature.Race);
cmd.Set("skinColor", creature.SkinColor);
cmd.Set("eyeType", creature.EyeType);
cmd.Set("eyeColor", creature.EyeColor);
cmd.Set("mouthType", creature.MouthType);
cmd.Set("state", (uint)creature.State);
cmd.Set("height", creature.Height);
cmd.Set("weight", creature.Weight);
cmd.Set("upper", creature.Upper);
cmd.Set("lower", creature.Lower);
cmd.Set("color1", creature.Color1);
cmd.Set("color2", creature.Color2);
cmd.Set("color3", creature.Color3);
cmd.Set("lifeMax", creature.Life);
cmd.Set("manaMax", creature.Mana);
cmd.Set("staminaMax", creature.Stamina);
cmd.Set("str", creature.Str);
cmd.Set("int", creature.Int);
cmd.Set("dex", creature.Dex);
cmd.Set("will", creature.Will);
cmd.Set("luck", creature.Luck);
cmd.Set("defense", creature.Defense);
cmd.Set("protection", creature.Protection);
cmd.Set("ap", creature.AP);
cmd.Set("creationTime", DateTime.Now);
cmd.Set("lastAging", DateTime.Now);
cmd.Execute();
return cmd.LastId;
}
}
/// <summary>
/// Adds items for creature.
/// </summary>
/// <param name="creatureId"></param>
/// <param name="items"></param>
/// <param name="conn"></param>
/// <param name="transaction"></param>
private void AddItems(long creatureId, List<Item> items, MySqlConnection conn, MySqlTransaction transaction)
{
foreach (var item in items)
{
var dataInfo = AuraData.ItemDb.Find(item.Info.Id);
if (dataInfo == null)
{
Log.Warning("Item '{0}' couldn't be found in the database.", item.Info.Id);
continue;
}
using (var cmd = new InsertCommand("INSERT INTO `items` {0}", conn, transaction))
{
cmd.Set("creatureId", creatureId);
cmd.Set("itemId", item.Info.Id);
cmd.Set("pocket", (byte)item.Info.Pocket);
cmd.Set("color1", item.Info.Color1);
cmd.Set("color2", item.Info.Color2);
cmd.Set("color3", item.Info.Color3);
cmd.Set("price", dataInfo.Price);
cmd.Set("durability", dataInfo.Durability);
cmd.Set("durabilityMax", dataInfo.Durability);
cmd.Set("durabilityOriginal", dataInfo.Durability);
cmd.Set("attackMin", dataInfo.AttackMin);
cmd.Set("attackMax", dataInfo.AttackMax);
cmd.Set("balance", dataInfo.Balance);
cmd.Set("critical", dataInfo.Critical);
cmd.Set("defense", dataInfo.Defense);
cmd.Set("protection", dataInfo.Protection);
cmd.Set("attackSpeed", dataInfo.AttackSpeed);
cmd.Set("sellPrice", dataInfo.SellingPrice);
cmd.Execute();
}
}
}
/// <summary>
/// Removes the card from the db, returns true if successful.
/// </summary>
/// <param name="card"></param>
/// <returns></returns>
public bool DeleteCard(Card card)
{
using (var conn = this.Connection)
using (var mc = new MySqlCommand("DELETE FROM `cards` WHERE `cardId` = @cardId", conn))
{
mc.Parameters.AddWithValue("@cardId", card.Id);
return (mc.ExecuteNonQuery() > 0);
}
}
/// <summary>
/// Changes gift card with the given id to a normal card.
/// </summary>
/// <param name="giftId"></param>
public void ChangeGiftToCard(long giftId)
{
using (var conn = this.Connection)
using (var mc = new MySqlCommand("UPDATE `cards` SET `isGift` = FALSE WHERE `cardId` = @cardId", conn))
{
mc.Parameters.AddWithValue("@cardId", giftId);
mc.ExecuteNonQuery();
}
}
/// <summary>
/// Updates deletion time for character, or deletes it.
/// </summary>
/// <param name="character"></param>
public void UpdateDeletionTime(Character character)
{
using (var conn = this.Connection)
{
if (character.DeletionFlag == DeletionFlag.Delete)
{
using (var mc = new MySqlCommand("DELETE FROM `creatures` WHERE `creatureId` = @creatureId", conn))
{
mc.Parameters.AddWithValue("@creatureId", character.CreatureId);
mc.ExecuteNonQuery();
}
}
else
{
using (var cmd = new UpdateCommand("UPDATE `creatures` SET {0} WHERE `creatureId` = @creatureId", conn))
{
cmd.AddParameter("@creatureId", character.CreatureId);
cmd.Set("deletionTime", character.DeletionTime);
cmd.Execute();
}
}
}
}
/// <summary>
/// Changes auth level of account.
/// </summary>
/// <param name="accountId"></param>
/// <param name="level"></param>
/// <returns></returns>
public bool ChangeAuth(string accountId, int level)
{
using (var conn = this.Connection)
using (var cmd = new UpdateCommand("UPDATE `accounts` SET {0} WHERE `accountId` = @accountId", conn))
{
cmd.AddParameter("@accountId", accountId);
cmd.Set("authority", level);
return (cmd.Execute() > 0);
}
}
/// <summary>
/// Adds trade item and points of card to character.
/// </summary>
/// <param name="targetCharacter"></param>
/// <param name="charCard"></param>
public void TradeCard(Character targetCharacter, CharCardData charCard)
{
using (var conn = this.Connection)
using (var cmd = new InsertCommand("INSERT INTO `items` {0}", conn))
{
cmd.Set("creatureId", targetCharacter.CreatureId);
cmd.Set("itemId", charCard.TradeItem);
cmd.Set("pocket", Pocket.Temporary);
cmd.Set("color1", 0x808080);
cmd.Set("color2", 0x808080);
cmd.Set("color3", 0x808080);
cmd.Execute();
}
// TODO: Add points (pons)...
}
/// <summary>
/// Unsets creature's Initialized creature state flag.
/// </summary>
/// <param name="creatureId"></param>
public void UninitializeCreature(long creatureId)
{
using (var conn = this.Connection)
using (var mc = new MySqlCommand("UPDATE `creatures` SET `state` = `state` & ~1 WHERE `creatureId` = @creatureId", conn))
{
mc.Parameters.AddWithValue("@creatureId", creatureId);
mc.ExecuteNonQuery();
}
}
}
}
| Zanaj/AuraMaster-production | src/LoginServer/Database/LoginDb.cs | C# | gpl-3.0 | 19,818 |
<?php
namespace Embed\Providers;
use Embed\Adapters\Adapter;
use Embed\Utils;
/**
* Provider to get the data from the Open Graph elements in the HTML
*/
class OpenGraph extends Provider
{
/**
* {@inheritdoc}
*/
public function __construct(Adapter $adapter)
{
parent::__construct($adapter);
if (!($html = $adapter->getResponse()->getHtmlContent())) {
return;
}
foreach ($html->getElementsByTagName('meta') as $meta) {
$name = trim(strtolower($meta->getAttribute('property')));
$value = $meta->getAttribute('content');
if (empty($name)) {
$name = trim(strtolower($meta->getAttribute('name')));
}
if (empty($name) || empty($value)) {
continue;
}
if (strpos($name, 'og:') === 0) {
$name = substr($name, 3);
} elseif (
strpos($name, 'article:') !== 0
&& strpos($name, 'image:') !== 0
&& strpos($name, 'video:') !== 0
&& strpos($name, 'book:') !== 0
&& strpos($name, 'music:') !== 0
&& strpos($name, 'profile:') !== 0
) {
continue;
}
switch ($name) {
case 'image':
case 'image:url':
case 'image:secure_url':
$this->bag->add('images', $value);
break;
case 'article:tag':
case 'video:tag':
case 'book:tag':
$this->bag->add('tags', $value);
break;
default:
$this->bag->set($name, $value);
}
}
}
/**
* {@inheritdoc}
*/
public function getTitle()
{
return $this->bag->get('title');
}
/**
* {@inheritdoc}
*/
public function getDescription()
{
return $this->bag->get('description');
}
/**
* {@inheritdoc}
*/
public function getType()
{
$type = $this->bag->get('type');
if (strpos($type, ':') !== false) {
$type = substr(strrchr($type, ':'), 1);
}
switch ($type) {
case 'video':
case 'photo':
case 'link':
case 'rich':
return $type;
case 'article':
return 'link';
}
if ($this->bag->has('video')) {
return 'video';
}
}
/**
* {@inheritdoc}
*/
public function getCode()
{
$names = ['video:secure_url', 'video:url', 'video'];
foreach ($names as $name) {
if ($this->bag->has($name)) {
$video = $this->normalizeUrl($this->bag->get($name));
if (!($videoPath = parse_url($video, PHP_URL_PATH)) || !($type = pathinfo($videoPath, PATHINFO_EXTENSION))) {
$type = $this->bag->get('video:type');
}
switch ($type) {
case 'swf':
case 'application/x-shockwave-flash':
return Utils::flash($video, $this->getWidth(), $this->getHeight());
case 'mp4':
case 'ogg':
case 'ogv':
case 'webm':
case 'application/mp4':
case 'video/mp4':
case 'video/ogg':
case 'video/ogv':
case 'video/webm':
$images = $this->getImagesUrls();
return Utils::videoHtml(current($images), $video, $this->getWidth(), $this->getHeight());
case 'text/html':
return Utils::iframe($video, $this->getWidth(), $this->getHeight());
}
}
}
}
/**
* {@inheritdoc}
*/
public function getUrl()
{
return $this->normalizeUrl($this->bag->get('url'));
}
/**
* {@inheritdoc}
*/
public function getTags()
{
return (array) $this->bag->get('tags') ?: [];
}
/**
* {@inheritdoc}
*/
public function getAuthorName()
{
return $this->bag->get('article:author') ?: $this->bag->get('book:author');
}
/**
* {@inheritdoc}
*/
public function getProviderName()
{
return $this->bag->get('site_name');
}
/**
* {@inheritdoc}
*/
public function getImagesUrls()
{
return $this->normalizeUrls($this->bag->get('images'));
}
/**
* {@inheritdoc}
*/
public function getWidth()
{
return $this->bag->get('image:width') ?: $this->bag->get('video:width');
}
/**
* {@inheritdoc}
*/
public function getHeight()
{
return $this->bag->get('image:height') ?: $this->bag->get('video:height');
}
/**
* {@inheritdoc}
*/
public function getPublishedTime()
{
return $this->bag->get('article:published_time')
?: $this->bag->get('article:modified_time')
?: $this->bag->get('video:release_date')
?: $this->bag->get('music:release_date');
}
/**
* {@inheritdoc}
*/
public function getProviderUrl()
{
return $this->bag->get('website');
}
}
| acrylian/zp_oembed | zp_oembed/Providers/OpenGraph.php | PHP | gpl-3.0 | 5,488 |
/* Part of Cosmos by OpenGenus Foundation */
/* Contributed by Vaibhav Jain (vaibhav29498) */
/* Refactored by Adeen Shukla (adeen-s) */
#include <iostream>
#include <stddef.h>
using namespace std;
struct term {
int coeff;
int pow;
term* next;
term(int, int);
};
term::term(int c, int p) {
coeff = c;
pow = p;
next = NULL;
}
class polynomial {
term* head;
public:
polynomial();
void insert_term(int, int);
void print();
friend polynomial operator+(polynomial, polynomial);
};
polynomial::polynomial() { head = NULL; }
void polynomial::insert_term(int c, int p) {
if (head == NULL) {
head = new term(c, p);
return;
}
if (p > head->pow) {
term* t = new term(c, p);
t->next = head;
head = t;
return;
}
term* cur = head;
while (cur != NULL) {
if (cur->pow == p) {
cur->coeff += c;
return;
}
if ((cur->next == NULL) || (cur->next->pow < p)) {
term* t = new term(c, p);
t->next = cur->next;
cur->next = t;
return;
}
cur = cur->next;
}
}
void polynomial::print() {
term* t = head;
while (t != NULL) {
cout << t->coeff;
if (t->pow) cout << "x^" << t->pow;
if (t->next != NULL) cout << "+";
t = t->next;
}
cout << endl;
}
polynomial operator+(polynomial p1, polynomial p2) {
polynomial p;
term *t1 = p1.head, *t2 = p2.head;
while ((t1 != NULL) && (t2 != NULL)) {
if (t1->pow > t2->pow) {
p.insert_term(t1->coeff, t1->pow);
t1 = t1->next;
} else if (t1->pow < t2->pow) {
p.insert_term(t2->coeff, t2->pow);
t2 = t2->next;
} else {
p.insert_term(t1->coeff + t2->coeff, t1->pow);
t1 = t1->next;
t2 = t2->next;
}
}
while (t1 != NULL) {
p.insert_term(t1->coeff, t1->pow);
t1 = t1->next;
}
while (t2 != NULL) {
p.insert_term(t2->coeff, t2->pow);
t2 = t2->next;
}
return p;
}
int main() {
polynomial p1, p2;
p1.insert_term(7, 4);
p1.insert_term(4, 5);
p1.insert_term(10, 0);
p1.insert_term(9, 2);
cout << "First polynomial:";
p1.print();
p2.insert_term(5, 0);
p2.insert_term(6, 5);
p2.insert_term(7, 0);
p2.insert_term(3, 2);
cout << "Second polynomial:";
p2.print();
polynomial p3 = p1 + p2;
cout << "Sum:";
p3.print();
return 0;
}
| beingadityak/cosmos | code/mathematical-algorithms/add_polynomial/add_polynomials.cpp | C++ | gpl-3.0 | 2,410 |
/*
Input Mask plugin extensions
http://github.com/RobinHerbots/jquery.inputmask
Copyright (c) 2010 - 2014 Robin Herbots
Licensed under the MIT license (http://www.opensource.org/licenses/mit-license.php)
Version: 0.0.0
Optional extensions on the jquery.inputmask base
*/
(function ($) {
//extra definitions
$.extend($.inputmask.defaults.definitions, {
'A': {
validator: "[A-Za-z]",
cardinality: 1,
casing: "upper" //auto uppercasing
},
'#': {
validator: "[A-Za-z\u0410-\u044F\u0401\u04510-9]",
cardinality: 1,
casing: "upper"
}
});
$.extend($.inputmask.defaults.aliases, {
'url': {
mask: "ir",
placeholder: "",
separator: "",
defaultPrefix: "http://",
regex: {
urlpre1: new RegExp("[fh]"),
urlpre2: new RegExp("(ft|ht)"),
urlpre3: new RegExp("(ftp|htt)"),
urlpre4: new RegExp("(ftp:|http|ftps)"),
urlpre5: new RegExp("(ftp:/|ftps:|http:|https)"),
urlpre6: new RegExp("(ftp://|ftps:/|http:/|https:)"),
urlpre7: new RegExp("(ftp://|ftps://|http://|https:/)"),
urlpre8: new RegExp("(ftp://|ftps://|http://|https://)")
},
definitions: {
'i': {
validator: function (chrs, buffer, pos, strict, opts) {
return true;
},
cardinality: 8,
prevalidator: (function () {
var result = [], prefixLimit = 8;
for (var i = 0; i < prefixLimit; i++) {
result[i] = (function () {
var j = i;
return {
validator: function (chrs, buffer, pos, strict, opts) {
if (opts.regex["urlpre" + (j + 1)]) {
var tmp = chrs, k;
if (((j + 1) - chrs.length) > 0) {
tmp = buffer.join('').substring(0, ((j + 1) - chrs.length)) + "" + tmp;
}
var isValid = opts.regex["urlpre" + (j + 1)].test(tmp);
if (!strict && !isValid) {
pos = pos - j;
for (k = 0; k < opts.defaultPrefix.length; k++) {
buffer[pos] = opts.defaultPrefix[k]; pos++;
}
for (k = 0; k < tmp.length - 1; k++) {
buffer[pos] = tmp[k]; pos++;
}
return { "pos": pos };
}
return isValid;
} else {
return false;
}
}, cardinality: j
};
})();
}
return result;
})()
},
"r": {
validator: ".",
cardinality: 50
}
},
insertMode: false,
autoUnmask: false
},
"ip": { //ip-address mask
mask: "i[i[i]].i[i[i]].i[i[i]].i[i[i]]",
definitions: {
'i': {
validator: function (chrs, buffer, pos, strict, opts) {
if (pos - 1 > -1 && buffer[pos - 1] != ".") {
chrs = buffer[pos - 1] + chrs;
if (pos - 2 > -1 && buffer[pos - 2] != ".") {
chrs = buffer[pos - 2] + chrs;
} else chrs = "0" + chrs;
} else chrs = "00" + chrs;
return new RegExp("25[0-5]|2[0-4][0-9]|[01][0-9][0-9]").test(chrs);
},
cardinality: 1
}
}
},
"email": {
mask: "*{1,20}[.*{1,20}][.*{1,20}][.*{1,20}]@*{1,20}.*{2,6}[.*{1,2}]",
greedy: false
}
});
})(jQuery);
| anex/web_mask_field | static/lib/jquery.inputmask.extensions.js | JavaScript | gpl-3.0 | 4,746 |
// *****************************************************************************
//
// (c) Crownwood Consulting Limited 2002-2003
// All rights reserved. The software and associated documentation
// supplied hereunder are the proprietary information of Crownwood Consulting
// Limited, Crownwood, Bracknell, Berkshire, England and are supplied subject
// to licence terms.
//
// Magic Version 1.7.4.0 www.dotnetmagic.com
// *****************************************************************************
using System;
using System.IO;
using System.Drawing;
using System.Reflection;
using System.Windows.Forms;
namespace Crownwood.Magic.Common
{
public class ResourceHelper
{
public static Cursor LoadCursor(Type assemblyType, string cursorName)
{
// Get the assembly that contains the bitmap resource
Assembly myAssembly = Assembly.GetAssembly(assemblyType);
// Get the resource stream containing the images
Stream iconStream = myAssembly.GetManifestResourceStream(cursorName);
// Load the Icon from the stream
return new Cursor(iconStream);
}
public static Icon LoadIcon(Type assemblyType, string iconName)
{
// Get the assembly that contains the bitmap resource
Assembly myAssembly = Assembly.GetAssembly(assemblyType);
// Get the resource stream containing the images
Stream iconStream = myAssembly.GetManifestResourceStream(iconName);
// Load the Icon from the stream
return new Icon(iconStream);
}
public static Icon LoadIcon(Type assemblyType, string iconName, Size iconSize)
{
// Load the entire Icon requested (may include several different Icon sizes)
Icon rawIcon = LoadIcon(assemblyType, iconName);
// Create and return a new Icon that only contains the requested size
return new Icon(rawIcon, iconSize);
}
public static Bitmap LoadBitmap(Type assemblyType, string imageName)
{
return LoadBitmap(assemblyType, imageName, false, new Point(0,0));
}
public static Bitmap LoadBitmap(Type assemblyType, string imageName, Point transparentPixel)
{
return LoadBitmap(assemblyType, imageName, true, transparentPixel);
}
public static ImageList LoadBitmapStrip(Type assemblyType, string imageName, Size imageSize)
{
return LoadBitmapStrip(assemblyType, imageName, imageSize, false, new Point(0,0));
}
public static ImageList LoadBitmapStrip(Type assemblyType,
string imageName,
Size imageSize,
Point transparentPixel)
{
return LoadBitmapStrip(assemblyType, imageName, imageSize, true, transparentPixel);
}
protected static Bitmap LoadBitmap(Type assemblyType,
string imageName,
bool makeTransparent,
Point transparentPixel)
{
// Get the assembly that contains the bitmap resource
Assembly myAssembly = Assembly.GetAssembly(assemblyType);
// Get the resource stream containing the images
Stream imageStream = myAssembly.GetManifestResourceStream(imageName);
// Load the bitmap from stream
Bitmap image = new Bitmap(imageStream);
if (makeTransparent)
{
Color backColor = image.GetPixel(transparentPixel.X, transparentPixel.Y);
// Make backColor transparent for Bitmap
image.MakeTransparent(backColor);
}
return image;
}
protected static ImageList LoadBitmapStrip(Type assemblyType,
string imageName,
Size imageSize,
bool makeTransparent,
Point transparentPixel)
{
// Create storage for bitmap strip
ImageList images = new ImageList();
// Define the size of images we supply
images.ImageSize = imageSize;
// Get the assembly that contains the bitmap resource
Assembly myAssembly = Assembly.GetAssembly(assemblyType);
// Get the resource stream containing the images
Stream imageStream = myAssembly.GetManifestResourceStream(imageName);
// Load the bitmap strip from resource
Bitmap pics = new Bitmap(imageStream);
if (makeTransparent)
{
Color backColor = pics.GetPixel(transparentPixel.X, transparentPixel.Y);
// Make backColor transparent for Bitmap
pics.MakeTransparent(backColor);
}
// Load them all !
images.Images.AddStrip(pics);
return images;
}
}
} | nithinphilips/SMOz | src/SMOz.WinForms/3rdParty/MagicLibrary/Common/ResourceHelper.cs | C# | gpl-3.0 | 5,281 |
/* Skandium: A Java(TM) based parallel skeleton library.
*
* Copyright (C) 2009 NIC Labs, Universidad de Chile.
*
* Skandium is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Skandium is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
* You should have received a copy of the GNU General Public License
* along with Skandium. If not, see <http://www.gnu.org/licenses/>.
*/
package cl.niclabs.skandium.examples.strassen;
public class Operands{
public Matrix a, b;
public Operands(Matrix a, Matrix b){
this.a=a;
this.b=b;
}
} | niclabs/Skandium | src-examples/cl/niclabs/skandium/examples/strassen/Operands.java | Java | gpl-3.0 | 942 |
<?php
// This file is part of Moodle - http://moodle.org/
//
// Moodle is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// Moodle is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with Moodle. If not, see <http://www.gnu.org/licenses/>.
/**
* Serve question type files
*
* @since 2.3
* @package qtype_gapfill
* @copyright Marcus Green 2012
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
defined('MOODLE_INTERNAL') || die();
/**
* Checks file access for gapfill questions.
* @package qtype_gapfill
* @category files
* @param stdClass $course course object
* @param stdClass $cm course module object
* @param stdClass $context context object
* @param string $filearea file area
* @param array $args extra arguments
* @param bool $forcedownload whether or not force download
* @param array $options additional options affecting the file serving
* @global moodle_database $DB
* @global type $CFG
*
*/
function qtype_gapfill_pluginfile($course, $cm, $context, $filearea, $args, $forcedownload, array $options = array()) {
global $DB, $CFG;
require_once($CFG->libdir . '/questionlib.php');
question_pluginfile($course, $context, 'qtype_gapfill', $filearea, $args, $forcedownload, $options);
} | PeTeL-Weizmann/moodle | question/type/gapfill/lib.php | PHP | gpl-3.0 | 1,711 |
<?php
/**
*
* ThinkUp/webapp/plugins/expandurls/model/class.URLExpander.php
*
* Copyright (c) 2012-2013 Gina Trapani
*
* LICENSE:
*
* This file is part of ThinkUp (http://thinkup.com).
*
* ThinkUp is free software: you can redistribute it and/or modify it under the terms of the GNU General Public
* License as published by the Free Software Foundation, either version 2 of the License, or (at your option) any
* later version.
*
* ThinkUp is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied
* warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
* details.
*
* You should have received a copy of the GNU General Public License along with ThinkUp. If not, see
* <http://www.gnu.org/licenses/>.
*
* URL Expander
*
* @license http://www.gnu.org/licenses/gpl.html
* @copyright 2012-2013 Gina Trapani
* @author Gina Trapani <ginatrapani[at]gmail[dot]com>
*
*/
class URLExpander {
/**
* Return the expanded version of a given short URL or save an error for the $original_link in links table and
* return an empty string.
*
* @param str $tinyurl Shortened URL
* @param str $original_link
* @param int $current_number Current link number
* @param int $total_number Total links in group
* @return str Expanded URL
*/
public static function expandURL($tinyurl, $original_link, $current_number, $total_number, $link_dao, $logger) {
if (getenv("MODE")=="TESTS") { //for testing without actually making requests
return $original_link.'/expandedversion';
}
$error_log_prefix = $current_number." of ".$total_number." links: ";
$url = parse_url($tinyurl);
if (isset($url['host'])) {
$host = $url['host'];
} else {
$error_msg = $tinyurl.": No host found.";
$logger->logError($error_log_prefix.$error_msg, __METHOD__.','.__LINE__);
$link_dao->saveExpansionError($original_link, $error_msg);
return '';
}
$port = isset($url['port']) ? ':'.$url['port'] : '';
$query = isset($url['query']) ? '?'.$url['query'] : '';
$fragment = isset($url['fragment']) ? '#'.$url['fragment'] : '';
if (empty($url['path'])) {
$path = '';
} else {
$path = $url['path'];
}
$scheme = isset($url['scheme'])?$url['scheme']:'http';
$reconstructed_url = $scheme."://$host$port".$path.$query.$fragment;
$logger->logInfo("Making cURL request for ".$reconstructed_url, __METHOD__.','.__LINE__);
$ch = curl_init();
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_URL, $reconstructed_url);
curl_setopt($ch, CURLOPT_TIMEOUT, 5); // seconds
curl_setopt($ch, CURLOPT_HEADER, true);
curl_setopt($ch, CURLOPT_NOBODY, true);
curl_setopt($ch, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_1);
curl_setopt($ch, CURLOPT_USERAGENT, "Mozilla/5.0");
$response = curl_exec($ch);
if ($response === false) {
$error_msg = $reconstructed_url." cURL error: ".curl_error($ch);
$logger->logError($error_log_prefix.$error_msg, __METHOD__.','.__LINE__);
$link_dao->saveExpansionError($original_link, $error_msg);
$tinyurl = '';
}
curl_close($ch);
$lines = explode("\r\n", $response);
foreach ($lines as $line) {
if (stripos($line, 'Location:') === 0) {
list(, $location) = explode(':', $line, 2);
$result = ltrim($location);
//If this is a relative redirect, add the host
$dest_url = parse_url($result);
if (!isset($dest_url['host'])) {
$result = $scheme."://$host$port".$result;
}
return $result;
}
}
if (strpos($response, 'HTTP/1.1 404 Not Found') === 0) {
$error_msg = $reconstructed_url." returned '404 Not Found'";
$logger->logError($error_log_prefix.$error_msg, __METHOD__.','.__LINE__);
$link_dao->saveExpansionError($original_link, $error_msg);
return '';
}
return $tinyurl;
}
public static function getWebPageDetails($url) {
$ch = curl_init();
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
curl_setopt($ch, CURLOPT_TIMEOUT, 1); // don't wait more than 1 second
$html = curl_exec($ch);
curl_close($ch);
//parsing begins here:
$doc = new DOMDocument();
@$doc->loadHTML($html);
$nodes = $doc->getElementsByTagName('title');
//get and display what you need:
$title = $nodes->item(0)->nodeValue;
$metas = $doc->getElementsByTagName('meta');
$description = null;
for ($i = 0; $i < $metas->length; $i++) {
$meta = $metas->item($i);
if ($meta->getAttribute('name') == 'description') {
$description = $meta->getAttribute('content');
}
}
//<link rel="shortcut icon" type="image/x-icon" href="/demo/ginatrapani/assets/img/favicon.png">
// $favicon = null;
// $metas = $doc->getElementsByTagName('link');
// for ($i = 0; $i < $metas->length; $i++) {
// $meta = $metas->item($i);
// if ($meta->getAttribute('rel') == 'shortcut icon') {
// $favicon = $meta->getAttribute('href');
// }
// }
return array('title'=>$title, 'description'=>$description);
}
} | anildash/ThinkUp | webapp/plugins/expandurls/model/class.URLExpander.php | PHP | gpl-3.0 | 5,894 |
package org.esa.snap.pixex.aggregators;
import org.esa.snap.pixex.calvalus.ma.Record;
import java.util.Arrays;
/**
* {@inheritDoc}
* <p>
* Retrieves the median value for a record.
* If the record contains an even number of values, the mean of the left and the right median is taken.
*/
public class MedianAggregatorStrategy extends AbstractAggregatorStrategy {
/**
* Returns the median value for the given record and raster index.
*
* @param record The record containing the data for all rasters.
* @param rasterIndex The raster the values shall be aggregated for.
* @return The median value.
*/
@Override
public Number[] getValues(Record record, int rasterIndex) {
final float median = getMedian((Number[]) record.getAttributeValues()[rasterIndex]);
return new Number[]{
median,
getAggregatedNumber(record, rasterIndex).nT
};
}
@Override
public String[] getSuffixes() {
return new String[]{"median", NUM_PIXELS_SUFFIX};
}
float getMedian(Number[] bandValues) {
if (bandValues == null || bandValues.length == 0) {
return Float.NaN;
}
Number[] values = bandValues.clone();
Arrays.sort(values);
if (values.length % 2 == 1) {
return values[values.length / 2].floatValue();
}
final float leftMedian = values[values.length / 2 - 1].floatValue();
final float rightMedian = values[values.length / 2].floatValue();
return (leftMedian + rightMedian) / 2;
}
}
| arraydev/snap-engine | snap-pixel-extraction/src/main/java/org/esa/snap/pixex/aggregators/MedianAggregatorStrategy.java | Java | gpl-3.0 | 1,592 |
/*
* Ext JS Library 1.1
* Copyright(c) 2006-2007, Ext JS, LLC.
* licensing@extjs.com
*
* http://www.extjs.com/license
*/
/*
* Simplified Chinese translation
* By DavidHu
* 09 April 2007
*/
Ext.UpdateManager.defaults.indicatorText = '<div class="loading-indicator">加载中...</div>';
if(Ext.View){
Ext.View.prototype.emptyText = "";
}
if(Ext.grid.Grid){
Ext.grid.Grid.prototype.ddText = "{0} 选择行";
}
if(Ext.TabPanelItem){
Ext.TabPanelItem.prototype.closeText = "关闭";
}
if(Ext.form.Field){
Ext.form.Field.prototype.invalidText = "输入值非法";
}
Date.monthNames = [
"一月",
"二月",
"三月",
"四月",
"五月",
"六月",
"七月",
"八月",
"九月",
"十月",
"十一月",
"十二月"
];
Date.dayNames = [
"周日",
"周一",
"周二",
"周三",
"周四",
"周五",
"周六"
];
if(Ext.MessageBox){
Ext.MessageBox.buttonText = {
ok : "确定",
cancel : "取消",
yes : "是",
no : "否"
};
}
if(Ext.util.Format){
Ext.util.Format.date = function(v, format){
if(!v) return "";
if(!(v instanceof Date)) v = new Date(Date.parse(v));
return v.dateFormat(format || "y年m月d日");
};
}
if(Ext.DatePicker){
Ext.apply(Ext.DatePicker.prototype, {
todayText : "今天",
minText : "日期在最小日期之前",
maxText : "日期在最大日期之后",
disabledDaysText : "",
disabledDatesText : "",
monthNames : Date.monthNames,
dayNames : Date.dayNames,
nextText : '下月 (Control+Right)',
prevText : '上月 (Control+Left)',
monthYearText : '选择一个月 (Control+Up/Down 来改变年)',
todayTip : "{0} (Spacebar)",
format : "y年m月d日"
});
}
if(Ext.PagingToolbar){
Ext.apply(Ext.PagingToolbar.prototype, {
beforePageText : "页",
afterPageText : "of {0}",
firstText : "第一页",
prevText : "前一页",
nextText : "下一页",
lastText : "最后页",
refreshText : "刷新",
displayMsg : "显示 {0} - {1} of {2}",
emptyMsg : '没有数据需要显示'
});
}
if(Ext.form.TextField){
Ext.apply(Ext.form.TextField.prototype, {
minLengthText : "该输入项的最小长度是 {0}",
maxLengthText : "该输入项的最大长度是 {0}",
blankText : "该输入项为必输项",
regexText : "",
emptyText : null
});
}
if(Ext.form.NumberField){
Ext.apply(Ext.form.NumberField.prototype, {
minText : "该输入项的最小值是 {0}",
maxText : "该输入项的最大值是 {0}",
nanText : "{0} 不是有效数值"
});
}
if(Ext.form.DateField){
Ext.apply(Ext.form.DateField.prototype, {
disabledDaysText : "禁用",
disabledDatesText : "禁用",
minText : "该输入项的日期必须在 {0} 之后",
maxText : "该输入项的日期必须在 {0} 之前",
invalidText : "{0} 是无效的日期 - 必须符合格式: {1}",
format : "y年m月d日"
});
}
if(Ext.form.ComboBox){
Ext.apply(Ext.form.ComboBox.prototype, {
loadingText : "加载...",
valueNotFoundText : undefined
});
}
if(Ext.form.VTypes){
Ext.apply(Ext.form.VTypes, {
emailText : '该输入项必须是电子邮件地址,格式如: "user@domain.com"',
urlText : '该输入项必须是URL地址,格式如: "http:/'+'/www.domain.com"',
alphaText : '该输入项只能包含字符和_',
alphanumText : '该输入项只能包含字符,数字和_'
});
}
if(Ext.grid.GridView){
Ext.apply(Ext.grid.GridView.prototype, {
sortAscText : "正序",
sortDescText : "逆序",
lockText : "锁列",
unlockText : "解锁列",
columnsText : "列"
});
}
if(Ext.grid.PropertyColumnModel){
Ext.apply(Ext.grid.PropertyColumnModel.prototype, {
nameText : "名称",
valueText : "值",
dateFormat : "y年m月d日"
});
}
if(Ext.SplitLayoutRegion){
Ext.apply(Ext.SplitLayoutRegion.prototype, {
splitTip : "拖动来改变尺寸.",
collapsibleSplitTip : "拖动来改变尺寸. 双击隐藏."
});
}
| jeffreyhynes-360training/tarantula | app/assets/javascripts/ext/source/locale/ext-lang-zh_CN.js | JavaScript | gpl-3.0 | 4,566 |
#ifndef _BOOKSIM_CONFIG_HPP_
#define _BOOKSIM_CONFIG_HPP_
#include "config_utils.hpp"
class BookSimConfig : public Configuration {
public:
BookSimConfig( );
};
#endif
| ray-chu/gpgpu-sim-test | v3.x/src/intersim/booksim_config.hpp | C++ | gpl-3.0 | 184 |
<?php
/*
* OpenSKOS
*
* LICENSE
*
* This source file is subject to the GPLv3 license that is bundled
* with this package in the file LICENSE.txt.
* It is also available through the world-wide-web at this URL:
* http://www.gnu.org/licenses/gpl-3.0.txt
*
* @category OpenSKOS
* @package OpenSKOS
* @copyright Copyright (c) 2015 Picturae (http://www.picturae.com)
* @author Picturae
* @license http://www.gnu.org/licenses/gpl-3.0.txt GPLv3
*/
namespace OpenSkos2\Api\Transform;
use DateTime;
use OpenSkos2\FieldsMaps;
use OpenSkos2\Namespaces\DcTerms;
use OpenSkos2\Namespaces\Dc;
use OpenSkos2\Namespaces\Skos;
use OpenSkos2\Namespaces\SkosXl;
use OpenSkos2\Namespaces\OpenSkos;
use OpenSkos2\Namespaces\Rdf;
use OpenSkos2\Namespaces\VCard;
use OpenSkos2\Rdf\Resource;
/**
* Transform Resource to a php array with only native values to encode as json output.
* Provide backwards compatability to the API output from OpenSKOS 1 as much as possible
*/
// Meertens: changes of 16/01/2017 are present (previois changes were from 12/03/2016)
class DataArray
{
/**
* @var Resource
*/
private $resource;
/**
* @var array
*/
private $propertiesList;
/**
* @var array
*/
private $excludePropertiesList;
/**
* @param \OpenSkos2\Rdf\Resource $resource
* @param array $propertiesList Properties to serialize.
*/
public function __construct(Resource $resource, $propertiesList = null, $excludePropertiesList = [])
{
$this->resource = $resource;
$this->propertiesList = $propertiesList;
$this->excludePropertiesList = $excludePropertiesList;
}
/**
* Transform the
*
* @return array
*/
// TODO: refactor to use transform, which is more universal
public function transform()
{
$resource = $this->resource;
/* @var $resource Resource */
$newResource = [];
if ($this->doIncludeProperty('uri')) {
$newResource['uri'] = $resource->getUri();
}
foreach (self::getFieldsPlusIsRepeatableMap() as $field => $prop) {
if (!$this->doIncludeProperty($prop['uri'])) {
continue;
}
if ($resource->isPropertyEmpty($prop['uri'])) {
continue;
}
$newResource = $this->getPropertyValue(
$resource->getProperty($prop['uri']),
$field,
$prop,
$newResource
);
}
return $newResource;
}
/**
* Should the property be included in the serialized data.
* @param string $property
* @return bool
*/
protected function doIncludeProperty($property)
{
//The exclude list specifies properties which properties should be skipped
//If a property is both in the include and exclude list we throw an error
if (empty($this->propertiesList)) {
if (in_array($property, $this->excludePropertiesList) === false) {
return true;
} else {
return false;
}
}
if (in_array($property, $this->propertiesList) === true) {
if (in_array($property, $this->excludePropertiesList) === false) {
return true;
} else {
throw new \OpenSkos2\Exception\InvalidArgumentException(
'The property ' . $property . ' is present both in the include and exclude lists'
);
}
}
}
/**
* Get data from property
*
* @param array $prop
* @param array $settings
* #param string $field field name to map
* @param array $resource
* @return array
*/
private function getPropertyValue(array $prop, $field, $settings, $resource)
{
foreach ($prop as $val) {
if ($val instanceof RdfResource) {
if (count($val->getProperties()) > 0) {
if ($settings['repeatable']) {
$resource[$field][] = (new DataArray($val))->transform();
} else {
$resource[$field] = (new DataArray($val))->transform();
}
continue;
}
}
// Some values only have a URI but not getValue or getLanguage
if ($val instanceof \OpenSkos2\Rdf\Uri && !method_exists($val, 'getLanguage')) {
if ($val instanceof Resource) {
if ($settings['repeatable']) {
$resource[$field][] = (new DataArray($val))->transform();
} else {
$resource[$field] = (new DataArray($val))->transform();
}
continue;
}
if ($settings['repeatable'] === true) {
$resource[$field][] = $val->getUri();
} else {
$resource[$field] = $val->getUri();
}
continue;
}
$value = $val->getValue();
if ($value instanceof DateTime) {
$value = $value->format(DATE_W3C);
}
if ($value === null || $value === '') {
continue;
}
$lang = $val->getLanguage();
$langField = $field;
if (!empty($lang)) {
$langField .= '@' . $lang;
}
if ($settings['repeatable'] === true) {
$resource[$langField][] = $value;
} else {
$resource[$langField] = $value;
}
}
return $resource;
}
/**
* Gets map of fields to properties. Including info for if a field is repeatable.
* @return array
*/
public static function getFieldsPlusIsRepeatableMap()
{
$notRepeatable = [
Dc::CREATOR, // literal for names and backward compatibility
DcTerms::CREATOR,
DcTerms::PUBLISHER,
DcTerms::LICENSE,
DcTerms::DATESUBMITTED,
DcTerms::DATEACCEPTED,
DcTerms::MODIFIED,
DcTerms::TITLE,
OpenSkos::ACCEPTEDBY,
OpenSkos::DELETEDBY,
OpenSkos::DATE_DELETED,
OpenSkos::STATUS,
OpenSkos::TENANT,
OpenSkos::SET,
OpenSkos::UUID,
OpenSkos::TOBECHECKED,
Skos::PREFLABEL,
OpenSkos::ENABLESTATUSSESSYSTEMS,
OpenSkos::DISABLESEARCHINOTERTENANTS,
OpenSkos::ENABLESKOSXL,
OpenSkos::ALLOW_OAI,
OpenSkos::CONCEPTBASEURI,
OpenSkos::CODE,
OpenSkos::OAI_BASEURL,
OpenSkos::WEBPAGE,
OpenSkos::NAME,
Rdf::TYPE,
VCard::ADR,
VCard::COUNTRY,
VCard::EMAIL,
VCard::LOCALITY,
VCard::NAME_SPACE,
VCard::ORG,
VCard::ORGNAME,
VCard::ORGUNIT,
VCard::PCODE,
VCard::STREET,
VCard::URL,
SkosXl::LITERALFORM
];
$map = [];
foreach (FieldsMaps::getKeyToPropertyMapping() as $field => $property) {
$map[$field] = [
'uri' => $property,
'repeatable' => !in_array($property, $notRepeatable),
];
}
return $map;
}
}
| CatchPlus/OpenSKOS | library/OpenSkos2/Api/Transform/DataArray.php | PHP | gpl-3.0 | 7,602 |
#region Copyright & License Information
/*
* Copyright 2007-2014 The OpenRA Developers (see AUTHORS)
* This file is part of OpenRA, which is free software. It is made
* available to you under the terms of the GNU General Public License
* as published by the Free Software Foundation. For more information,
* see COPYING.
*/
#endregion
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
namespace OpenRA.FileFormats
{
public class XccLocalDatabase
{
public readonly string[] Entries;
public XccLocalDatabase(Stream s)
{
// Skip unnecessary header data
s.Seek(48, SeekOrigin.Begin);
var reader = new BinaryReader(s);
var count = reader.ReadInt32();
Entries = new string[count];
for (var i = 0; i < count; i++)
{
var chars = new List<char>();
char c;
while ((c = reader.ReadChar()) != 0)
chars.Add(c);
Entries[i] = new string(chars.ToArray());
}
}
public XccLocalDatabase(IEnumerable<string> filenames)
{
Entries = filenames.ToArray();
}
public byte[] Data()
{
var data = new MemoryStream();
using (var writer = new BinaryWriter(data))
{
writer.Write(Encoding.ASCII.GetBytes("XCC by Olaf van der Spek"));
writer.Write(new byte[] {0x1A,0x04,0x17,0x27,0x10,0x19,0x80,0x00});
writer.Write((int)(Entries.Aggregate(Entries.Length, (a,b) => a + b.Length) + 52)); // Size
writer.Write((int)0); // Type
writer.Write((int)0); // Version
writer.Write((int)0); // Game/Format (0 == TD)
writer.Write((int)Entries.Length); // Entries
foreach (var e in Entries)
{
writer.Write(Encoding.ASCII.GetBytes(e));
writer.Write((byte)0);
}
}
return data.ToArray();
}
}
} | penev92/OpenRA | OpenRA.Game/FileFormats/XccLocalDatabase.cs | C# | gpl-3.0 | 1,731 |
/*
* Grakn - A Distributed Semantic Database
* Copyright (C) 2016 Grakn Labs Limited
*
* Grakn is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Grakn is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with Grakn. If not, see <http://www.gnu.org/licenses/gpl.txt>.
*/
package ai.grakn.graql.internal.gremlin.spanningtree;
import ai.grakn.graql.internal.gremlin.spanningtree.graph.DirectedEdge;
import com.google.common.base.Objects;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.Sets;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
/**
* An arborescence is a directed graph in which, for the root and any other vertex,
* there is exactly one directed path between them.
* (https://en.wikipedia.org/wiki/Arborescence_(graph_theory))
*
* @param <V> the type of the nodes
* @author Jason Liu
*/
public class Arborescence<V> {
/**
* In an arborescence, each node (other than the root) has exactly one parent. This is the map
* from each node to its parent.
*/
private final ImmutableMap<V, V> parents;
private final V root;
private Arborescence(ImmutableMap<V, V> parents, V root) {
this.parents = parents;
this.root = root;
}
public static <T> Arborescence<T> of(ImmutableMap<T, T> parents) {
if (parents != null && !parents.isEmpty()) {
HashSet<T> allParents = Sets.newHashSet(parents.values());
allParents.removeAll(parents.keySet());
if (allParents.size() == 1) {
return new Arborescence<>(parents, allParents.iterator().next());
}
}
return new Arborescence<>(parents, null);
}
public static <T> Arborescence<T> empty() {
return Arborescence.of(ImmutableMap.<T, T>of());
}
public boolean contains(DirectedEdge<V> e) {
final V dest = e.destination;
return parents.containsKey(dest) && parents.get(dest).equals(e.source);
}
public V getRoot() {
return root;
}
public int size() {
return parents.size();
}
public ImmutableMap<V, V> getParents() {
return parents;
}
@Override
public String toString() {
StringBuilder stringBuilder = new StringBuilder();
parents.forEach((key, value) -> stringBuilder.append(value).append(" -> ").append(key).append("; "));
return stringBuilder.toString();
}
@Override
public boolean equals(Object other) {
if (this == other) return true;
if (other == null || getClass() != other.getClass()) return false;
final Arborescence that = (Arborescence) other;
Set<Map.Entry<V, V>> myEntries = parents.entrySet();
Set thatEntries = that.parents.entrySet();
return myEntries.size() == thatEntries.size() && myEntries.containsAll(thatEntries);
}
@Override
public int hashCode() {
return Objects.hashCode(parents);
}
}
| sheldonkhall/grakn | grakn-graql/src/main/java/ai/grakn/graql/internal/gremlin/spanningtree/Arborescence.java | Java | gpl-3.0 | 3,426 |
"""Solar analemma."""
from ._skyBase import RadianceSky
from ..material.light import Light
from ..geometry.source import Source
from ladybug.epw import EPW
from ladybug.sunpath import Sunpath
import os
try:
from itertools import izip as zip
writemode = 'wb'
except ImportError:
# python 3
writemode = 'w'
class Analemma(RadianceSky):
"""Generate a radiance-based analemma.
Use Analemma for solar access/sunlight hours studies. For annual daylight/radiation
studies see AnalemmaReversed.
Analemma consists of two files:
1. *.ann file which includes sun geometries and materials.
2. *.mod file includes list of modifiers that are included in *.ann file.
"""
def __init__(self, sun_vectors, sun_up_hours):
"""Radiance-based analemma.
Args:
sun_vectors: A list of sun vectors as (x, y, z).
sun_up_hours: List of hours of the year that corresponds to sun_vectors.
"""
RadianceSky.__init__(self)
vectors = sun_vectors or []
# reverse sun vectors
self._sun_vectors = tuple(tuple(v) for v in vectors)
self._sun_up_hours = sun_up_hours
assert len(sun_up_hours) == len(vectors), \
ValueError(
'Length of vectors [%d] does not match the length of hours [%d]' %
(len(vectors), len(sun_up_hours))
)
@classmethod
def from_json(cls, inp):
"""Create an analemma from a dictionary."""
return cls(inp['sun_vectors'], inp['sun_up_hours'])
@classmethod
def from_location(cls, location, hoys=None, north=0, is_leap_year=False):
"""Generate a radiance-based analemma for a location.
Args:
location: A ladybug location.
hoys: A list of hours of the year (default: range(8760)).
north: North angle from Y direction (default: 0).
is_leap_year: A boolean to indicate if hours are for a leap year
(default: False).
"""
sun_vectors = []
sun_up_hours = []
hoys = hoys or range(8760)
north = north or 0
sp = Sunpath.from_location(location, north)
sp.is_leap_year = is_leap_year
for hour in hoys:
sun = sp.calculate_sun_from_hoy(hour)
if sun.altitude < 0:
continue
sun_vectors.append(sun.sun_vector)
sun_up_hours.append(hour)
return cls(sun_vectors, sun_up_hours)
@classmethod
def from_location_sun_up_hours(cls, location, sun_up_hours, north=0,
is_leap_year=False):
"""Generate a radiance-based analemma for a location.
Args:
location: A ladybug location.
sun_up_hours: A list of hours of the year to be included in analemma.
north: North angle from Y direction (default: 0).
is_leap_year: A boolean to indicate if hours are for a leap year
(default: False).
"""
sun_vectors = []
north = north or 0
sp = Sunpath.from_location(location, north)
sp.is_leap_year = is_leap_year
for hour in sun_up_hours:
sun = sp.calculate_sun_from_hoy(hour)
sun_vectors.append(sun.sun_vector)
return cls(sun_vectors, sun_up_hours)
@classmethod
def from_wea(cls, wea, hoys=None, north=0, is_leap_year=False):
"""Generate a radiance-based analemma from a ladybug wea.
NOTE: Only the location from wea will be used for creating analemma. For
climate-based sun materix see SunMatrix class.
Args:
wea: A ladybug Wea.
sun_up_hours: A list of hours of the year to be included in analemma.
north: North angle from Y direction (default: 0).
is_leap_year: A boolean to indicate if hours are for a leap year
(default: False).
"""
return cls.from_location(wea.location, hoys, north, is_leap_year)
@classmethod
def from_wea_sun_up_hours(cls, wea, sun_up_hours, north=0, is_leap_year=False):
"""Generate a radiance-based analemma from a ladybug wea.
NOTE: Only the location from wea will be used for creating analemma. For
climate-based sun materix see SunMatrix class.
Args:
wea: A ladybug Wea.
sun_up_hours: A list of hours of the year to be included in analemma.
north: North angle from Y direction (default: 0).
is_leap_year: A boolean to indicate if hours are for a leap year
(default: False).
"""
return cls.from_location_sun_up_hours(wea.location, sun_up_hours, north,
is_leap_year)
@classmethod
def from_epw_file(cls, epw_file, hoys=None, north=0, is_leap_year=False):
"""Create sun matrix from an epw file.
NOTE: Only the location from epw file will be used for creating analemma. For
climate-based sun materix see SunMatrix class.
Args:
epw_file: Full path to an epw file.
hoys: A list of hours of the year (default: range(8760)).
north: North angle from Y direction (default: 0).
is_leap_year: A boolean to indicate if hours are for a leap year
(default: False).
"""
return cls.from_location(EPW(epw_file).location, hoys, north, is_leap_year)
@classmethod
def from_epw_file_sun_up_hours(cls, epw_file, sun_up_hours, north=0,
is_leap_year=False):
"""Create sun matrix from an epw file.
NOTE: Only the location from epw file will be used for creating analemma. For
climate-based sun materix see SunMatrix class.
Args:
epw_file: Full path to an epw file.
sun_up_hours: A list of hours of the year to be included in analemma.
north: North angle from Y direction (default: 0).
is_leap_year: A boolean to indicate if hours are for a leap year
(default: False).
"""
return cls.from_location_sun_up_hours(EPW(epw_file).location, sun_up_hours,
north, is_leap_year)
@property
def isAnalemma(self):
"""Return True."""
return True
@property
def is_climate_based(self):
"""Return True if generated based on values from weather file."""
return False
@property
def analemma_file(self):
"""Analemma file name.
Use this file to create the octree.
"""
return 'analemma.rad'
@property
def sunlist_file(self):
"""Sun list file name.
Use this file as the list of modifiers in rcontrib.
"""
return 'analemma.mod'
@property
def sun_vectors(self):
"""Return list of sun vectors."""
return self._sun_vectors
@property
def sun_up_hours(self):
"""Return list of hours for sun vectors."""
return self._sun_up_hours
def execute(self, working_dir):
fp = os.path.join(working_dir, self.analemma_file) # analemma file (geo and mat)
sfp = os.path.join(working_dir, self.sunlist_file) # modifier list
with open(fp, writemode) as outf, open(sfp, writemode) as outm:
for hoy, vector in zip(self.sun_up_hours, self.sun_vectors):
# use minute of the year to name sun positions
moy = int(round(hoy * 60))
mat = Light('sol_%06d' % moy, 1e6, 1e6, 1e6)
sun = Source('sun_%06d' % moy, vector, 0.533, mat)
outf.write(sun.to_rad_string(True).replace('\n', ' ') + '\n')
outm.write('sol_%06d\n' % moy)
def duplicate(self):
"""Duplicate this class."""
return Analemma(self.sun_vectors, self.sun_up_hours)
def to_rad_string(self):
"""Get the radiance command line as a string."""
raise AttributeError(
'analemma does not have a single line command. Try execute method.'
)
def to_json(self):
"""Convert analemma to a dictionary."""
return {'sun_vectors': self.sun_vectors, 'sun_up_hours': self.sun_up_hours}
def ToString(self):
"""Overwrite .NET ToString method."""
return self.__repr__()
def __repr__(self):
"""Analemma representation."""
return 'Analemma: #%d' % len(self.sun_vectors)
class AnalemmaReversed(Analemma):
"""Generate a radiance-based analemma.
Reversed Analemma reverses direction of input sun vectors. Use reversed Analemma for
radiation and daylight studies.
Analemma consists of two files:
1. *_reversed.ann file which includes sun geometries and materials.
2. *.mod file includes list of modifiers that are included in
*_reversed.ann file.
"""
@property
def analemma_file(self):
"""Analemma file name.
Use this file to create the octree.
"""
return 'analemma_reversed.rad'
def execute(self, working_dir):
fp = os.path.join(working_dir, self.analemma_file) # analemma file (geo and mat)
sfp = os.path.join(working_dir, self.sunlist_file) # modifier list
with open(fp, writemode) as outf, open(sfp, writemode) as outm:
for hoy, vector in zip(self.sun_up_hours, self.sun_vectors):
# use minute of the year to name sun positions
moy = int(round(hoy * 60))
# reverse sun vector
r_vector = tuple(-1 * i for i in vector)
mat = Light('sol_%06d' % moy, 1e6, 1e6, 1e6)
sun = Source('sun_%06d' % moy, r_vector, 0.533, mat)
outf.write(sun.to_rad_string(True).replace('\n', ' ') + '\n')
outm.write('sol_%06d\n' % moy)
| ladybug-analysis-tools/honeybee | honeybee_plus/radiance/sky/analemma.py | Python | gpl-3.0 | 9,941 |
/*!
* FileInput Danish Translations
*
* This file must be loaded after 'fileinput.js'. Patterns in braces '{}', or
* any HTML markup tags in the messages must not be converted or translated.
*
* @see http://github.com/kartik-v/bootstrap-fileinput
*
* NOTE: this file must be saved in UTF-8 encoding.
*/
(function ($) {
"use strict";
$.fn.fileinputLocales['da'] = {
fileSingle: 'fil',
filePlural: 'filer',
browseLabel: 'Browse …',
removeLabel: 'Fjern',
removeTitle: 'Fjern valgte filer',
cancelLabel: 'Fortryd',
cancelTitle: 'Afbryd nuværende upload',
uploadLabel: 'Upload',
uploadTitle: 'Upload valgte filer',
msgNo: 'Ingen',
msgNoFilesSelected: '',
msgCancelled: 'aflyst',
msgZoomModalHeading: 'Detaljeret visning',
msgSizeTooLarge: 'Fil "{name}" (<b>{size} KB</b>) er større end de tilladte <b>{maxSize} KB</b>.',
msgFilesTooLess: 'Du skal mindst vælge <b>{n}</b> {files} til upload.',
msgFilesTooMany: '<b>({n})</b> filer valgt til upload, men maks. <b>{m}</b> er tilladt.',
msgFileNotFound: 'Filen "{name}" blev ikke fundet!',
msgFileSecured: 'Sikkerhedsrestriktioner forhindrer læsning af "{name}".',
msgFileNotReadable: 'Filen "{name}" kan ikke indlæses.',
msgFilePreviewAborted: 'Filpreview annulleret for "{name}".',
msgFilePreviewError: 'Der skete en fejl under læsningen af filen "{name}".',
msgInvalidFileType: 'Ukendt type for filen "{name}". Kun "{types}" kan bruges.',
msgInvalidFileExtension: 'Ukendt filtype for filen "{name}". Kun "{extensions}" filer kan bruges.',
msgUploadAborted: 'Filupload annulleret',
msgUploadThreshold: 'Processing...',
msgValidationError: 'Validering Fejl',
msgLoading: 'Henter fil {index} af {files} …',
msgProgress: 'Henter fil {index} af {files} - {name} - {percent}% færdiggjort.',
msgSelected: '{n} {files} valgt',
msgFoldersNotAllowed: 'Drag & drop kun filer! {n} mappe(r) sprunget over.',
msgImageWidthSmall: 'Bredden af billedet "{name}" skal være på mindst {size} px.',
msgImageHeightSmall: 'Højden af billedet "{name}" skal være på mindst {size} px.',
msgImageWidthLarge: 'Bredden af billedet "{name}" må ikke være over {size} px.',
msgImageHeightLarge: 'Højden af billedet "{name}" må ikke være over {size} px.',
msgImageResizeError: 'Kunne ikke få billedets dimensioner for at ændre størrelsen.',
msgImageResizeException: 'Fejl ved at ændre størrelsen på billedet.<pre>{errors}</pre>',
dropZoneTitle: 'Drag & drop filer her …',
dropZoneClickTitle: '<br>(or click to select {files})',
fileActionSettings: {
removeTitle: 'Fjern fil',
uploadTitle: 'Upload fil',
zoomTitle: 'Se detaljer',
dragTitle: 'Move / Rearrange',
indicatorNewTitle: 'Ikke uploadet endnu',
indicatorSuccessTitle: 'Uploadet',
indicatorErrorTitle: 'Upload fejl',
indicatorLoadingTitle: 'Uploader ...'
},
previewZoomButtonTitles: {
prev: 'View previous file',
next: 'View next file',
toggleheader: 'Toggle header',
fullscreen: 'Toggle full screen',
borderless: 'Toggle borderless mode',
close: 'Close detailed preview'
}
};
})(window.jQuery); | ur13l/LaPurisimaWeb | public/js/locales/da.js | JavaScript | gpl-3.0 | 3,695 |
/*
** Xbox360 USB Gamepad Userspace Driver
** Copyright (C) 2011 Ingo Ruhnke <grumbel@gmail.com>
**
** This program is free software: you can redistribute it and/or modify
** it under the terms of the GNU General Public License as published by
** the Free Software Foundation, either version 3 of the License, or
** (at your option) any later version.
**
** This program is distributed in the hope that it will be useful,
** but WITHOUT ANY WARRANTY; without even the implied warranty of
** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
** GNU General Public License for more details.
**
** You should have received a copy of the GNU General Public License
** along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include "xboxdrv_g_controller.hpp"
#include "controller.hpp"
#include "controller_slot.hpp"
#include "controller_thread.hpp"
#include "uinput_message_processor.hpp"
#include "log.hpp"
#define XBOXDRV_CONTROLLER_ERROR xboxdrv_controller_error_quark()
#define XBOXDRV_CONTROLLER_ERROR_FAILED 0
GQuark
xboxdrv_controller_error_quark()
{
return g_quark_from_static_string("xboxdrv-controller-error-quark");
}
/* will create xboxdrv_g_controller_get_type and set xboxdrv_g_controller_parent_class */
G_DEFINE_TYPE(XboxdrvGController, xboxdrv_g_controller, G_TYPE_OBJECT)
static GObject*
xboxdrv_g_controller_constructor(GType gtype,
guint n_properties,
GObjectConstructParam* properties)
{
// Always chain up to the parent constructor
GObjectClass* parent_class = G_OBJECT_CLASS(xboxdrv_g_controller_parent_class);
return parent_class->constructor(gtype, n_properties, properties);
}
static void
xboxdrv_g_controller_class_init(XboxdrvGControllerClass* klass)
{
GObjectClass* gobject_class = G_OBJECT_CLASS(klass);
gobject_class->constructor = xboxdrv_g_controller_constructor;
}
static void
xboxdrv_g_controller_init(XboxdrvGController* self)
{
self->controller = NULL;
}
XboxdrvGController*
xboxdrv_g_controller_new(ControllerSlot* controller)
{
XboxdrvGController* self = static_cast<XboxdrvGController*>(g_object_new(XBOXDRV_TYPE_G_CONTROLLER, NULL));
self->controller = controller;
return self;
}
gboolean
xboxdrv_g_controller_set_led(XboxdrvGController* self, int status, GError** error)
{
log_info("D-Bus: xboxdrv_g_controller_set_led(" << self << ", " << status << ")");
if (self->controller &&
self->controller->get_controller())
{
self->controller->get_controller()->set_led(status);
return TRUE;
}
else
{
g_set_error(error, XBOXDRV_CONTROLLER_ERROR, XBOXDRV_CONTROLLER_ERROR_FAILED,
"could't access controller");
return FALSE;
}
}
gboolean
xboxdrv_g_controller_set_rumble(XboxdrvGController* self, int strong, int weak, GError** error)
{
log_info("D-Bus: xboxdrv_g_controller_set_rumble(" << self << ", " << strong << ", " << weak << ")");
if (self->controller &&
self->controller->get_controller())
{
self->controller->get_controller()->set_rumble(strong, weak);
return TRUE;
}
else
{
g_set_error(error, XBOXDRV_CONTROLLER_ERROR, XBOXDRV_CONTROLLER_ERROR_FAILED,
"could't access controller");
return FALSE;
}
}
gboolean
xboxdrv_g_controller_set_config(XboxdrvGController* self, int config_num, GError** error)
{
log_info("D-Bus: xboxdrv_g_controller_set_config(" << self << ", " << config_num << ")");
if (self->controller &&
self->controller->get_thread() &&
self->controller->get_thread()->get_controller())
{
MessageProcessor* gen_msg_proc = self->controller->get_thread()->get_message_proc();
UInputMessageProcessor* msg_proc = dynamic_cast<UInputMessageProcessor*>(gen_msg_proc);
try
{
msg_proc->set_config(config_num);
return TRUE;
}
catch(const std::exception& err)
{
g_set_error(error, XBOXDRV_CONTROLLER_ERROR, XBOXDRV_CONTROLLER_ERROR_FAILED,
"%s", err.what());
return FALSE;
}
}
else
{
g_set_error(error, XBOXDRV_CONTROLLER_ERROR, XBOXDRV_CONTROLLER_ERROR_FAILED,
"could't access controller");
return FALSE;
}
}
/* EOF */
| TheyCallMeZ/xboxdrv | src/xboxdrv_g_controller.cpp | C++ | gpl-3.0 | 4,266 |
/*
* Copyright 2010-2015 OpenXcom Developers.
*
* This file is part of OpenXcom.
*
* OpenXcom is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* OpenXcom is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with OpenXcom. If not, see <http://www.gnu.org/licenses/>.
*/
#include "BuildFacilitiesState.h"
#include "../Engine/Game.h"
#include "../Mod/Mod.h"
#include "../Engine/LocalizedText.h"
#include "../Engine/Options.h"
#include "../Interface/TextButton.h"
#include "../Interface/Window.h"
#include "../Interface/Text.h"
#include "../Interface/TextList.h"
#include "../Mod/RuleBaseFacility.h"
#include "../Savegame/SavedGame.h"
#include "PlaceFacilityState.h"
namespace OpenXcom
{
/**
* Initializes all the elements in the Build Facilities window.
* @param game Pointer to the core game.
* @param base Pointer to the base to get info from.
* @param state Pointer to the base state to refresh.
*/
BuildFacilitiesState::BuildFacilitiesState(Base *base, State *state) : _base(base), _state(state)
{
_screen = false;
// Create objects
_window = new Window(this, 128, 160, 192, 40, POPUP_VERTICAL);
_btnOk = new TextButton(112, 16, 200, 176);
_lstFacilities = new TextList(104, 104, 200, 64);
_txtTitle = new Text(118, 17, 197, 48);
// Set palette
setInterface("selectFacility");
add(_window, "window", "selectFacility");
add(_btnOk, "button", "selectFacility");
add(_txtTitle, "text", "selectFacility");
add(_lstFacilities, "list", "selectFacility");
centerAllSurfaces();
// Set up objects
_window->setBackground(_game->getMod()->getSurface("BACK05.SCR"));
_btnOk->setText(tr("STR_OK"));
_btnOk->onMouseClick((ActionHandler)&BuildFacilitiesState::btnOkClick);
_btnOk->onKeyboardPress((ActionHandler)&BuildFacilitiesState::btnOkClick, Options::keyCancel);
_txtTitle->setBig();
_txtTitle->setAlign(ALIGN_CENTER);
_txtTitle->setText(tr("STR_INSTALLATION"));
_lstFacilities->setColumns(1, 104);
_lstFacilities->setSelectable(true);
_lstFacilities->setBackground(_window);
_lstFacilities->setMargin(2);
_lstFacilities->setWordWrap(true);
_lstFacilities->setScrolling(true, 0);
_lstFacilities->onMouseClick((ActionHandler)&BuildFacilitiesState::lstFacilitiesClick);
PopulateBuildList();
}
/**
*
*/
BuildFacilitiesState::~BuildFacilitiesState()
{
}
/**
* Populates the build list from the current "available" facilities.
*/
void BuildFacilitiesState::PopulateBuildList()
{
const std::vector<std::string> &facilities = _game->getMod()->getBaseFacilitiesList();
for (std::vector<std::string>::const_iterator i = facilities.begin(); i != facilities.end(); ++i)
{
RuleBaseFacility *rule = _game->getMod()->getBaseFacility(*i);
if (_game->getSavedGame()->isResearched(rule->getRequirements()) && !rule->isLift())
_facilities.push_back(rule);
}
for (std::vector<RuleBaseFacility*>::iterator i = _facilities.begin(); i != _facilities.end(); ++i)
{
_lstFacilities->addRow(1, tr((*i)->getType()).c_str());
}
}
/**
* The player can change the selected base
* or change info on other screens.
*/
void BuildFacilitiesState::init()
{
_state->init();
State::init();
}
/**
* Returns to the previous screen.
* @param action Pointer to an action.
*/
void BuildFacilitiesState::btnOkClick(Action *)
{
_game->popState();
}
/**
* Places the selected facility.
* @param action Pointer to an action.
*/
void BuildFacilitiesState::lstFacilitiesClick(Action *)
{
_game->pushState(new PlaceFacilityState(_base, _facilities[_lstFacilities->getSelectedRow()]));
}
}
| RJPercival/OpenXcom | src/Basescape/BuildFacilitiesState.cpp | C++ | gpl-3.0 | 4,111 |
using OrcaMDF.Core.Engine.Pages;
using OrcaMDF.Core.Engine.Records.VariableLengthDataProxies;
using OrcaMDF.Framework;
using System;
using System.Linq;
namespace OrcaMDF.Core.Engine.Records.Compression
{
internal class CompressedRecord
{
internal CompressedRecordFormat RecordFormat { get; private set; }
internal bool HasVersioningInformation { get; private set; }
internal CompressedRecordType RecordType { get; private set; }
internal short NumberOfColumns { get; private set; }
private readonly Page page;
private readonly byte[] record;
private bool containsLongDataRegion;
private CompressedRecordColumnCDIndicator[] columnValueIndicators;
private short[] shortDataRegionClusterPointers;
private short[] longDataColumnPointers;
private short[] longDataColumnLengths;
internal CompressedRecord(byte[] record, Page page)
{
this.record = record;
this.page = page;
short recordPointer = 1;
parseHeader();
parseCDRegion(ref recordPointer);
parseShortDataRegion(ref recordPointer);
parseLongDataRegion(ref recordPointer);
}
/// <summary>
/// Returns the byte value of a given column index in the record. The value may be compressed, meaning an
/// integer value will only use up as many bytes as required to store the value. Normalization may be needed
/// before the normal type parsers can read the value.
/// </summary>
internal IVariableLengthDataProxy GetPhysicalColumnBytes(int index)
{
// Get column compression indicator
var colDescription = columnValueIndicators[index];
// If it's null, we'll just return it
if (colDescription == CompressedRecordColumnCDIndicator.Null)
return null;
// We don't support page compression yet
if (colDescription == CompressedRecordColumnCDIndicator.DictionarySymbol)
throw new NotSupportedException();
// If it's a true bit,
if (colDescription == CompressedRecordColumnCDIndicator.TrueBit)
return new RawByteProxy(new byte[] { 1 });
// If it's zero-length
if (colDescription == CompressedRecordColumnCDIndicator.ZeroByte)
return new RawByteProxy(new byte[0]);
// Is the data long or short?
if (colDescription == CompressedRecordColumnCDIndicator.LongData)
{
// What's the long-data column index?
int longIndex = 0;
for (int i=0; i<index; i++)
if (columnValueIndicators[i] == CompressedRecordColumnCDIndicator.LongData)
longIndex++;
// Is data stored as a complex value or as raw bytes?
if ((longDataColumnLengths[longIndex] & 32768) > 0)
{
short actualLength = (short)(longDataColumnLengths[longIndex] & 32767);
byte[] data = ArrayHelper.SliceArray(record, longDataColumnPointers[longIndex], actualLength);
// For length 16 we know it'll be a text pointer
if (actualLength == 16)
return new TextPointerProxy(page, data);
// For other lengths we'll have to determine the type of complex column.
// TODO: https://github.com/improvedk/OrcaMDF/issues/2
short complexColumnID = data[0];
if (complexColumnID == 0)
complexColumnID = BitConverter.ToInt16(data, 0);
switch (complexColumnID)
{
// Row-overflow pointer, get referenced data
case 2:
return new BlobInlineRootProxy(page, data);
// BLOB Inline Root
case 4:
return new BlobInlineRootProxy(page, data);
// Back pointer
case 1024:
return new RawByteProxy(data);
default:
throw new ArgumentException("Invalid complex column ID encountered: 0x" + BitConverter.ToInt16(data, 0).ToString("X"));
}
}
else
return new RawByteProxy(ArrayHelper.SliceArray(record, longDataColumnPointers[longIndex], longDataColumnLengths[longIndex]));
}
else
{
// Which cluster is the value stored in?
int clusterIndex = index / 30;
short recordPointer = shortDataRegionClusterPointers[clusterIndex];
// Traverse columns within the cluster until we reach the desired index
for (int i=clusterIndex*30; i<index; i++)
if (columnValueIndicators[i] != CompressedRecordColumnCDIndicator.LongData)
recordPointer += getLengthFromColumnIndicator(columnValueIndicators[i]);
// Return the column value
return new RawByteProxy(ArrayHelper.SliceArray(record, recordPointer, getLengthFromColumnIndicator(colDescription)));
}
}
/// <summary>
/// Returns the value length in bytes of a given column indicator. Only to be used with
/// actual byte-length values, all others will fail.
/// </summary>
private byte getLengthFromColumnIndicator(CompressedRecordColumnCDIndicator indicator)
{
switch(indicator)
{
case CompressedRecordColumnCDIndicator.ZeroByte:
return 0;
case CompressedRecordColumnCDIndicator.OneByte:
return 1;
case CompressedRecordColumnCDIndicator.TwoByte:
return 2;
case CompressedRecordColumnCDIndicator.ThreeByte:
return 3;
case CompressedRecordColumnCDIndicator.FourByte:
return 4;
case CompressedRecordColumnCDIndicator.FiveByte:
return 5;
case CompressedRecordColumnCDIndicator.SixByte:
return 6;
case CompressedRecordColumnCDIndicator.SevenByte:
return 7;
case CompressedRecordColumnCDIndicator.EightByte:
return 8;
}
throw new ArgumentException();
}
private void parseHeader()
{
byte header = record[0];
// Bit 0
RecordFormat = (header & 0x1) > 0 ? CompressedRecordFormat.CD : CompressedRecordFormat.Unknown;
// Bit 1
HasVersioningInformation = (header & 0x2) > 0;
// Bits 2-4
RecordType = (CompressedRecordType)((header << 3) >> 5);
// Bit 5
containsLongDataRegion = (header & 0x20) > 0;
// Bits 6-7 unused in SQL Server 2008
}
private void parseCDRegion(ref short recordPointer)
{
// If the high order bit of the first byte is set, numColumns is a two-byte value,
// otherwise it's a one-byte value.
byte firstByte = record[recordPointer];
if((firstByte & 0x80) > 0)
{
NumberOfColumns = BitConverter.ToInt16(record, 1);
recordPointer += 2;
}
else
NumberOfColumns = record[recordPointer++];
// Next up we have 4 bits per column in the record. Loop all columns, alternating between reading
// the first 4 bits, then the last 4 bits.
columnValueIndicators = new CompressedRecordColumnCDIndicator[NumberOfColumns];
for(int i=0; i<NumberOfColumns; i++)
columnValueIndicators[i] = (CompressedRecordColumnCDIndicator)(i % 2 == 0 ? record[recordPointer] & 0xF : ((record[recordPointer++] & 0xF0) >> 4));
// Make sure to increase recordPointer if we end up reading the first 4 bits as the last
// column, and thus need to pad up to nearest byte.
if(NumberOfColumns % 2 == 1)
recordPointer++;
}
private void parseShortDataRegion(ref short recordPointer)
{
// Calculate the number of clusters in the record
int numClusters = (NumberOfColumns - 1) / 30;
// If there's less than 30 columns, no cluster lengths are stored
if(numClusters == 0)
{
shortDataRegionClusterPointers = new short[1];
shortDataRegionClusterPointers[0] = recordPointer;
// Loop all short data fields to advance the record pointer to the end of the fixed length data
foreach (var col in columnValueIndicators)
if (col >= CompressedRecordColumnCDIndicator.OneByte && col <= CompressedRecordColumnCDIndicator.EightByte)
recordPointer += getLengthFromColumnIndicator(col);
}
else
{
shortDataRegionClusterPointers = new short[numClusters];
// Read the length of each cluster
short[] clusterLengths = new short[numClusters];
for (int i = 0; i < numClusters; i++)
clusterLengths[i] = record[recordPointer++];
// The first cluster always starts right after the cluster length array
shortDataRegionClusterPointers[0] = recordPointer;
// Each consecutive cluster starts after the sum length of all previous clusters
for (int i = 1; i < numClusters; i++)
shortDataRegionClusterPointers[i] = (short)(shortDataRegionClusterPointers[0] + clusterLengths.Take(i).Sum(x => x));
// Once all the cluster lengths have been read, forward the record pointer to the end of the data
recordPointer = (short)(shortDataRegionClusterPointers[numClusters - 1] + clusterLengths[numClusters - 1]);
}
}
private void parseLongDataRegion(ref short recordPointer)
{
if(!containsLongDataRegion)
return;
// Read header
bool containsTwoByteOffsets = Convert.ToBoolean(record[recordPointer] & 0x1);
bool containsComplexColumns = Convert.ToBoolean(record[recordPointer] & 0x2);
recordPointer++;
// Read number of entries
short numEntries = BitConverter.ToInt16(record, recordPointer);
longDataColumnPointers = new short[numEntries];
longDataColumnLengths = new short[numEntries];
recordPointer += 2;
// Read offset entries
short[] offsetEntries = new short[numEntries];
for (int i=0; i<numEntries; i++)
{
offsetEntries[i] = BitConverter.ToInt16(record, recordPointer);
recordPointer += 2;
}
// Read cluster counts
int numClusters = (NumberOfColumns - 1) / 30;
byte[] clusterCount = new byte[numClusters];
// We don't care about the clusters for now, so we'll just forward the pointer right past them
recordPointer += (short)numClusters;
// For each long data column, calculate its starting index and length
for (int i=0; i<numEntries; i++)
{
longDataColumnPointers[i] = recordPointer;
longDataColumnLengths[i] = (short)(offsetEntries[i] - (i > 0 ? offsetEntries[i - 1] : (short)0));
recordPointer += longDataColumnLengths[i];
}
}
}
} | a9261/OrcaMDF | src/OrcaMDF.Core/Engine/Records/Compression/CompressedRecord.cs | C# | gpl-3.0 | 9,665 |
<?php
/**
* Entity of ProjectsMentorsTable
*
* @category Entity
* @package Website
* @author Noël Rignon <rignon.noel@openmailbox.org>
* @license http://www.gnu.org/licenses/gpl-3.0.en.html GPL v3
* @link https://github.com/MaisonLogicielLibre/Website
*/
namespace App\Model\Entity;
use Cake\ORM\Entity;
/**
* Entity of Permissions
*
* @category Entity
* @package Website
* @author Noël Rignon <rignon.noel@openmailbox.org>
* @license http://www.gnu.org/licenses/gpl-3.0.en.html GPL v3
* @link https://github.com/MaisonLogicielLibre/Website
*/
class ProjectsMentor extends Entity
{
/**
* Fields that can be mass assigned using newEntity() or patchEntity().
*
* Note that when '*' is set to true, this allows all unspecified fields to
* be mass assigned. For security purposes, it is advised to set '*' to false
* (or remove it), and explicitly make individual fields accessible as needed.
*
* @var array
*/
protected $accessible = [
'*' => true,
'id' => false,
];
}
| simon-begin/Website | src/Model/Entity/ProjectsMentor.php | PHP | gpl-3.0 | 1,071 |
#!/usr/bin/env python
#
# Copyright 2011 Free Software Foundation, Inc.
#
# This file is part of GNU Radio
#
# GNU Radio is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 3, or (at your option)
# any later version.
#
# GNU Radio is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with GNU Radio; see the file COPYING. If not, write to
# the Free Software Foundation, Inc., 51 Franklin Street,
# Boston, MA 02110-1301, USA.
#
"""
Read samples from a UHD device and write to file formatted as binary
outputs single precision complex float values or complex short values
(interleaved 16 bit signed short integers).
"""
from gnuradio import gr, eng_notation
from gnuradio import uhd
from gnuradio.eng_option import eng_option
from optparse import OptionParser
import sys
n2s = eng_notation.num_to_str
class rx_cfile_block(gr.top_block):
def __init__(self, options, filename):
gr.top_block.__init__(self)
# Create a UHD device source
if options.output_shorts:
self._u = uhd.usrp_source(device_addr=options.address,
io_type=uhd.io_type.COMPLEX_INT16,
num_channels=1)
self._sink = gr.file_sink(gr.sizeof_short*2, filename)
else:
self._u = uhd.usrp_source(device_addr=options.address,
io_type=uhd.io_type.COMPLEX_FLOAT32,
num_channels=1)
self._sink = gr.file_sink(gr.sizeof_gr_complex, filename)
# Set receiver sample rate
self._u.set_samp_rate(options.samp_rate)
# Set receive daughterboard gain
if options.gain is None:
g = self._u.get_gain_range()
options.gain = float(g.start()+g.stop())/2
print "Using mid-point gain of", options.gain, "(", g.start(), "-", g.stop(), ")"
self._u.set_gain(options.gain)
# Set the antenna
if(options.antenna):
self._u.set_antenna(options.antenna, 0)
# Set frequency (tune request takes lo_offset)
if(options.lo_offset is not None):
treq = uhd.tune_request(options.freq, options.lo_offset)
else:
treq = uhd.tune_request(options.freq)
tr = self._u.set_center_freq(treq)
if tr == None:
sys.stderr.write('Failed to set center frequency\n')
raise SystemExit, 1
# Create head block if needed and wire it up
if options.nsamples is None:
self.connect(self._u, self._sink)
else:
if options.output_shorts:
self._head = gr.head(gr.sizeof_short*2, int(options.nsamples))
else:
self._head = gr.head(gr.sizeof_gr_complex, int(options.nsamples))
self.connect(self._u, self._head, self._sink)
input_rate = self._u.get_samp_rate()
if options.verbose:
print "Address:", options.address
print "Rx gain:", options.gain
print "Rx baseband frequency:", n2s(tr.actual_rf_freq)
print "Rx DDC frequency:", n2s(tr.actual_dsp_freq)
print "Rx Sample Rate:", n2s(input_rate)
if options.nsamples is None:
print "Receiving samples until Ctrl-C"
else:
print "Receving", n2s(options.nsamples), "samples"
if options.output_shorts:
print "Writing 16-bit complex shorts"
else:
print "Writing 32-bit complex floats"
print "Output filename:", filename
def get_options():
usage="%prog: [options] output_filename"
parser = OptionParser(option_class=eng_option, usage=usage)
parser.add_option("-a", "--address", type="string", default="addr=192.168.10.2",
help="Address of UHD device, [default=%default]")
parser.add_option("-A", "--antenna", type="string", default=None,
help="select Rx Antenna where appropriate")
parser.add_option("", "--samp-rate", type="eng_float", default=1e6,
help="set sample rate (bandwidth) [default=%default]")
parser.add_option("-f", "--freq", type="eng_float", default=None,
help="set frequency to FREQ", metavar="FREQ")
parser.add_option("-g", "--gain", type="eng_float", default=None,
help="set gain in dB (default is midpoint)")
parser.add_option( "-s","--output-shorts", action="store_true", default=False,
help="output interleaved shorts instead of complex floats")
parser.add_option("-N", "--nsamples", type="eng_float", default=None,
help="number of samples to collect [default=+inf]")
parser.add_option("-v", "--verbose", action="store_true", default=False,
help="verbose output")
parser.add_option("", "--lo-offset", type="eng_float", default=None,
help="set daughterboard LO offset to OFFSET [default=hw default]")
(options, args) = parser.parse_args ()
if len(args) != 1:
parser.print_help()
raise SystemExit, 1
if options.freq is None:
parser.print_help()
sys.stderr.write('You must specify the frequency with -f FREQ\n');
raise SystemExit, 1
return (options, args[0])
if __name__ == '__main__':
(options, filename) = get_options()
tb = rx_cfile_block(options, filename)
try:
tb.run()
except KeyboardInterrupt:
pass
| tta/gnuradio-tta | gr-uhd/apps/uhd_rx_cfile.py | Python | gpl-3.0 | 5,930 |
/*******************************************************************************
* Copyright 2008(c) The OBiBa Consortium. All rights reserved.
*
* This program and the accompanying materials
* are made available under the terms of the GNU Public License v3.0.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
******************************************************************************/
package org.obiba.onyx.jade.core.wicket.wizard;
import java.util.List;
import org.apache.wicket.ajax.AjaxRequestTarget;
import org.apache.wicket.markup.html.panel.EmptyPanel;
import org.apache.wicket.spring.injection.annot.SpringBean;
import org.obiba.onyx.jade.core.domain.instrument.InstrumentOutputParameter;
import org.obiba.onyx.jade.core.domain.instrument.InstrumentType;
import org.obiba.onyx.jade.core.service.ActiveInstrumentRunService;
import org.obiba.onyx.jade.core.wicket.instrument.InstrumentLaunchPanel;
import org.obiba.onyx.jade.core.wicket.instrument.InstrumentOutputParameterPanel;
import org.obiba.onyx.wicket.wizard.WizardForm;
import org.obiba.onyx.wicket.wizard.WizardStepPanel;
public class OutputParametersStep extends WizardStepPanel {
private static final long serialVersionUID = 6617334507631332206L;
@SpringBean
private ActiveInstrumentRunService activeInstrumentRunService;
private InstrumentOutputParameterPanel instrumentOutputParameterPanel;
private WizardStepPanel conclusionStep;
private WizardStepPanel warningsStep;
public OutputParametersStep(String id, WizardStepPanel conclusionStep, WizardStepPanel warningsStep) {
super(id);
this.conclusionStep = conclusionStep;
this.warningsStep = warningsStep;
setOutputMarkupId(true);
add(new EmptyPanel(getTitleId()).setVisible(false));
// add(new Label("title", new StringResourceModel("ProvideTheFollowingInformation", OutputParametersStep.this,
// null)));
// add(new EmptyPanel("panel"));
}
@Override
public void handleWizardState(WizardForm form, AjaxRequestTarget target) {
form.getNextLink().setVisible(isEnableNextLink(form));
// Disable previous button when not needed.
WizardStepPanel previousStep = this.getPreviousStep();
if(previousStep == null || previousStep.equals(this)) {
form.getPreviousLink().setVisible(false);
} else {
form.getPreviousLink().setVisible(true);
}
form.getFinishLink().setVisible(false);
if(target != null) {
target.addComponent(form.getNextLink());
target.addComponent(form.getPreviousLink());
target.addComponent(form.getFinishLink());
}
}
private boolean isEnableNextLink(WizardForm form) {
InstrumentType instrumentType = activeInstrumentRunService.getInstrumentType();
if(instrumentType.isRepeatable()) {
// minimum is having the expected count of repeatable measures
int currentCount = activeInstrumentRunService.getInstrumentRun().getValidMeasureCount();
int expectedCount = instrumentType.getExpectedMeasureCount(activeInstrumentRunService.getParticipant());
boolean skipped = ((InstrumentOutputParameterPanel) get(getContentId())).isSkipMeasurement();
if(currentCount < expectedCount && !skipped) {
return false;
} else {
return true;
}
} else {
return true;
}
}
@Override
public void onStepInNext(WizardForm form, AjaxRequestTarget target) {
super.onStepInNext(form, target);
setContent(target, instrumentOutputParameterPanel = new InstrumentOutputParameterPanel(getContentId()));
}
@Override
public void onStepOutNext(WizardForm form, AjaxRequestTarget target) {
super.onStepOutNext(form, target);
instrumentOutputParameterPanel.saveOutputInstrumentRunValues();
List<InstrumentOutputParameter> paramsWithWarnings = activeInstrumentRunService.getParametersWithWarning();
if(!paramsWithWarnings.isEmpty()) {
warn(getString("ThereAreWarnings"));
((WarningsStep) warningsStep).setParametersWithWarnings(paramsWithWarnings);
setNextStep(warningsStep);
} else {
setNextStep(conclusionStep);
}
}
}
| obiba/onyx | onyx-modules/onyx-jade/onyx-jade-core/src/main/java/org/obiba/onyx/jade/core/wicket/wizard/OutputParametersStep.java | Java | gpl-3.0 | 4,204 |
/* -*-c++-*-
Copyright (C) 2003-2015 Runtime Revolution Ltd.
This file is part of LiveCode.
LiveCode is free software; you can redistribute it and/or modify it under
the terms of the GNU General Public License v3 as published by the Free
Software Foundation.
LiveCode is distributed in the hope that it will be useful, but WITHOUT ANY
WARRANTY; without even the implied warranty of MERCHANTABILITY or
FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
for more details.
You should have received a copy of the GNU General Public License
along with LiveCode. If not see <http://www.gnu.org/licenses/>. */
#include "em-util.h"
#include "sysdefs.h"
#include "osspec.h"
/* ================================================================
* Socket handling
* ================================================================ */
MCSocket *
MCS_accept(uint16_t p_port,
MCObject *p_object,
MCNameRef p_message,
Boolean p_datagram,
Boolean p_secure,
Boolean p_sslverify,
MCStringRef p_sslcertfile)
{
MCEmscriptenNotImplemented();
return nil;
}
bool
MCS_ha(MCSocket *p_socket,
MCStringRef & r_address)
{
MCEmscriptenNotImplemented();
return false;
}
| livecodestephen/livecode | engine/src/em-osspec-network.cpp | C++ | gpl-3.0 | 1,316 |
class Module
def delegate(*methods)
options = methods.pop
unless options.is_a?(Hash) && to = options[:to]
raise ArgumentError, "Delegation needs a target. Supply an options hash with a :to key"
end
methods.each do |method|
module_eval(<<-EOS, "(__DELEGATION__)", 1)
def #{method}(*args, &block)
#{to}.__send__(#{method.inspect}, *args, &block)
end
EOS
end
end
end | rays/PopCurrent | vendor/rails/activesupport/lib/active_support/core_ext/module/delegation.rb | Ruby | gpl-3.0 | 432 |
#ifndef GL_HEADER_HPP
#define GL_HEADER_HPP
#define GLEW_STATIC
extern "C" {
#include <GL/glew.h>
}
#include <cinttypes>
#if defined(__APPLE__)
# include <OpenGL/gl.h>
# include <OpenGL/gl3.h>
# define OGL32CTX
# ifdef GL_ARB_instanced_arrays
# define glVertexAttribDivisor glVertexAttribDivisorARB
# endif
# ifndef GL_TEXTURE_SWIZZLE_RGBA
# define GL_TEXTURE_SWIZZLE_RGBA 0x8E46
# endif
#elif defined(ANDROID)
# include <GLES/gl.h>
#elif defined(WIN32)
# define _WINSOCKAPI_
# include <windows.h>
#else
#define GL_GLEXT_PROTOTYPES
#define DEBUG_OUTPUT_DECLARED
# include <GL/gl.h>
# include <GL/glext.h>
#endif
struct DrawElementsIndirectCommand{
GLuint count;
GLuint instanceCount;
GLuint firstIndex;
GLuint baseVertex;
GLuint baseInstance;
};
#endif
| vlj/YAGE | src/graphics/gl_headers.hpp | C++ | gpl-3.0 | 828 |
<?php
/*
* This file is part of Phraseanet
*
* (c) 2005-2014 Alchemy
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Alchemy\Phrasea\Core\Provider;
use Alchemy\Phrasea\Application;
use Alchemy\Phrasea\Controller\LazyLocator;
use Alchemy\Phrasea\Model\Manager\UserManager;
use Alchemy\Phrasea\Model\Manipulator\ACLManipulator;
use Alchemy\Phrasea\Model\Manipulator\ApiAccountManipulator;
use Alchemy\Phrasea\Model\Manipulator\ApiApplicationManipulator;
use Alchemy\Phrasea\Model\Manipulator\ApiLogManipulator;
use Alchemy\Phrasea\Model\Manipulator\ApiOauthCodeManipulator;
use Alchemy\Phrasea\Model\Manipulator\ApiOauthRefreshTokenManipulator;
use Alchemy\Phrasea\Model\Manipulator\ApiOauthTokenManipulator;
use Alchemy\Phrasea\Model\Manipulator\BasketManipulator;
use Alchemy\Phrasea\Model\Manipulator\LazaretManipulator;
use Alchemy\Phrasea\Model\Manipulator\PresetManipulator;
use Alchemy\Phrasea\Model\Manipulator\RegistrationManipulator;
use Alchemy\Phrasea\Model\Manipulator\TaskManipulator;
use Alchemy\Phrasea\Model\Manipulator\TokenManipulator;
use Alchemy\Phrasea\Model\Manipulator\UserManipulator;
use Alchemy\Phrasea\Model\Manipulator\WebhookEventDeliveryManipulator;
use Alchemy\Phrasea\Model\Manipulator\WebhookEventManipulator;
use Silex\Application as SilexApplication;
use Silex\ServiceProviderInterface;
class ManipulatorServiceProvider implements ServiceProviderInterface
{
public function register(SilexApplication $app)
{
$app['manipulator.task'] = $app->share(function (Application $app) {
return new TaskManipulator($app['orm.em'], $app['translator'], $app['task-manager.notifier']);
});
$app['manipulator.user'] = $app->share(function (Application $app) {
return new UserManipulator(
$app['model.user-manager'],
$app['auth.password-encoder'],
$app['geonames.connector'],
$app['repo.users'],
$app['random.low'],
$app['dispatcher']
);
});
$app['manipulator.token'] = $app->share(function (Application $app) {
return new TokenManipulator(
$app['orm.em'],
$app['random.medium'],
$app['repo.tokens'],
$app['tmp.download.path']
);
});
$app['manipulator.preset'] = $app->share(function (Application $app) {
return new PresetManipulator($app['orm.em'], $app['repo.presets']);
});
$app['manipulator.acl'] = $app->share(function (Application $app) {
return new ACLManipulator($app['acl'], $app->getApplicationBox());
});
$app['model.user-manager'] = $app->share(function (Application $app) {
return new UserManager($app['orm.em'], $app->getApplicationBox()->get_connection());
});
$app['manipulator.registration'] = $app->share(function (Application $app) {
return new RegistrationManipulator(
$app,
$app['orm.em'],
$app['acl'],
$app->getApplicationBox(),
$app['repo.registrations']
);
});
$app['manipulator.api-application'] = $app->share(function (Application $app) {
return new ApiApplicationManipulator($app['orm.em'], $app['repo.api-applications'], $app['random.medium']);
});
$app['manipulator.api-account'] = $app->share(function (Application $app) {
return new ApiAccountManipulator($app['orm.em']);
});
$app['manipulator.api-oauth-code'] = $app->share(function (Application $app) {
return new ApiOauthCodeManipulator($app['orm.em'], $app['repo.api-oauth-codes'], $app['random.medium']);
});
$app['manipulator.api-oauth-token'] = $app->share(function (Application $app) {
return new ApiOauthTokenManipulator($app['orm.em'], $app['repo.api-oauth-tokens'], $app['random.medium']);
});
$app['manipulator.api-oauth-refresh-token'] = $app->share(function (Application $app) {
return new ApiOauthRefreshTokenManipulator($app['orm.em'], $app['repo.api-oauth-refresh-tokens'], $app['random.medium']);
});
$app['manipulator.api-log'] = $app->share(function (Application $app) {
return new ApiLogManipulator($app['orm.em'], $app['repo.api-logs']);
});
$app['manipulator.webhook-event'] = $app->share(function (Application $app) {
return new WebhookEventManipulator($app['orm.em'], $app['repo.webhook-event']);
});
$app['manipulator.webhook-delivery'] = $app->share(function (Application $app) {
return new WebhookEventDeliveryManipulator($app['orm.em'], $app['repo.webhook-delivery']);
});
$app['manipulator.basket'] = $app->share(function (Application $app) {
return new BasketManipulator($app, $app['repo.baskets'], $app['orm.em']);
});
$app['manipulator.lazaret'] = $app->share(function (Application $app) {
return new LazaretManipulator($app, $app['repo.lazaret-files'], $app['filesystem'], $app['orm.em']);
});
}
public function boot(SilexApplication $app)
{
// no-op
}
}
| lostdalek/Phraseanet | lib/Alchemy/Phrasea/Core/Provider/ManipulatorServiceProvider.php | PHP | gpl-3.0 | 5,393 |
/* xoreos - A reimplementation of BioWare's Aurora engine
*
* xoreos is the legal property of its developers, whose names
* can be found in the AUTHORS file distributed with this source
* distribution.
*
* xoreos is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version 3
* of the License, or (at your option) any later version.
*
* xoreos is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with xoreos. If not, see <http://www.gnu.org/licenses/>.
*/
/** @file
* Generic renderable line.
*/
#include "src/graphics/aurora/line.h"
namespace Graphics {
namespace Aurora {
Line::Line() : Renderable(kRenderableTypeObject) {
_color[0] = 1.f;
_color[1] = 0.f;
_color[2] = 1.f;
_color[3] = 0.8;
}
Line::~Line() {
}
void Line::setVertices(std::vector<glm::vec3> &points) {
if (points.size() < 2)
return;
_points = points;
}
void Line::setColor(float color[]) {
_color[0] = color[0];
_color[1] = color[1];
_color[2] = color[2];
_color[3] = color[3];
}
void Line::show() {
Renderable::show();
}
void Line::hide() {
Renderable::hide();
}
void Line::calculateDistance() {
}
void Line::render(RenderPass pass) {
if (pass == kRenderPassOpaque)
return;
if (_points.empty())
return;
glLineWidth(3.f);
glBegin(GL_LINES);
for (size_t p = 0; p < _points.size() - 1; ++p) {
glColor4f(_color[0], _color[1], _color[2], _color[3]);
glVertex3f(_points[p][0], _points[p][1], _points[p][2] + 0.1);
glVertex3f(_points[p + 1][0], _points[p + 1][1], _points[p + 1][2] + 0.1);
}
glEnd();
glLineWidth(1.f);
glColor4f(1.0f, 1.0f, 1.0f, 1.0f);
return;
}
} // End of namespace Aurora
} // End of namespace Graphics
| Supermanu/xoreos | src/graphics/aurora/line.cpp | C++ | gpl-3.0 | 2,024 |
###############################################################################
# ilastik: interactive learning and segmentation toolkit
#
# Copyright (C) 2011-2014, the ilastik developers
# <team@ilastik.org>
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation; either version 2
# of the License, or (at your option) any later version.
#
# In addition, as a special exception, the copyright holders of
# ilastik give you permission to combine ilastik with applets,
# workflows and plugins which are not covered under the GNU
# General Public License.
#
# See the LICENSE file for details. License information is also available
# on the ilastik web site at:
# http://ilastik.org/license.html
###############################################################################
from PyQt4.QtCore import Qt
from PyQt4.QtGui import QColor
from volumina.api import LazyflowSource, ColortableLayer, AlphaModulatedLayer
from ilastik.applets.dataExport.dataExportGui import DataExportGui, DataExportLayerViewerGui
from lazyflow.operators import OpMultiArraySlicer2
from ilastik.utility.exportingOperator import ExportingGui
class ObjectClassificationDataExportGui( DataExportGui, ExportingGui ):
"""
A subclass of the generic data export gui that creates custom layer viewers.
"""
def __init__(self, *args, **kwargs):
super(ObjectClassificationDataExportGui, self).__init__(*args, **kwargs)
self._exporting_operator = None
def set_exporting_operator(self, op):
self._exporting_operator = op
def get_exporting_operator(self, lane=0):
return self._exporting_operator.getLane(lane)
def createLayerViewer(self, opLane):
return ObjectClassificationResultsViewer(self.parentApplet, opLane)
def get_export_dialog_title(self):
return "Export Object Information"
@property
def gui_applet(self):
return self.parentApplet
def get_raw_shape(self):
return self.get_exporting_operator().RawImages.meta.shape
def get_feature_names(self):
return self.get_exporting_operator().ComputedFeatureNames([]).wait()
def _initAppletDrawerUic(self):
super(ObjectClassificationDataExportGui, self)._initAppletDrawerUic()
from PyQt4.QtGui import QGroupBox, QPushButton, QVBoxLayout
group = QGroupBox("Export Object Feature Table", self.drawer)
group.setLayout(QVBoxLayout())
self.drawer.layout().addWidget(group)
btn = QPushButton("Configure and export", group)
btn.clicked.connect(self.show_export_dialog)
group.layout().addWidget(btn)
def _createDefault16ColorColorTable():
colors = []
# Transparent for the zero label
colors.append(QColor(0,0,0,0))
# ilastik v0.5 colors
colors.append( QColor( Qt.red ) )
colors.append( QColor( Qt.green ) )
colors.append( QColor( Qt.yellow ) )
colors.append( QColor( Qt.blue ) )
colors.append( QColor( Qt.magenta ) )
colors.append( QColor( Qt.darkYellow ) )
colors.append( QColor( Qt.lightGray ) )
# Additional colors
colors.append( QColor(255, 105, 180) ) #hot pink
colors.append( QColor(102, 205, 170) ) #dark aquamarine
colors.append( QColor(165, 42, 42) ) #brown
colors.append( QColor(0, 0, 128) ) #navy
colors.append( QColor(255, 165, 0) ) #orange
colors.append( QColor(173, 255, 47) ) #green-yellow
colors.append( QColor(128,0, 128) ) #purple
colors.append( QColor(240, 230, 140) ) #khaki
# colors.append( QColor(192, 192, 192) ) #silver
# colors.append( QColor(69, 69, 69) ) # dark grey
# colors.append( QColor( Qt.cyan ) )
assert len(colors) == 16
return [c.rgba() for c in colors]
class ObjectClassificationResultsViewer(DataExportLayerViewerGui):
_colorTable16 = _createDefault16ColorColorTable()
def setupLayers(self):
layers = []
opLane = self.topLevelOperatorView
selection_names = opLane.SelectionNames.value
selection = selection_names[ opLane.InputSelection.value ]
# This code depends on a specific order for the export slots.
# If those change, update this function!
assert selection in ['Object Predictions', 'Object Probabilities', 'Pixel Probabilities']
if selection == "Object Predictions":
fromDiskSlot = self.topLevelOperatorView.ImageOnDisk
if fromDiskSlot.ready():
exportLayer = ColortableLayer( LazyflowSource(fromDiskSlot), colorTable=self._colorTable16 )
exportLayer.name = "Prediction - Exported"
exportLayer.visible = True
layers.append(exportLayer)
previewSlot = self.topLevelOperatorView.ImageToExport
if previewSlot.ready():
previewLayer = ColortableLayer( LazyflowSource(previewSlot), colorTable=self._colorTable16 )
previewLayer.name = "Prediction - Preview"
previewLayer.visible = False
layers.append(previewLayer)
elif selection == "Object Probabilities":
exportedLayers = self._initPredictionLayers(opLane.ImageOnDisk)
for layer in exportedLayers:
layer.visible = True
layer.name = layer.name + "- Exported"
layers += exportedLayers
previewLayers = self._initPredictionLayers(opLane.ImageToExport)
for layer in previewLayers:
layer.visible = False
layer.name = layer.name + "- Preview"
layers += previewLayers
elif selection == 'Pixel Probabilities':
exportedLayers = self._initPredictionLayers(opLane.ImageOnDisk)
for layer in exportedLayers:
layer.visible = True
layer.name = layer.name + "- Exported"
layers += exportedLayers
previewLayers = self._initPredictionLayers(opLane.ImageToExport)
for layer in previewLayers:
layer.visible = False
layer.name = layer.name + "- Preview"
layers += previewLayers
else:
assert False, "Unknown selection."
rawSlot = self.topLevelOperatorView.RawData
if rawSlot.ready():
rawLayer = self.createStandardLayerFromSlot(rawSlot)
rawLayer.name = "Raw Data"
rawLayer.opacity = 1.0
layers.append(rawLayer)
return layers
def _initPredictionLayers(self, predictionSlot):
layers = []
opLane = self.topLevelOperatorView
# Use a slicer to provide a separate slot for each channel layer
opSlicer = OpMultiArraySlicer2( parent=opLane.viewed_operator().parent )
opSlicer.Input.connect( predictionSlot )
opSlicer.AxisFlag.setValue('c')
for channel, channelSlot in enumerate(opSlicer.Slices):
if channelSlot.ready():
drange = channelSlot.meta.drange or (0.0, 1.0)
predictsrc = LazyflowSource(channelSlot)
predictLayer = AlphaModulatedLayer( predictsrc,
tintColor=QColor.fromRgba(self._colorTable16[channel+1]),
# FIXME: This is weird. Why are range and normalize both set to the same thing?
range=drange,
normalize=drange )
predictLayer.opacity = 1.0
predictLayer.visible = True
predictLayer.name = "Probability Channel #{}".format( channel+1 )
layers.append(predictLayer)
return layers | nielsbuwen/ilastik | ilastik/applets/objectClassification/objectClassificationDataExportGui.py | Python | gpl-3.0 | 7,930 |
/*
Copyright (c) 2004-2011, The Dojo Foundation All Rights Reserved.
Available via Academic Free License >= 2.1 OR the modified BSD license.
see: http://dojotoolkit.org/license for details
*/
//>>built
define("dojo/cldr/nls/nl/number",{"group":".","percentSign":"%","exponential":"E","scientificFormat":"#E0","percentFormat":"#,##0%","list":";","infinity":"∞","minusSign":"-","decimal":",","nan":"NaN","perMille":"‰","decimalFormat":"#,##0.###","currencyFormat":"¤ #,##0.00;¤ #,##0.00-","plusSign":"+","decimalFormat-long":"000 biljoen","decimalFormat-short":"000 bln'.'"});
| cryo3d/cryo3d | static/ThirdParty/dojo-release-1.9.3/dojo/cldr/nls/nl/number.js | JavaScript | gpl-3.0 | 596 |
package CollectionMusicInstrument;
/**
* Created by ZahornyiAI on 23.03.2016.
*/
public class Guitar extends MusicalInstrument {
public Guitar(String name, int quantity, int price) {
super(name, quantity, price);
}
}
| andrewzagor/goit | SortCollection/Guitar.java | Java | gpl-3.0 | 246 |
#region Copyright & License Information
/*
* Copyright 2007-2020 The OpenRA Developers (see AUTHORS)
* This file is part of OpenRA, which is free software. It is made
* available to you under the terms of the GNU General Public License
* as published by the Free Software Foundation, either version 3 of
* the License, or (at your option) any later version. For more
* information, see COPYING.
*/
#endregion
using System.Linq;
using OpenRA.Mods.Common;
using OpenRA.Mods.Common.Traits;
using OpenRA.Primitives;
using OpenRA.Traits;
namespace OpenRA.Mods.Cnc.Traits
{
[Desc("Creates a free duplicate of produced units.")]
public class ClonesProducedUnitsInfo : ConditionalTraitInfo, Requires<ProductionInfo>, Requires<ExitInfo>
{
[FieldLoader.Require]
[Desc("Uses the \"Cloneable\" trait to determine whether or not we should clone a produced unit.")]
public readonly BitSet<CloneableType> CloneableTypes = default(BitSet<CloneableType>);
[FieldLoader.Require]
[Desc("e.g. Infantry, Vehicles, Aircraft, Buildings")]
public readonly string ProductionType = "";
public override object Create(ActorInitializer init) { return new ClonesProducedUnits(init, this); }
}
public class ClonesProducedUnits : ConditionalTrait<ClonesProducedUnitsInfo>, INotifyOtherProduction
{
readonly Production[] productionTraits;
public ClonesProducedUnits(ActorInitializer init, ClonesProducedUnitsInfo info)
: base(info)
{
productionTraits = init.Self.TraitsImplementing<Production>().ToArray();
}
public void UnitProducedByOther(Actor self, Actor producer, Actor produced, string productionType, TypeDictionary init)
{
if (IsTraitDisabled)
return;
// No recursive cloning!
if (producer.Owner != self.Owner || producer.Info.HasTraitInfo<ClonesProducedUnitsInfo>())
return;
var ci = produced.Info.TraitInfoOrDefault<CloneableInfo>();
if (ci == null || !Info.CloneableTypes.Overlaps(ci.Types))
return;
var factionInit = init.GetOrDefault<FactionInit>();
// Stop as soon as one production trait successfully produced
foreach (var p in productionTraits)
{
if (!string.IsNullOrEmpty(Info.ProductionType) && !p.Info.Produces.Contains(Info.ProductionType))
continue;
var inits = new TypeDictionary
{
new OwnerInit(self.Owner),
factionInit ?? new FactionInit(BuildableInfo.GetInitialFaction(produced.Info, p.Faction))
};
if (p.Produce(self, produced.Info, Info.ProductionType, inits))
return;
}
}
}
}
| atlimit8/OpenRA | OpenRA.Mods.Cnc/Traits/Buildings/ClonesProducedUnits.cs | C# | gpl-3.0 | 2,514 |
/****************************************************************************
**
** Copyright (C) 2016 The Qt Company Ltd.
** Contact: https://www.qt.io/licensing/
**
** This file is part of Qt Creator.
**
** Commercial License Usage
** Licensees holding valid commercial Qt licenses may use this file in
** accordance with the commercial license agreement provided with the
** Software or, alternatively, in accordance with the terms contained in
** a written agreement between you and The Qt Company. For licensing terms
** and conditions see https://www.qt.io/terms-conditions. For further
** information use the contact form at https://www.qt.io/contact-us.
**
** GNU General Public License Usage
** Alternatively, this file may be used under the terms of the GNU
** General Public License version 3 as published by the Free Software
** Foundation with exceptions as appearing in the file LICENSE.GPL3-EXCEPT
** included in the packaging of this file. Please review the following
** information to ensure the GNU General Public License requirements will
** be met: https://www.gnu.org/licenses/gpl-3.0.html.
**
****************************************************************************/
#include "removeuiobjectmembervisitor.h"
#include <qmljs/parser/qmljsast_p.h>
#include <QDebug>
using namespace QmlDesigner;
using namespace QmlDesigner::Internal;
RemoveUIObjectMemberVisitor::RemoveUIObjectMemberVisitor(TextModifier &modifier,
quint32 objectLocation):
QMLRewriter(modifier),
objectLocation(objectLocation)
{
}
bool RemoveUIObjectMemberVisitor::preVisit(QmlJS::AST::Node *ast)
{
parents.push(ast);
return true;
}
void RemoveUIObjectMemberVisitor::postVisit(QmlJS::AST::Node *)
{
parents.pop();
}
bool RemoveUIObjectMemberVisitor::visit(QmlJS::AST::UiPublicMember *ast) { return visitObjectMember(ast); }
bool RemoveUIObjectMemberVisitor::visit(QmlJS::AST::UiObjectDefinition *ast) { return visitObjectMember(ast); }
bool RemoveUIObjectMemberVisitor::visit(QmlJS::AST::UiSourceElement *ast) { return visitObjectMember(ast); }
bool RemoveUIObjectMemberVisitor::visit(QmlJS::AST::UiObjectBinding *ast) { return visitObjectMember(ast); }
bool RemoveUIObjectMemberVisitor::visit(QmlJS::AST::UiScriptBinding *ast) { return visitObjectMember(ast); }
bool RemoveUIObjectMemberVisitor::visit(QmlJS::AST::UiArrayBinding *ast) { return visitObjectMember(ast); }
// FIXME: duplicate code in the QmlJS::Rewriter class, remove this
bool RemoveUIObjectMemberVisitor::visitObjectMember(QmlJS::AST::UiObjectMember *ast)
{
const quint32 memberStart = ast->firstSourceLocation().offset;
if (memberStart == objectLocation) {
// found it
int start = objectLocation;
int end = ast->lastSourceLocation().end();
if (QmlJS::AST::UiArrayBinding *parentArray = containingArray())
extendToLeadingOrTrailingComma(parentArray, ast, start, end);
else
includeSurroundingWhitespace(start, end);
includeLeadingEmptyLine(start);
replace(start, end - start, QStringLiteral(""));
setDidRewriting(true);
return false;
} else if (ast->lastSourceLocation().end() <= objectLocation) {
// optimization: if the location of the object-to-be-removed is not inside the current member, skip any children
return false;
} else {
// only visit children if the rewriting isn't done yet.
return !didRewriting();
}
}
QmlJS::AST::UiArrayBinding *RemoveUIObjectMemberVisitor::containingArray() const
{
if (parents.size() > 2) {
if (QmlJS::AST::cast<QmlJS::AST::UiArrayMemberList*>(parents[parents.size() - 2]))
return QmlJS::AST::cast<QmlJS::AST::UiArrayBinding*>(parents[parents.size() - 3]);
}
return 0;
}
// FIXME: duplicate code in the QmlJS::Rewriter class, remove this
void RemoveUIObjectMemberVisitor::extendToLeadingOrTrailingComma(QmlJS::AST::UiArrayBinding *parentArray,
QmlJS::AST::UiObjectMember *ast,
int &start,
int &end) const
{
QmlJS::AST::UiArrayMemberList *currentMember = 0;
for (QmlJS::AST::UiArrayMemberList *it = parentArray->members; it; it = it->next) {
if (it->member == ast) {
currentMember = it;
break;
}
}
if (!currentMember)
return;
if (currentMember->commaToken.isValid()) {
// leading comma
start = currentMember->commaToken.offset;
if (includeSurroundingWhitespace(start, end))
--end;
} else if (currentMember->next && currentMember->next->commaToken.isValid()) {
// trailing comma
end = currentMember->next->commaToken.end();
includeSurroundingWhitespace(start, end);
} else {
// array with 1 element, so remove the complete binding
start = parentArray->firstSourceLocation().offset;
end = parentArray->lastSourceLocation().end();
includeSurroundingWhitespace(start, end);
}
}
| pivonroll/Qt_Creator | src/plugins/qmldesigner/designercore/filemanager/removeuiobjectmembervisitor.cpp | C++ | gpl-3.0 | 5,209 |
package cz.incad.Kramerius.exts.menu.context.impl.adm.items;
import java.io.IOException;
import cz.incad.Kramerius.exts.menu.context.impl.AbstractContextMenuItem;
import cz.incad.Kramerius.exts.menu.context.impl.adm.AdminContextMenuItem;
public class ApplyMovingWallItem extends AbstractContextMenuItem implements AdminContextMenuItem {
@Override
public boolean isMultipleSelectSupported() {
return false;
}
@Override
public String getRenderedItem() throws IOException {
return super.renderContextMenuItem("javascript:parametrizedProcess.open('parametrizedapplymw');", "administrator.menu.applymw");
}
}
| ceskaexpedice/kramerius | search/src/java/cz/incad/Kramerius/exts/menu/context/impl/adm/items/ApplyMovingWallItem.java | Java | gpl-3.0 | 662 |
<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE TS><TS version="2.0" language="ru_RU" sourcelanguage="">
<context>
<name>Form</name>
<message>
<location filename="loop.ui" line="14"/>
<source>Form</source>
<translation type="unfinished">Окно</translation>
</message>
<message>
<location filename="logger.ui" line="23"/>
<source>Automatically detect and log all variables</source>
<translation type="unfinished">Приложение само находит и собирает данные по всем переменным</translation>
</message>
<message>
<location filename="logger.ui" line="30"/>
<source>Include variables with missing values</source>
<translation type="unfinished">Добавить переменные с отсутствующими значениями</translation>
</message>
<message>
<location filename="logger.ui" line="37"/>
<source>Put quotes around values</source>
<translation type="unfinished">Взять значения в кавычки</translation>
</message>
<message>
<location filename="logger.ui" line="50"/>
<source>Select all</source>
<translation type="unfinished">Выбрать всё</translation>
</message>
<message>
<location filename="logger.ui" line="57"/>
<source>Deselect all</source>
<translation type="unfinished">Отменить выбор всего</translation>
</message>
<message>
<location filename="logger.ui" line="77"/>
<source>Smart select</source>
<translation type="unfinished">Умный выбор</translation>
</message>
<message>
<location filename="logger.ui" line="84"/>
<source>Add custom variable</source>
<translation type="unfinished">Добавить свою переменную</translation>
</message>
<message>
<location filename="logger.ui" line="109"/>
<source>Variable</source>
<translation type="unfinished">Переменная</translation>
</message>
<message>
<location filename="logger.ui" line="114"/>
<source>Source item(s)</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="loop_operation.ui" line="32"/>
<source>TextLabel</source>
<translation type="unfinished">Надпись</translation>
</message>
<message>
<location filename="loop.ui" line="38"/>
<source>Item to run</source>
<translation type="unfinished">Составляющая</translation>
</message>
<message>
<location filename="loop.ui" line="45"/>
<source>PushButton</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="loop.ui" line="68"/>
<source>When running the experiment, do the following:</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="loop.ui" line="96"/>
<source>Add</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="loop.ui" line="109"/>
<source>Preview</source>
<translation type="unfinished"></translation>
</message>
</context>
<context>
<name>advanced_delay</name>
<message>
<location filename="translatables.py" line="15"/>
<source>Timing</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="translatables.py" line="16"/>
<source>Duration</source>
<translation type="unfinished">Длительность</translation>
</message>
<message>
<location filename="translatables.py" line="17"/>
<source>The average duration in milliseconds</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="translatables.py" line="21"/>
<source> ms</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="translatables.py" line="19"/>
<source>Jitter</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="translatables.py" line="20"/>
<source>The jitter of the actual duration in milliseconds (depends on Jitter mode)</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="translatables.py" line="22"/>
<source>Jitter mode</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="translatables.py" line="23"/>
<source>The mode for determining the actual duration (see Help)</source>
<translation type="unfinished"></translation>
</message>
</context>
<context>
<name>auto_example</name>
<message>
<location filename="translatables.py" line="289"/>
<source>Example plug-in.</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="translatables.py" line="290"/>
<source>Visual stimuli</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="translatables.py" line="291"/>
<source>Example checkbox</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="translatables.py" line="292"/>
<source>An example checkbox</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="translatables.py" line="293"/>
<source>Color</source>
<translation type="unfinished">Цвет</translation>
</message>
<message>
<location filename="translatables.py" line="294"/>
<source>An example color edit</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="translatables.py" line="295"/>
<source>Select option</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="translatables.py" line="296"/>
<source>An example combobox</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="translatables.py" line="297"/>
<source>Select file</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="translatables.py" line="298"/>
<source>An example filepool widget</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="translatables.py" line="299"/>
<source>Enter text</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="translatables.py" line="300"/>
<source>An example line_edit widget</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="translatables.py" line="301"/>
<source>Enter value</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="translatables.py" line="302"/>
<source>An example spinbox widget</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="translatables.py" line="303"/>
<source>approx. </source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="translatables.py" line="304"/>
<source> ms</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="translatables.py" line="305"/>
<source>Select value</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="translatables.py" line="306"/>
<source>An example slider widget</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="translatables.py" line="307"/>
<source>Some non-interactive text</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="translatables.py" line="308"/>
<source>Python editor</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="translatables.py" line="309"/>
<source>An example editor widget</source>
<translation type="unfinished"></translation>
</message>
</context>
<context>
<name>automatic_backup</name>
<message>
<location filename="translatables.py" line="226"/>
<source>Open backup folder</source>
<translation type="unfinished">Открыть папку с точками восстановления</translation>
</message>
<message>
<location filename="translatables.py" line="227"/>
<source>Periodically saves your experiment to a back-up folder.</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="translatables.py" line="225"/>
<source>Failed to save backup ...</source>
<translation type="unfinished">Не удалось сохранить точку восстановления...</translation>
</message>
</context>
<context>
<name>container_widget</name>
<message>
<location filename="general_properties.ui" line="14"/>
<source>Form</source>
<translation type="unfinished">Окно</translation>
</message>
<message>
<location filename="general_properties.ui" line="56"/>
<source><h3>Back-end</h3></source>
<translation type="unfinished">Движок</translation>
</message>
<message>
<location filename="general_properties.ui" line="94"/>
<source><h3>Resolution</h3></source>
<translation type="unfinished"><h3>Разрешение</h3></translation>
</message>
<message>
<location filename="general_properties.ui" line="119"/>
<source>The display resolution (width) in pixels</source>
<translation type="unfinished">Разрешение (ширина) в точках</translation>
</message>
<message>
<location filename="general_properties.ui" line="145"/>
<source>px</source>
<translation type="unfinished"> тчк</translation>
</message>
<message>
<location filename="general_properties.ui" line="135"/>
<source>x</source>
<translation type="unfinished">х</translation>
</message>
<message>
<location filename="general_properties.ui" line="142"/>
<source>The display resolution (height) in pixels</source>
<translation type="unfinished">Разрешение (высота) в точках</translation>
</message>
<message>
<location filename="general_properties.ui" line="161"/>
<source><h3>Colors</h3></source>
<translation type="unfinished"><h3>Цвета</h3></translation>
</message>
<message>
<location filename="general_properties.ui" line="189"/>
<source>Foreground</source>
<translation type="unfinished">Переднее поле</translation>
</message>
<message>
<location filename="general_properties.ui" line="196"/>
<source>Background</source>
<translation type="unfinished">Заднее поле</translation>
</message>
<message>
<location filename="general_properties.ui" line="212"/>
<source><small><i>Examples: 'white', '#FFFFFF'</i></small></source>
<translation type="unfinished"><small><i>Например: 'white', '#FFFFFF'</i></small></translation>
</message>
<message>
<location filename="general_properties.ui" line="228"/>
<source><h3>Font</h3></source>
<translation type="unfinished"><h3>Начертание</h3></translation>
</message>
<message>
<location filename="general_properties.ui" line="288"/>
<source><h3>Advanced</h3></source>
<translation type="unfinished"><h3>Расширенные настройки</h3></translation>
</message>
<message>
<location filename="general_properties.ui" line="319"/>
<source>Advanced settings for the selected back-end</source>
<translation type="unfinished">Дополнительные настройки для выбранного движка</translation>
</message>
<message>
<location filename="general_properties.ui" line="322"/>
<source>Back-end settings</source>
<translation type="unfinished">Свойства движка</translation>
</message>
<message>
<location filename="general_properties.ui" line="329"/>
<source>Edit the script for the entire experiment</source>
<translation type="unfinished">Изменить приказник всего опыта</translation>
</message>
<message>
<location filename="general_properties.ui" line="332"/>
<source>Script editor</source>
<translation type="unfinished">Правщик приказника</translation>
</message>
<message>
<location filename="general_properties.ui" line="288"/>
<source>Allows you to access experimental variables directly by name</source>
<translation type="obsolete">Позволяет пользоваться переменными, используя их имена</translation>
</message>
<message>
<location filename="general_properties.ui" line="291"/>
<source>Transparent variable management</source>
<translation type="obsolete">Прозрачное управление переменными</translation>
</message>
<message>
<location filename="general_properties.ui" line="275"/>
<source><html><head/><body><p><span style=" font-size:large; font-weight:600;">Miscellaneous</span></p></body></html></source>
<translation type="unfinished"><html><head/><body><p><span style=" font-size:large; font-weight:600;">Разное</span></p></body></html></translation>
</message>
<message>
<location filename="general_properties.ui" line="342"/>
<source>Enables support for bi-directional languages, such as Arabic and Hebrew</source>
<translation type="unfinished">Включает поддержку некоторых языков (арабский, иврит, и т.д.)</translation>
</message>
<message>
<location filename="general_properties.ui" line="345"/>
<source>Bi-directional-text support</source>
<translation type="unfinished">Поддержка письма в двух направлениях</translation>
</message>
<message>
<location filename="general_properties.ui" line="81"/>
<source><html><head/><body><p><a href="http://osdoc.cogsci.nl/back-ends/about"><span style="font-size:small;font-style:italic; text-decoration: underline; color:#0057ae;">Why is this important?</span></a></p></body></html></source>
<translation type="unfinished"><html><head/><body><p><a href="http://osdoc.cogsci.nl/back-ends/about"><span style="font-size:small;font-style:italic; text-decoration: underline; color:#0057ae;">Что это такое?</span></a></p></body></html></translation>
</message>
<message>
<location filename="general_properties.ui" line="352"/>
<source><html><head/><body><p><span style=" font-size:small; font-style:italic;">Warning: python-bidi is not available</span></p></body></html></source>
<translation type="unfinished"></translation>
</message>
</context>
<context>
<name>dock_manager</name>
<message>
<location filename="translatables.py" line="392"/>
<source>Lock dock widgets</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="translatables.py" line="393"/>
<source>Manage the dock widgets for the debug window, file pool, etc.</source>
<translation type="unfinished"></translation>
</message>
</context>
<context>
<name>example</name>
<message>
<location filename="translatables.py" line="409"/>
<source>Example extension</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="translatables.py" line="410"/>
<source>An example extenstion</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="translatables.py" line="411"/>
<source>Some tooltip</source>
<translation type="unfinished"></translation>
</message>
</context>
<context>
<name>fixation_dot</name>
<message>
<location filename="translatables.py" line="238"/>
<source>Visual stimuli</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="translatables.py" line="239"/>
<source>Syle</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="translatables.py" line="240"/>
<source>Style of the fixation dot</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="translatables.py" line="241"/>
<source>Pen width</source>
<translation type="unfinished">Толщина ручки</translation>
</message>
<message>
<location filename="translatables.py" line="242"/>
<source>Specifies the pen width, or line thickness</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="translatables.py" line="243"/>
<source>px</source>
<translation type="unfinished"> тчк</translation>
</message>
<message>
<location filename="translatables.py" line="244"/>
<source>Duration</source>
<translation type="unfinished">Длительность</translation>
</message>
<message>
<location filename="translatables.py" line="245"/>
<source>Expecting a value in milliseconds, 'keypress' or 'mouseclick'</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="translatables.py" line="246"/>
<source>Foreground color</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="translatables.py" line="249"/>
<source>Expecting a colorname (e.g., 'blue') or an HTML color (e.g., '#0000FF')</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="translatables.py" line="248"/>
<source>Background color</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="translatables.py" line="250"/>
<source>X coordinate</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="translatables.py" line="251"/>
<source>X-coordinate of the fixation dot (e.g., 0)</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="translatables.py" line="252"/>
<source>Y coordinate</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="translatables.py" line="253"/>
<source>Y-coordinate of the fixation dot (e.g., 0)</source>
<translation type="unfinished"></translation>
</message>
</context>
<context>
<name>font_widget</name>
<message>
<location filename="font_widget.ui" line="14"/>
<source>Form</source>
<translation>Окно</translation>
</message>
<message>
<location filename="font_widget.ui" line="32"/>
<source>Font family</source>
<translation>Семейство начертаний</translation>
</message>
<message>
<location filename="font_widget.ui" line="34"/>
<source>mono</source>
<translation type="obsolete">Одиночное</translation>
</message>
<message>
<location filename="font_widget.ui" line="39"/>
<source>sans</source>
<translation type="obsolete">Санс</translation>
</message>
<message>
<location filename="font_widget.ui" line="44"/>
<source>serif</source>
<translation type="obsolete">Шериф</translation>
</message>
<message>
<location filename="font_widget.ui" line="75"/>
<source>other ...</source>
<translation>Другое...</translation>
</message>
<message>
<location filename="font_widget.ui" line="92"/>
<source>Font size</source>
<translation>Размер начертания</translation>
</message>
<message>
<location filename="font_widget.ui" line="99"/>
<source> pt</source>
<translation type="obsolete"> </translation>
</message>
<message>
<location filename="font_widget.ui" line="132"/>
<source>Italic</source>
<translation>Наклонное</translation>
</message>
<message>
<location filename="font_widget.ui" line="145"/>
<source>Bold</source>
<translation>Жирное</translation>
</message>
<message>
<location filename="font_widget.ui" line="167"/>
<source>Example</source>
<translation>Пример</translation>
</message>
<message>
<location filename="font_widget.ui" line="49"/>
<source>arabic</source>
<translation type="obsolete">Арабская азбука</translation>
</message>
<message>
<location filename="font_widget.ui" line="54"/>
<source>chinese-japanese-korean</source>
<translation type="obsolete">Китайско-японско-корейская азбука</translation>
</message>
<message>
<location filename="font_widget.ui" line="59"/>
<source>hebrew</source>
<translation type="obsolete">Иврит</translation>
</message>
<message>
<location filename="font_widget.ui" line="64"/>
<source>hindi</source>
<translation type="obsolete">хинди</translation>
</message>
<message>
<location filename="font_widget.ui" line="99"/>
<source> px</source>
<translation type="unfinished"></translation>
</message>
</context>
<context>
<name>form_base</name>
<message>
<location filename="translatables.py" line="68"/>
<source>Form</source>
<translation type="unfinished">Окно</translation>
</message>
<message>
<location filename="translatables.py" line="69"/>
<source>Edit the script to modify the form</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="translatables.py" line="66"/>
<source>Widget column and row should be numeric</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="translatables.py" line="67"/>
<source>cols, rows, and margins should be numeric values separated by a semi-colon</source>
<translation type="unfinished"></translation>
</message>
</context>
<context>
<name>form_consent</name>
<message>
<location filename="translatables.py" line="317"/>
<source>Form</source>
<translation type="unfinished">Окно</translation>
</message>
<message>
<location filename="translatables.py" line="318"/>
<source>Form title</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="translatables.py" line="319"/>
<source>Title to appear above the form text</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="translatables.py" line="320"/>
<source>Checkbox text</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="translatables.py" line="321"/>
<source>Text for the checkbox</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="translatables.py" line="322"/>
<source>Accept-button text</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="translatables.py" line="323"/>
<source>Text for the accept button</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="translatables.py" line="324"/>
<source>Decline-button text</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="translatables.py" line="325"/>
<source>Text for the decline button</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="translatables.py" line="326"/>
<source>Message on decline</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="translatables.py" line="327"/>
<source>A message shown when the participant declines</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="translatables.py" line="328"/>
<source>Consent form text</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="translatables.py" line="329"/>
<source>Text to display in the form body</source>
<translation type="unfinished"></translation>
</message>
</context>
<context>
<name>form_multiple_choice</name>
<message>
<location filename="translatables.py" line="256"/>
<source>Form</source>
<translation type="unfinished">Окно</translation>
</message>
<message>
<location filename="translatables.py" line="258"/>
<source>Form title</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="translatables.py" line="260"/>
<source>Response variable</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="translatables.py" line="262"/>
<source>Allow multiple options to be selected</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="translatables.py" line="264"/>
<source>Advance immediately to the next item once a selection has been made</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="translatables.py" line="265"/>
<source>Button text</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="translatables.py" line="266"/>
<source>Text for the button to advance to the next item</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="translatables.py" line="268"/>
<source>Your question</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="translatables.py" line="269"/>
<source>Response options (different options on different lines)</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="translatables.py" line="270"/>
<source>Response options</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="translatables.py" line="271"/>
<source>margins should be numeric values separated by a semi-colon</source>
<translation type="unfinished"></translation>
</message>
</context>
<context>
<name>form_sketchpad</name>
<message>
<location filename="sketchpad.ui" line="14"/>
<source>Form</source>
<translation type="unfinished">Окно</translation>
</message>
<message>
<location filename="sketchpad.ui" line="38"/>
<source>Duration</source>
<translation type="unfinished">Длительность</translation>
</message>
<message>
<location filename="sketchpad.ui" line="51"/>
<source>A numeric value (duration in milliseconds), "keypress", or "mouseclick"</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="sketchpad.ui" line="110"/>
<source>Color</source>
<translation type="unfinished">Цвет</translation>
</message>
<message>
<location filename="sketchpad.ui" line="471"/>
<source> px</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="sketchpad.ui" line="139"/>
<source>Penwidth </source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="sketchpad.ui" line="171"/>
<source>Size of the arrowhead</source>
<translation type="unfinished">Размер стрелки</translation>
</message>
<message>
<location filename="sketchpad.ui" line="177"/>
<source>Arrowhead </source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="sketchpad.ui" line="212"/>
<source>Image scaling factor</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="sketchpad.ui" line="215"/>
<source>Scale </source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="sketchpad.ui" line="387"/>
<source> x</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="sketchpad.ui" line="259"/>
<source>Check to draw filled objects</source>
<translation type="unfinished">Заполнять нарисованные тела</translation>
</message>
<message>
<location filename="sketchpad.ui" line="262"/>
<source>Fill</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="sketchpad.ui" line="288"/>
<source>Center the object</source>
<translation type="unfinished">Поместить в середину</translation>
</message>
<message>
<location filename="sketchpad.ui" line="291"/>
<source>Center</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="sketchpad.ui" line="320"/>
<source>Show if</source>
<translation type="unfinished">Показать, если</translation>
</message>
<message>
<location filename="sketchpad.ui" line="374"/>
<source>0,0</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="sketchpad.ui" line="384"/>
<source>Zoom factor</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="sketchpad.ui" line="426"/>
<source>Parse a subset of HTML tags</source>
<translation type="unfinished">Проверить HTML</translation>
</message>
<message>
<location filename="sketchpad.ui" line="429"/>
<source>HTML</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="sketchpad.ui" line="455"/>
<source>Check to display the grid and enable snap-to-grid</source>
<translation type="unfinished">Показывает или прячет решётку на полотне</translation>
</message>
<message>
<location filename="sketchpad.ui" line="458"/>
<source>Grid</source>
<translation type="unfinished">Решётка</translation>
</message>
<message>
<location filename="sketchpad.ui" line="468"/>
<source>Grid size</source>
<translation type="unfinished">Размерность решётки</translation>
</message>
<message>
<location filename="sketchpad.ui" line="511"/>
<source>Select and move elements</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="sketchpad.ui" line="77"/>
<source>Reset feedback variables</source>
<translation type="unfinished"></translation>
</message>
</context>
<context>
<name>form_text_display</name>
<message>
<location filename="translatables.py" line="274"/>
<source>Form</source>
<translation type="unfinished">Окно</translation>
</message>
<message>
<location filename="translatables.py" line="275"/>
<source>Form title</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="translatables.py" line="276"/>
<source>Title to appear above the form text</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="translatables.py" line="277"/>
<source>Ok-button text</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="translatables.py" line="278"/>
<source>Text for the Ok button</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="translatables.py" line="279"/>
<source>Main form text</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="translatables.py" line="280"/>
<source>Text to display in the form body</source>
<translation type="unfinished"></translation>
</message>
</context>
<context>
<name>form_text_input</name>
<message>
<location filename="translatables.py" line="365"/>
<source>Form</source>
<translation type="unfinished">Окно</translation>
</message>
<message>
<location filename="translatables.py" line="366"/>
<source>Form title</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="translatables.py" line="367"/>
<source>Title to appear above the form text</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="translatables.py" line="368"/>
<source>Response variable</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="translatables.py" line="369"/>
<source>The experimental variable to save the response in</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="translatables.py" line="370"/>
<source>Your question</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="translatables.py" line="371"/>
<source>A question text</source>
<translation type="unfinished"></translation>
</message>
</context>
<context>
<name>gabor_dialog</name>
<message>
<location filename="gabor_settings.ui" line="58"/>
<source>Insert Gabor patch</source>
<translation>Добавить рисунок Габора</translation>
</message>
<message>
<location filename="gabor_settings.ui" line="82"/>
<source>Orientation<br /><i>in degrees (0 .. 360)</i></source>
<translation>Положение<br /><i>в ступенях (0 .. 360)</i></translation>
</message>
<message>
<location filename="gabor_dialog.ui" line="89"/>
<source>deg</source>
<translation type="obsolete"> ступеней</translation>
</message>
<message>
<location filename="gabor_settings.ui" line="99"/>
<source>Size<br /><i>in pixels</i></source>
<translation>Размер<br /><i>в точках</i></translation>
</message>
<message>
<location filename="gabor_dialog.ui" line="160"/>
<source>px</source>
<translation type="obsolete"> тчк</translation>
</message>
<message>
<location filename="gabor_settings.ui" line="122"/>
<source>Envelope</source>
<translation>Огибающая</translation>
</message>
<message>
<location filename="gabor_settings.ui" line="130"/>
<source>gaussian</source>
<translation>гауссова</translation>
</message>
<message>
<location filename="gabor_settings.ui" line="135"/>
<source>linear</source>
<translation>прямая</translation>
</message>
<message>
<location filename="gabor_settings.ui" line="140"/>
<source>circular (sharp edge)</source>
<translation>круговая</translation>
</message>
<message>
<location filename="gabor_dialog.ui" line="145"/>
<source>rectangle (no envelope)</source>
<translation type="obsolete">прямоугольная</translation>
</message>
<message>
<location filename="gabor_settings.ui" line="153"/>
<source>Standard deviation<br /><i>in pixels, only applies to Gaussian envelope</i></source>
<translation>Среднее отклонение<br /><i> в точках (только для гауссовой огибающей)</i></translation>
</message>
<message>
<location filename="gabor_settings.ui" line="173"/>
<source>Frequency<br /><i>in cycles/ px</i></source>
<translation>Частота<br /><i> в кругах или точках</i></translation>
</message>
<message>
<location filename="gabor_settings.ui" line="193"/>
<source>Phase<br /><i>in cycles (0 .. 1)</i></source>
<translation>Повторение<br /><i> в кругах (0..1)</i></translation>
</message>
<message>
<location filename="gabor_settings.ui" line="210"/>
<source>Color 1<br /><i>e.g., 'white' or '#FFFFFF'</i></source>
<translation>Цвет 1<br /><i>например,"'white" или "#FFFFFF"</i></translation>
</message>
<message>
<location filename="gabor_settings.ui" line="224"/>
<source>Color 1<br /><i>e.g., 'black' or '#000000'</i></source>
<translation>Цвет 1<br /><i>например,"'black" или "#000000"</i></translation>
</message>
<message>
<location filename="gabor_settings.ui" line="243"/>
<source>Background color *</source>
<translation>Цвет заднего поля *</translation>
</message>
<message>
<location filename="gabor_settings.ui" line="251"/>
<source>Color average</source>
<translation>Усреднённый цвет</translation>
</message>
<message>
<location filename="gabor_settings.ui" line="256"/>
<source>Color 2</source>
<translation>Цвет 2</translation>
</message>
<message>
<location filename="gabor_settings.ui" line="276"/>
<source>* Has no effect in psycho back-end</source>
<translation>* на движке "психо" не работает</translation>
</message>
<message encoding="UTF-8">
<location filename="gabor_settings.ui" line="89"/>
<source> °</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="gabor_settings.ui" line="160"/>
<source> px</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="gabor_settings.ui" line="145"/>
<source>rectangular (no envelope)</source>
<translation type="unfinished"></translation>
</message>
</context>
<context>
<name>general_widget</name>
<message>
<location filename="general_widget.ui" line="14"/>
<source>Form</source>
<translation type="obsolete">Окно</translation>
</message>
<message>
<location filename="general_widget.ui" line="85"/>
<source>The display resolution (width) in pixels</source>
<translation type="obsolete">Разрешение (ширина) в точках</translation>
</message>
<message>
<location filename="general_widget.ui" line="111"/>
<source>px</source>
<translation type="obsolete"> тчк</translation>
</message>
<message>
<location filename="general_widget.ui" line="108"/>
<source>The display resolution (height) in pixels</source>
<translation type="obsolete">Разрешение (высота) в точках</translation>
</message>
<message>
<location filename="general_widget.ui" line="56"/>
<source><h3>Back-end</h3></source>
<translation type="obsolete">Движок</translation>
</message>
<message>
<location filename="general_widget.ui" line="63"/>
<source><h3>Resolution</h3></source>
<translation type="obsolete"><h3>Разрешение</h3></translation>
</message>
<message>
<location filename="general_widget.ui" line="101"/>
<source>x</source>
<translation type="obsolete">х</translation>
</message>
<message>
<location filename="general_widget.ui" line="127"/>
<source><h3>Colors</h3></source>
<translation type="obsolete"><h3>Цвета</h3></translation>
</message>
<message>
<location filename="general_widget.ui" line="152"/>
<source>Foreground</source>
<translation type="obsolete">Переднее поле</translation>
</message>
<message>
<location filename="general_widget.ui" line="159"/>
<source>Background</source>
<translation type="obsolete">Заднее поле</translation>
</message>
<message>
<location filename="general_widget.ui" line="175"/>
<source><small><i>Examples: 'white', '#FFFFFF'</i></small></source>
<translation type="obsolete"><small><i>Например: 'white', '#FFFFFF'</i></small></translation>
</message>
<message>
<location filename="general_widget.ui" line="191"/>
<source><h3>Font</h3></source>
<translation type="obsolete"><h3>Начертание</h3></translation>
</message>
<message>
<location filename="general_widget.ui" line="235"/>
<source><h3>Advanced</h3></source>
<translation type="obsolete"><h3>Расширенные настройки</h3></translation>
</message>
<message>
<location filename="general_widget.ui" line="266"/>
<source>Back-end settings</source>
<translation type="obsolete">Свойства движка</translation>
</message>
<message>
<location filename="general_widget.ui" line="276"/>
<source>Script editor</source>
<translation type="obsolete">Правщик приказника</translation>
</message>
<message>
<location filename="general_widget.ui" line="289"/>
<source>Transparent variable management</source>
<translation type="obsolete">Прозрачное управление переменными</translation>
</message>
<message>
<location filename="general_widget.ui" line="263"/>
<source>Advanced settings for the selected back-end</source>
<translation type="obsolete">Дополнительные настройки для выбранного движка</translation>
</message>
<message>
<location filename="general_widget.ui" line="273"/>
<source>Edit the script for the entire experiment</source>
<translation type="obsolete">Изменить приказник всего опыта</translation>
</message>
<message>
<location filename="general_widget.ui" line="286"/>
<source>Allows you to access experimental variables directly by name</source>
<translation type="obsolete">Позволяет пользоваться переменными, используя их имена</translation>
</message>
<message>
<location filename="general_widget.ui" line="296"/>
<source><html><head/><body><p><span style=" font-size:large; font-weight:600;">Miscellaneous</span></p></body></html></source>
<translation type="obsolete"><html><head/><body><p><span style=" font-size:large; font-weight:600;">Разное</span></p></body></html></translation>
</message>
<message>
<location filename="general_widget.ui" line="306"/>
<source>Enables support for bi-directional languages, such as Arabic and Hebrew</source>
<translation type="obsolete">Включает поддержку некоторых языков (арабский, иврит, и т.д.)</translation>
</message>
<message>
<location filename="general_widget.ui" line="309"/>
<source>Bi-directional-text support</source>
<translation type="obsolete">Поддержка письма в двух направлениях</translation>
</message>
<message>
<location filename="general_widget.ui" line="331"/>
<source><html><head/><body><p><a href="http://osdoc.cogsci.nl/back-ends/about"><span style="font-size:small;font-style:italic; text-decoration: underline; color:#0057ae;">Why is this important?</span></a></p></body></html></source>
<translation type="obsolete"><html><head/><body><p><a href="http://osdoc.cogsci.nl/back-ends/about"><span style="font-size:small;font-style:italic; text-decoration: underline; color:#0057ae;">Что это такое?</span></a></p></body></html></translation>
</message>
</context>
<context>
<name>help</name>
<message>
<location filename="translatables.py" line="8"/>
<source>Help</source>
<translation type="unfinished">Помощь</translation>
</message>
<message>
<location filename="translatables.py" line="9"/>
<source>Offline help</source>
<translation type="unfinished">Справочник без подключения к Сети</translation>
</message>
<message>
<location filename="translatables.py" line="10"/>
<source>Online help</source>
<translation type="unfinished">Справочник в Сети</translation>
</message>
<message>
<location filename="translatables.py" line="12"/>
<source>Adds a Help menu.</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="translatables.py" line="11"/>
<source>PsychoPy API</source>
<translation type="unfinished"></translation>
</message>
</context>
<context>
<name>joystick</name>
<message>
<location filename="translatables.py" line="396"/>
<source>Response collection</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="translatables.py" line="397"/>
<source>Dummy mode (use keyboard instead of joystick)</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="translatables.py" line="398"/>
<source>Enable dummy mode to test the experiment using a keyboard</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="translatables.py" line="399"/>
<source>Device nr.</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="translatables.py" line="400"/>
<source>Identifies the joystick, in case there are multiple joysticks</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="translatables.py" line="401"/>
<source>Correct response</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="translatables.py" line="404"/>
<source>Expecting a comma-separated list of numbers between 1 and the number of joybuttons</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="translatables.py" line="403"/>
<source>Allowed responses</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="translatables.py" line="405"/>
<source>Timeout</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="translatables.py" line="406"/>
<source>Expecting a value in milliseconds of 'infinite'</source>
<translation type="unfinished"></translation>
</message>
</context>
<context>
<name>loop_widget</name>
<message>
<location filename="loop_widget.ui" line="14"/>
<source>Form</source>
<translation>Окно</translation>
</message>
<message>
<location filename="loop_widget.ui" line="32"/>
<source>Add variable</source>
<translation>Добавить переменную</translation>
</message>
<message>
<location filename="loop_widget.ui" line="45"/>
<source>Rename variable</source>
<translation>Переименовать переменную</translation>
</message>
<message>
<location filename="loop_widget.ui" line="58"/>
<source>Remove variable</source>
<translation>Удалить переменную</translation>
</message>
<message>
<location filename="loop_widget.ui" line="91"/>
<source>Variable wizard</source>
<translation>Доска переменных</translation>
</message>
<message>
<location filename="loop_widget.ui" line="119"/>
<source>Show advanced options</source>
<translation>Показать расширенные настройки</translation>
</message>
<message>
<location filename="loop_widget.ui" line="132"/>
<source> cycle(s)</source>
<translation> круг(ов)</translation>
</message>
<message>
<location filename="loop_widget.ui" line="135"/>
<source>first </source>
<translation>первый(е) </translation>
</message>
<message>
<location filename="loop_widget.ui" line="145"/>
<source>At loop start, skip the</source>
<translation>При запуске пропустить</translation>
</message>
<message>
<location filename="loop_widget.ui" line="152"/>
<source>Break if</source>
<translation>Прервать, если</translation>
</message>
<message>
<location filename="loop_widget.ui" line="162"/>
<source>Run skipped cycles at end of loop (offset mode)</source>
<translation>Запустить пропущенные круги в конце кольца</translation>
</message>
<message>
<location filename="loop_widget.ui" line="181"/>
<source>Item to run</source>
<translation>Составляющая</translation>
</message>
<message>
<location filename="loop_widget.ui" line="191"/>
<source>Cycles</source>
<translation>Круги</translation>
</message>
<message>
<location filename="loop_widget.ui" line="212"/>
<source>Order</source>
<translation>Порядок</translation>
</message>
<message>
<location filename="loop_widget.ui" line="226"/>
<source>Repeat</source>
<translation>Повторить</translation>
</message>
<message>
<location filename="loop_widget.ui" line="233"/>
<source>each cycle </source>
<translation>каждый круг</translation>
</message>
<message>
<location filename="loop_widget.ui" line="236"/>
<source> time(s)</source>
<translation> раз</translation>
</message>
<message>
<location filename="loop_widget.ui" line="267"/>
<source>TextLabel</source>
<translation>Надпись</translation>
</message>
<message>
<location filename="loop_widget.ui" line="274"/>
<source>Automatic summary</source>
<translation>Заключение</translation>
</message>
<message>
<location filename="loop_widget.ui" line="71"/>
<source>Apply weights</source>
<translation>Применить веса</translation>
</message>
</context>
<context>
<name>loop_wizard_dialog</name>
<message>
<location filename="loop_wizard_dialog.ui" line="14"/>
<source>Loop Variable Wizard</source>
<translation>Доска колец</translation>
</message>
<message>
<location filename="loop_wizard_dialog.ui" line="42"/>
<source><b>Loop variable wizard</b><br /><small>Enter the names of the variables (factors) in the first row in the table below. Under the variable names, enter the levels of the variables.<br /><i>Note: This will overwrite the current loop table</i></small></source>
<translation><b>Доска колец</b><br /><small>Введите имена переменных в первом ряду.Под ними введите их уровни.<br /><i>Имейте в виду, что это перепишет текущие значения</i></small></translation>
</message>
<message>
<location filename="loop_wizard_dialog.ui" line="61"/>
<source>Show example</source>
<translation>Показать пример</translation>
</message>
<message>
<location filename="loop_wizard_dialog.ui" line="152"/>
<source>New Row</source>
<translation>Новая строка</translation>
</message>
<message>
<location filename="loop_wizard_dialog.ui" line="202"/>
<source>New Column</source>
<translation>Новый столбец</translation>
</message>
<message>
<location filename="loop_wizard_dialog.ui" line="207"/>
<source>soa</source>
<translation></translation>
</message>
<message>
<location filename="loop_wizard_dialog.ui" line="212"/>
<source>target</source>
<translation></translation>
</message>
<message>
<location filename="loop_wizard_dialog.ui" line="217"/>
<source>cue</source>
<translation></translation>
</message>
<message>
<location filename="loop_wizard_dialog.ui" line="222"/>
<source>0</source>
<translation></translation>
</message>
<message>
<location filename="loop_wizard_dialog.ui" line="232"/>
<source>left</source>
<translation></translation>
</message>
<message>
<location filename="loop_wizard_dialog.ui" line="237"/>
<source>100</source>
<translation></translation>
</message>
<message>
<location filename="loop_wizard_dialog.ui" line="247"/>
<source>right</source>
<translation></translation>
</message>
<message>
<location filename="loop_wizard_dialog.ui" line="252"/>
<source>500</source>
<translation>500</translation>
</message>
<message>
<location filename="loop_wizard_dialog.ui" line="257"/>
<source>1000</source>
<translation>1000</translation>
</message>
</context>
<context>
<name>new_loop_sequence_dialog</name>
<message>
<location filename="new_loop_sequence.ui" line="14"/>
<source>Dialog</source>
<translation>Окно</translation>
</message>
<message>
<location filename="new_loop_sequence.ui" line="42"/>
<source>Explanation
</source>
<translation>Объяснение</translation>
</message>
<message>
<location filename="new_loop_sequence.ui" line="78"/>
<source>Create new item to use</source>
<translation>Создать новый</translation>
</message>
<message>
<location filename="new_loop_sequence.ui" line="99"/>
<source>Create</source>
<translation>Создать</translation>
</message>
<message>
<location filename="new_loop_sequence.ui" line="119"/>
<source>Select existing item to use</source>
<translation>Выбрать из существующих</translation>
</message>
<message>
<location filename="new_loop_sequence.ui" line="140"/>
<source>Select</source>
<translation>Выбрать</translation>
</message>
<message>
<location filename="new_loop_sequence.ui" line="182"/>
<source>Cancel</source>
<translation>Отменить</translation>
</message>
</context>
<context>
<name>noise_patch_dialog</name>
<message>
<location filename="noise_settings.ui" line="58"/>
<source>Insert noise patch</source>
<translation>Вставить шум</translation>
</message>
<message>
<location filename="noise_patch_dialog.ui" line="136"/>
<source>px</source>
<translation type="obsolete"> тчк</translation>
</message>
<message>
<location filename="noise_settings.ui" line="98"/>
<source>Envelope</source>
<translation>Огибающая</translation>
</message>
<message>
<location filename="noise_settings.ui" line="106"/>
<source>gaussian</source>
<translation>гауссова</translation>
</message>
<message>
<location filename="noise_settings.ui" line="111"/>
<source>linear</source>
<translation>прямая</translation>
</message>
<message>
<location filename="noise_settings.ui" line="116"/>
<source>circular (sharp edge)</source>
<translation>круговая</translation>
</message>
<message>
<location filename="noise_settings.ui" line="121"/>
<source>rectangle (no envelope)</source>
<translation>прямоугольная</translation>
</message>
<message>
<location filename="noise_settings.ui" line="129"/>
<source>Standard deviation<br /><i>in pixels, only applies to Gaussian envelope</i></source>
<translation>Среднее отклонение<br /><i> в точках (только для гауссовой огибающей)</i></translation>
</message>
<message>
<location filename="noise_settings.ui" line="149"/>
<source>Color 1<br /><i>e.g., 'white' or '#FFFFFF'</i></source>
<translation>Цвет 1<br /><i>например,"'white" или "#FFFFFF"</i></translation>
</message>
<message>
<location filename="noise_settings.ui" line="163"/>
<source>Color 2<br /><i>e.g., 'black' or '#000000'</i></source>
<translation>Цвет 1<br /><i>например,"'black" или "#000000"</i></translation>
</message>
<message>
<location filename="noise_settings.ui" line="182"/>
<source>Background color *</source>
<translation>Цвет заднего поля *</translation>
</message>
<message>
<location filename="noise_settings.ui" line="190"/>
<source>Color average</source>
<translation>Усреднённый цвет</translation>
</message>
<message>
<location filename="noise_settings.ui" line="195"/>
<source>Color 2</source>
<translation>Цвет 2</translation>
</message>
<message>
<location filename="noise_settings.ui" line="203"/>
<source>Size<br /><i>in pixels</i></source>
<translation>Размер<br /><i>в точках</i></translation>
</message>
<message>
<location filename="noise_settings.ui" line="222"/>
<source>* Has no effect in psycho back-end</source>
<translation>Не работает на движке "психо"</translation>
</message>
<message>
<location filename="noise_settings.ui" line="136"/>
<source> px</source>
<translation type="unfinished"></translation>
</message>
</context>
<context>
<name>notepad</name>
<message>
<location filename="translatables.py" line="312"/>
<source>Miscellaneous</source>
<translation type="unfinished">Разное</translation>
</message>
<message>
<location filename="translatables.py" line="313"/>
<source>Note</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="translatables.py" line="314"/>
<source>Type your note here</source>
<translation type="unfinished"></translation>
</message>
</context>
<context>
<name>notification_dialog</name>
<message>
<location filename="notification_dialog.ui" line="62"/>
<source>OpenSesame says ...</source>
<translation>"Сезам, откройся" сообщает...</translation>
</message>
</context>
<context>
<name>opensesame_mainwindow</name>
<message>
<location filename="main_window.ui" line="14"/>
<source>OpenSesame</source>
<translation>Сезам, откройся</translation>
</message>
<message>
<location filename="main_window.ui" line="60"/>
<source>File</source>
<translation>Опыт</translation>
</message>
<message>
<location filename="main_window.ui" line="64"/>
<source>Recent files</source>
<translation>Недавние записи</translation>
</message>
<message>
<location filename="main_window.ui" line="83"/>
<source>Run</source>
<translation>Запустить</translation>
</message>
<message>
<location filename="opensesame.ui" line="93"/>
<source>Items</source>
<translation type="obsolete">Составляющие</translation>
</message>
<message>
<location filename="main_window.ui" line="93"/>
<source>View</source>
<translation>Вид</translation>
</message>
<message>
<location filename="main_window.ui" line="107"/>
<source>Tools</source>
<translation>Орудия</translation>
</message>
<message>
<location filename="main_window.ui" line="128"/>
<source>Overview</source>
<translation>Обзорный лист</translation>
</message>
<message>
<location filename="main_window.ui" line="145"/>
<source>Name</source>
<translation>Имя</translation>
</message>
<message>
<location filename="main_window.ui" line="158"/>
<source>Variable inspector</source>
<translation>Проверить переменные</translation>
</message>
<message>
<location filename="opensesame.ui" line="265"/>
<source>Enter a filter</source>
<translation type="obsolete">Включить отсеиватель</translation>
</message>
<message>
<location filename="opensesame.ui" line="272"/>
<source>Clear filter</source>
<translation type="obsolete">Отменить отсеиватель</translation>
</message>
<message>
<location filename="main_window.ui" line="227"/>
<source>Help</source>
<translation>Помощь</translation>
</message>
<message>
<location filename="opensesame.ui" line="352"/>
<source>Variable</source>
<translation type="obsolete">Переменная</translation>
</message>
<message>
<location filename="opensesame.ui" line="357"/>
<source>Value</source>
<translation type="obsolete">Значение</translation>
</message>
<message>
<location filename="opensesame.ui" line="362"/>
<source>In item</source>
<translation type="obsolete">В составляющей</translation>
</message>
<message>
<location filename="main_window.ui" line="175"/>
<source>File pool</source>
<translation>Склад записей</translation>
</message>
<message>
<location filename="main_window.ui" line="189"/>
<source>Debug window</source>
<translation>Окно отладки</translation>
</message>
<message>
<location filename="main_window.ui" line="250"/>
<source>Clear debug window</source>
<translation>Очистить окно отладки</translation>
</message>
<message>
<location filename="main_window.ui" line="291"/>
<source>Main toolbar</source>
<translation>Доска орудий</translation>
</message>
<message>
<location filename="main_window.ui" line="329"/>
<source>Toolbar items</source>
<translation>Приборная доска</translation>
</message>
<message>
<location filename="main_window.ui" line="344"/>
<source>Open</source>
<translation>Открыть</translation>
</message>
<message>
<location filename="main_window.ui" line="347"/>
<source>Open (Ctrl+0)</source>
<translation>Открыть (Ctrl+0)</translation>
</message>
<message>
<location filename="main_window.ui" line="350"/>
<source>Ctrl+O</source>
<translation>Ctrl+O</translation>
</message>
<message>
<location filename="main_window.ui" line="359"/>
<source>Save</source>
<translation>Сохранить</translation>
</message>
<message>
<location filename="main_window.ui" line="362"/>
<source>Save (Control+S)</source>
<translation>Сохранить (Control+S)</translation>
</message>
<message>
<location filename="main_window.ui" line="365"/>
<source>Ctrl+S</source>
<translation>Ctrl+S</translation>
</message>
<message>
<location filename="main_window.ui" line="374"/>
<source>Save as</source>
<translation>Сохранить как...</translation>
</message>
<message>
<location filename="main_window.ui" line="377"/>
<source>Save as (Control+Shift+S)</source>
<translation>Сохранить как... (Control+Shift+S)</translation>
</message>
<message>
<location filename="main_window.ui" line="380"/>
<source>Ctrl+Shift+S</source>
<translation>Ctrl+Shift+S</translation>
</message>
<message>
<location filename="main_window.ui" line="389"/>
<source>Quit</source>
<translation>Выйти</translation>
</message>
<message>
<location filename="main_window.ui" line="392"/>
<source>Quit (Alt+F4)</source>
<translation>Выйти (Alt+F4)</translation>
</message>
<message>
<location filename="main_window.ui" line="397"/>
<source>Run fullscreen</source>
<translation>Запустить на всё полотно</translation>
</message>
<message>
<location filename="main_window.ui" line="400"/>
<source>Run fullscreen (Control+R)</source>
<translation>На всё полотно (Control+R)</translation>
</message>
<message>
<location filename="main_window.ui" line="403"/>
<source>Ctrl+R</source>
<translation>Ctrl+R</translation>
</message>
<message>
<location filename="main_window.ui" line="412"/>
<source>New</source>
<translation>Новый</translation>
</message>
<message>
<location filename="main_window.ui" line="415"/>
<source>New (Control+N)</source>
<translation>Новый (Control+N)</translation>
</message>
<message>
<location filename="main_window.ui" line="418"/>
<source>Ctrl+N</source>
<translation>Ctrl+N</translation>
</message>
<message>
<location filename="main_window.ui" line="427"/>
<source>Add sequence</source>
<translation>Добавить последовательность</translation>
</message>
<message>
<location filename="main_window.ui" line="436"/>
<source>Add sketchpad</source>
<translation>Добавить полотно</translation>
</message>
<message>
<location filename="main_window.ui" line="445"/>
<source>Add keyboard response</source>
<translation>Добавить ответ ключницей</translation>
</message>
<message>
<location filename="main_window.ui" line="454"/>
<source>Add logger</source>
<translation type="unfinished">Добавить сборщик данных</translation>
</message>
<message>
<location filename="main_window.ui" line="463"/>
<source>Add loop</source>
<translation>Добавить кольцо</translation>
</message>
<message>
<location filename="main_window.ui" line="472"/>
<source>Add feedback</source>
<translation>Добавить обратную связь</translation>
</message>
<message>
<location filename="main_window.ui" line="481"/>
<source>Add inline script</source>
<translation>Добавить приказник</translation>
</message>
<message>
<location filename="main_window.ui" line="490"/>
<source>Close all tabs</source>
<translation>Закрыть все вкладки</translation>
</message>
<message>
<location filename="main_window.ui" line="502"/>
<source>Close other tabs</source>
<translation>Закрыть другие вкладки</translation>
</message>
<message>
<location filename="main_window.ui" line="505"/>
<source>Close other tabs (Control+T)</source>
<translation>Закрыть другие вкладки (Control+T)</translation>
</message>
<message>
<location filename="main_window.ui" line="508"/>
<source>Ctrl+T</source>
<translation>Ctrl+T</translation>
</message>
<message>
<location filename="main_window.ui" line="526"/>
<source>About</source>
<translation>О нас</translation>
</message>
<message>
<location filename="main_window.ui" line="535"/>
<source>Add mouse response</source>
<translation>Добавить ответ мышкой</translation>
</message>
<message>
<location filename="main_window.ui" line="540"/>
<source>Run in window</source>
<translation>Открыть в окне</translation>
</message>
<message>
<location filename="main_window.ui" line="543"/>
<source>Run in window (Control+W)</source>
<translation>Открыть в окне (Ctrl+W)</translation>
</message>
<message>
<location filename="main_window.ui" line="546"/>
<source>Ctrl+W</source>
<translation>Ctrl+W</translation>
</message>
<message>
<location filename="main_window.ui" line="555"/>
<source>Check for updates</source>
<translation>Проверить обновления</translation>
</message>
<message>
<location filename="main_window.ui" line="567"/>
<source>Show variable inspector</source>
<translation type="unfinished">Показать проверщик переменных</translation>
</message>
<message>
<location filename="main_window.ui" line="570"/>
<source>Show variable inspector (Control+I)</source>
<translation>Показать проверщик переменных (Control+I)</translation>
</message>
<message>
<location filename="main_window.ui" line="573"/>
<source>Ctrl+I</source>
<translation>Ctrl+I</translation>
</message>
<message>
<location filename="main_window.ui" line="582"/>
<source>Add sampler</source>
<translation>Добавить звукозапись</translation>
</message>
<message>
<location filename="main_window.ui" line="585"/>
<source>Add sound sampler</source>
<translation>Добавить звукозапись</translation>
</message>
<message>
<location filename="main_window.ui" line="594"/>
<source>Add synth</source>
<translation>Добавить гудок</translation>
</message>
<message>
<location filename="main_window.ui" line="597"/>
<source>Add sound synthesizer</source>
<translation>Добавить гудок</translation>
</message>
<message>
<location filename="main_window.ui" line="609"/>
<source>Show file pool</source>
<translation>Показать склад записей</translation>
</message>
<message>
<location filename="main_window.ui" line="612"/>
<source>Ctrl+P</source>
<translation>Ctrl+P</translation>
</message>
<message>
<location filename="main_window.ui" line="624"/>
<source>Show debug window</source>
<translation>Показать окно отладки</translation>
</message>
<message>
<location filename="main_window.ui" line="627"/>
<source>Show debug window (standard output) and a Python interpreter (Control+D)</source>
<translation>Показать окно отладки и разработчик Питон (Control+D)</translation>
</message>
<message>
<location filename="main_window.ui" line="630"/>
<source>Ctrl+D</source>
<translation>Ctrl+D</translation>
</message>
<message>
<location filename="main_window.ui" line="638"/>
<source>Enable auto response</source>
<translation type="unfinished">Воображаемый испытуемый</translation>
</message>
<message>
<location filename="main_window.ui" line="646"/>
<source>Plugins</source>
<translation>Дополнения</translation>
</message>
<message>
<location filename="main_window.ui" line="655"/>
<source>Random tip</source>
<translation>Случайный совет</translation>
</message>
<message>
<location filename="main_window.ui" line="658"/>
<source>Show a random tip</source>
<translation>Показать случайный совет</translation>
</message>
<message>
<location filename="main_window.ui" line="667"/>
<source>Open backup folder</source>
<translation>Открыть папку с точками восстановления</translation>
</message>
<message>
<location filename="main_window.ui" line="676"/>
<source>Submit a bug</source>
<translation>Сообщить об ошибке</translation>
</message>
<message>
<location filename="main_window.ui" line="685"/>
<source>Contribute</source>
<translation>Помочь разработчикам</translation>
</message>
<message>
<location filename="main_window.ui" line="694"/>
<source>Preferences</source>
<translation>Настройки</translation>
</message>
<message>
<location filename="main_window.ui" line="699"/>
<source>Dummy</source>
<translation>Болванчик</translation>
</message>
<message>
<location filename="main_window.ui" line="707"/>
<source>Show overview area</source>
<translation>Показать обзорный лист</translation>
</message>
<message>
<location filename="main_window.ui" line="710"/>
<source>Ctrl+Shift+O</source>
<translation>Ctrl+Shift+O</translation>
</message>
<message>
<location filename="main_window.ui" line="722"/>
<source>One tab mode</source>
<translation>Только одна вкладка</translation>
</message>
<message>
<location filename="main_window.ui" line="725"/>
<source>Enable one tab mode</source>
<translation>Показывать только одну вкладку</translation>
</message>
<message>
<location filename="main_window.ui" line="733"/>
<source>Compact toolbar</source>
<translation>Уменьшенная приборная доска</translation>
</message>
<message>
<location filename="main_window.ui" line="517"/>
<source>Offline help</source>
<translation>Справочник без подключения к Сети</translation>
</message>
<message>
<location filename="main_window.ui" line="738"/>
<source>Online help</source>
<translation>Справочник в Сети</translation>
</message>
<message>
<location filename="main_window.ui" line="743"/>
<source>Online forum</source>
<translation>Сообщество в Сети</translation>
</message>
<message>
<location filename="main_window.ui" line="748"/>
<source>Quick run</source>
<translation>Быстрый запуск</translation>
</message>
<message>
<location filename="main_window.ui" line="751"/>
<source>Give your experiment a quick test run</source>
<translation>Быстро запустить Ваш опыт</translation>
</message>
<message>
<location filename="main_window.ui" line="754"/>
<source>Ctrl+Shift+W</source>
<translation>Ctrl+Shift+W</translation>
</message>
<message>
<location filename="main_window.ui" line="764"/>
<source>Quick switcher</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="main_window.ui" line="767"/>
<source>Meta+O</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="main_window.ui" line="493"/>
<source>Ctrl+Alt+T</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="main_window.ui" line="772"/>
<source>Close current tab</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="main_window.ui" line="775"/>
<source>Close the current tab</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="main_window.ui" line="778"/>
<source>Alt+T</source>
<translation type="unfinished"></translation>
</message>
</context>
<context>
<name>opensesamerun_mainwindow</name>
<message>
<location filename="opensesamerun.ui" line="14"/>
<source>OpenSesame Run</source>
<translation>Запуск опыта</translation>
</message>
<message>
<location filename="opensesamerun.ui" line="51"/>
<source><b>OpenSesame Run</b><br /><small><i>Run your OpenSesame experiment</i></small></source>
<translation><b>Запуск опыта</b><br /></translation>
</message>
<message>
<location filename="opensesamerun.ui" line="61"/>
<source>Experiment, subject and log file</source>
<translation>Опыт, испытуемый и запись данных</translation>
</message>
<message>
<location filename="opensesamerun.ui" line="121"/>
<source>Browse</source>
<translation>Обзор</translation>
</message>
<message>
<location filename="opensesamerun.ui" line="105"/>
<source>Experiment</source>
<translation>Опыт</translation>
</message>
<message>
<location filename="opensesamerun.ui" line="135"/>
<source>Log file</source>
<translation>Запись отчёта</translation>
</message>
<message>
<location filename="opensesamerun.ui" line="149"/>
<source>Subject number</source>
<translation>Порядковое значение испытуемого</translation>
</message>
<message>
<location filename="opensesamerun.ui" line="159"/>
<source>Display</source>
<translation>Показать</translation>
</message>
<message>
<location filename="opensesamerun.ui" line="180"/>
<source>Run fullscreen</source>
<translation>Запустить на всё полотно</translation>
</message>
<message>
<location filename="opensesamerun.ui" line="187"/>
<source>Use custom display resolution</source>
<translation>Выбрать разрешение полотна</translation>
</message>
<message>
<location filename="opensesamerun.ui" line="215"/>
<source>Width</source>
<translation>Ширина</translation>
</message>
<message>
<location filename="opensesamerun.ui" line="272"/>
<source>px</source>
<translation> тчк</translation>
</message>
<message>
<location filename="opensesamerun.ui" line="256"/>
<source>Height</source>
<translation>Высота</translation>
</message>
<message>
<location filename="opensesamerun.ui" line="307"/>
<source>Miscellaneous</source>
<translation>Разное</translation>
</message>
<message>
<location filename="opensesamerun.ui" line="328"/>
<source>Enable PyLink module (required for the Eyelink plug-ins)</source>
<translation>Разрешить "ПайЛинк" (для дополнений "АйЛинк")</translation>
</message>
<message>
<location filename="opensesamerun.ui" line="357"/>
<source>Cancel</source>
<translation>Отменить</translation>
</message>
<message>
<location filename="opensesamerun.ui" line="368"/>
<source>Run</source>
<translation>Запуск</translation>
</message>
</context>
<context>
<name>plugin_manager</name>
<message>
<location filename="translatables.py" line="387"/>
<source>Plug-in and extension manager</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="translatables.py" line="388"/>
<source>Enable or disable plug-ins and extensions.</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="translatables.py" line="389"/>
<source>Manage plug-ins and extensions</source>
<translation type="unfinished"></translation>
</message>
</context>
<context>
<name>pool_widget</name>
<message>
<location filename="pool_widget.ui" line="17"/>
<source>Form</source>
<translation>Окно</translation>
</message>
<message>
<location filename="pool_widget.ui" line="48"/>
<source><b>File pool</b><br /><small><i>You can drag and drop files into the pool</i></small></source>
<translation type="obsolete"><b>Склад записей</b><br /><small><i>Можете перетащить сюда Ваши записи с внутреннего носителя</i></small></translation>
</message>
<message>
<location filename="pool_widget.ui" line="58"/>
<source>Enter a filter</source>
<translation>Введите отсеиватель</translation>
</message>
<message>
<location filename="pool_widget.ui" line="71"/>
<source>Clear filter</source>
<translation>Очистить отсеиватель</translation>
</message>
<message>
<location filename="pool_widget.ui" line="91"/>
<source>Help</source>
<translation>Помощь</translation>
</message>
<message>
<location filename="pool_widget.ui" line="126"/>
<source>Add file</source>
<translation>Добавить запись</translation>
</message>
<message>
<location filename="pool_widget.ui" line="163"/>
<source>Open file pool in file manager</source>
<translation>Открыть папку со складом</translation>
</message>
<message>
<location filename="pool_widget.ui" line="190"/>
<source>View as list</source>
<translation>Показать в виде списка</translation>
</message>
<message>
<location filename="pool_widget.ui" line="199"/>
<source>View as icons</source>
<translation>Показать в виде значков</translation>
</message>
<message>
<location filename="pool_widget.ui" line="38"/>
<source>ICON</source>
<translation type="obsolete">Значок</translation>
</message>
<message>
<location filename="pool_widget.ui" line="23"/>
<source><html><head/><body><p>Warning text</p></body></html></source>
<translation type="unfinished"></translation>
</message>
</context>
<context>
<name>preferences_widget</name>
<message>
<location filename="preferences_widget.ui" line="14"/>
<source>Form</source>
<translation>Окно</translation>
</message>
<message>
<location filename="preferences_widget.ui" line="38"/>
<source>Miscellaneous</source>
<translation>Разное</translation>
</message>
<message>
<location filename="preferences_widget.ui" line="56"/>
<source>Offer to rename new items immediately</source>
<translation type="obsolete">Предлагать сразу же переименовывать новые составляющие </translation>
</message>
<message>
<location filename="preferences_widget.ui" line="53"/>
<source>Enable auto-response</source>
<translation>Воображаемый испытуемый (приложение проходит опыт само)</translation>
</message>
<message>
<location filename="preferences_widget.ui" line="125"/>
<source>Show text in toolbar</source>
<translation>Показывать подписи в приборной доске</translation>
</message>
<message>
<location filename="preferences_widget.ui" line="118"/>
<source>Small icons in toolbar</source>
<translation>Маленькие значки в приборной доске</translation>
</message>
<message>
<location filename="preferences_widget.ui" line="69"/>
<source>Appearance</source>
<translation>Вид</translation>
</message>
<message>
<location filename="preferences_widget.ui" line="144"/>
<source>Backups</source>
<translation type="obsolete">Точки восстановления</translation>
</message>
<message>
<location filename="preferences_widget.ui" line="168"/>
<source>Automatically create backups</source>
<translation type="obsolete">Самостоятельно создавать точки восстановления</translation>
</message>
<message>
<location filename="preferences_widget.ui" line="175"/>
<source>Auto-save interval:</source>
<translation type="obsolete">Самосохранение через:</translation>
</message>
<message>
<location filename="preferences_widget.ui" line="182"/>
<source> minute(s)</source>
<translation type="obsolete"> мин</translation>
</message>
<message>
<location filename="preferences_widget.ui" line="185"/>
<source>every </source>
<translation type="obsolete"> </translation>
</message>
<message>
<location filename="preferences_widget.ui" line="221"/>
<source>Open backup folder</source>
<translation type="obsolete">Открыть папку с точками восстановления</translation>
</message>
<message>
<location filename="preferences_widget.ui" line="201"/>
<source>Clean backups after:</source>
<translation type="obsolete">Очищать точки восстановления через:</translation>
</message>
<message>
<location filename="preferences_widget.ui" line="208"/>
<source> day(s)</source>
<translation type="obsolete"> дн</translation>
</message>
<message>
<location filename="preferences_widget.ui" line="241"/>
<source>Updates</source>
<translation type="obsolete">Обновления</translation>
</message>
<message>
<location filename="preferences_widget.ui" line="256"/>
<source>Check for updates on start-up</source>
<translation type="obsolete">Проверять обновления при запуске</translation>
</message>
<message>
<location filename="preferences_widget.ui" line="263"/>
<source>Check for updates now</source>
<translation type="obsolete">Проверить обновления сейчас</translation>
</message>
<message>
<location filename="preferences_widget.ui" line="339"/>
<source>Plug-ins</source>
<translation type="obsolete">Дополнения</translation>
</message>
<message>
<location filename="preferences_widget.ui" line="357"/>
<source>Plug-in folders:</source>
<translation type="obsolete">Хранилище дополнений:</translation>
</message>
<message>
<location filename="preferences_widget.ui" line="377"/>
<source>Installed plug-ins (requires restart):</source>
<translation type="obsolete">Установленные дополнения (требует перезапуск):</translation>
</message>
<message>
<location filename="preferences_widget.ui" line="98"/>
<source>Interface style</source>
<translation>Внешний вид приложения</translation>
</message>
<message>
<location filename="preferences_widget.ui" line="108"/>
<source>icon theme</source>
<translation>Вид значков</translation>
</message>
<message>
<location filename="preferences_widget.ui" line="87"/>
<source><small><i>Changes take effect the next time you start OpenSesame</i></small>
</source>
<translation><small><i>Изменения вступят в силу после перезапуска</i></small></translation>
</message>
<message>
<location filename="preferences_widget.ui" line="141"/>
<source>Runner</source>
<translation>Запускающий</translation>
</message>
<message>
<location filename="preferences_widget.ui" line="159"/>
<source><html><head/><body><p><span style=" font-size:8pt; font-style:italic;">The 'runner' determines how your OpenSesame experiment is executed. For more information, please visit </span><a href="http://osdoc.cogsci.nl/miscellaneous/runners"><span style=" font-size:8pt; font-style:italic; text-decoration: underline; color:#0057ae;">http://osdoc.cogsci.nl/miscellaneous/runners</span></a><span style=" font-size:8pt; font-style:italic;">.</span></p></body></html></source>
<translation><html><head/><body><p><span style=" font-size:8pt; font-style:italic;">"Запускающий"' определяет, как "Сезам, откройся" запускает опыты. Подробности на: </span><a href="http://osdoc.cogsci.nl/miscellaneous/runners"><span style=" font-size:8pt; font-style:italic; text-decoration: underline; color:#0057ae;">http://osdoc.cogsci.nl/miscellaneous/runners</span></a><span style=" font-size:8pt; font-style:italic;">.</span></p></body></html></translation>
</message>
<message>
<location filename="preferences_widget.ui" line="170"/>
<source>Run experiment in the same process (inprocess)</source>
<translation>Как часть "Сезам, откройся"</translation>
</message>
<message>
<location filename="preferences_widget.ui" line="175"/>
<source>Run experiment in a separate process (multiprocess)</source>
<translation>Одновременно с "Сезам, откройся"</translation>
</message>
<message>
<location filename="preferences_widget.ui" line="180"/>
<source>Run experiment with opensesamerun (external)</source>
<translation>Отдельно от "Сезам, откройся"</translation>
</message>
</context>
<context>
<name>psychopy_monitor_center</name>
<message>
<location filename="translatables.py" line="26"/>
<source>PsychoPy monitor center</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="translatables.py" line="27"/>
<source>Launches the PsychoPy monitor center</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="translatables.py" line="28"/>
<source>Launch the PsychoPy monitor center</source>
<translation type="unfinished"></translation>
</message>
</context>
<context>
<name>qprogedit_preferences</name>
<message>
<location filename="translatables.py" line="355"/>
<source>QProgEdit preferences</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="translatables.py" line="354"/>
<source>Editor preferences (QProgEdit)</source>
<translation type="unfinished"></translation>
</message>
</context>
<context>
<name>quest_staircase_init</name>
<message>
<location filename="translatables.py" line="43"/>
<source>Staircase</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="translatables.py" line="45"/>
<source>Estimated threshold (used for starting test value)</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="translatables.py" line="47"/>
<source>Std. dev. of estimated threshold</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="translatables.py" line="49"/>
<source>Desired proportion of correct responses</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="translatables.py" line="51"/>
<source>Steepness of the Weibull psychometric function (β)</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="translatables.py" line="53"/>
<source>Proportion of random responses at maximum stimulus intensity (δ)</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="translatables.py" line="55"/>
<source>Chance level (γ)</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="translatables.py" line="57"/>
<source>Method to determine optimal test value</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="translatables.py" line="59"/>
<source>Minimum test value</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="translatables.py" line="61"/>
<source>Maximum test value</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="translatables.py" line="63"/>
<source>Experimental variable for test value</source>
<translation type="unfinished"></translation>
</message>
</context>
<context>
<name>quest_staircase_next</name>
<message>
<location filename="translatables.py" line="3"/>
<source>Staircase</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="translatables.py" line="5"/>
<source>Response variable (0 or 1)</source>
<translation type="unfinished"></translation>
</message>
</context>
<context>
<name>quick_switcher</name>
<message>
<location filename="translatables.py" line="230"/>
<source>Quick switcher</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="translatables.py" line="231"/>
<source>Quickly open items and scripts.</source>
<translation type="unfinished"></translation>
</message>
</context>
<context>
<name>replace_dialog</name>
<message>
<location filename="replace_dialog.ui" line="14"/>
<source>Search/ Replace</source>
<translation type="obsolete">Искать/Заменить</translation>
</message>
<message>
<location filename="replace_dialog.ui" line="26"/>
<source>Search for</source>
<translation type="obsolete">Искать</translation>
</message>
<message>
<location filename="replace_dialog.ui" line="33"/>
<source>Replace with</source>
<translation type="obsolete">Заменить на</translation>
</message>
<message>
<location filename="replace_dialog.ui" line="40"/>
<source>Search term</source>
<translation type="obsolete">Найти понятие</translation>
</message>
<message>
<location filename="replace_dialog.ui" line="47"/>
<source>Replacement term</source>
<translation type="obsolete">Заменить понятие</translation>
</message>
<message>
<location filename="replace_dialog.ui" line="63"/>
<source>Search and select a single occurence</source>
<translation type="obsolete">Найти и выделить одно совпадение</translation>
</message>
<message>
<location filename="replace_dialog.ui" line="66"/>
<source>Search</source>
<translation type="obsolete">Искать</translation>
</message>
<message>
<location filename="replace_dialog.ui" line="77"/>
<source>Replace the current selection</source>
<translation type="obsolete">Заменить выделенное</translation>
</message>
<message>
<location filename="replace_dialog.ui" line="80"/>
<source>Replace</source>
<translation type="obsolete">Заменить</translation>
</message>
<message>
<location filename="replace_dialog.ui" line="91"/>
<source>Replace all occurences</source>
<translation type="obsolete">Заменить все совпадения</translation>
</message>
<message>
<location filename="replace_dialog.ui" line="94"/>
<source>Replace all</source>
<translation type="obsolete">Заменить все</translation>
</message>
<message>
<location filename="replace_dialog.ui" line="105"/>
<source>Close this dialog</source>
<translation type="obsolete">Закрыть это окно</translation>
</message>
<message>
<location filename="replace_dialog.ui" line="108"/>
<source>Close</source>
<translation type="obsolete">Закрыть</translation>
</message>
</context>
<context>
<name>reset_feedback</name>
<message>
<location filename="translatables.py" line="234"/>
<source>Response collection</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="translatables.py" line="235"/>
<source>This plug-in has no settings</source>
<translation type="unfinished"></translation>
</message>
</context>
<context>
<name>sampler_widget</name>
<message>
<location filename="sampler_widget.ui" line="14"/>
<source>Form</source>
<translation>Окно</translation>
</message>
<message>
<location filename="sampler_widget.ui" line="38"/>
<source>Sound file</source>
<translation>Звукозапись</translation>
</message>
<message>
<location filename="sampler_widget.ui" line="45"/>
<source>The sound file. Expecting a .ogg or .wav file.</source>
<translation>Звукозапись. Должна быть .ogg или .wav</translation>
</message>
<message>
<location filename="sampler_widget.ui" line="58"/>
<source>Select a sound file from the file pool</source>
<translation>Выбрать звукозапись со склада</translation>
</message>
<message>
<location filename="sampler_widget.ui" line="61"/>
<source>Browse</source>
<translation>Обзор</translation>
</message>
<message>
<location filename="sampler_widget.ui" line="90"/>
<source>Volume</source>
<translation>Громкость</translation>
</message>
<message>
<location filename="sampler_widget.ui" line="119"/>
<source>Set the volume of the sound</source>
<translation>Установить громкость записи</translation>
</message>
<message>
<location filename="sampler_widget.ui" line="212"/>
<source>%</source>
<translation type="obsolete">%</translation>
</message>
<message>
<location filename="sampler_widget.ui" line="138"/>
<source>Pan</source>
<translation>Сторона выхода звука</translation>
</message>
<message>
<location filename="sampler_widget.ui" line="148"/>
<source>Pitch</source>
<translation>Высота</translation>
</message>
<message>
<location filename="sampler_widget.ui" line="196"/>
<source>Set the panning (left-right) of the sound</source>
<translation>Слева или справа издаётся звук</translation>
</message>
<message>
<location filename="sampler_widget.ui" line="177"/>
<source>Set the relative pitch of the sound (100% = original)</source>
<translation>Относительная высота звука (100% = первоначальная запись)</translation>
</message>
<message>
<location filename="sampler_widget.ui" line="234"/>
<source>Stop after</source>
<translation>Остановить через</translation>
</message>
<message>
<location filename="sampler_widget.ui" line="241"/>
<source>Force playback to stop after a specified duration. 0ms corresponds to a full playback.</source>
<translation>Если стоит "0", то проигрывается полная звукозапись.</translation>
</message>
<message>
<location filename="sampler_widget.ui" line="251"/>
<source>ms</source>
<translation type="obsolete"> мс</translation>
</message>
<message>
<location filename="sampler_widget.ui" line="254"/>
<source>The fade-in time of the sound.</source>
<translation> </translation>
</message>
<message>
<location filename="sampler_widget.ui" line="267"/>
<source>Set the duration of the sampler item. Expecting a duration in ms, 'sound' (to wait until the sound is finished playing), 'keypress', 'mouseclick', or a variable (e.g., '[sampler_dur]').</source>
<translation>Длительность звукозаписи. Должна быть в мс, "sound" (полная длительность), "keypress" (нажатие ключа), "mouseclick" (щелчок мыши) или переменная</translation>
</message>
<message>
<location filename="sampler_widget.ui" line="270"/>
<source>sound</source>
<translation>звук</translation>
</message>
<message>
<location filename="sampler_widget.ui" line="277"/>
<source>Fade in</source>
<translation>Наступление</translation>
</message>
<message>
<location filename="sampler_widget.ui" line="284"/>
<source>Duration</source>
<translation>Длительность</translation>
</message>
<message>
<location filename="sampler_widget.ui" line="324"/>
<source>Sampler controls</source>
<translation>Настройки звукозаписи</translation>
</message>
<message>
<location filename="sampler_widget.ui" line="212"/>
<source>Set the relative pitch of the sound (1 = original)</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="sampler_widget.ui" line="257"/>
<source> ms</source>
<translation type="unfinished"></translation>
</message>
</context>
<context>
<name>script</name>
<message>
<location filename="translatables.py" line="154"/>
<source>Edit script</source>
<translation>Изменить приказник</translation>
</message>
<message>
<location filename="translatables.py" line="117"/>
<source>Tell me more about the %s item</source>
<translation>Вывести больше о составляющей %s </translation>
</message>
<message>
<location filename="translatables.py" line="101"/>
<source>%s (Edit the script to fix this)</source>
<translation type="obsolete">%s (Изменить приказник, чтобы исправить это)</translation>
</message>
<message>
<location filename="translatables.py" line="118"/>
<source>Forget changes?</source>
<translation type="obsolete">Забыть изменения?</translation>
</message>
<message>
<location filename="translatables.py" line="119"/>
<source>Are you sure you want to forget all changes to the script?</source>
<translation type="obsolete">Вы уверены, что хотите забыть все изменения в этом приказнике?</translation>
</message>
<message>
<location filename="translatables.py" line="118"/>
<source>Apply and close</source>
<translation type="unfinished">Применить и закрыть</translation>
</message>
<message>
<location filename="translatables.py" line="121"/>
<source>Apply changes and resume normal editing</source>
<translation type="obsolete">Применить изменения и продолжить исправление</translation>
</message>
<message>
<location filename="translatables.py" line="122"/>
<source>Forget changes and close</source>
<translation type="obsolete">Забыть изменения и закрыть</translation>
</message>
<message>
<location filename="translatables.py" line="123"/>
<source>Ignore changes and resume normal editing</source>
<translation type="obsolete">Не обращать внимание на изменения и продолжить исправление</translation>
</message>
<message>
<location filename="translatables.py" line="103"/>
<source>Editing script for <b>%s</b> - %s</source>
<translation type="obsolete">Изменить приказник для <b>%s</b> - %s</translation>
</message>
<message>
<location filename="translatables.py" line="216"/>
<source>Type: %s
Description: %s</source>
<translation>Вид: %s
Описание: %s</translation>
</message>
<message>
<location filename="translatables.py" line="120"/>
<source>Failed to set control '%s': %s</source>
<translation>Не получилось изменить'%s': %s</translation>
</message>
<message>
<location filename="translatables.py" line="109"/>
<source>Invalid or missing value for variable '%s' (edit script to fix this)</source>
<translation type="obsolete">Неправильное или пропущенное значение переменной '%s' (изменить приказник, чтобы исправить это)</translation>
</message>
<message>
<location filename="translatables.py" line="128"/>
<source>New variable</source>
<translation>Новая переменная</translation>
</message>
<message>
<location filename="translatables.py" line="124"/>
<source>Enter a variable name, optionally followed by a default value (i.e., "varname defaultvalue")</source>
<translation>Введите имя переменной, следующей за переменной по умолчанию (то есть., "varname defaultvalue")</translation>
</message>
<message>
<location filename="translatables.py" line="131"/>
<source>A variable with the name '%s' already exists</source>
<translation>Переменная с именем '%s' уже существует</translation>
</message>
<message>
<location filename="translatables.py" line="126"/>
<source>Rename variable</source>
<translation>Переименовать переменную</translation>
</message>
<message>
<location filename="translatables.py" line="127"/>
<source>Which variable do you want to rename?</source>
<translation>Какую переменную Вы хотите переименовать?</translation>
</message>
<message>
<location filename="translatables.py" line="129"/>
<source>Enter a new variable name</source>
<translation>Ввести новое имя переменной</translation>
</message>
<message>
<location filename="translatables.py" line="130"/>
<source>Please use only letters, numbers and underscores</source>
<translation>Используйте только буквы и цифры</translation>
</message>
<message>
<location filename="translatables.py" line="132"/>
<source>Remove variable</source>
<translation>Удалить переменную</translation>
</message>
<message>
<location filename="translatables.py" line="133"/>
<source>Which variable do you want to remove?</source>
<translation>Какую переменную Вы хотите удалить?</translation>
</message>
<message>
<location filename="translatables.py" line="134"/>
<source>Remove cycles?</source>
<translation>Удалить круги?</translation>
</message>
<message>
<location filename="translatables.py" line="135"/>
<source>By reducing the number of cycles, data will be lost from the table. Do you wish to continue?</source>
<translation>Если Вы уменьшите количество кругов, Вы потеряете данные из ячеицы. Продолжить?</translation>
</message>
<message>
<location filename="translatables.py" line="137"/>
<source><b>%s</b> will be called <b>%s</b> x <b>%s</b> - <b>%s</b> = <b>%s</b> times in <b>%s</b> order</source>
<translation><b>%s</b> будет вызываться <b>%s</b> x <b>%s</b> - <b>%s</b> = <b>%s</b> раз в <b>%s</b> порядке</translation>
</message>
<message>
<location filename="translatables.py" line="138"/>
<source><b>%s</b> will be called <b>%s</b> x <b>%s</b> = <b>%s</b> times in <b>%s</b> order</source>
<translation><b>%s</b> будет вызываться <b>%s</b> x <b>%s</b> = <b>%s</b> раз в <b>%s</b> порядке</translation>
</message>
<message>
<location filename="translatables.py" line="150"/>
<source> starting at cycle <b>%d</b></source>
<translation type="obsolete">начиная с круга <b>%d</b></translation>
</message>
<message>
<location filename="translatables.py" line="140"/>
<source> <font color='red'><b>(too many cycles skipped)</b></font></source>
<translation> <font color='red'><b>(слишком много кругов пропущено)</b></font></translation>
</message>
<message>
<location filename="translatables.py" line="152"/>
<source> <font color='red'><b>(zero or negative length)</b></font></source>
<translation type="obsolete"> <font color='red'><b>(пустая или отрицательная длина)</b></font></translation>
</message>
<message>
<location filename="translatables.py" line="146"/>
<source>The following key names are valid:<br /></source>
<translation>Возможны следующие ключи:<br /></translation>
</message>
<message>
<location filename="translatables.py" line="113"/>
<source>Prepare phase</source>
<translation type="obsolete">Подготовить петлю</translation>
</message>
<message>
<location filename="translatables.py" line="114"/>
<source>Run phase</source>
<translation type="obsolete">Запустить петлю</translation>
</message>
<message>
<location filename="translatables.py" line="143"/>
<source>Flush pending key presses at sequence start</source>
<translation type="obsolete">Запретить нажимать на нужные ключи до начала последовательности</translation>
</message>
<message>
<location filename="translatables.py" line="144"/>
<source>Append existing item to sequence</source>
<translation type="obsolete">Добавить существующую составляющую в последовательность</translation>
</message>
<message>
<location filename="translatables.py" line="145"/>
<source>Create and append new item to sequence</source>
<translation type="obsolete">Создать и добавить новую составляющую в последовательность</translation>
</message>
<message>
<location filename="translatables.py" line="146"/>
<source>Append existing item</source>
<translation type="obsolete">Добавить существующую составляющую</translation>
</message>
<message>
<location filename="translatables.py" line="198"/>
<source>Append new item</source>
<translation type="unfinished">Добавить новую составляющую</translation>
</message>
<message>
<location filename="translatables.py" line="98"/>
<source>Welcome to OpenSesame %s</source>
<translation>Добро пожаловать в "Сезам, откройся" %s</translation>
</message>
<message>
<location filename="translatables.py" line="99"/>
<source>Busy ...</source>
<translation>Подождите...</translation>
</message>
<message>
<location filename="translatables.py" line="100"/>
<source>Done!</source>
<translation>Готов к работе!</translation>
</message>
<message>
<location filename="translatables.py" line="14"/>
<source>Backup saved as %s</source>
<translation type="obsolete">Точка восстановления сохранена как %s</translation>
</message>
<message>
<location filename="translatables.py" line="15"/>
<source>Failed to save backup ...</source>
<translation type="obsolete">Не удалось сохранить точку восстановления...</translation>
</message>
<message>
<location filename="translatables.py" line="101"/>
<source>Save changes?</source>
<translation>Сохранить изменения?</translation>
</message>
<message>
<location filename="translatables.py" line="102"/>
<source>Your experiment contains unsaved changes. Do you want to save your experiment?</source>
<translation>В Вашем опыте имеются несохранённые изменения. Хотите сохранить Ваш опыт?</translation>
</message>
<message>
<location filename="translatables.py" line="103"/>
<source>%s [unsaved]</source>
<translation>%s [несохранено]</translation>
</message>
<message>
<location filename="translatables.py" line="19"/>
<source>... and is sorry to say that the attempt to check for updates has failed. Please make sure that you are connected to the internet and try again later. If this problem persists, please visit <a href='http://www.cogsci.nl/opensesame'>http://www.cogsci.nl/opensesame</a> for more information.</source>
<translation type="obsolete">Проверка обновлений не удалась. Проверьте, подключены ли Вы к Сети. Или посетите <a href='http://www.cogsci.nl/opensesame'>http://www.cogsci.nl/opensesame</a></translation>
</message>
<message>
<location filename="translatables.py" line="20"/>
<source>... and is happy to report that a new version of OpenSesame (%s) is available at <a href='http://www.cogsci.nl/opensesame'>http://www.cogsci.nl/opensesame</a>!</source>
<translation type="obsolete">Рады сообщить Вам, что новое исполнение "Сезам, откройся" (%s) доступно на <a href='http://www.cogsci.nl/opensesame'>http://www.cogsci.nl/opensesame</a>!</translation>
</message>
<message>
<location filename="translatables.py" line="21"/>
<source> ... and is happy to report that you are running the most recent version of OpenSesame.</source>
<translation type="obsolete">Вы пользуетесь последним исполнением "Сезам, откройся"</translation>
</message>
<message>
<location filename="translatables.py" line="15"/>
<source>Restart?</source>
<translation type="obsolete">Перезапустить?</translation>
</message>
<message>
<location filename="translatables.py" line="16"/>
<source>A restart is required. Do you want to save the current experiment and restart OpenSesame?</source>
<translation type="obsolete">Необходим перезапуск. Вы хотите сохранить текущий опыт и перезапустить "Сезам, откройся"?</translation>
</message>
<message>
<location filename="translatables.py" line="104"/>
<source>Quit?</source>
<translation>Выйти?</translation>
</message>
<message>
<location filename="translatables.py" line="105"/>
<source>Are you sure you want to quit OpenSesame?</source>
<translation>Вы уверены, что хотите выйти?</translation>
</message>
<message>
<location filename="translatables.py" line="106"/>
<source>(No recent files)</source>
<translation>(Нет последних записей)</translation>
</message>
<message>
<location filename="translatables.py" line="21"/>
<source><b>Error:</b> Failed to open '%s'<br /><b>Description:</b> %s<br /><br />Make sure that the file is in .opensesame or .opensesame.tar.gz format. If you should be able to open this file, but can't, please go to http://www.cogsci.nl/opensesame to find out how to recover your experiment and file a bug report.</source>
<translation type="obsolete"><b>Ошибка:</b> Невозможно открыть '%s'<br /><b>Описание:</b> %s<br /><br />Убедитесь, что запись имеет расширение .opensesame или .opensesame.tar.gz Если Вы уверены, что запись должна открываться, но она не открывается, пожалуйста, посетите http://www.cogsci.nl/opensesame чтобы разобраться, как восстановить Ваш опыт, и сообщить нам об ошибке.</translation>
</message>
<message>
<location filename="translatables.py" line="26"/>
<source>Could not save file, because the script could not be generated. The following error occured:<br/>%s</source>
<translation type="obsolete">Невозможно сохранить запись, так как приказник не может быть создан. Произошла следующая ошибка:<br/>%s</translation>
</message>
<message>
<location filename="translatables.py" line="109"/>
<source>Saved as %s</source>
<translation>Сохранено как %s</translation>
</message>
<message>
<location filename="translatables.py" line="110"/>
<source>Failed to save file. Error: %s</source>
<translation>Не удалось сохранить. Ошибка: %s</translation>
</message>
<message>
<location filename="translatables.py" line="111"/>
<source>Save file as ...</source>
<translation>Сохранить запись как...</translation>
</message>
<message>
<location filename="translatables.py" line="27"/>
<source>Failed to change the display resolution:</source>
<translation type="obsolete">Не удалось изменить разрешение полотна:</translation>
</message>
<message>
<location filename="translatables.py" line="113"/>
<source>Could not parse script: %s</source>
<translation>Не могу исследовать приказник: %s</translation>
</message>
<message>
<location filename="translatables.py" line="208"/>
<source><b><font size='5'>Unused</font></b></source>
<translation><b><font size='5'>Корзина</font></b></translation>
</message>
<message>
<location filename="translatables.py" line="209"/>
<source>Permanently delete unused items</source>
<translation>Удалить навсегда неиспользуемые составляющие</translation>
</message>
<message>
<location filename="translatables.py" line="210"/>
<source>Permanently delete items?</source>
<translation>Удалить навсегда эти составляющие?</translation>
</message>
<message>
<location filename="translatables.py" line="95"/>
<source>Are you sure you want to permanently delete all unused items? This action cannot be undone.</source>
<translation type="obsolete">Вы уверены, что хотите удалить навсегда неиспользуемые составляющие. Восстановить потом их не удастся.</translation>
</message>
<message>
<location filename="translatables.py" line="114"/>
<source>File renamed</source>
<translation>Запись переименована</translation>
</message>
<message>
<location filename="translatables.py" line="115"/>
<source>The file has been renamed to '%s', because the file pool already contains a file named '%s'.</source>
<translation>Эта запись была переименована в '%s', потому что склад уже содержит запись с именем '%s'.</translation>
</message>
<message>
<location filename="translatables.py" line="31"/>
<source><b>Failed to start opensesamerun</b><br />Please make sure that opensesamerun (or opensesamerun.exe) is present in the path, manually specify the run command, or deselect the 'Run as separate process' option.<br><pre>%s</pre></source>
<translation type="obsolete"><b>Не могу запустить opensesamerun</b><br />Убедитесь, что opensesamerun (или opensesamerun.exe) присутствует, исправьте приказник, или уберите в запускающем (в настройках "Сезам, откройся") "Одновременно с "Сезам, откройся"'.<br><pre>%s</pre></translation>
</message>
<message>
<location filename="translatables.py" line="94"/>
<source>Finished!</source>
<translation>Закончено!</translation>
</message>
<message>
<location filename="translatables.py" line="95"/>
<source>The experiment is finished and data has been logged to '%s'. Do you want to copy the logfile to the file pool?</source>
<translation>Опыт закончен и данных сохранены в '%s' Хотите отправить запись с этими данными на склад?</translation>
</message>
<message>
<location filename="translatables.py" line="92"/>
<source>Subject number</source>
<translation>Порядковое имя испытуемого</translation>
</message>
<message>
<location filename="translatables.py" line="93"/>
<source>Please enter the subject number</source>
<translation>Введите порядковое имя испытуемого</translation>
</message>
<message>
<location filename="translatables.py" line="90"/>
<source>Choose location for logfile (press 'escape' for default location)</source>
<translation>Выберите местоположение для записи собираемых данных</translation>
</message>
<message>
<location filename="translatables.py" line="91"/>
<source>The logfile '%s' is not writable. Please choose another location for the logfile.</source>
<translation>Запись для сбора данных '%s' не получилось создать. Выберите другое место для сохранения.</translation>
</message>
<message>
<location filename="translatables.py" line="38"/>
<source><b>Error</b>: OpenExp error<br /><b>Description</b>: %s</source>
<translation type="obsolete"><b>Ошибка</b>: OpenExp ошибка<br /><b>Описание</b>: %s</translation>
</message>
<message>
<location filename="translatables.py" line="39"/>
<source>An unexpected error occurred, which was not caught by OpenSesame. This should not happen! Message:<br/><b>%s</b></source>
<translation type="obsolete">Непредвиденная ошибка, которую "Сезам, откройся" не понимает.Это не должно было произойти! Сообщение:<br/><b>%s</b></translation>
</message>
<message>
<location filename="translatables.py" line="40"/>
<source>Failed to load plugin '%s'. Error: %s</source>
<translation type="obsolete">Невозможно загрузить дополнение '%s'. Ошибка: %s</translation>
</message>
<message>
<location filename="translatables.py" line="34"/>
<source>New name</source>
<translation type="obsolete">Новое имя</translation>
</message>
<message>
<location filename="translatables.py" line="35"/>
<source>Please enter a name for the new %s</source>
<translation type="obsolete">Пожалуйста, введите имя для нового(ой) %s</translation>
</message>
<message>
<location filename="translatables.py" line="63"/>
<source>Drag this <b>%s</b> item to the intended location in the overview area or into the item list of a sequence tab</source>
<translation type="obsolete">Перетащите составляющую <b>%s</b> на предполагаемое место в обзорном листе или на вкладку последовательности</translation>
</message>
<message>
<location filename="translatables.py" line="64"/>
<source><small>Commonly used</small></source>
<translation type="obsolete"><small>Часто используемые</small></translation>
</message>
<message>
<location filename="translatables.py" line="66"/>
<source>Drag this item to re-order</source>
<translation type="obsolete">Перетащите эту составляющую в нужное место</translation>
</message>
<message>
<location filename="translatables.py" line="67"/>
<source>Run this item only under the following conditions</source>
<translation type="obsolete">Запустить эту составляющую только при следующих условиях</translation>
</message>
<message>
<location filename="translatables.py" line="68"/>
<source>Click to edit this item</source>
<translation type="obsolete">Нажмите, чтобы изменить составляющую</translation>
</message>
<message>
<location filename="translatables.py" line="69"/>
<source><small><i>Run if</i></small></source>
<translation type="obsolete"><small><i>Запустить, если</i></small></translation>
</message>
<message>
<location filename="translatables.py" line="70"/>
<source>Unkown item '%s' in sequence '%s'. You can fix this using the script editor.</source>
<translation type="obsolete">Неизвестная составляющая '%s' в последовательности '%s'. Это можно исправить в приказнике</translation>
</message>
<message>
<location filename="translatables.py" line="75"/>
<source>(Out of sketchpad)</source>
<translation type="obsolete">(Вне полотна)</translation>
</message>
<message>
<location filename="translatables.py" line="173"/>
<source>Delete</source>
<translation>Удалить</translation>
</message>
<message>
<location filename="translatables.py" line="79"/>
<source>Edit</source>
<translation type="obsolete">Изменить</translation>
</message>
<message>
<location filename="translatables.py" line="80"/>
<source>Edit sketchpad element</source>
<translation type="obsolete">Добавить составляющую полотна</translation>
</message>
<message>
<location filename="translatables.py" line="153"/>
<source>Element script</source>
<translation>Приказник</translation>
</message>
<message>
<location filename="translatables.py" line="150"/>
<source>New textline</source>
<translation>Новая строка</translation>
</message>
<message>
<location filename="translatables.py" line="151"/>
<source>Please enter a text for the textline</source>
<translation>Введите слова</translation>
</message>
<message>
<location filename="translatables.py" line="84"/>
<source>Funky image alert: '%s' has a non-standard format. It is recommended to convert this image to .png format, for example with Gimp <http://www.gimp.org/>.</source>
<translation type="obsolete"> '%s' имеет неподходящее разширение. Используйте .png</translation>
</message>
<message>
<location filename="translatables.py" line="85"/>
<source>%d objects are not shown, because they are defined using variables.</source>
<translation type="obsolete">%d не видны, так как они определены переменными</translation>
</message>
<message>
<location filename="translatables.py" line="86"/>
<source>One object is not shown, because it is defined using variables.</source>
<translation type="obsolete">Один предмет не видно, потому что он определён переменными</translation>
</message>
<message>
<location filename="translatables.py" line="87"/>
<source>Some objects will not be visible (or partly) because they fall outside of the screen boundaries.</source>
<translation type="obsolete">Некоторые составляющие не видно, так как они находятся за пределами полотна</translation>
</message>
<message>
<location filename="translatables.py" line="88"/>
<source>Failed to parse the following item (use 'Edit script' to fix/ remove this line):
'%s'</source>
<translation type="obsolete">Не могу исследовать текущую составляющую (используйте правщик приказника, чтобы исправить эту строку):
'%s'</translation>
</message>
<message>
<location filename="translatables.py" line="179"/>
<source>Overwrite</source>
<translation>Перезаписать</translation>
</message>
<message>
<location filename="translatables.py" line="180"/>
<source>A file named '%s' already exists in the pool. Do you want to overwrite this file?</source>
<translation>Запись с именем '%s' уже существует на складе. Хотите переписать эту запись?</translation>
</message>
<message>
<location filename="translatables.py" line="181"/>
<source>Add files to pool</source>
<translation>Добавить записи на склад</translation>
</message>
<message>
<location filename="translatables.py" line="186"/>
<source>Remove from pool</source>
<translation>Удалить со склада</translation>
</message>
<message>
<location filename="translatables.py" line="190"/>
<source>Rename</source>
<translation>Переименовать</translation>
</message>
<message>
<location filename="translatables.py" line="188"/>
<source>Remove</source>
<translation>Удалить</translation>
</message>
<message>
<location filename="translatables.py" line="191"/>
<source>Please enter a new name for '%s'</source>
<translation>Пожалуйста, введите новое имя для '%s'</translation>
</message>
<message>
<location filename="translatables.py" line="192"/>
<source>There already is a file named '%s' in the file pool</source>
<translation>На складе уже существует запись '%s'</translation>
</message>
<message>
<location filename="translatables.py" line="193"/>
<source>Cancel</source>
<translation>Отменить</translation>
</message>
<message>
<location filename="translatables.py" line="194"/>
<source>Select</source>
<translation>Выбрать</translation>
</message>
<message>
<location filename="translatables.py" line="195"/>
<source>Select file from pool</source>
<translation>ВЫбрать запись со склада</translation>
</message>
<message>
<location filename="translatables.py" line="96"/>
<source>Oops!</source>
<translation type="obsolete">Ой!</translation>
</message>
<message>
<location filename="translatables.py" line="98"/>
<source>Replace all</source>
<translation type="obsolete">Заменить всё</translation>
</message>
<message>
<location filename="translatables.py" line="69"/>
<source>Enter a search term</source>
<translation type="obsolete">Введите поисковый запрос</translation>
</message>
<message>
<location filename="translatables.py" line="70"/>
<source>Search</source>
<translation type="obsolete">Искать</translation>
</message>
<message>
<location filename="translatables.py" line="71"/>
<source>Replace</source>
<translation type="obsolete">Заменить</translation>
</message>
<message>
<location filename="translatables.py" line="72"/>
<source>Indent one level (tab)</source>
<translation type="obsolete">Сделать отступ</translation>
</message>
<message>
<location filename="translatables.py" line="73"/>
<source>Unindent one level (super + tab)</source>
<translation type="obsolete">Убрать отступ</translation>
</message>
<message>
<location filename="translatables.py" line="76"/>
<source>Press Alt + A to apply unsaved changes</source>
<translation type="obsolete">Нажмите Alt + A чтобы применить несохранённые изменения</translation>
</message>
<message>
<location filename="translatables.py" line="93"/>
<source>Apply</source>
<translation type="obsolete">Применить</translation>
</message>
<message>
<location filename="translatables.py" line="86"/>
<source>Tell me more about OpenSesame!</source>
<translation type="obsolete">Больше о "Сезам, откройся"</translation>
</message>
<message>
<location filename="translatables.py" line="213"/>
<source>No settings for %s</source>
<translation>Нет настроек для %s</translation>
</message>
<message>
<location filename="translatables.py" line="214"/>
<source>Settings for %s:</source>
<translation>Настройки для %s:</translation>
</message>
<message>
<location filename="translatables.py" line="196"/>
<source>Failed to parse the resolution. Expecting positive numeric values.</source>
<translation>Не получилось исследовать разрешение. Ожидается положительное число.</translation>
</message>
<message>
<location filename="translatables.py" line="44"/>
<source>Open %s</source>
<translation type="obsolete">Открыть %s</translation>
</message>
<message>
<location filename="translatables.py" line="49"/>
<source>%s help</source>
<translation type="obsolete">Помощь по %s</translation>
</message>
<message>
<location filename="translatables.py" line="43"/>
<source>Please enter a new name</source>
<translation type="obsolete">Введите новое имя</translation>
</message>
<message>
<location filename="translatables.py" line="222"/>
<source>Click to edit</source>
<translation>Нажмите, чтобы изменить</translation>
</message>
<message>
<location filename="translatables.py" line="197"/>
<source>Error: Command contains invalid characters</source>
<translation>Ошибка: Введены знаки, которые нельзя использовать</translation>
</message>
<message>
<location filename="translatables.py" line="215"/>
<source>Ready</source>
<translation>Готов к работе!</translation>
</message>
<message>
<location filename="translatables.py" line="107"/>
<source>Open file</source>
<translation>Открыть опыт</translation>
</message>
<message>
<location filename="translatables.py" line="211"/>
<source>Apply?</source>
<translation>Применить?</translation>
</message>
<message>
<location filename="translatables.py" line="212"/>
<source>Are you sure you want to apply the changes to the general script?</source>
<translation>Вы уверены, что хотите применить изменения в общем приказнике?</translation>
</message>
<message>
<location filename="translatables.py" line="36"/>
<source>Failed to parse script (see traceback in debug window): %s</source>
<translation type="obsolete">Не получилось исследовать приказник (см. окно отладки): %s</translation>
</message>
<message>
<location filename="translatables.py" line="185"/>
<source>Open</source>
<translation>Открыть</translation>
</message>
<message>
<location filename="translatables.py" line="187"/>
<source>And %d more file(s)</source>
<translation>И %d больше записей</translation>
</message>
<message>
<location filename="translatables.py" line="189"/>
<source><p>Are you sure you want to remove the following files from the file pool? This operation will only affect the OpenSesame file pool, not the original files on your disk.</p><p><b> - %s</b></p><p>%s</p></source>
<translation><p> Вы уверены что хотите удалить эти записи со склада? Это действие коснётся только склад в "Сезам, откройся", но не записи на Вашем внутреннем носителе.</p><p><b> - %s</b></p><p>%s</p></translation>
</message>
<message>
<location filename="translatables.py" line="121"/>
<source>All non-alphanumeric characters except underscores have been stripped</source>
<translation>Все знаки не являющиеся числами и буквами были зачищены</translation>
</message>
<message>
<location filename="translatables.py" line="122"/>
<source>The following characters are not allowed and have been stripped: double-quote ("), backslash (), and newline</source>
<translation></translation>
</message>
<message>
<location filename="translatables.py" line="145"/>
<source>"%s" is not a valid qtautoplugin control</source>
<translation>"%s" не подходит для qtautoplugin</translation>
</message>
<message>
<location filename="translatables.py" line="142"/>
<source>You provided an empty or invalid variable definition. For an example of a valid variable definition, open the variable wizard and select "Show example".</source>
<translation>Вы ввели пустое или недопустимое значение для определения переменной. Чтобы посмотреть пример, откройте доску переменных и нажмите "Показать пример".</translation>
</message>
<message>
<location filename="translatables.py" line="143"/>
<source>Apply weight</source>
<translation>Применить веса</translation>
</message>
<message>
<location filename="translatables.py" line="144"/>
<source>Which variable contains the weights?</source>
<translation>Какая переменная содержит веса?</translation>
</message>
<message>
<location filename="translatables.py" line="176"/>
<source>Add custom variable</source>
<translation>Добавить свою переменную</translation>
</message>
<message>
<location filename="translatables.py" line="134"/>
<source>Add an arbitrary variable by name</source>
<translation type="obsolete">Добавить случайную переменную</translation>
</message>
<message>
<location filename="translatables.py" line="135"/>
<source>Smart select</source>
<translation type="obsolete">Умный выбор</translation>
</message>
<message>
<location filename="translatables.py" line="136"/>
<source>Select all</source>
<translation type="obsolete">Выбрать всё</translation>
</message>
<message>
<location filename="translatables.py" line="137"/>
<source>Select all variables</source>
<translation type="obsolete">Выбрать все переменные</translation>
</message>
<message>
<location filename="translatables.py" line="138"/>
<source>Deselect all</source>
<translation type="obsolete">Отменить выбор всего</translation>
</message>
<message>
<location filename="translatables.py" line="139"/>
<source>Deselect all variables</source>
<translation type="obsolete">Отменить выбор всех переменных</translation>
</message>
<message>
<location filename="translatables.py" line="140"/>
<source>Include variables with missing values</source>
<translation type="obsolete">Добавить переменные с отсутствующими значениями</translation>
</message>
<message>
<location filename="translatables.py" line="141"/>
<source>Automatically detect and log all variables</source>
<translation type="obsolete">Приложение само находит и собирает данные по всем переменным</translation>
</message>
<message>
<location filename="translatables.py" line="142"/>
<source>Put quotes around values</source>
<translation type="obsolete">Взять значения в кавычки</translation>
</message>
<message>
<location filename="translatables.py" line="89"/>
<source>Failed to copy `opensesame` to `opensesame.py`, which is required for the multiprocess runner. Please copy the file manually, or select a different runner under Preferences.</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="translatables.py" line="178"/>
<source>'%s' is not a regular file and could not be added to the file pool.</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="translatables.py" line="139"/>
<source> starting at cycle <b>%s</b></source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="translatables.py" line="141"/>
<source> <font color='red'><b>(zero, negative, or unknown length)</b></font></source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="translatables.py" line="112"/>
<source>You have selected the <code>.opensesame</code> format. This means that the file pool has <i>not</i> been saved. To save the file pool along with your experiment, select the <code>.opensesame.tar.gz</code> format.</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="translatables.py" line="74"/>
<source>Image name "%s" is unknown or variably defined, using fallback image</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="translatables.py" line="75"/>
<source>Penwidth "%s" is unknown or variably defined, using 1</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="translatables.py" line="76"/>
<source>Color "%s" is unknown or variably defined, using placeholder color</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="translatables.py" line="77"/>
<source>X coordinate "%s" is unknown or variably defined, using display center</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="translatables.py" line="78"/>
<source>Y coordinate "%s" is unknown or variably defined, using display center</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="translatables.py" line="80"/>
<source>Width "%s" is unknown or variably defined, using 100</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="translatables.py" line="81"/>
<source>Height "%s" is unknown or variably defined, using 100</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="translatables.py" line="82"/>
<source>Scale "%s" is unknown or variably defined, using 1.0</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="translatables.py" line="87"/>
<source>An item with that name already exists.</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="translatables.py" line="88"/>
<source>An item name cannot be empty.</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="translatables.py" line="165"/>
<source>General options</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="translatables.py" line="163"/>
<source>Unused items</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="translatables.py" line="158"/>
<source>View controls</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="translatables.py" line="159"/>
<source>View script</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="translatables.py" line="160"/>
<source>Split view</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="translatables.py" line="201"/>
<source>Item name</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="translatables.py" line="202"/>
<source>Run if</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="translatables.py" line="177"/>
<source>Which variable do you wish to log?</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="translatables.py" line="116"/>
<source>Toggle pop-out</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="translatables.py" line="136"/>
<source><font color='red'>No item to run specified</font></source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="translatables.py" line="152"/>
<source>Edit element</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="translatables.py" line="155"/>
<source>Raise to front</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="translatables.py" line="156"/>
<source>Lower to bottom</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="translatables.py" line="148"/>
<source>Edit text</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="translatables.py" line="96"/>
<source>Loading extensions</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="translatables.py" line="97"/>
<source>Done</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="translatables.py" line="108"/>
<source>The following error occured while trying to save:<br/>%s</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="translatables.py" line="168"/>
<source>Edit run-if statement</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="translatables.py" line="169"/>
<source>Copy to clipboard</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="translatables.py" line="170"/>
<source>Paste from clipboard</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="translatables.py" line="171"/>
<source>Create linked copy</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="translatables.py" line="172"/>
<source>Create unlinked copy</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="translatables.py" line="174"/>
<source>Permanently delete all linked copies</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="translatables.py" line="175"/>
<source>Help</source>
<translation type="unfinished">Помощь</translation>
</message>
<message>
<location filename="translatables.py" line="164"/>
<source>Move to unused items</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="translatables.py" line="161"/>
<source>Select view</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="translatables.py" line="217"/>
<source>Set as item to run for %s</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="translatables.py" line="218"/>
<source>Insert into %s</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="translatables.py" line="219"/>
<source>Drop below %s</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="translatables.py" line="220"/>
<source>Permanently delete item</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="translatables.py" line="221"/>
<source>Are you sure you want to permanently delete <b>%s</b>? All linked copies of <b>%s</b> will be deleted. You will not be able to undo this.</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="translatables.py" line="73"/>
<source>Please confirm</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="translatables.py" line="79"/>
<source>Radius "%s" is unknown or variably defined, using 50</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="translatables.py" line="83"/>
<source>Font size "%s" is invalid or variably defined, using 18</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="translatables.py" line="84"/>
<source>Some properties of a Gabor patch are unknown or variably defined, using fallback image</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="translatables.py" line="85"/>
<source>Some properties of a noise patch are unknown or variably defined, using fallback image</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="translatables.py" line="86"/>
<source>Fixdot style "%s" is unknown or variably defined</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="translatables.py" line="147"/>
<source>You have multiple unlinked loggers. This can lead to messy log files.</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="translatables.py" line="199"/>
<source>Append linked copy</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="translatables.py" line="200"/>
<source>Append unlinked copy</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="translatables.py" line="203"/>
<source>Drop cancelled: Target not droppable</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="translatables.py" line="204"/>
<source>Drop cancelled: Recursion prevented</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="translatables.py" line="207"/>
<source>I know, do it!</source>
<translation type="unfinished"></translation>
</message>
</context>
<context>
<name>sketchpad_widget</name>
<message>
<location filename="sketchpad_widget.ui" line="14"/>
<source>Form</source>
<translation type="obsolete">Окно</translation>
</message>
<message>
<location filename="sketchpad_widget.ui" line="95"/>
<source>Line tool</source>
<translation type="obsolete">Прямая</translation>
</message>
<message>
<location filename="sketchpad_widget.ui" line="124"/>
<source>Arrow tool</source>
<translation type="obsolete">Стрелка</translation>
</message>
<message>
<location filename="sketchpad_widget.ui" line="150"/>
<source>Text tool</source>
<translation type="obsolete">Надпись</translation>
</message>
<message>
<location filename="sketchpad_widget.ui" line="176"/>
<source>Image tool</source>
<translation type="obsolete">Изображение</translation>
</message>
<message>
<location filename="sketchpad_widget.ui" line="202"/>
<source>Gabor patch tool</source>
<translation type="obsolete">Рисунок Габора</translation>
</message>
<message>
<location filename="sketchpad_widget.ui" line="228"/>
<source>Rectangle tool</source>
<translation type="obsolete">Прямоугольник</translation>
</message>
<message>
<location filename="sketchpad_widget.ui" line="254"/>
<source>Ellipse tool</source>
<translation type="obsolete">Овал</translation>
</message>
<message>
<location filename="sketchpad_widget.ui" line="280"/>
<source>Circle tool</source>
<translation type="obsolete">Круг</translation>
</message>
<message>
<location filename="sketchpad_widget.ui" line="306"/>
<source>Fixation dot tool</source>
<translation type="obsolete">Точка для привлеченя внимания</translation>
</message>
<message>
<location filename="sketchpad_widget.ui" line="335"/>
<source>Noise patch tool</source>
<translation type="obsolete">Шум</translation>
</message>
<message>
<location filename="sketchpad_widget.ui" line="424"/>
<source>Color</source>
<translation type="obsolete">Цвет</translation>
</message>
<message>
<location filename="sketchpad_widget.ui" line="490"/>
<source>Pen width</source>
<translation type="obsolete">Толщина ручки</translation>
</message>
<message>
<location filename="sketchpad_widget.ui" line="618"/>
<source>px</source>
<translation type="obsolete"> тчк</translation>
</message>
<message>
<location filename="sketchpad_widget.ui" line="400"/>
<source>Arrowhead size</source>
<translation type="obsolete">Размер стрелки</translation>
</message>
<message>
<location filename="sketchpad_widget.ui" line="444"/>
<source>Size of the arrowhead</source>
<translation type="obsolete">Размер стрелки</translation>
</message>
<message>
<location filename="sketchpad_widget.ui" line="506"/>
<source>Image scale</source>
<translation type="obsolete">Видимый размер</translation>
</message>
<message>
<location filename="sketchpad_widget.ui" line="513"/>
<source>Image scaling in %</source>
<translation type="obsolete">Видимый размер в %</translation>
</message>
<message>
<location filename="sketchpad_widget.ui" line="592"/>
<source>%</source>
<translation type="obsolete">%</translation>
</message>
<message>
<location filename="sketchpad_widget.ui" line="431"/>
<source>Center the object</source>
<translation type="obsolete">Поместить в середину</translation>
</message>
<message>
<location filename="sketchpad_widget.ui" line="434"/>
<source>Center object</source>
<translation type="obsolete">Поместить в середину</translation>
</message>
<message>
<location filename="sketchpad_widget.ui" line="393"/>
<source>Click on the sketchpad for options</source>
<translation type="obsolete">Настройки</translation>
</message>
<message>
<location filename="sketchpad_widget.ui" line="417"/>
<source>Show if</source>
<translation type="obsolete">Показать, если</translation>
</message>
<message>
<location filename="sketchpad_widget.ui" line="464"/>
<source>Check to draw filled objects</source>
<translation type="obsolete">Заполнять нарисованные тела</translation>
</message>
<message>
<location filename="sketchpad_widget.ui" line="467"/>
<source>Fill object</source>
<translation type="obsolete">Заполнить середину</translation>
</message>
<message>
<location filename="sketchpad_widget.ui" line="582"/>
<source>Zoom</source>
<translation type="obsolete">Приближение</translation>
</message>
<message>
<location filename="sketchpad_widget.ui" line="589"/>
<source>Zoom level in %</source>
<translation type="obsolete">Приближение в %</translation>
</message>
<message>
<location filename="sketchpad_widget.ui" line="608"/>
<source>Grid</source>
<translation type="obsolete">Решётка</translation>
</message>
<message>
<location filename="sketchpad_widget.ui" line="615"/>
<source>Grid size</source>
<translation type="obsolete">Размерность решётки</translation>
</message>
<message>
<location filename="sketchpad_widget.ui" line="631"/>
<source>Check to display the grid and enable snap-to-grid</source>
<translation type="obsolete">Показывает или прячет решётку на полотне</translation>
</message>
<message>
<location filename="sketchpad_widget.ui" line="634"/>
<source>Show grid</source>
<translation type="obsolete">Показать решётку</translation>
</message>
<message>
<location filename="sketchpad_widget.ui" line="656"/>
<source>(0, 0)</source>
<translation type="obsolete">(0, 0)</translation>
</message>
<message>
<location filename="sketchpad_widget.ui" line="706"/>
<source>[nr] objects are not shown, because their definition contains variables.</source>
<translation type="obsolete">[nr] не показаны, потому что они определены переменными</translation>
</message>
<message>
<location filename="sketchpad_widget.ui" line="725"/>
<source>Edit the script to see objects defined using variables</source>
<translation type="obsolete">Изменить приказник, чтобы увидеть предметы, заданные переменными</translation>
</message>
<message>
<location filename="sketchpad_widget.ui" line="728"/>
<source>Edit script</source>
<translation type="obsolete">Изменить приказник</translation>
</message>
<message>
<location filename="sketchpad_widget.ui" line="535"/>
<source>Parse a subset of HTML tags</source>
<translation type="obsolete">Проверить HTML</translation>
</message>
<message>
<location filename="sketchpad_widget.ui" line="538"/>
<source>Parse HTML subset</source>
<translation type="obsolete">Проверить HTML</translation>
</message>
</context>
<context>
<name>synth_widget</name>
<message>
<location filename="synth_widget.ui" line="14"/>
<source>Form</source>
<translation>Окно</translation>
</message>
<message>
<location filename="synth_widget.ui" line="75"/>
<source>Volume</source>
<translation>Громкость</translation>
</message>
<message>
<location filename="synth_widget.ui" line="104"/>
<source>Set the volume of the sound</source>
<translation>Установите громкость звука</translation>
</message>
<message>
<location filename="synth_widget.ui" line="107"/>
<source>%</source>
<translation type="obsolete">%</translation>
</message>
<message>
<location filename="synth_widget.ui" line="123"/>
<source>Pan</source>
<translation>Сторона выхода звука</translation>
</message>
<message>
<location filename="synth_widget.ui" line="152"/>
<source>Set the panning (left-right) of the sound</source>
<translation>Слева или справа издаётся звук</translation>
</message>
<message>
<location filename="synth_widget.ui" line="236"/>
<source>Set the decay ("fade out") of the sound</source>
<translation>Спад</translation>
</message>
<message>
<location filename="synth_widget.ui" line="223"/>
<source>Set the attack ("fade in") of the sound</source>
<translation>Наступление</translation>
</message>
<message>
<location filename="synth_widget.ui" line="203"/>
<source>Attack</source>
<translation>Наступление</translation>
</message>
<message>
<location filename="synth_widget.ui" line="213"/>
<source>Decay</source>
<translation>Спад</translation>
</message>
<message>
<location filename="synth_widget.ui" line="282"/>
<source>ms</source>
<translation type="obsolete"> мс</translation>
</message>
<message>
<location filename="synth_widget.ui" line="255"/>
<source>Length</source>
<translation>Длительность</translation>
</message>
<message>
<location filename="synth_widget.ui" line="262"/>
<source>Set the duration of the synth item. Expecting a duration in ms, 'sound' (to wait until the sound is finished playing), 'keypress', 'mouseclick', or a variable (e.g., '[synth_dur]').</source>
<translation type="unfinished">Длительность гудка. Должна быть в мс, "sound" (полная длительность), "keypress" (нажатие ключа), "mouseclick" (щелчок мыши) или переменная</translation>
</message>
<message>
<location filename="synth_widget.ui" line="265"/>
<source>sound</source>
<translation>Звук</translation>
</message>
<message>
<location filename="synth_widget.ui" line="272"/>
<source>Duration</source>
<translation>Длительность</translation>
</message>
<message>
<location filename="synth_widget.ui" line="279"/>
<source>Set the length of the sound</source>
<translation>Длина звука</translation>
</message>
<message>
<location filename="synth_widget.ui" line="295"/>
<source>Frequency<br /><small><i>in Hertz (Hz) or by note, like 'A1'</i></small></source>
<translation>Частота <br /><small><i>в герцах (Hz) или нота, например, 'A1'</i></small></translation>
</message>
<message>
<location filename="synth_widget.ui" line="302"/>
<source>The frequence of the sound. Expecting a numeric value (frequency in Hertz) a note (like 'C#2' and 'A1') or a variable (like '[freq]')</source>
<translation>Частота звука. Значение в герцах, нота ('C#2' или 'A1) или переменная (например, [freq])</translation>
</message>
<message>
<location filename="synth_widget.ui" line="305"/>
<source>A1</source>
<translation>Ля 1</translation>
</message>
<message>
<location filename="synth_widget.ui" line="345"/>
<source>Synth controls</source>
<translation>Настройки гудка</translation>
</message>
<message>
<location filename="synth_widget.ui" line="367"/>
<source>Sine wave</source>
<translation>Синусовидная волна</translation>
</message>
<message>
<location filename="synth_widget.ui" line="377"/>
<source>Sawtooth wave</source>
<translation>Зубчатая волна</translation>
</message>
<message>
<location filename="synth_widget.ui" line="387"/>
<source>Square wave</source>
<translation>Прямоугольная волна</translation>
</message>
<message>
<location filename="synth_widget.ui" line="397"/>
<source>White noise</source>
<translation>Белый шум</translation>
</message>
<message>
<location filename="synth_widget.ui" line="407"/>
<source>Generate a sine wav</source>
<translation>Создать синусовую волну</translation>
</message>
<message>
<location filename="synth_widget.ui" line="436"/>
<source>Generate a sawtooth wave</source>
<translation>Создать зубчатую волну</translation>
</message>
<message>
<location filename="synth_widget.ui" line="462"/>
<source>Generate a square wave</source>
<translation>Создать прямоугольную волну</translation>
</message>
<message>
<location filename="synth_widget.ui" line="488"/>
<source>Generate white noise</source>
<translation>Создать белые шумы</translation>
</message>
<message>
<location filename="synth_widget.ui" line="282"/>
<source> ms</source>
<translation type="unfinished"></translation>
</message>
</context>
<context>
<name>text_display</name>
<message>
<location filename="translatables.py" line="332"/>
<source>Visual stimuli</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="translatables.py" line="333"/>
<source><b>Tip:</b> Tip: Forms provide a more flexible way to present text stimuli and collect text responses.</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="translatables.py" line="334"/>
<source>Duration</source>
<translation type="unfinished">Длительность</translation>
</message>
<message>
<location filename="translatables.py" line="335"/>
<source>Expecting a value in milliseconds, 'keypress' or 'mouseclick'</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="translatables.py" line="336"/>
<source>Foreground color</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="translatables.py" line="339"/>
<source>Expecting a colorname (e.g., 'blue') or an HTML color (e.g., '#0000FF')</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="translatables.py" line="338"/>
<source>Background color</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="translatables.py" line="340"/>
<source>Font family</source>
<translation type="unfinished">Семейство начертаний</translation>
</message>
<message>
<location filename="translatables.py" line="341"/>
<source>The font family</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="translatables.py" line="342"/>
<source>Font size</source>
<translation type="unfinished">Размер начертания</translation>
</message>
<message>
<location filename="translatables.py" line="343"/>
<source>The font size</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="translatables.py" line="344"/>
<source> pt</source>
<translation type="unfinished"> </translation>
</message>
<message>
<location filename="translatables.py" line="345"/>
<source>Wrap line after</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="translatables.py" line="346"/>
<source>Maximum number of characters per line</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="translatables.py" line="347"/>
<source> characters</source>
<translation type="unfinished"> знаков</translation>
</message>
<message>
<location filename="translatables.py" line="349"/>
<source>Text alignment</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="translatables.py" line="350"/>
<source>Text</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="translatables.py" line="351"/>
<source>The text to be displayed</source>
<translation type="unfinished"></translation>
</message>
</context>
<context>
<name>text_input_dialog</name>
<message>
<location filename="text_input_dialog.ui" line="14"/>
<source>OpenSesame says ...</source>
<translation>"Сезам, откройся" сообщает</translation>
</message>
<message>
<location filename="text_input_dialog.ui" line="62"/>
<source>Message</source>
<translation>Сообщение</translation>
</message>
</context>
<context>
<name>toolbar_menu</name>
<message>
<location filename="translatables.py" line="284"/>
<source>Integrate menu and toolbar</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="translatables.py" line="285"/>
<source>Integrates the menu into the toolbar.</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="translatables.py" line="286"/>
<source>Integrates the menu into the toolbar</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="translatables.py" line="283"/>
<source>Menu</source>
<translation type="unfinished"></translation>
</message>
</context>
<context>
<name>touch_response</name>
<message>
<location filename="translatables.py" line="374"/>
<source>Response collection</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="translatables.py" line="375"/>
<source>Correct response</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="translatables.py" line="376"/>
<source>Set the correct response</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="translatables.py" line="377"/>
<source>Timeout</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="translatables.py" line="378"/>
<source>Expecting a value in milliseconds or 'infinite'</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="translatables.py" line="379"/>
<source>Number of columns</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="translatables.py" line="380"/>
<source>Specifies the number of columns</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="translatables.py" line="381"/>
<source>Number of rows</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="translatables.py" line="382"/>
<source>Specifies the number of rows</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="translatables.py" line="383"/>
<source>Show cursor</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="translatables.py" line="384"/>
<source>Show a mouse cursor (if supported on device)</source>
<translation type="unfinished"></translation>
</message>
</context>
<context>
<name>update_checker</name>
<message>
<location filename="translatables.py" line="361"/>
<source>Check for updates</source>
<translation type="unfinished">Проверить обновления</translation>
</message>
<message>
<location filename="translatables.py" line="362"/>
<source>Checks whether a new version of OpenSesame is available.</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="translatables.py" line="358"/>
<source>... and is sorry to say that the attempt to check for updates has failed. Please make sure that you are connected to the internet and try again later. If this problem persists, please visit <a href='http://www.cogsci.nl/opensesame'>http://www.cogsci.nl/opensesame</a> for more information.</source>
<translation type="unfinished">Проверка обновлений не удалась. Проверьте, подключены ли Вы к Сети. Или посетите <a href='http://www.cogsci.nl/opensesame'>http://www.cogsci.nl/opensesame</a></translation>
</message>
<message>
<location filename="translatables.py" line="359"/>
<source>... and is happy to report that a new version of OpenSesame (%s) is available at <a href='http://www.cogsci.nl/opensesame'>http://www.cogsci.nl/opensesame</a>!</source>
<translation type="unfinished">Рады сообщить Вам, что новое исполнение "Сезам, откройся" (%s) доступно на <a href='http://www.cogsci.nl/opensesame'>http://www.cogsci.nl/opensesame</a>!</translation>
</message>
<message>
<location filename="translatables.py" line="360"/>
<source> ... and is happy to report that you are running the most recent version of OpenSesame.</source>
<translation type="unfinished">Вы пользуетесь последним исполнением "Сезам, откройся"</translation>
</message>
</context>
<context>
<name>update_dialog</name>
<message>
<location filename="update_dialog.ui" line="62"/>
<source>OpenSesame has checked for updates ...</source>
<translation type="obsolete">"Сезам, откройся" проверило обновления</translation>
</message>
<message>
<location filename="update_dialog.ui" line="81"/>
<source>Check for updates on start-up</source>
<translation type="obsolete">Проверять обновления при запуске</translation>
</message>
</context>
<context>
<name>user_hint_widget</name>
<message>
<location filename="user_hint_widget.ui" line="14"/>
<source>Form</source>
<translation>Окно</translation>
</message>
<message>
<location filename="user_hint_widget.ui" line="20"/>
<source>A list of user hints</source>
<translation>Список пользовательский подсказок</translation>
</message>
<message>
<location filename="user_hint_widget.ui" line="23"/>
<source>User hints</source>
<translation>Пользовательские подсказки</translation>
</message>
<message>
<location filename="user_hint_widget.ui" line="36"/>
<source>Click to open script editor</source>
<translation>Нажмиет, чтобы изменить приказник</translation>
</message>
<message>
<location filename="user_hint_widget.ui" line="39"/>
<source>Edit script</source>
<translation type="obsolete">Изменить приказник</translation>
</message>
<message>
<location filename="user_hint_widget.ui" line="39"/>
<source>Hide</source>
<translation type="unfinished"></translation>
</message>
</context>
<context>
<name>variable_inspector</name>
<message>
<location filename="variable_inspector.ui" line="14"/>
<source>Form</source>
<translation type="unfinished">Окно</translation>
</message>
<message>
<location filename="variable_inspector.ui" line="52"/>
<source>Variable inspector</source>
<translation type="obsolete">Проверить переменные</translation>
</message>
<message>
<location filename="variable_inspector.ui" line="36"/>
<source>Enter a filter</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="variable_inspector.ui" line="43"/>
<source>Clear filter</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="variable_inspector.ui" line="69"/>
<source>Help</source>
<translation type="unfinished">Помощь</translation>
</message>
<message>
<location filename="variable_inspector.ui" line="123"/>
<source>Variable</source>
<translation type="unfinished">Переменная</translation>
</message>
<message>
<location filename="variable_inspector.ui" line="128"/>
<source>Value</source>
<translation type="unfinished">Значение</translation>
</message>
<message>
<location filename="variable_inspector.ui" line="133"/>
<source>In item</source>
<translation type="unfinished">В составляющей</translation>
</message>
</context>
<context>
<name>video_player</name>
<message>
<location filename="translatables.py" line="31"/>
<source>Visual stimuli</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="translatables.py" line="32"/>
<source>Video file</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="translatables.py" line="33"/>
<source>A video file</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="translatables.py" line="34"/>
<source>Resize to fit screen</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="translatables.py" line="35"/>
<source>Resize the video to fit the full screen</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="translatables.py" line="38"/>
<source>Duration</source>
<translation type="unfinished">Длительность</translation>
</message>
<message>
<location filename="translatables.py" line="37"/>
<source>Expecting a value in milliseconds, 'keypress' or 'mouseclick'</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="translatables.py" line="39"/>
<source>Frame duration in milliseconds</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="translatables.py" line="40"/>
<source>ms</source>
<translation type="unfinished"> мс</translation>
</message>
</context>
<context>
<name>webbrowser_widget</name>
<message>
<location filename="webbrowser_widget.ui" line="14"/>
<source>Form</source>
<translation>Окно</translation>
</message>
<message>
<location filename="webbrowser_widget.ui" line="41"/>
<source>Go back</source>
<translation>Назад</translation>
</message>
<message>
<location filename="webbrowser_widget.ui" line="54"/>
<source>Open OpenSesame documentation area</source>
<translation>Открыть руководство "Сезам, откройся"</translation>
</message>
<message>
<location filename="webbrowser_widget.ui" line="67"/>
<source>Open cogsci.nl forum</source>
<translation>Открыть сообщество на cogsci.nl</translation>
</message>
<message>
<location filename="webbrowser_widget.ui" line="80"/>
<source>Address</source>
<translation>Местоположение</translation>
</message>
<message>
<location filename="webbrowser_widget.ui" line="101"/>
<source>Progress</source>
<translation>Продвижение</translation>
</message>
<message>
<location filename="webbrowser_widget.ui" line="104"/>
<source>50%</source>
<translation>50/100</translation>
</message>
</context>
<context>
<name>widgetFind</name>
<message>
<location filename="findWidget.ui" line="14"/>
<source>Form</source>
<translation>Окно</translation>
</message>
<message>
<location filename="findWidget.ui" line="23"/>
<source>Replace:</source>
<translation>Заменить:</translation>
</message>
<message>
<location filename="findWidget.ui" line="33"/>
<source>Find:</source>
<translation>Найти:</translation>
</message>
<message>
<location filename="findWidget.ui" line="49"/>
<source>Search</source>
<translation>Поиск</translation>
</message>
<message>
<location filename="findWidget.ui" line="61"/>
<source>Replace</source>
<translation>Заменить</translation>
</message>
<message>
<location filename="findWidget.ui" line="73"/>
<source>Replace all</source>
<translation>Заменить всё</translation>
</message>
<message>
<location filename="findWidget.ui" line="94"/>
<source>Case sensitive</source>
<translation>Чувствительно к заглавным буквам</translation>
</message>
<message>
<location filename="findWidget.ui" line="101"/>
<source>Match whole words</source>
<translation>Совпадение целых слов</translation>
</message>
</context>
<context>
<name>widgetPrefs</name>
<message>
<location filename="prefsWidget.ui" line="14"/>
<source>Form</source>
<translation>Окно</translation>
</message>
<message>
<location filename="prefsWidget.ui" line="183"/>
<source>Show 80 character word-wrap marker</source>
<translation>Показывать границу 80 знаков</translation>
</message>
<message>
<location filename="prefsWidget.ui" line="78"/>
<source>Tab width</source>
<translation>Ширина отступа строки</translation>
</message>
<message>
<location filename="prefsWidget.ui" line="40"/>
<source> characters</source>
<translation> знаков</translation>
</message>
<message>
<location filename="prefsWidget.ui" line="47"/>
<source>Font family</source>
<translation>Семейство начертаний</translation>
</message>
<message>
<location filename="prefsWidget.ui" line="141"/>
<source>Show whitespace</source>
<translation>Помечать отступ строки</translation>
</message>
<message>
<location filename="prefsWidget.ui" line="92"/>
<source>Show line numbers</source>
<translation>Помечать числа строк</translation>
</message>
<message>
<location filename="prefsWidget.ui" line="23"/>
<source>Enable word wrapping</source>
<translation>Перенос слов</translation>
</message>
<message>
<location filename="prefsWidget.ui" line="148"/>
<source>Enable block folding</source>
<translation>Разрешить сворачивание абзацев</translation>
</message>
<message>
<location filename="prefsWidget.ui" line="169"/>
<source>Enable automatic completion</source>
<translation>Разрешить приложению заканчивать строки</translation>
</message>
<message>
<location filename="prefsWidget.ui" line="71"/>
<source>Show end-of-lines</source>
<translation>Помечать концы строк</translation>
</message>
<message>
<location filename="prefsWidget.ui" line="54"/>
<source>Show indentation</source>
<translation>Помечать начало абзаца</translation>
</message>
<message>
<location filename="prefsWidget.ui" line="106"/>
<source>Font size</source>
<translation>Размер начертания</translation>
</message>
<message>
<location filename="prefsWidget.ui" line="64"/>
<source> pt</source>
<translation> </translation>
</message>
<message>
<location filename="prefsWidget.ui" line="113"/>
<source>Highlight current line</source>
<translation>Подсветить текущую строку</translation>
</message>
<message>
<location filename="prefsWidget.ui" line="120"/>
<source>Highlight matching brackets</source>
<translation>Показать совпадающие скобки</translation>
</message>
<message>
<location filename="prefsWidget.ui" line="85"/>
<source>Enable automatic indentation</source>
<translation>Включить самодеятельные скобки</translation>
</message>
<message>
<location filename="prefsWidget.ui" line="162"/>
<source>Color scheme</source>
<translation>Набор цветов</translation>
</message>
<message>
<location filename="prefsWidget.ui" line="30"/>
<source>A color scheme for the editor component</source>
<translation>Цветовое исполнение приложения</translation>
</message>
<message>
<location filename="prefsWidget.ui" line="37"/>
<source>The tab width for the editor component</source>
<translation>Ширина отступа строки</translation>
</message>
<message>
<location filename="prefsWidget.ui" line="61"/>
<source>The font size for the editor component</source>
<translation>Размер начертания</translation>
</message>
<message>
<location filename="prefsWidget.ui" line="99"/>
<source>The font font the editor component</source>
<translation>Вид начертания </translation>
</message>
<message>
<location filename="prefsWidget.ui" line="127"/>
<source>Comment shortcut</source>
<translation>Замечание по значку</translation>
</message>
<message>
<location filename="prefsWidget.ui" line="134"/>
<source>A keyboard shortcut, such as Ctrl+Shift+M</source>
<translation>Горячий ключ вида Ctrl+Shift+M</translation>
</message>
<message>
<location filename="prefsWidget.ui" line="155"/>
<source>A keyboard shortcut, such as Ctrl+M</source>
<translation>Горячий ключ вида Ctrl+M</translation>
</message>
<message>
<location filename="prefsWidget.ui" line="176"/>
<source>Uncomment shortcut</source>
<translation>Убрать замечание по значку</translation>
</message>
<message>
<location filename="prefsWidget.ui" line="190"/>
<source>Validate content</source>
<translation>Проверять содержимое</translation>
</message>
</context>
<context>
<name>widget_backend_settings</name>
<message>
<location filename="backend_settings.ui" line="14"/>
<source>Form</source>
<translation>Окно</translation>
</message>
<message>
<location filename="backend_settings.ui" line="53"/>
<source>ICON</source>
<translation>Значок</translation>
</message>
<message>
<location filename="backend_settings.ui" line="60"/>
<source><b>Back-end settings</b><br />
Various settings related to the control of the display, sound, and input devices</source>
<translation><b>Настройки движка</b><br />
Настройки для полотна, звука и устройств ввода</translation>
</message>
<message>
<location filename="backend_settings.ui" line="71"/>
<source>Canvas</source>
<translation>Полотно</translation>
</message>
<message>
<location filename="backend_settings.ui" line="186"/>
<source>TextLabel</source>
<translation>Надпись</translation>
</message>
<message>
<location filename="backend_settings.ui" line="96"/>
<source>Keyboard</source>
<translation>Ключница</translation>
</message>
<message>
<location filename="backend_settings.ui" line="121"/>
<source>Mouse</source>
<translation>Мышь</translation>
</message>
<message>
<location filename="backend_settings.ui" line="146"/>
<source>Sampler</source>
<translation>Звукозапись</translation>
</message>
<message>
<location filename="backend_settings.ui" line="171"/>
<source>Synth</source>
<translation>Гудок</translation>
</message>
</context>
<context>
<name>widget_credits</name>
<message>
<location filename="credits_widget.ui" line="20"/>
<source>Form</source>
<translation>Окно</translation>
</message>
<message>
<location filename="credits_widget.ui" line="78"/>
<source>Visit Facebook page</source>
<translation>Посетить страницу в "Фэйсбуке"</translation>
</message>
<message>
<location filename="credits_widget.ui" line="81"/>
<source>F</source>
<translation> </translation>
</message>
<message>
<location filename="credits_widget.ui" line="91"/>
<source>Visit Twitter page</source>
<translation>Посетите страницу в "Твиттере"</translation>
</message>
<message>
<location filename="credits_widget.ui" line="94"/>
<source>T</source>
<translation> </translation>
</message>
<message>
<location filename="credits_widget.ui" line="104"/>
<source>Visit cogsci.nl</source>
<translation>Посетить cogsci.nl</translation>
</message>
<message>
<location filename="credits_widget.ui" line="107"/>
<source>H</source>
<translation> </translation>
</message>
<message>
<location filename="credits_widget.ui" line="114"/>
<source><html><head/><body><p>COGSCIdotNL // cognitive science and more</p></body></html></source>
<translation><html><head/><body><p>COGSCIdotNL // Науки о познании и другое</p></body></html></translation>
</message>
<message>
<location filename="credits_widget.ui" line="121"/>
<source><a href="http://osdoc.cogsci.nl/contribute/">Contribute</a></source>
<translation><a href="http://osdoc.cogsci.nl/contribute/">Участвовать в разработке</a></translation>
</message>
<message>
<location filename="credits_widget.ui" line="131"/>
<source><a href="http://osdoc.cogsci.nl/donate/">Donate</a></source>
<translation><a href="http://osdoc.cogsci.nl/donate/">Сделать пожертвование</a></translation>
</message>
<message encoding="UTF-8">
<location filename="credits_widget.ui" line="179"/>
<source>OpenSesame [version] [codename]
Copyright Sebastiaan Mathôt (2010-2014)</source>
<translation type="obsolete">"Сезам, откройся" [version] [codename]
Права принадлежат Себастьяну Матоту (Sebastiaan Mathôt) (2010-2014)
Перевод: Владимир Косоногов (vladimirkosonogov@yandex.ru)</translation>
</message>
<message encoding="UTF-8">
<location filename="credits_widget.ui" line="179"/>
<source>OpenSesame [version] [codename]
Copyright Sebastiaan Mathôt (2010-2015)</source>
<translation type="unfinished"></translation>
</message>
</context>
<context>
<name>widget_general_script_editor</name>
<message>
<location filename="general_script_editor.ui" line="14"/>
<source>Form</source>
<translation>Окно</translation>
</message>
<message>
<location filename="general_script_editor.ui" line="44"/>
<source>ICON</source>
<translation>Значок</translation>
</message>
<message>
<location filename="general_script_editor.ui" line="57"/>
<source><b>General script editor</b><br />
Edit your experiment in script form</source>
<translation><b>Общий правщик приказника</b><br />
Изменяет опыт через приказник</translation>
</message>
</context>
<context>
<name>widget_start_new</name>
<message>
<location filename="start_new_widget.ui" line="20"/>
<source>Form</source>
<translation>Окно</translation>
</message>
<message>
<location filename="start_new_widget.ui" line="149"/>
<source><h3>New</h3></source>
<translation><h3>Новый</h3></translation>
</message>
<message>
<location filename="start_new_widget.ui" line="172"/>
<source><h3>Recent</h3></source>
<translation><h3>Недавние</h3></translation>
</message>
<message>
<location filename="start_new_widget.ui" line="189"/>
<source><h3>Open</h3></source>
<translation><h3>Открыть</h3></translation>
</message>
<message>
<location filename="start_new_widget.ui" line="196"/>
<source>Open an existing experiment</source>
<translation>Открыть существующий опыт</translation>
</message>
<message>
<location filename="start_new_widget.ui" line="203"/>
<source><h3>Help</h3></source>
<translation><h3>Помощь</h3></translation>
</message>
<message>
<location filename="start_new_widget.ui" line="216"/>
<source>Visit the documentation site</source>
<translation>Посетить страницу с руководством</translation>
</message>
<message>
<location filename="start_new_widget.ui" line="223"/>
<source>Ask a question on the forum</source>
<translation>Задать вопрос в сетевом сообществе</translation>
</message>
<message>
<location filename="start_new_widget.ui" line="248"/>
<source>ICON</source>
<translation>Значок</translation>
</message>
<message>
<location filename="start_new_widget.ui" line="119"/>
<source><b>Get started!</b><br />
<small><i>Select an item in the overview area to start right away</i></small></source>
<translation><b>Начнём!</b><br />
<small><i>Добавьте составляющую в обзорный лист, чтобы начать прямо сейчас</i></small></translation>
</message>
<message>
<location filename="start_new_widget.ui" line="255"/>
<source><b>New expriment</b><br />
<small><i>Click 'cancel' or close this tab to resume your current experiment</i></small></source>
<translation><b>Новый опыт</b><br />
<small><i>Нажмите "Отменить" или закройте эту вкладку, чтобы продолжить старый опыт</i></small></translation>
</message>
<message>
<location filename="start_new_widget.ui" line="272"/>
<source>Cancel</source>
<translation>Отменить</translation>
</message>
</context>
</TS>
| SCgeeker/OpenSesame | resources/ts/ru_RU.ts | TypeScript | gpl-3.0 | 211,711 |
/////////////////////////////////////////////////////////////////////////////
//
// Project ProjectForge Community Edition
// www.projectforge.org
//
// Copyright (C) 2001-2014 Kai Reinhard (k.reinhard@micromata.de)
//
// ProjectForge is dual-licensed.
//
// This community edition is free software; you can redistribute it and/or
// modify it under the terms of the GNU General Public License as published
// by the Free Software Foundation; version 3 of the License.
//
// This community edition is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General
// Public License for more details.
//
// You should have received a copy of the GNU General Public License along
// with this program; if not, see http://www.gnu.org/licenses/.
//
/////////////////////////////////////////////////////////////////////////////
package org.projectforge.web.common;
import org.apache.wicket.validation.IValidatable;
import org.apache.wicket.validation.ValidationError;
import org.apache.wicket.validation.validator.AbstractValidator;
import org.projectforge.common.StringHelper;
public class PhoneNumberValidator extends AbstractValidator<String>
{
private static final long serialVersionUID = 6488923290863235755L;
@Override
protected void onValidate(final IValidatable<String> validatable)
{
if (StringHelper.checkPhoneNumberFormat(validatable.getValue()) == false) {
validatable.error(new ValidationError().addMessageKey("address.error.phone.invalidFormat"));
}
}
}
| linqingyicen/projectforge-webapp | src/main/java/org/projectforge/web/common/PhoneNumberValidator.java | Java | gpl-3.0 | 1,626 |
import fs from 'fs';
import path from 'path';
import Wxr from 'wxr';
import Base from './base';
const NOT_SAFE_IN_XML = /[^\x09\x0A\x0D\x20-\xFF\x85\xA0-\uD7FF\uE000-\uFDCF\uFDE0-\uFFFD]/gm;
export default class extends Base {
constructor(...args) {
super(...args);
this.outputFile = path.join(think.RUNTIME_PATH, 'output_wordpress.xml');
}
async run() {
let importer = new Wxr();
let posts = await this.getPosts();
for(let post of posts) {
post.content = post.content.replace(NOT_SAFE_IN_XML, '');
post.summary = post.summary.replace(NOT_SAFE_IN_XML, '');
importer.addPost({
id: post.id,
title: post.title,
date: think.datetime(post.create_time),
contentEncoded: post.content,
excerptEncoded: post.summary,
categories: post.cate
})
}
let cateList = await this.model('cate').select();
for(let cate of cateList) {
importer.addCategory({
id: cate.id,
title: cate.name,
slug: cate.pathname
});
}
try {
fs.writeFileSync(
this.outputFile,
importer.stringify()
)
return this.outputFile;
} catch (e) {
throw new Error(e);
}
}
}
| Genffy/Blog.Genffy | src/admin/service/export/wordpress.js | JavaScript | gpl-3.0 | 1,230 |
/****************************************************************************
**
** Copyright (C) 2016 The Qt Company Ltd.
** Contact: https://www.qt.io/licensing/
**
** This file is part of Qt Creator.
**
** Commercial License Usage
** Licensees holding valid commercial Qt licenses may use this file in
** accordance with the commercial license agreement provided with the
** Software or, alternatively, in accordance with the terms contained in
** a written agreement between you and The Qt Company. For licensing terms
** and conditions see https://www.qt.io/terms-conditions. For further
** information use the contact form at https://www.qt.io/contact-us.
**
** GNU General Public License Usage
** Alternatively, this file may be used under the terms of the GNU
** General Public License version 3 as published by the Free Software
** Foundation with exceptions as appearing in the file LICENSE.GPL3-EXCEPT
** included in the packaging of this file. Please review the following
** information to ensure the GNU General Public License requirements will
** be met: https://www.gnu.org/licenses/gpl-3.0.html.
**
****************************************************************************/
#include "workarounds.h"
#include <QPalette>
#include <utils/stylehelper.h>
QPalette panelPalette(const QPalette &oldPalette, bool lightColored)
{
QColor color = Utils::StyleHelper::panelTextColor(lightColored);
QPalette pal = oldPalette;
pal.setBrush(QPalette::All, QPalette::WindowText, color);
pal.setBrush(QPalette::All, QPalette::ButtonText, color);
pal.setBrush(QPalette::All, QPalette::Foreground, color);
color.setAlpha(100);
pal.setBrush(QPalette::Disabled, QPalette::WindowText, color);
pal.setBrush(QPalette::Disabled, QPalette::ButtonText, color);
pal.setBrush(QPalette::Disabled, QPalette::Foreground, color);
return pal;
}
| Philips14171/qt-creator-opensource-src-4.2.1 | src/plugins/valgrind/workarounds.cpp | C++ | gpl-3.0 | 1,874 |
/* webui functions */
function model_server(data) {
var self = this;
$.extend(self, data);
self.mem_utilization = ko.computed(function() {
return '{0} / {1}'.format(parseInt(self.memory), self.java_xmx);
})
self.capacity = ko.computed(function() {
return '{0} / {1}'.format(self.players_online, self.max_players);
})
self.overextended = ko.computed(function() {
try {
return parseInt(self.memory) > parseInt(self.java_xmx)
} catch (err) {
return false;
}
})
self.online_pct = ko.computed(function() {
return parseInt((self.players_online / self.max_players) * 100)
})
self.memory_pct = ko.computed(function() {
return parseInt((parseInt(self.memory) / parseInt(self.java_xmx)) * 100)
})
if (self.eula == null)
self.eula_ok = true;
else if (self.eula.toLowerCase() == 'false')
self.eula_ok = false;
else
self.eula_ok = true;
}
function model_property(server_name, option, value, section, new_prop) {
var self = this;
self.option = ko.observable(option);
self.val = ko.observable(value);
self.section = ko.observable(section);
self.success = ko.observable(null);
self.newly_created = ko.observable(new_prop || false);
self.type = 'textbox';
self.check_type = function(option, section) {
if (section) {
var fixed = [
{section: 'java', option: 'java_debug', type: 'truefalse'},
{section: 'onreboot', option: 'restore', type: 'truefalse'},
{section: 'onreboot', option: 'start', type: 'truefalse'},
{section: 'crontabs', option: 'archive_interval', type: 'interval'},
{section: 'crontabs', option: 'backup_interval', type: 'interval'},
{section: 'crontabs', option: 'restart_interval', type: 'interval'}
]
$.each(fixed, function(i,v) {
if (v.section == section && v.option == option){
self.type = v.type;
self.id = v.id;
return false;
}
})
} else {
var fixed = [
{option: 'pvp', type: 'truefalse'},
{option: 'allow-nether', type: 'truefalse'},
{option: 'spawn-animals', type: 'truefalse'},
{option: 'enable-query', type: 'truefalse'},
{option: 'generate-structures', type: 'truefalse'},
{option: 'hardcore', type: 'truefalse'},
{option: 'allow-flight', type: 'truefalse'},
{option: 'online-mode', type: 'truefalse'},
{option: 'spawn-monsters', type: 'truefalse'},
{option: 'force-gamemode', type: 'truefalse'},
{option: 'spawn-npcs', type: 'truefalse'},
{option: 'snooper-enabled', type: 'truefalse'},
{option: 'white-list', type: 'truefalse'},
{option: 'enable-rcon', type: 'truefalse'},
{option: 'announce-player-achievements', type: 'truefalse'},
{option: 'enable-command-block', type: 'truefalse'}
]
$.each(fixed, function(i,v) {
if (v.option == option){
self.type = v.type;
return false;
}
})
}
if (self.type == 'truefalse') {
if (self.val().toLowerCase() == 'true')
self.val(true);
else
self.val(false);
}
}
self.toggle = function(model, eventobj) {
$(eventobj.currentTarget).find('input').iCheck('destroy');
if (self.val() == true) {
$(eventobj.currentTarget).find('input').iCheck('uncheck');
self.val(false);
} else if (self.val() == false) {
var target = $(eventobj.currentTarget).find('input');
$(target).iCheck({
checkboxClass: 'icheckbox_minimal-grey',
radioClass: 'iradio_minimal-grey',
increaseArea: '40%' // optional
});
$(target).iCheck('check');
self.val(true);
}
}
self.change_select = function(model, eventobj) {
var new_value = $(eventobj.currentTarget).val();
var params = {
server_name: server_name,
cmd: 'modify_config',
option: self.option(),
value: new_value,
section: self.section()
}
$.getJSON('/server', params)
}
self.val.subscribe(function(value) {
function flash_success(data) {
if (data.result == 'success') {
self.newly_created(false);
self.success(true);
setTimeout(function() {self.success(null)}, 5000)
} else {
self.success(false);
}
}
function flash_failure(data) {
self.success(false);
}
var params = {
server_name: server_name,
cmd: 'modify_config',
option: self.option(),
value: self.val(),
section: self.section()
}
$.getJSON('/server', params).then(flash_success, flash_failure)
}, self)
self.check_type(option, section);
self.id = '{0}_{1}'.format((section ? section : ''), option);
}
function model_logline(str) {
var self = this;
self.timestamp = '';
self.entry = ansi_up.ansi_to_html(ansi_up.linkify(ansi_up.escape_for_html(str)));
}
function model_profile(data) {
var self = this;
$.extend(self, data);
self.description = ko.observable(self.desc);
self.success = ko.observable(null);
self.description.subscribe(function(value) {
var params = {
cmd: 'modify_profile',
option: 'desc',
value: self.description(),
section: self.profile
}
$.getJSON('/host', params)
}, self)
}
function webui() {
var self = this;
self.server = ko.observable({});
self.page = ko.observable();
self.profile = ko.observable({});
self.server.extend({ notify: 'always' });
self.page.extend({ notify: 'always' });
self.refresh_rate = 100;
self.refresh_loadavg = 2000;
self.dashboard = {
whoami: ko.observable(''),
group: ko.observable(),
groups: ko.observableArray([]),
memfree: ko.observable(),
uptime: ko.observable(),
servers_up: ko.observable(0),
disk_usage: ko.observable(),
disk_usage_pct: ko.observable(),
pc_permissions: ko.observable(),
pc_group: ko.observable(),
git_hash: ko.observable(),
stock_profiles: ko.observableArray([]),
base_directory: ko.observable()
}
self.logs = {
reversed: ko.observable(true)
}
self.load_averages = {
one: [0],
five: [0],
fifteen: [0],
autorefresh: ko.observable(true),
options: {
series: {
lines: {
show: true,
fill: .3
},
shadowSize: 0
},
yaxis: {
min: 0,
max: 1,
axisLabel: "Load Average for last minute",
axisLabelUseCanvas: true,
axisLabelFontSizePixels: 12,
axisLabelFontFamily: 'Verdana, Arial',
axisLabelPadding: 3
},
xaxis: { min: 0, max: 30, show: false },
grid: {
borderWidth: 0,
hoverable: false
},
legend: {
labelBoxBorderColor: "#858585",
position: "ne"
}
}
}
self.vmdata = {
pings: ko.observableArray(),
archives: ko.observableArray(),
increments: ko.observableArray(),
importable: ko.observableArray(),
profiles: ko.observableArray(),
sp: ko.observableArray(),
sc: ko.observableArray(),
logs: ko.observableArray()
}
self.import_information = ko.observable();
self.profile_type = ko.observable();
self.summary = {
backup: {
most_recent: ko.computed(function() {
try { return self.vmdata.increments()[0].timestamp } catch (e) { return 'None' }
}),
first: ko.computed(function() {
try { return self.vmdata.increments()[self.vmdata.increments().length-1].timestamp } catch (e) { return 'None' }
}),
cumulative: ko.computed(function() {
try { return self.vmdata.increments()[self.vmdata.increments().length-1].cumulative_size } catch (e) { return '0 MB' }
})
},
archive: {
most_recent: ko.computed(function() {
try { return self.vmdata.archives()[0].friendly_timestamp } catch (e) { return 'None' }
}),
first: ko.computed(function() {
try { return self.vmdata.archives()[self.vmdata.archives().length-1].friendly_timestamp } catch (e) { return 'None' }
}),
cumulative: ko.computed(function() {
return bytes_to_mb(self.vmdata.archives().sum('size'))
})
},
owner: ko.observable(''),
group: ko.observable(''),
du_cwd: ko.observable(0),
du_bwd: ko.observable(0),
du_awd: ko.observable(0)
}
self.pruning = {
increments: {
user_input: ko.observable(''),
remove_count: ko.observable(0),
step: '',
space_reclaimed: ko.observable(0.0)
},
archives: {
user_input: ko.observable(),
filename: ko.observable(),
remove_count: ko.observable(0),
archives_to_delete: '',
space_reclaimed: ko.observable(0.0)
},
profiles: {
profile: ko.observable()
}
}
/* beginning root functions */
self.save_state = function() {
var state_to_save = {
page: self.page(),
server: JSON.stringify(self.server()),
profile: self.profile()
}
history.pushState(state_to_save, 'MineOS Web UI');
}
self.restore_state = function(state) {
var server = new model_server(JSON.parse(state.server));
$('.container-fluid').hide();
if ($.isEmptyObject(server)) {
self.server({})
$('#dashboard').show();
} else {
self.server(server);
self.page(state.page);
$('.container-fluid').hide();
$('#{0}'.format(self.page())).show();
}
}
self.toggle_loadaverages = function() {
if (self.load_averages.autorefresh())
self.load_averages.autorefresh(false);
else {
self.load_averages.autorefresh(true);
self.redraw.chart();
}
}
self.reset_logs = function() {
self.vmdata.logs([]);
$.getJSON('/logs', {server_name: self.server().server_name, reset: true}).then(self.refresh.logs);
}
self.select_server = function(model) {
self.server(model);
if (self.page() == 'dashboard')
self.show_page('server_status');
else
self.ajax.refresh(null);
}
self.select_profile = function(model) {
self.profile(model);
self.show_page('profile_view');
}
self.new_property = function(vm, event) {
var config = $(event.target).data('config');
if (config == 'sp') {
self.vmdata.sp.push(new model_property(self.server().server_name, null, null, null, true))
} else if (config == 'sc') {
self.vmdata.sc.push(new model_property(self.server().server_name, null, null, null, true))
}
}
self.show_page = function(vm, event) {
try {
self.page($(event.currentTarget).data('page'));
} catch (e) {
self.page(vm);
}
$('.container-fluid').hide();
$('#{0}'.format(self.page())).show();
self.save_state();
}
self.extract_required = function(required, element, vm) {
var params = {};
$.each(required, function(i,v) {
//checks if required param in DOM element
//then falls back to vm
var required_param = v.replace(/\s/g, '');
if (required_param in $(element).data())
params[required_param] = $(element).data(required_param);
else if (required_param in vm)
params[required_param] = vm[required_param];
})
return params;
}
self.remember_import = function(model, eventobj) {
var target = $(eventobj.currentTarget);
var params = {
path: model['path'],
filename: model['filename']
}
$.extend(params, self.extract_required(['path','filename'], target, model));
self.import_information(params);
}
self.import_server = function(vm, eventobj) {
var params = self.import_information();
params['server_name'] = $('#import_server_modal').find('input[name="newname"]').val();
$.getJSON('/import_server', params).then(self.ajax.received, self.ajax.lost)
.then(self.show_page('dashboard'));
}
self.prune_archives = function(vm, eventobj) {
var params = {
cmd: 'prune_archives',
server_name: self.server().server_name,
filename: self.pruning.archives.archives_to_delete
}
$.getJSON('/server', params).then(self.ajax.received, self.ajax.lost)
.then(function() {self.ajax.refresh(null)});
}
self.prune_increments = function(vm, eventobj) {
var params = {
cmd: 'prune',
server_name: self.server().server_name,
step: self.pruning.increments.step
}
$.getJSON('/server', params).then(self.ajax.received, self.ajax.lost)
.then(function() {self.ajax.refresh(null)});
}
self.remember_profile = function(model, eventobj) {
self.pruning.profiles.profile(model.profile);
}
self.prune_profile = function(vm, eventobj) {
var params = {
cmd: 'remove_profile',
profile: self.pruning.profiles.profile
}
$.getJSON('/host', params).then(self.ajax.received, self.ajax.lost)
.then(function() {self.ajax.refresh(null)});
}
self.delete_server = function(vm, eventobj) {
var params = {
server_name: self.server().server_name
}
var unchecked = $('#delete_confirmations input[type=checkbox]').filter(function(i,v) {
return !$(v).prop('checked');
})
if (unchecked.length == 0) {
$.getJSON('/delete_server', params)
.then(self.ajax.received, self.ajax.lost)
.done(function(){ self.show_page('dashboard') },
function(){})
} else {
$.gritter.add({
text: 'No action taken; must confirm all content will be deleted to continue.',
sticky: false,
time: '3000',
class_name: 'gritter-warning'
});
}
}
self.change_group = function(vm, eventobj) {
var params = {
group: $(eventobj.currentTarget).val(),
server_name: self.server().server_name
}
$.getJSON('/change_group', params).then(self.ajax.received, self.ajax.lost)
}
self.change_pc_group = function(vm, eventobj) {
var params = {
group: $(eventobj.currentTarget).val()
}
$.getJSON('/change_pc_group', params).then(self.ajax.received, self.ajax.lost)
}
self.command = function(vm, eventobj) {
var target = $(eventobj.currentTarget);
var cmd = $(target).data('cmd');
var required = $(target).data('required').split(',');
var params = {cmd: cmd};
$.extend(params, self.extract_required(required, target, vm));
if (required.indexOf('force') >= 0)
params['force'] = true;
//console.log(params)
var refresh_time = parseInt($(target).data('refresh'));
if (required.indexOf('server_name') >= 0) {
$.extend(params, {server_name: self.server().server_name});
$.getJSON('/server', params).then(self.ajax.received, self.ajax.lost)
.then(function() {self.ajax.refresh(refresh_time)});
} else {
$.getJSON('/host', params).then(self.ajax.received, self.ajax.lost)
.then(function() {self.ajax.refresh(refresh_time)});
}
}
self.page.subscribe(function(page){
var server_name = self.server().server_name;
var params = {server_name: server_name};
switch(page) {
case 'dashboard':
$.getJSON('/vm/status').then(self.refresh.pings);
$.getJSON('/vm/dashboard').then(self.refresh.dashboard).then(self.redraw.gauges);
self.redraw.chart();
break;
case 'backup_list':
$.getJSON('/vm/increments', params).then(self.refresh.increments);
break;
case 'archive_list':
$.getJSON('/vm/archives', params).then(self.refresh.archives);
break;
case 'server_status':
$.getJSON('/vm/status').then(self.refresh.pings).then(self.redraw.gauges);
$.getJSON('/vm/increments', params).then(self.refresh.increments);
$.getJSON('/vm/archives', params).then(self.refresh.archives);
$.getJSON('/vm/server_summary', params).then(self.refresh.summary);
setTimeout(function() {
$('#delete_server input[type="checkbox"]').not('.nostyle').iCheck({
checkboxClass: 'icheckbox_minimal-grey',
radioClass: 'iradio_minimal-grey',
increaseArea: '40%' // optional
});
}, 500)
break;
case 'profiles':
$.getJSON('/vm/profiles').then(self.refresh.profiles);
break;
case 'profile_view':
$.getJSON('/vm/profiles').then(self.refresh.profiles);
break;
case 'create_server':
$.getJSON('/vm/profiles').then(self.refresh.profiles);
break;
case 'server_properties':
$.getJSON('/server', $.extend({}, params, {'cmd': 'sp'})).then(self.refresh.sp);
break;
case 'server_config':
$.getJSON('/server', $.extend({}, params, {'cmd': 'sc'})).then(self.refresh.sc);
break;
case 'importable':
$.getJSON('/vm/importable', {}).then(self.refresh.importable);
break;
case 'console':
$.getJSON('/logs', params).then(self.refresh.logs);
break;
default:
break;
}
})
self.pruning.archives.user_input.subscribe(function(new_value) {
var clone = self.vmdata.archives().slice(0).reverse();
var match;
var reclaimed = 0.0;
$.each(clone, function(i,v) {
if (v.friendly_timestamp == new_value) {
match = i;
self.pruning.archives.filename(v.filename);
return false;
}
reclaimed += v.size;
})
if (!match){
self.pruning.archives.remove_count(0);
self.pruning.archives.space_reclaimed(0.0);
self.pruning.archives.archives_to_delete = '';
} else {
var hits = clone.slice(0,match).map(function(e) { return e.filename });
self.pruning.archives.remove_count(hits.length);
self.pruning.archives.space_reclaimed(bytes_to_mb(reclaimed));
self.pruning.archives.archives_to_delete = hits.join(' ');
}
})
self.pruning.increments.user_input.subscribe(function(new_value){
var clone = self.vmdata.increments().slice(0).reverse();
var match;
var reclaimed = 0.0;
$.each(clone, function(i,v) {
if (v.timestamp == new_value || v.step == new_value) {
match = i;
self.pruning.increments.step = v.step;
return false;
}
if (v.increment_size.slice(-2) == 'KB')
reclaimed += parseFloat(v.increment_size) / 1000;
else
reclaimed += parseFloat(v.increment_size);
})
if (!match){
self.pruning.increments.remove_count(0);
self.pruning.increments.space_reclaimed(0);
self.pruning.increments.step = '';
} else {
self.pruning.increments.remove_count(clone.slice(0,match).length);
self.pruning.increments.space_reclaimed(reclaimed);
}
})
/* form submissions */
self.create_server = function(form) {
var server_name = $(form).find('input[name="server_name"]').val();
var group = $(form).find('select[name=group]').val();
var step1 = $(form).find('fieldset#step1 :input').filter(function() {
return ($(this).val() ? true : false);
})
var step2 = $(form).find('fieldset#step2 :input').filter(function() {
return ($(this).val() ? true : false);
})
var step3 = $(form).find('fieldset#step3 :input').filter(function() {
return ($(this).val() ? true : false);
})
var sp = {};
$.each($(step2).serialize().split('&'), function(i,v) {
sp[v.split('=')[0]] = v.split('=')[1];
})
var sc = {};
$.each(step3, function(i,v) {
input = $(v);
section = input.data('section');
if (!(section in sc))
sc[section] = {};
if ($(input).is(':checkbox')) {
sc[section][input.attr('name')] = $(input).is(':checked');
} else{
sc[section][input.attr('name')] = input.val();
}
})
params = {
'server_name': server_name,
'sp': JSON.stringify(sp),
'sc': JSON.stringify(sc),
'group': group
}
$.getJSON('/create', params)
.then(self.ajax.received, self.ajax.lost)
.done(function() {
self.show_page('dashboard');
},function(){
});
}
self.console_command = function(form) {
var user_input = $(form).find('input[name=console_command]');
params = {
cmd: user_input.val(),
server_name: self.server().server_name
}
$.getJSON('/server', params)
.then(self.ajax.received, self.ajax.lost).then(function() {
self.ajax.refresh(null);
user_input.val('');
});
}
self.define_profile = function(form) {
var step1 = $(form).find('fieldset :input').filter(function() {
return ($(this).val() ? true : false);
})
var properties = {};
$(step1).each(function() {
properties[ $(this).attr('name') ] = $(this).val();
})
var props = $(form).find('input[name="tags"]').map(function(i,v) {
return $(this).val();
});
properties['ignore'] = (props.length > 0) ? props.get().join(' ') : '';
delete properties.tags;
params = {
'cmd': 'define_profile',
'profile_dict': JSON.stringify(properties),
}
$.getJSON('/host', params)
.then(self.ajax.received, self.ajax.lost)
.done(function() {
self.show_page('profiles');
},function(){
});
}
/* promises */
self.ajax = {
received: function(data) {
$.gritter.add({
text: (data.payload) ? data.payload : '{0} [{1}]'.format(data.cmd, data.result),
sticky: false,
time: '3000',
class_name: 'gritter-{0}'.format(data.result)
});
console.log(data);
if (data.result == 'success')
return $.Deferred().resolve().promise();
else
return $.Deferred().reject().promise();
},
lost: function(data) {
$.gritter.add({
text: data.payload || 'Server did not respond to request',
time: '4000',
class_name: 'gritter-warning'
});
console.log(data);
return $.Deferred().reject().promise();
},
refresh: function(time) {
setTimeout(self.page.valueHasMutated, time || self.refresh_rate)
}
}
self.refresh = {
dashboard: function(data) {
self.dashboard.uptime(seconds_to_days(data.uptime));
self.dashboard.memfree(data.memfree);
self.dashboard.whoami(data.whoami);
self.dashboard.group(data.group);
self.dashboard.disk_usage(data.df);
self.dashboard.disk_usage_pct((str_to_bytes(self.dashboard.disk_usage().used) /
str_to_bytes(self.dashboard.disk_usage().total) * 100).toFixed(1));
self.dashboard.groups(data.groups);
self.dashboard.pc_permissions(data.pc_permissions);
self.dashboard.pc_group(data.pc_group);
self.dashboard.git_hash(data.git_hash);
self.dashboard.stock_profiles(data.stock_profiles);
self.dashboard.base_directory(data.base_directory);
$('#pc_group option').filter(function () {
return $(this).val() == data.pc_group
}).prop('selected', true);
},
pings: function(data) {
self.vmdata.pings.removeAll();
self.dashboard.servers_up(0);
$.each(data.ascending_by('server_name'), function(i,v) {
self.vmdata.pings.push( new model_server(v) );
if (self.server().server_name == v.server_name)
self.server(new model_server(v));
if (v.up)
self.dashboard.servers_up(self.dashboard.servers_up()+1)
})
},
archives: function(data) {
self.vmdata.archives(data.ascending_by('timestamp').reverse());
$("input#prune_archive_input").autocomplete({
source: self.vmdata.archives().map(function(i) {
return i.friendly_timestamp
})
});
},
increments: function(data) {
self.vmdata.increments(data);
$("input#prune_increment_input").autocomplete({
source: self.vmdata.increments().map(function(i) {
return i.timestamp
})
});
},
summary: function(data) {
self.summary.owner(data.owner);
self.summary.group(data.group);
self.summary.du_cwd(bytes_to_mb(data.du_cwd));
setTimeout(function() {
$('#available_groups option').filter(function () {
return $(this).val() == self.summary.group()
}).prop('selected', true)}, 50)
},
profiles: function(data) {
self.vmdata.profiles.removeAll();
$.each(data, function(i,v) {
self.vmdata.profiles.push( new model_profile(v) );
if (self.profile().profile == v.profile)
self.profile(new model_profile(v));
})
self.vmdata.profiles(self.vmdata.profiles().ascending_by('profile'));
},
sp: function(data) {
self.vmdata.sp.removeAll();
$.each(data.payload, function(option, value) {
self.vmdata.sp.push( new model_property(self.server().server_name, option, value) )
})
self.vmdata.sp(self.vmdata.sp().ascending_by('option'));
$('table#table_properties input[type="checkbox"]').not('.nostyle').iCheck({
checkboxClass: 'icheckbox_minimal-grey',
radioClass: 'iradio_minimal-grey',
increaseArea: '40%' // optional
});
},
sc: function(data) {
self.vmdata.sc.removeAll();
$.each(data.payload, function(section, option_value_pair){
$.each(option_value_pair, function(option, value){
self.vmdata.sc.push(new model_property(self.server().server_name, option, value, section))
})
})
self.vmdata.sc(self.vmdata.sc().ascending_by('section'));
$('table#table_config input[type="checkbox"]').not('.nostyle').iCheck({
checkboxClass: 'icheckbox_minimal-grey',
radioClass: 'iradio_minimal-grey',
increaseArea: '40%' // optional
});
setTimeout(function() {
$.each(self.vmdata.sc(), function(i,v) {
if (v.type == 'interval'){
$('#{0}_{1} option'.format(v.section(), v.option())).filter(function () {
return $(this).val() == v.val()
}).prop('selected', true)
}
})
}, 50)
},
importable: function(data) {
self.vmdata.importable(data.ascending_by('filename'));
},
logs: function(data) {
if (!data.payload.length) {
self.reset_logs();
} else {
$.each(data.payload, function(i,v) {
if (!v.match(/\[INFO\] \/127.0.0.1:\d+ lost connection/) && !v.match(/\[SEVERE\] Reached end of stream for \/127.0.0.1/))
self.vmdata.logs.push(new model_logline(v));
})
}
}
}
/* redraw functions */
self.judge_severity = function(percent) {
var colors = ['green', 'yellow', 'orange', 'red'];
var thresholds = [0, 60, 75, 90];
var gauge_color = colors[0];
for (var i=0; i < colors.length; i++)
gauge_color = (parseInt(percent) >= thresholds[i] ? colors[i] : gauge_color)
return gauge_color;
}
self.redraw = {
gauges: function() {
$('#{0} .gauge'.format(self.page())).easyPieChart({
barColor: $color[self.judge_severity( $(this).data('percent') )],
scaleColor: false,
trackColor: '#999',
lineCap: 'butt',
lineWidth: 4,
size: 50,
animate: 1000
});
},
chart: function() {
function rerender(data) {
function enumerate(arr) {
var res = [];
for (var i = 0; i < arr.length; ++i)
res.push([i, arr[i]])
return res;
}
self.load_averages.one.push(data[0])
self.load_averages.five.push(data[1])
self.load_averages.fifteen.push(data[2])
while (self.load_averages.one.length > (self.load_averages.options.xaxis.max + 1)){
self.load_averages.one.splice(0,1)
self.load_averages.five.splice(0,1)
self.load_averages.fifteen.splice(0,1)
}
//colors http://www.jqueryflottutorial.com/tester-4.html
var dataset = [
{ label: "fifteen", data: enumerate(self.load_averages['fifteen']), color: "#0077FF" },
{ label: "five", data: enumerate(self.load_averages['five']), color: "#ED7B00" },
{ label: "one", data: enumerate(self.load_averages['one']), color: "#E8E800" }
]
self.load_averages.options.yaxis.max = Math.max(
self.load_averages.one.max(),
self.load_averages.five.max(),
self.load_averages.fifteen.max()) || 1;
var plot = $.plot($("#load_averages"), dataset, self.load_averages.options);
plot.draw();
}
function update() {
if (self.page() != 'dashboard' || !self.load_averages.autorefresh()) {
self.load_averages.one.push.apply(self.load_averages.one, [0,0,0])
self.load_averages.five.push.apply(self.load_averages.five, [0,0,0])
self.load_averages.fifteen.push.apply(self.load_averages.fifteen, [0,0,0])
return
}
$.getJSON('/vm/loadavg').then(rerender);
setTimeout(update, self.refresh_loadavg);
}
update();
}
}
/* viewmodel startup */
self.show_page('dashboard');
}
/* prototypes */
String.prototype.format = String.prototype.f = function() {
var s = this,
i = arguments.length;
while (i--) { s = s.replace(new RegExp('\\{' + i + '\\}', 'gm'), arguments[i]);}
return s;
};
Array.prototype.max = function () {
return Math.max.apply(Math, this);
};
Array.prototype.ascending_by = function(param) {
return this.sort(function(a, b) {return a[param] == b[param] ? 0 : (a[param] < b[param] ? -1 : 1) })
}
Array.prototype.sum = function(param) {
var total = 0;
for (var i=0; i < this.length; i++)
total += this[i][param]
return total;
}
function seconds_to_days(seconds){
var numdays = Math.floor(seconds / 86400);
var numhours = Math.floor((seconds % 86400) / 3600);
var numminutes = Math.floor(((seconds % 86400) % 3600) / 60);
var numseconds = ((seconds % 86400) % 3600) % 60;
return numdays + " days " + ('0' + numhours).slice(-2) + ":" + ('0' + numminutes).slice(-2) + ":" + ('0' + numseconds).slice(-2);
}
function seconds_to_time(seconds) {
function zero_pad(number){
if (number.toString().length == 1)
return '0' + number;
else
return number;
}
var hours = Math.floor(seconds / (60 * 60));
var divisor_for_minutes = seconds % (60 * 60);
var minutes = Math.floor(divisor_for_minutes / 60);
var divisor_for_seconds = divisor_for_minutes % 60;
var seconds = Math.ceil(divisor_for_seconds);
return '{0}:{1}:{2}'.format(hours, zero_pad(minutes), zero_pad(seconds));
}
function str_to_bytes(str) {
if (str.substr(-1) == 'T')
return parseFloat(str) * Math.pow(10,12);
else if (str.substr(-1) == 'G')
return parseFloat(str) * Math.pow(10,9);
else if (str.substr(-1) == 'M')
return parseFloat(str) * Math.pow(10,6);
else if (str.substr(-1) == 'K')
return parseFloat(str) * Math.pow(10,3);
else
return parseFloat(str);
}
function bytes_to_mb(bytes){
//http://stackoverflow.com/a/18650828
if (bytes == 0)
return '0B';
else if (bytes < 1024)
return bytes + 'B';
var k = 1024;
var sizes = ['Bytes', 'KB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB'];
var i = Math.floor(Math.log(bytes) / Math.log(k));
return (bytes / Math.pow(k, i)).toPrecision(3) + sizes[i];
}
| koderiter/mineos | html/js/scriptin.js | JavaScript | gpl-3.0 | 30,637 |
(function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){
(i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o),
m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m)
})(window,document,'script','//www.google-analytics.com/analytics.js','ga');
ga('create', 'UA-26989160-4', '3scape.me');
ga('require', 'displayfeatures');
ga('require', 'linkid', 'linkid.js');
ga('send', 'pageview');
| kmcurry/3Scape | public/js/google.js | JavaScript | gpl-3.0 | 453 |
/**
Copyright 2012-2013 John Cummens (aka Shadowmage, Shadowmage4513)
This software is distributed under the terms of the GNU General Public License.
Please see COPYING for precise license information.
This file is part of Ancient Warfare.
Ancient Warfare is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
Ancient Warfare is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with Ancient Warfare. If not, see <http://www.gnu.org/licenses/>.
*/
package net.shadowmage.ancientwarfare.structure.api;
import net.minecraft.item.ItemStack;
import net.minecraft.nbt.JsonToNBT;
import net.minecraft.nbt.NBTBase;
import net.minecraft.nbt.NBTTagCompound;
import net.minecraft.world.World;
import net.shadowmage.ancientwarfare.core.util.Json;
import net.shadowmage.ancientwarfare.core.util.JsonTagReader;
import net.shadowmage.ancientwarfare.core.util.JsonTagWriter;
import net.shadowmage.ancientwarfare.structure.api.TemplateParsingException.TemplateRuleParsingException;
import net.shadowmage.ancientwarfare.structure.template.build.StructureBuildingException;
import java.io.BufferedWriter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Locale;
/**
* base template-rule class. Plugins should define their own rule classes.
* all data to place the block/entity/target of the rule must be contained in the rule.
* ONLY one rule per block-position in the template. So -- no entity/block combination in same space unless
* handled specially via a plugin rule
*
* @author Shadowmage
*/
public abstract class TemplateRule {
public int ruleNumber = -1;
/**
* all sub-classes must implement a no-param constructor for when loaded from file (at which point they should initialize from the parseRuleData method)
*/
public TemplateRule() {
}
/**
* input params are the target position for placement of this rule and destination orientation
*/
public abstract void handlePlacement(World world, int turns, int x, int y, int z, IStructureBuilder builder) throws StructureBuildingException;
public abstract void parseRuleData(NBTTagCompound tag);
public abstract void writeRuleData(NBTTagCompound tag);
public abstract void addResources(List<ItemStack> resources);
public abstract boolean shouldPlaceOnBuildPass(World world, int turns, int x, int y, int z, int buildPass);
public void writeRule(BufferedWriter out) throws IOException {
NBTTagCompound tag = new NBTTagCompound();
writeRuleData(tag);
writeTag(out, tag);
}
public void parseRule(int ruleNumber, List<String> lines) throws TemplateRuleParsingException {
this.ruleNumber = ruleNumber;
NBTTagCompound tag = readTag(lines);
parseRuleData(tag);
}
public final void writeTag(BufferedWriter out, NBTTagCompound tag) throws IOException {
String line = Json.getJsonData(JsonTagWriter.getJsonForTag(tag));
out.write(line);
out.newLine();
}
public final NBTTagCompound readTag(List<String> ruleData) throws TemplateRuleParsingException {
for (String line : ruleData)//new json format
{
if (line.startsWith("JSON:{")) {
return JsonTagReader.parseTagCompound(line);
}
}
for (String line : ruleData)//old json format
{
if (line.toLowerCase(Locale.ENGLISH).startsWith("jsontag=")) {
try {
NBTBase tag = JsonToNBT.func_150315_a(line.split("=", -1)[1]);
if (tag instanceof NBTTagCompound) {
return (NBTTagCompound) tag;
}
} catch (Exception e) {
e.printStackTrace();
throw new TemplateRuleParsingException("Caught exception while parsing json-nbt tag: " + line, e);
}
}
}
//old tag: format
List<String> tagLines = new ArrayList<String>();
String line;
Iterator<String> it = ruleData.iterator();
while (it.hasNext() && (line = it.next()) != null) {
if (line.startsWith("tag:")) {
it.remove();
while (it.hasNext() && (line = it.next()) != null) {
it.remove();
if (line.startsWith(":endtag")) {
break;
}
tagLines.add(line);
}
}
}
return NBTTools.readNBTFrom(tagLines);
}
@Override
public String toString() {
return "Template rule: " + ruleNumber + " type: " + getClass().getSimpleName();
}
}
| CosmicDan-Minecraft/AncientWarfare2_CosmicDanFork | src/main/java/net/shadowmage/ancientwarfare/structure/api/TemplateRule.java | Java | gpl-3.0 | 5,289 |
#include <propeller.h>
#include "test11.h"
#ifdef __GNUC__
#define INLINE__ static inline
#define PostEffect__(X, Y) __extension__({ int32_t tmp__ = (X); (X) = (Y); tmp__; })
#else
#define INLINE__ static
static int32_t tmp__;
#define PostEffect__(X, Y) (tmp__ = (X), (X) = (Y), tmp__)
#endif
int32_t test11::Peek(void)
{
return Count;
}
int32_t test11::Donext(void)
{
Count = (Peek() + 1);
return Count;
}
| BackupGGCode/propgcc | spin2cpp/Test/Expect/test11.cpp | C++ | gpl-3.0 | 417 |
<?php
/*
##########################################################################
# #
# Version 4 / / / #
# -----------__---/__---__------__----__---/---/- #
# | /| / /___) / ) (_ ` / ) /___) / / #
# _|/_|/__(___ _(___/_(__)___/___/_(___ _/___/___ #
# Free Content / Management System #
# / #
# #
# #
# Copyright 2005-2011 by webspell.org #
# #
# visit webSPELL.org, webspell.info to get webSPELL for free #
# - Script runs under the GNU GENERAL PUBLIC LICENSE #
# - It's NOT allowed to remove this copyright-tag #
# -- http://www.fsf.org/licensing/licenses/gpl.html #
# #
# Code based on WebSPELL Clanpackage (Michael Gruber - webspell.at), #
# Far Development by Development Team - webspell.org #
# #
# visit webspell.org #
# #
##########################################################################
*/
$ergebnis=safe_query("SELECT * FROM ".PREFIX."squads WHERE gamesquad = '1' ORDER BY sort");
if(mysql_num_rows($ergebnis)) {
echo '<table width="100%" cellspacing="0" cellpadding="2">';
$n=1;
while($db=mysql_fetch_array($ergebnis)) {
if($n%2) {
$bg1=BG_1;
$bg2=BG_2;
}
else {
$bg1=BG_3;
$bg2=BG_4;
}
$n++;
if(!empty($db['icon_small'])) $squadicon='<img src="images/squadicons/'.$db['icon_small'].'" style="margin:2px 0;" border="0" alt="'.getinput($db['name']).'" title="'.getinput($db['name']).'" />';
else $squadicon='';
$squadname=getinput($db['name']);
eval ("\$sc_squads = \"".gettemplate("sc_squads")."\";");
echo $sc_squads;
}
echo '</table>';
}
?> | kevinwiede/webspell-nerv | sc_squads.php | PHP | gpl-3.0 | 2,429 |
# -*- encoding: binary -*-
# :enddoc:
module Rainbows::ProcessClient
include Rainbows::Response
include Rainbows::Const
NULL_IO = Unicorn::HttpRequest::NULL_IO
RACK_INPUT = Unicorn::HttpRequest::RACK_INPUT
IC = Unicorn::HttpRequest.input_class
Rainbows.config!(self, :client_header_buffer_size, :keepalive_timeout)
def read_expire
Time.now + KEEPALIVE_TIMEOUT
end
# used for reading headers (respecting keepalive_timeout)
def timed_read(buf)
expire = nil
begin
case rv = kgio_tryread(CLIENT_HEADER_BUFFER_SIZE, buf)
when :wait_readable
return if expire && expire < Time.now
expire ||= read_expire
kgio_wait_readable(KEEPALIVE_TIMEOUT)
else
return rv
end
end while true
end
def process_loop
@hp = hp = Rainbows::HttpParser.new
kgio_read!(CLIENT_HEADER_BUFFER_SIZE, buf = hp.buf) or return
begin # loop
until env = hp.parse
timed_read(buf2 ||= "") or return
buf << buf2
end
set_input(env, hp)
env[REMOTE_ADDR] = kgio_addr
hp.hijack_setup(env, to_io)
status, headers, body = APP.call(env.merge!(RACK_DEFAULTS))
if 100 == status.to_i
write(EXPECT_100_RESPONSE)
env.delete(HTTP_EXPECT)
status, headers, body = APP.call(env)
end
return if hp.hijacked?
write_response(status, headers, body, alive = hp.next?) or return
end while alive
# if we get any error, try to write something back to the client
# assuming we haven't closed the socket, but don't get hung up
# if the socket is already closed or broken. We'll always ensure
# the socket is closed at the end of this function
rescue => e
handle_error(e)
ensure
close unless closed? || hp.hijacked?
end
def handle_error(e)
Rainbows::Error.write(self, e)
end
def set_input(env, hp)
env[RACK_INPUT] = 0 == hp.content_length ? NULL_IO : IC.new(self, hp)
end
def process_pipeline(env, hp)
begin
set_input(env, hp)
env[REMOTE_ADDR] = kgio_addr
hp.hijack_setup(env, to_io)
status, headers, body = APP.call(env.merge!(RACK_DEFAULTS))
if 100 == status.to_i
write(EXPECT_100_RESPONSE)
env.delete(HTTP_EXPECT)
status, headers, body = APP.call(env)
end
return if hp.hijacked?
write_response(status, headers, body, alive = hp.next?) or return
end while alive && pipeline_ready(hp)
alive or close
rescue => e
handle_error(e)
end
# override this in subclass/module
def pipeline_ready(hp)
end
end
| tankerwng/rainbows | lib/rainbows/process_client.rb | Ruby | gpl-3.0 | 2,593 |
$(document).ready(function(){
$('#countdown').countdown( {date: '19 april 2013 16:24:00'} );
}); | gengjian1203/GoldAbacus | vendor/countdown/ext.js | JavaScript | gpl-3.0 | 99 |
/**Copyright 2010 Research Studios Austria Forschungsgesellschaft mBH
*
* This file is part of easyrec.
*
* easyrec is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* easyrec is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with easyrec. If not, see <http://www.gnu.org/licenses/>.
*/
package org.easyrec.util.core;
import com.google.common.base.Strings;
import org.easyrec.model.core.web.Operator;
import org.easyrec.utils.io.Text;
import org.springframework.web.servlet.ModelAndView;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.Random;
import java.util.logging.Level;
import java.util.logging.Logger;
/**
* This class checks if a Operator or Administrator is signed in.
*
* @author phlavac
*/
public class Security {
// TODO: move to vocabulary? i would say remove this pathetic class :)
public static final Integer ACCESS_LEVEL_DEVELOPER = 1;
// The User can view this sites without a login:
private static String[] WHITELIST_DOMAIN = {"localhost"};
/**
* This function signs in an operator and returns a security token
* the a valid for the current session.
*
* @param request
* @param operator
*/
public static String signIn(HttpServletRequest request, Operator operator) {
String token = null;
if (operator != null) {
request.getSession(true).setAttribute("signedInOperatorId", operator.getOperatorId());
request.getSession(true).setAttribute("signedInOperator", operator);
token = Text.generateHash(Long.toString(System.currentTimeMillis()) + operator.getOperatorId());
Security.setAttribute(request, "token", token);
}
return token;
}
/**
* This function checks if an operator is signed in
*
* @param request
* @return
*/
public static boolean isSignedIn(HttpServletRequest request) {
return request.getSession().getAttribute("signedInOperatorId") != null;
}
/**
* This function checks if an operator is signed in as a developer
* Developer can edit/remove core-, remote-tenants and operators
*
* @param request
* @return
*/
public static boolean isDeveloper(HttpServletRequest request) {
if (request.getSession(false) != null) {
Operator o = (Operator) request.getSession().getAttribute("signedInOperator");
if (o != null) {
return (ACCESS_LEVEL_DEVELOPER.equals(o.getAccessLevel()));
} else {
return false;
}
} else {
return false;
}
}
/**
* Returns the operator Id of the signed in operator, "" otherwise.
*
* @param request
* @return
*/
public static String signedInOperatorId(HttpServletRequest request) {
String signedInOperatorId = "";
try {
signedInOperatorId = request.getSession().getAttribute("signedInOperatorId").toString();
} catch (Exception e) {
}
return (Strings.isNullOrEmpty(signedInOperatorId)) ? "" : signedInOperatorId;
}
/**
* Returns the operator Object of the signed in operator, "" otherwise.
*
* @param request
* @return
*/
public static Operator signedInOperator(HttpServletRequest request) {
Operator operator;
try {
operator = (Operator) request.getSession(true).getAttribute("signedInOperator");
return operator;
} catch (Exception e) {
}
return null;
}
/**
* This function returns an empty mav object and tries to redirect the user
* to the homepage (e.g. if not logged in)
*
* @param request
* @param response
* @return
*/
public static ModelAndView redirectHome(HttpServletRequest request, HttpServletResponse response) {
try {
response.sendRedirect(request.getContextPath() + "/home");
} catch (IOException ex) {
Logger.getLogger(Security.class.getName()).log(Level.SEVERE, null, ex);
}
return null;
}
/**
* Returns the operatorId from the Parameter "operatorId" in the request object,
* if signed in as administrator or the operatorId of the signed in Operator.
* If not signed in, null is returned.
*
* @param request
* @return
*/
public static String getOperatorId(HttpServletRequest request) {
String operatorId = null;
// a developer account is allowed to read and write item objects from
// any operator
if (Security.isDeveloper(request)) {
operatorId = request.getParameter("operatorId");
}
if (operatorId == null) {
Operator o = Security.signedInOperator(request);
if (o != null) {
operatorId = o.getOperatorId();
}
}
return operatorId;
}
/**
* Returns a security token valid for this session. A secrity token
* is used to call specific REST-API calls to manipulate Data.
* If not signed in, null is returned.
*
* @param request
* @return
*/
public static String getSecurityToken(HttpServletRequest request) {
String token = "xxxxx";
if (Security.isSignedIn(request)) {
if (nullAttribute(request, "token")) {
setAttribute(request, "token",
Text.generateHash(Long.toString(System.currentTimeMillis()) + Security.getOperatorId(request)));
} else {
return (String) getAttribute(request, "token");
}
}
return token;
}
/**
* This function returns true if url
* contains a domain that is in white list.
*
* @param url
* @return
*/
public static boolean inWhiteListDomain(String url) {
if (!Strings.isNullOrEmpty(url)) {
for (String whiteDomain : WHITELIST_DOMAIN) {
if (url.contains(whiteDomain)) {
return true;
}
}
}
return false;
}
/**
* This function returns a new randomized 8-digit password.
*
* @return
*/
public static String getNewPassword() {
String password = "";
Random r = new Random();
String validChars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890";
for (int i = 1; i < 8; i++) {
password = password + validChars.charAt(r.nextInt(validChars.length()));
}
return password;
}
/**
* Sets a given attribute for a session
*
* @param request
* @param name
* @param value
*/
public static void setAttribute(HttpServletRequest request, String name, Object value) {
HttpSession session = request.getSession(false);
if (session != null && name != null) {
session.setAttribute(name, value);
}
}
/**
* return a given attribute (if available) for a session
*
* @param request
* @param name
* @return
*/
public static Object getAttribute(HttpServletRequest request, String name) {
HttpSession session = request.getSession(false);
if (session != null && name != null) {
return session.getAttribute(name);
}
return null;
}
/**
* returns true if a given attribute is null
*
* @param request
* @param name
* @return
*/
public static Boolean nullAttribute(HttpServletRequest request, String name) {
HttpSession session = request.getSession(false);
if (session != null && name != null) {
return (session.getAttribute(name) == null);
}
return true;
}
}
| ferronrsmith/easyrec | easyrec-core/src/main/java/org/easyrec/util/core/Security.java | Java | gpl-3.0 | 8,400 |
<?php
// This file is part of Moodle - http://moodle.org/
//
// Moodle is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// Moodle is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with Moodle. If not, see <http://www.gnu.org/licenses/>.
/**
* Redirect the user based on their capabilities to either a scorm activity or to scorm reports
*
* @package mod_scorm
* @category grade
* @copyright 2010 onwards Dan Marsden
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
require_once("../../config.php");
$id = required_param('id', PARAM_INT); // Course module ID
if (! $cm = get_coursemodule_from_id('scorm', $id)) {
print_error('invalidcoursemodule');
}
if (! $scorm = $DB->get_record('scorm', array('id' => $cm->instance))) {
print_error('invalidcoursemodule');
}
if (! $course = $DB->get_record('course', array('id' => $scorm->course))) {
print_error('coursemisconf');
}
require_login($course, false, $cm);
if (has_capability('mod/scorm:viewreport', context_module::instance($cm->id))) {
redirect('report.php?id='.$cm->id);
} else {
redirect('view.php?id='.$cm->id);
}
| Dynamic-Business/moodle | mod/scorm/grade.php | PHP | gpl-3.0 | 1,591 |
odoo.define('website_forum.tour_forum', function (require) {
'use strict';
var core = require('web.core');
var Tour = require('web.Tour');
var _t = core._t;
Tour.register({
id: 'question',
name: _t("Create a question"),
steps: [
{
title: _t("Create a Question!"),
content: _t("Let's go through the first steps to create a new question."),
popover: { next: _t("Start Tutorial"), end: _t("Skip It") },
},
{
title: _t("Add Content"),
element: '#oe_main_menu_navbar a[data-action=new_page]',
placement: 'bottom',
content: _t("Use this button to create a new forum like any other document (page, menu, products, event, ...)."),
popover: { fixed: true },
},
{
title: _t("New Forum"),
element: 'a[data-action=new_forum]',
placement: 'left',
content: _t("Select this menu item to create a new forum."),
popover: { fixed: true },
},
{
title: _t("Forum Name"),
element: '.modal #editor_new_forum input[type=text]',
sampleText:'New Forum',
placement: 'right',
content: _t("Enter a name for your new forum."),
},
{
title: _t("Create Forum"),
waitNot: ".modal #editor_new_forum input[type=text]:propValue('')",
element: '.modal button.btn-primary',
placement: 'right',
content: _t("Click <em>Continue</em> to create the forum."),
},
{
title: _t("New Forum Created"),
waitNot: '.modal:visible',
content: _t("This page contains all the information related to the new forum."),
popover: { next: _t("Continue") },
},
{
title: _t("Ask a Question"),
element: '.btn-block a:first',
placement: 'left',
content: _t("Ask the question in this forum by clicking on the button."),
},
{
title: _t("Question Title"),
element: 'input[name=post_name]',
sampleText:'First Question Title',
placement: 'top',
content: _t("Give your question title."),
},
{
title: _t("Question"),
waitNot: "input[name=post_name]:propValue('')",
element: '.note-editable p',
sampleText: 'First Question',
placement: 'top',
content: _t("Put your question here."),
},
{
title: _t("Give Tag"),
waitNot: '.note-editable p:containsExact("<br>")',
element: '.select2-choices',
placement: 'top',
content: _t("Insert tags related to your question."),
},
{
title: _t("Post Question"),
waitNot: "input[id=s2id_autogen2]:propValue('Tags')",
element: 'button:contains("Post Your Question")',
placement: 'bottom',
content: _t("Click to post your question."),
},
{
title: _t("New Question Created"),
waitFor: '.fa-star',
content: _t("This page contains the newly created questions."),
popover: { next: _t("Continue") },
},
{
title: _t("Answer"),
element: '.note-editable p',
sampleText: 'First Answer',
placement: 'top',
content: _t("Put your answer here."),
},
{
title: _t("Post Answer"),
waitNot: '.note-editable p:containsExact("<br>")',
element: 'button:contains("Post Answer")',
placement: 'bottom',
content: _t("Click to post your answer."),
},
{
title: _t("Answer Posted"),
waitFor: '.fa-check-circle',
content: _t("This page contains the newly created questions and its answers."),
popover: { next: _t("Continue") },
},
{
title: _t("Accept Answer"),
element: 'a[data-karma="20"]:first',
placement: 'right',
content: _t("Click here to accept this answer."),
},
{
title: _t("Congratulations"),
waitFor: '.oe_answer_true',
content: _t("Congratulations! You just created and post your first question and answer."),
popover: { next: _t("Close Tutorial") },
},
]
});
});
| akhmadMizkat/odoo | addons/website_forum/static/src/js/website_tour_forum.js | JavaScript | gpl-3.0 | 4,695 |
<?php
namespace Claroline\BundleRecorder\Log;
use Psr\Log\LoggerAwareTrait;
use Psr\Log\LogLevel;
trait LoggableTrait
{
use LoggerAwareTrait;
public function log($message, $logLevel = null)
{
if ($this->logger) {
$time = date('m-d-y h:i:s').': ';
if (!$logLevel) {
$logLevel = LogLevel::INFO;
}
$this->logger->log($logLevel, $time.$message);
}
}
}
| remytms/Distribution | main/recorder/Log/LoggableTrait.php | PHP | gpl-3.0 | 448 |
tutao.provide('tutao.tutanota.ctrl.lang.ja');
tutao.tutanota.ctrl.lang.ja.writing_direction = "ltr";
tutao.tutanota.ctrl.lang.ja.id = "ja";
tutao.tutanota.ctrl.lang.ja.keys = {
"account_label": "ユーザー",
"activate_action": "有効にする",
"address_label": "アドレス",
"add_action": "追加する",
"adminEmailSettings_action": "メール",
"adminMessages_action": "表示されたメッセージ",
"adminUserList_action": "ユーザー管理",
"afterRegistration_msg": "アカウントが作成されました。ログインして楽しみましょう。",
"archive_action": "アーカイブ",
"backTologin_action": "ログインに戻る",
"back_action": "前",
"bcc_label": "Bcc",
"birthday_alt": "生年月日",
"cancel_action": "キャンセルする",
"captchaDisplay_label": "キャプチャ",
"changeNotificationMailLanguage_msg": "通知メールの言語:",
"comment_label": "コメント",
"community_label": "コミュニティ",
"company_label": "会社",
"company_placeholder": "会社",
"confidentialMail_alt": "このメールはエンドツーエンドで暗号化され、送信されました。",
"confidential_action": "親展",
"contactImage_alt": "画像",
"contacts_alt": "連絡先",
"contacts_label": "連絡先",
"createAccountInvalidCaptcha_msg": "申し訳ありませんが、回答が間違っています。もう一度やり直して下さい。",
"createAccountRunning_msg": "アカウントを作成しています...",
"custom_label": "カスタム",
"db_label": "データベース",
"defaultExternalDelivery_label": "デフォルトの送信設定",
"defaultSenderMailAddress_label": "デフォルトの送信元",
"deleteAccountWait_msg": "アカウントを削除しています...",
"deleteContact_msg": "この連絡先を本当に削除しますか?",
"deleteMail_msg": "新規メールを送信せずに削除しますか?",
"deleteTrash_action": "すべて削除",
"delete_action": "削除",
"dev_label": "開発者",
"discardContactChangesFor_msg": "{1}の連絡先の変更を破棄しますか?",
"editFolder_action": "編集",
"editUser_label": "ユーザーを編集する",
"email_label": "Eメール",
"enterPresharedPassword_msg": "送信者と共有しているパスワードを入力して下さい。",
"errorNotification_label": "エラー通知",
"export_action": "エクスポートする",
"externalNotificationMailBody3_msg": "暗号化メールを表示する",
"facebook_label": "Facebook",
"fax_label": "ファックス",
"finished_msg": "完了しました。",
"folderNameCreate_label": "新しいフォルダーを作成する",
"folderNameNeutral_msg": "フォルダ名を入力して下さい。",
"folderTitle_label": "フォルダ",
"goodPassphrase_action": "良いパスワードにするには?",
"help_label": "ヘルプを見る:",
"importCsvInvalid_msg": "",
"importCsv_label": "CSVデータをインポートする",
"import_action": "インポートする",
"invalidLink_msg": "申し訳ありません、このリンクは無効です。",
"invalidPassword_msg": "無効なパスワードです。もう一度確認して下さい。",
"invalidRecipients_msg": "受信者欄の無効なメールアドレスを修正して下さい。",
"invitationMailSubject_msg": "Tutanotaで私たちのプライバシーを取り戻そう!",
"invite_alt": "招待",
"invite_label": "招待",
"languageAlbanian_label": "アルバニア語",
"languageArabic_label": "アラビア語",
"languageBulgarian_label": "ブルガリア語",
"languageChineseSimplified_label": "中国語, 簡体字",
"languageCroatian_label": "クロアチア語",
"languageDutch_label": "オランダ語",
"languageEnglish_label": "英語",
"languageFinnish_label": "フィンランド語",
"languageFrench_label": "フランス語",
"languageGerman_label": "ドイツ語",
"languageGreek_label": "ギリシャ語",
"languageItalian_label": "イタリア語",
"languageLithuanian_label": "リトアニア語",
"languageMacedonian_label": "マケドニア語",
"languagePolish_label": "ポーランド語",
"languagePortugeseBrazil_label": "ポルトガル語, ブラジル",
"languagePortugesePortugal_label": "ポルトガル語, ポルトガル",
"languageRomanian_label": "ルーマニア語",
"languageRussian_label": "ロシア語",
"languageSerbian_label": "セルビア語",
"languageSpanish_label": "スペイン語",
"languageTurkish_label": "トルコ語",
"lastName_placeholder": "姓",
"linkedin_label": "LinkedIn",
"loading_msg": "読み込み中",
"loginNameInfoAdmin_msg": "任意: ユーザー名",
"login_action": "ログイン",
"login_msg": "ログインする。",
"logout_alt": "ログアウト",
"logout_label": "ログアウト",
"logs_label": "ログ",
"mailAddressAliases_label": "メールエイリアス",
"mailAddressNA_msg": "このメールアドレスは利用できません。",
"meDativ_label": "自分",
"meNominative_label": "自分",
"mobileNumberValidFormat_msg": "フォーマット OK.",
"monthNames_label": [
"1月",
"2月",
"3月",
"4月",
"5月",
"6月",
"7月",
"8月",
"9月",
"10月",
"11月",
"12月"
],
"move_action": "移動する",
"newMails_msg": "Tutanotaの新着メールを受信しました。",
"noConnection_msg": "あなたはオフラインです。Tutanotaに接続できませんでした。",
"noContact_msg": "連絡先が1つも選択されていません。",
"notificationMailSignatureSubject_msg": "{1}からの機密メール",
"notificationMailSignature_label": "サイン",
"ok_action": "OK",
"oldBrowser_msg": "申し訳ありませんが、あなたは古いブラウザをご利用中です。以下のいずれかのブラウザの最新バージョンにアップグレードして下さい:",
"other_label": "その他",
"password1InvalidUnsecure_msg": "このパスワードは安全性に問題があります。",
"passwords_label": "パスワード",
"passwordTransmission_label": "パスワードの送信",
"passwordWrongInvalid_msg": "パスワードが間違っています。",
"password_label": "パスワード",
"presharedPasswordAndStrength_msg": "パスワードの強さ",
"preSharedPasswordNeeded_label": "各外部受信者用の承認パスワードを入力して下さい。",
"privacyLink_label": "プライバシーポリシー",
"registrationSubHeadline2_msg": "登録情報を入力して下さい。(ステップ2/2)",
"removeAddress_alt": "このアドレスを削除する",
"removePhoneNumber_alt": "",
"removeRecipient_alt": "受信者を削除する",
"rename_action": "名前の変更",
"replyAll_action": "全員に返信",
"saved_msg": "保存が完了しました!",
"savePassword_label": "保存",
"save_action": "保存",
"selectAddress_label": "Eメールアドレスを選択して下さい",
"sendMail_alt": "このアドレス宛にメールを送る",
"send_action": "送信する",
"sentMails_alt": "送信済みメール",
"sent_action": "送信完了",
"settings_label": "設定",
"showAddress_alt": "この住所をGoogleマップで表示する",
"showAttachment_label": "添付を表示する",
"showInAddressBook_alt": "連絡先を編集する",
"storageCapacityNoLimit_label": "制限なし",
"subject_label": "件名",
"terms_label": "確認",
"title_placeholder": "件名",
"tooBigAttachment_msg": "次のファイルは全体サイズが25MBを超えるため添付できません:",
"unsecureMailSendFailureSubject_msg": "メールを送信できませんでした",
"unsupportedBrowser_msg": "申し訳ありませんが、ご利用のブラウザは対応していません。以下のいずれかのブラウザをご利用下さい。",
"welcomeMailSubject_msg": "安心して下さい: あなたのデータのプライバシーは保たれています。",
"work_label": "仕事",
"xing_label": "XING"
}; | msoftware/tutanota-1 | web/js/ctrl/lang/ja.js | JavaScript | gpl-3.0 | 8,146 |
/****************************************************************************
**
* (C) Copyright 2007 Trolltech ASA
* All rights reserved.
**
* This is version of the Pictureflow animated image show widget modified by Trolltech ASA.
*
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of the <organization> nor the
* names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY TROLLTECH ASA ``AS IS'' AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL <copyright holder> BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
****************************************************************************/
/*
ORIGINAL COPYRIGHT HEADER
PictureFlow - animated image show widget
http://pictureflow.googlecode.com
Copyright (C) 2007 Ariya Hidayat (ariya@kde.org)
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
*/
#include "pictureflow.h"
#include <QBasicTimer>
#include <QCache>
#include <QImage>
#include <QKeyEvent>
#include <QPainter>
#include <QPixmap>
#include <QTimer>
#include <QVector>
#include <QWidget>
#include <QTime>
#ifdef Q_WS_QWS
#include <QScreen>
#endif
#include <QDebug>
// for fixed-point arithmetic, we need minimum 32-bit long
// long long (64-bit) might be useful for multiplication and division
typedef long PFreal;
typedef unsigned short QRgb565;
#define REFLECTION_FACTOR 1.5
#define MAX(x, y) ((x > y) ? x : y)
#define MIN(x, y) ((x < y) ? x : y)
#define RGB565_RED_MASK 0xF800
#define RGB565_GREEN_MASK 0x07E0
#define RGB565_BLUE_MASK 0x001F
#define RGB565_RED(col) ((col&RGB565_RED_MASK)>>11)
#define RGB565_GREEN(col) ((col&RGB565_GREEN_MASK)>>5)
#define RGB565_BLUE(col) (col&RGB565_BLUE_MASK)
#define PFREAL_SHIFT 10
#define PFREAL_FACTOR (1 << PFREAL_SHIFT)
#define PFREAL_ONE (1 << PFREAL_SHIFT)
#define PFREAL_HALF (PFREAL_ONE >> 1)
#define TEXT_FLAGS (Qt::TextWordWrap|Qt::TextHideMnemonic|Qt::AlignCenter)
inline PFreal fmul(PFreal a, PFreal b)
{
return ((long long)(a))*((long long)(b)) >> PFREAL_SHIFT;
}
inline PFreal fdiv(PFreal num, PFreal den)
{
long long p = (long long)(num) << (PFREAL_SHIFT*2);
long long q = p / (long long)den;
long long r = q >> PFREAL_SHIFT;
return r;
}
inline float fixedToFloat(PFreal val)
{
return ((float)val) / (float)PFREAL_ONE;
}
inline PFreal floatToFixed(float val)
{
return (PFreal)(val*PFREAL_ONE);
}
// sinTable {{{
#define IANGLE_MAX 1024
#define IANGLE_MASK 1023
// warning: regenerate the table if IANGLE_MAX and PFREAL_SHIFT are changed!
static const PFreal sinTable[IANGLE_MAX] = {
3, 9, 15, 21, 28, 34, 40, 47,
53, 59, 65, 72, 78, 84, 90, 97,
103, 109, 115, 122, 128, 134, 140, 147,
153, 159, 165, 171, 178, 184, 190, 196,
202, 209, 215, 221, 227, 233, 239, 245,
251, 257, 264, 270, 276, 282, 288, 294,
300, 306, 312, 318, 324, 330, 336, 342,
347, 353, 359, 365, 371, 377, 383, 388,
394, 400, 406, 412, 417, 423, 429, 434,
440, 446, 451, 457, 463, 468, 474, 479,
485, 491, 496, 501, 507, 512, 518, 523,
529, 534, 539, 545, 550, 555, 561, 566,
571, 576, 581, 587, 592, 597, 602, 607,
612, 617, 622, 627, 632, 637, 642, 647,
652, 656, 661, 666, 671, 675, 680, 685,
690, 694, 699, 703, 708, 712, 717, 721,
726, 730, 735, 739, 743, 748, 752, 756,
760, 765, 769, 773, 777, 781, 785, 789,
793, 797, 801, 805, 809, 813, 816, 820,
824, 828, 831, 835, 839, 842, 846, 849,
853, 856, 860, 863, 866, 870, 873, 876,
879, 883, 886, 889, 892, 895, 898, 901,
904, 907, 910, 913, 916, 918, 921, 924,
927, 929, 932, 934, 937, 939, 942, 944,
947, 949, 951, 954, 956, 958, 960, 963,
965, 967, 969, 971, 973, 975, 977, 978,
980, 982, 984, 986, 987, 989, 990, 992,
994, 995, 997, 998, 999, 1001, 1002, 1003,
1004, 1006, 1007, 1008, 1009, 1010, 1011, 1012,
1013, 1014, 1015, 1015, 1016, 1017, 1018, 1018,
1019, 1019, 1020, 1020, 1021, 1021, 1022, 1022,
1022, 1023, 1023, 1023, 1023, 1023, 1023, 1023,
1023, 1023, 1023, 1023, 1023, 1023, 1023, 1022,
1022, 1022, 1021, 1021, 1020, 1020, 1019, 1019,
1018, 1018, 1017, 1016, 1015, 1015, 1014, 1013,
1012, 1011, 1010, 1009, 1008, 1007, 1006, 1004,
1003, 1002, 1001, 999, 998, 997, 995, 994,
992, 990, 989, 987, 986, 984, 982, 980,
978, 977, 975, 973, 971, 969, 967, 965,
963, 960, 958, 956, 954, 951, 949, 947,
944, 942, 939, 937, 934, 932, 929, 927,
924, 921, 918, 916, 913, 910, 907, 904,
901, 898, 895, 892, 889, 886, 883, 879,
876, 873, 870, 866, 863, 860, 856, 853,
849, 846, 842, 839, 835, 831, 828, 824,
820, 816, 813, 809, 805, 801, 797, 793,
789, 785, 781, 777, 773, 769, 765, 760,
756, 752, 748, 743, 739, 735, 730, 726,
721, 717, 712, 708, 703, 699, 694, 690,
685, 680, 675, 671, 666, 661, 656, 652,
647, 642, 637, 632, 627, 622, 617, 612,
607, 602, 597, 592, 587, 581, 576, 571,
566, 561, 555, 550, 545, 539, 534, 529,
523, 518, 512, 507, 501, 496, 491, 485,
479, 474, 468, 463, 457, 451, 446, 440,
434, 429, 423, 417, 412, 406, 400, 394,
388, 383, 377, 371, 365, 359, 353, 347,
342, 336, 330, 324, 318, 312, 306, 300,
294, 288, 282, 276, 270, 264, 257, 251,
245, 239, 233, 227, 221, 215, 209, 202,
196, 190, 184, 178, 171, 165, 159, 153,
147, 140, 134, 128, 122, 115, 109, 103,
97, 90, 84, 78, 72, 65, 59, 53,
47, 40, 34, 28, 21, 15, 9, 3,
-4, -10, -16, -22, -29, -35, -41, -48,
-54, -60, -66, -73, -79, -85, -91, -98,
-104, -110, -116, -123, -129, -135, -141, -148,
-154, -160, -166, -172, -179, -185, -191, -197,
-203, -210, -216, -222, -228, -234, -240, -246,
-252, -258, -265, -271, -277, -283, -289, -295,
-301, -307, -313, -319, -325, -331, -337, -343,
-348, -354, -360, -366, -372, -378, -384, -389,
-395, -401, -407, -413, -418, -424, -430, -435,
-441, -447, -452, -458, -464, -469, -475, -480,
-486, -492, -497, -502, -508, -513, -519, -524,
-530, -535, -540, -546, -551, -556, -562, -567,
-572, -577, -582, -588, -593, -598, -603, -608,
-613, -618, -623, -628, -633, -638, -643, -648,
-653, -657, -662, -667, -672, -676, -681, -686,
-691, -695, -700, -704, -709, -713, -718, -722,
-727, -731, -736, -740, -744, -749, -753, -757,
-761, -766, -770, -774, -778, -782, -786, -790,
-794, -798, -802, -806, -810, -814, -817, -821,
-825, -829, -832, -836, -840, -843, -847, -850,
-854, -857, -861, -864, -867, -871, -874, -877,
-880, -884, -887, -890, -893, -896, -899, -902,
-905, -908, -911, -914, -917, -919, -922, -925,
-928, -930, -933, -935, -938, -940, -943, -945,
-948, -950, -952, -955, -957, -959, -961, -964,
-966, -968, -970, -972, -974, -976, -978, -979,
-981, -983, -985, -987, -988, -990, -991, -993,
-995, -996, -998, -999, -1000, -1002, -1003, -1004,
-1005, -1007, -1008, -1009, -1010, -1011, -1012, -1013,
-1014, -1015, -1016, -1016, -1017, -1018, -1019, -1019,
-1020, -1020, -1021, -1021, -1022, -1022, -1023, -1023,
-1023, -1024, -1024, -1024, -1024, -1024, -1024, -1024,
-1024, -1024, -1024, -1024, -1024, -1024, -1024, -1023,
-1023, -1023, -1022, -1022, -1021, -1021, -1020, -1020,
-1019, -1019, -1018, -1017, -1016, -1016, -1015, -1014,
-1013, -1012, -1011, -1010, -1009, -1008, -1007, -1005,
-1004, -1003, -1002, -1000, -999, -998, -996, -995,
-993, -991, -990, -988, -987, -985, -983, -981,
-979, -978, -976, -974, -972, -970, -968, -966,
-964, -961, -959, -957, -955, -952, -950, -948,
-945, -943, -940, -938, -935, -933, -930, -928,
-925, -922, -919, -917, -914, -911, -908, -905,
-902, -899, -896, -893, -890, -887, -884, -880,
-877, -874, -871, -867, -864, -861, -857, -854,
-850, -847, -843, -840, -836, -832, -829, -825,
-821, -817, -814, -810, -806, -802, -798, -794,
-790, -786, -782, -778, -774, -770, -766, -761,
-757, -753, -749, -744, -740, -736, -731, -727,
-722, -718, -713, -709, -704, -700, -695, -691,
-686, -681, -676, -672, -667, -662, -657, -653,
-648, -643, -638, -633, -628, -623, -618, -613,
-608, -603, -598, -593, -588, -582, -577, -572,
-567, -562, -556, -551, -546, -540, -535, -530,
-524, -519, -513, -508, -502, -497, -492, -486,
-480, -475, -469, -464, -458, -452, -447, -441,
-435, -430, -424, -418, -413, -407, -401, -395,
-389, -384, -378, -372, -366, -360, -354, -348,
-343, -337, -331, -325, -319, -313, -307, -301,
-295, -289, -283, -277, -271, -265, -258, -252,
-246, -240, -234, -228, -222, -216, -210, -203,
-197, -191, -185, -179, -172, -166, -160, -154,
-148, -141, -135, -129, -123, -116, -110, -104,
-98, -91, -85, -79, -73, -66, -60, -54,
-48, -41, -35, -29, -22, -16, -10, -4
};
// this is the program the generate the above table
#if 0
#include <stdio.h>
#include <math.h>
#ifndef M_PI
#define M_PI 3.14159265358979323846
#endif
#define PFREAL_ONE 1024
#define IANGLE_MAX 1024
int main(int, char**)
{
FILE*f = fopen("table.c","wt");
fprintf(f,"PFreal sinTable[] = {\n");
for(int i = 0; i < 128; i++)
{
for(int j = 0; j < 8; j++)
{
int iang = j+i*8;
double ii = (double)iang + 0.5;
double angle = ii * 2 * M_PI / IANGLE_MAX;
double sinAngle = sin(angle);
fprintf(f,"%6d, ", (int)(floor(PFREAL_ONE*sinAngle)));
}
fprintf(f,"\n");
}
fprintf(f,"};\n");
fclose(f);
return 0;
}
#endif
// }}}
inline PFreal fsin(int iangle)
{
while(iangle < 0)
iangle += IANGLE_MAX;
return sinTable[iangle & IANGLE_MASK];
}
inline PFreal fcos(int iangle)
{
// quarter phase shift
return fsin(iangle + (IANGLE_MAX >> 2));
}
struct SlideInfo
{
int slideIndex;
int angle;
PFreal cx;
PFreal cy;
};
static const QString OFFSET_KEY("offset");
static const QString WIDTH_KEY("width");
// PicturePlowPrivate {{{
class PictureFlowPrivate
{
public:
PictureFlowPrivate(PictureFlow* widget, int queueLength);
int slideCount() const;
void setSlideCount(int count);
QSize slideSize() const;
void setSlideSize(QSize size);
int zoomFactor() const;
void setZoomFactor(int z);
QImage slide(int index) const;
void setSlide(int index, const QImage& image);
int currentSlide() const;
void setCurrentSlide(int index);
bool showReflections() const;
void setShowReflections(bool show);
int getTarget() const;
void showPrevious();
void showNext();
void showSlide(int index);
void resize(int w, int h);
void render();
void startAnimation();
void updateAnimation();
void clearSurfaceCache();
QImage buffer;
QBasicTimer animateTimer;
bool singlePress;
int singlePressThreshold;
QPoint firstPress;
QPoint previousPos;
QTime previousPosTimestamp;
int pixelDistanceMoved;
int pixelsToMovePerSlide;
bool preserveAspectRatio;
QFont subtitleFont;
void setImages(FlowImages *images);
void dataChanged();
private:
PictureFlow* widget;
FlowImages *slideImages;
int slideWidth;
int slideHeight;
int fontSize;
int queueLength;
bool doReflections;
int centerIndex;
SlideInfo centerSlide;
QVector<SlideInfo> leftSlides;
QVector<SlideInfo> rightSlides;
QVector<PFreal> rays;
int itilt;
int spacing;
PFreal offsetX;
PFreal offsetY;
QImage blankSurface;
QCache<int, QImage> surfaceCache;
QTimer triggerTimer;
long long slideFrame;
int step;
int target;
int fade;
void recalc(int w, int h);
QRect renderSlide(const SlideInfo &slide, int alpha=256, int col1=-1, int col=-1);
QRect renderCenterSlide(const SlideInfo &slide);
QImage* surface(int slideIndex);
void triggerRender();
void resetSlides();
void render_text(QPainter*, int);
};
PictureFlowPrivate::PictureFlowPrivate(PictureFlow* w, int queueLength_)
{
widget = w;
slideImages = new FlowImages();
slideWidth = 200;
slideHeight = 200;
fontSize = 10;
doReflections = true;
preserveAspectRatio = false;
centerIndex = 0;
queueLength = queueLength_;
slideFrame = 0;
step = 0;
target = 0;
fade = 256;
subtitleFont = QFont();
triggerTimer.setSingleShot(true);
triggerTimer.setInterval(0);
QObject::connect(&triggerTimer, SIGNAL(timeout()), widget, SLOT(render()));
recalc(200, 200);
resetSlides();
}
void PictureFlowPrivate::dataChanged() {
surfaceCache.clear();
resetSlides();
triggerRender();
}
void PictureFlowPrivate::setImages(FlowImages *images)
{
QObject::disconnect(slideImages, SIGNAL(dataChanged()), widget, SLOT(dataChanged()));
slideImages = images;
dataChanged();
QObject::connect(slideImages, SIGNAL(dataChanged()), widget, SLOT(dataChanged()),
Qt::QueuedConnection);
}
int PictureFlowPrivate::slideCount() const
{
return slideImages->count();
}
QSize PictureFlowPrivate::slideSize() const
{
return QSize(slideWidth, slideHeight);
}
void PictureFlowPrivate::setSlideSize(QSize size)
{
slideWidth = size.width();
slideHeight = size.height();
recalc(buffer.width(), buffer.height());
triggerRender();
}
QImage PictureFlowPrivate::slide(int index) const
{
return slideImages->image(index);
}
int PictureFlowPrivate::getTarget() const
{
return target;
}
int PictureFlowPrivate::currentSlide() const
{
return centerIndex;
}
void PictureFlowPrivate::setCurrentSlide(int index)
{
animateTimer.stop();
step = 0;
centerIndex = qBound(0, index, qMax(0, slideImages->count()-1));
target = centerIndex;
slideFrame = ((long long)centerIndex) << 16;
resetSlides();
triggerRender();
widget->emitcurrentChanged(centerIndex);
}
bool PictureFlowPrivate::showReflections() const {
return doReflections;
}
void PictureFlowPrivate::setShowReflections(bool show) {
doReflections = show;
triggerRender();
}
void PictureFlowPrivate::showPrevious()
{
if(step >= 0)
{
if(centerIndex > 0)
{
target--;
startAnimation();
}
}
else
{
target = qMax(0, centerIndex - 2);
}
}
void PictureFlowPrivate::showNext()
{
if(step <= 0)
{
if(centerIndex < slideImages->count()-1)
{
target++;
startAnimation();
}
}
else
{
target = qMin(centerIndex + 2, slideImages->count()-1);
}
}
void PictureFlowPrivate::showSlide(int index)
{
index = qMax(index, 0);
index = qMin(slideImages->count()-1, index);
if(index == centerSlide.slideIndex)
return;
target = index;
startAnimation();
}
void PictureFlowPrivate::resize(int w, int h)
{
if (w < 10) w = 10;
if (h < 10) h = 10;
slideHeight = int(float(h)/REFLECTION_FACTOR);
slideWidth = int(float(slideHeight) * 3./4.);
//qDebug() << slideHeight << "x" << slideWidth;
fontSize = MAX(int(h/15.), 12);
recalc(w, h);
resetSlides();
triggerRender();
}
// adjust slides so that they are in "steady state" position
void PictureFlowPrivate::resetSlides()
{
centerSlide.angle = 0;
centerSlide.cx = 0;
centerSlide.cy = 0;
centerSlide.slideIndex = centerIndex;
leftSlides.clear();
leftSlides.resize(queueLength);
for(int i = 0; i < leftSlides.count(); i++)
{
SlideInfo& si = leftSlides[i];
si.angle = itilt;
si.cx = -(offsetX + spacing*i*PFREAL_ONE);
si.cy = offsetY;
si.slideIndex = centerIndex-1-i;
//qDebug() << "Left[" << i << "] x=" << fixedToFloat(si.cx) << ", y=" << fixedToFloat(si.cy) ;
}
rightSlides.clear();
rightSlides.resize(queueLength);
for(int i = 0; i < rightSlides.count(); i++)
{
SlideInfo& si = rightSlides[i];
si.angle = -itilt;
si.cx = offsetX + spacing*i*PFREAL_ONE;
si.cy = offsetY;
si.slideIndex = centerIndex+1+i;
//qDebug() << "Right[" << i << "] x=" << fixedToFloat(si.cx) << ", y=" << fixedToFloat(si.cy) ;
}
}
static QImage prepareSurface(QImage srcimg, int w, int h, bool doReflections, bool preserveAspectRatio)
{
// slightly larger, to accommodate for the reflection
int hs = int(h * REFLECTION_FACTOR), left = 0, top = 0, a = 0, r = 0, g = 0, b = 0, ht, x, y, bpp;
QImage img = (preserveAspectRatio) ? QImage(w, h, srcimg.format()) : srcimg.scaled(w, h, Qt::IgnoreAspectRatio, Qt::SmoothTransformation);
QRgb color;
// offscreen buffer: black is sweet
QImage result(hs, w, QImage::Format_RGB16);
result.fill(0);
if (preserveAspectRatio) {
QImage temp = srcimg.scaled(w, h, Qt::KeepAspectRatio, Qt::SmoothTransformation);
img = QImage(w, h, temp.format());
img.fill(0);
left = (w - temp.width()) / 2;
top = h - temp.height();
bpp = img.bytesPerLine() / img.width();
x = temp.width() * bpp;
result.setText(OFFSET_KEY, QString::number(left));
result.setText(WIDTH_KEY, QString::number(temp.width()));
for (y = 0; y < temp.height(); y++) {
const uchar *src = temp.scanLine(y);
uchar *dest = img.scanLine(top + y) + (bpp * left);
memcpy(dest, src, x);
}
}
// transpose the image, this is to speed-up the rendering
// because we process one column at a time
// (and much better and faster to work row-wise, i.e in one scanline)
for(x = 0; x < w; x++)
for(y = 0; y < h; y++)
result.setPixel(y, x, img.pixel(x, y));
if (doReflections) {
// create the reflection
ht = hs - h;
for(x = 0; x < w; x++)
for(y = 0; y < ht; y++)
{
color = img.pixel(x, img.height()-y-1);
//QRgb565 color = img.scanLine(img.height()-y-1) + x*sizeof(QRgb565); //img.pixel(x, img.height()-y-1);
a = qAlpha(color);
r = qRed(color) * a / 256 * (ht - y) / ht * 3/5;
g = qGreen(color) * a / 256 * (ht - y) / ht * 3/5;
b = qBlue(color) * a / 256 * (ht - y) / ht * 3/5;
result.setPixel(h+y, x, qRgb(r, g, b));
}
}
return result;
}
// get transformed image for specified slide
// if it does not exist, create it and place it in the cache
QImage* PictureFlowPrivate::surface(int slideIndex)
{
if(slideIndex < 0)
return 0;
if(slideIndex >= slideImages->count())
return 0;
if(surfaceCache.contains(slideIndex))
return surfaceCache[slideIndex];
QImage img = widget->slide(slideIndex);
if(img.isNull())
{
if(blankSurface.isNull())
{
blankSurface = QImage(slideWidth, slideHeight, QImage::Format_RGB16);
QPainter painter(&blankSurface);
QPoint p1(slideWidth*4/10, 0);
QPoint p2(slideWidth*6/10, slideHeight);
QLinearGradient linearGrad(p1, p2);
linearGrad.setColorAt(0, Qt::black);
linearGrad.setColorAt(1, Qt::white);
painter.setBrush(linearGrad);
painter.fillRect(0, 0, slideWidth, slideHeight, QBrush(linearGrad));
painter.setPen(QPen(QColor(64,64,64), 4));
painter.setBrush(QBrush());
painter.drawRect(2, 2, slideWidth-3, slideHeight-3);
painter.end();
blankSurface = prepareSurface(blankSurface, slideWidth, slideHeight, doReflections, preserveAspectRatio);
}
return &blankSurface;
}
surfaceCache.insert(slideIndex, new QImage(prepareSurface(img, slideWidth, slideHeight, doReflections, preserveAspectRatio)));
return surfaceCache[slideIndex];
}
// Schedules rendering the slides. Call this function to avoid immediate
// render and thus cause less flicker.
void PictureFlowPrivate::triggerRender()
{
triggerTimer.start();
}
void PictureFlowPrivate::render_text(QPainter *painter, int index) {
QRect brect, brect2;
int buffer_width, buffer_height;
QString caption, subtitle;
caption = slideImages->caption(index);
subtitle = slideImages->subtitle(index);
buffer_width = buffer.width(); buffer_height = buffer.height();
subtitleFont.setPixelSize(fontSize);
brect = painter->boundingRect(QRect(0, 0, buffer_width, fontSize), TEXT_FLAGS, caption);
painter->save();
painter->setFont(subtitleFont);
brect2 = painter->boundingRect(QRect(0, 0, buffer_width, fontSize), TEXT_FLAGS, subtitle);
painter->restore();
// So that if there is no subtitle, the caption is not flush with the bottom
if (brect2.height() < fontSize) brect2.setHeight(fontSize);
brect2.setHeight(brect2.height()+5); // A bit of buffer
// So that the text does not occupy more than the lower half of the buffer
if (brect.height() > ((int)(buffer.height()/3.0)) - fontSize*2)
brect.setHeight(((int)buffer.height()/3.0) - fontSize*2);
brect.moveTop(buffer_height - (brect.height() + brect2.height()));
//printf("top: %d, height: %d\n", brect.top(), brect.height());
//
painter->drawText(brect, TEXT_FLAGS, caption);
brect2.moveTop(buffer_height - brect2.height());
painter->save();
painter->setFont(subtitleFont);
painter->drawText(brect2, TEXT_FLAGS, slideImages->subtitle(index));
painter->restore();
}
// Render the slides. Updates only the offscreen buffer.
void PictureFlowPrivate::render()
{
buffer.fill(0);
int nleft = leftSlides.count();
int nright = rightSlides.count();
QRect r;
if (step == 0)
r = renderCenterSlide(centerSlide);
else
r = renderSlide(centerSlide);
int c1 = r.left();
int c2 = r.right();
if(step == 0)
{
// no animation, boring plain rendering
for(int index = 0; index < nleft-1; index++)
{
int alpha = (index < nleft-2) ? 256 : 128;
QRect rs = renderSlide(leftSlides[index], alpha, 0, c1-1);
if(!rs.isEmpty())
c1 = rs.left();
}
for(int index = 0; index < nright-1; index++)
{
int alpha = (index < nright-2) ? 256 : 128;
QRect rs = renderSlide(rightSlides[index], alpha, c2+1, buffer.width());
if(!rs.isEmpty())
c2 = rs.right();
}
QPainter painter;
painter.begin(&buffer);
QFont font = QFont();
font.setBold(true);
font.setPixelSize(fontSize);
painter.setFont(font);
painter.setPen(Qt::white);
//painter.setPen(QColor(255,255,255,127));
if (centerIndex < slideCount() && centerIndex > -1) {
render_text(&painter, centerIndex);
}
painter.end();
}
else
{
// the first and last slide must fade in/fade out
for(int index = 0; index < nleft; index++)
{
int alpha = 256;
if(index == nleft-1)
alpha = (step > 0) ? 0 : 128-fade/2;
if(index == nleft-2)
alpha = (step > 0) ? 128-fade/2 : 256-fade/2;
if(index == nleft-3)
alpha = (step > 0) ? 256-fade/2 : 256;
QRect rs = renderSlide(leftSlides[index], alpha, 0, c1-1);
if(!rs.isEmpty())
c1 = rs.left();
alpha = (step > 0) ? 256-fade/2 : 256;
}
for(int index = 0; index < nright; index++)
{
int alpha = (index < nright-2) ? 256 : 128;
if(index == nright-1)
alpha = (step > 0) ? fade/2 : 0;
if(index == nright-2)
alpha = (step > 0) ? 128+fade/2 : fade/2;
if(index == nright-3)
alpha = (step > 0) ? 256 : 128+fade/2;
QRect rs = renderSlide(rightSlides[index], alpha, c2+1, buffer.width());
if(!rs.isEmpty())
c2 = rs.right();
}
QPainter painter;
painter.begin(&buffer);
QFont font = QFont();
font.setBold(true);
font.setPixelSize(fontSize);
painter.setFont(font);
int leftTextIndex = (step>0) ? centerIndex : centerIndex-1;
int sc = slideCount();
painter.setPen(QColor(255,255,255, (255-fade) ));
if (leftTextIndex < sc && leftTextIndex > -1) {
render_text(&painter, leftTextIndex);
}
painter.setPen(QColor(255,255,255, fade));
if (leftTextIndex+1 < sc && leftTextIndex > -2) {
render_text(&painter, leftTextIndex+1);
}
painter.end();
}
}
static inline uint BYTE_MUL_RGB16(uint x, uint a) {
a += 1;
uint t = (((x & 0x07e0)*a) >> 8) & 0x07e0;
t |= (((x & 0xf81f)*(a>>2)) >> 6) & 0xf81f;
return t;
}
static inline uint BYTE_MUL_RGB16_32(uint x, uint a) {
uint t = (((x & 0xf81f07e0) >> 5)*a) & 0xf81f07e0;
t |= (((x & 0x07e0f81f)*a) >> 5) & 0x07e0f81f;
return t;
}
QRect PictureFlowPrivate::renderCenterSlide(const SlideInfo &slide) {
QImage* src = surface(slide.slideIndex);
if(!src)
return QRect();
int sw = src->height();
int sh = src->width();
int h = buffer.height();
int srcoff = 0;
int left = buffer.width()/2 - sw/2;
if (left < 0) {
srcoff = -left;
sw += left;
left = 0;
}
QRect rect(left, 0, sw, h-1);
int xcon = MIN(h-1, sh-1);
int ycon = MIN(sw, buffer.width() - left);
for(int x = 0; x < xcon; x++)
for(int y = 0; y < ycon; y++)
buffer.setPixel(left + y, 1+x, src->pixel(x, srcoff+y));
return rect;
}
// Renders a slide to offscreen buffer. Returns a rect of the rendered area.
// alpha=256 means normal, alpha=0 is fully black, alpha=128 half transparent
// col1 and col2 limit the column for rendering.
QRect PictureFlowPrivate::renderSlide(const SlideInfo &slide, int alpha, int col1, int col2)
{
QImage* src = surface(slide.slideIndex);
if(!src)
return QRect();
QRect rect(0, 0, 0, 0);
int sw = src->height();
int sh = src->width();
int h = buffer.height();
int w = buffer.width();
if(col1 > col2)
{
int c = col2;
col2 = col1;
col1 = c;
}
col1 = (col1 >= 0) ? col1 : 0;
col2 = (col2 >= 0) ? col2 : w-1;
col1 = qMin(col1, w-1);
col2 = qMin(col2, w-1);
int distance = h;
PFreal sdx = fcos(slide.angle);
PFreal sdy = fsin(slide.angle);
PFreal xs = slide.cx - slideWidth * sdx/2;
PFreal ys = slide.cy - slideWidth * sdy/2;
PFreal dist = distance * PFREAL_ONE;
int xi = qMax((PFreal)0, ((w*PFREAL_ONE/2) + fdiv(xs*h, dist+ys)) >> PFREAL_SHIFT);
if(xi >= w)
return rect;
bool flag = false;
rect.setLeft(xi);
int img_offset = 0, img_width = 0;
bool slide_moving_to_center = false;
if (preserveAspectRatio) {
img_offset = src->text(OFFSET_KEY).toInt();
img_width = src->text(WIDTH_KEY).toInt();
slide_moving_to_center = slide.slideIndex == target && target != centerIndex;
}
for(int x = qMax(xi, col1); x <= col2; x++)
{
PFreal hity = 0;
PFreal fk = rays[x];
if(sdy)
{
fk = fk - fdiv(sdx,sdy);
hity = -fdiv((rays[x]*distance - slide.cx + slide.cy*sdx/sdy), fk);
}
dist = distance*PFREAL_ONE + hity;
if(dist < 0)
continue;
PFreal hitx = fmul(dist, rays[x]);
PFreal hitdist = fdiv(hitx - slide.cx, sdx);
int column = sw/2 + (hitdist >> PFREAL_SHIFT);
if(column >= sw)
break;
if(column < 0)
continue;
if (preserveAspectRatio && !slide_moving_to_center) {
// We dont want a black border at the edge of narrow images when the images are in the left or right stacks
if (slide.slideIndex < centerIndex) {
column = qMin(column + img_offset, sw - 1);
} else if (slide.slideIndex == centerIndex) {
if (target > centerIndex) column = qMin(column + img_offset, sw - 1);
else if (target < centerIndex) column = qMax(column - sw + img_offset + img_width, 0);
} else {
column = qMax(column - sw + img_offset + img_width, 0);
}
}
rect.setRight(x);
if(!flag)
rect.setLeft(x);
flag = true;
int y1 = h/2;
int y2 = y1+ 1;
QRgb565* pixel1 = (QRgb565*)(buffer.scanLine(y1)) + x;
QRgb565* pixel2 = (QRgb565*)(buffer.scanLine(y2)) + x;
int pixelstep = pixel2 - pixel1;
int center = sh/2;
int dy = dist / h;
int p1 = center*PFREAL_ONE - dy/2;
int p2 = center*PFREAL_ONE + dy/2;
const QRgb565 *ptr = (const QRgb565*)(src->scanLine(column));
if(alpha == 256)
while((y1 >= 0) && (y2 < h) && (p1 >= 0))
{
*pixel1 = ptr[p1 >> PFREAL_SHIFT];
*pixel2 = ptr[p2 >> PFREAL_SHIFT];
p1 -= dy;
p2 += dy;
y1--;
y2++;
pixel1 -= pixelstep;
pixel2 += pixelstep;
}
else
while((y1 >= 0) && (y2 < h) && (p1 >= 0))
{
QRgb565 c1 = ptr[p1 >> PFREAL_SHIFT];
QRgb565 c2 = ptr[p2 >> PFREAL_SHIFT];
*pixel1 = BYTE_MUL_RGB16(c1, alpha);
*pixel2 = BYTE_MUL_RGB16(c2, alpha);
/*
int r1 = qRed(c1) * alpha/256;
int g1 = qGreen(c1) * alpha/256;
int b1 = qBlue(c1) * alpha/256;
int r2 = qRed(c2) * alpha/256;
int g2 = qGreen(c2) * alpha/256;
int b2 = qBlue(c2) * alpha/256;
*pixel1 = qRgb(r1, g1, b1);
*pixel2 = qRgb(r2, g2, b2);
*/
p1 -= dy;
p2 += dy;
y1--;
y2++;
pixel1 -= pixelstep;
pixel2 += pixelstep;
}
}
rect.setTop(0);
rect.setBottom(h-1);
return rect;
}
// Updates look-up table and other stuff necessary for the rendering.
// Call this when the viewport size or slide dimension is changed.
void PictureFlowPrivate::recalc(int ww, int wh)
{
int w = (ww+1)/2;
int h = (wh+1)/2;
buffer = QImage(ww, wh, QImage::Format_RGB16);
buffer.fill(0);
rays.resize(w*2);
for(int i = 0; i < w; i++)
{
PFreal gg = (PFREAL_HALF + i * PFREAL_ONE) / (2*h);
rays[w-i-1] = -gg;
rays[w+i] = gg;
}
// pointer must move more than 1/15 of the window to enter drag mode
singlePressThreshold = ww / 15;
// qDebug() << "singlePressThreshold now set to " << singlePressThreshold;
pixelsToMovePerSlide = ww / 3;
// qDebug() << "pixelsToMovePerSlide now set to " << pixelsToMovePerSlide;
itilt = 80 * IANGLE_MAX / 360; // approx. 80 degrees tilted
offsetY = slideWidth/2 * fsin(itilt);
offsetY += slideWidth * PFREAL_ONE / 4;
// offsetX = slideWidth/2 * (PFREAL_ONE-fcos(itilt));
// offsetX += slideWidth * PFREAL_ONE;
// center slide + side slide
offsetX = slideWidth*PFREAL_ONE;
// offsetX = 150*PFREAL_ONE;//(slideWidth/2)*PFREAL_ONE + ( slideWidth*fcos(itilt) )/2;
// qDebug() << "center width = " << slideWidth;
// qDebug() << "side width = " << fixedToFloat(slideWidth/2 * (PFREAL_ONE-fcos(itilt)));
// qDebug() << "offsetX now " << fixedToFloat(offsetX);
spacing = slideWidth/5;
surfaceCache.clear();
blankSurface = QImage();
}
void PictureFlowPrivate::startAnimation()
{
if(!animateTimer.isActive())
{
step = (target < centerSlide.slideIndex) ? -1 : 1;
animateTimer.start(30, widget);
}
}
// Updates the animation effect. Call this periodically from a timer.
void PictureFlowPrivate::updateAnimation()
{
if(!animateTimer.isActive())
return;
if(step == 0)
return;
int speed = 16384;
// deaccelerate when approaching the target
if(true)
{
const int max = 2 * 65536;
int fi = slideFrame;
fi -= (target << 16);
if(fi < 0)
fi = -fi;
fi = qMin(fi, max);
int ia = IANGLE_MAX * (fi-max/2) / (max*2);
speed = 512 + 16384 * (PFREAL_ONE+fsin(ia))/PFREAL_ONE;
}
slideFrame += speed*step;
int index = slideFrame >> 16;
int pos = slideFrame & 0xffff;
int neg = 65536 - pos;
int tick = (step < 0) ? neg : pos;
PFreal ftick = (tick * PFREAL_ONE) >> 16;
// the leftmost and rightmost slide must fade away
fade = pos / 256;
if(step < 0)
index++;
if(centerIndex != index)
{
centerIndex = index;
slideFrame = ((long long)index) << 16;
centerSlide.slideIndex = centerIndex;
for(int i = 0; i < leftSlides.count(); i++)
leftSlides[i].slideIndex = centerIndex-1-i;
for(int i = 0; i < rightSlides.count(); i++)
rightSlides[i].slideIndex = centerIndex+1+i;
widget->emitcurrentChanged(centerIndex);
}
centerSlide.angle = (step * tick * itilt) >> 16;
centerSlide.cx = -step * fmul(offsetX, ftick);
centerSlide.cy = fmul(offsetY, ftick);
if(centerIndex == target)
{
resetSlides();
animateTimer.stop();
triggerRender();
step = 0;
fade = 256;
return;
}
for(int i = 0; i < leftSlides.count(); i++)
{
SlideInfo& si = leftSlides[i];
si.angle = itilt;
si.cx = -(offsetX + spacing*i*PFREAL_ONE + step*spacing*ftick);
si.cy = offsetY;
}
for(int i = 0; i < rightSlides.count(); i++)
{
SlideInfo& si = rightSlides[i];
si.angle = -itilt;
si.cx = offsetX + spacing*i*PFREAL_ONE - step*spacing*ftick;
si.cy = offsetY;
}
if(step > 0)
{
PFreal ftick = (neg * PFREAL_ONE) >> 16;
rightSlides[0].angle = -(neg * itilt) >> 16;
rightSlides[0].cx = fmul(offsetX, ftick);
rightSlides[0].cy = fmul(offsetY, ftick);
}
else
{
PFreal ftick = (pos * PFREAL_ONE) >> 16;
leftSlides[0].angle = (pos * itilt) >> 16;
leftSlides[0].cx = -fmul(offsetX, ftick);
leftSlides[0].cy = fmul(offsetY, ftick);
}
// must change direction ?
if(target < index) if(step > 0)
step = -1;
if(target > index) if(step < 0)
step = 1;
triggerRender();
}
void PictureFlowPrivate::clearSurfaceCache()
{
surfaceCache.clear();
}
// }}}
// PictureFlow {{{
PictureFlow::PictureFlow(QWidget* parent, int queueLength): QWidget(parent)
{
d = new PictureFlowPrivate(this, queueLength);
setAttribute(Qt::WA_StaticContents, true);
setAttribute(Qt::WA_OpaquePaintEvent, true);
setAttribute(Qt::WA_NoSystemBackground, true);
#ifdef Q_WS_QWS
if (QScreen::instance()->pixelFormat() != QImage::Format_Invalid)
setAttribute(Qt::WA_PaintOnScreen, true);
#endif
}
PictureFlow::~PictureFlow()
{
delete d;
}
QSize PictureFlow::slideSize() const
{
return d->slideSize();
}
void PictureFlow::setSlideSize(QSize size)
{
d->setSlideSize(size);
}
bool PictureFlow::preserveAspectRatio() const
{
return d->preserveAspectRatio;
}
void PictureFlow::setPreserveAspectRatio(bool preserve)
{
d->preserveAspectRatio = preserve;
clearCaches();
}
void PictureFlow::setSubtitleFont(QFont font)
{
d->subtitleFont = font;
}
QFont PictureFlow::subtitleFont() const
{
return d->subtitleFont;
}
QImage PictureFlow::slide(int index) const
{
return d->slide(index);
}
bool PictureFlow::showReflections() const {
return d->showReflections();
}
void PictureFlow::setShowReflections(bool show) {
d->setShowReflections(show);
}
void PictureFlow::setImages(FlowImages *images)
{
d->setImages(images);
}
int PictureFlow::currentSlide() const
{
return d->currentSlide();
}
void PictureFlow::setCurrentSlide(int index)
{
d->setCurrentSlide(index);
}
void PictureFlow::clearCaches()
{
d->clearSurfaceCache();
}
void PictureFlow::render()
{
d->render();
update();
}
void PictureFlow::showPrevious()
{
d->showPrevious();
}
void PictureFlow::showNext()
{
d->showNext();
}
void PictureFlow::showSlide(int index)
{
d->showSlide(index);
}
void PictureFlow::keyPressEvent(QKeyEvent* event)
{
if(event->key() == Qt::Key_Left)
{
if(event->modifiers() == Qt::ControlModifier)
showSlide(currentSlide()-10);
else
showPrevious();
event->accept();
return;
}
if(event->key() == Qt::Key_Right)
{
if(event->modifiers() == Qt::ControlModifier)
showSlide(currentSlide()+10);
else
showNext();
event->accept();
return;
}
if(event->key() == Qt::Key_Escape)
{
emit stop();
event->accept();
return;
}
event->ignore();
}
#define SPEED_LOWER_THRESHOLD 10
#define SPEED_UPPER_LIMIT 40
void PictureFlow::mouseMoveEvent(QMouseEvent* event)
{
int distanceMovedSinceLastEvent = event->pos().x() - d->previousPos.x();
// Check to see if we need to switch from single press mode to a drag mode
if (d->singlePress)
{
// Increment the distance moved for this event
d->pixelDistanceMoved += distanceMovedSinceLastEvent;
// Check against threshold
if (qAbs(d->pixelDistanceMoved) > d->singlePressThreshold)
{
d->singlePress = false;
// qDebug() << "DRAG MODE ON";
}
}
if (!d->singlePress)
{
int speed;
// Calculate velocity in a 10th of a window width per second
if (d->previousPosTimestamp.elapsed() == 0)
speed = SPEED_LOWER_THRESHOLD;
else
{
speed = ((qAbs(event->pos().x()-d->previousPos.x())*1000) / d->previousPosTimestamp.elapsed())
/ (d->buffer.width() / 10);
if (speed < SPEED_LOWER_THRESHOLD)
speed = SPEED_LOWER_THRESHOLD;
else if (speed > SPEED_UPPER_LIMIT)
speed = SPEED_UPPER_LIMIT;
else {
speed = SPEED_LOWER_THRESHOLD + (speed / 3);
// qDebug() << "ACCELERATION ENABLED Speed = " << speed << ", Distance = " << distanceMovedSinceLastEvent;
}
}
// qDebug() << "Speed = " << speed;
// int incr = ((event->pos().x() - d->previousPos.x())/10) * speed;
// qDebug() << "Incremented by " << incr;
int incr = (distanceMovedSinceLastEvent * speed);
//qDebug() << "(distanceMovedSinceLastEvent * speed) = " << incr;
if (incr > d->pixelsToMovePerSlide*2) {
incr = d->pixelsToMovePerSlide*2;
//qDebug() << "Limiting incr to " << incr;
}
d->pixelDistanceMoved += (distanceMovedSinceLastEvent * speed);
// qDebug() << "distance: " << d->pixelDistanceMoved;
int slideInc;
slideInc = d->pixelDistanceMoved / (d->pixelsToMovePerSlide * 10);
if (slideInc != 0) {
int targetSlide = d->getTarget() - slideInc;
showSlide(targetSlide);
// qDebug() << "TargetSlide = " << targetSlide;
//qDebug() << "Decrementing pixelDistanceMoved by " << (d->pixelsToMovePerSlide *10) * slideInc;
d->pixelDistanceMoved -= (d->pixelsToMovePerSlide *10) * slideInc;
/*
if ( (targetSlide <= 0) || (targetSlide >= d->slideCount()-1) )
d->pixelDistanceMoved = 0;
*/
}
}
d->previousPos = event->pos();
d->previousPosTimestamp.restart();
emit inputReceived();
}
void PictureFlow::mousePressEvent(QMouseEvent* event)
{
d->firstPress = event->pos();
d->previousPos = event->pos();
d->previousPosTimestamp.start();
d->singlePress = true; // Initially assume a single press
// d->dragStartSlide = d->getTarget();
d->pixelDistanceMoved = 0;
emit inputReceived();
}
void PictureFlow::mouseReleaseEvent(QMouseEvent* event)
{
bool accepted = false;
int sideWidth = (d->buffer.width() - slideSize().width()) /2;
if (d->singlePress)
{
if (event->x() < sideWidth )
{
showPrevious();
accepted = true;
} else if ( event->x() > sideWidth + slideSize().width() ) {
showNext();
accepted = true;
} else {
if (event->button() == Qt::LeftButton) {
emit itemActivated(d->getTarget());
accepted = true;
}
}
if (accepted) {
event->accept();
}
}
emit inputReceived();
}
void PictureFlow::paintEvent(QPaintEvent* event)
{
Q_UNUSED(event);
QPainter painter(this);
painter.setRenderHint(QPainter::Antialiasing, false);
painter.drawImage(QPoint(0,0), d->buffer);
}
void PictureFlow::resizeEvent(QResizeEvent* event)
{
d->resize(width(), height());
QWidget::resizeEvent(event);
}
void PictureFlow::timerEvent(QTimerEvent* event)
{
if(event->timerId() == d->animateTimer.timerId())
{
// QTime now = QTime::currentTime();
d->updateAnimation();
// d->animateTimer.start(qMax(0, 30-now.elapsed() ), this);
}
else
QWidget::timerEvent(event);
}
void PictureFlow::dataChanged() { d->dataChanged(); }
void PictureFlow::emitcurrentChanged(int index) { emit currentChanged(index); }
int FlowImages::count() { return 0; }
QImage FlowImages::image(int index) { Q_UNUSED(index); return QImage(); }
QString FlowImages::caption(int index) { Q_UNUSED(index); return QString(); }
QString FlowImages::subtitle(int index) { Q_UNUSED(index); return QString(); }
// }}}
| nozuono/calibre-webserver | src/calibre/gui2/pictureflow/pictureflow.cpp | C++ | gpl-3.0 | 43,872 |
'use strict';var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
if (typeof Reflect === "object" && typeof Reflect.decorate === "function") return Reflect.decorate(decorators, target, key, desc);
switch (arguments.length) {
case 2: return decorators.reduceRight(function(o, d) { return (d && d(o)) || o; }, target);
case 3: return decorators.reduceRight(function(o, d) { return (d && d(target, key)), void 0; }, void 0);
case 4: return decorators.reduceRight(function(o, d) { return (d && d(target, key, o)) || o; }, desc);
}
};
var __metadata = (this && this.__metadata) || function (k, v) {
if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
};
var di_1 = require('angular2/src/core/di');
var serializer_1 = require('angular2/src/web_workers/shared/serializer');
var messaging_api_1 = require('angular2/src/web_workers/shared/messaging_api');
var xhr_1 = require('angular2/src/core/compiler/xhr');
var service_message_broker_1 = require('angular2/src/web_workers/shared/service_message_broker');
var bind_1 = require('./bind');
var MessageBasedXHRImpl = (function () {
function MessageBasedXHRImpl(_brokerFactory, _xhr) {
this._brokerFactory = _brokerFactory;
this._xhr = _xhr;
}
MessageBasedXHRImpl.prototype.start = function () {
var broker = this._brokerFactory.createMessageBroker(messaging_api_1.XHR_CHANNEL);
broker.registerMethod("get", [serializer_1.PRIMITIVE], bind_1.bind(this._xhr.get, this._xhr), serializer_1.PRIMITIVE);
};
MessageBasedXHRImpl = __decorate([
di_1.Injectable(),
__metadata('design:paramtypes', [service_message_broker_1.ServiceMessageBrokerFactory, xhr_1.XHR])
], MessageBasedXHRImpl);
return MessageBasedXHRImpl;
})();
exports.MessageBasedXHRImpl = MessageBasedXHRImpl;
//# sourceMappingURL=xhr_impl.js.map | NodeVision/NodeVision | node_modules/angular2/src/web_workers/ui/xhr_impl.js | JavaScript | gpl-3.0 | 1,947 |
define("ghost-admin/templates/components/gh-subscribers-table", ["exports"], function (exports) {
exports["default"] = Ember.HTMLBars.template((function () {
var child0 = (function () {
var child0 = (function () {
var child0 = (function () {
var child0 = (function () {
return {
meta: {
"fragmentReason": false,
"revision": "Ember@2.6.1",
"loc": {
"source": null,
"start": {
"line": 6,
"column": 12
},
"end": {
"line": 8,
"column": 12
}
},
"moduleName": "ghost-admin/templates/components/gh-subscribers-table.hbs"
},
isEmpty: false,
arity: 0,
cachedFragment: null,
hasRendered: false,
buildFragment: function buildFragment(dom) {
var el0 = dom.createDocumentFragment();
var el1 = dom.createTextNode(" Loading...\n");
dom.appendChild(el0, el1);
return el0;
},
buildRenderNodes: function buildRenderNodes() {
return [];
},
statements: [],
locals: [],
templates: []
};
})();
return {
meta: {
"fragmentReason": false,
"revision": "Ember@2.6.1",
"loc": {
"source": null,
"start": {
"line": 5,
"column": 8
},
"end": {
"line": 9,
"column": 8
}
},
"moduleName": "ghost-admin/templates/components/gh-subscribers-table.hbs"
},
isEmpty: false,
arity: 0,
cachedFragment: null,
hasRendered: false,
buildFragment: function buildFragment(dom) {
var el0 = dom.createDocumentFragment();
var el1 = dom.createComment("");
dom.appendChild(el0, el1);
return el0;
},
buildRenderNodes: function buildRenderNodes(dom, fragment, contextualElement) {
var morphs = new Array(1);
morphs[0] = dom.createMorphAt(fragment, 0, 0, contextualElement);
dom.insertBoundary(fragment, 0);
dom.insertBoundary(fragment, null);
return morphs;
},
statements: [["block", "body.loader", [], [], 0, null, ["loc", [null, [6, 12], [8, 28]]]]],
locals: [],
templates: [child0]
};
})();
var child1 = (function () {
var child0 = (function () {
var child0 = (function () {
return {
meta: {
"fragmentReason": false,
"revision": "Ember@2.6.1",
"loc": {
"source": null,
"start": {
"line": 11,
"column": 16
},
"end": {
"line": 13,
"column": 16
}
},
"moduleName": "ghost-admin/templates/components/gh-subscribers-table.hbs"
},
isEmpty: false,
arity: 0,
cachedFragment: null,
hasRendered: false,
buildFragment: function buildFragment(dom) {
var el0 = dom.createDocumentFragment();
var el1 = dom.createTextNode(" No subscribers found.\n");
dom.appendChild(el0, el1);
return el0;
},
buildRenderNodes: function buildRenderNodes() {
return [];
},
statements: [],
locals: [],
templates: []
};
})();
return {
meta: {
"fragmentReason": false,
"revision": "Ember@2.6.1",
"loc": {
"source": null,
"start": {
"line": 10,
"column": 12
},
"end": {
"line": 14,
"column": 12
}
},
"moduleName": "ghost-admin/templates/components/gh-subscribers-table.hbs"
},
isEmpty: false,
arity: 0,
cachedFragment: null,
hasRendered: false,
buildFragment: function buildFragment(dom) {
var el0 = dom.createDocumentFragment();
var el1 = dom.createComment("");
dom.appendChild(el0, el1);
return el0;
},
buildRenderNodes: function buildRenderNodes(dom, fragment, contextualElement) {
var morphs = new Array(1);
morphs[0] = dom.createMorphAt(fragment, 0, 0, contextualElement);
dom.insertBoundary(fragment, 0);
dom.insertBoundary(fragment, null);
return morphs;
},
statements: [["block", "body.no-data", [], [], 0, null, ["loc", [null, [11, 16], [13, 33]]]]],
locals: [],
templates: [child0]
};
})();
return {
meta: {
"fragmentReason": false,
"revision": "Ember@2.6.1",
"loc": {
"source": null,
"start": {
"line": 9,
"column": 8
},
"end": {
"line": 15,
"column": 8
}
},
"moduleName": "ghost-admin/templates/components/gh-subscribers-table.hbs"
},
isEmpty: false,
arity: 0,
cachedFragment: null,
hasRendered: false,
buildFragment: function buildFragment(dom) {
var el0 = dom.createDocumentFragment();
var el1 = dom.createComment("");
dom.appendChild(el0, el1);
return el0;
},
buildRenderNodes: function buildRenderNodes(dom, fragment, contextualElement) {
var morphs = new Array(1);
morphs[0] = dom.createMorphAt(fragment, 0, 0, contextualElement);
dom.insertBoundary(fragment, 0);
dom.insertBoundary(fragment, null);
return morphs;
},
statements: [["block", "if", [["get", "table.isEmpty", ["loc", [null, [10, 18], [10, 31]]]]], [], 0, null, ["loc", [null, [10, 12], [14, 19]]]]],
locals: [],
templates: [child0]
};
})();
return {
meta: {
"fragmentReason": false,
"revision": "Ember@2.6.1",
"loc": {
"source": null,
"start": {
"line": 4,
"column": 4
},
"end": {
"line": 16,
"column": 4
}
},
"moduleName": "ghost-admin/templates/components/gh-subscribers-table.hbs"
},
isEmpty: false,
arity: 1,
cachedFragment: null,
hasRendered: false,
buildFragment: function buildFragment(dom) {
var el0 = dom.createDocumentFragment();
var el1 = dom.createComment("");
dom.appendChild(el0, el1);
return el0;
},
buildRenderNodes: function buildRenderNodes(dom, fragment, contextualElement) {
var morphs = new Array(1);
morphs[0] = dom.createMorphAt(fragment, 0, 0, contextualElement);
dom.insertBoundary(fragment, 0);
dom.insertBoundary(fragment, null);
return morphs;
},
statements: [["block", "if", [["get", "isLoading", ["loc", [null, [5, 14], [5, 23]]]]], [], 0, 1, ["loc", [null, [5, 8], [15, 15]]]]],
locals: ["body"],
templates: [child0, child1]
};
})();
return {
meta: {
"fragmentReason": {
"name": "missing-wrapper",
"problems": ["wrong-type", "multiple-nodes"]
},
"revision": "Ember@2.6.1",
"loc": {
"source": null,
"start": {
"line": 1,
"column": 0
},
"end": {
"line": 17,
"column": 0
}
},
"moduleName": "ghost-admin/templates/components/gh-subscribers-table.hbs"
},
isEmpty: false,
arity: 1,
cachedFragment: null,
hasRendered: false,
buildFragment: function buildFragment(dom) {
var el0 = dom.createDocumentFragment();
var el1 = dom.createTextNode(" ");
dom.appendChild(el0, el1);
var el1 = dom.createComment("");
dom.appendChild(el0, el1);
var el1 = dom.createTextNode("\n\n");
dom.appendChild(el0, el1);
var el1 = dom.createComment("");
dom.appendChild(el0, el1);
return el0;
},
buildRenderNodes: function buildRenderNodes(dom, fragment, contextualElement) {
var morphs = new Array(2);
morphs[0] = dom.createMorphAt(fragment, 1, 1, contextualElement);
morphs[1] = dom.createMorphAt(fragment, 3, 3, contextualElement);
dom.insertBoundary(fragment, null);
return morphs;
},
statements: [["inline", "t.head", [], ["onColumnClick", ["subexpr", "action", [["get", "sortByColumn", ["loc", [null, [2, 35], [2, 47]]]]], [], ["loc", [null, [2, 27], [2, 48]]]], "iconAscending", "icon-ascending", "iconDescending", "icon-descending"], ["loc", [null, [2, 4], [2, 114]]]], ["block", "t.body", [], ["canSelect", false, "tableActions", ["subexpr", "hash", [], ["delete", ["subexpr", "action", [["get", "delete", ["loc", [null, [4, 64], [4, 70]]]]], [], ["loc", [null, [4, 56], [4, 71]]]]], ["loc", [null, [4, 43], [4, 72]]]]], 0, null, ["loc", [null, [4, 4], [16, 15]]]]],
locals: ["t"],
templates: [child0]
};
})();
return {
meta: {
"fragmentReason": {
"name": "missing-wrapper",
"problems": ["wrong-type"]
},
"revision": "Ember@2.6.1",
"loc": {
"source": null,
"start": {
"line": 1,
"column": 0
},
"end": {
"line": 18,
"column": 0
}
},
"moduleName": "ghost-admin/templates/components/gh-subscribers-table.hbs"
},
isEmpty: false,
arity: 0,
cachedFragment: null,
hasRendered: false,
buildFragment: function buildFragment(dom) {
var el0 = dom.createDocumentFragment();
var el1 = dom.createComment("");
dom.appendChild(el0, el1);
return el0;
},
buildRenderNodes: function buildRenderNodes(dom, fragment, contextualElement) {
var morphs = new Array(1);
morphs[0] = dom.createMorphAt(fragment, 0, 0, contextualElement);
dom.insertBoundary(fragment, 0);
dom.insertBoundary(fragment, null);
return morphs;
},
statements: [["block", "gh-light-table", [["get", "table", ["loc", [null, [1, 18], [1, 23]]]]], ["scrollContainer", ".subscribers-table", "scrollBuffer", 100, "onScrolledToBottom", ["subexpr", "action", ["onScrolledToBottom"], [], ["loc", [null, [1, 97], [1, 126]]]]], 0, null, ["loc", [null, [1, 0], [17, 19]]]]],
locals: [],
templates: [child0]
};
})());
}); | Elektro1776/latestEarthables | core/client/tmp/broccoli_persistent_filterbabel-output_path-OKbFKF1N.tmp/ghost-admin/templates/components/gh-subscribers-table.js | JavaScript | gpl-3.0 | 12,139 |
<?php
/**
* 2007-2016 [PagSeguro Internet Ltda.]
*
* NOTICE OF LICENSE
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* @author PagSeguro Internet Ltda.
* @copyright 2007-2016 PagSeguro Internet Ltda.
* @license http://www.apache.org/licenses/LICENSE-2.0
*
*/
namespace PagSeguro\Parsers\PreApproval\Charge;
use PagSeguro\Domains\Requests\Requests;
use PagSeguro\Enum\Properties\Current;
use PagSeguro\Parsers\Basic;
use PagSeguro\Parsers\Item;
use PagSeguro\Parsers\Error;
use PagSeguro\Parsers\Parser;
use PagSeguro\Parsers\PreApproval\Response;
use PagSeguro\Resources\Http;
/**
* Request class
*/
class Request extends Error implements Parser
{
use Basic;
use Item;
/**
* @param Requests $request
* @param $request
* @return array
*/
public static function getData(Requests $request)
{
$data = [];
$properties = new Current;
if (!is_null($request->getCode())) {
$data[$properties::PRE_APPROVAL_CODE] = $request->getCode();
}
return array_merge(
$data,
Basic::getData($request, $properties),
Item::getData($request, $properties)
);
}
/**
* @param \PagSeguro\Resources\Http $http
* @return Response
*/
public static function success(Http $http)
{
$xml = simplexml_load_string($http->getResponse());
return (new Response)->setCode(current($xml->transactionCode))
->setDate(current($xml->date));
}
/**
* @param \PagSeguro\Resources\Http $http
* @return \PagSeguro\Domains\Error
*/
public static function error(Http $http)
{
$error = parent::error($http);
return $error;
}
}
| pagseguro/woocommerce | library/source/Parsers/PreApproval/Charge/Request.php | PHP | gpl-3.0 | 2,276 |
package org.impact2585.lib2585;
import java.io.Serializable;
import edu.wpi.first.wpilibj.IterativeRobot;
/**
* Robot that uses executers This is the equivelant of a main class in WPILib.
*/
public abstract class ExecutorBasedRobot extends IterativeRobot implements Serializable {
private static final long serialVersionUID = 2220871954112107703L;
private transient Executer executor;
private RobotEnvironment environ;
/*
* (non-Javadoc)
* @see edu.wpi.first.wpilibj.IterativeRobot#robotInit()
*/
@Override
public abstract void robotInit();
/*
* (non-Javadoc)
* @see edu.wpi.first.wpilibj.IterativeRobot#autonomousPeriodic()
*/
@Override
public void autonomousPeriodic() {
if (executor != null)
executor.execute();
}
/*
* (non-Javadoc)
* @see edu.wpi.first.wpilibj.IterativeRobot#teleopPeriodic()
*/
@Override
public void teleopPeriodic() {
if (executor != null)
executor.execute();
}
/*
* (non-Javadoc)
* @see edu.wpi.first.wpilibj.IterativeRobot#testPeriodic()
*/
@Override
public void testPeriodic() {
if (executor != null)
executor.execute();
}
/*
* (non-Javadoc)
* @see edu.wpi.first.wpilibj.IterativeRobot#disabledInit()
*/
@Override
public void disabledInit() {
setExecutor(null);
if (environ != null)
environ.stopRobot();
}
/*
* (non-Javadoc)
* @see edu.wpi.first.wpilibj.IterativeRobot#disabledPeriodic()
*/
@Override
public void disabledPeriodic() {
if (environ != null)
environ.stopRobot();
}
/**
* Accessor for executer
* @return the executer
*/
protected synchronized Executer getExecutor() {
return executor;
}
/**
* Mutator for executer
* @param executer the executer to set
*/
protected synchronized void setExecutor(Executer executer) {
this.executor = executer;
}
}
| Impact2585/Lib2585 | src/org/impact2585/lib2585/ExecutorBasedRobot.java | Java | gpl-3.0 | 1,813 |
package mv.view;
import java.awt.Color;
import javax.swing.JCheckBox;
import javax.swing.JLabel;
import javax.swing.JPanel;
import mv.controller.Controller;
import mv.model.OperandStack.Data;
@SuppressWarnings("serial")
public class StatusPanel extends JPanel implements mv.model.ControlUnit.Observer,
mv.model.Memory.Observer,
mv.model.OperandStack.Observer{
private Controller _controller;
private JLabel _info;
private JLabel _numInstructions;
private JCheckBox _firstCheck;
private JLabel _firstMessage;
private JCheckBox _secondCheck;
private JLabel _secondMessage;
private int _instructionCounter;
private boolean _stackChanged;
private boolean _memoryChanged;
public StatusPanel(Controller controller){
_controller = controller;
_instructionCounter = 0;
_info = new JLabel("Numero de intrucciones ejecutadas: ");
_numInstructions = new JLabel("0");
_firstCheck = new JCheckBox();
_firstCheck.setBackground(Color.gray);
_firstMessage = new JLabel("Pila modificada: ");
_secondCheck = new JCheckBox();
_secondCheck.setBackground(Color.gray);
_secondMessage = new JLabel("Memoria modificada: ");
setBackground(Color.gray);
add(_info);
add(_numInstructions);
add(_firstCheck);
add(_firstMessage);
add(_secondCheck);
add(_secondMessage);
_controller.addControlUnitObserver(this);
_controller.addStackObserver(this);
_controller.addMemoryObserver(this);
}
@Override
public void onCPchange(mv.model.ControlUnit.Data cpData) {
_instructionCounter++;
_numInstructions.setText("" + _instructionCounter);
if(_stackChanged && !_firstCheck.isSelected())
_firstCheck.doClick();
else if(!_stackChanged && _firstCheck.isSelected())
_firstCheck.doClick();
if(_memoryChanged && !_secondCheck.isSelected())
_secondCheck.doClick();
else if(!_memoryChanged && _secondCheck.isSelected())
_secondCheck.doClick();
_memoryChanged=false;
_stackChanged=false;
}
@Override
public void onStackChange(Data data) {
_stackChanged = true;
}
@Override
public void onMemoryChange(mv.model.Memory.Data data) {
_memoryChanged = true;
}
@Override
public void onHalt() {
// TODO Auto-generated method stub
}
}
| oka-haist/codeHere | tinyVirtualMachine/VMUndoMod/src/mv/view/StatusPanel.java | Java | gpl-3.0 | 2,286 |
/*
* Copyright (c) 2015 The CyanogenMod Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.lineageos.settings.doze;
import android.content.Context;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
import android.util.Log;
public class ProximitySensor implements SensorEventListener {
private static final boolean DEBUG = false;
private static final String TAG = "ProximitySensor";
private static final int POCKET_DELTA_NS = 1000 * 1000 * 1000;
private SensorManager mSensorManager;
private Sensor mSensor;
private Context mContext;
private boolean mSawNear = false;
private long mInPocketTime = 0;
public ProximitySensor(Context context) {
mContext = context;
mSensorManager = (SensorManager)
mContext.getSystemService(Context.SENSOR_SERVICE);
mSensor = mSensorManager.getDefaultSensor(Sensor.TYPE_PROXIMITY);
}
@Override
public void onSensorChanged(SensorEvent event) {
boolean isNear = event.values[0] < mSensor.getMaximumRange();
if (mSawNear && !isNear) {
if (shouldPulse(event.timestamp)) {
Utils.launchDozePulse(mContext);
}
} else {
mInPocketTime = event.timestamp;
}
mSawNear = isNear;
}
private boolean shouldPulse(long timestamp) {
long delta = timestamp - mInPocketTime;
if (Utils.handwaveGestureEnabled(mContext)
&& Utils.pocketGestureEnabled(mContext)) {
return true;
} else if (Utils.handwaveGestureEnabled(mContext)
&& !Utils.pocketGestureEnabled(mContext)) {
return delta < POCKET_DELTA_NS;
} else if (!Utils.handwaveGestureEnabled(mContext)
&& Utils.pocketGestureEnabled(mContext)) {
return delta >= POCKET_DELTA_NS;
}
return false;
}
@Override
public void onAccuracyChanged(Sensor sensor, int accuracy) {
/* Empty */
}
protected void enable() {
if (DEBUG) Log.d(TAG, "Enabling");
mSensorManager.registerListener(this, mSensor,
SensorManager.SENSOR_DELAY_NORMAL);
}
protected void disable() {
if (DEBUG) Log.d(TAG, "Disabling");
mSensorManager.unregisterListener(this, mSensor);
}
}
| psy-herolte/android_device_samsung_hero-common | doze/src/org/lineageos/settings/doze/ProximitySensor.java | Java | gpl-3.0 | 2,971 |
package org.json;
/**
* The JSONException is thrown by the JSON.org classes then things are amiss.
* @author JSON.org
* @version 2
*/
public class JSONException extends Exception {
private Throwable cause;
/**
* Constructs a JSONException with an explanatory message.
* @param message Detail about the reason for the exception.
*/
public JSONException(String message) {
super(message);
}
public JSONException(Throwable t) {
super(t.getMessage());
this.cause = t;
}
public Throwable getCause() {
return this.cause;
}
}
| yangsong19/DayPo | src/org/json/JSONException.java | Java | gpl-3.0 | 632 |
# -*- coding: utf-8 -*-
"""
sphinx.environment.managers.toctree
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Toctree manager for sphinx.environment.
:copyright: Copyright 2007-2016 by the Sphinx team, see AUTHORS.
:license: BSD, see LICENSE for details.
"""
from six import iteritems
from docutils import nodes
from sphinx import addnodes
from sphinx.util import url_re
from sphinx.util.nodes import clean_astext, process_only_nodes
from sphinx.transforms import SphinxContentsFilter
from sphinx.environment.managers import EnvironmentManager
class Toctree(EnvironmentManager):
name = 'toctree'
def __init__(self, env):
super(Toctree, self).__init__(env)
self.tocs = env.tocs
self.toc_num_entries = env.toc_num_entries
self.toc_secnumbers = env.toc_secnumbers
self.toc_fignumbers = env.toc_fignumbers
self.toctree_includes = env.toctree_includes
self.files_to_rebuild = env.files_to_rebuild
self.glob_toctrees = env.glob_toctrees
self.numbered_toctrees = env.numbered_toctrees
def clear_doc(self, docname):
self.tocs.pop(docname, None)
self.toc_secnumbers.pop(docname, None)
self.toc_fignumbers.pop(docname, None)
self.toc_num_entries.pop(docname, None)
self.toctree_includes.pop(docname, None)
self.glob_toctrees.discard(docname)
self.numbered_toctrees.discard(docname)
for subfn, fnset in list(self.files_to_rebuild.items()):
fnset.discard(docname)
if not fnset:
del self.files_to_rebuild[subfn]
def merge_other(self, docnames, other):
for docname in docnames:
self.tocs[docname] = other.tocs[docname]
self.toc_num_entries[docname] = other.toc_num_entries[docname]
if docname in other.toctree_includes:
self.toctree_includes[docname] = other.toctree_includes[docname]
if docname in other.glob_toctrees:
self.glob_toctrees.add(docname)
if docname in other.numbered_toctrees:
self.numbered_toctrees.add(docname)
for subfn, fnset in other.files_to_rebuild.items():
self.files_to_rebuild.setdefault(subfn, set()).update(fnset & docnames)
def process_doc(self, docname, doctree):
"""Build a TOC from the doctree and store it in the inventory."""
numentries = [0] # nonlocal again...
def traverse_in_section(node, cls):
"""Like traverse(), but stay within the same section."""
result = []
if isinstance(node, cls):
result.append(node)
for child in node.children:
if isinstance(child, nodes.section):
continue
result.extend(traverse_in_section(child, cls))
return result
def build_toc(node, depth=1):
entries = []
for sectionnode in node:
# find all toctree nodes in this section and add them
# to the toc (just copying the toctree node which is then
# resolved in self.get_and_resolve_doctree)
if isinstance(sectionnode, addnodes.only):
onlynode = addnodes.only(expr=sectionnode['expr'])
blist = build_toc(sectionnode, depth)
if blist:
onlynode += blist.children
entries.append(onlynode)
continue
if not isinstance(sectionnode, nodes.section):
for toctreenode in traverse_in_section(sectionnode,
addnodes.toctree):
item = toctreenode.copy()
entries.append(item)
# important: do the inventory stuff
self.note_toctree(docname, toctreenode)
continue
title = sectionnode[0]
# copy the contents of the section title, but without references
# and unnecessary stuff
visitor = SphinxContentsFilter(doctree)
title.walkabout(visitor)
nodetext = visitor.get_entry_text()
if not numentries[0]:
# for the very first toc entry, don't add an anchor
# as it is the file's title anyway
anchorname = ''
else:
anchorname = '#' + sectionnode['ids'][0]
numentries[0] += 1
# make these nodes:
# list_item -> compact_paragraph -> reference
reference = nodes.reference(
'', '', internal=True, refuri=docname,
anchorname=anchorname, *nodetext)
para = addnodes.compact_paragraph('', '', reference)
item = nodes.list_item('', para)
sub_item = build_toc(sectionnode, depth + 1)
item += sub_item
entries.append(item)
if entries:
return nodes.bullet_list('', *entries)
return []
toc = build_toc(doctree)
if toc:
self.tocs[docname] = toc
else:
self.tocs[docname] = nodes.bullet_list('')
self.toc_num_entries[docname] = numentries[0]
def note_toctree(self, docname, toctreenode):
"""Note a TOC tree directive in a document and gather information about
file relations from it.
"""
if toctreenode['glob']:
self.glob_toctrees.add(docname)
if toctreenode.get('numbered'):
self.numbered_toctrees.add(docname)
includefiles = toctreenode['includefiles']
for includefile in includefiles:
# note that if the included file is rebuilt, this one must be
# too (since the TOC of the included file could have changed)
self.files_to_rebuild.setdefault(includefile, set()).add(docname)
self.toctree_includes.setdefault(docname, []).extend(includefiles)
def get_toc_for(self, docname, builder):
"""Return a TOC nodetree -- for use on the same page only!"""
tocdepth = self.env.metadata[docname].get('tocdepth', 0)
try:
toc = self.tocs[docname].deepcopy()
self._toctree_prune(toc, 2, tocdepth)
except KeyError:
# the document does not exist anymore: return a dummy node that
# renders to nothing
return nodes.paragraph()
process_only_nodes(toc, builder.tags, warn_node=self.env.warn_node)
for node in toc.traverse(nodes.reference):
node['refuri'] = node['anchorname'] or '#'
return toc
def get_toctree_for(self, docname, builder, collapse, **kwds):
"""Return the global TOC nodetree."""
doctree = self.env.get_doctree(self.env.config.master_doc)
toctrees = []
if 'includehidden' not in kwds:
kwds['includehidden'] = True
if 'maxdepth' not in kwds:
kwds['maxdepth'] = 0
kwds['collapse'] = collapse
for toctreenode in doctree.traverse(addnodes.toctree):
toctree = self.env.resolve_toctree(docname, builder, toctreenode,
prune=True, **kwds)
if toctree:
toctrees.append(toctree)
if not toctrees:
return None
result = toctrees[0]
for toctree in toctrees[1:]:
result.extend(toctree.children)
return result
def resolve_toctree(self, docname, builder, toctree, prune=True, maxdepth=0,
titles_only=False, collapse=False, includehidden=False):
"""Resolve a *toctree* node into individual bullet lists with titles
as items, returning None (if no containing titles are found) or
a new node.
If *prune* is True, the tree is pruned to *maxdepth*, or if that is 0,
to the value of the *maxdepth* option on the *toctree* node.
If *titles_only* is True, only toplevel document titles will be in the
resulting tree.
If *collapse* is True, all branches not containing docname will
be collapsed.
"""
if toctree.get('hidden', False) and not includehidden:
return None
# For reading the following two helper function, it is useful to keep
# in mind the node structure of a toctree (using HTML-like node names
# for brevity):
#
# <ul>
# <li>
# <p><a></p>
# <p><a></p>
# ...
# <ul>
# ...
# </ul>
# </li>
# </ul>
#
# The transformation is made in two passes in order to avoid
# interactions between marking and pruning the tree (see bug #1046).
toctree_ancestors = self.get_toctree_ancestors(docname)
def _toctree_add_classes(node, depth):
"""Add 'toctree-l%d' and 'current' classes to the toctree."""
for subnode in node.children:
if isinstance(subnode, (addnodes.compact_paragraph,
nodes.list_item)):
# for <p> and <li>, indicate the depth level and recurse
subnode['classes'].append('toctree-l%d' % (depth-1))
_toctree_add_classes(subnode, depth)
elif isinstance(subnode, nodes.bullet_list):
# for <ul>, just recurse
_toctree_add_classes(subnode, depth+1)
elif isinstance(subnode, nodes.reference):
# for <a>, identify which entries point to the current
# document and therefore may not be collapsed
if subnode['refuri'] == docname:
if not subnode['anchorname']:
# give the whole branch a 'current' class
# (useful for styling it differently)
branchnode = subnode
while branchnode:
branchnode['classes'].append('current')
branchnode = branchnode.parent
# mark the list_item as "on current page"
if subnode.parent.parent.get('iscurrent'):
# but only if it's not already done
return
while subnode:
subnode['iscurrent'] = True
subnode = subnode.parent
def _entries_from_toctree(toctreenode, parents,
separate=False, subtree=False):
"""Return TOC entries for a toctree node."""
refs = [(e[0], e[1]) for e in toctreenode['entries']]
entries = []
for (title, ref) in refs:
try:
refdoc = None
if url_re.match(ref):
if title is None:
title = ref
reference = nodes.reference('', '', internal=False,
refuri=ref, anchorname='',
*[nodes.Text(title)])
para = addnodes.compact_paragraph('', '', reference)
item = nodes.list_item('', para)
toc = nodes.bullet_list('', item)
elif ref == 'self':
# 'self' refers to the document from which this
# toctree originates
ref = toctreenode['parent']
if not title:
title = clean_astext(self.env.titles[ref])
reference = nodes.reference('', '', internal=True,
refuri=ref,
anchorname='',
*[nodes.Text(title)])
para = addnodes.compact_paragraph('', '', reference)
item = nodes.list_item('', para)
# don't show subitems
toc = nodes.bullet_list('', item)
else:
if ref in parents:
self.env.warn(ref, 'circular toctree references '
'detected, ignoring: %s <- %s' %
(ref, ' <- '.join(parents)))
continue
refdoc = ref
toc = self.tocs[ref].deepcopy()
maxdepth = self.env.metadata[ref].get('tocdepth', 0)
if ref not in toctree_ancestors or (prune and maxdepth > 0):
self._toctree_prune(toc, 2, maxdepth, collapse)
process_only_nodes(toc, builder.tags, warn_node=self.env.warn_node)
if title and toc.children and len(toc.children) == 1:
child = toc.children[0]
for refnode in child.traverse(nodes.reference):
if refnode['refuri'] == ref and \
not refnode['anchorname']:
refnode.children = [nodes.Text(title)]
if not toc.children:
# empty toc means: no titles will show up in the toctree
self.env.warn_node(
'toctree contains reference to document %r that '
'doesn\'t have a title: no link will be generated'
% ref, toctreenode)
except KeyError:
# this is raised if the included file does not exist
self.env.warn_node(
'toctree contains reference to nonexisting document %r'
% ref, toctreenode)
else:
# if titles_only is given, only keep the main title and
# sub-toctrees
if titles_only:
# delete everything but the toplevel title(s)
# and toctrees
for toplevel in toc:
# nodes with length 1 don't have any children anyway
if len(toplevel) > 1:
subtrees = toplevel.traverse(addnodes.toctree)
if subtrees:
toplevel[1][:] = subtrees
else:
toplevel.pop(1)
# resolve all sub-toctrees
for subtocnode in toc.traverse(addnodes.toctree):
if not (subtocnode.get('hidden', False) and
not includehidden):
i = subtocnode.parent.index(subtocnode) + 1
for item in _entries_from_toctree(
subtocnode, [refdoc] + parents,
subtree=True):
subtocnode.parent.insert(i, item)
i += 1
subtocnode.parent.remove(subtocnode)
if separate:
entries.append(toc)
else:
entries.extend(toc.children)
if not subtree and not separate:
ret = nodes.bullet_list()
ret += entries
return [ret]
return entries
maxdepth = maxdepth or toctree.get('maxdepth', -1)
if not titles_only and toctree.get('titlesonly', False):
titles_only = True
if not includehidden and toctree.get('includehidden', False):
includehidden = True
# NOTE: previously, this was separate=True, but that leads to artificial
# separation when two or more toctree entries form a logical unit, so
# separating mode is no longer used -- it's kept here for history's sake
tocentries = _entries_from_toctree(toctree, [], separate=False)
if not tocentries:
return None
newnode = addnodes.compact_paragraph('', '')
caption = toctree.attributes.get('caption')
if caption:
caption_node = nodes.caption(caption, '', *[nodes.Text(caption)])
caption_node.line = toctree.line
caption_node.source = toctree.source
caption_node.rawsource = toctree['rawcaption']
if hasattr(toctree, 'uid'):
# move uid to caption_node to translate it
caption_node.uid = toctree.uid
del toctree.uid
newnode += caption_node
newnode.extend(tocentries)
newnode['toctree'] = True
# prune the tree to maxdepth, also set toc depth and current classes
_toctree_add_classes(newnode, 1)
self._toctree_prune(newnode, 1, prune and maxdepth or 0, collapse)
if len(newnode[-1]) == 0: # No titles found
return None
# set the target paths in the toctrees (they are not known at TOC
# generation time)
for refnode in newnode.traverse(nodes.reference):
if not url_re.match(refnode['refuri']):
refnode['refuri'] = builder.get_relative_uri(
docname, refnode['refuri']) + refnode['anchorname']
return newnode
def get_toctree_ancestors(self, docname):
parent = {}
for p, children in iteritems(self.toctree_includes):
for child in children:
parent[child] = p
ancestors = []
d = docname
while d in parent and d not in ancestors:
ancestors.append(d)
d = parent[d]
return ancestors
def _toctree_prune(self, node, depth, maxdepth, collapse=False):
"""Utility: Cut a TOC at a specified depth."""
for subnode in node.children[:]:
if isinstance(subnode, (addnodes.compact_paragraph,
nodes.list_item)):
# for <p> and <li>, just recurse
self._toctree_prune(subnode, depth, maxdepth, collapse)
elif isinstance(subnode, nodes.bullet_list):
# for <ul>, determine if the depth is too large or if the
# entry is to be collapsed
if maxdepth > 0 and depth > maxdepth:
subnode.parent.replace(subnode, [])
else:
# cull sub-entries whose parents aren't 'current'
if (collapse and depth > 1 and
'iscurrent' not in subnode.parent):
subnode.parent.remove(subnode)
else:
# recurse on visible children
self._toctree_prune(subnode, depth+1, maxdepth, collapse)
def assign_section_numbers(self):
"""Assign a section number to each heading under a numbered toctree."""
# a list of all docnames whose section numbers changed
rewrite_needed = []
assigned = set()
old_secnumbers = self.toc_secnumbers
self.toc_secnumbers = self.env.toc_secnumbers = {}
def _walk_toc(node, secnums, depth, titlenode=None):
# titlenode is the title of the document, it will get assigned a
# secnumber too, so that it shows up in next/prev/parent rellinks
for subnode in node.children:
if isinstance(subnode, nodes.bullet_list):
numstack.append(0)
_walk_toc(subnode, secnums, depth-1, titlenode)
numstack.pop()
titlenode = None
elif isinstance(subnode, nodes.list_item):
_walk_toc(subnode, secnums, depth, titlenode)
titlenode = None
elif isinstance(subnode, addnodes.only):
# at this stage we don't know yet which sections are going
# to be included; just include all of them, even if it leads
# to gaps in the numbering
_walk_toc(subnode, secnums, depth, titlenode)
titlenode = None
elif isinstance(subnode, addnodes.compact_paragraph):
numstack[-1] += 1
if depth > 0:
number = tuple(numstack)
else:
number = None
secnums[subnode[0]['anchorname']] = \
subnode[0]['secnumber'] = number
if titlenode:
titlenode['secnumber'] = number
titlenode = None
elif isinstance(subnode, addnodes.toctree):
_walk_toctree(subnode, depth)
def _walk_toctree(toctreenode, depth):
if depth == 0:
return
for (title, ref) in toctreenode['entries']:
if url_re.match(ref) or ref == 'self' or ref in assigned:
# don't mess with those
continue
if ref in self.tocs:
secnums = self.toc_secnumbers[ref] = {}
assigned.add(ref)
_walk_toc(self.tocs[ref], secnums, depth,
self.env.titles.get(ref))
if secnums != old_secnumbers.get(ref):
rewrite_needed.append(ref)
for docname in self.numbered_toctrees:
assigned.add(docname)
doctree = self.env.get_doctree(docname)
for toctreenode in doctree.traverse(addnodes.toctree):
depth = toctreenode.get('numbered', 0)
if depth:
# every numbered toctree gets new numbering
numstack = [0]
_walk_toctree(toctreenode, depth)
return rewrite_needed
def assign_figure_numbers(self):
"""Assign a figure number to each figure under a numbered toctree."""
rewrite_needed = []
assigned = set()
old_fignumbers = self.toc_fignumbers
self.toc_fignumbers = self.env.toc_fignumbers = {}
fignum_counter = {}
def get_section_number(docname, section):
anchorname = '#' + section['ids'][0]
secnumbers = self.toc_secnumbers.get(docname, {})
if anchorname in secnumbers:
secnum = secnumbers.get(anchorname)
else:
secnum = secnumbers.get('')
return secnum or tuple()
def get_next_fignumber(figtype, secnum):
counter = fignum_counter.setdefault(figtype, {})
secnum = secnum[:self.env.config.numfig_secnum_depth]
counter[secnum] = counter.get(secnum, 0) + 1
return secnum + (counter[secnum],)
def register_fignumber(docname, secnum, figtype, fignode):
self.toc_fignumbers.setdefault(docname, {})
fignumbers = self.toc_fignumbers[docname].setdefault(figtype, {})
figure_id = fignode['ids'][0]
fignumbers[figure_id] = get_next_fignumber(figtype, secnum)
def _walk_doctree(docname, doctree, secnum):
for subnode in doctree.children:
if isinstance(subnode, nodes.section):
next_secnum = get_section_number(docname, subnode)
if next_secnum:
_walk_doctree(docname, subnode, next_secnum)
else:
_walk_doctree(docname, subnode, secnum)
continue
elif isinstance(subnode, addnodes.toctree):
for title, subdocname in subnode['entries']:
if url_re.match(subdocname) or subdocname == 'self':
# don't mess with those
continue
_walk_doc(subdocname, secnum)
continue
figtype = self.env.domains['std'].get_figtype(subnode)
if figtype and subnode['ids']:
register_fignumber(docname, secnum, figtype, subnode)
_walk_doctree(docname, subnode, secnum)
def _walk_doc(docname, secnum):
if docname not in assigned:
assigned.add(docname)
doctree = self.env.get_doctree(docname)
_walk_doctree(docname, doctree, secnum)
if self.env.config.numfig:
_walk_doc(self.env.config.master_doc, tuple())
for docname, fignums in iteritems(self.toc_fignumbers):
if fignums != old_fignumbers.get(docname):
rewrite_needed.append(docname)
return rewrite_needed
| bgris/ODL_bgris | lib/python3.5/site-packages/Sphinx-1.5.1-py3.5.egg/sphinx/environment/managers/toctree.py | Python | gpl-3.0 | 25,403 |
package vault
import "time"
type dynamicSystemView struct {
core *Core
mountEntry *MountEntry
}
func (d dynamicSystemView) DefaultLeaseTTL() time.Duration {
def, _ := d.fetchTTLs()
return def
}
func (d dynamicSystemView) MaxLeaseTTL() time.Duration {
_, max := d.fetchTTLs()
return max
}
// TTLsByPath returns the default and max TTLs corresponding to a particular
// mount point, or the system default
func (d dynamicSystemView) fetchTTLs() (def, max time.Duration) {
def = d.core.defaultLeaseTTL
max = d.core.maxLeaseTTL
if d.mountEntry.Config.DefaultLeaseTTL != 0 {
def = d.mountEntry.Config.DefaultLeaseTTL
}
if d.mountEntry.Config.MaxLeaseTTL != 0 {
max = d.mountEntry.Config.MaxLeaseTTL
}
return
}
| jklein/vault | vault/dynamic_system_view.go | GO | mpl-2.0 | 734 |
// Copyright 2012-present Oliver Eilhard. All rights reserved.
// Use of this source code is governed by a MIT-license.
// See http://olivere.mit-license.org/license.txt for details.
package opentracing
import (
"strconv"
)
func atouint16(s string) uint16 {
v, _ := strconv.ParseUint(s, 10, 16)
return uint16(v)
}
| kjmkznr/terraform-provider-elasticsearch | vendor/gopkg.in/olivere/elastic.v6/trace/opentracing/util.go | GO | mpl-2.0 | 320 |
#
# Newfies-Dialer License
# http://www.newfies-dialer.org
#
# This Source Code Form is subject to the terms of the Mozilla Public
# License, v. 2.0. If a copy of the MPL was not distributed with this file,
# You can obtain one at http://mozilla.org/MPL/2.0/.
#
# Copyright (C) 2011-2014 Star2Billing S.L.
#
# The Initial Developer of the Original Code is
# Arezqui Belaid <info@star2billing.com>
#
from django.template.defaultfilters import register
from appointment.constants import EVENT_STATUS, ALARM_STATUS, ALARM_METHOD
@register.filter(name='event_status')
def event_status(value):
"""Event Status Templatetag"""
if not value:
return ''
STATUS = dict(EVENT_STATUS)
try:
return STATUS[value].encode('utf-8')
except:
return ''
@register.filter(name='alarm_status')
def alarm_status(value):
"""Alarm Status Templatetag"""
if not value:
return ''
STATUS = dict(ALARM_STATUS)
try:
return STATUS[value].encode('utf-8')
except:
return ''
@register.filter(name='alarm_method')
def alarm_method(value):
"""Alarm Method Templatetag"""
if not value:
return ''
METHOD = dict(ALARM_METHOD)
try:
return METHOD[value].encode('utf-8')
except:
return ''
| gale320/newfies-dialer | newfies/appointment/templatetags/appointment_tags.py | Python | mpl-2.0 | 1,283 |
package nomad
import (
"bytes"
"context"
"errors"
"fmt"
"io"
"net"
"time"
log "github.com/hashicorp/go-hclog"
sframer "github.com/hashicorp/nomad/client/lib/streamframer"
cstructs "github.com/hashicorp/nomad/client/structs"
"github.com/hashicorp/nomad/command/agent/host"
"github.com/hashicorp/nomad/command/agent/monitor"
"github.com/hashicorp/nomad/command/agent/pprof"
"github.com/hashicorp/nomad/helper"
"github.com/hashicorp/nomad/nomad/structs"
"github.com/hashicorp/go-msgpack/codec"
)
type Agent struct {
srv *Server
}
func (a *Agent) register() {
a.srv.streamingRpcs.Register("Agent.Monitor", a.monitor)
}
func (a *Agent) Profile(args *structs.AgentPprofRequest, reply *structs.AgentPprofResponse) error {
// Check ACL for agent write
aclObj, err := a.srv.ResolveToken(args.AuthToken)
if err != nil {
return err
} else if aclObj != nil && !aclObj.AllowAgentWrite() {
return structs.ErrPermissionDenied
}
// Forward to different region if necessary
// this would typically be done in a.srv.forward() but since
// we are targeting a specific server, not just the leader
// we must manually handle region forwarding here.
region := args.RequestRegion()
if region == "" {
return fmt.Errorf("missing target RPC")
}
if region != a.srv.config.Region {
// Mark that we are forwarding
args.SetForwarded()
return a.srv.forwardRegion(region, "Agent.Profile", args, reply)
}
// Targeting a node, forward request to node
if args.NodeID != "" {
return a.forwardProfileClient(args, reply)
}
// Handle serverID not equal to ours
if args.ServerID != "" {
serverToFwd, err := a.forwardFor(args.ServerID, region)
if err != nil {
return err
}
if serverToFwd != nil {
return a.srv.forwardServer(serverToFwd, "Agent.Profile", args, reply)
}
}
// If ACLs are disabled, EnableDebug must be enabled
if aclObj == nil && !a.srv.config.EnableDebug {
return structs.ErrPermissionDenied
}
// Process the request on this server
var resp []byte
var headers map[string]string
// Determine which profile to run and generate profile.
// Blocks for args.Seconds
// Our RPC endpoints currently don't support context
// or request cancellation so using server shutdownCtx as a
// best effort.
switch args.ReqType {
case pprof.CPUReq:
resp, headers, err = pprof.CPUProfile(a.srv.shutdownCtx, args.Seconds)
case pprof.CmdReq:
resp, headers, err = pprof.Cmdline()
case pprof.LookupReq:
resp, headers, err = pprof.Profile(args.Profile, args.Debug, args.GC)
case pprof.TraceReq:
resp, headers, err = pprof.Trace(a.srv.shutdownCtx, args.Seconds)
default:
err = structs.NewErrRPCCoded(404, "Unknown profile request type")
}
if err != nil {
if pprof.IsErrProfileNotFound(err) {
return structs.NewErrRPCCoded(404, err.Error())
}
return structs.NewErrRPCCoded(500, err.Error())
}
// Copy profile response to reply
reply.Payload = resp
reply.HTTPHeaders = headers
reply.AgentID = a.srv.serf.LocalMember().Name
return nil
}
func (a *Agent) monitor(conn io.ReadWriteCloser) {
defer conn.Close()
// Decode args
var args cstructs.MonitorRequest
decoder := codec.NewDecoder(conn, structs.MsgpackHandle)
encoder := codec.NewEncoder(conn, structs.MsgpackHandle)
if err := decoder.Decode(&args); err != nil {
handleStreamResultError(err, helper.Int64ToPtr(500), encoder)
return
}
// Check agent read permissions
if aclObj, err := a.srv.ResolveToken(args.AuthToken); err != nil {
handleStreamResultError(err, nil, encoder)
return
} else if aclObj != nil && !aclObj.AllowAgentRead() {
handleStreamResultError(structs.ErrPermissionDenied, helper.Int64ToPtr(403), encoder)
return
}
logLevel := log.LevelFromString(args.LogLevel)
if args.LogLevel == "" {
logLevel = log.LevelFromString("INFO")
}
if logLevel == log.NoLevel {
handleStreamResultError(errors.New("Unknown log level"), helper.Int64ToPtr(400), encoder)
return
}
// Targeting a node, forward request to node
if args.NodeID != "" {
a.forwardMonitorClient(conn, args, encoder, decoder)
// forwarded request has ended, return
return
}
region := args.RequestRegion()
if region == "" {
handleStreamResultError(fmt.Errorf("missing target RPC"), helper.Int64ToPtr(400), encoder)
return
}
if region != a.srv.config.Region {
// Mark that we are forwarding
args.SetForwarded()
}
// Try to forward request to remote region/server
if args.ServerID != "" {
serverToFwd, err := a.forwardFor(args.ServerID, region)
if err != nil {
handleStreamResultError(err, helper.Int64ToPtr(400), encoder)
return
}
if serverToFwd != nil {
a.forwardMonitorServer(conn, serverToFwd, args, encoder, decoder)
return
}
}
// NodeID was empty, ServerID was equal to this server, monitor this server
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
monitor := monitor.New(512, a.srv.logger, &log.LoggerOptions{
Level: logLevel,
JSONFormat: args.LogJSON,
})
frames := make(chan *sframer.StreamFrame, 32)
errCh := make(chan error)
var buf bytes.Buffer
frameCodec := codec.NewEncoder(&buf, structs.JsonHandle)
framer := sframer.NewStreamFramer(frames, 1*time.Second, 200*time.Millisecond, 1024)
framer.Run()
defer framer.Destroy()
// goroutine to detect remote side closing
go func() {
if _, err := conn.Read(nil); err != nil {
// One end of the pipe explicitly closed, exit
cancel()
return
}
<-ctx.Done()
}()
logCh := monitor.Start()
defer monitor.Stop()
initialOffset := int64(0)
// receive logs and build frames
go func() {
defer framer.Destroy()
LOOP:
for {
select {
case log := <-logCh:
if err := framer.Send("", "log", log, initialOffset); err != nil {
select {
case errCh <- err:
case <-ctx.Done():
}
break LOOP
}
case <-ctx.Done():
break LOOP
}
}
}()
var streamErr error
OUTER:
for {
select {
case frame, ok := <-frames:
if !ok {
// frame may have been closed when an error
// occurred. Check once more for an error.
select {
case streamErr = <-errCh:
// There was a pending error!
default:
// No error, continue on
}
break OUTER
}
var resp cstructs.StreamErrWrapper
if args.PlainText {
resp.Payload = frame.Data
} else {
if err := frameCodec.Encode(frame); err != nil {
streamErr = err
break OUTER
}
resp.Payload = buf.Bytes()
buf.Reset()
}
if err := encoder.Encode(resp); err != nil {
streamErr = err
break OUTER
}
encoder.Reset(conn)
case <-ctx.Done():
break OUTER
}
}
if streamErr != nil {
handleStreamResultError(streamErr, helper.Int64ToPtr(500), encoder)
return
}
}
// forwardFor returns a serverParts for a request to be forwarded to.
// A response of nil, nil indicates that the current server is equal to the
// serverID and region so the request should not be forwarded.
func (a *Agent) forwardFor(serverID, region string) (*serverParts, error) {
var target *serverParts
var err error
if serverID == "leader" {
isLeader, remoteLeader := a.srv.getLeader()
if !isLeader && remoteLeader != nil {
target = remoteLeader
} else if !isLeader && remoteLeader == nil {
return nil, structs.ErrNoLeader
} else if isLeader {
// This server is current leader do not forward
return nil, nil
}
} else {
target, err = a.srv.getServer(region, serverID)
if err != nil {
return nil, err
}
}
// Unable to find a server
if target == nil {
return nil, fmt.Errorf("unknown nomad server %s", serverID)
}
// ServerID is this current server,
// No need to forward request
if target.Name == a.srv.LocalMember().Name {
return nil, nil
}
return target, nil
}
func (a *Agent) forwardMonitorClient(conn io.ReadWriteCloser, args cstructs.MonitorRequest, encoder *codec.Encoder, decoder *codec.Decoder) {
// Get the Connection to the client either by fowarding to another server
// or creating direct stream
state, srv, err := a.findClientConn(args.NodeID)
if err != nil {
handleStreamResultError(err, helper.Int64ToPtr(500), encoder)
return
}
var clientConn net.Conn
if state == nil {
conn, err := a.srv.streamingRpc(srv, "Agent.Monitor")
if err != nil {
handleStreamResultError(err, nil, encoder)
return
}
clientConn = conn
} else {
stream, err := NodeStreamingRpc(state.Session, "Agent.Monitor")
if err != nil {
handleStreamResultError(err, nil, encoder)
return
}
clientConn = stream
}
defer clientConn.Close()
// Send the Request
outEncoder := codec.NewEncoder(clientConn, structs.MsgpackHandle)
if err := outEncoder.Encode(args); err != nil {
handleStreamResultError(err, nil, encoder)
return
}
structs.Bridge(conn, clientConn)
}
func (a *Agent) forwardMonitorServer(conn io.ReadWriteCloser, server *serverParts, args cstructs.MonitorRequest, encoder *codec.Encoder, decoder *codec.Decoder) {
// empty ServerID to prevent forwarding loop
args.ServerID = ""
serverConn, err := a.srv.streamingRpc(server, "Agent.Monitor")
if err != nil {
handleStreamResultError(err, helper.Int64ToPtr(500), encoder)
return
}
defer serverConn.Close()
// Send the Request
outEncoder := codec.NewEncoder(serverConn, structs.MsgpackHandle)
if err := outEncoder.Encode(args); err != nil {
handleStreamResultError(err, helper.Int64ToPtr(500), encoder)
return
}
structs.Bridge(conn, serverConn)
}
func (a *Agent) forwardProfileClient(args *structs.AgentPprofRequest, reply *structs.AgentPprofResponse) error {
state, srv, err := a.findClientConn(args.NodeID)
if err != nil {
return err
}
if srv != nil {
return a.srv.forwardServer(srv, "Agent.Profile", args, reply)
}
// NodeRpc
rpcErr := NodeRpc(state.Session, "Agent.Profile", args, reply)
if rpcErr != nil {
return rpcErr
}
return nil
}
// Host returns data about the agent's host system for the `debug` command.
func (a *Agent) Host(args *structs.HostDataRequest, reply *structs.HostDataResponse) error {
aclObj, err := a.srv.ResolveToken(args.AuthToken)
if err != nil {
return err
}
if (aclObj != nil && !aclObj.AllowAgentRead()) ||
(aclObj == nil && !a.srv.config.EnableDebug) {
return structs.ErrPermissionDenied
}
// Forward to different region if necessary
// this would typically be done in a.srv.forward() but since
// we are targeting a specific server, not just the leader
// we must manually handle region forwarding here.
region := args.RequestRegion()
if region == "" {
return fmt.Errorf("missing target RPC")
}
if region != a.srv.config.Region {
// Mark that we are forwarding
args.SetForwarded()
return a.srv.forwardRegion(region, "Agent.Host", args, reply)
}
// Targeting a client node, forward request to node
if args.NodeID != "" {
client, srv, err := a.findClientConn(args.NodeID)
if err != nil {
return err
}
if srv != nil {
return a.srv.forwardServer(srv, "Agent.Host", args, reply)
}
return NodeRpc(client.Session, "Agent.Host", args, reply)
}
// Handle serverID not equal to ours
if args.ServerID != "" {
srv, err := a.forwardFor(args.ServerID, region)
if err != nil {
return err
}
if srv != nil {
return a.srv.forwardServer(srv, "Agent.Host", args, reply)
}
}
data, err := host.MakeHostData()
if err != nil {
return err
}
reply.AgentID = a.srv.serf.LocalMember().Name
reply.HostData = data
return nil
}
// findClientConn is a helper that returns a connection to the client node or, if the client
// is connected to a different server, a serverParts describing the server to which the
// client bound RPC should be forwarded.
func (a *Agent) findClientConn(nodeID string) (*nodeConnState, *serverParts, error) {
snap, err := a.srv.State().Snapshot()
if err != nil {
return nil, nil, structs.NewErrRPCCoded(500, err.Error())
}
node, err := snap.NodeByID(nil, nodeID)
if err != nil {
return nil, nil, structs.NewErrRPCCoded(500, err.Error())
}
if node == nil {
err := fmt.Errorf("Unknown node %q", nodeID)
return nil, nil, structs.NewErrRPCCoded(404, err.Error())
}
if err := nodeSupportsRpc(node); err != nil {
return nil, nil, structs.NewErrRPCCoded(400, err.Error())
}
// Get the Connection to the client either by fowarding to another server
// or creating direct stream
state, ok := a.srv.getNodeConn(nodeID)
if ok {
return state, nil, nil
}
// Determine the server that has a connection to the node
srv, err := a.srv.serverWithNodeConn(nodeID, a.srv.Region())
if err != nil {
code := 500
if structs.IsErrNoNodeConn(err) {
code = 404
}
return nil, nil, structs.NewErrRPCCoded(code, err.Error())
}
return nil, srv, nil
}
| hashicorp/nomad | nomad/client_agent_endpoint.go | GO | mpl-2.0 | 12,707 |
// Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "base/threading/sequenced_worker_pool.h"
#include <list>
#include <map>
#include <set>
#include <utility>
#include <vector>
#include "base/atomic_sequence_num.h"
#include "base/callback.h"
#include "base/compiler_specific.h"
#include "base/critical_closure.h"
#include "base/debug/trace_event.h"
#include "base/lazy_instance.h"
#include "base/logging.h"
#include "base/memory/linked_ptr.h"
#include "base/message_loop/message_loop_proxy.h"
#include "base/stl_util.h"
#include "base/strings/stringprintf.h"
#include "base/synchronization/condition_variable.h"
#include "base/synchronization/lock.h"
#include "base/threading/platform_thread.h"
#include "base/threading/simple_thread.h"
#include "base/threading/thread_local.h"
#include "base/threading/thread_restrictions.h"
#include "base/time/time.h"
#include "base/tracked_objects.h"
#if defined(OS_MACOSX)
#include "base/mac/scoped_nsautorelease_pool.h"
#elif defined(OS_WIN)
#include "base/win/scoped_com_initializer.h"
#endif
#if !defined(OS_NACL)
#include "base/metrics/histogram.h"
#endif
namespace base {
namespace {
struct SequencedTask : public TrackingInfo {
SequencedTask()
: sequence_token_id(0),
trace_id(0),
sequence_task_number(0),
shutdown_behavior(SequencedWorkerPool::BLOCK_SHUTDOWN) {}
explicit SequencedTask(const tracked_objects::Location& from_here)
: base::TrackingInfo(from_here, TimeTicks()),
sequence_token_id(0),
trace_id(0),
sequence_task_number(0),
shutdown_behavior(SequencedWorkerPool::BLOCK_SHUTDOWN) {}
~SequencedTask() {}
int sequence_token_id;
int trace_id;
int64 sequence_task_number;
SequencedWorkerPool::WorkerShutdown shutdown_behavior;
tracked_objects::Location posted_from;
Closure task;
// Non-delayed tasks and delayed tasks are managed together by time-to-run
// order. We calculate the time by adding the posted time and the given delay.
TimeTicks time_to_run;
};
struct SequencedTaskLessThan {
public:
bool operator()(const SequencedTask& lhs, const SequencedTask& rhs) const {
if (lhs.time_to_run < rhs.time_to_run)
return true;
if (lhs.time_to_run > rhs.time_to_run)
return false;
// If the time happen to match, then we use the sequence number to decide.
return lhs.sequence_task_number < rhs.sequence_task_number;
}
};
// SequencedWorkerPoolTaskRunner ---------------------------------------------
// A TaskRunner which posts tasks to a SequencedWorkerPool with a
// fixed ShutdownBehavior.
//
// Note that this class is RefCountedThreadSafe (inherited from TaskRunner).
class SequencedWorkerPoolTaskRunner : public TaskRunner {
public:
SequencedWorkerPoolTaskRunner(
const scoped_refptr<SequencedWorkerPool>& pool,
SequencedWorkerPool::WorkerShutdown shutdown_behavior);
// TaskRunner implementation
bool PostDelayedTask(const tracked_objects::Location& from_here,
const Closure& task,
TimeDelta delay) override;
bool RunsTasksOnCurrentThread() const override;
private:
~SequencedWorkerPoolTaskRunner() override;
const scoped_refptr<SequencedWorkerPool> pool_;
const SequencedWorkerPool::WorkerShutdown shutdown_behavior_;
DISALLOW_COPY_AND_ASSIGN(SequencedWorkerPoolTaskRunner);
};
SequencedWorkerPoolTaskRunner::SequencedWorkerPoolTaskRunner(
const scoped_refptr<SequencedWorkerPool>& pool,
SequencedWorkerPool::WorkerShutdown shutdown_behavior)
: pool_(pool),
shutdown_behavior_(shutdown_behavior) {
}
SequencedWorkerPoolTaskRunner::~SequencedWorkerPoolTaskRunner() {
}
bool SequencedWorkerPoolTaskRunner::PostDelayedTask(
const tracked_objects::Location& from_here,
const Closure& task,
TimeDelta delay) {
if (delay == TimeDelta()) {
return pool_->PostWorkerTaskWithShutdownBehavior(
from_here, task, shutdown_behavior_);
}
return pool_->PostDelayedWorkerTask(from_here, task, delay);
}
bool SequencedWorkerPoolTaskRunner::RunsTasksOnCurrentThread() const {
return pool_->RunsTasksOnCurrentThread();
}
// SequencedWorkerPoolSequencedTaskRunner ------------------------------------
// A SequencedTaskRunner which posts tasks to a SequencedWorkerPool with a
// fixed sequence token.
//
// Note that this class is RefCountedThreadSafe (inherited from TaskRunner).
class SequencedWorkerPoolSequencedTaskRunner : public SequencedTaskRunner {
public:
SequencedWorkerPoolSequencedTaskRunner(
const scoped_refptr<SequencedWorkerPool>& pool,
SequencedWorkerPool::SequenceToken token,
SequencedWorkerPool::WorkerShutdown shutdown_behavior);
// patch start huangshaobin ================================================
virtual void Finalize() override;
// patch end huangshaobin ================================================
// TaskRunner implementation
bool PostDelayedTask(const tracked_objects::Location& from_here,
const Closure& task,
TimeDelta delay) override;
bool RunsTasksOnCurrentThread() const override;
// SequencedTaskRunner implementation
bool PostNonNestableDelayedTask(const tracked_objects::Location& from_here,
const Closure& task,
TimeDelta delay) override;
private:
~SequencedWorkerPoolSequencedTaskRunner() override;
const scoped_refptr<SequencedWorkerPool> pool_;
const SequencedWorkerPool::SequenceToken token_;
const SequencedWorkerPool::WorkerShutdown shutdown_behavior_;
DISALLOW_COPY_AND_ASSIGN(SequencedWorkerPoolSequencedTaskRunner);
};
SequencedWorkerPoolSequencedTaskRunner::SequencedWorkerPoolSequencedTaskRunner(
const scoped_refptr<SequencedWorkerPool>& pool,
SequencedWorkerPool::SequenceToken token,
SequencedWorkerPool::WorkerShutdown shutdown_behavior)
: pool_(pool),
token_(token),
shutdown_behavior_(shutdown_behavior) {
}
SequencedWorkerPoolSequencedTaskRunner::
~SequencedWorkerPoolSequencedTaskRunner() {
}
bool SequencedWorkerPoolSequencedTaskRunner::PostDelayedTask(
const tracked_objects::Location& from_here,
const Closure& task,
TimeDelta delay) {
if (delay == TimeDelta()) {
return pool_->PostSequencedWorkerTaskWithShutdownBehavior(
token_, from_here, task, shutdown_behavior_);
}
return pool_->PostDelayedSequencedWorkerTask(token_, from_here, task, delay);
}
bool SequencedWorkerPoolSequencedTaskRunner::RunsTasksOnCurrentThread() const {
return pool_->IsRunningSequenceOnCurrentThread(token_);
}
bool SequencedWorkerPoolSequencedTaskRunner::PostNonNestableDelayedTask(
const tracked_objects::Location& from_here,
const Closure& task,
TimeDelta delay) {
// There's no way to run nested tasks, so simply forward to
// PostDelayedTask.
return PostDelayedTask(from_here, task, delay);
}
// patch start huangshaobin ====================================================
void
SequencedWorkerPoolSequencedTaskRunner::Finalize() {
pool_->FinalizeToken(token_);
}
// patch end huangshaobin ====================================================
// Create a process-wide unique ID to represent this task in trace events. This
// will be mangled with a Process ID hash to reduce the likelyhood of colliding
// with MessageLoop pointers on other processes.
uint64 GetTaskTraceID(const SequencedTask& task,
void* pool) {
return (static_cast<uint64>(task.trace_id) << 32) |
static_cast<uint64>(reinterpret_cast<intptr_t>(pool));
}
base::LazyInstance<base::ThreadLocalPointer<
SequencedWorkerPool::SequenceToken> >::Leaky g_lazy_tls_ptr =
LAZY_INSTANCE_INITIALIZER;
} // namespace
// Worker ---------------------------------------------------------------------
class SequencedWorkerPool::Worker : public SimpleThread {
public:
// Hold a (cyclic) ref to |worker_pool|, since we want to keep it
// around as long as we are running.
Worker(const scoped_refptr<SequencedWorkerPool>& worker_pool,
int thread_number,
const std::string& thread_name_prefix);
~Worker() override;
// SimpleThread implementation. This actually runs the background thread.
void Run() override;
void set_running_task_info(SequenceToken token,
WorkerShutdown shutdown_behavior) {
running_sequence_ = token;
running_shutdown_behavior_ = shutdown_behavior;
}
SequenceToken running_sequence() const {
return running_sequence_;
}
WorkerShutdown running_shutdown_behavior() const {
return running_shutdown_behavior_;
}
private:
scoped_refptr<SequencedWorkerPool> worker_pool_;
SequenceToken running_sequence_;
WorkerShutdown running_shutdown_behavior_;
DISALLOW_COPY_AND_ASSIGN(Worker);
};
// Inner ----------------------------------------------------------------------
class SequencedWorkerPool::Inner {
public:
// Take a raw pointer to |worker| to avoid cycles (since we're owned
// by it).
Inner(SequencedWorkerPool* worker_pool, size_t max_threads,
const std::string& thread_name_prefix,
TestingObserver* observer);
~Inner();
SequenceToken GetSequenceToken();
SequenceToken GetNamedSequenceToken(const std::string& name);
// This function accepts a name and an ID. If the name is null, the
// token ID is used. This allows us to implement the optional name lookup
// from a single function without having to enter the lock a separate time.
bool PostTask(const std::string* optional_token_name,
SequenceToken sequence_token,
WorkerShutdown shutdown_behavior,
const tracked_objects::Location& from_here,
const Closure& task,
TimeDelta delay);
bool RunsTasksOnCurrentThread() const;
bool IsRunningSequenceOnCurrentThread(SequenceToken sequence_token) const;
void CleanupForTesting();
void SignalHasWorkForTesting();
int GetWorkSignalCountForTesting() const;
void Shutdown(int max_blocking_tasks_after_shutdown);
bool IsShutdownInProgress();
// Runs the worker loop on the background thread.
void ThreadLoop(Worker* this_worker);
// patch start tanjianwen ====================================================
void FinalizeToken(SequenceToken token);
void FinalizeNamedToken(const std::string& name);
// patch end tanjianwen ====================================================
private:
enum GetWorkStatus {
GET_WORK_FOUND,
GET_WORK_NOT_FOUND,
GET_WORK_WAIT,
};
enum CleanupState {
CLEANUP_REQUESTED,
CLEANUP_STARTING,
CLEANUP_RUNNING,
CLEANUP_FINISHING,
CLEANUP_DONE,
};
// patch start tanjianwen ====================================================
// Every runner's finalization includes two stages.
//
// In the first one, we discard all non-blocking tasks, and we will wait till
// the last blocking task is executed in the next stage.
//
// Distinguishing one stage to another is just an improvement in performance.
enum FinalizationStage {
DISCARDING_NON_BLOCKING_TASKS,
WAITING_FOR_BLOCKING_TASKS
};
// patch end tanjianwen ====================================================
// Called from within the lock, this converts the given token name into a
// token ID, creating a new one if necessary.
int LockedGetNamedTokenID(const std::string& name);
// Called from within the lock, this returns the next sequence task number.
int64 LockedGetNextSequenceTaskNumber();
// Called from within the lock, returns the shutdown behavior of the task
// running on the currently executing worker thread. If invoked from a thread
// that is not one of the workers, returns CONTINUE_ON_SHUTDOWN.
WorkerShutdown LockedCurrentThreadShutdownBehavior() const;
// Gets new task. There are 3 cases depending on the return value:
//
// 1) If the return value is |GET_WORK_FOUND|, |task| is filled in and should
// be run immediately.
// 2) If the return value is |GET_WORK_NOT_FOUND|, there are no tasks to run,
// and |task| is not filled in. In this case, the caller should wait until
// a task is posted.
// 3) If the return value is |GET_WORK_WAIT|, there are no tasks to run
// immediately, and |task| is not filled in. Likewise, |wait_time| is
// filled in the time to wait until the next task to run. In this case, the
// caller should wait the time.
//
// In any case, the calling code should clear the given
// delete_these_outside_lock vector the next time the lock is released.
// See the implementation for a more detailed description.
GetWorkStatus GetWork(SequencedTask* task,
TimeDelta* wait_time,
std::vector<Closure>* delete_these_outside_lock);
void HandleCleanup();
// Peforms init and cleanup around running the given task. WillRun...
// returns the value from PrepareToStartAdditionalThreadIfNecessary.
// The calling code should call FinishStartingAdditionalThread once the
// lock is released if the return values is nonzero.
int WillRunWorkerTask(const SequencedTask& task);
void DidRunWorkerTask(const SequencedTask& task);
// Returns true if there are no threads currently running the given
// sequence token.
bool IsSequenceTokenRunnable(int sequence_token_id) const;
// Checks if all threads are busy and the addition of one more could run an
// additional task waiting in the queue. This must be called from within
// the lock.
//
// If another thread is helpful, this will mark the thread as being in the
// process of starting and returns the index of the new thread which will be
// 0 or more. The caller should then call FinishStartingAdditionalThread to
// complete initialization once the lock is released.
//
// If another thread is not necessary, returne 0;
//
// See the implementedion for more.
int PrepareToStartAdditionalThreadIfHelpful();
// The second part of thread creation after
// PrepareToStartAdditionalThreadIfHelpful with the thread number it
// generated. This actually creates the thread and should be called outside
// the lock to avoid blocking important work starting a thread in the lock.
void FinishStartingAdditionalThread(int thread_number);
// Signal |has_work_| and increment |has_work_signal_count_|.
void SignalHasWork();
// Checks whether there is work left that's blocking shutdown. Must be
// called inside the lock.
bool CanShutdown() const;
// patch start tanjianwen ====================================================
void DeprecateTokensIfNeeded(int last_task_token_id,
std::vector<Closure>* delete_these_outside_lock);
// patch end tanjianwen ====================================================
SequencedWorkerPool* const worker_pool_;
// The last sequence number used. Managed by GetSequenceToken, since this
// only does threadsafe increment operations, you do not need to hold the
// lock. This is class-static to make SequenceTokens issued by
// GetSequenceToken unique across SequencedWorkerPool instances.
static base::StaticAtomicSequenceNumber g_last_sequence_number_;
// This lock protects |everything in this class|. Do not read or modify
// anything without holding this lock. Do not block while holding this
// lock.
mutable Lock lock_;
// Condition variable that is waited on by worker threads until new
// tasks are posted or shutdown starts.
ConditionVariable has_work_cv_;
// Condition variable that is waited on by non-worker threads (in
// Shutdown()) until CanShutdown() goes to true.
ConditionVariable can_shutdown_cv_;
// The maximum number of worker threads we'll create.
const size_t max_threads_;
const std::string thread_name_prefix_;
// Associates all known sequence token names with their IDs.
std::map<std::string, int> named_sequence_tokens_;
// Owning pointers to all threads we've created so far, indexed by
// ID. Since we lazily create threads, this may be less than
// max_threads_ and will be initially empty.
typedef std::map<PlatformThreadId, linked_ptr<Worker> > ThreadMap;
ThreadMap threads_;
// Set to true when we're in the process of creating another thread.
// See PrepareToStartAdditionalThreadIfHelpful for more.
bool thread_being_created_;
// Number of threads currently waiting for work.
size_t waiting_thread_count_;
// Number of threads currently running tasks that have the BLOCK_SHUTDOWN
// or SKIP_ON_SHUTDOWN flag set.
size_t blocking_shutdown_thread_count_;
// A set of all pending tasks in time-to-run order. These are tasks that are
// either waiting for a thread to run on, waiting for their time to run,
// or blocked on a previous task in their sequence. We have to iterate over
// the tasks by time-to-run order, so we use the set instead of the
// traditional priority_queue.
typedef std::set<SequencedTask, SequencedTaskLessThan> PendingTaskSet;
PendingTaskSet pending_tasks_;
// The next sequence number for a new sequenced task.
int64 next_sequence_task_number_;
// Number of tasks in the pending_tasks_ list that are marked as blocking
// shutdown.
size_t blocking_shutdown_pending_task_count_;
// Lists all sequence tokens currently executing.
std::set<int> current_sequences_;
// An ID for each posted task to distinguish the task from others in traces.
int trace_id_;
// Set when Shutdown is called and no further tasks should be
// allowed, though we may still be running existing tasks.
bool shutdown_called_;
// The number of new BLOCK_SHUTDOWN tasks that may be posted after Shudown()
// has been called.
int max_blocking_tasks_after_shutdown_;
// State used to cleanup for testing, all guarded by lock_.
CleanupState cleanup_state_;
size_t cleanup_idlers_;
ConditionVariable cleanup_cv_;
TestingObserver* const testing_observer_;
// patch start tanjianwen ====================================================
//
// A token is deprecated as soon as the finalization is started.
// Posting a task associated with deprecated tokens will fail.
std::set<int> deprecated_tokens_;
typedef std::map<int, std::pair<base::WaitableEvent*, FinalizationStage>>
TokenFinalizing;
TokenFinalizing token_final_sync_;
// patch end tanjianwen ====================================================
DISALLOW_COPY_AND_ASSIGN(Inner);
};
// Worker definitions ---------------------------------------------------------
SequencedWorkerPool::Worker::Worker(
const scoped_refptr<SequencedWorkerPool>& worker_pool,
int thread_number,
const std::string& prefix)
: SimpleThread(prefix + StringPrintf("Worker%d", thread_number)),
worker_pool_(worker_pool),
running_shutdown_behavior_(CONTINUE_ON_SHUTDOWN) {
Start();
}
SequencedWorkerPool::Worker::~Worker() {
}
void SequencedWorkerPool::Worker::Run() {
#if defined(OS_WIN)
win::ScopedCOMInitializer com_initializer;
#endif
// Store a pointer to the running sequence in thread local storage for
// static function access.
g_lazy_tls_ptr.Get().Set(&running_sequence_);
// Just jump back to the Inner object to run the thread, since it has all the
// tracking information and queues. It might be more natural to implement
// using DelegateSimpleThread and have Inner implement the Delegate to avoid
// having these worker objects at all, but that method lacks the ability to
// send thread-specific information easily to the thread loop.
worker_pool_->inner_->ThreadLoop(this);
// Release our cyclic reference once we're done.
worker_pool_ = NULL;
}
// Inner definitions ---------------------------------------------------------
SequencedWorkerPool::Inner::Inner(
SequencedWorkerPool* worker_pool,
size_t max_threads,
const std::string& thread_name_prefix,
TestingObserver* observer)
: worker_pool_(worker_pool),
lock_(),
has_work_cv_(&lock_),
can_shutdown_cv_(&lock_),
max_threads_(max_threads),
thread_name_prefix_(thread_name_prefix),
thread_being_created_(false),
waiting_thread_count_(0),
blocking_shutdown_thread_count_(0),
next_sequence_task_number_(0),
blocking_shutdown_pending_task_count_(0),
trace_id_(0),
shutdown_called_(false),
max_blocking_tasks_after_shutdown_(0),
cleanup_state_(CLEANUP_DONE),
cleanup_idlers_(0),
cleanup_cv_(&lock_),
testing_observer_(observer) {}
SequencedWorkerPool::Inner::~Inner() {
// You must call Shutdown() before destroying the pool.
DCHECK(shutdown_called_);
// Need to explicitly join with the threads before they're destroyed or else
// they will be running when our object is half torn down.
for (ThreadMap::iterator it = threads_.begin(); it != threads_.end(); ++it)
it->second->Join();
threads_.clear();
if (testing_observer_)
testing_observer_->OnDestruct();
}
SequencedWorkerPool::SequenceToken
SequencedWorkerPool::Inner::GetSequenceToken() {
// Need to add one because StaticAtomicSequenceNumber starts at zero, which
// is used as a sentinel value in SequenceTokens.
return SequenceToken(g_last_sequence_number_.GetNext() + 1);
}
SequencedWorkerPool::SequenceToken
SequencedWorkerPool::Inner::GetNamedSequenceToken(const std::string& name) {
AutoLock lock(lock_);
return SequenceToken(LockedGetNamedTokenID(name));
}
bool SequencedWorkerPool::Inner::PostTask(
const std::string* optional_token_name,
SequenceToken sequence_token,
WorkerShutdown shutdown_behavior,
const tracked_objects::Location& from_here,
const Closure& task,
TimeDelta delay) {
DCHECK(delay == TimeDelta() || shutdown_behavior == SKIP_ON_SHUTDOWN);
SequencedTask sequenced(from_here);
sequenced.sequence_token_id = sequence_token.id_;
sequenced.shutdown_behavior = shutdown_behavior;
sequenced.posted_from = from_here;
sequenced.task =
shutdown_behavior == BLOCK_SHUTDOWN ?
base::MakeCriticalClosure(task) : task;
sequenced.time_to_run = TimeTicks::Now() + delay;
int create_thread_id = 0;
{
AutoLock lock(lock_);
// patch start tanjianwen ==================================================
if (!deprecated_tokens_.empty()) {
if (deprecated_tokens_.find(sequence_token.id_) !=
deprecated_tokens_.end())
return false;
}
// patch end tanjianwen ==================================================
if (shutdown_called_) {
if (shutdown_behavior != BLOCK_SHUTDOWN ||
LockedCurrentThreadShutdownBehavior() == CONTINUE_ON_SHUTDOWN) {
return false;
}
if (max_blocking_tasks_after_shutdown_ <= 0) {
DLOG(WARNING) << "BLOCK_SHUTDOWN task disallowed";
return false;
}
max_blocking_tasks_after_shutdown_ -= 1;
}
// The trace_id is used for identifying the task in about:tracing.
sequenced.trace_id = trace_id_++;
TRACE_EVENT_FLOW_BEGIN0(TRACE_DISABLED_BY_DEFAULT("toplevel.flow"),
"SequencedWorkerPool::PostTask",
TRACE_ID_MANGLE(GetTaskTraceID(sequenced, static_cast<void*>(this))));
sequenced.sequence_task_number = LockedGetNextSequenceTaskNumber();
// Now that we have the lock, apply the named token rules.
if (optional_token_name)
sequenced.sequence_token_id = LockedGetNamedTokenID(*optional_token_name);
pending_tasks_.insert(sequenced);
if (shutdown_behavior == BLOCK_SHUTDOWN)
blocking_shutdown_pending_task_count_++;
create_thread_id = PrepareToStartAdditionalThreadIfHelpful();
}
// Actually start the additional thread or signal an existing one now that
// we're outside the lock.
if (create_thread_id)
FinishStartingAdditionalThread(create_thread_id);
else
SignalHasWork();
return true;
}
bool SequencedWorkerPool::Inner::RunsTasksOnCurrentThread() const {
AutoLock lock(lock_);
return ContainsKey(threads_, PlatformThread::CurrentId());
}
bool SequencedWorkerPool::Inner::IsRunningSequenceOnCurrentThread(
SequenceToken sequence_token) const {
AutoLock lock(lock_);
ThreadMap::const_iterator found = threads_.find(PlatformThread::CurrentId());
if (found == threads_.end())
return false;
return sequence_token.Equals(found->second->running_sequence());
}
// See https://code.google.com/p/chromium/issues/detail?id=168415
void SequencedWorkerPool::Inner::CleanupForTesting() {
DCHECK(!RunsTasksOnCurrentThread());
base::ThreadRestrictions::ScopedAllowWait allow_wait;
AutoLock lock(lock_);
CHECK_EQ(CLEANUP_DONE, cleanup_state_);
if (shutdown_called_)
return;
if (pending_tasks_.empty() && waiting_thread_count_ == threads_.size())
return;
cleanup_state_ = CLEANUP_REQUESTED;
cleanup_idlers_ = 0;
has_work_cv_.Signal();
while (cleanup_state_ != CLEANUP_DONE)
cleanup_cv_.Wait();
}
void SequencedWorkerPool::Inner::SignalHasWorkForTesting() {
SignalHasWork();
}
void SequencedWorkerPool::Inner::Shutdown(
int max_new_blocking_tasks_after_shutdown) {
DCHECK_GE(max_new_blocking_tasks_after_shutdown, 0);
{
AutoLock lock(lock_);
// Cleanup and Shutdown should not be called concurrently.
CHECK_EQ(CLEANUP_DONE, cleanup_state_);
if (shutdown_called_)
return;
shutdown_called_ = true;
max_blocking_tasks_after_shutdown_ = max_new_blocking_tasks_after_shutdown;
// Tickle the threads. This will wake up a waiting one so it will know that
// it can exit, which in turn will wake up any other waiting ones.
SignalHasWork();
// There are no pending or running tasks blocking shutdown, we're done.
if (CanShutdown())
return;
}
// If we're here, then something is blocking shutdown. So wait for
// CanShutdown() to go to true.
if (testing_observer_)
testing_observer_->WillWaitForShutdown();
#if !defined(OS_NACL)
TimeTicks shutdown_wait_begin = TimeTicks::Now();
#endif
{
base::ThreadRestrictions::ScopedAllowWait allow_wait;
AutoLock lock(lock_);
while (!CanShutdown())
can_shutdown_cv_.Wait();
}
#if !defined(OS_NACL)
UMA_HISTOGRAM_TIMES("SequencedWorkerPool.ShutdownDelayTime",
TimeTicks::Now() - shutdown_wait_begin);
#endif
}
bool SequencedWorkerPool::Inner::IsShutdownInProgress() {
AutoLock lock(lock_);
return shutdown_called_;
}
void SequencedWorkerPool::Inner::ThreadLoop(Worker* this_worker) {
{
AutoLock lock(lock_);
DCHECK(thread_being_created_);
thread_being_created_ = false;
std::pair<ThreadMap::iterator, bool> result =
threads_.insert(
std::make_pair(this_worker->tid(), make_linked_ptr(this_worker)));
DCHECK(result.second);
while (true) {
#if defined(OS_MACOSX)
base::mac::ScopedNSAutoreleasePool autorelease_pool;
#endif
HandleCleanup();
// See GetWork for what delete_these_outside_lock is doing.
SequencedTask task;
TimeDelta wait_time;
std::vector<Closure> delete_these_outside_lock;
GetWorkStatus status =
GetWork(&task, &wait_time, &delete_these_outside_lock);
if (status == GET_WORK_FOUND) {
TRACE_EVENT_FLOW_END0(TRACE_DISABLED_BY_DEFAULT("toplevel.flow"),
"SequencedWorkerPool::PostTask",
TRACE_ID_MANGLE(GetTaskTraceID(task, static_cast<void*>(this))));
TRACE_EVENT2("toplevel", "SequencedWorkerPool::ThreadLoop",
"src_file", task.posted_from.file_name(),
"src_func", task.posted_from.function_name());
int new_thread_id = WillRunWorkerTask(task);
{
AutoUnlock unlock(lock_);
// There may be more work available, so wake up another
// worker thread. (Technically not required, since we
// already get a signal for each new task, but it doesn't
// hurt.)
SignalHasWork();
delete_these_outside_lock.clear();
// Complete thread creation outside the lock if necessary.
if (new_thread_id)
FinishStartingAdditionalThread(new_thread_id);
this_worker->set_running_task_info(
SequenceToken(task.sequence_token_id), task.shutdown_behavior);
tracked_objects::ThreadData::PrepareForStartOfRun(task.birth_tally);
tracked_objects::TaskStopwatch stopwatch;
stopwatch.Start();
task.task.Run();
stopwatch.Stop();
tracked_objects::ThreadData::TallyRunOnNamedThreadIfTracking(
task, stopwatch);
// Make sure our task is erased outside the lock for the
// same reason we do this with delete_these_oustide_lock.
// Also, do it before calling set_running_task_info() so
// that sequence-checking from within the task's destructor
// still works.
task.task = Closure();
this_worker->set_running_task_info(
SequenceToken(), CONTINUE_ON_SHUTDOWN);
}
DidRunWorkerTask(task); // Must be done inside the lock.
// patch start tanjianwen ==================================================
DeprecateTokensIfNeeded(task.sequence_token_id,
&delete_these_outside_lock);
// patch end tanjianwen ==================================================
} else if (cleanup_state_ == CLEANUP_RUNNING) {
switch (status) {
case GET_WORK_WAIT: {
AutoUnlock unlock(lock_);
delete_these_outside_lock.clear();
}
break;
case GET_WORK_NOT_FOUND:
CHECK(delete_these_outside_lock.empty());
cleanup_state_ = CLEANUP_FINISHING;
cleanup_cv_.Broadcast();
break;
default:
NOTREACHED();
}
} else {
// When we're terminating and there's no more work, we can
// shut down, other workers can complete any pending or new tasks.
// We can get additional tasks posted after shutdown_called_ is set
// but only worker threads are allowed to post tasks at that time, and
// the workers responsible for posting those tasks will be available
// to run them. Also, there may be some tasks stuck behind running
// ones with the same sequence token, but additional threads won't
// help this case.
if (shutdown_called_ &&
blocking_shutdown_pending_task_count_ == 0)
break;
waiting_thread_count_++;
switch (status) {
case GET_WORK_NOT_FOUND:
has_work_cv_.Wait();
break;
case GET_WORK_WAIT:
has_work_cv_.TimedWait(wait_time);
break;
default:
NOTREACHED();
}
waiting_thread_count_--;
}
}
} // Release lock_.
// We noticed we should exit. Wake up the next worker so it knows it should
// exit as well (because the Shutdown() code only signals once).
SignalHasWork();
// Possibly unblock shutdown.
can_shutdown_cv_.Signal();
}
void SequencedWorkerPool::Inner::HandleCleanup() {
lock_.AssertAcquired();
if (cleanup_state_ == CLEANUP_DONE)
return;
if (cleanup_state_ == CLEANUP_REQUESTED) {
// We win, we get to do the cleanup as soon as the others wise up and idle.
cleanup_state_ = CLEANUP_STARTING;
while (thread_being_created_ ||
cleanup_idlers_ != threads_.size() - 1) {
has_work_cv_.Signal();
cleanup_cv_.Wait();
}
cleanup_state_ = CLEANUP_RUNNING;
return;
}
if (cleanup_state_ == CLEANUP_STARTING) {
// Another worker thread is cleaning up, we idle here until thats done.
++cleanup_idlers_;
cleanup_cv_.Broadcast();
while (cleanup_state_ != CLEANUP_FINISHING) {
cleanup_cv_.Wait();
}
--cleanup_idlers_;
cleanup_cv_.Broadcast();
return;
}
if (cleanup_state_ == CLEANUP_FINISHING) {
// We wait for all idlers to wake up prior to being DONE.
while (cleanup_idlers_ != 0) {
cleanup_cv_.Broadcast();
cleanup_cv_.Wait();
}
if (cleanup_state_ == CLEANUP_FINISHING) {
cleanup_state_ = CLEANUP_DONE;
cleanup_cv_.Signal();
}
return;
}
}
int SequencedWorkerPool::Inner::LockedGetNamedTokenID(
const std::string& name) {
lock_.AssertAcquired();
DCHECK(!name.empty());
std::map<std::string, int>::const_iterator found =
named_sequence_tokens_.find(name);
if (found != named_sequence_tokens_.end())
return found->second; // Got an existing one.
// Create a new one for this name.
SequenceToken result = GetSequenceToken();
named_sequence_tokens_.insert(std::make_pair(name, result.id_));
return result.id_;
}
int64 SequencedWorkerPool::Inner::LockedGetNextSequenceTaskNumber() {
lock_.AssertAcquired();
// We assume that we never create enough tasks to wrap around.
return next_sequence_task_number_++;
}
SequencedWorkerPool::WorkerShutdown
SequencedWorkerPool::Inner::LockedCurrentThreadShutdownBehavior() const {
lock_.AssertAcquired();
ThreadMap::const_iterator found = threads_.find(PlatformThread::CurrentId());
if (found == threads_.end())
return CONTINUE_ON_SHUTDOWN;
return found->second->running_shutdown_behavior();
}
SequencedWorkerPool::Inner::GetWorkStatus SequencedWorkerPool::Inner::GetWork(
SequencedTask* task,
TimeDelta* wait_time,
std::vector<Closure>* delete_these_outside_lock) {
lock_.AssertAcquired();
// Find the next task with a sequence token that's not currently in use.
// If the token is in use, that means another thread is running something
// in that sequence, and we can't run it without going out-of-order.
//
// This algorithm is simple and fair, but inefficient in some cases. For
// example, say somebody schedules 1000 slow tasks with the same sequence
// number. We'll have to go through all those tasks each time we feel like
// there might be work to schedule. If this proves to be a problem, we
// should make this more efficient.
//
// One possible enhancement would be to keep a map from sequence ID to a
// list of pending but currently blocked SequencedTasks for that ID.
// When a worker finishes a task of one sequence token, it can pick up the
// next one from that token right away.
//
// This may lead to starvation if there are sufficient numbers of sequences
// in use. To alleviate this, we could add an incrementing priority counter
// to each SequencedTask. Then maintain a priority_queue of all runnable
// tasks, sorted by priority counter. When a sequenced task is completed
// we would pop the head element off of that tasks pending list and add it
// to the priority queue. Then we would run the first item in the priority
// queue.
GetWorkStatus status = GET_WORK_NOT_FOUND;
int unrunnable_tasks = 0;
PendingTaskSet::iterator i = pending_tasks_.begin();
// We assume that the loop below doesn't take too long and so we can just do
// a single call to TimeTicks::Now().
const TimeTicks current_time = TimeTicks::Now();
while (i != pending_tasks_.end()) {
if (!IsSequenceTokenRunnable(i->sequence_token_id)) {
unrunnable_tasks++;
++i;
continue;
}
if (shutdown_called_ && i->shutdown_behavior != BLOCK_SHUTDOWN) {
// We're shutting down and the task we just found isn't blocking
// shutdown. Delete it and get more work.
//
// Note that we do not want to delete unrunnable tasks. Deleting a task
// can have side effects (like freeing some objects) and deleting a
// task that's supposed to run after one that's currently running could
// cause an obscure crash.
//
// We really want to delete these tasks outside the lock in case the
// closures are holding refs to objects that want to post work from
// their destructorss (which would deadlock). The closures are
// internally refcounted, so we just need to keep a copy of them alive
// until the lock is exited. The calling code can just clear() the
// vector they passed to us once the lock is exited to make this
// happen.
delete_these_outside_lock->push_back(i->task);
pending_tasks_.erase(i++);
continue;
}
if (i->time_to_run > current_time) {
// The time to run has not come yet.
*wait_time = i->time_to_run - current_time;
status = GET_WORK_WAIT;
if (cleanup_state_ == CLEANUP_RUNNING) {
// Deferred tasks are deleted when cleaning up, see Inner::ThreadLoop.
delete_these_outside_lock->push_back(i->task);
pending_tasks_.erase(i);
}
break;
}
// Found a runnable task.
*task = *i;
pending_tasks_.erase(i);
if (task->shutdown_behavior == BLOCK_SHUTDOWN) {
blocking_shutdown_pending_task_count_--;
}
status = GET_WORK_FOUND;
break;
}
return status;
}
int SequencedWorkerPool::Inner::WillRunWorkerTask(const SequencedTask& task) {
lock_.AssertAcquired();
// Mark the task's sequence number as in use.
if (task.sequence_token_id)
current_sequences_.insert(task.sequence_token_id);
// Ensure that threads running tasks posted with either SKIP_ON_SHUTDOWN
// or BLOCK_SHUTDOWN will prevent shutdown until that task or thread
// completes.
if (task.shutdown_behavior != CONTINUE_ON_SHUTDOWN)
blocking_shutdown_thread_count_++;
// We just picked up a task. Since StartAdditionalThreadIfHelpful only
// creates a new thread if there is no free one, there is a race when posting
// tasks that many tasks could have been posted before a thread started
// running them, so only one thread would have been created. So we also check
// whether we should create more threads after removing our task from the
// queue, which also has the nice side effect of creating the workers from
// background threads rather than the main thread of the app.
//
// If another thread wasn't created, we want to wake up an existing thread
// if there is one waiting to pick up the next task.
//
// Note that we really need to do this *before* running the task, not
// after. Otherwise, if more than one task is posted, the creation of the
// second thread (since we only create one at a time) will be blocked by
// the execution of the first task, which could be arbitrarily long.
return PrepareToStartAdditionalThreadIfHelpful();
}
void SequencedWorkerPool::Inner::DidRunWorkerTask(const SequencedTask& task) {
lock_.AssertAcquired();
if (task.shutdown_behavior != CONTINUE_ON_SHUTDOWN) {
DCHECK_GT(blocking_shutdown_thread_count_, 0u);
blocking_shutdown_thread_count_--;
}
if (task.sequence_token_id)
current_sequences_.erase(task.sequence_token_id);
}
bool SequencedWorkerPool::Inner::IsSequenceTokenRunnable(
int sequence_token_id) const {
lock_.AssertAcquired();
return !sequence_token_id ||
current_sequences_.find(sequence_token_id) ==
current_sequences_.end();
}
int SequencedWorkerPool::Inner::PrepareToStartAdditionalThreadIfHelpful() {
lock_.AssertAcquired();
// How thread creation works:
//
// We'de like to avoid creating threads with the lock held. However, we
// need to be sure that we have an accurate accounting of the threads for
// proper Joining and deltion on shutdown.
//
// We need to figure out if we need another thread with the lock held, which
// is what this function does. It then marks us as in the process of creating
// a thread. When we do shutdown, we wait until the thread_being_created_
// flag is cleared, which ensures that the new thread is properly added to
// all the data structures and we can't leak it. Once shutdown starts, we'll
// refuse to create more threads or they would be leaked.
//
// Note that this creates a mostly benign race condition on shutdown that
// will cause fewer workers to be created than one would expect. It isn't
// much of an issue in real life, but affects some tests. Since we only spawn
// one worker at a time, the following sequence of events can happen:
//
// 1. Main thread posts a bunch of unrelated tasks that would normally be
// run on separate threads.
// 2. The first task post causes us to start a worker. Other tasks do not
// cause a worker to start since one is pending.
// 3. Main thread initiates shutdown.
// 4. No more threads are created since the shutdown_called_ flag is set.
//
// The result is that one may expect that max_threads_ workers to be created
// given the workload, but in reality fewer may be created because the
// sequence of thread creation on the background threads is racing with the
// shutdown call.
if (!shutdown_called_ &&
!thread_being_created_ &&
cleanup_state_ == CLEANUP_DONE &&
threads_.size() < max_threads_ &&
waiting_thread_count_ == 0) {
// We could use an additional thread if there's work to be done.
for (PendingTaskSet::const_iterator i = pending_tasks_.begin();
i != pending_tasks_.end(); ++i) {
if (IsSequenceTokenRunnable(i->sequence_token_id)) {
// Found a runnable task, mark the thread as being started.
thread_being_created_ = true;
return static_cast<int>(threads_.size() + 1);
}
}
}
return 0;
}
void SequencedWorkerPool::Inner::FinishStartingAdditionalThread(
int thread_number) {
// Called outside of the lock.
DCHECK(thread_number > 0);
// The worker is assigned to the list when the thread actually starts, which
// will manage the memory of the pointer.
new Worker(worker_pool_, thread_number, thread_name_prefix_);
}
void SequencedWorkerPool::Inner::SignalHasWork() {
has_work_cv_.Signal();
if (testing_observer_) {
testing_observer_->OnHasWork();
}
}
bool SequencedWorkerPool::Inner::CanShutdown() const {
lock_.AssertAcquired();
// See PrepareToStartAdditionalThreadIfHelpful for how thread creation works.
return !thread_being_created_ &&
blocking_shutdown_thread_count_ == 0 &&
blocking_shutdown_pending_task_count_ == 0;
}
// patch start tanjianwen ======================================================
void SequencedWorkerPool::Inner::FinalizeToken(SequenceToken token) {
std::vector<Closure> delete_these_outside_lock;
{
AutoLock lock(lock_);
// Don't invoke FinalizeToken() with the same token more than once.
DCHECK(deprecated_tokens_.find(token.id_) == deprecated_tokens_.end());
deprecated_tokens_.insert(token.id_);
// Consider such a situation, that no any pending tasks within the thread
// pool at all, and the current executing task is not associated with the
// specified token, then we got no chance to signal the event. In this case,
// we just do nothing but deprecate the token.
bool no_related_task = true;
for (PendingTaskSet::iterator i = pending_tasks_.begin();
i != pending_tasks_.end();) {
if (i->sequence_token_id == token.id_) {
if (i->shutdown_behavior != BLOCK_SHUTDOWN) {
delete_these_outside_lock.push_back(i->task);
i = pending_tasks_.erase(i);
continue;
}
no_related_task = false;
break;
}
++i;
}
if (no_related_task) {
if (current_sequences_.find(token.id_) != current_sequences_.end())
no_related_task = false;
}
if (!no_related_task) {
base::WaitableEvent sync(true, false);
// Don't invoke FinalizeToken() with the same token more than once.
DCHECK(token_final_sync_.find(token.id_) == token_final_sync_.end());
token_final_sync_[token.id_] =
std::make_pair(&sync, DISCARDING_NON_BLOCKING_TASKS);
{
AutoUnlock unlock(lock_);
sync.Wait();
}
}
}
}
void SequencedWorkerPool::Inner::FinalizeNamedToken(const std::string& name) {
int id;
{
AutoLock lock(lock_);
id = LockedGetNamedTokenID(name);
}
FinalizeToken(SequenceToken(id));
}
void SequencedWorkerPool::Inner::DeprecateTokensIfNeeded(
int last_task_token_id, std::vector<Closure>* delete_these_outside_lock) {
lock_.AssertAcquired();
// For most of the time, there would be 0 or 1 items inside
// |token_final_sync_|, so the follow iteration won't take much time really.
for (TokenFinalizing::iterator i = token_final_sync_.begin();
i != token_final_sync_.end();) {
bool through_first_stage = false;
int blocking_task_count = 0;
if (i->second.second == DISCARDING_NON_BLOCKING_TASKS) {
through_first_stage = true;
// In this stage, we need to collect all of the non-blocking tasks
// associated with the specified token, and evict them.
for (PendingTaskSet::iterator j = pending_tasks_.begin();
j != pending_tasks_.end();) {
if (j->sequence_token_id == i->first) {
if (j->shutdown_behavior != BLOCK_SHUTDOWN) {
delete_these_outside_lock->push_back(j->task);
j = pending_tasks_.erase(j);
continue;
} else {
blocking_task_count++;
}
}
++j;
}
// Continue to the next stage.
i->second.second = WAITING_FOR_BLOCKING_TASKS;
}
// No blocking task found.
if (through_first_stage && !blocking_task_count) {
// Before signaling the caller requesting finalization, we have to first
// make sure there is no any task of the same token running
// simultaneously in another worker thread, in which case the event will
// be signaled within that thread after the execution.
if (current_sequences_.find(i->first) == current_sequences_.end()) {
i->second.first->Signal();
i = token_final_sync_.erase(i);
}
continue;
}
// Here we reached the waiting stage. We will not signal the event until
// the last task associated with the specified token is executed.
//
// Here is a small optimization: we don't need to do the checking if the
// last run task's token doesn't match the token being proceeded. Since we
// already ensure that each token in |token_final_sync_| has at least one
// corresponding task in the pending task queue(see FinalizeToken()).
if (last_task_token_id == i->first) {
bool found = false;
for (PendingTaskSet::iterator j = pending_tasks_.begin();
j != pending_tasks_.end(); ++j) {
if (j->sequence_token_id == i->first) {
found = true;
break;
}
}
if (!found) {
// Make sure there is no any task of the same token running
// simultaneously in another worker thread. See comments above.
if (current_sequences_.find(i->first) == current_sequences_.end()) {
i->second.first->Signal();
i = token_final_sync_.erase(i);
}
continue;
}
}
++i;
}
if (!delete_these_outside_lock->empty()) {
AutoUnlock unlock(lock_);
delete_these_outside_lock->clear();
}
}
// patch end tanjianwen ======================================================
base::StaticAtomicSequenceNumber
SequencedWorkerPool::Inner::g_last_sequence_number_;
// SequencedWorkerPool --------------------------------------------------------
// static
SequencedWorkerPool::SequenceToken
SequencedWorkerPool::GetSequenceTokenForCurrentThread() {
// Don't construct lazy instance on check.
if (g_lazy_tls_ptr == NULL)
return SequenceToken();
SequencedWorkerPool::SequenceToken* token = g_lazy_tls_ptr.Get().Get();
if (!token)
return SequenceToken();
return *token;
}
SequencedWorkerPool::SequencedWorkerPool(
size_t max_threads,
const std::string& thread_name_prefix)
: constructor_message_loop_(MessageLoopProxy::current()),
inner_(new Inner(this, max_threads, thread_name_prefix, NULL)) {
}
SequencedWorkerPool::SequencedWorkerPool(
size_t max_threads,
const std::string& thread_name_prefix,
TestingObserver* observer)
: constructor_message_loop_(MessageLoopProxy::current()),
inner_(new Inner(this, max_threads, thread_name_prefix, observer)) {
}
SequencedWorkerPool::~SequencedWorkerPool() {}
void SequencedWorkerPool::OnDestruct() const {
DCHECK(constructor_message_loop_.get());
// Avoid deleting ourselves on a worker thread (which would
// deadlock).
if (RunsTasksOnCurrentThread()) {
constructor_message_loop_->DeleteSoon(FROM_HERE, this);
} else {
delete this;
}
}
SequencedWorkerPool::SequenceToken SequencedWorkerPool::GetSequenceToken() {
return inner_->GetSequenceToken();
}
SequencedWorkerPool::SequenceToken SequencedWorkerPool::GetNamedSequenceToken(
const std::string& name) {
return inner_->GetNamedSequenceToken(name);
}
scoped_refptr<SequencedTaskRunner> SequencedWorkerPool::GetSequencedTaskRunner(
SequenceToken token) {
return GetSequencedTaskRunnerWithShutdownBehavior(token, BLOCK_SHUTDOWN);
}
scoped_refptr<SequencedTaskRunner>
SequencedWorkerPool::GetSequencedTaskRunnerWithShutdownBehavior(
SequenceToken token, WorkerShutdown shutdown_behavior) {
return new SequencedWorkerPoolSequencedTaskRunner(
this, token, shutdown_behavior);
}
scoped_refptr<TaskRunner>
SequencedWorkerPool::GetTaskRunnerWithShutdownBehavior(
WorkerShutdown shutdown_behavior) {
return new SequencedWorkerPoolTaskRunner(this, shutdown_behavior);
}
bool SequencedWorkerPool::PostWorkerTask(
const tracked_objects::Location& from_here,
const Closure& task) {
return inner_->PostTask(NULL, SequenceToken(), BLOCK_SHUTDOWN,
from_here, task, TimeDelta());
}
bool SequencedWorkerPool::PostDelayedWorkerTask(
const tracked_objects::Location& from_here,
const Closure& task,
TimeDelta delay) {
WorkerShutdown shutdown_behavior =
delay == TimeDelta() ? BLOCK_SHUTDOWN : SKIP_ON_SHUTDOWN;
return inner_->PostTask(NULL, SequenceToken(), shutdown_behavior,
from_here, task, delay);
}
bool SequencedWorkerPool::PostWorkerTaskWithShutdownBehavior(
const tracked_objects::Location& from_here,
const Closure& task,
WorkerShutdown shutdown_behavior) {
return inner_->PostTask(NULL, SequenceToken(), shutdown_behavior,
from_here, task, TimeDelta());
}
bool SequencedWorkerPool::PostSequencedWorkerTask(
SequenceToken sequence_token,
const tracked_objects::Location& from_here,
const Closure& task) {
return inner_->PostTask(NULL, sequence_token, BLOCK_SHUTDOWN,
from_here, task, TimeDelta());
}
bool SequencedWorkerPool::PostDelayedSequencedWorkerTask(
SequenceToken sequence_token,
const tracked_objects::Location& from_here,
const Closure& task,
TimeDelta delay) {
WorkerShutdown shutdown_behavior =
delay == TimeDelta() ? BLOCK_SHUTDOWN : SKIP_ON_SHUTDOWN;
return inner_->PostTask(NULL, sequence_token, shutdown_behavior,
from_here, task, delay);
}
bool SequencedWorkerPool::PostNamedSequencedWorkerTask(
const std::string& token_name,
const tracked_objects::Location& from_here,
const Closure& task) {
DCHECK(!token_name.empty());
return inner_->PostTask(&token_name, SequenceToken(), BLOCK_SHUTDOWN,
from_here, task, TimeDelta());
}
bool SequencedWorkerPool::PostSequencedWorkerTaskWithShutdownBehavior(
SequenceToken sequence_token,
const tracked_objects::Location& from_here,
const Closure& task,
WorkerShutdown shutdown_behavior) {
return inner_->PostTask(NULL, sequence_token, shutdown_behavior,
from_here, task, TimeDelta());
}
bool SequencedWorkerPool::PostDelayedTask(
const tracked_objects::Location& from_here,
const Closure& task,
TimeDelta delay) {
return PostDelayedWorkerTask(from_here, task, delay);
}
bool SequencedWorkerPool::RunsTasksOnCurrentThread() const {
return inner_->RunsTasksOnCurrentThread();
}
bool SequencedWorkerPool::IsRunningSequenceOnCurrentThread(
SequenceToken sequence_token) const {
return inner_->IsRunningSequenceOnCurrentThread(sequence_token);
}
void SequencedWorkerPool::FlushForTesting() {
inner_->CleanupForTesting();
}
void SequencedWorkerPool::SignalHasWorkForTesting() {
inner_->SignalHasWorkForTesting();
}
void SequencedWorkerPool::Shutdown(int max_new_blocking_tasks_after_shutdown) {
DCHECK(constructor_message_loop_->BelongsToCurrentThread());
inner_->Shutdown(max_new_blocking_tasks_after_shutdown);
}
bool SequencedWorkerPool::IsShutdownInProgress() {
return inner_->IsShutdownInProgress();
}
// patch start tanjianwen ==================================================
void SequencedWorkerPool::FinalizeToken(SequenceToken token) {
inner_->FinalizeToken(token);
}
void SequencedWorkerPool::FinalizeNamedToken(const std::string& name) {
inner_->FinalizeNamedToken(name);
}
// patch end tanjianwen ==================================================
} // namespace base
| michaelforfxhelp/master | third_party/chromium/base/threading/sequenced_worker_pool.cc | C++ | mpl-2.0 | 53,345 |
<?php
/*
* Copyright (C) 2006-2011 Alex Lance, Clancy Malcolm, Cyber IT Solutions
* Pty. Ltd.
*
* This file is part of the allocPSA application <info@cyber.com.au>.
*
* allocPSA is free software: you can redistribute it and/or modify it
* under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or (at
* your option) any later version.
*
* allocPSA is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public
* License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with allocPSA. If not, see <http://www.gnu.org/licenses/>.
*/
class tools_module extends module {
var $module = "tools";
}
?>
| mattcen/alloc | tools/lib/init.php | PHP | agpl-3.0 | 901 |
<?php
/*
* Copyright (c) 2012-2015 Jochen S. Klar <jklar@aip.de>,
* Adrian M. Partl <apartl@aip.de>,
* AIP E-Science (www.aip.de)
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
class Data_Model_Databases extends Daiquiri_Model_Table {
/**
* Constructor. Sets resource object.
*/
public function __construct() {
$this->setResource('Data_Model_Resource_Databases');
}
/**
* Returns all database entries.
* @return array $response
*/
public function index() {
$databases = array();
foreach($this->getResource()->fetchRows() as $row) {
$database = $this->getResource()->fetchRow($row['id'], true, true);
$database['publication_role'] = Daiquiri_Auth::getInstance()->getRole($database['publication_role_id']);
$database['value'] = '/data/databases/show/id/' . $database['id'];
foreach ($database['tables'] as $tableKey => $table) {
$database['tables'][$tableKey]['publication_role'] = Daiquiri_Auth::getInstance()->getRole($table['publication_role_id']);
$database['tables'][$tableKey]['value'] = '/data/tables/show/id/' . $table['id'];
foreach ($table['columns'] as $columnKey => $column) {
$database['tables'][$tableKey]['columns'][$columnKey]['value'] = '/data/columns/show/id/' . $column['id'];
}
}
$databases[] = $database;
}
return array('databases' => $databases, 'status' => 'ok');
}
/**
* Creates database entry.
* @param array $formParams
* @return array $response
*/
public function create(array $formParams = array()) {
// create the form object
$roles = array_merge(array(0 => 'not published'), Daiquiri_Auth::getInstance()->getRoles());
$form = new Data_Form_Databases(array(
'roles' => $roles,
'submit' => 'Create database entry'
));
// valiadate the form if POST
if (!empty($formParams)) {
if ($form->isValid($formParams)) {
// get the form values
$values = $form->getValues();
// check if entry is already there
if ($this->getResource()->fetchRowByName($values['name']) !== false) {
return $this->getModelHelper('CRUD')->validationErrorResponse($form,'Database entry already exists.');
}
// check if the order needs to be set to NULL
if ($values['order'] === '') {
$values['order'] = NULL;
}
// store the values in the database
try {
$this->getResource()->insertRow($values);
} catch (Exception $e) {
return $this->getModelHelper('CRUD')->validationErrorResponse($form, $e->getMessage());
}
return array('status' => 'ok');
} else {
return $this->getModelHelper('CRUD')->validationErrorResponse($form);
}
}
return array('form' => $form, 'status' => 'form');
}
/**
* Returns a database entry.
* @param mixed $input int id or array with "db" key
* @param bool $tables fetch table information
* @param bool $columns fetch colums information
* @return array $response
*/
public function show($input, $tables = false, $columns = false) {
if (is_int($input)) {
$row = $this->getResource()->fetchRow($input, $tables, $columns);
} elseif (is_array($input)) {
if (empty($input['db'])) {
throw new Exception('Either int id or array with "db" key must be provided as $input');
}
$row = $this->getResource()->fetchRowByName($input['db'], $tables, $columns);
} else {
throw new Exception('$input has wrong type.');
}
if (empty($row)) {
throw new Daiquiri_Exception_NotFound();
}
$row['publication_role'] = Daiquiri_Auth::getInstance()->getRole($row['publication_role_id']);
return array('status' => 'ok','row' => $row);
}
/**
* Updates a database entry.
* @param mixed $input int id or array with "db" key
* @return array $response
*/
public function update($input, array $formParams = array()) {
if (is_int($input)) {
$entry = $this->getResource()->fetchRow($input);
} elseif (is_array($input)) {
if (empty($input['db'])) {
throw new Exception('Either int id or array with "db" key must be provided as $input');
}
$entry = $this->getResource()->fetchRowByName($input['db']);
} else {
throw new Exception('$input has wrong type.');
}
if (empty($entry)) {
throw new Daiquiri_Exception_NotFound();
}
// create the form object
$roles = array_merge(array(0 => 'not published'), Daiquiri_Auth::getInstance()->getRoles());
$form = new Data_Form_Databases(array(
'entry' => $entry,
'roles' => $roles,
'submit' => 'Update database entry'
));
// valiadate the form if POST
if (!empty($formParams)) {
if ($form->isValid($formParams)) {
// get the form values
$values = $form->getValues();
// check if the order needs to be set to NULL
if ($values['order'] === '') {
$values['order'] = NULL;
}
$this->getResource()->updateRow($entry['id'], $values);
return array('status' => 'ok');
} else {
return $this->getModelHelper('CRUD')->validationErrorResponse($form);
}
}
return array('form' => $form, 'status' => 'form');
}
/**
* Deletes a database entry.
* @param mixed $input int id or array with "db" key
* @return array $response
*/
public function delete($input, array $formParams = array()) {
if (is_int($input)) {
$row = $this->getResource()->fetchRow($input);
} elseif (is_array($input)) {
if (empty($input['db'])) {
throw new Exception('Either int id or array with "db" key must be provided as $input');
}
$row = $this->getResource()->fetchRowByName($input['db']);
} else {
throw new Exception('$input has wrong type.');
}
if (empty($row)) {
throw new Daiquiri_Exception_NotFound();
}
return $this->getModelHelper('CRUD')->delete($row['id'], $formParams);
}
/**
* Returns all config databases for export.
* @return array $response
*/
public function export() {
$rows = array();
foreach($this->getResource()->fetchRows() as $dbRow) {
$rows[] = array(
'name' => $dbRow['name'],
'order' => $dbRow['order'],
'description' => $dbRow['description'],
'publication_select' => $dbRow['publication_select'],
'publication_update' => $dbRow['publication_update'],
'publication_insert' => $dbRow['publication_insert'],
'publication_show' => $dbRow['publication_show'],
'publication_role' => Daiquiri_Auth::getInstance()->getRole($dbRow['publication_role_id'])
);
}
return array(
'data' => array('databases' => $rows),
'status' => 'ok'
);
}
}
| aipescience/daiquiri | modules/data/models/Databases.php | PHP | agpl-3.0 | 8,415 |
package info.nightscout.androidaps.plugins.pump.medtronic.driver;
import org.joda.time.LocalDateTime;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.HashMap;
import java.util.Map;
import info.nightscout.androidaps.MainApp;
import info.nightscout.androidaps.R;
import info.nightscout.androidaps.interfaces.PumpDescription;
import info.nightscout.androidaps.logging.L;
import info.nightscout.androidaps.plugins.pump.common.data.PumpStatus;
import info.nightscout.androidaps.plugins.pump.common.defs.PumpType;
import info.nightscout.androidaps.plugins.pump.common.hw.rileylink.RileyLinkConst;
import info.nightscout.androidaps.plugins.pump.common.hw.rileylink.RileyLinkUtil;
import info.nightscout.androidaps.plugins.pump.common.hw.rileylink.ble.defs.RileyLinkEncodingType;
import info.nightscout.androidaps.plugins.pump.common.hw.rileylink.ble.defs.RileyLinkTargetFrequency;
import info.nightscout.androidaps.plugins.pump.common.hw.rileylink.defs.RileyLinkError;
import info.nightscout.androidaps.plugins.pump.common.hw.rileylink.defs.RileyLinkServiceState;
import info.nightscout.androidaps.plugins.pump.medtronic.data.MedtronicHistoryData;
import info.nightscout.androidaps.plugins.pump.medtronic.defs.BasalProfileStatus;
import info.nightscout.androidaps.plugins.pump.medtronic.defs.BatteryType;
import info.nightscout.androidaps.plugins.pump.medtronic.defs.MedtronicDeviceType;
import info.nightscout.androidaps.plugins.pump.medtronic.defs.PumpDeviceState;
import info.nightscout.androidaps.plugins.pump.medtronic.util.MedtronicConst;
import info.nightscout.androidaps.plugins.pump.medtronic.util.MedtronicUtil;
import info.nightscout.androidaps.utils.SP;
/**
* Created by andy on 4/28/18.
*/
public class MedtronicPumpStatus extends PumpStatus {
private static Logger LOG = LoggerFactory.getLogger(L.PUMP);
public String errorDescription = null;
public String serialNumber;
public String pumpFrequency = null;
public String rileyLinkAddress = null;
public Double maxBolus;
public Double maxBasal;
public boolean inPreInit = true;
// statuses
public RileyLinkServiceState rileyLinkServiceState = RileyLinkServiceState.NotStarted;
public RileyLinkError rileyLinkError;
public PumpDeviceState pumpDeviceState = PumpDeviceState.NeverContacted;
public MedtronicDeviceType medtronicDeviceType = null;
public double currentBasal = 0;
public int tempBasalInProgress = 0;
public int tempBasalRatio = 0;
public int tempBasalRemainMin = 0;
public Date tempBasalStart;
public Double tempBasalAmount = 0.0d;
// fixme
public Integer tempBasalLength = 0;
private String regexMac = "([\\da-fA-F]{1,2}(?:\\:|$)){6}";
private String regexSN = "[0-9]{6}";
private boolean serialChanged = false;
private boolean rileyLinkAddressChanged = false;
private boolean encodingChanged = false;
private boolean targetFrequencyChanged = false;
private RileyLinkEncodingType encodingType;
private String[] frequencies;
private boolean isFrequencyUS = false;
private Map<String, PumpType> medtronicPumpMap = null;
private Map<String, MedtronicDeviceType> medtronicDeviceTypeMap = null;
private RileyLinkTargetFrequency targetFrequency;
public BasalProfileStatus basalProfileStatus = BasalProfileStatus.NotInitialized;
public BatteryType batteryType = BatteryType.None;
public MedtronicPumpStatus(PumpDescription pumpDescription) {
super(pumpDescription);
}
@Override
public void initSettings() {
this.activeProfileName = "STD";
this.reservoirRemainingUnits = 75d;
this.batteryRemaining = 75;
if (this.medtronicPumpMap == null)
createMedtronicPumpMap();
if (this.medtronicDeviceTypeMap == null)
createMedtronicDeviceTypeMap();
this.lastConnection = SP.getLong(MedtronicConst.Statistics.LastGoodPumpCommunicationTime, 0L);
this.lastDataTime = new LocalDateTime(this.lastConnection);
}
private void createMedtronicDeviceTypeMap() {
medtronicDeviceTypeMap = new HashMap<>();
medtronicDeviceTypeMap.put("512", MedtronicDeviceType.Medtronic_512);
medtronicDeviceTypeMap.put("712", MedtronicDeviceType.Medtronic_712);
medtronicDeviceTypeMap.put("515", MedtronicDeviceType.Medtronic_515);
medtronicDeviceTypeMap.put("715", MedtronicDeviceType.Medtronic_715);
medtronicDeviceTypeMap.put("522", MedtronicDeviceType.Medtronic_522);
medtronicDeviceTypeMap.put("722", MedtronicDeviceType.Medtronic_722);
medtronicDeviceTypeMap.put("523", MedtronicDeviceType.Medtronic_523_Revel);
medtronicDeviceTypeMap.put("723", MedtronicDeviceType.Medtronic_723_Revel);
medtronicDeviceTypeMap.put("554", MedtronicDeviceType.Medtronic_554_Veo);
medtronicDeviceTypeMap.put("754", MedtronicDeviceType.Medtronic_754_Veo);
}
private void createMedtronicPumpMap() {
medtronicPumpMap = new HashMap<>();
medtronicPumpMap.put("512", PumpType.Medtronic_512_712);
medtronicPumpMap.put("712", PumpType.Medtronic_512_712);
medtronicPumpMap.put("515", PumpType.Medtronic_515_715);
medtronicPumpMap.put("715", PumpType.Medtronic_515_715);
medtronicPumpMap.put("522", PumpType.Medtronic_522_722);
medtronicPumpMap.put("722", PumpType.Medtronic_522_722);
medtronicPumpMap.put("523", PumpType.Medtronic_523_723_Revel);
medtronicPumpMap.put("723", PumpType.Medtronic_523_723_Revel);
medtronicPumpMap.put("554", PumpType.Medtronic_554_754_Veo);
medtronicPumpMap.put("754", PumpType.Medtronic_554_754_Veo);
frequencies = new String[2];
frequencies[0] = MainApp.gs(R.string.key_medtronic_pump_frequency_us_ca);
frequencies[1] = MainApp.gs(R.string.key_medtronic_pump_frequency_worldwide);
}
public boolean verifyConfiguration() {
try {
// FIXME don't reload information several times
if (this.medtronicPumpMap == null)
createMedtronicPumpMap();
if (this.medtronicDeviceTypeMap == null)
createMedtronicDeviceTypeMap();
this.errorDescription = "-";
String serialNr = SP.getString(MedtronicConst.Prefs.PumpSerial, null);
if (serialNr == null) {
this.errorDescription = MainApp.gs(R.string.medtronic_error_serial_not_set);
return false;
} else {
if (!serialNr.matches(regexSN)) {
this.errorDescription = MainApp.gs(R.string.medtronic_error_serial_invalid);
return false;
} else {
if (!serialNr.equals(this.serialNumber)) {
this.serialNumber = serialNr;
serialChanged = true;
}
}
}
String pumpType = SP.getString(MedtronicConst.Prefs.PumpType, null);
if (pumpType == null) {
this.errorDescription = MainApp.gs(R.string.medtronic_error_pump_type_not_set);
return false;
} else {
String pumpTypePart = pumpType.substring(0, 3);
if (!pumpTypePart.matches("[0-9]{3}")) {
this.errorDescription = MainApp.gs(R.string.medtronic_error_pump_type_invalid);
return false;
} else {
this.pumpType = medtronicPumpMap.get(pumpTypePart);
this.medtronicDeviceType = medtronicDeviceTypeMap.get(pumpTypePart);
this.pumpDescription.setPumpDescription(this.pumpType);
if (pumpTypePart.startsWith("7"))
this.reservoirFullUnits = 300;
else
this.reservoirFullUnits = 176;
}
}
String pumpFrequency = SP.getString(MedtronicConst.Prefs.PumpFrequency, null);
if (pumpFrequency == null) {
this.errorDescription = MainApp.gs(R.string.medtronic_error_pump_frequency_not_set);
return false;
} else {
if (!pumpFrequency.equals(frequencies[0]) && !pumpFrequency.equals(frequencies[1])) {
this.errorDescription = MainApp.gs(R.string.medtronic_error_pump_frequency_invalid);
return false;
} else {
this.pumpFrequency = pumpFrequency;
this.isFrequencyUS = pumpFrequency.equals(frequencies[0]);
RileyLinkTargetFrequency newTargetFrequency = this.isFrequencyUS ? //
RileyLinkTargetFrequency.Medtronic_US
: RileyLinkTargetFrequency.Medtronic_WorldWide;
if (targetFrequency != newTargetFrequency) {
RileyLinkUtil.setRileyLinkTargetFrequency(newTargetFrequency);
targetFrequency = newTargetFrequency;
targetFrequencyChanged = true;
}
}
}
String rileyLinkAddress = SP.getString(RileyLinkConst.Prefs.RileyLinkAddress, null);
if (rileyLinkAddress == null) {
if (isLogEnabled())
LOG.debug("RileyLink address invalid: null");
this.errorDescription = MainApp.gs(R.string.medtronic_error_rileylink_address_invalid);
return false;
} else {
if (!rileyLinkAddress.matches(regexMac)) {
this.errorDescription = MainApp.gs(R.string.medtronic_error_rileylink_address_invalid);
if (isLogEnabled())
LOG.debug("RileyLink address invalid: {}", rileyLinkAddress);
} else {
if (!rileyLinkAddress.equals(this.rileyLinkAddress)) {
this.rileyLinkAddress = rileyLinkAddress;
rileyLinkAddressChanged = true;
}
}
}
double maxBolusLcl = checkParameterValue(MedtronicConst.Prefs.MaxBolus, "25.0", 25.0d);
if (maxBolus == null || !maxBolus.equals(maxBolusLcl)) {
maxBolus = maxBolusLcl;
//LOG.debug("Max Bolus from AAPS settings is " + maxBolus);
}
double maxBasalLcl = checkParameterValue(MedtronicConst.Prefs.MaxBasal, "35.0", 35.0d);
if (maxBasal == null || !maxBasal.equals(maxBasalLcl)) {
maxBasal = maxBasalLcl;
//LOG.debug("Max Basal from AAPS settings is " + maxBasal);
}
String encodingTypeStr = SP.getString(MedtronicConst.Prefs.Encoding, null);
if (encodingTypeStr == null) {
return false;
}
RileyLinkEncodingType newEncodingType = RileyLinkEncodingType.getByDescription(encodingTypeStr);
if (this.encodingType == null) {
this.encodingType = newEncodingType;
} else if (this.encodingType != newEncodingType) {
this.encodingType = newEncodingType;
this.encodingChanged = true;
}
String batteryTypeStr = SP.getString(MedtronicConst.Prefs.BatteryType, null);
if (batteryTypeStr == null)
return false;
BatteryType batteryType = BatteryType.getByDescription(batteryTypeStr);
if (this.batteryType != batteryType) {
this.batteryType = batteryType;
MedtronicUtil.setBatteryType(this.batteryType);
}
String bolusDebugEnabled = SP.getString(MedtronicConst.Prefs.BolusDebugEnabled, null);
boolean bolusDebug = bolusDebugEnabled != null && bolusDebugEnabled.equals(MainApp.gs(R.string.common_on));
MedtronicHistoryData.doubleBolusDebug = bolusDebug;
reconfigureService();
return true;
} catch (Exception ex) {
this.errorDescription = ex.getMessage();
LOG.error("Error on Verification: " + ex.getMessage(), ex);
return false;
}
}
private boolean reconfigureService() {
if (!inPreInit && MedtronicUtil.getMedtronicService() != null) {
if (serialChanged) {
MedtronicUtil.getMedtronicService().setPumpIDString(this.serialNumber); // short operation
serialChanged = false;
}
if (rileyLinkAddressChanged) {
MedtronicUtil.sendBroadcastMessage(RileyLinkConst.Intents.RileyLinkNewAddressSet);
rileyLinkAddressChanged = false;
}
if (encodingChanged) {
RileyLinkUtil.getRileyLinkService().changeRileyLinkEncoding(encodingType);
encodingChanged = false;
}
}
// if (targetFrequencyChanged && !inPreInit && MedtronicUtil.getMedtronicService() != null) {
// RileyLinkUtil.setRileyLinkTargetFrequency(targetFrequency);
// // RileyLinkUtil.getRileyLinkCommunicationManager().refreshRileyLinkTargetFrequency();
// targetFrequencyChanged = false;
// }
return (!rileyLinkAddressChanged && !serialChanged && !encodingChanged); // && !targetFrequencyChanged);
}
private double checkParameterValue(int key, String defaultValue, double defaultValueDouble) {
double val = 0.0d;
String value = SP.getString(key, defaultValue);
try {
val = Double.parseDouble(value);
} catch (Exception ex) {
LOG.error("Error parsing setting: {}, value found {}", key, value);
val = defaultValueDouble;
}
if (val > defaultValueDouble) {
SP.putString(key, defaultValue);
val = defaultValueDouble;
}
return val;
}
public String getErrorInfo() {
verifyConfiguration();
return (this.errorDescription == null) ? "-" : this.errorDescription;
}
@Override
public void refreshConfiguration() {
verifyConfiguration();
}
public boolean setNotInPreInit() {
this.inPreInit = false;
return reconfigureService();
}
public double getBasalProfileForHour() {
if (basalsByHour != null) {
GregorianCalendar c = new GregorianCalendar();
int hour = c.get(Calendar.HOUR_OF_DAY);
return basalsByHour[hour];
}
return 0;
}
private boolean isLogEnabled() {
return L.isEnabled(L.PUMP);
}
}
| PoweRGbg/AndroidAPS | app/src/main/java/info/nightscout/androidaps/plugins/pump/medtronic/driver/MedtronicPumpStatus.java | Java | agpl-3.0 | 14,862 |
// Ryzom - MMORPG Framework <http://dev.ryzom.com/projects/ryzom/>
// Copyright (C) 2010 Winch Gate Property Limited
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as
// published by the Free Software Foundation, either version 3 of the
// License, or (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
// LuaFrame.cpp : implementation of the CLuaFrame class
//
#include "stdafx.h"
#include "ide2.h"
#include "LuaFrame.h"
#include "LuaDoc.h"
#ifdef _DEBUG
#define new DEBUG_NEW
#undef THIS_FILE
static char THIS_FILE[] = __FILE__;
#endif
/////////////////////////////////////////////////////////////////////////////
// CLuaFrame
IMPLEMENT_DYNCREATE(CLuaFrame, CMDIChildWnd)
BEGIN_MESSAGE_MAP(CLuaFrame, CMDIChildWnd)
//{{AFX_MSG_MAP(CLuaFrame)
// NOTE - the ClassWizard will add and remove mapping macros here.
// DO NOT EDIT what you see in these blocks of generated code !
//}}AFX_MSG_MAP
END_MESSAGE_MAP()
/////////////////////////////////////////////////////////////////////////////
// CLuaFrame construction/destruction
CLuaFrame::CLuaFrame()
{
// TODO: add member initialization code here
}
CLuaFrame::~CLuaFrame()
{
}
BOOL CLuaFrame::PreCreateWindow(CREATESTRUCT& cs)
{
// TODO: Modify the Window class or styles here by modifying
// the CREATESTRUCT cs
if( !CMDIChildWnd::PreCreateWindow(cs) )
return FALSE;
return TRUE;
}
/////////////////////////////////////////////////////////////////////////////
// CLuaFrame diagnostics
#ifdef _DEBUG
void CLuaFrame::AssertValid() const
{
CMDIChildWnd::AssertValid();
}
void CLuaFrame::Dump(CDumpContext& dc) const
{
CMDIChildWnd::Dump(dc);
}
#endif //_DEBUG
/////////////////////////////////////////////////////////////////////////////
// CLuaFrame message handlers
BOOL CLuaFrame::PreTranslateMessage(MSG* pMsg)
{
// TODO: Add your specialized code here and/or call the base class
return CMDIChildWnd::PreTranslateMessage(pMsg);
}
void CLuaFrame::OnUpdateFrameTitle(BOOL bAddToTitle)
{
// update our parent window first
GetMDIFrame()->OnUpdateFrameTitle(bAddToTitle);
if ((GetStyle() & FWS_ADDTOTITLE) == 0)
return; // leave child window alone!
CDocument* pDocument = GetActiveDocument();
if (bAddToTitle)
{
TCHAR szText[256+_MAX_PATH];
if (pDocument == NULL)
lstrcpy(szText, m_strTitle);
else
lstrcpy(szText, ((CLuaDoc *) pDocument)->GetTitle());
if (m_nWindow > 0)
wsprintf(szText + lstrlen(szText), _T(":%d"), m_nWindow);
// set title if changed, but don't remove completely
AfxSetWindowText(m_hWnd, szText);
}
}
| osgcc/ryzom | ryzom/client/src/lua_ide_dll_nevrax/source/Ide2/LuaFrame.cpp | C++ | agpl-3.0 | 3,036 |
class AddUserIdToPetition < ActiveRecord::Migration
def change
add_column :petitions, :user_id, :integer
end
end
| ChrisAntaki/victorykit | db/migrate/20120424204557_add_user_id_to_petition.rb | Ruby | agpl-3.0 | 121 |
// Copyright 2014 Canonical Ltd.
// Licensed under the AGPLv3, see LICENCE file for details.
package block
import (
"github.com/juju/cmd"
"github.com/juju/juju/apiserver/params"
"github.com/juju/juju/cmd/envcmd"
)
var (
BlockClient = &getBlockClientAPI
UnblockClient = &getUnblockClientAPI
ListClient = &getBlockListAPI
NewDestroyCommand = newDestroyCommand
NewRemoveCommand = newRemoveCommand
NewChangeCommand = newChangeCommand
NewListCommand = newListCommand
)
type MockBlockClient struct {
BlockType string
Msg string
}
func (c *MockBlockClient) Close() error {
return nil
}
func (c *MockBlockClient) SwitchBlockOn(blockType, msg string) error {
c.BlockType = blockType
c.Msg = msg
return nil
}
func (c *MockBlockClient) SwitchBlockOff(blockType string) error {
c.BlockType = blockType
c.Msg = ""
return nil
}
func (c *MockBlockClient) List() ([]params.Block, error) {
if c.BlockType == "" {
return []params.Block{}, nil
}
return []params.Block{
params.Block{
Type: c.BlockType,
Message: c.Msg,
},
}, nil
}
func NewUnblockCommandWithClient(client UnblockClientAPI) cmd.Command {
return envcmd.Wrap(&unblockCommand{client: client})
}
| fwereade/juju | cmd/juju/block/export_test.go | GO | agpl-3.0 | 1,204 |
<?php
/**
* @author Bart Visscher <bartv@thisnet.nl>
* @author eduardo <eduardo@vnexu.net>
* @author Joas Schilling <nickvergessen@owncloud.com>
* @author Morris Jobke <hey@morrisjobke.de>
* @author Roeland Jago Douma <rullzer@owncloud.com>
* @author Stefan Weil <sw@weilnetz.de>
* @author Thomas Müller <thomas.mueller@tmit.eu>
*
* @copyright Copyright (c) 2016, ownCloud, Inc.
* @license AGPL-3.0
*
* This code is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License, version 3,
* as published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License, version 3,
* along with this program. If not, see <http://www.gnu.org/licenses/>
*
*/
namespace OC\Setup;
class PostgreSQL extends AbstractDatabase {
public $dbprettyname = 'PostgreSQL';
public function setupDatabase($username) {
$e_host = addslashes($this->dbHost);
$e_user = addslashes($this->dbUser);
$e_password = addslashes($this->dbPassword);
// Fix database with port connection
if(strpos($e_host, ':')) {
list($e_host, $port)=explode(':', $e_host, 2);
} else {
$port=false;
}
//check if the database user has admin rights
$connection_string = "host='$e_host' dbname=postgres user='$e_user' port='$port' password='$e_password'";
$connection = @pg_connect($connection_string);
if(!$connection) {
// Try if we can connect to the DB with the specified name
$e_dbname = addslashes($this->dbName);
$connection_string = "host='$e_host' dbname='$e_dbname' user='$e_user' port='$port' password='$e_password'";
$connection = @pg_connect($connection_string);
if(!$connection)
throw new \OC\DatabaseSetupException($this->trans->t('PostgreSQL username and/or password not valid'),
$this->trans->t('You need to enter either an existing account or the administrator.'));
}
$e_user = pg_escape_string($this->dbUser);
//check for roles creation rights in postgresql
$query="SELECT 1 FROM pg_roles WHERE rolcreaterole=TRUE AND rolname='$e_user'";
$result = pg_query($connection, $query);
if($result and pg_num_rows($result) > 0) {
//use the admin login data for the new database user
//add prefix to the postgresql user name to prevent collisions
$this->dbUser='oc_'.$username;
//create a new password so we don't need to store the admin config in the config file
$this->dbPassword = \OC::$server->getSecureRandom()->generate(30, \OCP\Security\ISecureRandom::CHAR_LOWER.\OCP\Security\ISecureRandom::CHAR_DIGITS);
$this->createDBUser($connection);
}
$systemConfig = \OC::$server->getSystemConfig();
$systemConfig->setValues([
'dbuser' => $this->dbUser,
'dbpassword' => $this->dbPassword,
]);
//create the database
$this->createDatabase($connection);
// the connection to dbname=postgres is not needed anymore
pg_close($connection);
// connect to the ownCloud database (dbname=$this->dbname) and check if it needs to be filled
$this->dbUser = $systemConfig->getValue('dbuser');
$this->dbPassword = $systemConfig->getValue('dbpassword');
$e_host = addslashes($this->dbHost);
$e_dbname = addslashes($this->dbName);
$e_user = addslashes($this->dbUser);
$e_password = addslashes($this->dbPassword);
// Fix database with port connection
if(strpos($e_host, ':')) {
list($e_host, $port)=explode(':', $e_host, 2);
} else {
$port=false;
}
$connection_string = "host='$e_host' dbname='$e_dbname' user='$e_user' port='$port' password='$e_password'";
$connection = @pg_connect($connection_string);
if(!$connection) {
throw new \OC\DatabaseSetupException($this->trans->t('PostgreSQL username and/or password not valid'),
$this->trans->t('You need to enter either an existing account or the administrator.'));
}
$query = "select count(*) FROM pg_class WHERE relname='".$this->tablePrefix."users' limit 1";
$result = pg_query($connection, $query);
if($result) {
$row = pg_fetch_row($result);
}
if(!$result or $row[0]==0) {
\OC_DB::createDbFromStructure($this->dbDefinitionFile);
}
}
private function createDatabase($connection) {
//we can't use OC_BD functions here because we need to connect as the administrative user.
$e_name = pg_escape_string($this->dbName);
$e_user = pg_escape_string($this->dbUser);
$query = "select datname from pg_database where datname = '$e_name'";
$result = pg_query($connection, $query);
if(!$result) {
$entry = $this->trans->t('DB Error: "%s"', array(pg_last_error($connection))) . '<br />';
$entry .= $this->trans->t('Offending command was: "%s"', array($query)) . '<br />';
\OCP\Util::writeLog('setup.pg', $entry, \OCP\Util::WARN);
}
if(! pg_fetch_row($result)) {
//The database does not exists... let's create it
$query = "CREATE DATABASE \"$e_name\" OWNER \"$e_user\"";
$result = pg_query($connection, $query);
if(!$result) {
$entry = $this->trans->t('DB Error: "%s"', array(pg_last_error($connection))) . '<br />';
$entry .= $this->trans->t('Offending command was: "%s"', array($query)) . '<br />';
\OCP\Util::writeLog('setup.pg', $entry, \OCP\Util::WARN);
}
else {
$query = "REVOKE ALL PRIVILEGES ON DATABASE \"$e_name\" FROM PUBLIC";
pg_query($connection, $query);
}
}
}
private function createDBUser($connection) {
$e_name = pg_escape_string($this->dbUser);
$e_password = pg_escape_string($this->dbPassword);
$query = "select * from pg_roles where rolname='$e_name';";
$result = pg_query($connection, $query);
if(!$result) {
$entry = $this->trans->t('DB Error: "%s"', array(pg_last_error($connection))) . '<br />';
$entry .= $this->trans->t('Offending command was: "%s"', array($query)) . '<br />';
\OCP\Util::writeLog('setup.pg', $entry, \OCP\Util::WARN);
}
if(! pg_fetch_row($result)) {
//user does not exists let's create it :)
$query = "CREATE USER \"$e_name\" CREATEDB PASSWORD '$e_password';";
$result = pg_query($connection, $query);
if(!$result) {
$entry = $this->trans->t('DB Error: "%s"', array(pg_last_error($connection))) . '<br />';
$entry .= $this->trans->t('Offending command was: "%s"', array($query)) . '<br />';
\OCP\Util::writeLog('setup.pg', $entry, \OCP\Util::WARN);
}
}
else { // change password of the existing role
$query = "ALTER ROLE \"$e_name\" WITH PASSWORD '$e_password';";
$result = pg_query($connection, $query);
if(!$result) {
$entry = $this->trans->t('DB Error: "%s"', array(pg_last_error($connection))) . '<br />';
$entry .= $this->trans->t('Offending command was: "%s"', array($query)) . '<br />';
\OCP\Util::writeLog('setup.pg', $entry, \OCP\Util::WARN);
}
}
}
}
| bluelml/core | lib/private/Setup/PostgreSQL.php | PHP | agpl-3.0 | 7,003 |
#-*- coding:utf-8 -*-
#
#
# Copyright (C) 2013 Michael Telahun Makonnen <mmakonnen@gmail.com>.
# All Rights Reserved.
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
#
#
from datetime import datetime, date, timedelta
from dateutil.relativedelta import relativedelta
from openerp.osv import fields, osv
from openerp.tools import DEFAULT_SERVER_DATE_FORMAT as OE_DATEFORMAT
class hr_employee(osv.Model):
_inherit = 'hr.employee'
def _get_contracts_list(self, employee):
'''Return list of contracts in chronological order'''
contracts = []
for c in employee.contract_ids:
l = len(contracts)
if l == 0:
contracts.append(c)
else:
dCStart = datetime.strptime(c.date_start, OE_DATEFORMAT).date()
i = l - 1
while i >= 0:
dContractStart = datetime.strptime(
contracts[i].date_start, OE_DATEFORMAT).date()
if dContractStart < dCStart:
contracts = contracts[:i + 1] + [c] + contracts[i + 1:]
break
elif i == 0:
contracts = [c] + contracts
i -= 1
return contracts
def _get_days_in_month(self, d):
last_date = d - timedelta(days=(d.day - 1)) + relativedelta(
months= +1) + relativedelta(days= -1)
return last_date.day
def get_months_service_to_date(self, cr, uid, ids, dToday=None, context=None):
'''Returns a dictionary of floats. The key is the employee id, and the value is
number of months of employment.'''
res = dict.fromkeys(ids, 0)
if dToday == None:
dToday = date.today()
for ee in self.pool.get('hr.employee').browse(cr, uid, ids, context=context):
delta = relativedelta(dToday, dToday)
contracts = self._get_contracts_list(ee)
if len(contracts) == 0:
res[ee.id] = (0.0, False)
continue
dInitial = datetime.strptime(
contracts[0].date_start, OE_DATEFORMAT).date()
if ee.initial_employment_date:
dFirstContract = dInitial
dInitial = datetime.strptime(
ee.initial_employment_date, '%Y-%m-%d').date()
if dFirstContract < dInitial:
raise osv.except_osv(_('Employment Date mismatch!'),
_('The initial employment date cannot be after the first contract in the system.\nEmployee: %s', ee.name))
delta = relativedelta(dFirstContract, dInitial)
for c in contracts:
dStart = datetime.strptime(c.date_start, '%Y-%m-%d').date()
if dStart >= dToday:
continue
# If the contract doesn't have an end date, use today's date
# If the contract has finished consider the entire duration of
# the contract, otherwise consider only the months in the
# contract until today.
#
if c.date_end:
dEnd = datetime.strptime(c.date_end, '%Y-%m-%d').date()
else:
dEnd = dToday
if dEnd > dToday:
dEnd = dToday
delta += relativedelta(dEnd, dStart)
# Set the number of months the employee has worked
date_part = float(delta.days) / float(
self._get_days_in_month(dInitial))
res[ee.id] = (
float((delta.years * 12) + delta.months) + date_part, dInitial)
return res
def _get_employed_months(self, cr, uid, ids, field_name, arg, context=None):
res = dict.fromkeys(ids, 0.0)
_res = self.get_months_service_to_date(cr, uid, ids, context=context)
for k, v in _res.iteritems():
res[k] = v[0]
return res
def _search_amount(self, cr, uid, obj, name, args, context):
ids = set()
for cond in args:
amount = cond[2]
if isinstance(cond[2], (list, tuple)):
if cond[1] in ['in', 'not in']:
amount = tuple(cond[2])
else:
continue
else:
if cond[1] in ['=like', 'like', 'not like', 'ilike', 'not ilike', 'in', 'not in', 'child_of']:
continue
cr.execute("select id from hr_employee having %s %%s" %
(cond[1]), (amount,))
res_ids = set(id[0] for id in cr.fetchall())
ids = ids and (ids & res_ids) or res_ids
if ids:
return [('id', 'in', tuple(ids))]
return [('id', '=', '0')]
_columns = {
'initial_employment_date': fields.date('Initial Date of Employment', groups=False,
help='Date of first employment if it was before the start of the first contract in the system.'),
'length_of_service': fields.function(_get_employed_months, type='float', method=True,
groups=False,
string='Lenght of Service'),
}
| bwrsandman/openerp-hr | hr_employee_seniority/hr.py | Python | agpl-3.0 | 5,976 |
#
# Copyright (C) 2011 - present Instructure, Inc.
#
# This file is part of Canvas.
#
# Canvas is free software: you can redistribute it and/or modify it under
# the terms of the GNU Affero General Public License as published by the Free
# Software Foundation, version 3 of the License.
#
# Canvas is distributed in the hope that it will be useful, but WITHOUT ANY
# WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
# A PARTICULAR PURPOSE. See the GNU Affero General Public License for more
# details.
#
# You should have received a copy of the GNU Affero General Public License along
# with this program. If not, see <http://www.gnu.org/licenses/>.
#
module Factories
def assignment_override_model(opts={})
override_for = opts.delete(:set)
assignment = opts.delete(:assignment) || opts.delete(:quiz) || assignment_model(opts)
attrs = assignment_override_valid_attributes.merge(opts)
attrs[:due_at_overridden] = opts.key?(:due_at)
attrs[:lock_at_overridden] = opts.key?(:lock_at)
attrs[:unlock_at_overridden] = opts.key?(:unlock_at)
attrs[:set] = override_for if override_for
@override = factory_with_protected_attributes(assignment.assignment_overrides, attrs)
end
def assignment_override_valid_attributes
{ :title => "Some Title" }
end
def create_section_override_for_assignment(assignment_or_quiz, opts={})
opts_with_default = opts.reverse_merge({
due_at: 2.days.from_now,
due_at_overridden: true,
set_type: "CourseSection",
course_section: assignment_or_quiz.context.default_section,
title: "test override",
workflow_state: "active"
})
ao = assignment_or_quiz.assignment_overrides.build
ao.due_at = opts_with_default[:due_at]
ao.due_at_overridden = opts_with_default[:due_at_overridden]
ao.set_type = opts_with_default[:set_type]
ao.set = opts_with_default[:course_section]
ao.title = opts_with_default[:title]
ao.workflow_state = opts_with_default[:workflow_state]
ao.save!
ao
end
alias create_section_override_for_quiz create_section_override_for_assignment
def create_group_override_for_assignment(assignment, opts={})
group_category = group_category(context: assignment.context)
group_opts = opts.merge({context: group_category})
group = opts[:group] || group(group_opts)
group.add_user(opts[:user], 'accepted', opts[:moderator]) if opts[:user]
opts_with_default = opts.reverse_merge({
due_at: 2.days.from_now,
due_at_overridden: true,
set_type: "Group",
group: group,
title: "group override",
workflow_state: "active"
})
ao = assignment.assignment_overrides.build
ao.due_at = opts_with_default[:due_at]
ao.due_at_overridden = opts_with_default[:due_at_overridden]
ao.set_type = opts_with_default[:set_type]
ao.set = opts_with_default[:group]
ao.title = opts_with_default[:title]
ao.workflow_state = opts_with_default[:workflow_state]
ao.save!
ao
end
def create_adhoc_override_for_assignment(assignment_or_quiz, users, opts={})
assignment_override_model(opts.merge(assignment: assignment_or_quiz))
@override.set = nil
@override.set_type = 'ADHOC'
@override.due_at = opts[:due_at]
@override.save!
users = Array.wrap(users)
users.each do |user|
@override_student = @override.assignment_override_students.build
@override_student.user = user
@override_student.save!
end
@override
end
def create_mastery_paths_override_for_assignment(assignment_or_quiz, opts={})
mastery_paths_opts = {
assignment: assignment_or_quiz,
set_type: AssignmentOverride::SET_TYPE_NOOP,
set_id: AssignmentOverride::NOOP_MASTERY_PATHS
}
assignment_override_model(opts.merge(mastery_paths_opts))
end
end
| djbender/canvas-lms | spec/factories/assignment_override_factory.rb | Ruby | agpl-3.0 | 3,841 |
// ┌────────────────────────────────────────────────────────────────────┐ \\
// │ Raphaël 2.1.2 - JavaScript Vector Library │ \\
// ├────────────────────────────────────────────────────────────────────┤ \\
// │ Copyright © 2008-2012 Dmitry Baranovskiy (http://raphaeljs.com) │ \\
// │ Copyright © 2008-2012 Sencha Labs (http://sencha.com) │ \\
// ├────────────────────────────────────────────────────────────────────┤ \\
// │ Licensed under the MIT (http://raphaeljs.com/license.html) license.│ \\
// └────────────────────────────────────────────────────────────────────┘ \\
// Copyright (c) 2013 Adobe Systems Incorporated. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// ┌────────────────────────────────────────────────────────────┐ \\
// │ Eve 0.4.2 - JavaScript Events Library │ \\
// ├────────────────────────────────────────────────────────────┤ \\
// │ Author Dmitry Baranovskiy (http://dmitry.baranovskiy.com/) │ \\
// └────────────────────────────────────────────────────────────┘ \\
(function (glob) {
var version = "0.4.2",
has = "hasOwnProperty",
separator = /[\.\/]/,
wildcard = "*",
fun = function () {},
numsort = function (a, b) {
return a - b;
},
current_event,
stop,
events = {n: {}},
/*\
* eve
[ method ]
* Fires event with given `name`, given scope and other parameters.
> Arguments
- name (string) name of the *event*, dot (`.`) or slash (`/`) separated
- scope (object) context for the event handlers
- varargs (...) the rest of arguments will be sent to event handlers
= (object) array of returned values from the listeners
\*/
eve = function (name, scope) {
name = String(name);
var e = events,
oldstop = stop,
args = Array.prototype.slice.call(arguments, 2),
listeners = eve.listeners(name),
z = 0,
f = false,
l,
indexed = [],
queue = {},
out = [],
ce = current_event,
errors = [];
current_event = name;
stop = 0;
for (var i = 0, ii = listeners.length; i < ii; i++) if ("zIndex" in listeners[i]) {
indexed.push(listeners[i].zIndex);
if (listeners[i].zIndex < 0) {
queue[listeners[i].zIndex] = listeners[i];
}
}
indexed.sort(numsort);
while (indexed[z] < 0) {
l = queue[indexed[z++]];
out.push(l.apply(scope, args));
if (stop) {
stop = oldstop;
return out;
}
}
for (i = 0; i < ii; i++) {
l = listeners[i];
if ("zIndex" in l) {
if (l.zIndex == indexed[z]) {
out.push(l.apply(scope, args));
if (stop) {
break;
}
do {
z++;
l = queue[indexed[z]];
l && out.push(l.apply(scope, args));
if (stop) {
break;
}
} while (l)
} else {
queue[l.zIndex] = l;
}
} else {
out.push(l.apply(scope, args));
if (stop) {
break;
}
}
}
stop = oldstop;
current_event = ce;
return out.length ? out : null;
};
// Undocumented. Debug only.
eve._events = events;
/*\
* eve.listeners
[ method ]
* Internal method which gives you array of all event handlers that will be triggered by the given `name`.
> Arguments
- name (string) name of the event, dot (`.`) or slash (`/`) separated
= (array) array of event handlers
\*/
eve.listeners = function (name) {
var names = name.split(separator),
e = events,
item,
items,
k,
i,
ii,
j,
jj,
nes,
es = [e],
out = [];
for (i = 0, ii = names.length; i < ii; i++) {
nes = [];
for (j = 0, jj = es.length; j < jj; j++) {
e = es[j].n;
items = [e[names[i]], e[wildcard]];
k = 2;
while (k--) {
item = items[k];
if (item) {
nes.push(item);
out = out.concat(item.f || []);
}
}
}
es = nes;
}
return out;
};
/*\
* eve.on
[ method ]
**
* Binds given event handler with a given name. You can use wildcards “`*`” for the names:
| eve.on("*.under.*", f);
| eve("mouse.under.floor"); // triggers f
* Use @eve to trigger the listener.
**
> Arguments
**
- name (string) name of the event, dot (`.`) or slash (`/`) separated, with optional wildcards
- f (function) event handler function
**
= (function) returned function accepts a single numeric parameter that represents z-index of the handler. It is an optional feature and only used when you need to ensure that some subset of handlers will be invoked in a given order, despite of the order of assignment.
> Example:
| eve.on("mouse", eatIt)(2);
| eve.on("mouse", scream);
| eve.on("mouse", catchIt)(1);
* This will ensure that `catchIt()` function will be called before `eatIt()`.
*
* If you want to put your handler before non-indexed handlers, specify a negative value.
* Note: I assume most of the time you don’t need to worry about z-index, but it’s nice to have this feature “just in case”.
\*/
eve.on = function (name, f) {
name = String(name);
if (typeof f != "function") {
return function () {};
}
var names = name.split(separator),
e = events;
for (var i = 0, ii = names.length; i < ii; i++) {
e = e.n;
e = e.hasOwnProperty(names[i]) && e[names[i]] || (e[names[i]] = {n: {}});
}
e.f = e.f || [];
for (i = 0, ii = e.f.length; i < ii; i++) if (e.f[i] == f) {
return fun;
}
e.f.push(f);
return function (zIndex) {
if (+zIndex == +zIndex) {
f.zIndex = +zIndex;
}
};
};
/*\
* eve.f
[ method ]
**
* Returns function that will fire given event with optional arguments.
* Arguments that will be passed to the result function will be also
* concated to the list of final arguments.
| el.onclick = eve.f("click", 1, 2);
| eve.on("click", function (a, b, c) {
| console.log(a, b, c); // 1, 2, [event object]
| });
> Arguments
- event (string) event name
- varargs (…) and any other arguments
= (function) possible event handler function
\*/
eve.f = function (event) {
var attrs = [].slice.call(arguments, 1);
return function () {
eve.apply(null, [event, null].concat(attrs).concat([].slice.call(arguments, 0)));
};
};
/*\
* eve.stop
[ method ]
**
* Is used inside an event handler to stop the event, preventing any subsequent listeners from firing.
\*/
eve.stop = function () {
stop = 1;
};
/*\
* eve.nt
[ method ]
**
* Could be used inside event handler to figure out actual name of the event.
**
> Arguments
**
- subname (string) #optional subname of the event
**
= (string) name of the event, if `subname` is not specified
* or
= (boolean) `true`, if current event’s name contains `subname`
\*/
eve.nt = function (subname) {
if (subname) {
return new RegExp("(?:\\.|\\/|^)" + subname + "(?:\\.|\\/|$)").test(current_event);
}
return current_event;
};
/*\
* eve.nts
[ method ]
**
* Could be used inside event handler to figure out actual name of the event.
**
**
= (array) names of the event
\*/
eve.nts = function () {
return current_event.split(separator);
};
/*\
* eve.off
[ method ]
**
* Removes given function from the list of event listeners assigned to given name.
* If no arguments specified all the events will be cleared.
**
> Arguments
**
- name (string) name of the event, dot (`.`) or slash (`/`) separated, with optional wildcards
- f (function) event handler function
\*/
/*\
* eve.unbind
[ method ]
**
* See @eve.off
\*/
eve.off = eve.unbind = function (name, f) {
if (!name) {
eve._events = events = {n: {}};
return;
}
var names = name.split(separator),
e,
key,
splice,
i, ii, j, jj,
cur = [events];
for (i = 0, ii = names.length; i < ii; i++) {
for (j = 0; j < cur.length; j += splice.length - 2) {
splice = [j, 1];
e = cur[j].n;
if (names[i] != wildcard) {
if (e[names[i]]) {
splice.push(e[names[i]]);
}
} else {
for (key in e) if (e[has](key)) {
splice.push(e[key]);
}
}
cur.splice.apply(cur, splice);
}
}
for (i = 0, ii = cur.length; i < ii; i++) {
e = cur[i];
while (e.n) {
if (f) {
if (e.f) {
for (j = 0, jj = e.f.length; j < jj; j++) if (e.f[j] == f) {
e.f.splice(j, 1);
break;
}
!e.f.length && delete e.f;
}
for (key in e.n) if (e.n[has](key) && e.n[key].f) {
var funcs = e.n[key].f;
for (j = 0, jj = funcs.length; j < jj; j++) if (funcs[j] == f) {
funcs.splice(j, 1);
break;
}
!funcs.length && delete e.n[key].f;
}
} else {
delete e.f;
for (key in e.n) if (e.n[has](key) && e.n[key].f) {
delete e.n[key].f;
}
}
e = e.n;
}
}
};
/*\
* eve.once
[ method ]
**
* Binds given event handler with a given name to only run once then unbind itself.
| eve.once("login", f);
| eve("login"); // triggers f
| eve("login"); // no listeners
* Use @eve to trigger the listener.
**
> Arguments
**
- name (string) name of the event, dot (`.`) or slash (`/`) separated, with optional wildcards
- f (function) event handler function
**
= (function) same return function as @eve.on
\*/
eve.once = function (name, f) {
var f2 = function () {
eve.unbind(name, f2);
return f.apply(this, arguments);
};
return eve.on(name, f2);
};
/*\
* eve.version
[ property (string) ]
**
* Current version of the library.
\*/
eve.version = version;
eve.toString = function () {
return "You are running Eve " + version;
};
(typeof module != "undefined" && module.exports) ? (module.exports = eve) : (typeof define != "undefined" ? (define("eve", [], function() { return eve; })) : (glob.eve = eve));
})(window || this);
// ┌─────────────────────────────────────────────────────────────────────┐ \\
// │ "Raphaël 2.1.2" - JavaScript Vector Library │ \\
// ├─────────────────────────────────────────────────────────────────────┤ \\
// │ Copyright (c) 2008-2011 Dmitry Baranovskiy (http://raphaeljs.com) │ \\
// │ Copyright (c) 2008-2011 Sencha Labs (http://sencha.com) │ \\
// │ Licensed under the MIT (http://raphaeljs.com/license.html) license. │ \\
// └─────────────────────────────────────────────────────────────────────┘ \\
(function (glob, factory) {
// AMD support
if (typeof define === "function" && define.amd) {
// Define as an anonymous module
define(["eve"], function( eve ) {
return factory(glob, eve);
});
} else {
// Browser globals (glob is window)
// Raphael adds itself to window
factory(glob, glob.eve);
}
}(this, function (window, eve) {
/*\
* Raphael
[ method ]
**
* Creates a canvas object on which to draw.
* You must do this first, as all future calls to drawing methods
* from this instance will be bound to this canvas.
> Parameters
**
- container (HTMLElement|string) DOM element or its ID which is going to be a parent for drawing surface
- width (number)
- height (number)
- callback (function) #optional callback function which is going to be executed in the context of newly created paper
* or
- x (number)
- y (number)
- width (number)
- height (number)
- callback (function) #optional callback function which is going to be executed in the context of newly created paper
* or
- all (array) (first 3 or 4 elements in the array are equal to [containerID, width, height] or [x, y, width, height]. The rest are element descriptions in format {type: type, <attributes>}). See @Paper.add.
- callback (function) #optional callback function which is going to be executed in the context of newly created paper
* or
- onReadyCallback (function) function that is going to be called on DOM ready event. You can also subscribe to this event via Eve’s “DOMLoad” event. In this case method returns `undefined`.
= (object) @Paper
> Usage
| // Each of the following examples create a canvas
| // that is 320px wide by 200px high.
| // Canvas is created at the viewport’s 10,50 coordinate.
| var paper = Raphael(10, 50, 320, 200);
| // Canvas is created at the top left corner of the #notepad element
| // (or its top right corner in dir="rtl" elements)
| var paper = Raphael(document.getElementById("notepad"), 320, 200);
| // Same as above
| var paper = Raphael("notepad", 320, 200);
| // Image dump
| var set = Raphael(["notepad", 320, 200, {
| type: "rect",
| x: 10,
| y: 10,
| width: 25,
| height: 25,
| stroke: "#f00"
| }, {
| type: "text",
| x: 30,
| y: 40,
| text: "Dump"
| }]);
\*/
function R(first) {
if (R.is(first, "function")) {
return loaded ? first() : eve.on("raphael.DOMload", first);
} else if (R.is(first, array)) {
return R._engine.create[apply](R, first.splice(0, 3 + R.is(first[0], nu))).add(first);
} else {
var args = Array.prototype.slice.call(arguments, 0);
if (R.is(args[args.length - 1], "function")) {
var f = args.pop();
return loaded ? f.call(R._engine.create[apply](R, args)) : eve.on("raphael.DOMload", function () {
f.call(R._engine.create[apply](R, args));
});
} else {
return R._engine.create[apply](R, arguments);
}
}
}
R.version = "2.1.2";
R.eve = eve;
var loaded,
separator = /[, ]+/,
elements = {circle: 1, rect: 1, path: 1, ellipse: 1, text: 1, image: 1},
formatrg = /\{(\d+)\}/g,
proto = "prototype",
has = "hasOwnProperty",
g = {
doc: document,
win: window
},
oldRaphael = {
was: Object.prototype[has].call(g.win, "Raphael"),
is: g.win.Raphael
},
Paper = function () {
/*\
* Paper.ca
[ property (object) ]
**
* Shortcut for @Paper.customAttributes
\*/
/*\
* Paper.customAttributes
[ property (object) ]
**
* If you have a set of attributes that you would like to represent
* as a function of some number you can do it easily with custom attributes:
> Usage
| paper.customAttributes.hue = function (num) {
| num = num % 1;
| return {fill: "hsb(" + num + ", 0.75, 1)"};
| };
| // Custom attribute “hue” will change fill
| // to be given hue with fixed saturation and brightness.
| // Now you can use it like this:
| var c = paper.circle(10, 10, 10).attr({hue: .45});
| // or even like this:
| c.animate({hue: 1}, 1e3);
|
| // You could also create custom attribute
| // with multiple parameters:
| paper.customAttributes.hsb = function (h, s, b) {
| return {fill: "hsb(" + [h, s, b].join(",") + ")"};
| };
| c.attr({hsb: "0.5 .8 1"});
| c.animate({hsb: [1, 0, 0.5]}, 1e3);
\*/
this.ca = this.customAttributes = {};
},
paperproto,
appendChild = "appendChild",
apply = "apply",
concat = "concat",
supportsTouch = ('ontouchstart' in g.win) || g.win.DocumentTouch && g.doc instanceof DocumentTouch, //taken from Modernizr touch test
E = "",
S = " ",
Str = String,
split = "split",
events = "click dblclick mousedown mousemove mouseout mouseover mouseup touchstart touchmove touchend touchcancel"[split](S),
touchMap = {
mousedown: "touchstart",
mousemove: "touchmove",
mouseup: "touchend"
},
lowerCase = Str.prototype.toLowerCase,
math = Math,
mmax = math.max,
mmin = math.min,
abs = math.abs,
pow = math.pow,
PI = math.PI,
nu = "number",
string = "string",
array = "array",
toString = "toString",
fillString = "fill",
objectToString = Object.prototype.toString,
paper = {},
push = "push",
ISURL = R._ISURL = /^url\(['"]?([^\)]+?)['"]?\)$/i,
colourRegExp = /^\s*((#[a-f\d]{6})|(#[a-f\d]{3})|rgba?\(\s*([\d\.]+%?\s*,\s*[\d\.]+%?\s*,\s*[\d\.]+%?(?:\s*,\s*[\d\.]+%?)?)\s*\)|hsba?\(\s*([\d\.]+(?:deg|\xb0|%)?\s*,\s*[\d\.]+%?\s*,\s*[\d\.]+(?:%?\s*,\s*[\d\.]+)?)%?\s*\)|hsla?\(\s*([\d\.]+(?:deg|\xb0|%)?\s*,\s*[\d\.]+%?\s*,\s*[\d\.]+(?:%?\s*,\s*[\d\.]+)?)%?\s*\))\s*$/i,
isnan = {"NaN": 1, "Infinity": 1, "-Infinity": 1},
bezierrg = /^(?:cubic-)?bezier\(([^,]+),([^,]+),([^,]+),([^\)]+)\)/,
round = math.round,
setAttribute = "setAttribute",
toFloat = parseFloat,
toInt = parseInt,
upperCase = Str.prototype.toUpperCase,
availableAttrs = R._availableAttrs = {
"arrow-end": "none",
"arrow-start": "none",
blur: 0,
"clip-rect": "0 0 1e9 1e9",
cursor: "default",
cx: 0,
cy: 0,
fill: "#fff",
"fill-opacity": 1,
font: '10px "Arial"',
"font-family": '"Arial"',
"font-size": "10",
"font-style": "normal",
"font-weight": 400,
gradient: 0,
height: 0,
href: "http://raphaeljs.com/",
"letter-spacing": 0,
opacity: 1,
path: "M0,0",
r: 0,
rx: 0,
ry: 0,
src: "",
stroke: "#000",
"stroke-dasharray": "",
"stroke-linecap": "butt",
"stroke-linejoin": "butt",
"stroke-miterlimit": 0,
"stroke-opacity": 1,
"stroke-width": 1,
target: "_blank",
"text-anchor": "middle",
title: "Raphael",
transform: "",
width: 0,
x: 0,
y: 0
},
availableAnimAttrs = R._availableAnimAttrs = {
blur: nu,
"clip-rect": "csv",
cx: nu,
cy: nu,
fill: "colour",
"fill-opacity": nu,
"font-size": nu,
height: nu,
opacity: nu,
path: "path",
r: nu,
rx: nu,
ry: nu,
stroke: "colour",
"stroke-opacity": nu,
"stroke-width": nu,
transform: "transform",
width: nu,
x: nu,
y: nu
},
whitespace = /[\x09\x0a\x0b\x0c\x0d\x20\xa0\u1680\u180e\u2000\u2001\u2002\u2003\u2004\u2005\u2006\u2007\u2008\u2009\u200a\u202f\u205f\u3000\u2028\u2029]/g,
commaSpaces = /[\x09\x0a\x0b\x0c\x0d\x20\xa0\u1680\u180e\u2000\u2001\u2002\u2003\u2004\u2005\u2006\u2007\u2008\u2009\u200a\u202f\u205f\u3000\u2028\u2029]*,[\x09\x0a\x0b\x0c\x0d\x20\xa0\u1680\u180e\u2000\u2001\u2002\u2003\u2004\u2005\u2006\u2007\u2008\u2009\u200a\u202f\u205f\u3000\u2028\u2029]*/,
hsrg = {hs: 1, rg: 1},
p2s = /,?([achlmqrstvxz]),?/gi,
pathCommand = /([achlmrqstvz])[\x09\x0a\x0b\x0c\x0d\x20\xa0\u1680\u180e\u2000\u2001\u2002\u2003\u2004\u2005\u2006\u2007\u2008\u2009\u200a\u202f\u205f\u3000\u2028\u2029,]*((-?\d*\.?\d*(?:e[\-+]?\d+)?[\x09\x0a\x0b\x0c\x0d\x20\xa0\u1680\u180e\u2000\u2001\u2002\u2003\u2004\u2005\u2006\u2007\u2008\u2009\u200a\u202f\u205f\u3000\u2028\u2029]*,?[\x09\x0a\x0b\x0c\x0d\x20\xa0\u1680\u180e\u2000\u2001\u2002\u2003\u2004\u2005\u2006\u2007\u2008\u2009\u200a\u202f\u205f\u3000\u2028\u2029]*)+)/ig,
tCommand = /([rstm])[\x09\x0a\x0b\x0c\x0d\x20\xa0\u1680\u180e\u2000\u2001\u2002\u2003\u2004\u2005\u2006\u2007\u2008\u2009\u200a\u202f\u205f\u3000\u2028\u2029,]*((-?\d*\.?\d*(?:e[\-+]?\d+)?[\x09\x0a\x0b\x0c\x0d\x20\xa0\u1680\u180e\u2000\u2001\u2002\u2003\u2004\u2005\u2006\u2007\u2008\u2009\u200a\u202f\u205f\u3000\u2028\u2029]*,?[\x09\x0a\x0b\x0c\x0d\x20\xa0\u1680\u180e\u2000\u2001\u2002\u2003\u2004\u2005\u2006\u2007\u2008\u2009\u200a\u202f\u205f\u3000\u2028\u2029]*)+)/ig,
pathValues = /(-?\d*\.?\d*(?:e[\-+]?\d+)?)[\x09\x0a\x0b\x0c\x0d\x20\xa0\u1680\u180e\u2000\u2001\u2002\u2003\u2004\u2005\u2006\u2007\u2008\u2009\u200a\u202f\u205f\u3000\u2028\u2029]*,?[\x09\x0a\x0b\x0c\x0d\x20\xa0\u1680\u180e\u2000\u2001\u2002\u2003\u2004\u2005\u2006\u2007\u2008\u2009\u200a\u202f\u205f\u3000\u2028\u2029]*/ig,
radial_gradient = R._radial_gradient = /^r(?:\(([^,]+?)[\x09\x0a\x0b\x0c\x0d\x20\xa0\u1680\u180e\u2000\u2001\u2002\u2003\u2004\u2005\u2006\u2007\u2008\u2009\u200a\u202f\u205f\u3000\u2028\u2029]*,[\x09\x0a\x0b\x0c\x0d\x20\xa0\u1680\u180e\u2000\u2001\u2002\u2003\u2004\u2005\u2006\u2007\u2008\u2009\u200a\u202f\u205f\u3000\u2028\u2029]*([^\)]+?)\))?/,
eldata = {},
sortByKey = function (a, b) {
return a.key - b.key;
},
sortByNumber = function (a, b) {
return toFloat(a) - toFloat(b);
},
fun = function () {},
pipe = function (x) {
return x;
},
rectPath = R._rectPath = function (x, y, w, h, r) {
if (r) {
return [["M", x + r, y], ["l", w - r * 2, 0], ["a", r, r, 0, 0, 1, r, r], ["l", 0, h - r * 2], ["a", r, r, 0, 0, 1, -r, r], ["l", r * 2 - w, 0], ["a", r, r, 0, 0, 1, -r, -r], ["l", 0, r * 2 - h], ["a", r, r, 0, 0, 1, r, -r], ["z"]];
}
return [["M", x, y], ["l", w, 0], ["l", 0, h], ["l", -w, 0], ["z"]];
},
ellipsePath = function (x, y, rx, ry) {
if (ry == null) {
ry = rx;
}
return [["M", x, y], ["m", 0, -ry], ["a", rx, ry, 0, 1, 1, 0, 2 * ry], ["a", rx, ry, 0, 1, 1, 0, -2 * ry], ["z"]];
},
getPath = R._getPath = {
path: function (el) {
return el.attr("path");
},
circle: function (el) {
var a = el.attrs;
return ellipsePath(a.cx, a.cy, a.r);
},
ellipse: function (el) {
var a = el.attrs;
return ellipsePath(a.cx, a.cy, a.rx, a.ry);
},
rect: function (el) {
var a = el.attrs;
return rectPath(a.x, a.y, a.width, a.height, a.r);
},
image: function (el) {
var a = el.attrs;
return rectPath(a.x, a.y, a.width, a.height);
},
text: function (el) {
var bbox = el._getBBox();
return rectPath(bbox.x, bbox.y, bbox.width, bbox.height);
},
set : function(el) {
var bbox = el._getBBox();
return rectPath(bbox.x, bbox.y, bbox.width, bbox.height);
}
},
/*\
* Raphael.mapPath
[ method ]
**
* Transform the path string with given matrix.
> Parameters
- path (string) path string
- matrix (object) see @Matrix
= (string) transformed path string
\*/
mapPath = R.mapPath = function (path, matrix) {
if (!matrix) {
return path;
}
var x, y, i, j, ii, jj, pathi;
path = path2curve(path);
for (i = 0, ii = path.length; i < ii; i++) {
pathi = path[i];
for (j = 1, jj = pathi.length; j < jj; j += 2) {
x = matrix.x(pathi[j], pathi[j + 1]);
y = matrix.y(pathi[j], pathi[j + 1]);
pathi[j] = x;
pathi[j + 1] = y;
}
}
return path;
};
R._g = g;
/*\
* Raphael.type
[ property (string) ]
**
* Can be “SVG”, “VML” or empty, depending on browser support.
\*/
R.type = (g.win.SVGAngle || g.doc.implementation.hasFeature("http://www.w3.org/TR/SVG11/feature#BasicStructure", "1.1") ? "SVG" : "VML");
if (R.type == "VML") {
var d = g.doc.createElement("div"),
b;
d.innerHTML = '<v:shape adj="1"/>';
b = d.firstChild;
b.style.behavior = "url(#default#VML)";
if (!(b && typeof b.adj == "object")) {
return (R.type = E);
}
d = null;
}
/*\
* Raphael.svg
[ property (boolean) ]
**
* `true` if browser supports SVG.
\*/
/*\
* Raphael.vml
[ property (boolean) ]
**
* `true` if browser supports VML.
\*/
R.svg = !(R.vml = R.type == "VML");
R._Paper = Paper;
/*\
* Raphael.fn
[ property (object) ]
**
* You can add your own method to the canvas. For example if you want to draw a pie chart,
* you can create your own pie chart function and ship it as a Raphaël plugin. To do this
* you need to extend the `Raphael.fn` object. You should modify the `fn` object before a
* Raphaël instance is created, otherwise it will take no effect. Please note that the
* ability for namespaced plugins was removed in Raphael 2.0. It is up to the plugin to
* ensure any namespacing ensures proper context.
> Usage
| Raphael.fn.arrow = function (x1, y1, x2, y2, size) {
| return this.path( ... );
| };
| // or create namespace
| Raphael.fn.mystuff = {
| arrow: function () {…},
| star: function () {…},
| // etc…
| };
| var paper = Raphael(10, 10, 630, 480);
| // then use it
| paper.arrow(10, 10, 30, 30, 5).attr({fill: "#f00"});
| paper.mystuff.arrow();
| paper.mystuff.star();
\*/
R.fn = paperproto = Paper.prototype = R.prototype;
R._id = 0;
R._oid = 0;
/*\
* Raphael.is
[ method ]
**
* Handfull replacement for `typeof` operator.
> Parameters
- o (…) any object or primitive
- type (string) name of the type, i.e. “string”, “function”, “number”, etc.
= (boolean) is given value is of given type
\*/
R.is = function (o, type) {
type = lowerCase.call(type);
if (type == "finite") {
return !isnan[has](+o);
}
if (type == "array") {
return o instanceof Array;
}
return (type == "null" && o === null) ||
(type == typeof o && o !== null) ||
(type == "object" && o === Object(o)) ||
(type == "array" && Array.isArray && Array.isArray(o)) ||
objectToString.call(o).slice(8, -1).toLowerCase() == type;
};
function clone(obj) {
if (typeof obj == "function" || Object(obj) !== obj) {
return obj;
}
var res = new obj.constructor;
for (var key in obj) if (obj[has](key)) {
res[key] = clone(obj[key]);
}
return res;
}
/*\
* Raphael.angle
[ method ]
**
* Returns angle between two or three points
> Parameters
- x1 (number) x coord of first point
- y1 (number) y coord of first point
- x2 (number) x coord of second point
- y2 (number) y coord of second point
- x3 (number) #optional x coord of third point
- y3 (number) #optional y coord of third point
= (number) angle in degrees.
\*/
R.angle = function (x1, y1, x2, y2, x3, y3) {
if (x3 == null) {
var x = x1 - x2,
y = y1 - y2;
if (!x && !y) {
return 0;
}
return (180 + math.atan2(-y, -x) * 180 / PI + 360) % 360;
} else {
return R.angle(x1, y1, x3, y3) - R.angle(x2, y2, x3, y3);
}
};
/*\
* Raphael.rad
[ method ]
**
* Transform angle to radians
> Parameters
- deg (number) angle in degrees
= (number) angle in radians.
\*/
R.rad = function (deg) {
return deg % 360 * PI / 180;
};
/*\
* Raphael.deg
[ method ]
**
* Transform angle to degrees
> Parameters
- deg (number) angle in radians
= (number) angle in degrees.
\*/
R.deg = function (rad) {
return rad * 180 / PI % 360;
};
/*\
* Raphael.snapTo
[ method ]
**
* Snaps given value to given grid.
> Parameters
- values (array|number) given array of values or step of the grid
- value (number) value to adjust
- tolerance (number) #optional tolerance for snapping. Default is `10`.
= (number) adjusted value.
\*/
R.snapTo = function (values, value, tolerance) {
tolerance = R.is(tolerance, "finite") ? tolerance : 10;
if (R.is(values, array)) {
var i = values.length;
while (i--) if (abs(values[i] - value) <= tolerance) {
return values[i];
}
} else {
values = +values;
var rem = value % values;
if (rem < tolerance) {
return value - rem;
}
if (rem > values - tolerance) {
return value - rem + values;
}
}
return value;
};
/*\
* Raphael.createUUID
[ method ]
**
* Returns RFC4122, version 4 ID
\*/
var createUUID = R.createUUID = (function (uuidRegEx, uuidReplacer) {
return function () {
return "xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(uuidRegEx, uuidReplacer).toUpperCase();
};
})(/[xy]/g, function (c) {
var r = math.random() * 16 | 0,
v = c == "x" ? r : (r & 3 | 8);
return v.toString(16);
});
/*\
* Raphael.setWindow
[ method ]
**
* Used when you need to draw in `<iframe>`. Switched window to the iframe one.
> Parameters
- newwin (window) new window object
\*/
R.setWindow = function (newwin) {
eve("raphael.setWindow", R, g.win, newwin);
g.win = newwin;
g.doc = g.win.document;
if (R._engine.initWin) {
R._engine.initWin(g.win);
}
};
var toHex = function (color) {
if (R.vml) {
// http://dean.edwards.name/weblog/2009/10/convert-any-colour-value-to-hex-in-msie/
var trim = /^\s+|\s+$/g;
var bod;
try {
var docum = new ActiveXObject("htmlfile");
docum.write("<body>");
docum.close();
bod = docum.body;
} catch(e) {
bod = createPopup().document.body;
}
var range = bod.createTextRange();
toHex = cacher(function (color) {
try {
bod.style.color = Str(color).replace(trim, E);
var value = range.queryCommandValue("ForeColor");
value = ((value & 255) << 16) | (value & 65280) | ((value & 16711680) >>> 16);
return "#" + ("000000" + value.toString(16)).slice(-6);
} catch(e) {
return "none";
}
});
} else {
var i = g.doc.createElement("i");
i.title = "Rapha\xebl Colour Picker";
i.style.display = "none";
g.doc.body.appendChild(i);
toHex = cacher(function (color) {
i.style.color = color;
return g.doc.defaultView.getComputedStyle(i, E).getPropertyValue("color");
});
}
return toHex(color);
},
hsbtoString = function () {
return "hsb(" + [this.h, this.s, this.b] + ")";
},
hsltoString = function () {
return "hsl(" + [this.h, this.s, this.l] + ")";
},
rgbtoString = function () {
return this.hex;
},
prepareRGB = function (r, g, b) {
if (g == null && R.is(r, "object") && "r" in r && "g" in r && "b" in r) {
b = r.b;
g = r.g;
r = r.r;
}
if (g == null && R.is(r, string)) {
var clr = R.getRGB(r);
r = clr.r;
g = clr.g;
b = clr.b;
}
if (r > 1 || g > 1 || b > 1) {
r /= 255;
g /= 255;
b /= 255;
}
return [r, g, b];
},
packageRGB = function (r, g, b, o) {
r *= 255;
g *= 255;
b *= 255;
var rgb = {
r: r,
g: g,
b: b,
hex: R.rgb(r, g, b),
toString: rgbtoString
};
R.is(o, "finite") && (rgb.opacity = o);
return rgb;
};
/*\
* Raphael.color
[ method ]
**
* Parses the color string and returns object with all values for the given color.
> Parameters
- clr (string) color string in one of the supported formats (see @Raphael.getRGB)
= (object) Combined RGB & HSB object in format:
o {
o r (number) red,
o g (number) green,
o b (number) blue,
o hex (string) color in HTML/CSS format: #••••••,
o error (boolean) `true` if string can’t be parsed,
o h (number) hue,
o s (number) saturation,
o v (number) value (brightness),
o l (number) lightness
o }
\*/
R.color = function (clr) {
var rgb;
if (R.is(clr, "object") && "h" in clr && "s" in clr && "b" in clr) {
rgb = R.hsb2rgb(clr);
clr.r = rgb.r;
clr.g = rgb.g;
clr.b = rgb.b;
clr.hex = rgb.hex;
} else if (R.is(clr, "object") && "h" in clr && "s" in clr && "l" in clr) {
rgb = R.hsl2rgb(clr);
clr.r = rgb.r;
clr.g = rgb.g;
clr.b = rgb.b;
clr.hex = rgb.hex;
} else {
if (R.is(clr, "string")) {
clr = R.getRGB(clr);
}
if (R.is(clr, "object") && "r" in clr && "g" in clr && "b" in clr) {
rgb = R.rgb2hsl(clr);
clr.h = rgb.h;
clr.s = rgb.s;
clr.l = rgb.l;
rgb = R.rgb2hsb(clr);
clr.v = rgb.b;
} else {
clr = {hex: "none"};
clr.r = clr.g = clr.b = clr.h = clr.s = clr.v = clr.l = -1;
}
}
clr.toString = rgbtoString;
return clr;
};
/*\
* Raphael.hsb2rgb
[ method ]
**
* Converts HSB values to RGB object.
> Parameters
- h (number) hue
- s (number) saturation
- v (number) value or brightness
= (object) RGB object in format:
o {
o r (number) red,
o g (number) green,
o b (number) blue,
o hex (string) color in HTML/CSS format: #••••••
o }
\*/
R.hsb2rgb = function (h, s, v, o) {
if (this.is(h, "object") && "h" in h && "s" in h && "b" in h) {
v = h.b;
s = h.s;
h = h.h;
o = h.o;
}
h *= 360;
var R, G, B, X, C;
h = (h % 360) / 60;
C = v * s;
X = C * (1 - abs(h % 2 - 1));
R = G = B = v - C;
h = ~~h;
R += [C, X, 0, 0, X, C][h];
G += [X, C, C, X, 0, 0][h];
B += [0, 0, X, C, C, X][h];
return packageRGB(R, G, B, o);
};
/*\
* Raphael.hsl2rgb
[ method ]
**
* Converts HSL values to RGB object.
> Parameters
- h (number) hue
- s (number) saturation
- l (number) luminosity
= (object) RGB object in format:
o {
o r (number) red,
o g (number) green,
o b (number) blue,
o hex (string) color in HTML/CSS format: #••••••
o }
\*/
R.hsl2rgb = function (h, s, l, o) {
if (this.is(h, "object") && "h" in h && "s" in h && "l" in h) {
l = h.l;
s = h.s;
h = h.h;
}
if (h > 1 || s > 1 || l > 1) {
h /= 360;
s /= 100;
l /= 100;
}
h *= 360;
var R, G, B, X, C;
h = (h % 360) / 60;
C = 2 * s * (l < .5 ? l : 1 - l);
X = C * (1 - abs(h % 2 - 1));
R = G = B = l - C / 2;
h = ~~h;
R += [C, X, 0, 0, X, C][h];
G += [X, C, C, X, 0, 0][h];
B += [0, 0, X, C, C, X][h];
return packageRGB(R, G, B, o);
};
/*\
* Raphael.rgb2hsb
[ method ]
**
* Converts RGB values to HSB object.
> Parameters
- r (number) red
- g (number) green
- b (number) blue
= (object) HSB object in format:
o {
o h (number) hue
o s (number) saturation
o b (number) brightness
o }
\*/
R.rgb2hsb = function (r, g, b) {
b = prepareRGB(r, g, b);
r = b[0];
g = b[1];
b = b[2];
var H, S, V, C;
V = mmax(r, g, b);
C = V - mmin(r, g, b);
H = (C == 0 ? null :
V == r ? (g - b) / C :
V == g ? (b - r) / C + 2 :
(r - g) / C + 4
);
H = ((H + 360) % 6) * 60 / 360;
S = C == 0 ? 0 : C / V;
return {h: H, s: S, b: V, toString: hsbtoString};
};
/*\
* Raphael.rgb2hsl
[ method ]
**
* Converts RGB values to HSL object.
> Parameters
- r (number) red
- g (number) green
- b (number) blue
= (object) HSL object in format:
o {
o h (number) hue
o s (number) saturation
o l (number) luminosity
o }
\*/
R.rgb2hsl = function (r, g, b) {
b = prepareRGB(r, g, b);
r = b[0];
g = b[1];
b = b[2];
var H, S, L, M, m, C;
M = mmax(r, g, b);
m = mmin(r, g, b);
C = M - m;
H = (C == 0 ? null :
M == r ? (g - b) / C :
M == g ? (b - r) / C + 2 :
(r - g) / C + 4);
H = ((H + 360) % 6) * 60 / 360;
L = (M + m) / 2;
S = (C == 0 ? 0 :
L < .5 ? C / (2 * L) :
C / (2 - 2 * L));
return {h: H, s: S, l: L, toString: hsltoString};
};
R._path2string = function () {
return this.join(",").replace(p2s, "$1");
};
function repush(array, item) {
for (var i = 0, ii = array.length; i < ii; i++) if (array[i] === item) {
return array.push(array.splice(i, 1)[0]);
}
}
function cacher(f, scope, postprocessor) {
function newf() {
var arg = Array.prototype.slice.call(arguments, 0),
args = arg.join("\u2400"),
cache = newf.cache = newf.cache || {},
count = newf.count = newf.count || [];
if (cache[has](args)) {
repush(count, args);
return postprocessor ? postprocessor(cache[args]) : cache[args];
}
count.length >= 1e3 && delete cache[count.shift()];
count.push(args);
cache[args] = f[apply](scope, arg);
return postprocessor ? postprocessor(cache[args]) : cache[args];
}
return newf;
}
var preload = R._preload = function (src, f) {
var img = g.doc.createElement("img");
img.style.cssText = "position:absolute;left:-9999em;top:-9999em";
img.onload = function () {
f.call(this);
this.onload = null;
g.doc.body.removeChild(this);
};
img.onerror = function () {
g.doc.body.removeChild(this);
};
g.doc.body.appendChild(img);
img.src = src;
};
function clrToString() {
return this.hex;
}
/*\
* Raphael.getRGB
[ method ]
**
* Parses colour string as RGB object
> Parameters
- colour (string) colour string in one of formats:
# <ul>
# <li>Colour name (“<code>red</code>”, “<code>green</code>”, “<code>cornflowerblue</code>”, etc)</li>
# <li>#••• — shortened HTML colour: (“<code>#000</code>”, “<code>#fc0</code>”, etc)</li>
# <li>#•••••• — full length HTML colour: (“<code>#000000</code>”, “<code>#bd2300</code>”)</li>
# <li>rgb(•••, •••, •••) — red, green and blue channels’ values: (“<code>rgb(200, 100, 0)</code>”)</li>
# <li>rgb(•••%, •••%, •••%) — same as above, but in %: (“<code>rgb(100%, 175%, 0%)</code>”)</li>
# <li>hsb(•••, •••, •••) — hue, saturation and brightness values: (“<code>hsb(0.5, 0.25, 1)</code>”)</li>
# <li>hsb(•••%, •••%, •••%) — same as above, but in %</li>
# <li>hsl(•••, •••, •••) — same as hsb</li>
# <li>hsl(•••%, •••%, •••%) — same as hsb</li>
# </ul>
= (object) RGB object in format:
o {
o r (number) red,
o g (number) green,
o b (number) blue
o hex (string) color in HTML/CSS format: #••••••,
o error (boolean) true if string can’t be parsed
o }
\*/
R.getRGB = cacher(function (colour) {
if (!colour || !!((colour = Str(colour)).indexOf("-") + 1)) {
return {r: -1, g: -1, b: -1, hex: "none", error: 1, toString: clrToString};
}
if (colour == "none") {
return {r: -1, g: -1, b: -1, hex: "none", toString: clrToString};
}
!(hsrg[has](colour.toLowerCase().substring(0, 2)) || colour.charAt() == "#") && (colour = toHex(colour));
var res,
red,
green,
blue,
opacity,
t,
values,
rgb = colour.match(colourRegExp);
if (rgb) {
if (rgb[2]) {
blue = toInt(rgb[2].substring(5), 16);
green = toInt(rgb[2].substring(3, 5), 16);
red = toInt(rgb[2].substring(1, 3), 16);
}
if (rgb[3]) {
blue = toInt((t = rgb[3].charAt(3)) + t, 16);
green = toInt((t = rgb[3].charAt(2)) + t, 16);
red = toInt((t = rgb[3].charAt(1)) + t, 16);
}
if (rgb[4]) {
values = rgb[4][split](commaSpaces);
red = toFloat(values[0]);
values[0].slice(-1) == "%" && (red *= 2.55);
green = toFloat(values[1]);
values[1].slice(-1) == "%" && (green *= 2.55);
blue = toFloat(values[2]);
values[2].slice(-1) == "%" && (blue *= 2.55);
rgb[1].toLowerCase().slice(0, 4) == "rgba" && (opacity = toFloat(values[3]));
values[3] && values[3].slice(-1) == "%" && (opacity /= 100);
}
if (rgb[5]) {
values = rgb[5][split](commaSpaces);
red = toFloat(values[0]);
values[0].slice(-1) == "%" && (red *= 2.55);
green = toFloat(values[1]);
values[1].slice(-1) == "%" && (green *= 2.55);
blue = toFloat(values[2]);
values[2].slice(-1) == "%" && (blue *= 2.55);
(values[0].slice(-3) == "deg" || values[0].slice(-1) == "\xb0") && (red /= 360);
rgb[1].toLowerCase().slice(0, 4) == "hsba" && (opacity = toFloat(values[3]));
values[3] && values[3].slice(-1) == "%" && (opacity /= 100);
return R.hsb2rgb(red, green, blue, opacity);
}
if (rgb[6]) {
values = rgb[6][split](commaSpaces);
red = toFloat(values[0]);
values[0].slice(-1) == "%" && (red *= 2.55);
green = toFloat(values[1]);
values[1].slice(-1) == "%" && (green *= 2.55);
blue = toFloat(values[2]);
values[2].slice(-1) == "%" && (blue *= 2.55);
(values[0].slice(-3) == "deg" || values[0].slice(-1) == "\xb0") && (red /= 360);
rgb[1].toLowerCase().slice(0, 4) == "hsla" && (opacity = toFloat(values[3]));
values[3] && values[3].slice(-1) == "%" && (opacity /= 100);
return R.hsl2rgb(red, green, blue, opacity);
}
rgb = {r: red, g: green, b: blue, toString: clrToString};
rgb.hex = "#" + (16777216 | blue | (green << 8) | (red << 16)).toString(16).slice(1);
R.is(opacity, "finite") && (rgb.opacity = opacity);
return rgb;
}
return {r: -1, g: -1, b: -1, hex: "none", error: 1, toString: clrToString};
}, R);
/*\
* Raphael.hsb
[ method ]
**
* Converts HSB values to hex representation of the colour.
> Parameters
- h (number) hue
- s (number) saturation
- b (number) value or brightness
= (string) hex representation of the colour.
\*/
R.hsb = cacher(function (h, s, b) {
return R.hsb2rgb(h, s, b).hex;
});
/*\
* Raphael.hsl
[ method ]
**
* Converts HSL values to hex representation of the colour.
> Parameters
- h (number) hue
- s (number) saturation
- l (number) luminosity
= (string) hex representation of the colour.
\*/
R.hsl = cacher(function (h, s, l) {
return R.hsl2rgb(h, s, l).hex;
});
/*\
* Raphael.rgb
[ method ]
**
* Converts RGB values to hex representation of the colour.
> Parameters
- r (number) red
- g (number) green
- b (number) blue
= (string) hex representation of the colour.
\*/
R.rgb = cacher(function (r, g, b) {
return "#" + (16777216 | b | (g << 8) | (r << 16)).toString(16).slice(1);
});
/*\
* Raphael.getColor
[ method ]
**
* On each call returns next colour in the spectrum. To reset it back to red call @Raphael.getColor.reset
> Parameters
- value (number) #optional brightness, default is `0.75`
= (string) hex representation of the colour.
\*/
R.getColor = function (value) {
var start = this.getColor.start = this.getColor.start || {h: 0, s: 1, b: value || .75},
rgb = this.hsb2rgb(start.h, start.s, start.b);
start.h += .075;
if (start.h > 1) {
start.h = 0;
start.s -= .2;
start.s <= 0 && (this.getColor.start = {h: 0, s: 1, b: start.b});
}
return rgb.hex;
};
/*\
* Raphael.getColor.reset
[ method ]
**
* Resets spectrum position for @Raphael.getColor back to red.
\*/
R.getColor.reset = function () {
delete this.start;
};
// http://schepers.cc/getting-to-the-point
function catmullRom2bezier(crp, z) {
var d = [];
for (var i = 0, iLen = crp.length; iLen - 2 * !z > i; i += 2) {
var p = [
{x: +crp[i - 2], y: +crp[i - 1]},
{x: +crp[i], y: +crp[i + 1]},
{x: +crp[i + 2], y: +crp[i + 3]},
{x: +crp[i + 4], y: +crp[i + 5]}
];
if (z) {
if (!i) {
p[0] = {x: +crp[iLen - 2], y: +crp[iLen - 1]};
} else if (iLen - 4 == i) {
p[3] = {x: +crp[0], y: +crp[1]};
} else if (iLen - 2 == i) {
p[2] = {x: +crp[0], y: +crp[1]};
p[3] = {x: +crp[2], y: +crp[3]};
}
} else {
if (iLen - 4 == i) {
p[3] = p[2];
} else if (!i) {
p[0] = {x: +crp[i], y: +crp[i + 1]};
}
}
d.push(["C",
(-p[0].x + 6 * p[1].x + p[2].x) / 6,
(-p[0].y + 6 * p[1].y + p[2].y) / 6,
(p[1].x + 6 * p[2].x - p[3].x) / 6,
(p[1].y + 6*p[2].y - p[3].y) / 6,
p[2].x,
p[2].y
]);
}
return d;
}
/*\
* Raphael.parsePathString
[ method ]
**
* Utility method
**
* Parses given path string into an array of arrays of path segments.
> Parameters
- pathString (string|array) path string or array of segments (in the last case it will be returned straight away)
= (array) array of segments.
\*/
R.parsePathString = function (pathString) {
if (!pathString) {
return null;
}
var pth = paths(pathString);
if (pth.arr) {
return pathClone(pth.arr);
}
var paramCounts = {a: 7, c: 6, h: 1, l: 2, m: 2, r: 4, q: 4, s: 4, t: 2, v: 1, z: 0},
data = [];
if (R.is(pathString, array) && R.is(pathString[0], array)) { // rough assumption
data = pathClone(pathString);
}
if (!data.length) {
Str(pathString).replace(pathCommand, function (a, b, c) {
var params = [],
name = b.toLowerCase();
c.replace(pathValues, function (a, b) {
b && params.push(+b);
});
if (name == "m" && params.length > 2) {
data.push([b][concat](params.splice(0, 2)));
name = "l";
b = b == "m" ? "l" : "L";
}
if (name == "r") {
data.push([b][concat](params));
} else while (params.length >= paramCounts[name]) {
data.push([b][concat](params.splice(0, paramCounts[name])));
if (!paramCounts[name]) {
break;
}
}
});
}
data.toString = R._path2string;
pth.arr = pathClone(data);
return data;
};
/*\
* Raphael.parseTransformString
[ method ]
**
* Utility method
**
* Parses given path string into an array of transformations.
> Parameters
- TString (string|array) transform string or array of transformations (in the last case it will be returned straight away)
= (array) array of transformations.
\*/
R.parseTransformString = cacher(function (TString) {
if (!TString) {
return null;
}
var paramCounts = {r: 3, s: 4, t: 2, m: 6},
data = [];
if (R.is(TString, array) && R.is(TString[0], array)) { // rough assumption
data = pathClone(TString);
}
if (!data.length) {
Str(TString).replace(tCommand, function (a, b, c) {
var params = [],
name = lowerCase.call(b);
c.replace(pathValues, function (a, b) {
b && params.push(+b);
});
data.push([b][concat](params));
});
}
data.toString = R._path2string;
return data;
});
// PATHS
var paths = function (ps) {
var p = paths.ps = paths.ps || {};
if (p[ps]) {
p[ps].sleep = 100;
} else {
p[ps] = {
sleep: 100
};
}
setTimeout(function () {
for (var key in p) if (p[has](key) && key != ps) {
p[key].sleep--;
!p[key].sleep && delete p[key];
}
});
return p[ps];
};
/*\
* Raphael.findDotsAtSegment
[ method ]
**
* Utility method
**
* Find dot coordinates on the given cubic bezier curve at the given t.
> Parameters
- p1x (number) x of the first point of the curve
- p1y (number) y of the first point of the curve
- c1x (number) x of the first anchor of the curve
- c1y (number) y of the first anchor of the curve
- c2x (number) x of the second anchor of the curve
- c2y (number) y of the second anchor of the curve
- p2x (number) x of the second point of the curve
- p2y (number) y of the second point of the curve
- t (number) position on the curve (0..1)
= (object) point information in format:
o {
o x: (number) x coordinate of the point
o y: (number) y coordinate of the point
o m: {
o x: (number) x coordinate of the left anchor
o y: (number) y coordinate of the left anchor
o }
o n: {
o x: (number) x coordinate of the right anchor
o y: (number) y coordinate of the right anchor
o }
o start: {
o x: (number) x coordinate of the start of the curve
o y: (number) y coordinate of the start of the curve
o }
o end: {
o x: (number) x coordinate of the end of the curve
o y: (number) y coordinate of the end of the curve
o }
o alpha: (number) angle of the curve derivative at the point
o }
\*/
R.findDotsAtSegment = function (p1x, p1y, c1x, c1y, c2x, c2y, p2x, p2y, t) {
var t1 = 1 - t,
t13 = pow(t1, 3),
t12 = pow(t1, 2),
t2 = t * t,
t3 = t2 * t,
x = t13 * p1x + t12 * 3 * t * c1x + t1 * 3 * t * t * c2x + t3 * p2x,
y = t13 * p1y + t12 * 3 * t * c1y + t1 * 3 * t * t * c2y + t3 * p2y,
mx = p1x + 2 * t * (c1x - p1x) + t2 * (c2x - 2 * c1x + p1x),
my = p1y + 2 * t * (c1y - p1y) + t2 * (c2y - 2 * c1y + p1y),
nx = c1x + 2 * t * (c2x - c1x) + t2 * (p2x - 2 * c2x + c1x),
ny = c1y + 2 * t * (c2y - c1y) + t2 * (p2y - 2 * c2y + c1y),
ax = t1 * p1x + t * c1x,
ay = t1 * p1y + t * c1y,
cx = t1 * c2x + t * p2x,
cy = t1 * c2y + t * p2y,
alpha = (90 - math.atan2(mx - nx, my - ny) * 180 / PI);
(mx > nx || my < ny) && (alpha += 180);
return {
x: x,
y: y,
m: {x: mx, y: my},
n: {x: nx, y: ny},
start: {x: ax, y: ay},
end: {x: cx, y: cy},
alpha: alpha
};
};
/*\
* Raphael.bezierBBox
[ method ]
**
* Utility method
**
* Return bounding box of a given cubic bezier curve
> Parameters
- p1x (number) x of the first point of the curve
- p1y (number) y of the first point of the curve
- c1x (number) x of the first anchor of the curve
- c1y (number) y of the first anchor of the curve
- c2x (number) x of the second anchor of the curve
- c2y (number) y of the second anchor of the curve
- p2x (number) x of the second point of the curve
- p2y (number) y of the second point of the curve
* or
- bez (array) array of six points for bezier curve
= (object) point information in format:
o {
o min: {
o x: (number) x coordinate of the left point
o y: (number) y coordinate of the top point
o }
o max: {
o x: (number) x coordinate of the right point
o y: (number) y coordinate of the bottom point
o }
o }
\*/
R.bezierBBox = function (p1x, p1y, c1x, c1y, c2x, c2y, p2x, p2y) {
if (!R.is(p1x, "array")) {
p1x = [p1x, p1y, c1x, c1y, c2x, c2y, p2x, p2y];
}
var bbox = curveDim.apply(null, p1x);
return {
x: bbox.min.x,
y: bbox.min.y,
x2: bbox.max.x,
y2: bbox.max.y,
width: bbox.max.x - bbox.min.x,
height: bbox.max.y - bbox.min.y
};
};
/*\
* Raphael.isPointInsideBBox
[ method ]
**
* Utility method
**
* Returns `true` if given point is inside bounding boxes.
> Parameters
- bbox (string) bounding box
- x (string) x coordinate of the point
- y (string) y coordinate of the point
= (boolean) `true` if point inside
\*/
R.isPointInsideBBox = function (bbox, x, y) {
return x >= bbox.x && x <= bbox.x2 && y >= bbox.y && y <= bbox.y2;
};
/*\
* Raphael.isBBoxIntersect
[ method ]
**
* Utility method
**
* Returns `true` if two bounding boxes intersect
> Parameters
- bbox1 (string) first bounding box
- bbox2 (string) second bounding box
= (boolean) `true` if they intersect
\*/
R.isBBoxIntersect = function (bbox1, bbox2) {
var i = R.isPointInsideBBox;
return i(bbox2, bbox1.x, bbox1.y)
|| i(bbox2, bbox1.x2, bbox1.y)
|| i(bbox2, bbox1.x, bbox1.y2)
|| i(bbox2, bbox1.x2, bbox1.y2)
|| i(bbox1, bbox2.x, bbox2.y)
|| i(bbox1, bbox2.x2, bbox2.y)
|| i(bbox1, bbox2.x, bbox2.y2)
|| i(bbox1, bbox2.x2, bbox2.y2)
|| (bbox1.x < bbox2.x2 && bbox1.x > bbox2.x || bbox2.x < bbox1.x2 && bbox2.x > bbox1.x)
&& (bbox1.y < bbox2.y2 && bbox1.y > bbox2.y || bbox2.y < bbox1.y2 && bbox2.y > bbox1.y);
};
function base3(t, p1, p2, p3, p4) {
var t1 = -3 * p1 + 9 * p2 - 9 * p3 + 3 * p4,
t2 = t * t1 + 6 * p1 - 12 * p2 + 6 * p3;
return t * t2 - 3 * p1 + 3 * p2;
}
function bezlen(x1, y1, x2, y2, x3, y3, x4, y4, z) {
if (z == null) {
z = 1;
}
z = z > 1 ? 1 : z < 0 ? 0 : z;
var z2 = z / 2,
n = 12,
Tvalues = [-0.1252,0.1252,-0.3678,0.3678,-0.5873,0.5873,-0.7699,0.7699,-0.9041,0.9041,-0.9816,0.9816],
Cvalues = [0.2491,0.2491,0.2335,0.2335,0.2032,0.2032,0.1601,0.1601,0.1069,0.1069,0.0472,0.0472],
sum = 0;
for (var i = 0; i < n; i++) {
var ct = z2 * Tvalues[i] + z2,
xbase = base3(ct, x1, x2, x3, x4),
ybase = base3(ct, y1, y2, y3, y4),
comb = xbase * xbase + ybase * ybase;
sum += Cvalues[i] * math.sqrt(comb);
}
return z2 * sum;
}
function getTatLen(x1, y1, x2, y2, x3, y3, x4, y4, ll) {
if (ll < 0 || bezlen(x1, y1, x2, y2, x3, y3, x4, y4) < ll) {
return;
}
var t = 1,
step = t / 2,
t2 = t - step,
l,
e = .01;
l = bezlen(x1, y1, x2, y2, x3, y3, x4, y4, t2);
while (abs(l - ll) > e) {
step /= 2;
t2 += (l < ll ? 1 : -1) * step;
l = bezlen(x1, y1, x2, y2, x3, y3, x4, y4, t2);
}
return t2;
}
function intersect(x1, y1, x2, y2, x3, y3, x4, y4) {
if (
mmax(x1, x2) < mmin(x3, x4) ||
mmin(x1, x2) > mmax(x3, x4) ||
mmax(y1, y2) < mmin(y3, y4) ||
mmin(y1, y2) > mmax(y3, y4)
) {
return;
}
var nx = (x1 * y2 - y1 * x2) * (x3 - x4) - (x1 - x2) * (x3 * y4 - y3 * x4),
ny = (x1 * y2 - y1 * x2) * (y3 - y4) - (y1 - y2) * (x3 * y4 - y3 * x4),
denominator = (x1 - x2) * (y3 - y4) - (y1 - y2) * (x3 - x4);
if (!denominator) {
return;
}
var px = nx / denominator,
py = ny / denominator,
px2 = +px.toFixed(2),
py2 = +py.toFixed(2);
if (
px2 < +mmin(x1, x2).toFixed(2) ||
px2 > +mmax(x1, x2).toFixed(2) ||
px2 < +mmin(x3, x4).toFixed(2) ||
px2 > +mmax(x3, x4).toFixed(2) ||
py2 < +mmin(y1, y2).toFixed(2) ||
py2 > +mmax(y1, y2).toFixed(2) ||
py2 < +mmin(y3, y4).toFixed(2) ||
py2 > +mmax(y3, y4).toFixed(2)
) {
return;
}
return {x: px, y: py};
}
function inter(bez1, bez2) {
return interHelper(bez1, bez2);
}
function interCount(bez1, bez2) {
return interHelper(bez1, bez2, 1);
}
function interHelper(bez1, bez2, justCount) {
var bbox1 = R.bezierBBox(bez1),
bbox2 = R.bezierBBox(bez2);
if (!R.isBBoxIntersect(bbox1, bbox2)) {
return justCount ? 0 : [];
}
var l1 = bezlen.apply(0, bez1),
l2 = bezlen.apply(0, bez2),
n1 = mmax(~~(l1 / 5), 1),
n2 = mmax(~~(l2 / 5), 1),
dots1 = [],
dots2 = [],
xy = {},
res = justCount ? 0 : [];
for (var i = 0; i < n1 + 1; i++) {
var p = R.findDotsAtSegment.apply(R, bez1.concat(i / n1));
dots1.push({x: p.x, y: p.y, t: i / n1});
}
for (i = 0; i < n2 + 1; i++) {
p = R.findDotsAtSegment.apply(R, bez2.concat(i / n2));
dots2.push({x: p.x, y: p.y, t: i / n2});
}
for (i = 0; i < n1; i++) {
for (var j = 0; j < n2; j++) {
var di = dots1[i],
di1 = dots1[i + 1],
dj = dots2[j],
dj1 = dots2[j + 1],
ci = abs(di1.x - di.x) < .001 ? "y" : "x",
cj = abs(dj1.x - dj.x) < .001 ? "y" : "x",
is = intersect(di.x, di.y, di1.x, di1.y, dj.x, dj.y, dj1.x, dj1.y);
if (is) {
if (xy[is.x.toFixed(4)] == is.y.toFixed(4)) {
continue;
}
xy[is.x.toFixed(4)] = is.y.toFixed(4);
var t1 = di.t + abs((is[ci] - di[ci]) / (di1[ci] - di[ci])) * (di1.t - di.t),
t2 = dj.t + abs((is[cj] - dj[cj]) / (dj1[cj] - dj[cj])) * (dj1.t - dj.t);
if (t1 >= 0 && t1 <= 1.001 && t2 >= 0 && t2 <= 1.001) {
if (justCount) {
res++;
} else {
res.push({
x: is.x,
y: is.y,
t1: mmin(t1, 1),
t2: mmin(t2, 1)
});
}
}
}
}
}
return res;
}
/*\
* Raphael.pathIntersection
[ method ]
**
* Utility method
**
* Finds intersections of two paths
> Parameters
- path1 (string) path string
- path2 (string) path string
= (array) dots of intersection
o [
o {
o x: (number) x coordinate of the point
o y: (number) y coordinate of the point
o t1: (number) t value for segment of path1
o t2: (number) t value for segment of path2
o segment1: (number) order number for segment of path1
o segment2: (number) order number for segment of path2
o bez1: (array) eight coordinates representing beziér curve for the segment of path1
o bez2: (array) eight coordinates representing beziér curve for the segment of path2
o }
o ]
\*/
R.pathIntersection = function (path1, path2) {
return interPathHelper(path1, path2);
};
R.pathIntersectionNumber = function (path1, path2) {
return interPathHelper(path1, path2, 1);
};
function interPathHelper(path1, path2, justCount) {
path1 = R._path2curve(path1);
path2 = R._path2curve(path2);
var x1, y1, x2, y2, x1m, y1m, x2m, y2m, bez1, bez2,
res = justCount ? 0 : [];
for (var i = 0, ii = path1.length; i < ii; i++) {
var pi = path1[i];
if (pi[0] == "M") {
x1 = x1m = pi[1];
y1 = y1m = pi[2];
} else {
if (pi[0] == "C") {
bez1 = [x1, y1].concat(pi.slice(1));
x1 = bez1[6];
y1 = bez1[7];
} else {
bez1 = [x1, y1, x1, y1, x1m, y1m, x1m, y1m];
x1 = x1m;
y1 = y1m;
}
for (var j = 0, jj = path2.length; j < jj; j++) {
var pj = path2[j];
if (pj[0] == "M") {
x2 = x2m = pj[1];
y2 = y2m = pj[2];
} else {
if (pj[0] == "C") {
bez2 = [x2, y2].concat(pj.slice(1));
x2 = bez2[6];
y2 = bez2[7];
} else {
bez2 = [x2, y2, x2, y2, x2m, y2m, x2m, y2m];
x2 = x2m;
y2 = y2m;
}
var intr = interHelper(bez1, bez2, justCount);
if (justCount) {
res += intr;
} else {
for (var k = 0, kk = intr.length; k < kk; k++) {
intr[k].segment1 = i;
intr[k].segment2 = j;
intr[k].bez1 = bez1;
intr[k].bez2 = bez2;
}
res = res.concat(intr);
}
}
}
}
}
return res;
}
/*\
* Raphael.isPointInsidePath
[ method ]
**
* Utility method
**
* Returns `true` if given point is inside a given closed path.
> Parameters
- path (string) path string
- x (number) x of the point
- y (number) y of the point
= (boolean) true, if point is inside the path
\*/
R.isPointInsidePath = function (path, x, y) {
var bbox = R.pathBBox(path);
return R.isPointInsideBBox(bbox, x, y) &&
interPathHelper(path, [["M", x, y], ["H", bbox.x2 + 10]], 1) % 2 == 1;
};
R._removedFactory = function (methodname) {
return function () {
eve("raphael.log", null, "Rapha\xebl: you are calling to method \u201c" + methodname + "\u201d of removed object", methodname);
};
};
/*\
* Raphael.pathBBox
[ method ]
**
* Utility method
**
* Return bounding box of a given path
> Parameters
- path (string) path string
= (object) bounding box
o {
o x: (number) x coordinate of the left top point of the box
o y: (number) y coordinate of the left top point of the box
o x2: (number) x coordinate of the right bottom point of the box
o y2: (number) y coordinate of the right bottom point of the box
o width: (number) width of the box
o height: (number) height of the box
o cx: (number) x coordinate of the center of the box
o cy: (number) y coordinate of the center of the box
o }
\*/
var pathDimensions = R.pathBBox = function (path) {
var pth = paths(path);
if (pth.bbox) {
return clone(pth.bbox);
}
if (!path) {
return {x: 0, y: 0, width: 0, height: 0, x2: 0, y2: 0};
}
path = path2curve(path);
var x = 0,
y = 0,
X = [],
Y = [],
p;
for (var i = 0, ii = path.length; i < ii; i++) {
p = path[i];
if (p[0] == "M") {
x = p[1];
y = p[2];
X.push(x);
Y.push(y);
} else {
var dim = curveDim(x, y, p[1], p[2], p[3], p[4], p[5], p[6]);
X = X[concat](dim.min.x, dim.max.x);
Y = Y[concat](dim.min.y, dim.max.y);
x = p[5];
y = p[6];
}
}
var xmin = mmin[apply](0, X),
ymin = mmin[apply](0, Y),
xmax = mmax[apply](0, X),
ymax = mmax[apply](0, Y),
width = xmax - xmin,
height = ymax - ymin,
bb = {
x: xmin,
y: ymin,
x2: xmax,
y2: ymax,
width: width,
height: height,
cx: xmin + width / 2,
cy: ymin + height / 2
};
pth.bbox = clone(bb);
return bb;
},
pathClone = function (pathArray) {
var res = clone(pathArray);
res.toString = R._path2string;
return res;
},
pathToRelative = R._pathToRelative = function (pathArray) {
var pth = paths(pathArray);
if (pth.rel) {
return pathClone(pth.rel);
}
if (!R.is(pathArray, array) || !R.is(pathArray && pathArray[0], array)) { // rough assumption
pathArray = R.parsePathString(pathArray);
}
var res = [],
x = 0,
y = 0,
mx = 0,
my = 0,
start = 0;
if (pathArray[0][0] == "M") {
x = pathArray[0][1];
y = pathArray[0][2];
mx = x;
my = y;
start++;
res.push(["M", x, y]);
}
for (var i = start, ii = pathArray.length; i < ii; i++) {
var r = res[i] = [],
pa = pathArray[i];
if (pa[0] != lowerCase.call(pa[0])) {
r[0] = lowerCase.call(pa[0]);
switch (r[0]) {
case "a":
r[1] = pa[1];
r[2] = pa[2];
r[3] = pa[3];
r[4] = pa[4];
r[5] = pa[5];
r[6] = +(pa[6] - x).toFixed(3);
r[7] = +(pa[7] - y).toFixed(3);
break;
case "v":
r[1] = +(pa[1] - y).toFixed(3);
break;
case "m":
mx = pa[1];
my = pa[2];
default:
for (var j = 1, jj = pa.length; j < jj; j++) {
r[j] = +(pa[j] - ((j % 2) ? x : y)).toFixed(3);
}
}
} else {
r = res[i] = [];
if (pa[0] == "m") {
mx = pa[1] + x;
my = pa[2] + y;
}
for (var k = 0, kk = pa.length; k < kk; k++) {
res[i][k] = pa[k];
}
}
var len = res[i].length;
switch (res[i][0]) {
case "z":
x = mx;
y = my;
break;
case "h":
x += +res[i][len - 1];
break;
case "v":
y += +res[i][len - 1];
break;
default:
x += +res[i][len - 2];
y += +res[i][len - 1];
}
}
res.toString = R._path2string;
pth.rel = pathClone(res);
return res;
},
pathToAbsolute = R._pathToAbsolute = function (pathArray) {
var pth = paths(pathArray);
if (pth.abs) {
return pathClone(pth.abs);
}
if (!R.is(pathArray, array) || !R.is(pathArray && pathArray[0], array)) { // rough assumption
pathArray = R.parsePathString(pathArray);
}
if (!pathArray || !pathArray.length) {
return [["M", 0, 0]];
}
var res = [],
x = 0,
y = 0,
mx = 0,
my = 0,
start = 0;
if (pathArray[0][0] == "M") {
x = +pathArray[0][1];
y = +pathArray[0][2];
mx = x;
my = y;
start++;
res[0] = ["M", x, y];
}
var crz = pathArray.length == 3 && pathArray[0][0] == "M" && pathArray[1][0].toUpperCase() == "R" && pathArray[2][0].toUpperCase() == "Z";
for (var r, pa, i = start, ii = pathArray.length; i < ii; i++) {
res.push(r = []);
pa = pathArray[i];
if (pa[0] != upperCase.call(pa[0])) {
r[0] = upperCase.call(pa[0]);
switch (r[0]) {
case "A":
r[1] = pa[1];
r[2] = pa[2];
r[3] = pa[3];
r[4] = pa[4];
r[5] = pa[5];
r[6] = +(pa[6] + x);
r[7] = +(pa[7] + y);
break;
case "V":
r[1] = +pa[1] + y;
break;
case "H":
r[1] = +pa[1] + x;
break;
case "R":
var dots = [x, y][concat](pa.slice(1));
for (var j = 2, jj = dots.length; j < jj; j++) {
dots[j] = +dots[j] + x;
dots[++j] = +dots[j] + y;
}
res.pop();
res = res[concat](catmullRom2bezier(dots, crz));
break;
case "M":
mx = +pa[1] + x;
my = +pa[2] + y;
default:
for (j = 1, jj = pa.length; j < jj; j++) {
r[j] = +pa[j] + ((j % 2) ? x : y);
}
}
} else if (pa[0] == "R") {
dots = [x, y][concat](pa.slice(1));
res.pop();
res = res[concat](catmullRom2bezier(dots, crz));
r = ["R"][concat](pa.slice(-2));
} else {
for (var k = 0, kk = pa.length; k < kk; k++) {
r[k] = pa[k];
}
}
switch (r[0]) {
case "Z":
x = mx;
y = my;
break;
case "H":
x = r[1];
break;
case "V":
y = r[1];
break;
case "M":
mx = r[r.length - 2];
my = r[r.length - 1];
default:
x = r[r.length - 2];
y = r[r.length - 1];
}
}
res.toString = R._path2string;
pth.abs = pathClone(res);
return res;
},
l2c = function (x1, y1, x2, y2) {
return [x1, y1, x2, y2, x2, y2];
},
q2c = function (x1, y1, ax, ay, x2, y2) {
var _13 = 1 / 3,
_23 = 2 / 3;
return [
_13 * x1 + _23 * ax,
_13 * y1 + _23 * ay,
_13 * x2 + _23 * ax,
_13 * y2 + _23 * ay,
x2,
y2
];
},
a2c = function (x1, y1, rx, ry, angle, large_arc_flag, sweep_flag, x2, y2, recursive) {
// for more information of where this math came from visit:
// http://www.w3.org/TR/SVG11/implnote.html#ArcImplementationNotes
var _120 = PI * 120 / 180,
rad = PI / 180 * (+angle || 0),
res = [],
xy,
rotate = cacher(function (x, y, rad) {
var X = x * math.cos(rad) - y * math.sin(rad),
Y = x * math.sin(rad) + y * math.cos(rad);
return {x: X, y: Y};
});
if (!recursive) {
xy = rotate(x1, y1, -rad);
x1 = xy.x;
y1 = xy.y;
xy = rotate(x2, y2, -rad);
x2 = xy.x;
y2 = xy.y;
var cos = math.cos(PI / 180 * angle),
sin = math.sin(PI / 180 * angle),
x = (x1 - x2) / 2,
y = (y1 - y2) / 2;
var h = (x * x) / (rx * rx) + (y * y) / (ry * ry);
if (h > 1) {
h = math.sqrt(h);
rx = h * rx;
ry = h * ry;
}
var rx2 = rx * rx,
ry2 = ry * ry,
k = (large_arc_flag == sweep_flag ? -1 : 1) *
math.sqrt(abs((rx2 * ry2 - rx2 * y * y - ry2 * x * x) / (rx2 * y * y + ry2 * x * x))),
cx = k * rx * y / ry + (x1 + x2) / 2,
cy = k * -ry * x / rx + (y1 + y2) / 2,
f1 = math.asin(((y1 - cy) / ry).toFixed(9)),
f2 = math.asin(((y2 - cy) / ry).toFixed(9));
f1 = x1 < cx ? PI - f1 : f1;
f2 = x2 < cx ? PI - f2 : f2;
f1 < 0 && (f1 = PI * 2 + f1);
f2 < 0 && (f2 = PI * 2 + f2);
if (sweep_flag && f1 > f2) {
f1 = f1 - PI * 2;
}
if (!sweep_flag && f2 > f1) {
f2 = f2 - PI * 2;
}
} else {
f1 = recursive[0];
f2 = recursive[1];
cx = recursive[2];
cy = recursive[3];
}
var df = f2 - f1;
if (abs(df) > _120) {
var f2old = f2,
x2old = x2,
y2old = y2;
f2 = f1 + _120 * (sweep_flag && f2 > f1 ? 1 : -1);
x2 = cx + rx * math.cos(f2);
y2 = cy + ry * math.sin(f2);
res = a2c(x2, y2, rx, ry, angle, 0, sweep_flag, x2old, y2old, [f2, f2old, cx, cy]);
}
df = f2 - f1;
var c1 = math.cos(f1),
s1 = math.sin(f1),
c2 = math.cos(f2),
s2 = math.sin(f2),
t = math.tan(df / 4),
hx = 4 / 3 * rx * t,
hy = 4 / 3 * ry * t,
m1 = [x1, y1],
m2 = [x1 + hx * s1, y1 - hy * c1],
m3 = [x2 + hx * s2, y2 - hy * c2],
m4 = [x2, y2];
m2[0] = 2 * m1[0] - m2[0];
m2[1] = 2 * m1[1] - m2[1];
if (recursive) {
return [m2, m3, m4][concat](res);
} else {
res = [m2, m3, m4][concat](res).join()[split](",");
var newres = [];
for (var i = 0, ii = res.length; i < ii; i++) {
newres[i] = i % 2 ? rotate(res[i - 1], res[i], rad).y : rotate(res[i], res[i + 1], rad).x;
}
return newres;
}
},
findDotAtSegment = function (p1x, p1y, c1x, c1y, c2x, c2y, p2x, p2y, t) {
var t1 = 1 - t;
return {
x: pow(t1, 3) * p1x + pow(t1, 2) * 3 * t * c1x + t1 * 3 * t * t * c2x + pow(t, 3) * p2x,
y: pow(t1, 3) * p1y + pow(t1, 2) * 3 * t * c1y + t1 * 3 * t * t * c2y + pow(t, 3) * p2y
};
},
curveDim = cacher(function (p1x, p1y, c1x, c1y, c2x, c2y, p2x, p2y) {
var a = (c2x - 2 * c1x + p1x) - (p2x - 2 * c2x + c1x),
b = 2 * (c1x - p1x) - 2 * (c2x - c1x),
c = p1x - c1x,
t1 = (-b + math.sqrt(b * b - 4 * a * c)) / 2 / a,
t2 = (-b - math.sqrt(b * b - 4 * a * c)) / 2 / a,
y = [p1y, p2y],
x = [p1x, p2x],
dot;
abs(t1) > "1e12" && (t1 = .5);
abs(t2) > "1e12" && (t2 = .5);
if (t1 > 0 && t1 < 1) {
dot = findDotAtSegment(p1x, p1y, c1x, c1y, c2x, c2y, p2x, p2y, t1);
x.push(dot.x);
y.push(dot.y);
}
if (t2 > 0 && t2 < 1) {
dot = findDotAtSegment(p1x, p1y, c1x, c1y, c2x, c2y, p2x, p2y, t2);
x.push(dot.x);
y.push(dot.y);
}
a = (c2y - 2 * c1y + p1y) - (p2y - 2 * c2y + c1y);
b = 2 * (c1y - p1y) - 2 * (c2y - c1y);
c = p1y - c1y;
t1 = (-b + math.sqrt(b * b - 4 * a * c)) / 2 / a;
t2 = (-b - math.sqrt(b * b - 4 * a * c)) / 2 / a;
abs(t1) > "1e12" && (t1 = .5);
abs(t2) > "1e12" && (t2 = .5);
if (t1 > 0 && t1 < 1) {
dot = findDotAtSegment(p1x, p1y, c1x, c1y, c2x, c2y, p2x, p2y, t1);
x.push(dot.x);
y.push(dot.y);
}
if (t2 > 0 && t2 < 1) {
dot = findDotAtSegment(p1x, p1y, c1x, c1y, c2x, c2y, p2x, p2y, t2);
x.push(dot.x);
y.push(dot.y);
}
return {
min: {x: mmin[apply](0, x), y: mmin[apply](0, y)},
max: {x: mmax[apply](0, x), y: mmax[apply](0, y)}
};
}),
path2curve = R._path2curve = cacher(function (path, path2) {
var pth = !path2 && paths(path);
if (!path2 && pth.curve) {
return pathClone(pth.curve);
}
var p = pathToAbsolute(path),
p2 = path2 && pathToAbsolute(path2),
attrs = {x: 0, y: 0, bx: 0, by: 0, X: 0, Y: 0, qx: null, qy: null},
attrs2 = {x: 0, y: 0, bx: 0, by: 0, X: 0, Y: 0, qx: null, qy: null},
processPath = function (path, d, pcom) {
var nx, ny, tq = {T:1, Q:1};
if (!path) {
return ["C", d.x, d.y, d.x, d.y, d.x, d.y];
}
!(path[0] in tq) && (d.qx = d.qy = null);
switch (path[0]) {
case "M":
d.X = path[1];
d.Y = path[2];
break;
case "A":
path = ["C"][concat](a2c[apply](0, [d.x, d.y][concat](path.slice(1))));
break;
case "S":
if (pcom == "C" || pcom == "S") { // In "S" case we have to take into account, if the previous command is C/S.
nx = d.x * 2 - d.bx; // And reflect the previous
ny = d.y * 2 - d.by; // command's control point relative to the current point.
}
else { // or some else or nothing
nx = d.x;
ny = d.y;
}
path = ["C", nx, ny][concat](path.slice(1));
break;
case "T":
if (pcom == "Q" || pcom == "T") { // In "T" case we have to take into account, if the previous command is Q/T.
d.qx = d.x * 2 - d.qx; // And make a reflection similar
d.qy = d.y * 2 - d.qy; // to case "S".
}
else { // or something else or nothing
d.qx = d.x;
d.qy = d.y;
}
path = ["C"][concat](q2c(d.x, d.y, d.qx, d.qy, path[1], path[2]));
break;
case "Q":
d.qx = path[1];
d.qy = path[2];
path = ["C"][concat](q2c(d.x, d.y, path[1], path[2], path[3], path[4]));
break;
case "L":
path = ["C"][concat](l2c(d.x, d.y, path[1], path[2]));
break;
case "H":
path = ["C"][concat](l2c(d.x, d.y, path[1], d.y));
break;
case "V":
path = ["C"][concat](l2c(d.x, d.y, d.x, path[1]));
break;
case "Z":
path = ["C"][concat](l2c(d.x, d.y, d.X, d.Y));
break;
}
return path;
},
fixArc = function (pp, i) {
if (pp[i].length > 7) {
pp[i].shift();
var pi = pp[i];
while (pi.length) {
pp.splice(i++, 0, ["C"][concat](pi.splice(0, 6)));
}
pp.splice(i, 1);
ii = mmax(p.length, p2 && p2.length || 0);
}
},
fixM = function (path1, path2, a1, a2, i) {
if (path1 && path2 && path1[i][0] == "M" && path2[i][0] != "M") {
path2.splice(i, 0, ["M", a2.x, a2.y]);
a1.bx = 0;
a1.by = 0;
a1.x = path1[i][1];
a1.y = path1[i][2];
ii = mmax(p.length, p2 && p2.length || 0);
}
};
for (var i = 0, ii = mmax(p.length, p2 && p2.length || 0); i < ii; i++) {
p[i] = processPath(p[i], attrs);
fixArc(p, i);
p2 && (p2[i] = processPath(p2[i], attrs2));
p2 && fixArc(p2, i);
fixM(p, p2, attrs, attrs2, i);
fixM(p2, p, attrs2, attrs, i);
var seg = p[i],
seg2 = p2 && p2[i],
seglen = seg.length,
seg2len = p2 && seg2.length;
attrs.x = seg[seglen - 2];
attrs.y = seg[seglen - 1];
attrs.bx = toFloat(seg[seglen - 4]) || attrs.x;
attrs.by = toFloat(seg[seglen - 3]) || attrs.y;
attrs2.bx = p2 && (toFloat(seg2[seg2len - 4]) || attrs2.x);
attrs2.by = p2 && (toFloat(seg2[seg2len - 3]) || attrs2.y);
attrs2.x = p2 && seg2[seg2len - 2];
attrs2.y = p2 && seg2[seg2len - 1];
}
if (!p2) {
pth.curve = pathClone(p);
}
return p2 ? [p, p2] : p;
}, null, pathClone),
parseDots = R._parseDots = cacher(function (gradient) {
var dots = [];
for (var i = 0, ii = gradient.length; i < ii; i++) {
var dot = {},
par = gradient[i].match(/^([^:]*):?([\d\.]*)/);
dot.color = R.getRGB(par[1]);
if (dot.color.error) {
return null;
}
dot.color = dot.color.hex;
par[2] && (dot.offset = par[2] + "%");
dots.push(dot);
}
for (i = 1, ii = dots.length - 1; i < ii; i++) {
if (!dots[i].offset) {
var start = toFloat(dots[i - 1].offset || 0),
end = 0;
for (var j = i + 1; j < ii; j++) {
if (dots[j].offset) {
end = dots[j].offset;
break;
}
}
if (!end) {
end = 100;
j = ii;
}
end = toFloat(end);
var d = (end - start) / (j - i + 1);
for (; i < j; i++) {
start += d;
dots[i].offset = start + "%";
}
}
}
return dots;
}),
tear = R._tear = function (el, paper) {
el == paper.top && (paper.top = el.prev);
el == paper.bottom && (paper.bottom = el.next);
el.next && (el.next.prev = el.prev);
el.prev && (el.prev.next = el.next);
},
tofront = R._tofront = function (el, paper) {
if (paper.top === el) {
return;
}
tear(el, paper);
el.next = null;
el.prev = paper.top;
paper.top.next = el;
paper.top = el;
},
toback = R._toback = function (el, paper) {
if (paper.bottom === el) {
return;
}
tear(el, paper);
el.next = paper.bottom;
el.prev = null;
paper.bottom.prev = el;
paper.bottom = el;
},
insertafter = R._insertafter = function (el, el2, paper) {
tear(el, paper);
el2 == paper.top && (paper.top = el);
el2.next && (el2.next.prev = el);
el.next = el2.next;
el.prev = el2;
el2.next = el;
},
insertbefore = R._insertbefore = function (el, el2, paper) {
tear(el, paper);
el2 == paper.bottom && (paper.bottom = el);
el2.prev && (el2.prev.next = el);
el.prev = el2.prev;
el2.prev = el;
el.next = el2;
},
/*\
* Raphael.toMatrix
[ method ]
**
* Utility method
**
* Returns matrix of transformations applied to a given path
> Parameters
- path (string) path string
- transform (string|array) transformation string
= (object) @Matrix
\*/
toMatrix = R.toMatrix = function (path, transform) {
var bb = pathDimensions(path),
el = {
_: {
transform: E
},
getBBox: function () {
return bb;
}
};
extractTransform(el, transform);
return el.matrix;
},
/*\
* Raphael.transformPath
[ method ]
**
* Utility method
**
* Returns path transformed by a given transformation
> Parameters
- path (string) path string
- transform (string|array) transformation string
= (string) path
\*/
transformPath = R.transformPath = function (path, transform) {
return mapPath(path, toMatrix(path, transform));
},
extractTransform = R._extractTransform = function (el, tstr) {
if (tstr == null) {
return el._.transform;
}
tstr = Str(tstr).replace(/\.{3}|\u2026/g, el._.transform || E);
var tdata = R.parseTransformString(tstr),
deg = 0,
dx = 0,
dy = 0,
sx = 1,
sy = 1,
_ = el._,
m = new Matrix;
_.transform = tdata || [];
if (tdata) {
for (var i = 0, ii = tdata.length; i < ii; i++) {
var t = tdata[i],
tlen = t.length,
command = Str(t[0]).toLowerCase(),
absolute = t[0] != command,
inver = absolute ? m.invert() : 0,
x1,
y1,
x2,
y2,
bb;
if (command == "t" && tlen == 3) {
if (absolute) {
x1 = inver.x(0, 0);
y1 = inver.y(0, 0);
x2 = inver.x(t[1], t[2]);
y2 = inver.y(t[1], t[2]);
m.translate(x2 - x1, y2 - y1);
} else {
m.translate(t[1], t[2]);
}
} else if (command == "r") {
if (tlen == 2) {
bb = bb || el.getBBox(1);
m.rotate(t[1], bb.x + bb.width / 2, bb.y + bb.height / 2);
deg += t[1];
} else if (tlen == 4) {
if (absolute) {
x2 = inver.x(t[2], t[3]);
y2 = inver.y(t[2], t[3]);
m.rotate(t[1], x2, y2);
} else {
m.rotate(t[1], t[2], t[3]);
}
deg += t[1];
}
} else if (command == "s") {
if (tlen == 2 || tlen == 3) {
bb = bb || el.getBBox(1);
m.scale(t[1], t[tlen - 1], bb.x + bb.width / 2, bb.y + bb.height / 2);
sx *= t[1];
sy *= t[tlen - 1];
} else if (tlen == 5) {
if (absolute) {
x2 = inver.x(t[3], t[4]);
y2 = inver.y(t[3], t[4]);
m.scale(t[1], t[2], x2, y2);
} else {
m.scale(t[1], t[2], t[3], t[4]);
}
sx *= t[1];
sy *= t[2];
}
} else if (command == "m" && tlen == 7) {
m.add(t[1], t[2], t[3], t[4], t[5], t[6]);
}
_.dirtyT = 1;
el.matrix = m;
}
}
/*\
* Element.matrix
[ property (object) ]
**
* Keeps @Matrix object, which represents element transformation
\*/
el.matrix = m;
_.sx = sx;
_.sy = sy;
_.deg = deg;
_.dx = dx = m.e;
_.dy = dy = m.f;
if (sx == 1 && sy == 1 && !deg && _.bbox) {
_.bbox.x += +dx;
_.bbox.y += +dy;
} else {
_.dirtyT = 1;
}
},
getEmpty = function (item) {
var l = item[0];
switch (l.toLowerCase()) {
case "t": return [l, 0, 0];
case "m": return [l, 1, 0, 0, 1, 0, 0];
case "r": if (item.length == 4) {
return [l, 0, item[2], item[3]];
} else {
return [l, 0];
}
case "s": if (item.length == 5) {
return [l, 1, 1, item[3], item[4]];
} else if (item.length == 3) {
return [l, 1, 1];
} else {
return [l, 1];
}
}
},
equaliseTransform = R._equaliseTransform = function (t1, t2) {
t2 = Str(t2).replace(/\.{3}|\u2026/g, t1);
t1 = R.parseTransformString(t1) || [];
t2 = R.parseTransformString(t2) || [];
var maxlength = mmax(t1.length, t2.length),
from = [],
to = [],
i = 0, j, jj,
tt1, tt2;
for (; i < maxlength; i++) {
tt1 = t1[i] || getEmpty(t2[i]);
tt2 = t2[i] || getEmpty(tt1);
if ((tt1[0] != tt2[0]) ||
(tt1[0].toLowerCase() == "r" && (tt1[2] != tt2[2] || tt1[3] != tt2[3])) ||
(tt1[0].toLowerCase() == "s" && (tt1[3] != tt2[3] || tt1[4] != tt2[4]))
) {
return;
}
from[i] = [];
to[i] = [];
for (j = 0, jj = mmax(tt1.length, tt2.length); j < jj; j++) {
j in tt1 && (from[i][j] = tt1[j]);
j in tt2 && (to[i][j] = tt2[j]);
}
}
return {
from: from,
to: to
};
};
R._getContainer = function (x, y, w, h) {
var container;
container = h == null && !R.is(x, "object") ? g.doc.getElementById(x) : x;
if (container == null) {
return;
}
if (container.tagName) {
if (y == null) {
return {
container: container,
width: container.style.pixelWidth || container.offsetWidth,
height: container.style.pixelHeight || container.offsetHeight
};
} else {
return {
container: container,
width: y,
height: w
};
}
}
return {
container: 1,
x: x,
y: y,
width: w,
height: h
};
};
/*\
* Raphael.pathToRelative
[ method ]
**
* Utility method
**
* Converts path to relative form
> Parameters
- pathString (string|array) path string or array of segments
= (array) array of segments.
\*/
R.pathToRelative = pathToRelative;
R._engine = {};
/*\
* Raphael.path2curve
[ method ]
**
* Utility method
**
* Converts path to a new path where all segments are cubic bezier curves.
> Parameters
- pathString (string|array) path string or array of segments
= (array) array of segments.
\*/
R.path2curve = path2curve;
/*\
* Raphael.matrix
[ method ]
**
* Utility method
**
* Returns matrix based on given parameters.
> Parameters
- a (number)
- b (number)
- c (number)
- d (number)
- e (number)
- f (number)
= (object) @Matrix
\*/
R.matrix = function (a, b, c, d, e, f) {
return new Matrix(a, b, c, d, e, f);
};
function Matrix(a, b, c, d, e, f) {
if (a != null) {
this.a = +a;
this.b = +b;
this.c = +c;
this.d = +d;
this.e = +e;
this.f = +f;
} else {
this.a = 1;
this.b = 0;
this.c = 0;
this.d = 1;
this.e = 0;
this.f = 0;
}
}
(function (matrixproto) {
/*\
* Matrix.add
[ method ]
**
* Adds given matrix to existing one.
> Parameters
- a (number)
- b (number)
- c (number)
- d (number)
- e (number)
- f (number)
or
- matrix (object) @Matrix
\*/
matrixproto.add = function (a, b, c, d, e, f) {
var out = [[], [], []],
m = [[this.a, this.c, this.e], [this.b, this.d, this.f], [0, 0, 1]],
matrix = [[a, c, e], [b, d, f], [0, 0, 1]],
x, y, z, res;
if (a && a instanceof Matrix) {
matrix = [[a.a, a.c, a.e], [a.b, a.d, a.f], [0, 0, 1]];
}
for (x = 0; x < 3; x++) {
for (y = 0; y < 3; y++) {
res = 0;
for (z = 0; z < 3; z++) {
res += m[x][z] * matrix[z][y];
}
out[x][y] = res;
}
}
this.a = out[0][0];
this.b = out[1][0];
this.c = out[0][1];
this.d = out[1][1];
this.e = out[0][2];
this.f = out[1][2];
};
/*\
* Matrix.invert
[ method ]
**
* Returns inverted version of the matrix
= (object) @Matrix
\*/
matrixproto.invert = function () {
var me = this,
x = me.a * me.d - me.b * me.c;
return new Matrix(me.d / x, -me.b / x, -me.c / x, me.a / x, (me.c * me.f - me.d * me.e) / x, (me.b * me.e - me.a * me.f) / x);
};
/*\
* Matrix.clone
[ method ]
**
* Returns copy of the matrix
= (object) @Matrix
\*/
matrixproto.clone = function () {
return new Matrix(this.a, this.b, this.c, this.d, this.e, this.f);
};
/*\
* Matrix.translate
[ method ]
**
* Translate the matrix
> Parameters
- x (number)
- y (number)
\*/
matrixproto.translate = function (x, y) {
this.add(1, 0, 0, 1, x, y);
};
/*\
* Matrix.scale
[ method ]
**
* Scales the matrix
> Parameters
- x (number)
- y (number) #optional
- cx (number) #optional
- cy (number) #optional
\*/
matrixproto.scale = function (x, y, cx, cy) {
y == null && (y = x);
(cx || cy) && this.add(1, 0, 0, 1, cx, cy);
this.add(x, 0, 0, y, 0, 0);
(cx || cy) && this.add(1, 0, 0, 1, -cx, -cy);
};
/*\
* Matrix.rotate
[ method ]
**
* Rotates the matrix
> Parameters
- a (number)
- x (number)
- y (number)
\*/
matrixproto.rotate = function (a, x, y) {
a = R.rad(a);
x = x || 0;
y = y || 0;
var cos = +math.cos(a).toFixed(9),
sin = +math.sin(a).toFixed(9);
this.add(cos, sin, -sin, cos, x, y);
this.add(1, 0, 0, 1, -x, -y);
};
/*\
* Matrix.x
[ method ]
**
* Return x coordinate for given point after transformation described by the matrix. See also @Matrix.y
> Parameters
- x (number)
- y (number)
= (number) x
\*/
matrixproto.x = function (x, y) {
return x * this.a + y * this.c + this.e;
};
/*\
* Matrix.y
[ method ]
**
* Return y coordinate for given point after transformation described by the matrix. See also @Matrix.x
> Parameters
- x (number)
- y (number)
= (number) y
\*/
matrixproto.y = function (x, y) {
return x * this.b + y * this.d + this.f;
};
matrixproto.get = function (i) {
return +this[Str.fromCharCode(97 + i)].toFixed(4);
};
matrixproto.toString = function () {
return R.svg ?
"matrix(" + [this.get(0), this.get(1), this.get(2), this.get(3), this.get(4), this.get(5)].join() + ")" :
[this.get(0), this.get(2), this.get(1), this.get(3), 0, 0].join();
};
matrixproto.toFilter = function () {
return "progid:DXImageTransform.Microsoft.Matrix(M11=" + this.get(0) +
", M12=" + this.get(2) + ", M21=" + this.get(1) + ", M22=" + this.get(3) +
", Dx=" + this.get(4) + ", Dy=" + this.get(5) + ", sizingmethod='auto expand')";
};
matrixproto.offset = function () {
return [this.e.toFixed(4), this.f.toFixed(4)];
};
function norm(a) {
return a[0] * a[0] + a[1] * a[1];
}
function normalize(a) {
var mag = math.sqrt(norm(a));
a[0] && (a[0] /= mag);
a[1] && (a[1] /= mag);
}
/*\
* Matrix.split
[ method ]
**
* Splits matrix into primitive transformations
= (object) in format:
o dx (number) translation by x
o dy (number) translation by y
o scalex (number) scale by x
o scaley (number) scale by y
o shear (number) shear
o rotate (number) rotation in deg
o isSimple (boolean) could it be represented via simple transformations
\*/
matrixproto.split = function () {
var out = {};
// translation
out.dx = this.e;
out.dy = this.f;
// scale and shear
var row = [[this.a, this.c], [this.b, this.d]];
out.scalex = math.sqrt(norm(row[0]));
normalize(row[0]);
out.shear = row[0][0] * row[1][0] + row[0][1] * row[1][1];
row[1] = [row[1][0] - row[0][0] * out.shear, row[1][1] - row[0][1] * out.shear];
out.scaley = math.sqrt(norm(row[1]));
normalize(row[1]);
out.shear /= out.scaley;
// rotation
var sin = -row[0][1],
cos = row[1][1];
if (cos < 0) {
out.rotate = R.deg(math.acos(cos));
if (sin < 0) {
out.rotate = 360 - out.rotate;
}
} else {
out.rotate = R.deg(math.asin(sin));
}
out.isSimple = !+out.shear.toFixed(9) && (out.scalex.toFixed(9) == out.scaley.toFixed(9) || !out.rotate);
out.isSuperSimple = !+out.shear.toFixed(9) && out.scalex.toFixed(9) == out.scaley.toFixed(9) && !out.rotate;
out.noRotation = !+out.shear.toFixed(9) && !out.rotate;
return out;
};
/*\
* Matrix.toTransformString
[ method ]
**
* Return transform string that represents given matrix
= (string) transform string
\*/
matrixproto.toTransformString = function (shorter) {
var s = shorter || this[split]();
if (s.isSimple) {
s.scalex = +s.scalex.toFixed(4);
s.scaley = +s.scaley.toFixed(4);
s.rotate = +s.rotate.toFixed(4);
return (s.dx || s.dy ? "t" + [s.dx, s.dy] : E) +
(s.scalex != 1 || s.scaley != 1 ? "s" + [s.scalex, s.scaley, 0, 0] : E) +
(s.rotate ? "r" + [s.rotate, 0, 0] : E);
} else {
return "m" + [this.get(0), this.get(1), this.get(2), this.get(3), this.get(4), this.get(5)];
}
};
})(Matrix.prototype);
// WebKit rendering bug workaround method
var version = navigator.userAgent.match(/Version\/(.*?)\s/) || navigator.userAgent.match(/Chrome\/(\d+)/);
if ((navigator.vendor == "Apple Computer, Inc.") && (version && version[1] < 4 || navigator.platform.slice(0, 2) == "iP") ||
(navigator.vendor == "Google Inc." && version && version[1] < 8)) {
/*\
* Paper.safari
[ method ]
**
* There is an inconvenient rendering bug in Safari (WebKit):
* sometimes the rendering should be forced.
* This method should help with dealing with this bug.
\*/
paperproto.safari = function () {
var rect = this.rect(-99, -99, this.width + 99, this.height + 99).attr({stroke: "none"});
setTimeout(function () {rect.remove();});
};
} else {
paperproto.safari = fun;
}
var preventDefault = function () {
this.returnValue = false;
},
preventTouch = function () {
return this.originalEvent.preventDefault();
},
stopPropagation = function () {
this.cancelBubble = true;
},
stopTouch = function () {
return this.originalEvent.stopPropagation();
},
getEventPosition = function (e) {
var scrollY = g.doc.documentElement.scrollTop || g.doc.body.scrollTop,
scrollX = g.doc.documentElement.scrollLeft || g.doc.body.scrollLeft;
return {
x: e.clientX + scrollX,
y: e.clientY + scrollY
};
},
addEvent = (function () {
if (g.doc.addEventListener) {
return function (obj, type, fn, element) {
var f = function (e) {
var pos = getEventPosition(e);
return fn.call(element, e, pos.x, pos.y);
};
obj.addEventListener(type, f, false);
if (supportsTouch && touchMap[type]) {
var _f = function (e) {
var pos = getEventPosition(e),
olde = e;
for (var i = 0, ii = e.targetTouches && e.targetTouches.length; i < ii; i++) {
if (e.targetTouches[i].target == obj) {
e = e.targetTouches[i];
e.originalEvent = olde;
e.preventDefault = preventTouch;
e.stopPropagation = stopTouch;
break;
}
}
return fn.call(element, e, pos.x, pos.y);
};
obj.addEventListener(touchMap[type], _f, false);
}
return function () {
obj.removeEventListener(type, f, false);
if (supportsTouch && touchMap[type])
obj.removeEventListener(touchMap[type], f, false);
return true;
};
};
} else if (g.doc.attachEvent) {
return function (obj, type, fn, element) {
var f = function (e) {
e = e || g.win.event;
var scrollY = g.doc.documentElement.scrollTop || g.doc.body.scrollTop,
scrollX = g.doc.documentElement.scrollLeft || g.doc.body.scrollLeft,
x = e.clientX + scrollX,
y = e.clientY + scrollY;
e.preventDefault = e.preventDefault || preventDefault;
e.stopPropagation = e.stopPropagation || stopPropagation;
return fn.call(element, e, x, y);
};
obj.attachEvent("on" + type, f);
var detacher = function () {
obj.detachEvent("on" + type, f);
return true;
};
return detacher;
};
}
})(),
drag = [],
dragMove = function (e) {
var x = e.clientX,
y = e.clientY,
scrollY = g.doc.documentElement.scrollTop || g.doc.body.scrollTop,
scrollX = g.doc.documentElement.scrollLeft || g.doc.body.scrollLeft,
dragi,
j = drag.length;
while (j--) {
dragi = drag[j];
if (supportsTouch && e.touches) {
var i = e.touches.length,
touch;
while (i--) {
touch = e.touches[i];
if (touch.identifier == dragi.el._drag.id) {
x = touch.clientX;
y = touch.clientY;
(e.originalEvent ? e.originalEvent : e).preventDefault();
break;
}
}
} else {
e.preventDefault();
}
var node = dragi.el.node,
o,
next = node.nextSibling,
parent = node.parentNode,
display = node.style.display;
g.win.opera && parent.removeChild(node);
node.style.display = "none";
o = dragi.el.paper.getElementByPoint(x, y);
node.style.display = display;
g.win.opera && (next ? parent.insertBefore(node, next) : parent.appendChild(node));
o && eve("raphael.drag.over." + dragi.el.id, dragi.el, o);
x += scrollX;
y += scrollY;
eve("raphael.drag.move." + dragi.el.id, dragi.move_scope || dragi.el, x - dragi.el._drag.x, y - dragi.el._drag.y, x, y, e);
}
},
dragUp = function (e) {
R.unmousemove(dragMove).unmouseup(dragUp);
var i = drag.length,
dragi;
while (i--) {
dragi = drag[i];
dragi.el._drag = {};
eve("raphael.drag.end." + dragi.el.id, dragi.end_scope || dragi.start_scope || dragi.move_scope || dragi.el, e);
}
drag = [];
},
/*\
* Raphael.el
[ property (object) ]
**
* You can add your own method to elements. This is usefull when you want to hack default functionality or
* want to wrap some common transformation or attributes in one method. In difference to canvas methods,
* you can redefine element method at any time. Expending element methods wouldn’t affect set.
> Usage
| Raphael.el.red = function () {
| this.attr({fill: "#f00"});
| };
| // then use it
| paper.circle(100, 100, 20).red();
\*/
elproto = R.el = {};
/*\
* Element.click
[ method ]
**
* Adds event handler for click for the element.
> Parameters
- handler (function) handler for the event
= (object) @Element
\*/
/*\
* Element.unclick
[ method ]
**
* Removes event handler for click for the element.
> Parameters
- handler (function) #optional handler for the event
= (object) @Element
\*/
/*\
* Element.dblclick
[ method ]
**
* Adds event handler for double click for the element.
> Parameters
- handler (function) handler for the event
= (object) @Element
\*/
/*\
* Element.undblclick
[ method ]
**
* Removes event handler for double click for the element.
> Parameters
- handler (function) #optional handler for the event
= (object) @Element
\*/
/*\
* Element.mousedown
[ method ]
**
* Adds event handler for mousedown for the element.
> Parameters
- handler (function) handler for the event
= (object) @Element
\*/
/*\
* Element.unmousedown
[ method ]
**
* Removes event handler for mousedown for the element.
> Parameters
- handler (function) #optional handler for the event
= (object) @Element
\*/
/*\
* Element.mousemove
[ method ]
**
* Adds event handler for mousemove for the element.
> Parameters
- handler (function) handler for the event
= (object) @Element
\*/
/*\
* Element.unmousemove
[ method ]
**
* Removes event handler for mousemove for the element.
> Parameters
- handler (function) #optional handler for the event
= (object) @Element
\*/
/*\
* Element.mouseout
[ method ]
**
* Adds event handler for mouseout for the element.
> Parameters
- handler (function) handler for the event
= (object) @Element
\*/
/*\
* Element.unmouseout
[ method ]
**
* Removes event handler for mouseout for the element.
> Parameters
- handler (function) #optional handler for the event
= (object) @Element
\*/
/*\
* Element.mouseover
[ method ]
**
* Adds event handler for mouseover for the element.
> Parameters
- handler (function) handler for the event
= (object) @Element
\*/
/*\
* Element.unmouseover
[ method ]
**
* Removes event handler for mouseover for the element.
> Parameters
- handler (function) #optional handler for the event
= (object) @Element
\*/
/*\
* Element.mouseup
[ method ]
**
* Adds event handler for mouseup for the element.
> Parameters
- handler (function) handler for the event
= (object) @Element
\*/
/*\
* Element.unmouseup
[ method ]
**
* Removes event handler for mouseup for the element.
> Parameters
- handler (function) #optional handler for the event
= (object) @Element
\*/
/*\
* Element.touchstart
[ method ]
**
* Adds event handler for touchstart for the element.
> Parameters
- handler (function) handler for the event
= (object) @Element
\*/
/*\
* Element.untouchstart
[ method ]
**
* Removes event handler for touchstart for the element.
> Parameters
- handler (function) #optional handler for the event
= (object) @Element
\*/
/*\
* Element.touchmove
[ method ]
**
* Adds event handler for touchmove for the element.
> Parameters
- handler (function) handler for the event
= (object) @Element
\*/
/*\
* Element.untouchmove
[ method ]
**
* Removes event handler for touchmove for the element.
> Parameters
- handler (function) #optional handler for the event
= (object) @Element
\*/
/*\
* Element.touchend
[ method ]
**
* Adds event handler for touchend for the element.
> Parameters
- handler (function) handler for the event
= (object) @Element
\*/
/*\
* Element.untouchend
[ method ]
**
* Removes event handler for touchend for the element.
> Parameters
- handler (function) #optional handler for the event
= (object) @Element
\*/
/*\
* Element.touchcancel
[ method ]
**
* Adds event handler for touchcancel for the element.
> Parameters
- handler (function) handler for the event
= (object) @Element
\*/
/*\
* Element.untouchcancel
[ method ]
**
* Removes event handler for touchcancel for the element.
> Parameters
- handler (function) #optional handler for the event
= (object) @Element
\*/
for (var i = events.length; i--;) {
(function (eventName) {
R[eventName] = elproto[eventName] = function (fn, scope) {
if (R.is(fn, "function")) {
this.events = this.events || [];
this.events.push({name: eventName, f: fn, unbind: addEvent(this.shape || this.node || g.doc, eventName, fn, scope || this)});
}
return this;
};
R["un" + eventName] = elproto["un" + eventName] = function (fn) {
var events = this.events || [],
l = events.length;
while (l--){
if (events[l].name == eventName && (R.is(fn, "undefined") || events[l].f == fn)) {
events[l].unbind();
events.splice(l, 1);
!events.length && delete this.events;
}
}
return this;
};
})(events[i]);
}
/*\
* Element.data
[ method ]
**
* Adds or retrieves given value asociated with given key.
**
* See also @Element.removeData
> Parameters
- key (string) key to store data
- value (any) #optional value to store
= (object) @Element
* or, if value is not specified:
= (any) value
* or, if key and value are not specified:
= (object) Key/value pairs for all the data associated with the element.
> Usage
| for (var i = 0, i < 5, i++) {
| paper.circle(10 + 15 * i, 10, 10)
| .attr({fill: "#000"})
| .data("i", i)
| .click(function () {
| alert(this.data("i"));
| });
| }
\*/
elproto.data = function (key, value) {
var data = eldata[this.id] = eldata[this.id] || {};
if (arguments.length == 0) {
return data;
}
if (arguments.length == 1) {
if (R.is(key, "object")) {
for (var i in key) if (key[has](i)) {
this.data(i, key[i]);
}
return this;
}
eve("raphael.data.get." + this.id, this, data[key], key);
return data[key];
}
data[key] = value;
eve("raphael.data.set." + this.id, this, value, key);
return this;
};
/*\
* Element.removeData
[ method ]
**
* Removes value associated with an element by given key.
* If key is not provided, removes all the data of the element.
> Parameters
- key (string) #optional key
= (object) @Element
\*/
elproto.removeData = function (key) {
if (key == null) {
eldata[this.id] = {};
} else {
eldata[this.id] && delete eldata[this.id][key];
}
return this;
};
/*\
* Element.getData
[ method ]
**
* Retrieves the element data
= (object) data
\*/
elproto.getData = function () {
return clone(eldata[this.id] || {});
};
/*\
* Element.hover
[ method ]
**
* Adds event handlers for hover for the element.
> Parameters
- f_in (function) handler for hover in
- f_out (function) handler for hover out
- icontext (object) #optional context for hover in handler
- ocontext (object) #optional context for hover out handler
= (object) @Element
\*/
elproto.hover = function (f_in, f_out, scope_in, scope_out) {
return this.mouseover(f_in, scope_in).mouseout(f_out, scope_out || scope_in);
};
/*\
* Element.unhover
[ method ]
**
* Removes event handlers for hover for the element.
> Parameters
- f_in (function) handler for hover in
- f_out (function) handler for hover out
= (object) @Element
\*/
elproto.unhover = function (f_in, f_out) {
return this.unmouseover(f_in).unmouseout(f_out);
};
var draggable = [];
/*\
* Element.drag
[ method ]
**
* Adds event handlers for drag of the element.
> Parameters
- onmove (function) handler for moving
- onstart (function) handler for drag start
- onend (function) handler for drag end
- mcontext (object) #optional context for moving handler
- scontext (object) #optional context for drag start handler
- econtext (object) #optional context for drag end handler
* Additionaly following `drag` events will be triggered: `drag.start.<id>` on start,
* `drag.end.<id>` on end and `drag.move.<id>` on every move. When element will be dragged over another element
* `drag.over.<id>` will be fired as well.
*
* Start event and start handler will be called in specified context or in context of the element with following parameters:
o x (number) x position of the mouse
o y (number) y position of the mouse
o event (object) DOM event object
* Move event and move handler will be called in specified context or in context of the element with following parameters:
o dx (number) shift by x from the start point
o dy (number) shift by y from the start point
o x (number) x position of the mouse
o y (number) y position of the mouse
o event (object) DOM event object
* End event and end handler will be called in specified context or in context of the element with following parameters:
o event (object) DOM event object
= (object) @Element
\*/
elproto.drag = function (onmove, onstart, onend, move_scope, start_scope, end_scope) {
function start(e) {
(e.originalEvent || e).preventDefault();
var x = e.clientX,
y = e.clientY,
scrollY = g.doc.documentElement.scrollTop || g.doc.body.scrollTop,
scrollX = g.doc.documentElement.scrollLeft || g.doc.body.scrollLeft;
this._drag.id = e.identifier;
if (supportsTouch && e.touches) {
var i = e.touches.length, touch;
while (i--) {
touch = e.touches[i];
this._drag.id = touch.identifier;
if (touch.identifier == this._drag.id) {
x = touch.clientX;
y = touch.clientY;
break;
}
}
}
this._drag.x = x + scrollX;
this._drag.y = y + scrollY;
!drag.length && R.mousemove(dragMove).mouseup(dragUp);
drag.push({el: this, move_scope: move_scope, start_scope: start_scope, end_scope: end_scope});
onstart && eve.on("raphael.drag.start." + this.id, onstart);
onmove && eve.on("raphael.drag.move." + this.id, onmove);
onend && eve.on("raphael.drag.end." + this.id, onend);
eve("raphael.drag.start." + this.id, start_scope || move_scope || this, e.clientX + scrollX, e.clientY + scrollY, e);
}
this._drag = {};
draggable.push({el: this, start: start});
this.mousedown(start);
return this;
};
/*\
* Element.onDragOver
[ method ]
**
* Shortcut for assigning event handler for `drag.over.<id>` event, where id is id of the element (see @Element.id).
> Parameters
- f (function) handler for event, first argument would be the element you are dragging over
\*/
elproto.onDragOver = function (f) {
f ? eve.on("raphael.drag.over." + this.id, f) : eve.unbind("raphael.drag.over." + this.id);
};
/*\
* Element.undrag
[ method ]
**
* Removes all drag event handlers from given element.
\*/
elproto.undrag = function () {
var i = draggable.length;
while (i--) if (draggable[i].el == this) {
this.unmousedown(draggable[i].start);
draggable.splice(i, 1);
eve.unbind("raphael.drag.*." + this.id);
}
!draggable.length && R.unmousemove(dragMove).unmouseup(dragUp);
drag = [];
};
/*\
* Paper.circle
[ method ]
**
* Draws a circle.
**
> Parameters
**
- x (number) x coordinate of the centre
- y (number) y coordinate of the centre
- r (number) radius
= (object) Raphaël element object with type “circle”
**
> Usage
| var c = paper.circle(50, 50, 40);
\*/
paperproto.circle = function (x, y, r) {
var out = R._engine.circle(this, x || 0, y || 0, r || 0);
this.__set__ && this.__set__.push(out);
return out;
};
/*\
* Paper.rect
[ method ]
*
* Draws a rectangle.
**
> Parameters
**
- x (number) x coordinate of the top left corner
- y (number) y coordinate of the top left corner
- width (number) width
- height (number) height
- r (number) #optional radius for rounded corners, default is 0
= (object) Raphaël element object with type “rect”
**
> Usage
| // regular rectangle
| var c = paper.rect(10, 10, 50, 50);
| // rectangle with rounded corners
| var c = paper.rect(40, 40, 50, 50, 10);
\*/
paperproto.rect = function (x, y, w, h, r) {
var out = R._engine.rect(this, x || 0, y || 0, w || 0, h || 0, r || 0);
this.__set__ && this.__set__.push(out);
return out;
};
/*\
* Paper.ellipse
[ method ]
**
* Draws an ellipse.
**
> Parameters
**
- x (number) x coordinate of the centre
- y (number) y coordinate of the centre
- rx (number) horizontal radius
- ry (number) vertical radius
= (object) Raphaël element object with type “ellipse”
**
> Usage
| var c = paper.ellipse(50, 50, 40, 20);
\*/
paperproto.ellipse = function (x, y, rx, ry) {
var out = R._engine.ellipse(this, x || 0, y || 0, rx || 0, ry || 0);
this.__set__ && this.__set__.push(out);
return out;
};
/*\
* Paper.path
[ method ]
**
* Creates a path element by given path data string.
> Parameters
- pathString (string) #optional path string in SVG format.
* Path string consists of one-letter commands, followed by comma seprarated arguments in numercal form. Example:
| "M10,20L30,40"
* Here we can see two commands: “M”, with arguments `(10, 20)` and “L” with arguments `(30, 40)`. Upper case letter mean command is absolute, lower case—relative.
*
# <p>Here is short list of commands available, for more details see <a href="http://www.w3.org/TR/SVG/paths.html#PathData" title="Details of a path's data attribute's format are described in the SVG specification.">SVG path string format</a>.</p>
# <table><thead><tr><th>Command</th><th>Name</th><th>Parameters</th></tr></thead><tbody>
# <tr><td>M</td><td>moveto</td><td>(x y)+</td></tr>
# <tr><td>Z</td><td>closepath</td><td>(none)</td></tr>
# <tr><td>L</td><td>lineto</td><td>(x y)+</td></tr>
# <tr><td>H</td><td>horizontal lineto</td><td>x+</td></tr>
# <tr><td>V</td><td>vertical lineto</td><td>y+</td></tr>
# <tr><td>C</td><td>curveto</td><td>(x1 y1 x2 y2 x y)+</td></tr>
# <tr><td>S</td><td>smooth curveto</td><td>(x2 y2 x y)+</td></tr>
# <tr><td>Q</td><td>quadratic Bézier curveto</td><td>(x1 y1 x y)+</td></tr>
# <tr><td>T</td><td>smooth quadratic Bézier curveto</td><td>(x y)+</td></tr>
# <tr><td>A</td><td>elliptical arc</td><td>(rx ry x-axis-rotation large-arc-flag sweep-flag x y)+</td></tr>
# <tr><td>R</td><td><a href="http://en.wikipedia.org/wiki/Catmull–Rom_spline#Catmull.E2.80.93Rom_spline">Catmull-Rom curveto</a>*</td><td>x1 y1 (x y)+</td></tr></tbody></table>
* * “Catmull-Rom curveto” is a not standard SVG command and added in 2.0 to make life easier.
* Note: there is a special case when path consist of just three commands: “M10,10R…z”. In this case path will smoothly connects to its beginning.
> Usage
| var c = paper.path("M10 10L90 90");
| // draw a diagonal line:
| // move to 10,10, line to 90,90
* For example of path strings, check out these icons: http://raphaeljs.com/icons/
\*/
paperproto.path = function (pathString) {
pathString && !R.is(pathString, string) && !R.is(pathString[0], array) && (pathString += E);
var out = R._engine.path(R.format[apply](R, arguments), this);
this.__set__ && this.__set__.push(out);
return out;
};
/*\
* Paper.image
[ method ]
**
* Embeds an image into the surface.
**
> Parameters
**
- src (string) URI of the source image
- x (number) x coordinate position
- y (number) y coordinate position
- width (number) width of the image
- height (number) height of the image
= (object) Raphaël element object with type “image”
**
> Usage
| var c = paper.image("apple.png", 10, 10, 80, 80);
\*/
paperproto.image = function (src, x, y, w, h) {
var out = R._engine.image(this, src || "about:blank", x || 0, y || 0, w || 0, h || 0);
this.__set__ && this.__set__.push(out);
return out;
};
/*\
* Paper.text
[ method ]
**
* Draws a text string. If you need line breaks, put “\n” in the string.
**
> Parameters
**
- x (number) x coordinate position
- y (number) y coordinate position
- text (string) The text string to draw
= (object) Raphaël element object with type “text”
**
> Usage
| var t = paper.text(50, 50, "Raphaël\nkicks\nbutt!");
\*/
paperproto.text = function (x, y, text) {
var out = R._engine.text(this, x || 0, y || 0, Str(text));
this.__set__ && this.__set__.push(out);
return out;
};
/*\
* Paper.set
[ method ]
**
* Creates array-like object to keep and operate several elements at once.
* Warning: it doesn’t create any elements for itself in the page, it just groups existing elements.
* Sets act as pseudo elements — all methods available to an element can be used on a set.
= (object) array-like object that represents set of elements
**
> Usage
| var st = paper.set();
| st.push(
| paper.circle(10, 10, 5),
| paper.circle(30, 10, 5)
| );
| st.attr({fill: "red"}); // changes the fill of both circles
\*/
paperproto.set = function (itemsArray) {
!R.is(itemsArray, "array") && (itemsArray = Array.prototype.splice.call(arguments, 0, arguments.length));
var out = new Set(itemsArray);
this.__set__ && this.__set__.push(out);
out["paper"] = this;
out["type"] = "set";
return out;
};
/*\
* Paper.setStart
[ method ]
**
* Creates @Paper.set. All elements that will be created after calling this method and before calling
* @Paper.setFinish will be added to the set.
**
> Usage
| paper.setStart();
| paper.circle(10, 10, 5),
| paper.circle(30, 10, 5)
| var st = paper.setFinish();
| st.attr({fill: "red"}); // changes the fill of both circles
\*/
paperproto.setStart = function (set) {
this.__set__ = set || this.set();
};
/*\
* Paper.setFinish
[ method ]
**
* See @Paper.setStart. This method finishes catching and returns resulting set.
**
= (object) set
\*/
paperproto.setFinish = function (set) {
var out = this.__set__;
delete this.__set__;
return out;
};
/*\
* Paper.setSize
[ method ]
**
* If you need to change dimensions of the canvas call this method
**
> Parameters
**
- width (number) new width of the canvas
- height (number) new height of the canvas
\*/
paperproto.setSize = function (width, height) {
return R._engine.setSize.call(this, width, height);
};
/*\
* Paper.setViewBox
[ method ]
**
* Sets the view box of the paper. Practically it gives you ability to zoom and pan whole paper surface by
* specifying new boundaries.
**
> Parameters
**
- x (number) new x position, default is `0`
- y (number) new y position, default is `0`
- w (number) new width of the canvas
- h (number) new height of the canvas
- fit (boolean) `true` if you want graphics to fit into new boundary box
\*/
paperproto.setViewBox = function (x, y, w, h, fit) {
return R._engine.setViewBox.call(this, x, y, w, h, fit);
};
/*\
* Paper.top
[ property ]
**
* Points to the topmost element on the paper
\*/
/*\
* Paper.bottom
[ property ]
**
* Points to the bottom element on the paper
\*/
paperproto.top = paperproto.bottom = null;
/*\
* Paper.raphael
[ property ]
**
* Points to the @Raphael object/function
\*/
paperproto.raphael = R;
var getOffset = function (elem) {
var box = elem.getBoundingClientRect(),
doc = elem.ownerDocument,
body = doc.body,
docElem = doc.documentElement,
clientTop = docElem.clientTop || body.clientTop || 0, clientLeft = docElem.clientLeft || body.clientLeft || 0,
top = box.top + (g.win.pageYOffset || docElem.scrollTop || body.scrollTop ) - clientTop,
left = box.left + (g.win.pageXOffset || docElem.scrollLeft || body.scrollLeft) - clientLeft;
return {
y: top,
x: left
};
};
/*\
* Paper.getElementByPoint
[ method ]
**
* Returns you topmost element under given point.
**
= (object) Raphaël element object
> Parameters
**
- x (number) x coordinate from the top left corner of the window
- y (number) y coordinate from the top left corner of the window
> Usage
| paper.getElementByPoint(mouseX, mouseY).attr({stroke: "#f00"});
\*/
paperproto.getElementByPoint = function (x, y) {
var paper = this,
svg = paper.canvas,
target = g.doc.elementFromPoint(x, y);
if (g.win.opera && target.tagName == "svg") {
var so = getOffset(svg),
sr = svg.createSVGRect();
sr.x = x - so.x;
sr.y = y - so.y;
sr.width = sr.height = 1;
var hits = svg.getIntersectionList(sr, null);
if (hits.length) {
target = hits[hits.length - 1];
}
}
if (!target) {
return null;
}
while (target.parentNode && target != svg.parentNode && !target.raphael) {
target = target.parentNode;
}
target == paper.canvas.parentNode && (target = svg);
target = target && target.raphael ? paper.getById(target.raphaelid) : null;
return target;
};
/*\
* Paper.getElementsByBBox
[ method ]
**
* Returns set of elements that have an intersecting bounding box
**
> Parameters
**
- bbox (object) bbox to check with
= (object) @Set
\*/
paperproto.getElementsByBBox = function (bbox) {
var set = this.set();
this.forEach(function (el) {
if (R.isBBoxIntersect(el.getBBox(), bbox)) {
set.push(el);
}
});
return set;
};
/*\
* Paper.getById
[ method ]
**
* Returns you element by its internal ID.
**
> Parameters
**
- id (number) id
= (object) Raphaël element object
\*/
paperproto.getById = function (id) {
var bot = this.bottom;
while (bot) {
if (bot.id == id) {
return bot;
}
bot = bot.next;
}
return null;
};
/*\
* Paper.forEach
[ method ]
**
* Executes given function for each element on the paper
*
* If callback function returns `false` it will stop loop running.
**
> Parameters
**
- callback (function) function to run
- thisArg (object) context object for the callback
= (object) Paper object
> Usage
| paper.forEach(function (el) {
| el.attr({ stroke: "blue" });
| });
\*/
paperproto.forEach = function (callback, thisArg) {
var bot = this.bottom;
while (bot) {
if (callback.call(thisArg, bot) === false) {
return this;
}
bot = bot.next;
}
return this;
};
/*\
* Paper.getElementsByPoint
[ method ]
**
* Returns set of elements that have common point inside
**
> Parameters
**
- x (number) x coordinate of the point
- y (number) y coordinate of the point
= (object) @Set
\*/
paperproto.getElementsByPoint = function (x, y) {
var set = this.set();
this.forEach(function (el) {
if (el.isPointInside(x, y)) {
set.push(el);
}
});
return set;
};
function x_y() {
return this.x + S + this.y;
}
function x_y_w_h() {
return this.x + S + this.y + S + this.width + " \xd7 " + this.height;
}
/*\
* Element.isPointInside
[ method ]
**
* Determine if given point is inside this element’s shape
**
> Parameters
**
- x (number) x coordinate of the point
- y (number) y coordinate of the point
= (boolean) `true` if point inside the shape
\*/
elproto.isPointInside = function (x, y) {
var rp = this.realPath = getPath[this.type](this);
if (this.attr('transform') && this.attr('transform').length) {
rp = R.transformPath(rp, this.attr('transform'));
}
return R.isPointInsidePath(rp, x, y);
};
/*\
* Element.getBBox
[ method ]
**
* Return bounding box for a given element
**
> Parameters
**
- isWithoutTransform (boolean) flag, `true` if you want to have bounding box before transformations. Default is `false`.
= (object) Bounding box object:
o {
o x: (number) top left corner x
o y: (number) top left corner y
o x2: (number) bottom right corner x
o y2: (number) bottom right corner y
o width: (number) width
o height: (number) height
o }
\*/
elproto.getBBox = function (isWithoutTransform) {
if (this.removed) {
return {};
}
var _ = this._;
if (isWithoutTransform) {
if (_.dirty || !_.bboxwt) {
this.realPath = getPath[this.type](this);
_.bboxwt = pathDimensions(this.realPath);
_.bboxwt.toString = x_y_w_h;
_.dirty = 0;
}
return _.bboxwt;
}
if (_.dirty || _.dirtyT || !_.bbox) {
if (_.dirty || !this.realPath) {
_.bboxwt = 0;
this.realPath = getPath[this.type](this);
}
_.bbox = pathDimensions(mapPath(this.realPath, this.matrix));
_.bbox.toString = x_y_w_h;
_.dirty = _.dirtyT = 0;
}
return _.bbox;
};
/*\
* Element.clone
[ method ]
**
= (object) clone of a given element
**
\*/
elproto.clone = function () {
if (this.removed) {
return null;
}
var out = this.paper[this.type]().attr(this.attr());
this.__set__ && this.__set__.push(out);
return out;
};
/*\
* Element.glow
[ method ]
**
* Return set of elements that create glow-like effect around given element. See @Paper.set.
*
* Note: Glow is not connected to the element. If you change element attributes it won’t adjust itself.
**
> Parameters
**
- glow (object) #optional parameters object with all properties optional:
o {
o width (number) size of the glow, default is `10`
o fill (boolean) will it be filled, default is `false`
o opacity (number) opacity, default is `0.5`
o offsetx (number) horizontal offset, default is `0`
o offsety (number) vertical offset, default is `0`
o color (string) glow colour, default is `black`
o }
= (object) @Paper.set of elements that represents glow
\*/
elproto.glow = function (glow) {
if (this.type == "text") {
return null;
}
glow = glow || {};
var s = {
width: (glow.width || 10) + (+this.attr("stroke-width") || 1),
fill: glow.fill || false,
opacity: glow.opacity || .5,
offsetx: glow.offsetx || 0,
offsety: glow.offsety || 0,
color: glow.color || "#000"
},
c = s.width / 2,
r = this.paper,
out = r.set(),
path = this.realPath || getPath[this.type](this);
path = this.matrix ? mapPath(path, this.matrix) : path;
for (var i = 1; i < c + 1; i++) {
out.push(r.path(path).attr({
stroke: s.color,
fill: s.fill ? s.color : "none",
"stroke-linejoin": "round",
"stroke-linecap": "round",
"stroke-width": +(s.width / c * i).toFixed(3),
opacity: +(s.opacity / c).toFixed(3)
}));
}
return out.insertBefore(this).translate(s.offsetx, s.offsety);
};
var curveslengths = {},
getPointAtSegmentLength = function (p1x, p1y, c1x, c1y, c2x, c2y, p2x, p2y, length) {
if (length == null) {
return bezlen(p1x, p1y, c1x, c1y, c2x, c2y, p2x, p2y);
} else {
return R.findDotsAtSegment(p1x, p1y, c1x, c1y, c2x, c2y, p2x, p2y, getTatLen(p1x, p1y, c1x, c1y, c2x, c2y, p2x, p2y, length));
}
},
getLengthFactory = function (istotal, subpath) {
return function (path, length, onlystart) {
path = path2curve(path);
var x, y, p, l, sp = "", subpaths = {}, point,
len = 0;
for (var i = 0, ii = path.length; i < ii; i++) {
p = path[i];
if (p[0] == "M") {
x = +p[1];
y = +p[2];
} else {
l = getPointAtSegmentLength(x, y, p[1], p[2], p[3], p[4], p[5], p[6]);
if (len + l > length) {
if (subpath && !subpaths.start) {
point = getPointAtSegmentLength(x, y, p[1], p[2], p[3], p[4], p[5], p[6], length - len);
sp += ["C" + point.start.x, point.start.y, point.m.x, point.m.y, point.x, point.y];
if (onlystart) {return sp;}
subpaths.start = sp;
sp = ["M" + point.x, point.y + "C" + point.n.x, point.n.y, point.end.x, point.end.y, p[5], p[6]].join();
len += l;
x = +p[5];
y = +p[6];
continue;
}
if (!istotal && !subpath) {
point = getPointAtSegmentLength(x, y, p[1], p[2], p[3], p[4], p[5], p[6], length - len);
return {x: point.x, y: point.y, alpha: point.alpha};
}
}
len += l;
x = +p[5];
y = +p[6];
}
sp += p.shift() + p;
}
subpaths.end = sp;
point = istotal ? len : subpath ? subpaths : R.findDotsAtSegment(x, y, p[0], p[1], p[2], p[3], p[4], p[5], 1);
point.alpha && (point = {x: point.x, y: point.y, alpha: point.alpha});
return point;
};
};
var getTotalLength = getLengthFactory(1),
getPointAtLength = getLengthFactory(),
getSubpathsAtLength = getLengthFactory(0, 1);
/*\
* Raphael.getTotalLength
[ method ]
**
* Returns length of the given path in pixels.
**
> Parameters
**
- path (string) SVG path string.
**
= (number) length.
\*/
R.getTotalLength = getTotalLength;
/*\
* Raphael.getPointAtLength
[ method ]
**
* Return coordinates of the point located at the given length on the given path.
**
> Parameters
**
- path (string) SVG path string
- length (number)
**
= (object) representation of the point:
o {
o x: (number) x coordinate
o y: (number) y coordinate
o alpha: (number) angle of derivative
o }
\*/
R.getPointAtLength = getPointAtLength;
/*\
* Raphael.getSubpath
[ method ]
**
* Return subpath of a given path from given length to given length.
**
> Parameters
**
- path (string) SVG path string
- from (number) position of the start of the segment
- to (number) position of the end of the segment
**
= (string) pathstring for the segment
\*/
R.getSubpath = function (path, from, to) {
if (this.getTotalLength(path) - to < 1e-6) {
return getSubpathsAtLength(path, from).end;
}
var a = getSubpathsAtLength(path, to, 1);
return from ? getSubpathsAtLength(a, from).end : a;
};
/*\
* Element.getTotalLength
[ method ]
**
* Returns length of the path in pixels. Only works for element of “path” type.
= (number) length.
\*/
elproto.getTotalLength = function () {
var path = this.getPath();
if (!path) {
return;
}
if (this.node.getTotalLength) {
return this.node.getTotalLength();
}
return getTotalLength(path);
};
/*\
* Element.getPointAtLength
[ method ]
**
* Return coordinates of the point located at the given length on the given path. Only works for element of “path” type.
**
> Parameters
**
- length (number)
**
= (object) representation of the point:
o {
o x: (number) x coordinate
o y: (number) y coordinate
o alpha: (number) angle of derivative
o }
\*/
elproto.getPointAtLength = function (length) {
var path = this.getPath();
if (!path) {
return;
}
return getPointAtLength(path, length);
};
/*\
* Element.getPath
[ method ]
**
* Returns path of the element. Only works for elements of “path” type and simple elements like circle.
= (object) path
**
\*/
elproto.getPath = function () {
var path,
getPath = R._getPath[this.type];
if (this.type == "text" || this.type == "set") {
return;
}
if (getPath) {
path = getPath(this);
}
return path;
};
/*\
* Element.getSubpath
[ method ]
**
* Return subpath of a given element from given length to given length. Only works for element of “path” type.
**
> Parameters
**
- from (number) position of the start of the segment
- to (number) position of the end of the segment
**
= (string) pathstring for the segment
\*/
elproto.getSubpath = function (from, to) {
var path = this.getPath();
if (!path) {
return;
}
return R.getSubpath(path, from, to);
};
/*\
* Raphael.easing_formulas
[ property ]
**
* Object that contains easing formulas for animation. You could extend it with your own. By default it has following list of easing:
# <ul>
# <li>“linear”</li>
# <li>“<” or “easeIn” or “ease-in”</li>
# <li>“>” or “easeOut” or “ease-out”</li>
# <li>“<>” or “easeInOut” or “ease-in-out”</li>
# <li>“backIn” or “back-in”</li>
# <li>“backOut” or “back-out”</li>
# <li>“elastic”</li>
# <li>“bounce”</li>
# </ul>
# <p>See also <a href="http://raphaeljs.com/easing.html">Easing demo</a>.</p>
\*/
var ef = R.easing_formulas = {
linear: function (n) {
return n;
},
"<": function (n) {
return pow(n, 1.7);
},
">": function (n) {
return pow(n, .48);
},
"<>": function (n) {
var q = .48 - n / 1.04,
Q = math.sqrt(.1734 + q * q),
x = Q - q,
X = pow(abs(x), 1 / 3) * (x < 0 ? -1 : 1),
y = -Q - q,
Y = pow(abs(y), 1 / 3) * (y < 0 ? -1 : 1),
t = X + Y + .5;
return (1 - t) * 3 * t * t + t * t * t;
},
backIn: function (n) {
var s = 1.70158;
return n * n * ((s + 1) * n - s);
},
backOut: function (n) {
n = n - 1;
var s = 1.70158;
return n * n * ((s + 1) * n + s) + 1;
},
elastic: function (n) {
if (n == !!n) {
return n;
}
return pow(2, -10 * n) * math.sin((n - .075) * (2 * PI) / .3) + 1;
},
bounce: function (n) {
var s = 7.5625,
p = 2.75,
l;
if (n < (1 / p)) {
l = s * n * n;
} else {
if (n < (2 / p)) {
n -= (1.5 / p);
l = s * n * n + .75;
} else {
if (n < (2.5 / p)) {
n -= (2.25 / p);
l = s * n * n + .9375;
} else {
n -= (2.625 / p);
l = s * n * n + .984375;
}
}
}
return l;
}
};
ef.easeIn = ef["ease-in"] = ef["<"];
ef.easeOut = ef["ease-out"] = ef[">"];
ef.easeInOut = ef["ease-in-out"] = ef["<>"];
ef["back-in"] = ef.backIn;
ef["back-out"] = ef.backOut;
var animationElements = [],
requestAnimFrame = window.requestAnimationFrame ||
window.webkitRequestAnimationFrame ||
window.mozRequestAnimationFrame ||
window.oRequestAnimationFrame ||
window.msRequestAnimationFrame ||
function (callback) {
setTimeout(callback, 16);
},
animation = function () {
var Now = +new Date,
l = 0;
for (; l < animationElements.length; l++) {
var e = animationElements[l];
if (e.el.removed || e.paused) {
continue;
}
var time = Now - e.start,
ms = e.ms,
easing = e.easing,
from = e.from,
diff = e.diff,
to = e.to,
t = e.t,
that = e.el,
set = {},
now,
init = {},
key;
if (e.initstatus) {
time = (e.initstatus * e.anim.top - e.prev) / (e.percent - e.prev) * ms;
e.status = e.initstatus;
delete e.initstatus;
e.stop && animationElements.splice(l--, 1);
} else {
e.status = (e.prev + (e.percent - e.prev) * (time / ms)) / e.anim.top;
}
if (time < 0) {
continue;
}
if (time < ms) {
var pos = easing(time / ms);
for (var attr in from) if (from[has](attr)) {
switch (availableAnimAttrs[attr]) {
case nu:
now = +from[attr] + pos * ms * diff[attr];
break;
case "colour":
now = "rgb(" + [
upto255(round(from[attr].r + pos * ms * diff[attr].r)),
upto255(round(from[attr].g + pos * ms * diff[attr].g)),
upto255(round(from[attr].b + pos * ms * diff[attr].b))
].join(",") + ")";
break;
case "path":
now = [];
for (var i = 0, ii = from[attr].length; i < ii; i++) {
now[i] = [from[attr][i][0]];
for (var j = 1, jj = from[attr][i].length; j < jj; j++) {
now[i][j] = +from[attr][i][j] + pos * ms * diff[attr][i][j];
}
now[i] = now[i].join(S);
}
now = now.join(S);
break;
case "transform":
if (diff[attr].real) {
now = [];
for (i = 0, ii = from[attr].length; i < ii; i++) {
now[i] = [from[attr][i][0]];
for (j = 1, jj = from[attr][i].length; j < jj; j++) {
now[i][j] = from[attr][i][j] + pos * ms * diff[attr][i][j];
}
}
} else {
var get = function (i) {
return +from[attr][i] + pos * ms * diff[attr][i];
};
// now = [["r", get(2), 0, 0], ["t", get(3), get(4)], ["s", get(0), get(1), 0, 0]];
now = [["m", get(0), get(1), get(2), get(3), get(4), get(5)]];
}
break;
case "csv":
if (attr == "clip-rect") {
now = [];
i = 4;
while (i--) {
now[i] = +from[attr][i] + pos * ms * diff[attr][i];
}
}
break;
default:
var from2 = [][concat](from[attr]);
now = [];
i = that.paper.customAttributes[attr].length;
while (i--) {
now[i] = +from2[i] + pos * ms * diff[attr][i];
}
break;
}
set[attr] = now;
}
that.attr(set);
(function (id, that, anim) {
setTimeout(function () {
eve("raphael.anim.frame." + id, that, anim);
});
})(that.id, that, e.anim);
} else {
(function(f, el, a) {
setTimeout(function() {
eve("raphael.anim.frame." + el.id, el, a);
eve("raphael.anim.finish." + el.id, el, a);
R.is(f, "function") && f.call(el);
});
})(e.callback, that, e.anim);
that.attr(to);
animationElements.splice(l--, 1);
if (e.repeat > 1 && !e.next) {
for (key in to) if (to[has](key)) {
init[key] = e.totalOrigin[key];
}
e.el.attr(init);
runAnimation(e.anim, e.el, e.anim.percents[0], null, e.totalOrigin, e.repeat - 1);
}
if (e.next && !e.stop) {
runAnimation(e.anim, e.el, e.next, null, e.totalOrigin, e.repeat);
}
}
}
R.svg && that && that.paper && that.paper.safari();
animationElements.length && requestAnimFrame(animation);
},
upto255 = function (color) {
return color > 255 ? 255 : color < 0 ? 0 : color;
};
/*\
* Element.animateWith
[ method ]
**
* Acts similar to @Element.animate, but ensure that given animation runs in sync with another given element.
**
> Parameters
**
- el (object) element to sync with
- anim (object) animation to sync with
- params (object) #optional final attributes for the element, see also @Element.attr
- ms (number) #optional number of milliseconds for animation to run
- easing (string) #optional easing type. Accept on of @Raphael.easing_formulas or CSS format: `cubic‐bezier(XX, XX, XX, XX)`
- callback (function) #optional callback function. Will be called at the end of animation.
* or
- element (object) element to sync with
- anim (object) animation to sync with
- animation (object) #optional animation object, see @Raphael.animation
**
= (object) original element
\*/
elproto.animateWith = function (el, anim, params, ms, easing, callback) {
var element = this;
if (element.removed) {
callback && callback.call(element);
return element;
}
var a = params instanceof Animation ? params : R.animation(params, ms, easing, callback),
x, y;
runAnimation(a, element, a.percents[0], null, element.attr());
for (var i = 0, ii = animationElements.length; i < ii; i++) {
if (animationElements[i].anim == anim && animationElements[i].el == el) {
animationElements[ii - 1].start = animationElements[i].start;
break;
}
}
return element;
//
//
// var a = params ? R.animation(params, ms, easing, callback) : anim,
// status = element.status(anim);
// return this.animate(a).status(a, status * anim.ms / a.ms);
};
function CubicBezierAtTime(t, p1x, p1y, p2x, p2y, duration) {
var cx = 3 * p1x,
bx = 3 * (p2x - p1x) - cx,
ax = 1 - cx - bx,
cy = 3 * p1y,
by = 3 * (p2y - p1y) - cy,
ay = 1 - cy - by;
function sampleCurveX(t) {
return ((ax * t + bx) * t + cx) * t;
}
function solve(x, epsilon) {
var t = solveCurveX(x, epsilon);
return ((ay * t + by) * t + cy) * t;
}
function solveCurveX(x, epsilon) {
var t0, t1, t2, x2, d2, i;
for(t2 = x, i = 0; i < 8; i++) {
x2 = sampleCurveX(t2) - x;
if (abs(x2) < epsilon) {
return t2;
}
d2 = (3 * ax * t2 + 2 * bx) * t2 + cx;
if (abs(d2) < 1e-6) {
break;
}
t2 = t2 - x2 / d2;
}
t0 = 0;
t1 = 1;
t2 = x;
if (t2 < t0) {
return t0;
}
if (t2 > t1) {
return t1;
}
while (t0 < t1) {
x2 = sampleCurveX(t2);
if (abs(x2 - x) < epsilon) {
return t2;
}
if (x > x2) {
t0 = t2;
} else {
t1 = t2;
}
t2 = (t1 - t0) / 2 + t0;
}
return t2;
}
return solve(t, 1 / (200 * duration));
}
elproto.onAnimation = function (f) {
f ? eve.on("raphael.anim.frame." + this.id, f) : eve.unbind("raphael.anim.frame." + this.id);
return this;
};
function Animation(anim, ms) {
var percents = [],
newAnim = {};
this.ms = ms;
this.times = 1;
if (anim) {
for (var attr in anim) if (anim[has](attr)) {
newAnim[toFloat(attr)] = anim[attr];
percents.push(toFloat(attr));
}
percents.sort(sortByNumber);
}
this.anim = newAnim;
this.top = percents[percents.length - 1];
this.percents = percents;
}
/*\
* Animation.delay
[ method ]
**
* Creates a copy of existing animation object with given delay.
**
> Parameters
**
- delay (number) number of ms to pass between animation start and actual animation
**
= (object) new altered Animation object
| var anim = Raphael.animation({cx: 10, cy: 20}, 2e3);
| circle1.animate(anim); // run the given animation immediately
| circle2.animate(anim.delay(500)); // run the given animation after 500 ms
\*/
Animation.prototype.delay = function (delay) {
var a = new Animation(this.anim, this.ms);
a.times = this.times;
a.del = +delay || 0;
return a;
};
/*\
* Animation.repeat
[ method ]
**
* Creates a copy of existing animation object with given repetition.
**
> Parameters
**
- repeat (number) number iterations of animation. For infinite animation pass `Infinity`
**
= (object) new altered Animation object
\*/
Animation.prototype.repeat = function (times) {
var a = new Animation(this.anim, this.ms);
a.del = this.del;
a.times = math.floor(mmax(times, 0)) || 1;
return a;
};
function runAnimation(anim, element, percent, status, totalOrigin, times) {
percent = toFloat(percent);
var params,
isInAnim,
isInAnimSet,
percents = [],
next,
prev,
timestamp,
ms = anim.ms,
from = {},
to = {},
diff = {};
if (status) {
for (i = 0, ii = animationElements.length; i < ii; i++) {
var e = animationElements[i];
if (e.el.id == element.id && e.anim == anim) {
if (e.percent != percent) {
animationElements.splice(i, 1);
isInAnimSet = 1;
} else {
isInAnim = e;
}
element.attr(e.totalOrigin);
break;
}
}
} else {
status = +to; // NaN
}
for (var i = 0, ii = anim.percents.length; i < ii; i++) {
if (anim.percents[i] == percent || anim.percents[i] > status * anim.top) {
percent = anim.percents[i];
prev = anim.percents[i - 1] || 0;
ms = ms / anim.top * (percent - prev);
next = anim.percents[i + 1];
params = anim.anim[percent];
break;
} else if (status) {
element.attr(anim.anim[anim.percents[i]]);
}
}
if (!params) {
return;
}
if (!isInAnim) {
for (var attr in params) if (params[has](attr)) {
if (availableAnimAttrs[has](attr) || element.paper.customAttributes[has](attr)) {
from[attr] = element.attr(attr);
(from[attr] == null) && (from[attr] = availableAttrs[attr]);
to[attr] = params[attr];
switch (availableAnimAttrs[attr]) {
case nu:
diff[attr] = (to[attr] - from[attr]) / ms;
break;
case "colour":
from[attr] = R.getRGB(from[attr]);
var toColour = R.getRGB(to[attr]);
diff[attr] = {
r: (toColour.r - from[attr].r) / ms,
g: (toColour.g - from[attr].g) / ms,
b: (toColour.b - from[attr].b) / ms
};
break;
case "path":
var pathes = path2curve(from[attr], to[attr]),
toPath = pathes[1];
from[attr] = pathes[0];
diff[attr] = [];
for (i = 0, ii = from[attr].length; i < ii; i++) {
diff[attr][i] = [0];
for (var j = 1, jj = from[attr][i].length; j < jj; j++) {
diff[attr][i][j] = (toPath[i][j] - from[attr][i][j]) / ms;
}
}
break;
case "transform":
var _ = element._,
eq = equaliseTransform(_[attr], to[attr]);
if (eq) {
from[attr] = eq.from;
to[attr] = eq.to;
diff[attr] = [];
diff[attr].real = true;
for (i = 0, ii = from[attr].length; i < ii; i++) {
diff[attr][i] = [from[attr][i][0]];
for (j = 1, jj = from[attr][i].length; j < jj; j++) {
diff[attr][i][j] = (to[attr][i][j] - from[attr][i][j]) / ms;
}
}
} else {
var m = (element.matrix || new Matrix),
to2 = {
_: {transform: _.transform},
getBBox: function () {
return element.getBBox(1);
}
};
from[attr] = [
m.a,
m.b,
m.c,
m.d,
m.e,
m.f
];
extractTransform(to2, to[attr]);
to[attr] = to2._.transform;
diff[attr] = [
(to2.matrix.a - m.a) / ms,
(to2.matrix.b - m.b) / ms,
(to2.matrix.c - m.c) / ms,
(to2.matrix.d - m.d) / ms,
(to2.matrix.e - m.e) / ms,
(to2.matrix.f - m.f) / ms
];
// from[attr] = [_.sx, _.sy, _.deg, _.dx, _.dy];
// var to2 = {_:{}, getBBox: function () { return element.getBBox(); }};
// extractTransform(to2, to[attr]);
// diff[attr] = [
// (to2._.sx - _.sx) / ms,
// (to2._.sy - _.sy) / ms,
// (to2._.deg - _.deg) / ms,
// (to2._.dx - _.dx) / ms,
// (to2._.dy - _.dy) / ms
// ];
}
break;
case "csv":
var values = Str(params[attr])[split](separator),
from2 = Str(from[attr])[split](separator);
if (attr == "clip-rect") {
from[attr] = from2;
diff[attr] = [];
i = from2.length;
while (i--) {
diff[attr][i] = (values[i] - from[attr][i]) / ms;
}
}
to[attr] = values;
break;
default:
values = [][concat](params[attr]);
from2 = [][concat](from[attr]);
diff[attr] = [];
i = element.paper.customAttributes[attr].length;
while (i--) {
diff[attr][i] = ((values[i] || 0) - (from2[i] || 0)) / ms;
}
break;
}
}
}
var easing = params.easing,
easyeasy = R.easing_formulas[easing];
if (!easyeasy) {
easyeasy = Str(easing).match(bezierrg);
if (easyeasy && easyeasy.length == 5) {
var curve = easyeasy;
easyeasy = function (t) {
return CubicBezierAtTime(t, +curve[1], +curve[2], +curve[3], +curve[4], ms);
};
} else {
easyeasy = pipe;
}
}
timestamp = params.start || anim.start || +new Date;
e = {
anim: anim,
percent: percent,
timestamp: timestamp,
start: timestamp + (anim.del || 0),
status: 0,
initstatus: status || 0,
stop: false,
ms: ms,
easing: easyeasy,
from: from,
diff: diff,
to: to,
el: element,
callback: params.callback,
prev: prev,
next: next,
repeat: times || anim.times,
origin: element.attr(),
totalOrigin: totalOrigin
};
animationElements.push(e);
if (status && !isInAnim && !isInAnimSet) {
e.stop = true;
e.start = new Date - ms * status;
if (animationElements.length == 1) {
return animation();
}
}
if (isInAnimSet) {
e.start = new Date - e.ms * status;
}
animationElements.length == 1 && requestAnimFrame(animation);
} else {
isInAnim.initstatus = status;
isInAnim.start = new Date - isInAnim.ms * status;
}
eve("raphael.anim.start." + element.id, element, anim);
}
/*\
* Raphael.animation
[ method ]
**
* Creates an animation object that can be passed to the @Element.animate or @Element.animateWith methods.
* See also @Animation.delay and @Animation.repeat methods.
**
> Parameters
**
- params (object) final attributes for the element, see also @Element.attr
- ms (number) number of milliseconds for animation to run
- easing (string) #optional easing type. Accept one of @Raphael.easing_formulas or CSS format: `cubic‐bezier(XX, XX, XX, XX)`
- callback (function) #optional callback function. Will be called at the end of animation.
**
= (object) @Animation
\*/
R.animation = function (params, ms, easing, callback) {
if (params instanceof Animation) {
return params;
}
if (R.is(easing, "function") || !easing) {
callback = callback || easing || null;
easing = null;
}
params = Object(params);
ms = +ms || 0;
var p = {},
json,
attr;
for (attr in params) if (params[has](attr) && toFloat(attr) != attr && toFloat(attr) + "%" != attr) {
json = true;
p[attr] = params[attr];
}
if (!json) {
return new Animation(params, ms);
} else {
easing && (p.easing = easing);
callback && (p.callback = callback);
return new Animation({100: p}, ms);
}
};
/*\
* Element.animate
[ method ]
**
* Creates and starts animation for given element.
**
> Parameters
**
- params (object) final attributes for the element, see also @Element.attr
- ms (number) number of milliseconds for animation to run
- easing (string) #optional easing type. Accept one of @Raphael.easing_formulas or CSS format: `cubic‐bezier(XX, XX, XX, XX)`
- callback (function) #optional callback function. Will be called at the end of animation.
* or
- animation (object) animation object, see @Raphael.animation
**
= (object) original element
\*/
elproto.animate = function (params, ms, easing, callback) {
var element = this;
if (element.removed) {
callback && callback.call(element);
return element;
}
var anim = params instanceof Animation ? params : R.animation(params, ms, easing, callback);
runAnimation(anim, element, anim.percents[0], null, element.attr());
return element;
};
/*\
* Element.setTime
[ method ]
**
* Sets the status of animation of the element in milliseconds. Similar to @Element.status method.
**
> Parameters
**
- anim (object) animation object
- value (number) number of milliseconds from the beginning of the animation
**
= (object) original element if `value` is specified
* Note, that during animation following events are triggered:
*
* On each animation frame event `anim.frame.<id>`, on start `anim.start.<id>` and on end `anim.finish.<id>`.
\*/
elproto.setTime = function (anim, value) {
if (anim && value != null) {
this.status(anim, mmin(value, anim.ms) / anim.ms);
}
return this;
};
/*\
* Element.status
[ method ]
**
* Gets or sets the status of animation of the element.
**
> Parameters
**
- anim (object) #optional animation object
- value (number) #optional 0 – 1. If specified, method works like a setter and sets the status of a given animation to the value. This will cause animation to jump to the given position.
**
= (number) status
* or
= (array) status if `anim` is not specified. Array of objects in format:
o {
o anim: (object) animation object
o status: (number) status
o }
* or
= (object) original element if `value` is specified
\*/
elproto.status = function (anim, value) {
var out = [],
i = 0,
len,
e;
if (value != null) {
runAnimation(anim, this, -1, mmin(value, 1));
return this;
} else {
len = animationElements.length;
for (; i < len; i++) {
e = animationElements[i];
if (e.el.id == this.id && (!anim || e.anim == anim)) {
if (anim) {
return e.status;
}
out.push({
anim: e.anim,
status: e.status
});
}
}
if (anim) {
return 0;
}
return out;
}
};
/*\
* Element.pause
[ method ]
**
* Stops animation of the element with ability to resume it later on.
**
> Parameters
**
- anim (object) #optional animation object
**
= (object) original element
\*/
elproto.pause = function (anim) {
for (var i = 0; i < animationElements.length; i++) if (animationElements[i].el.id == this.id && (!anim || animationElements[i].anim == anim)) {
if (eve("raphael.anim.pause." + this.id, this, animationElements[i].anim) !== false) {
animationElements[i].paused = true;
}
}
return this;
};
/*\
* Element.resume
[ method ]
**
* Resumes animation if it was paused with @Element.pause method.
**
> Parameters
**
- anim (object) #optional animation object
**
= (object) original element
\*/
elproto.resume = function (anim) {
for (var i = 0; i < animationElements.length; i++) if (animationElements[i].el.id == this.id && (!anim || animationElements[i].anim == anim)) {
var e = animationElements[i];
if (eve("raphael.anim.resume." + this.id, this, e.anim) !== false) {
delete e.paused;
this.status(e.anim, e.status);
}
}
return this;
};
/*\
* Element.stop
[ method ]
**
* Stops animation of the element.
**
> Parameters
**
- anim (object) #optional animation object
**
= (object) original element
\*/
elproto.stop = function (anim) {
for (var i = 0; i < animationElements.length; i++) if (animationElements[i].el.id == this.id && (!anim || animationElements[i].anim == anim)) {
if (eve("raphael.anim.stop." + this.id, this, animationElements[i].anim) !== false) {
animationElements.splice(i--, 1);
}
}
return this;
};
function stopAnimation(paper) {
for (var i = 0; i < animationElements.length; i++) if (animationElements[i].el.paper == paper) {
animationElements.splice(i--, 1);
}
}
eve.on("raphael.remove", stopAnimation);
eve.on("raphael.clear", stopAnimation);
elproto.toString = function () {
return "Rapha\xebl\u2019s object";
};
// Set
var Set = function (items) {
this.items = [];
this.length = 0;
this.type = "set";
if (items) {
for (var i = 0, ii = items.length; i < ii; i++) {
if (items[i] && (items[i].constructor == elproto.constructor || items[i].constructor == Set)) {
this[this.items.length] = this.items[this.items.length] = items[i];
this.length++;
}
}
}
},
setproto = Set.prototype;
/*\
* Set.push
[ method ]
**
* Adds each argument to the current set.
= (object) original element
\*/
setproto.push = function () {
var item,
len;
for (var i = 0, ii = arguments.length; i < ii; i++) {
item = arguments[i];
if (item && (item.constructor == elproto.constructor || item.constructor == Set)) {
len = this.items.length;
this[len] = this.items[len] = item;
this.length++;
}
}
return this;
};
/*\
* Set.pop
[ method ]
**
* Removes last element and returns it.
= (object) element
\*/
setproto.pop = function () {
this.length && delete this[this.length--];
return this.items.pop();
};
/*\
* Set.forEach
[ method ]
**
* Executes given function for each element in the set.
*
* If function returns `false` it will stop loop running.
**
> Parameters
**
- callback (function) function to run
- thisArg (object) context object for the callback
= (object) Set object
\*/
setproto.forEach = function (callback, thisArg) {
for (var i = 0, ii = this.items.length; i < ii; i++) {
if (callback.call(thisArg, this.items[i], i) === false) {
return this;
}
}
return this;
};
for (var method in elproto) if (elproto[has](method)) {
setproto[method] = (function (methodname) {
return function () {
var arg = arguments;
return this.forEach(function (el) {
el[methodname][apply](el, arg);
});
};
})(method);
}
setproto.attr = function (name, value) {
if (name && R.is(name, array) && R.is(name[0], "object")) {
for (var j = 0, jj = name.length; j < jj; j++) {
this.items[j].attr(name[j]);
}
} else {
for (var i = 0, ii = this.items.length; i < ii; i++) {
this.items[i].attr(name, value);
}
}
return this;
};
/*\
* Set.clear
[ method ]
**
* Removeds all elements from the set
\*/
setproto.clear = function () {
while (this.length) {
this.pop();
}
};
/*\
* Set.splice
[ method ]
**
* Removes given element from the set
**
> Parameters
**
- index (number) position of the deletion
- count (number) number of element to remove
- insertion… (object) #optional elements to insert
= (object) set elements that were deleted
\*/
setproto.splice = function (index, count, insertion) {
index = index < 0 ? mmax(this.length + index, 0) : index;
count = mmax(0, mmin(this.length - index, count));
var tail = [],
todel = [],
args = [],
i;
for (i = 2; i < arguments.length; i++) {
args.push(arguments[i]);
}
for (i = 0; i < count; i++) {
todel.push(this[index + i]);
}
for (; i < this.length - index; i++) {
tail.push(this[index + i]);
}
var arglen = args.length;
for (i = 0; i < arglen + tail.length; i++) {
this.items[index + i] = this[index + i] = i < arglen ? args[i] : tail[i - arglen];
}
i = this.items.length = this.length -= count - arglen;
while (this[i]) {
delete this[i++];
}
return new Set(todel);
};
/*\
* Set.exclude
[ method ]
**
* Removes given element from the set
**
> Parameters
**
- element (object) element to remove
= (boolean) `true` if object was found & removed from the set
\*/
setproto.exclude = function (el) {
for (var i = 0, ii = this.length; i < ii; i++) if (this[i] == el) {
this.splice(i, 1);
return true;
}
};
setproto.animate = function (params, ms, easing, callback) {
(R.is(easing, "function") || !easing) && (callback = easing || null);
var len = this.items.length,
i = len,
item,
set = this,
collector;
if (!len) {
return this;
}
callback && (collector = function () {
!--len && callback.call(set);
});
easing = R.is(easing, string) ? easing : collector;
var anim = R.animation(params, ms, easing, collector);
item = this.items[--i].animate(anim);
while (i--) {
this.items[i] && !this.items[i].removed && this.items[i].animateWith(item, anim, anim);
(this.items[i] && !this.items[i].removed) || len--;
}
return this;
};
setproto.insertAfter = function (el) {
var i = this.items.length;
while (i--) {
this.items[i].insertAfter(el);
}
return this;
};
setproto.getBBox = function () {
var x = [],
y = [],
x2 = [],
y2 = [];
for (var i = this.items.length; i--;) if (!this.items[i].removed) {
var box = this.items[i].getBBox();
x.push(box.x);
y.push(box.y);
x2.push(box.x + box.width);
y2.push(box.y + box.height);
}
x = mmin[apply](0, x);
y = mmin[apply](0, y);
x2 = mmax[apply](0, x2);
y2 = mmax[apply](0, y2);
return {
x: x,
y: y,
x2: x2,
y2: y2,
width: x2 - x,
height: y2 - y
};
};
setproto.clone = function (s) {
s = this.paper.set();
for (var i = 0, ii = this.items.length; i < ii; i++) {
s.push(this.items[i].clone());
}
return s;
};
setproto.toString = function () {
return "Rapha\xebl\u2018s set";
};
setproto.glow = function(glowConfig) {
var ret = this.paper.set();
this.forEach(function(shape, index){
var g = shape.glow(glowConfig);
if(g != null){
g.forEach(function(shape2, index2){
ret.push(shape2);
});
}
});
return ret;
};
/*\
* Set.isPointInside
[ method ]
**
* Determine if given point is inside this set’s elements
**
> Parameters
**
- x (number) x coordinate of the point
- y (number) y coordinate of the point
= (boolean) `true` if point is inside any of the set's elements
\*/
setproto.isPointInside = function (x, y) {
var isPointInside = false;
this.forEach(function (el) {
if (el.isPointInside(x, y)) {
isPointInside = true;
return false; // stop loop
}
});
return isPointInside;
};
/*\
* Raphael.registerFont
[ method ]
**
* Adds given font to the registered set of fonts for Raphaël. Should be used as an internal call from within Cufón’s font file.
* Returns original parameter, so it could be used with chaining.
# <a href="http://wiki.github.com/sorccu/cufon/about">More about Cufón and how to convert your font form TTF, OTF, etc to JavaScript file.</a>
**
> Parameters
**
- font (object) the font to register
= (object) the font you passed in
> Usage
| Cufon.registerFont(Raphael.registerFont({…}));
\*/
R.registerFont = function (font) {
if (!font.face) {
return font;
}
this.fonts = this.fonts || {};
var fontcopy = {
w: font.w,
face: {},
glyphs: {}
},
family = font.face["font-family"];
for (var prop in font.face) if (font.face[has](prop)) {
fontcopy.face[prop] = font.face[prop];
}
if (this.fonts[family]) {
this.fonts[family].push(fontcopy);
} else {
this.fonts[family] = [fontcopy];
}
if (!font.svg) {
fontcopy.face["units-per-em"] = toInt(font.face["units-per-em"], 10);
for (var glyph in font.glyphs) if (font.glyphs[has](glyph)) {
var path = font.glyphs[glyph];
fontcopy.glyphs[glyph] = {
w: path.w,
k: {},
d: path.d && "M" + path.d.replace(/[mlcxtrv]/g, function (command) {
return {l: "L", c: "C", x: "z", t: "m", r: "l", v: "c"}[command] || "M";
}) + "z"
};
if (path.k) {
for (var k in path.k) if (path[has](k)) {
fontcopy.glyphs[glyph].k[k] = path.k[k];
}
}
}
}
return font;
};
/*\
* Paper.getFont
[ method ]
**
* Finds font object in the registered fonts by given parameters. You could specify only one word from the font name, like “Myriad” for “Myriad Pro”.
**
> Parameters
**
- family (string) font family name or any word from it
- weight (string) #optional font weight
- style (string) #optional font style
- stretch (string) #optional font stretch
= (object) the font object
> Usage
| paper.print(100, 100, "Test string", paper.getFont("Times", 800), 30);
\*/
paperproto.getFont = function (family, weight, style, stretch) {
stretch = stretch || "normal";
style = style || "normal";
weight = +weight || {normal: 400, bold: 700, lighter: 300, bolder: 800}[weight] || 400;
if (!R.fonts) {
return;
}
var font = R.fonts[family];
if (!font) {
var name = new RegExp("(^|\\s)" + family.replace(/[^\w\d\s+!~.:_-]/g, E) + "(\\s|$)", "i");
for (var fontName in R.fonts) if (R.fonts[has](fontName)) {
if (name.test(fontName)) {
font = R.fonts[fontName];
break;
}
}
}
var thefont;
if (font) {
for (var i = 0, ii = font.length; i < ii; i++) {
thefont = font[i];
if (thefont.face["font-weight"] == weight && (thefont.face["font-style"] == style || !thefont.face["font-style"]) && thefont.face["font-stretch"] == stretch) {
break;
}
}
}
return thefont;
};
/*\
* Paper.print
[ method ]
**
* Creates path that represent given text written using given font at given position with given size.
* Result of the method is path element that contains whole text as a separate path.
**
> Parameters
**
- x (number) x position of the text
- y (number) y position of the text
- string (string) text to print
- font (object) font object, see @Paper.getFont
- size (number) #optional size of the font, default is `16`
- origin (string) #optional could be `"baseline"` or `"middle"`, default is `"middle"`
- letter_spacing (number) #optional number in range `-1..1`, default is `0`
- line_spacing (number) #optional number in range `1..3`, default is `1`
= (object) resulting path element, which consist of all letters
> Usage
| var txt = r.print(10, 50, "print", r.getFont("Museo"), 30).attr({fill: "#fff"});
\*/
paperproto.print = function (x, y, string, font, size, origin, letter_spacing, line_spacing) {
origin = origin || "middle"; // baseline|middle
letter_spacing = mmax(mmin(letter_spacing || 0, 1), -1);
line_spacing = mmax(mmin(line_spacing || 1, 3), 1);
var letters = Str(string)[split](E),
shift = 0,
notfirst = 0,
path = E,
scale;
R.is(font, "string") && (font = this.getFont(font));
if (font) {
scale = (size || 16) / font.face["units-per-em"];
var bb = font.face.bbox[split](separator),
top = +bb[0],
lineHeight = bb[3] - bb[1],
shifty = 0,
height = +bb[1] + (origin == "baseline" ? lineHeight + (+font.face.descent) : lineHeight / 2);
for (var i = 0, ii = letters.length; i < ii; i++) {
if (letters[i] == "\n") {
shift = 0;
curr = 0;
notfirst = 0;
shifty += lineHeight * line_spacing;
} else {
var prev = notfirst && font.glyphs[letters[i - 1]] || {},
curr = font.glyphs[letters[i]];
shift += notfirst ? (prev.w || font.w) + (prev.k && prev.k[letters[i]] || 0) + (font.w * letter_spacing) : 0;
notfirst = 1;
}
if (curr && curr.d) {
path += R.transformPath(curr.d, ["t", shift * scale, shifty * scale, "s", scale, scale, top, height, "t", (x - top) / scale, (y - height) / scale]);
}
}
}
return this.path(path).attr({
fill: "#000",
stroke: "none"
});
};
/*\
* Paper.add
[ method ]
**
* Imports elements in JSON array in format `{type: type, <attributes>}`
**
> Parameters
**
- json (array)
= (object) resulting set of imported elements
> Usage
| paper.add([
| {
| type: "circle",
| cx: 10,
| cy: 10,
| r: 5
| },
| {
| type: "rect",
| x: 10,
| y: 10,
| width: 10,
| height: 10,
| fill: "#fc0"
| }
| ]);
\*/
paperproto.add = function (json) {
if (R.is(json, "array")) {
var res = this.set(),
i = 0,
ii = json.length,
j;
for (; i < ii; i++) {
j = json[i] || {};
elements[has](j.type) && res.push(this[j.type]().attr(j));
}
}
return res;
};
/*\
* Raphael.format
[ method ]
**
* Simple format function. Replaces construction of type “`{<number>}`” to the corresponding argument.
**
> Parameters
**
- token (string) string to format
- … (string) rest of arguments will be treated as parameters for replacement
= (string) formated string
> Usage
| var x = 10,
| y = 20,
| width = 40,
| height = 50;
| // this will draw a rectangular shape equivalent to "M10,20h40v50h-40z"
| paper.path(Raphael.format("M{0},{1}h{2}v{3}h{4}z", x, y, width, height, -width));
\*/
R.format = function (token, params) {
var args = R.is(params, array) ? [0][concat](params) : arguments;
token && R.is(token, string) && args.length - 1 && (token = token.replace(formatrg, function (str, i) {
return args[++i] == null ? E : args[i];
}));
return token || E;
};
/*\
* Raphael.fullfill
[ method ]
**
* A little bit more advanced format function than @Raphael.format. Replaces construction of type “`{<name>}`” to the corresponding argument.
**
> Parameters
**
- token (string) string to format
- json (object) object which properties will be used as a replacement
= (string) formated string
> Usage
| // this will draw a rectangular shape equivalent to "M10,20h40v50h-40z"
| paper.path(Raphael.fullfill("M{x},{y}h{dim.width}v{dim.height}h{dim['negative width']}z", {
| x: 10,
| y: 20,
| dim: {
| width: 40,
| height: 50,
| "negative width": -40
| }
| }));
\*/
R.fullfill = (function () {
var tokenRegex = /\{([^\}]+)\}/g,
objNotationRegex = /(?:(?:^|\.)(.+?)(?=\[|\.|$|\()|\[('|")(.+?)\2\])(\(\))?/g, // matches .xxxxx or ["xxxxx"] to run over object properties
replacer = function (all, key, obj) {
var res = obj;
key.replace(objNotationRegex, function (all, name, quote, quotedName, isFunc) {
name = name || quotedName;
if (res) {
if (name in res) {
res = res[name];
}
typeof res == "function" && isFunc && (res = res());
}
});
res = (res == null || res == obj ? all : res) + "";
return res;
};
return function (str, obj) {
return String(str).replace(tokenRegex, function (all, key) {
return replacer(all, key, obj);
});
};
})();
/*\
* Raphael.ninja
[ method ]
**
* If you want to leave no trace of Raphaël (Well, Raphaël creates only one global variable `Raphael`, but anyway.) You can use `ninja` method.
* Beware, that in this case plugins could stop working, because they are depending on global variable existance.
**
= (object) Raphael object
> Usage
| (function (local_raphael) {
| var paper = local_raphael(10, 10, 320, 200);
| …
| })(Raphael.ninja());
\*/
R.ninja = function () {
oldRaphael.was ? (g.win.Raphael = oldRaphael.is) : delete Raphael;
return R;
};
/*\
* Raphael.st
[ property (object) ]
**
* You can add your own method to elements and sets. It is wise to add a set method for each element method
* you added, so you will be able to call the same method on sets too.
**
* See also @Raphael.el.
> Usage
| Raphael.el.red = function () {
| this.attr({fill: "#f00"});
| };
| Raphael.st.red = function () {
| this.forEach(function (el) {
| el.red();
| });
| };
| // then use it
| paper.set(paper.circle(100, 100, 20), paper.circle(110, 100, 20)).red();
\*/
R.st = setproto;
// Firefox <3.6 fix: http://webreflection.blogspot.com/2009/11/195-chars-to-help-lazy-loading.html
(function (doc, loaded, f) {
if (doc.readyState == null && doc.addEventListener){
doc.addEventListener(loaded, f = function () {
doc.removeEventListener(loaded, f, false);
doc.readyState = "complete";
}, false);
doc.readyState = "loading";
}
function isLoaded() {
(/in/).test(doc.readyState) ? setTimeout(isLoaded, 9) : R.eve("raphael.DOMload");
}
isLoaded();
})(document, "DOMContentLoaded");
eve.on("raphael.DOMload", function () {
loaded = true;
});
// ┌─────────────────────────────────────────────────────────────────────┐ \\
// │ Raphaël - JavaScript Vector Library │ \\
// ├─────────────────────────────────────────────────────────────────────┤ \\
// │ SVG Module │ \\
// ├─────────────────────────────────────────────────────────────────────┤ \\
// │ Copyright (c) 2008-2011 Dmitry Baranovskiy (http://raphaeljs.com) │ \\
// │ Copyright (c) 2008-2011 Sencha Labs (http://sencha.com) │ \\
// │ Licensed under the MIT (http://raphaeljs.com/license.html) license. │ \\
// └─────────────────────────────────────────────────────────────────────┘ \\
(function(){
if (!R.svg) {
return;
}
var has = "hasOwnProperty",
Str = String,
toFloat = parseFloat,
toInt = parseInt,
math = Math,
mmax = math.max,
abs = math.abs,
pow = math.pow,
separator = /[, ]+/,
eve = R.eve,
E = "",
S = " ";
var xlink = "http://www.w3.org/1999/xlink",
markers = {
block: "M5,0 0,2.5 5,5z",
classic: "M5,0 0,2.5 5,5 3.5,3 3.5,2z",
diamond: "M2.5,0 5,2.5 2.5,5 0,2.5z",
open: "M6,1 1,3.5 6,6",
oval: "M2.5,0A2.5,2.5,0,0,1,2.5,5 2.5,2.5,0,0,1,2.5,0z"
},
markerCounter = {};
R.toString = function () {
return "Your browser supports SVG.\nYou are running Rapha\xebl " + this.version;
};
var $ = function (el, attr) {
if (attr) {
if (typeof el == "string") {
el = $(el);
}
for (var key in attr) if (attr[has](key)) {
if (key.substring(0, 6) == "xlink:") {
el.setAttributeNS(xlink, key.substring(6), Str(attr[key]));
} else {
el.setAttribute(key, Str(attr[key]));
}
}
} else {
el = R._g.doc.createElementNS("http://www.w3.org/2000/svg", el);
el.style && (el.style.webkitTapHighlightColor = "rgba(0,0,0,0)");
}
return el;
},
addGradientFill = function (element, gradient) {
var type = "linear",
id = element.id + gradient,
fx = .5, fy = .5,
o = element.node,
SVG = element.paper,
s = o.style,
el = R._g.doc.getElementById(id);
if (!el) {
gradient = Str(gradient).replace(R._radial_gradient, function (all, _fx, _fy) {
type = "radial";
if (_fx && _fy) {
fx = toFloat(_fx);
fy = toFloat(_fy);
var dir = ((fy > .5) * 2 - 1);
pow(fx - .5, 2) + pow(fy - .5, 2) > .25 &&
(fy = math.sqrt(.25 - pow(fx - .5, 2)) * dir + .5) &&
fy != .5 &&
(fy = fy.toFixed(5) - 1e-5 * dir);
}
return E;
});
gradient = gradient.split(/\s*\-\s*/);
if (type == "linear") {
var angle = gradient.shift();
angle = -toFloat(angle);
if (isNaN(angle)) {
return null;
}
var vector = [0, 0, math.cos(R.rad(angle)), math.sin(R.rad(angle))],
max = 1 / (mmax(abs(vector[2]), abs(vector[3])) || 1);
vector[2] *= max;
vector[3] *= max;
if (vector[2] < 0) {
vector[0] = -vector[2];
vector[2] = 0;
}
if (vector[3] < 0) {
vector[1] = -vector[3];
vector[3] = 0;
}
}
var dots = R._parseDots(gradient);
if (!dots) {
return null;
}
id = id.replace(/[\(\)\s,\xb0#]/g, "_");
if (element.gradient && id != element.gradient.id) {
SVG.defs.removeChild(element.gradient);
delete element.gradient;
}
if (!element.gradient) {
el = $(type + "Gradient", {id: id});
element.gradient = el;
$(el, type == "radial" ? {
fx: fx,
fy: fy
} : {
x1: vector[0],
y1: vector[1],
x2: vector[2],
y2: vector[3],
gradientTransform: element.matrix.invert()
});
SVG.defs.appendChild(el);
for (var i = 0, ii = dots.length; i < ii; i++) {
el.appendChild($("stop", {
offset: dots[i].offset ? dots[i].offset : i ? "100%" : "0%",
"stop-color": dots[i].color || "#fff"
}));
}
}
}
$(o, {
fill: "url(#" + id + ")",
opacity: 1,
"fill-opacity": 1
});
s.fill = E;
s.opacity = 1;
s.fillOpacity = 1;
return 1;
},
updatePosition = function (o) {
var bbox = o.getBBox(1);
$(o.pattern, {patternTransform: o.matrix.invert() + " translate(" + bbox.x + "," + bbox.y + ")"});
},
addArrow = function (o, value, isEnd) {
if (o.type == "path") {
var values = Str(value).toLowerCase().split("-"),
p = o.paper,
se = isEnd ? "end" : "start",
node = o.node,
attrs = o.attrs,
stroke = attrs["stroke-width"],
i = values.length,
type = "classic",
from,
to,
dx,
refX,
attr,
w = 3,
h = 3,
t = 5;
while (i--) {
switch (values[i]) {
case "block":
case "classic":
case "oval":
case "diamond":
case "open":
case "none":
type = values[i];
break;
case "wide": h = 5; break;
case "narrow": h = 2; break;
case "long": w = 5; break;
case "short": w = 2; break;
}
}
if (type == "open") {
w += 2;
h += 2;
t += 2;
dx = 1;
refX = isEnd ? 4 : 1;
attr = {
fill: "none",
stroke: attrs.stroke
};
} else {
refX = dx = w / 2;
attr = {
fill: attrs.stroke,
stroke: "none"
};
}
if (o._.arrows) {
if (isEnd) {
o._.arrows.endPath && markerCounter[o._.arrows.endPath]--;
o._.arrows.endMarker && markerCounter[o._.arrows.endMarker]--;
} else {
o._.arrows.startPath && markerCounter[o._.arrows.startPath]--;
o._.arrows.startMarker && markerCounter[o._.arrows.startMarker]--;
}
} else {
o._.arrows = {};
}
if (type != "none") {
var pathId = "raphael-marker-" + type,
markerId = "raphael-marker-" + se + type + w + h;
if (!R._g.doc.getElementById(pathId)) {
p.defs.appendChild($($("path"), {
"stroke-linecap": "round",
d: markers[type],
id: pathId
}));
markerCounter[pathId] = 1;
} else {
markerCounter[pathId]++;
}
var marker = R._g.doc.getElementById(markerId),
use;
if (!marker) {
marker = $($("marker"), {
id: markerId,
markerHeight: h,
markerWidth: w,
orient: "auto",
refX: refX,
refY: h / 2
});
use = $($("use"), {
"xlink:href": "#" + pathId,
transform: (isEnd ? "rotate(180 " + w / 2 + " " + h / 2 + ") " : E) + "scale(" + w / t + "," + h / t + ")",
"stroke-width": (1 / ((w / t + h / t) / 2)).toFixed(4)
});
marker.appendChild(use);
p.defs.appendChild(marker);
markerCounter[markerId] = 1;
} else {
markerCounter[markerId]++;
use = marker.getElementsByTagName("use")[0];
}
$(use, attr);
var delta = dx * (type != "diamond" && type != "oval");
if (isEnd) {
from = o._.arrows.startdx * stroke || 0;
to = R.getTotalLength(attrs.path) - delta * stroke;
} else {
from = delta * stroke;
to = R.getTotalLength(attrs.path) - (o._.arrows.enddx * stroke || 0);
}
attr = {};
attr["marker-" + se] = "url(#" + markerId + ")";
if (to || from) {
attr.d = R.getSubpath(attrs.path, from, to);
}
$(node, attr);
o._.arrows[se + "Path"] = pathId;
o._.arrows[se + "Marker"] = markerId;
o._.arrows[se + "dx"] = delta;
o._.arrows[se + "Type"] = type;
o._.arrows[se + "String"] = value;
} else {
if (isEnd) {
from = o._.arrows.startdx * stroke || 0;
to = R.getTotalLength(attrs.path) - from;
} else {
from = 0;
to = R.getTotalLength(attrs.path) - (o._.arrows.enddx * stroke || 0);
}
o._.arrows[se + "Path"] && $(node, {d: R.getSubpath(attrs.path, from, to)});
delete o._.arrows[se + "Path"];
delete o._.arrows[se + "Marker"];
delete o._.arrows[se + "dx"];
delete o._.arrows[se + "Type"];
delete o._.arrows[se + "String"];
}
for (attr in markerCounter) if (markerCounter[has](attr) && !markerCounter[attr]) {
var item = R._g.doc.getElementById(attr);
item && item.parentNode.removeChild(item);
}
}
},
dasharray = {
"": [0],
"none": [0],
"-": [3, 1],
".": [1, 1],
"-.": [3, 1, 1, 1],
"-..": [3, 1, 1, 1, 1, 1],
". ": [1, 3],
"- ": [4, 3],
"--": [8, 3],
"- .": [4, 3, 1, 3],
"--.": [8, 3, 1, 3],
"--..": [8, 3, 1, 3, 1, 3]
},
addDashes = function (o, value, params) {
value = dasharray[Str(value).toLowerCase()];
if (value) {
var width = o.attrs["stroke-width"] || "1",
butt = {round: width, square: width, butt: 0}[o.attrs["stroke-linecap"] || params["stroke-linecap"]] || 0,
dashes = [],
i = value.length;
while (i--) {
dashes[i] = value[i] * width + ((i % 2) ? 1 : -1) * butt;
}
$(o.node, {"stroke-dasharray": dashes.join(",")});
}
},
setFillAndStroke = function (o, params) {
var node = o.node,
attrs = o.attrs,
vis = node.style.visibility;
node.style.visibility = "hidden";
for (var att in params) {
if (params[has](att)) {
if (!R._availableAttrs[has](att)) {
continue;
}
var value = params[att];
attrs[att] = value;
switch (att) {
case "blur":
o.blur(value);
break;
case "title":
var title = node.getElementsByTagName("title");
// Use the existing <title>.
if (title.length && (title = title[0])) {
title.firstChild.nodeValue = value;
} else {
title = $("title");
var val = R._g.doc.createTextNode(value);
title.appendChild(val);
node.appendChild(title);
}
break;
case "href":
case "target":
var pn = node.parentNode;
if (pn.tagName.toLowerCase() != "a") {
var hl = $("a");
pn.insertBefore(hl, node);
hl.appendChild(node);
pn = hl;
}
if (att == "target") {
pn.setAttributeNS(xlink, "show", value == "blank" ? "new" : value);
} else {
pn.setAttributeNS(xlink, att, value);
}
break;
case "cursor":
node.style.cursor = value;
break;
case "transform":
o.transform(value);
break;
case "arrow-start":
addArrow(o, value);
break;
case "arrow-end":
addArrow(o, value, 1);
break;
case "clip-rect":
var rect = Str(value).split(separator);
if (rect.length == 4) {
o.clip && o.clip.parentNode.parentNode.removeChild(o.clip.parentNode);
var el = $("clipPath"),
rc = $("rect");
el.id = R.createUUID();
$(rc, {
x: rect[0],
y: rect[1],
width: rect[2],
height: rect[3]
});
el.appendChild(rc);
o.paper.defs.appendChild(el);
$(node, {"clip-path": "url(#" + el.id + ")"});
o.clip = rc;
}
if (!value) {
var path = node.getAttribute("clip-path");
if (path) {
var clip = R._g.doc.getElementById(path.replace(/(^url\(#|\)$)/g, E));
clip && clip.parentNode.removeChild(clip);
$(node, {"clip-path": E});
delete o.clip;
}
}
break;
case "path":
if (o.type == "path") {
$(node, {d: value ? attrs.path = R._pathToAbsolute(value) : "M0,0"});
o._.dirty = 1;
if (o._.arrows) {
"startString" in o._.arrows && addArrow(o, o._.arrows.startString);
"endString" in o._.arrows && addArrow(o, o._.arrows.endString, 1);
}
}
break;
case "width":
node.setAttribute(att, value);
o._.dirty = 1;
if (attrs.fx) {
att = "x";
value = attrs.x;
} else {
break;
}
case "x":
if (attrs.fx) {
value = -attrs.x - (attrs.width || 0);
}
case "rx":
if (att == "rx" && o.type == "rect") {
break;
}
case "cx":
node.setAttribute(att, value);
o.pattern && updatePosition(o);
o._.dirty = 1;
break;
case "height":
node.setAttribute(att, value);
o._.dirty = 1;
if (attrs.fy) {
att = "y";
value = attrs.y;
} else {
break;
}
case "y":
if (attrs.fy) {
value = -attrs.y - (attrs.height || 0);
}
case "ry":
if (att == "ry" && o.type == "rect") {
break;
}
case "cy":
node.setAttribute(att, value);
o.pattern && updatePosition(o);
o._.dirty = 1;
break;
case "r":
if (o.type == "rect") {
$(node, {rx: value, ry: value});
} else {
node.setAttribute(att, value);
}
o._.dirty = 1;
break;
case "src":
if (o.type == "image") {
node.setAttributeNS(xlink, "href", value);
}
break;
case "stroke-width":
if (o._.sx != 1 || o._.sy != 1) {
value /= mmax(abs(o._.sx), abs(o._.sy)) || 1;
}
if (o.paper._vbSize) {
value *= o.paper._vbSize;
}
node.setAttribute(att, value);
if (attrs["stroke-dasharray"]) {
addDashes(o, attrs["stroke-dasharray"], params);
}
if (o._.arrows) {
"startString" in o._.arrows && addArrow(o, o._.arrows.startString);
"endString" in o._.arrows && addArrow(o, o._.arrows.endString, 1);
}
break;
case "stroke-dasharray":
addDashes(o, value, params);
break;
case "fill":
var isURL = Str(value).match(R._ISURL);
if (isURL) {
el = $("pattern");
var ig = $("image");
el.id = R.createUUID();
$(el, {x: 0, y: 0, patternUnits: "userSpaceOnUse", height: 1, width: 1});
$(ig, {x: 0, y: 0, "xlink:href": isURL[1]});
el.appendChild(ig);
(function (el) {
R._preload(isURL[1], function () {
var w = this.offsetWidth,
h = this.offsetHeight;
$(el, {width: w, height: h});
$(ig, {width: w, height: h});
o.paper.safari();
});
})(el);
o.paper.defs.appendChild(el);
$(node, {fill: "url(#" + el.id + ")"});
o.pattern = el;
o.pattern && updatePosition(o);
break;
}
var clr = R.getRGB(value);
if (!clr.error) {
delete params.gradient;
delete attrs.gradient;
!R.is(attrs.opacity, "undefined") &&
R.is(params.opacity, "undefined") &&
$(node, {opacity: attrs.opacity});
!R.is(attrs["fill-opacity"], "undefined") &&
R.is(params["fill-opacity"], "undefined") &&
$(node, {"fill-opacity": attrs["fill-opacity"]});
} else if ((o.type == "circle" || o.type == "ellipse" || Str(value).charAt() != "r") && addGradientFill(o, value)) {
if ("opacity" in attrs || "fill-opacity" in attrs) {
var gradient = R._g.doc.getElementById(node.getAttribute("fill").replace(/^url\(#|\)$/g, E));
if (gradient) {
var stops = gradient.getElementsByTagName("stop");
$(stops[stops.length - 1], {"stop-opacity": ("opacity" in attrs ? attrs.opacity : 1) * ("fill-opacity" in attrs ? attrs["fill-opacity"] : 1)});
}
}
attrs.gradient = value;
attrs.fill = "none";
break;
}
clr[has]("opacity") && $(node, {"fill-opacity": clr.opacity > 1 ? clr.opacity / 100 : clr.opacity});
case "stroke":
clr = R.getRGB(value);
node.setAttribute(att, clr.hex);
att == "stroke" && clr[has]("opacity") && $(node, {"stroke-opacity": clr.opacity > 1 ? clr.opacity / 100 : clr.opacity});
if (att == "stroke" && o._.arrows) {
"startString" in o._.arrows && addArrow(o, o._.arrows.startString);
"endString" in o._.arrows && addArrow(o, o._.arrows.endString, 1);
}
break;
case "gradient":
(o.type == "circle" || o.type == "ellipse" || Str(value).charAt() != "r") && addGradientFill(o, value);
break;
case "opacity":
if (attrs.gradient && !attrs[has]("stroke-opacity")) {
$(node, {"stroke-opacity": value > 1 ? value / 100 : value});
}
// fall
case "fill-opacity":
if (attrs.gradient) {
gradient = R._g.doc.getElementById(node.getAttribute("fill").replace(/^url\(#|\)$/g, E));
if (gradient) {
stops = gradient.getElementsByTagName("stop");
$(stops[stops.length - 1], {"stop-opacity": value});
}
break;
}
default:
att == "font-size" && (value = toInt(value, 10) + "px");
var cssrule = att.replace(/(\-.)/g, function (w) {
return w.substring(1).toUpperCase();
});
node.style[cssrule] = value;
o._.dirty = 1;
node.setAttribute(att, value);
break;
}
}
}
tuneText(o, params);
node.style.visibility = vis;
},
leading = 1.2,
tuneText = function (el, params) {
if (el.type != "text" || !(params[has]("text") || params[has]("font") || params[has]("font-size") || params[has]("x") || params[has]("y"))) {
return;
}
var a = el.attrs,
node = el.node,
fontSize = node.firstChild ? toInt(R._g.doc.defaultView.getComputedStyle(node.firstChild, E).getPropertyValue("font-size"), 10) : 10;
if (params[has]("text")) {
a.text = params.text;
while (node.firstChild) {
node.removeChild(node.firstChild);
}
var texts = Str(params.text).split("\n"),
tspans = [],
tspan;
for (var i = 0, ii = texts.length; i < ii; i++) {
tspan = $("tspan");
i && $(tspan, {dy: fontSize * leading, x: a.x});
tspan.appendChild(R._g.doc.createTextNode(texts[i]));
node.appendChild(tspan);
tspans[i] = tspan;
}
} else {
tspans = node.getElementsByTagName("tspan");
for (i = 0, ii = tspans.length; i < ii; i++) if (i) {
$(tspans[i], {dy: fontSize * leading, x: a.x});
} else {
$(tspans[0], {dy: 0});
}
}
$(node, {x: a.x, y: a.y});
el._.dirty = 1;
var bb = el._getBBox(),
dif = a.y - (bb.y + bb.height / 2);
dif && R.is(dif, "finite") && $(tspans[0], {dy: dif});
},
Element = function (node, svg) {
var X = 0,
Y = 0;
/*\
* Element.node
[ property (object) ]
**
* Gives you a reference to the DOM object, so you can assign event handlers or just mess around.
**
* Note: Don’t mess with it.
> Usage
| // draw a circle at coordinate 10,10 with radius of 10
| var c = paper.circle(10, 10, 10);
| c.node.onclick = function () {
| c.attr("fill", "red");
| };
\*/
this[0] = this.node = node;
/*\
* Element.raphael
[ property (object) ]
**
* Internal reference to @Raphael object. In case it is not available.
> Usage
| Raphael.el.red = function () {
| var hsb = this.paper.raphael.rgb2hsb(this.attr("fill"));
| hsb.h = 1;
| this.attr({fill: this.paper.raphael.hsb2rgb(hsb).hex});
| }
\*/
node.raphael = true;
/*\
* Element.id
[ property (number) ]
**
* Unique id of the element. Especially usesful when you want to listen to events of the element,
* because all events are fired in format `<module>.<action>.<id>`. Also useful for @Paper.getById method.
\*/
this.id = R._oid++;
node.raphaelid = this.id;
this.matrix = R.matrix();
this.realPath = null;
/*\
* Element.paper
[ property (object) ]
**
* Internal reference to “paper” where object drawn. Mainly for use in plugins and element extensions.
> Usage
| Raphael.el.cross = function () {
| this.attr({fill: "red"});
| this.paper.path("M10,10L50,50M50,10L10,50")
| .attr({stroke: "red"});
| }
\*/
this.paper = svg;
this.attrs = this.attrs || {};
this._ = {
transform: [],
sx: 1,
sy: 1,
deg: 0,
dx: 0,
dy: 0,
dirty: 1
};
!svg.bottom && (svg.bottom = this);
/*\
* Element.prev
[ property (object) ]
**
* Reference to the previous element in the hierarchy.
\*/
this.prev = svg.top;
svg.top && (svg.top.next = this);
svg.top = this;
/*\
* Element.next
[ property (object) ]
**
* Reference to the next element in the hierarchy.
\*/
this.next = null;
},
elproto = R.el;
Element.prototype = elproto;
elproto.constructor = Element;
R._engine.path = function (pathString, SVG) {
var el = $("path");
SVG.canvas && SVG.canvas.appendChild(el);
var p = new Element(el, SVG);
p.type = "path";
setFillAndStroke(p, {
fill: "none",
stroke: "#000",
path: pathString
});
return p;
};
/*\
* Element.rotate
[ method ]
**
* Deprecated! Use @Element.transform instead.
* Adds rotation by given angle around given point to the list of
* transformations of the element.
> Parameters
- deg (number) angle in degrees
- cx (number) #optional x coordinate of the centre of rotation
- cy (number) #optional y coordinate of the centre of rotation
* If cx & cy aren’t specified centre of the shape is used as a point of rotation.
= (object) @Element
\*/
elproto.rotate = function (deg, cx, cy) {
if (this.removed) {
return this;
}
deg = Str(deg).split(separator);
if (deg.length - 1) {
cx = toFloat(deg[1]);
cy = toFloat(deg[2]);
}
deg = toFloat(deg[0]);
(cy == null) && (cx = cy);
if (cx == null || cy == null) {
var bbox = this.getBBox(1);
cx = bbox.x + bbox.width / 2;
cy = bbox.y + bbox.height / 2;
}
this.transform(this._.transform.concat([["r", deg, cx, cy]]));
return this;
};
/*\
* Element.scale
[ method ]
**
* Deprecated! Use @Element.transform instead.
* Adds scale by given amount relative to given point to the list of
* transformations of the element.
> Parameters
- sx (number) horisontal scale amount
- sy (number) vertical scale amount
- cx (number) #optional x coordinate of the centre of scale
- cy (number) #optional y coordinate of the centre of scale
* If cx & cy aren’t specified centre of the shape is used instead.
= (object) @Element
\*/
elproto.scale = function (sx, sy, cx, cy) {
if (this.removed) {
return this;
}
sx = Str(sx).split(separator);
if (sx.length - 1) {
sy = toFloat(sx[1]);
cx = toFloat(sx[2]);
cy = toFloat(sx[3]);
}
sx = toFloat(sx[0]);
(sy == null) && (sy = sx);
(cy == null) && (cx = cy);
if (cx == null || cy == null) {
var bbox = this.getBBox(1);
}
cx = cx == null ? bbox.x + bbox.width / 2 : cx;
cy = cy == null ? bbox.y + bbox.height / 2 : cy;
this.transform(this._.transform.concat([["s", sx, sy, cx, cy]]));
return this;
};
/*\
* Element.translate
[ method ]
**
* Deprecated! Use @Element.transform instead.
* Adds translation by given amount to the list of transformations of the element.
> Parameters
- dx (number) horisontal shift
- dy (number) vertical shift
= (object) @Element
\*/
elproto.translate = function (dx, dy) {
if (this.removed) {
return this;
}
dx = Str(dx).split(separator);
if (dx.length - 1) {
dy = toFloat(dx[1]);
}
dx = toFloat(dx[0]) || 0;
dy = +dy || 0;
this.transform(this._.transform.concat([["t", dx, dy]]));
return this;
};
/*\
* Element.transform
[ method ]
**
* Adds transformation to the element which is separate to other attributes,
* i.e. translation doesn’t change `x` or `y` of the rectange. The format
* of transformation string is similar to the path string syntax:
| "t100,100r30,100,100s2,2,100,100r45s1.5"
* Each letter is a command. There are four commands: `t` is for translate, `r` is for rotate, `s` is for
* scale and `m` is for matrix.
*
* There are also alternative “absolute” translation, rotation and scale: `T`, `R` and `S`. They will not take previous transformation into account. For example, `...T100,0` will always move element 100 px horisontally, while `...t100,0` could move it vertically if there is `r90` before. Just compare results of `r90t100,0` and `r90T100,0`.
*
* So, the example line above could be read like “translate by 100, 100; rotate 30° around 100, 100; scale twice around 100, 100;
* rotate 45° around centre; scale 1.5 times relative to centre”. As you can see rotate and scale commands have origin
* coordinates as optional parameters, the default is the centre point of the element.
* Matrix accepts six parameters.
> Usage
| var el = paper.rect(10, 20, 300, 200);
| // translate 100, 100, rotate 45°, translate -100, 0
| el.transform("t100,100r45t-100,0");
| // if you want you can append or prepend transformations
| el.transform("...t50,50");
| el.transform("s2...");
| // or even wrap
| el.transform("t50,50...t-50-50");
| // to reset transformation call method with empty string
| el.transform("");
| // to get current value call it without parameters
| console.log(el.transform());
> Parameters
- tstr (string) #optional transformation string
* If tstr isn’t specified
= (string) current transformation string
* else
= (object) @Element
\*/
elproto.transform = function (tstr) {
var _ = this._;
if (tstr == null) {
return _.transform;
}
R._extractTransform(this, tstr);
this.clip && $(this.clip, {transform: this.matrix.invert()});
this.pattern && updatePosition(this);
this.node && $(this.node, {transform: this.matrix});
if (_.sx != 1 || _.sy != 1) {
var sw = this.attrs[has]("stroke-width") ? this.attrs["stroke-width"] : 1;
this.attr({"stroke-width": sw});
}
return this;
};
/*\
* Element.hide
[ method ]
**
* Makes element invisible. See @Element.show.
= (object) @Element
\*/
elproto.hide = function () {
!this.removed && this.paper.safari(this.node.style.display = "none");
return this;
};
/*\
* Element.show
[ method ]
**
* Makes element visible. See @Element.hide.
= (object) @Element
\*/
elproto.show = function () {
!this.removed && this.paper.safari(this.node.style.display = "");
return this;
};
/*\
* Element.remove
[ method ]
**
* Removes element from the paper.
\*/
elproto.remove = function () {
if (this.removed || !this.node.parentNode) {
return;
}
var paper = this.paper;
paper.__set__ && paper.__set__.exclude(this);
eve.unbind("raphael.*.*." + this.id);
if (this.gradient) {
paper.defs.removeChild(this.gradient);
}
R._tear(this, paper);
if (this.node.parentNode.tagName.toLowerCase() == "a") {
this.node.parentNode.parentNode.removeChild(this.node.parentNode);
} else {
this.node.parentNode.removeChild(this.node);
}
for (var i in this) {
this[i] = typeof this[i] == "function" ? R._removedFactory(i) : null;
}
this.removed = true;
};
elproto._getBBox = function () {
if (this.node.style.display == "none") {
this.show();
var hide = true;
}
var bbox = {};
try {
bbox = this.node.getBBox();
} catch(e) {
// Firefox 3.0.x plays badly here
} finally {
bbox = bbox || {};
}
hide && this.hide();
return bbox;
};
/*\
* Element.attr
[ method ]
**
* Sets the attributes of the element.
> Parameters
- attrName (string) attribute’s name
- value (string) value
* or
- params (object) object of name/value pairs
* or
- attrName (string) attribute’s name
* or
- attrNames (array) in this case method returns array of current values for given attribute names
= (object) @Element if attrsName & value or params are passed in.
= (...) value of the attribute if only attrsName is passed in.
= (array) array of values of the attribute if attrsNames is passed in.
= (object) object of attributes if nothing is passed in.
> Possible parameters
# <p>Please refer to the <a href="http://www.w3.org/TR/SVG/" title="The W3C Recommendation for the SVG language describes these properties in detail.">SVG specification</a> for an explanation of these parameters.</p>
o arrow-end (string) arrowhead on the end of the path. The format for string is `<type>[-<width>[-<length>]]`. Possible types: `classic`, `block`, `open`, `oval`, `diamond`, `none`, width: `wide`, `narrow`, `medium`, length: `long`, `short`, `midium`.
o clip-rect (string) comma or space separated values: x, y, width and height
o cursor (string) CSS type of the cursor
o cx (number) the x-axis coordinate of the center of the circle, or ellipse
o cy (number) the y-axis coordinate of the center of the circle, or ellipse
o fill (string) colour, gradient or image
o fill-opacity (number)
o font (string)
o font-family (string)
o font-size (number) font size in pixels
o font-weight (string)
o height (number)
o href (string) URL, if specified element behaves as hyperlink
o opacity (number)
o path (string) SVG path string format
o r (number) radius of the circle, ellipse or rounded corner on the rect
o rx (number) horisontal radius of the ellipse
o ry (number) vertical radius of the ellipse
o src (string) image URL, only works for @Element.image element
o stroke (string) stroke colour
o stroke-dasharray (string) [“”, “`-`”, “`.`”, “`-.`”, “`-..`”, “`. `”, “`- `”, “`--`”, “`- .`”, “`--.`”, “`--..`”]
o stroke-linecap (string) [“`butt`”, “`square`”, “`round`”]
o stroke-linejoin (string) [“`bevel`”, “`round`”, “`miter`”]
o stroke-miterlimit (number)
o stroke-opacity (number)
o stroke-width (number) stroke width in pixels, default is '1'
o target (string) used with href
o text (string) contents of the text element. Use `\n` for multiline text
o text-anchor (string) [“`start`”, “`middle`”, “`end`”], default is “`middle`”
o title (string) will create tooltip with a given text
o transform (string) see @Element.transform
o width (number)
o x (number)
o y (number)
> Gradients
* Linear gradient format: “`‹angle›-‹colour›[-‹colour›[:‹offset›]]*-‹colour›`”, example: “`90-#fff-#000`” – 90°
* gradient from white to black or “`0-#fff-#f00:20-#000`” – 0° gradient from white via red (at 20%) to black.
*
* radial gradient: “`r[(‹fx›, ‹fy›)]‹colour›[-‹colour›[:‹offset›]]*-‹colour›`”, example: “`r#fff-#000`” –
* gradient from white to black or “`r(0.25, 0.75)#fff-#000`” – gradient from white to black with focus point
* at 0.25, 0.75. Focus point coordinates are in 0..1 range. Radial gradients can only be applied to circles and ellipses.
> Path String
# <p>Please refer to <a href="http://www.w3.org/TR/SVG/paths.html#PathData" title="Details of a path’s data attribute’s format are described in the SVG specification.">SVG documentation regarding path string</a>. Raphaël fully supports it.</p>
> Colour Parsing
# <ul>
# <li>Colour name (“<code>red</code>”, “<code>green</code>”, “<code>cornflowerblue</code>”, etc)</li>
# <li>#••• — shortened HTML colour: (“<code>#000</code>”, “<code>#fc0</code>”, etc)</li>
# <li>#•••••• — full length HTML colour: (“<code>#000000</code>”, “<code>#bd2300</code>”)</li>
# <li>rgb(•••, •••, •••) — red, green and blue channels’ values: (“<code>rgb(200, 100, 0)</code>”)</li>
# <li>rgb(•••%, •••%, •••%) — same as above, but in %: (“<code>rgb(100%, 175%, 0%)</code>”)</li>
# <li>rgba(•••, •••, •••, •••) — red, green and blue channels’ values: (“<code>rgba(200, 100, 0, .5)</code>”)</li>
# <li>rgba(•••%, •••%, •••%, •••%) — same as above, but in %: (“<code>rgba(100%, 175%, 0%, 50%)</code>”)</li>
# <li>hsb(•••, •••, •••) — hue, saturation and brightness values: (“<code>hsb(0.5, 0.25, 1)</code>”)</li>
# <li>hsb(•••%, •••%, •••%) — same as above, but in %</li>
# <li>hsba(•••, •••, •••, •••) — same as above, but with opacity</li>
# <li>hsl(•••, •••, •••) — almost the same as hsb, see <a href="http://en.wikipedia.org/wiki/HSL_and_HSV" title="HSL and HSV - Wikipedia, the free encyclopedia">Wikipedia page</a></li>
# <li>hsl(•••%, •••%, •••%) — same as above, but in %</li>
# <li>hsla(•••, •••, •••, •••) — same as above, but with opacity</li>
# <li>Optionally for hsb and hsl you could specify hue as a degree: “<code>hsl(240deg, 1, .5)</code>” or, if you want to go fancy, “<code>hsl(240°, 1, .5)</code>”</li>
# </ul>
\*/
elproto.attr = function (name, value) {
if (this.removed) {
return this;
}
if (name == null) {
var res = {};
for (var a in this.attrs) if (this.attrs[has](a)) {
res[a] = this.attrs[a];
}
res.gradient && res.fill == "none" && (res.fill = res.gradient) && delete res.gradient;
res.transform = this._.transform;
return res;
}
if (value == null && R.is(name, "string")) {
if (name == "fill" && this.attrs.fill == "none" && this.attrs.gradient) {
return this.attrs.gradient;
}
if (name == "transform") {
return this._.transform;
}
var names = name.split(separator),
out = {};
for (var i = 0, ii = names.length; i < ii; i++) {
name = names[i];
if (name in this.attrs) {
out[name] = this.attrs[name];
} else if (R.is(this.paper.customAttributes[name], "function")) {
out[name] = this.paper.customAttributes[name].def;
} else {
out[name] = R._availableAttrs[name];
}
}
return ii - 1 ? out : out[names[0]];
}
if (value == null && R.is(name, "array")) {
out = {};
for (i = 0, ii = name.length; i < ii; i++) {
out[name[i]] = this.attr(name[i]);
}
return out;
}
if (value != null) {
var params = {};
params[name] = value;
} else if (name != null && R.is(name, "object")) {
params = name;
}
for (var key in params) {
eve("raphael.attr." + key + "." + this.id, this, params[key]);
}
for (key in this.paper.customAttributes) if (this.paper.customAttributes[has](key) && params[has](key) && R.is(this.paper.customAttributes[key], "function")) {
var par = this.paper.customAttributes[key].apply(this, [].concat(params[key]));
this.attrs[key] = params[key];
for (var subkey in par) if (par[has](subkey)) {
params[subkey] = par[subkey];
}
}
setFillAndStroke(this, params);
return this;
};
/*\
* Element.toFront
[ method ]
**
* Moves the element so it is the closest to the viewer’s eyes, on top of other elements.
= (object) @Element
\*/
elproto.toFront = function () {
if (this.removed) {
return this;
}
if (this.node.parentNode.tagName.toLowerCase() == "a") {
this.node.parentNode.parentNode.appendChild(this.node.parentNode);
} else {
this.node.parentNode.appendChild(this.node);
}
var svg = this.paper;
svg.top != this && R._tofront(this, svg);
return this;
};
/*\
* Element.toBack
[ method ]
**
* Moves the element so it is the furthest from the viewer’s eyes, behind other elements.
= (object) @Element
\*/
elproto.toBack = function () {
if (this.removed) {
return this;
}
var parent = this.node.parentNode;
if (parent.tagName.toLowerCase() == "a") {
parent.parentNode.insertBefore(this.node.parentNode, this.node.parentNode.parentNode.firstChild);
} else if (parent.firstChild != this.node) {
parent.insertBefore(this.node, this.node.parentNode.firstChild);
}
R._toback(this, this.paper);
var svg = this.paper;
return this;
};
/*\
* Element.insertAfter
[ method ]
**
* Inserts current object after the given one.
= (object) @Element
\*/
elproto.insertAfter = function (element) {
if (this.removed) {
return this;
}
var node = element.node || element[element.length - 1].node;
if (node.nextSibling) {
node.parentNode.insertBefore(this.node, node.nextSibling);
} else {
node.parentNode.appendChild(this.node);
}
R._insertafter(this, element, this.paper);
return this;
};
/*\
* Element.insertBefore
[ method ]
**
* Inserts current object before the given one.
= (object) @Element
\*/
elproto.insertBefore = function (element) {
if (this.removed) {
return this;
}
var node = element.node || element[0].node;
node.parentNode.insertBefore(this.node, node);
R._insertbefore(this, element, this.paper);
return this;
};
elproto.blur = function (size) {
// Experimental. No Safari support. Use it on your own risk.
var t = this;
if (+size !== 0) {
var fltr = $("filter"),
blur = $("feGaussianBlur");
t.attrs.blur = size;
fltr.id = R.createUUID();
$(blur, {stdDeviation: +size || 1.5});
fltr.appendChild(blur);
t.paper.defs.appendChild(fltr);
t._blur = fltr;
$(t.node, {filter: "url(#" + fltr.id + ")"});
} else {
if (t._blur) {
t._blur.parentNode.removeChild(t._blur);
delete t._blur;
delete t.attrs.blur;
}
t.node.removeAttribute("filter");
}
return t;
};
R._engine.circle = function (svg, x, y, r) {
var el = $("circle");
svg.canvas && svg.canvas.appendChild(el);
var res = new Element(el, svg);
res.attrs = {cx: x, cy: y, r: r, fill: "none", stroke: "#000"};
res.type = "circle";
$(el, res.attrs);
return res;
};
R._engine.rect = function (svg, x, y, w, h, r) {
var el = $("rect");
svg.canvas && svg.canvas.appendChild(el);
var res = new Element(el, svg);
res.attrs = {x: x, y: y, width: w, height: h, r: r || 0, rx: r || 0, ry: r || 0, fill: "none", stroke: "#000"};
res.type = "rect";
$(el, res.attrs);
return res;
};
R._engine.ellipse = function (svg, x, y, rx, ry) {
var el = $("ellipse");
svg.canvas && svg.canvas.appendChild(el);
var res = new Element(el, svg);
res.attrs = {cx: x, cy: y, rx: rx, ry: ry, fill: "none", stroke: "#000"};
res.type = "ellipse";
$(el, res.attrs);
return res;
};
R._engine.image = function (svg, src, x, y, w, h) {
var el = $("image");
$(el, {x: x, y: y, width: w, height: h, preserveAspectRatio: "xMinYMin"});
el.setAttributeNS(xlink, "href", src);
svg.canvas && svg.canvas.appendChild(el);
var res = new Element(el, svg);
res.attrs = {x: x, y: y, width: w, height: h, src: src};
res.type = "image";
return res;
};
R._engine.text = function (svg, x, y, text) {
var el = $("text");
svg.canvas && svg.canvas.appendChild(el);
var res = new Element(el, svg);
res.attrs = {
x: x,
y: y,
"text-anchor": "middle",
text: text,
font: R._availableAttrs.font,
stroke: "none",
fill: "#000"
};
res.type = "text";
setFillAndStroke(res, res.attrs);
return res;
};
R._engine.setSize = function (width, height) {
this.width = width || this.width;
this.height = height || this.height;
this.canvas.setAttribute("width", this.width);
this.canvas.setAttribute("height", this.height);
if (this._viewBox) {
this.setViewBox.apply(this, this._viewBox);
}
return this;
};
R._engine.create = function () {
var con = R._getContainer.apply(0, arguments),
container = con && con.container,
x = con.x,
y = con.y,
width = con.width,
height = con.height;
if (!container) {
throw new Error("SVG container not found.");
}
var cnvs = $("svg"),
css = "overflow:hidden;",
isFloating;
x = x || 0;
y = y || 0;
width = width || 512;
height = height || 342;
$(cnvs, {
height: height,
version: 1.1,
width: width,
xmlns: "http://www.w3.org/2000/svg"
});
if (container == 1) {
cnvs.style.cssText = css + "position:absolute;left:" + x + "px;top:" + y + "px";
R._g.doc.body.appendChild(cnvs);
isFloating = 1;
} else {
cnvs.style.cssText = css + "position:relative";
if (container.firstChild) {
container.insertBefore(cnvs, container.firstChild);
} else {
container.appendChild(cnvs);
}
}
container = new R._Paper;
container.width = width;
container.height = height;
container.canvas = cnvs;
container.clear();
container._left = container._top = 0;
isFloating && (container.renderfix = function () {});
container.renderfix();
return container;
};
R._engine.setViewBox = function (x, y, w, h, fit) {
eve("raphael.setViewBox", this, this._viewBox, [x, y, w, h, fit]);
var size = mmax(w / this.width, h / this.height),
top = this.top,
aspectRatio = fit ? "meet" : "xMinYMin",
vb,
sw;
if (x == null) {
if (this._vbSize) {
size = 1;
}
delete this._vbSize;
vb = "0 0 " + this.width + S + this.height;
} else {
this._vbSize = size;
vb = x + S + y + S + w + S + h;
}
$(this.canvas, {
viewBox: vb,
preserveAspectRatio: aspectRatio
});
while (size && top) {
sw = "stroke-width" in top.attrs ? top.attrs["stroke-width"] : 1;
top.attr({"stroke-width": sw});
top._.dirty = 1;
top._.dirtyT = 1;
top = top.prev;
}
this._viewBox = [x, y, w, h, !!fit];
return this;
};
/*\
* Paper.renderfix
[ method ]
**
* Fixes the issue of Firefox and IE9 regarding subpixel rendering. If paper is dependant
* on other elements after reflow it could shift half pixel which cause for lines to lost their crispness.
* This method fixes the issue.
**
Special thanks to Mariusz Nowak (http://www.medikoo.com/) for this method.
\*/
R.prototype.renderfix = function () {
var cnvs = this.canvas,
s = cnvs.style,
pos;
try {
pos = cnvs.getScreenCTM() || cnvs.createSVGMatrix();
} catch (e) {
pos = cnvs.createSVGMatrix();
}
var left = -pos.e % 1,
top = -pos.f % 1;
if (left || top) {
if (left) {
this._left = (this._left + left) % 1;
s.left = this._left + "px";
}
if (top) {
this._top = (this._top + top) % 1;
s.top = this._top + "px";
}
}
};
/*\
* Paper.clear
[ method ]
**
* Clears the paper, i.e. removes all the elements.
\*/
R.prototype.clear = function () {
R.eve("raphael.clear", this);
var c = this.canvas;
while (c.firstChild) {
c.removeChild(c.firstChild);
}
this.bottom = this.top = null;
(this.desc = $("desc")).appendChild(R._g.doc.createTextNode("Created with Rapha\xebl " + R.version));
c.appendChild(this.desc);
c.appendChild(this.defs = $("defs"));
};
/*\
* Paper.remove
[ method ]
**
* Removes the paper from the DOM.
\*/
R.prototype.remove = function () {
eve("raphael.remove", this);
this.canvas.parentNode && this.canvas.parentNode.removeChild(this.canvas);
for (var i in this) {
this[i] = typeof this[i] == "function" ? R._removedFactory(i) : null;
}
};
var setproto = R.st;
for (var method in elproto) if (elproto[has](method) && !setproto[has](method)) {
setproto[method] = (function (methodname) {
return function () {
var arg = arguments;
return this.forEach(function (el) {
el[methodname].apply(el, arg);
});
};
})(method);
}
})();
// ┌─────────────────────────────────────────────────────────────────────┐ \\
// │ Raphaël - JavaScript Vector Library │ \\
// ├─────────────────────────────────────────────────────────────────────┤ \\
// │ VML Module │ \\
// ├─────────────────────────────────────────────────────────────────────┤ \\
// │ Copyright (c) 2008-2011 Dmitry Baranovskiy (http://raphaeljs.com) │ \\
// │ Copyright (c) 2008-2011 Sencha Labs (http://sencha.com) │ \\
// │ Licensed under the MIT (http://raphaeljs.com/license.html) license. │ \\
// └─────────────────────────────────────────────────────────────────────┘ \\
(function(){
if (!R.vml) {
return;
}
var has = "hasOwnProperty",
Str = String,
toFloat = parseFloat,
math = Math,
round = math.round,
mmax = math.max,
mmin = math.min,
abs = math.abs,
fillString = "fill",
separator = /[, ]+/,
eve = R.eve,
ms = " progid:DXImageTransform.Microsoft",
S = " ",
E = "",
map = {M: "m", L: "l", C: "c", Z: "x", m: "t", l: "r", c: "v", z: "x"},
bites = /([clmz]),?([^clmz]*)/gi,
blurregexp = / progid:\S+Blur\([^\)]+\)/g,
val = /-?[^,\s-]+/g,
cssDot = "position:absolute;left:0;top:0;width:1px;height:1px",
zoom = 21600,
pathTypes = {path: 1, rect: 1, image: 1},
ovalTypes = {circle: 1, ellipse: 1},
path2vml = function (path) {
var total = /[ahqstv]/ig,
command = R._pathToAbsolute;
Str(path).match(total) && (command = R._path2curve);
total = /[clmz]/g;
if (command == R._pathToAbsolute && !Str(path).match(total)) {
var res = Str(path).replace(bites, function (all, command, args) {
var vals = [],
isMove = command.toLowerCase() == "m",
res = map[command];
args.replace(val, function (value) {
if (isMove && vals.length == 2) {
res += vals + map[command == "m" ? "l" : "L"];
vals = [];
}
vals.push(round(value * zoom));
});
return res + vals;
});
return res;
}
var pa = command(path), p, r;
res = [];
for (var i = 0, ii = pa.length; i < ii; i++) {
p = pa[i];
r = pa[i][0].toLowerCase();
r == "z" && (r = "x");
for (var j = 1, jj = p.length; j < jj; j++) {
r += round(p[j] * zoom) + (j != jj - 1 ? "," : E);
}
res.push(r);
}
return res.join(S);
},
compensation = function (deg, dx, dy) {
var m = R.matrix();
m.rotate(-deg, .5, .5);
return {
dx: m.x(dx, dy),
dy: m.y(dx, dy)
};
},
setCoords = function (p, sx, sy, dx, dy, deg) {
var _ = p._,
m = p.matrix,
fillpos = _.fillpos,
o = p.node,
s = o.style,
y = 1,
flip = "",
dxdy,
kx = zoom / sx,
ky = zoom / sy;
s.visibility = "hidden";
if (!sx || !sy) {
return;
}
o.coordsize = abs(kx) + S + abs(ky);
s.rotation = deg * (sx * sy < 0 ? -1 : 1);
if (deg) {
var c = compensation(deg, dx, dy);
dx = c.dx;
dy = c.dy;
}
sx < 0 && (flip += "x");
sy < 0 && (flip += " y") && (y = -1);
s.flip = flip;
o.coordorigin = (dx * -kx) + S + (dy * -ky);
if (fillpos || _.fillsize) {
var fill = o.getElementsByTagName(fillString);
fill = fill && fill[0];
o.removeChild(fill);
if (fillpos) {
c = compensation(deg, m.x(fillpos[0], fillpos[1]), m.y(fillpos[0], fillpos[1]));
fill.position = c.dx * y + S + c.dy * y;
}
if (_.fillsize) {
fill.size = _.fillsize[0] * abs(sx) + S + _.fillsize[1] * abs(sy);
}
o.appendChild(fill);
}
s.visibility = "visible";
};
R.toString = function () {
return "Your browser doesn\u2019t support SVG. Falling down to VML.\nYou are running Rapha\xebl " + this.version;
};
var addArrow = function (o, value, isEnd) {
var values = Str(value).toLowerCase().split("-"),
se = isEnd ? "end" : "start",
i = values.length,
type = "classic",
w = "medium",
h = "medium";
while (i--) {
switch (values[i]) {
case "block":
case "classic":
case "oval":
case "diamond":
case "open":
case "none":
type = values[i];
break;
case "wide":
case "narrow": h = values[i]; break;
case "long":
case "short": w = values[i]; break;
}
}
var stroke = o.node.getElementsByTagName("stroke")[0];
stroke[se + "arrow"] = type;
stroke[se + "arrowlength"] = w;
stroke[se + "arrowwidth"] = h;
},
setFillAndStroke = function (o, params) {
// o.paper.canvas.style.display = "none";
o.attrs = o.attrs || {};
var node = o.node,
a = o.attrs,
s = node.style,
xy,
newpath = pathTypes[o.type] && (params.x != a.x || params.y != a.y || params.width != a.width || params.height != a.height || params.cx != a.cx || params.cy != a.cy || params.rx != a.rx || params.ry != a.ry || params.r != a.r),
isOval = ovalTypes[o.type] && (a.cx != params.cx || a.cy != params.cy || a.r != params.r || a.rx != params.rx || a.ry != params.ry),
res = o;
for (var par in params) if (params[has](par)) {
a[par] = params[par];
}
if (newpath) {
a.path = R._getPath[o.type](o);
o._.dirty = 1;
}
params.href && (node.href = params.href);
params.title && (node.title = params.title);
params.target && (node.target = params.target);
params.cursor && (s.cursor = params.cursor);
"blur" in params && o.blur(params.blur);
if (params.path && o.type == "path" || newpath) {
node.path = path2vml(~Str(a.path).toLowerCase().indexOf("r") ? R._pathToAbsolute(a.path) : a.path);
if (o.type == "image") {
o._.fillpos = [a.x, a.y];
o._.fillsize = [a.width, a.height];
setCoords(o, 1, 1, 0, 0, 0);
}
}
"transform" in params && o.transform(params.transform);
if (isOval) {
var cx = +a.cx,
cy = +a.cy,
rx = +a.rx || +a.r || 0,
ry = +a.ry || +a.r || 0;
node.path = R.format("ar{0},{1},{2},{3},{4},{1},{4},{1}x", round((cx - rx) * zoom), round((cy - ry) * zoom), round((cx + rx) * zoom), round((cy + ry) * zoom), round(cx * zoom));
o._.dirty = 1;
}
if ("clip-rect" in params) {
var rect = Str(params["clip-rect"]).split(separator);
if (rect.length == 4) {
rect[2] = +rect[2] + (+rect[0]);
rect[3] = +rect[3] + (+rect[1]);
var div = node.clipRect || R._g.doc.createElement("div"),
dstyle = div.style;
dstyle.clip = R.format("rect({1}px {2}px {3}px {0}px)", rect);
if (!node.clipRect) {
dstyle.position = "absolute";
dstyle.top = 0;
dstyle.left = 0;
dstyle.width = o.paper.width + "px";
dstyle.height = o.paper.height + "px";
node.parentNode.insertBefore(div, node);
div.appendChild(node);
node.clipRect = div;
}
}
if (!params["clip-rect"]) {
node.clipRect && (node.clipRect.style.clip = "auto");
}
}
if (o.textpath) {
var textpathStyle = o.textpath.style;
params.font && (textpathStyle.font = params.font);
params["font-family"] && (textpathStyle.fontFamily = '"' + params["font-family"].split(",")[0].replace(/^['"]+|['"]+$/g, E) + '"');
params["font-size"] && (textpathStyle.fontSize = params["font-size"]);
params["font-weight"] && (textpathStyle.fontWeight = params["font-weight"]);
params["font-style"] && (textpathStyle.fontStyle = params["font-style"]);
}
if ("arrow-start" in params) {
addArrow(res, params["arrow-start"]);
}
if ("arrow-end" in params) {
addArrow(res, params["arrow-end"], 1);
}
if (params.opacity != null ||
params["stroke-width"] != null ||
params.fill != null ||
params.src != null ||
params.stroke != null ||
params["stroke-width"] != null ||
params["stroke-opacity"] != null ||
params["fill-opacity"] != null ||
params["stroke-dasharray"] != null ||
params["stroke-miterlimit"] != null ||
params["stroke-linejoin"] != null ||
params["stroke-linecap"] != null) {
var fill = node.getElementsByTagName(fillString),
newfill = false;
fill = fill && fill[0];
!fill && (newfill = fill = createNode(fillString));
if (o.type == "image" && params.src) {
fill.src = params.src;
}
params.fill && (fill.on = true);
if (fill.on == null || params.fill == "none" || params.fill === null) {
fill.on = false;
}
if (fill.on && params.fill) {
var isURL = Str(params.fill).match(R._ISURL);
if (isURL) {
fill.parentNode == node && node.removeChild(fill);
fill.rotate = true;
fill.src = isURL[1];
fill.type = "tile";
var bbox = o.getBBox(1);
fill.position = bbox.x + S + bbox.y;
o._.fillpos = [bbox.x, bbox.y];
R._preload(isURL[1], function () {
o._.fillsize = [this.offsetWidth, this.offsetHeight];
});
} else {
fill.color = R.getRGB(params.fill).hex;
fill.src = E;
fill.type = "solid";
if (R.getRGB(params.fill).error && (res.type in {circle: 1, ellipse: 1} || Str(params.fill).charAt() != "r") && addGradientFill(res, params.fill, fill)) {
a.fill = "none";
a.gradient = params.fill;
fill.rotate = false;
}
}
}
if ("fill-opacity" in params || "opacity" in params) {
var opacity = ((+a["fill-opacity"] + 1 || 2) - 1) * ((+a.opacity + 1 || 2) - 1) * ((+R.getRGB(params.fill).o + 1 || 2) - 1);
opacity = mmin(mmax(opacity, 0), 1);
fill.opacity = opacity;
if (fill.src) {
fill.color = "none";
}
}
node.appendChild(fill);
var stroke = (node.getElementsByTagName("stroke") && node.getElementsByTagName("stroke")[0]),
newstroke = false;
!stroke && (newstroke = stroke = createNode("stroke"));
if ((params.stroke && params.stroke != "none") ||
params["stroke-width"] ||
params["stroke-opacity"] != null ||
params["stroke-dasharray"] ||
params["stroke-miterlimit"] ||
params["stroke-linejoin"] ||
params["stroke-linecap"]) {
stroke.on = true;
}
(params.stroke == "none" || params.stroke === null || stroke.on == null || params.stroke == 0 || params["stroke-width"] == 0) && (stroke.on = false);
var strokeColor = R.getRGB(params.stroke);
stroke.on && params.stroke && (stroke.color = strokeColor.hex);
opacity = ((+a["stroke-opacity"] + 1 || 2) - 1) * ((+a.opacity + 1 || 2) - 1) * ((+strokeColor.o + 1 || 2) - 1);
var width = (toFloat(params["stroke-width"]) || 1) * .75;
opacity = mmin(mmax(opacity, 0), 1);
params["stroke-width"] == null && (width = a["stroke-width"]);
params["stroke-width"] && (stroke.weight = width);
width && width < 1 && (opacity *= width) && (stroke.weight = 1);
stroke.opacity = opacity;
params["stroke-linejoin"] && (stroke.joinstyle = params["stroke-linejoin"] || "miter");
stroke.miterlimit = params["stroke-miterlimit"] || 8;
params["stroke-linecap"] && (stroke.endcap = params["stroke-linecap"] == "butt" ? "flat" : params["stroke-linecap"] == "square" ? "square" : "round");
if ("stroke-dasharray" in params) {
var dasharray = {
"-": "shortdash",
".": "shortdot",
"-.": "shortdashdot",
"-..": "shortdashdotdot",
". ": "dot",
"- ": "dash",
"--": "longdash",
"- .": "dashdot",
"--.": "longdashdot",
"--..": "longdashdotdot"
};
stroke.dashstyle = dasharray[has](params["stroke-dasharray"]) ? dasharray[params["stroke-dasharray"]] : E;
}
newstroke && node.appendChild(stroke);
}
if (res.type == "text") {
res.paper.canvas.style.display = E;
var span = res.paper.span,
m = 100,
fontSize = a.font && a.font.match(/\d+(?:\.\d*)?(?=px)/);
s = span.style;
a.font && (s.font = a.font);
a["font-family"] && (s.fontFamily = a["font-family"]);
a["font-weight"] && (s.fontWeight = a["font-weight"]);
a["font-style"] && (s.fontStyle = a["font-style"]);
fontSize = toFloat(a["font-size"] || fontSize && fontSize[0]) || 10;
s.fontSize = fontSize * m + "px";
res.textpath.string && (span.innerHTML = Str(res.textpath.string).replace(/</g, "<").replace(/&/g, "&").replace(/\n/g, "<br>"));
var brect = span.getBoundingClientRect();
res.W = a.w = (brect.right - brect.left) / m;
res.H = a.h = (brect.bottom - brect.top) / m;
// res.paper.canvas.style.display = "none";
res.X = a.x;
res.Y = a.y + res.H / 2;
("x" in params || "y" in params) && (res.path.v = R.format("m{0},{1}l{2},{1}", round(a.x * zoom), round(a.y * zoom), round(a.x * zoom) + 1));
var dirtyattrs = ["x", "y", "text", "font", "font-family", "font-weight", "font-style", "font-size"];
for (var d = 0, dd = dirtyattrs.length; d < dd; d++) if (dirtyattrs[d] in params) {
res._.dirty = 1;
break;
}
// text-anchor emulation
switch (a["text-anchor"]) {
case "start":
res.textpath.style["v-text-align"] = "left";
res.bbx = res.W / 2;
break;
case "end":
res.textpath.style["v-text-align"] = "right";
res.bbx = -res.W / 2;
break;
default:
res.textpath.style["v-text-align"] = "center";
res.bbx = 0;
break;
}
res.textpath.style["v-text-kern"] = true;
}
// res.paper.canvas.style.display = E;
},
addGradientFill = function (o, gradient, fill) {
o.attrs = o.attrs || {};
var attrs = o.attrs,
pow = Math.pow,
opacity,
oindex,
type = "linear",
fxfy = ".5 .5";
o.attrs.gradient = gradient;
gradient = Str(gradient).replace(R._radial_gradient, function (all, fx, fy) {
type = "radial";
if (fx && fy) {
fx = toFloat(fx);
fy = toFloat(fy);
pow(fx - .5, 2) + pow(fy - .5, 2) > .25 && (fy = math.sqrt(.25 - pow(fx - .5, 2)) * ((fy > .5) * 2 - 1) + .5);
fxfy = fx + S + fy;
}
return E;
});
gradient = gradient.split(/\s*\-\s*/);
if (type == "linear") {
var angle = gradient.shift();
angle = -toFloat(angle);
if (isNaN(angle)) {
return null;
}
}
var dots = R._parseDots(gradient);
if (!dots) {
return null;
}
o = o.shape || o.node;
if (dots.length) {
o.removeChild(fill);
fill.on = true;
fill.method = "none";
fill.color = dots[0].color;
fill.color2 = dots[dots.length - 1].color;
var clrs = [];
for (var i = 0, ii = dots.length; i < ii; i++) {
dots[i].offset && clrs.push(dots[i].offset + S + dots[i].color);
}
fill.colors = clrs.length ? clrs.join() : "0% " + fill.color;
if (type == "radial") {
fill.type = "gradientTitle";
fill.focus = "100%";
fill.focussize = "0 0";
fill.focusposition = fxfy;
fill.angle = 0;
} else {
// fill.rotate= true;
fill.type = "gradient";
fill.angle = (270 - angle) % 360;
}
o.appendChild(fill);
}
return 1;
},
Element = function (node, vml) {
this[0] = this.node = node;
node.raphael = true;
this.id = R._oid++;
node.raphaelid = this.id;
this.X = 0;
this.Y = 0;
this.attrs = {};
this.paper = vml;
this.matrix = R.matrix();
this._ = {
transform: [],
sx: 1,
sy: 1,
dx: 0,
dy: 0,
deg: 0,
dirty: 1,
dirtyT: 1
};
!vml.bottom && (vml.bottom = this);
this.prev = vml.top;
vml.top && (vml.top.next = this);
vml.top = this;
this.next = null;
};
var elproto = R.el;
Element.prototype = elproto;
elproto.constructor = Element;
elproto.transform = function (tstr) {
if (tstr == null) {
return this._.transform;
}
var vbs = this.paper._viewBoxShift,
vbt = vbs ? "s" + [vbs.scale, vbs.scale] + "-1-1t" + [vbs.dx, vbs.dy] : E,
oldt;
if (vbs) {
oldt = tstr = Str(tstr).replace(/\.{3}|\u2026/g, this._.transform || E);
}
R._extractTransform(this, vbt + tstr);
var matrix = this.matrix.clone(),
skew = this.skew,
o = this.node,
split,
isGrad = ~Str(this.attrs.fill).indexOf("-"),
isPatt = !Str(this.attrs.fill).indexOf("url(");
matrix.translate(1, 1);
if (isPatt || isGrad || this.type == "image") {
skew.matrix = "1 0 0 1";
skew.offset = "0 0";
split = matrix.split();
if ((isGrad && split.noRotation) || !split.isSimple) {
o.style.filter = matrix.toFilter();
var bb = this.getBBox(),
bbt = this.getBBox(1),
dx = bb.x - bbt.x,
dy = bb.y - bbt.y;
o.coordorigin = (dx * -zoom) + S + (dy * -zoom);
setCoords(this, 1, 1, dx, dy, 0);
} else {
o.style.filter = E;
setCoords(this, split.scalex, split.scaley, split.dx, split.dy, split.rotate);
}
} else {
o.style.filter = E;
skew.matrix = Str(matrix);
skew.offset = matrix.offset();
}
oldt && (this._.transform = oldt);
return this;
};
elproto.rotate = function (deg, cx, cy) {
if (this.removed) {
return this;
}
if (deg == null) {
return;
}
deg = Str(deg).split(separator);
if (deg.length - 1) {
cx = toFloat(deg[1]);
cy = toFloat(deg[2]);
}
deg = toFloat(deg[0]);
(cy == null) && (cx = cy);
if (cx == null || cy == null) {
var bbox = this.getBBox(1);
cx = bbox.x + bbox.width / 2;
cy = bbox.y + bbox.height / 2;
}
this._.dirtyT = 1;
this.transform(this._.transform.concat([["r", deg, cx, cy]]));
return this;
};
elproto.translate = function (dx, dy) {
if (this.removed) {
return this;
}
dx = Str(dx).split(separator);
if (dx.length - 1) {
dy = toFloat(dx[1]);
}
dx = toFloat(dx[0]) || 0;
dy = +dy || 0;
if (this._.bbox) {
this._.bbox.x += dx;
this._.bbox.y += dy;
}
this.transform(this._.transform.concat([["t", dx, dy]]));
return this;
};
elproto.scale = function (sx, sy, cx, cy) {
if (this.removed) {
return this;
}
sx = Str(sx).split(separator);
if (sx.length - 1) {
sy = toFloat(sx[1]);
cx = toFloat(sx[2]);
cy = toFloat(sx[3]);
isNaN(cx) && (cx = null);
isNaN(cy) && (cy = null);
}
sx = toFloat(sx[0]);
(sy == null) && (sy = sx);
(cy == null) && (cx = cy);
if (cx == null || cy == null) {
var bbox = this.getBBox(1);
}
cx = cx == null ? bbox.x + bbox.width / 2 : cx;
cy = cy == null ? bbox.y + bbox.height / 2 : cy;
this.transform(this._.transform.concat([["s", sx, sy, cx, cy]]));
this._.dirtyT = 1;
return this;
};
elproto.hide = function () {
!this.removed && (this.node.style.display = "none");
return this;
};
elproto.show = function () {
!this.removed && (this.node.style.display = E);
return this;
};
elproto._getBBox = function () {
if (this.removed) {
return {};
}
return {
x: this.X + (this.bbx || 0) - this.W / 2,
y: this.Y - this.H,
width: this.W,
height: this.H
};
};
elproto.remove = function () {
if (this.removed || !this.node.parentNode) {
return;
}
this.paper.__set__ && this.paper.__set__.exclude(this);
R.eve.unbind("raphael.*.*." + this.id);
R._tear(this, this.paper);
this.node.parentNode.removeChild(this.node);
this.shape && this.shape.parentNode.removeChild(this.shape);
for (var i in this) {
this[i] = typeof this[i] == "function" ? R._removedFactory(i) : null;
}
this.removed = true;
};
elproto.attr = function (name, value) {
if (this.removed) {
return this;
}
if (name == null) {
var res = {};
for (var a in this.attrs) if (this.attrs[has](a)) {
res[a] = this.attrs[a];
}
res.gradient && res.fill == "none" && (res.fill = res.gradient) && delete res.gradient;
res.transform = this._.transform;
return res;
}
if (value == null && R.is(name, "string")) {
if (name == fillString && this.attrs.fill == "none" && this.attrs.gradient) {
return this.attrs.gradient;
}
var names = name.split(separator),
out = {};
for (var i = 0, ii = names.length; i < ii; i++) {
name = names[i];
if (name in this.attrs) {
out[name] = this.attrs[name];
} else if (R.is(this.paper.customAttributes[name], "function")) {
out[name] = this.paper.customAttributes[name].def;
} else {
out[name] = R._availableAttrs[name];
}
}
return ii - 1 ? out : out[names[0]];
}
if (this.attrs && value == null && R.is(name, "array")) {
out = {};
for (i = 0, ii = name.length; i < ii; i++) {
out[name[i]] = this.attr(name[i]);
}
return out;
}
var params;
if (value != null) {
params = {};
params[name] = value;
}
value == null && R.is(name, "object") && (params = name);
for (var key in params) {
eve("raphael.attr." + key + "." + this.id, this, params[key]);
}
if (params) {
for (key in this.paper.customAttributes) if (this.paper.customAttributes[has](key) && params[has](key) && R.is(this.paper.customAttributes[key], "function")) {
var par = this.paper.customAttributes[key].apply(this, [].concat(params[key]));
this.attrs[key] = params[key];
for (var subkey in par) if (par[has](subkey)) {
params[subkey] = par[subkey];
}
}
// this.paper.canvas.style.display = "none";
if (params.text && this.type == "text") {
this.textpath.string = params.text;
}
setFillAndStroke(this, params);
// this.paper.canvas.style.display = E;
}
return this;
};
elproto.toFront = function () {
!this.removed && this.node.parentNode.appendChild(this.node);
this.paper && this.paper.top != this && R._tofront(this, this.paper);
return this;
};
elproto.toBack = function () {
if (this.removed) {
return this;
}
if (this.node.parentNode.firstChild != this.node) {
this.node.parentNode.insertBefore(this.node, this.node.parentNode.firstChild);
R._toback(this, this.paper);
}
return this;
};
elproto.insertAfter = function (element) {
if (this.removed) {
return this;
}
if (element.constructor == R.st.constructor) {
element = element[element.length - 1];
}
if (element.node.nextSibling) {
element.node.parentNode.insertBefore(this.node, element.node.nextSibling);
} else {
element.node.parentNode.appendChild(this.node);
}
R._insertafter(this, element, this.paper);
return this;
};
elproto.insertBefore = function (element) {
if (this.removed) {
return this;
}
if (element.constructor == R.st.constructor) {
element = element[0];
}
element.node.parentNode.insertBefore(this.node, element.node);
R._insertbefore(this, element, this.paper);
return this;
};
elproto.blur = function (size) {
var s = this.node.runtimeStyle,
f = s.filter;
f = f.replace(blurregexp, E);
if (+size !== 0) {
this.attrs.blur = size;
s.filter = f + S + ms + ".Blur(pixelradius=" + (+size || 1.5) + ")";
s.margin = R.format("-{0}px 0 0 -{0}px", round(+size || 1.5));
} else {
s.filter = f;
s.margin = 0;
delete this.attrs.blur;
}
return this;
};
R._engine.path = function (pathString, vml) {
var el = createNode("shape");
el.style.cssText = cssDot;
el.coordsize = zoom + S + zoom;
el.coordorigin = vml.coordorigin;
var p = new Element(el, vml),
attr = {fill: "none", stroke: "#000"};
pathString && (attr.path = pathString);
p.type = "path";
p.path = [];
p.Path = E;
setFillAndStroke(p, attr);
vml.canvas.appendChild(el);
var skew = createNode("skew");
skew.on = true;
el.appendChild(skew);
p.skew = skew;
p.transform(E);
return p;
};
R._engine.rect = function (vml, x, y, w, h, r) {
var path = R._rectPath(x, y, w, h, r),
res = vml.path(path),
a = res.attrs;
res.X = a.x = x;
res.Y = a.y = y;
res.W = a.width = w;
res.H = a.height = h;
a.r = r;
a.path = path;
res.type = "rect";
return res;
};
R._engine.ellipse = function (vml, x, y, rx, ry) {
var res = vml.path(),
a = res.attrs;
res.X = x - rx;
res.Y = y - ry;
res.W = rx * 2;
res.H = ry * 2;
res.type = "ellipse";
setFillAndStroke(res, {
cx: x,
cy: y,
rx: rx,
ry: ry
});
return res;
};
R._engine.circle = function (vml, x, y, r) {
var res = vml.path(),
a = res.attrs;
res.X = x - r;
res.Y = y - r;
res.W = res.H = r * 2;
res.type = "circle";
setFillAndStroke(res, {
cx: x,
cy: y,
r: r
});
return res;
};
R._engine.image = function (vml, src, x, y, w, h) {
var path = R._rectPath(x, y, w, h),
res = vml.path(path).attr({stroke: "none"}),
a = res.attrs,
node = res.node,
fill = node.getElementsByTagName(fillString)[0];
a.src = src;
res.X = a.x = x;
res.Y = a.y = y;
res.W = a.width = w;
res.H = a.height = h;
a.path = path;
res.type = "image";
fill.parentNode == node && node.removeChild(fill);
fill.rotate = true;
fill.src = src;
fill.type = "tile";
res._.fillpos = [x, y];
res._.fillsize = [w, h];
node.appendChild(fill);
setCoords(res, 1, 1, 0, 0, 0);
return res;
};
R._engine.text = function (vml, x, y, text) {
var el = createNode("shape"),
path = createNode("path"),
o = createNode("textpath");
x = x || 0;
y = y || 0;
text = text || "";
path.v = R.format("m{0},{1}l{2},{1}", round(x * zoom), round(y * zoom), round(x * zoom) + 1);
path.textpathok = true;
o.string = Str(text);
o.on = true;
el.style.cssText = cssDot;
el.coordsize = zoom + S + zoom;
el.coordorigin = "0 0";
var p = new Element(el, vml),
attr = {
fill: "#000",
stroke: "none",
font: R._availableAttrs.font,
text: text
};
p.shape = el;
p.path = path;
p.textpath = o;
p.type = "text";
p.attrs.text = Str(text);
p.attrs.x = x;
p.attrs.y = y;
p.attrs.w = 1;
p.attrs.h = 1;
setFillAndStroke(p, attr);
el.appendChild(o);
el.appendChild(path);
vml.canvas.appendChild(el);
var skew = createNode("skew");
skew.on = true;
el.appendChild(skew);
p.skew = skew;
p.transform(E);
return p;
};
R._engine.setSize = function (width, height) {
var cs = this.canvas.style;
this.width = width;
this.height = height;
width == +width && (width += "px");
height == +height && (height += "px");
cs.width = width;
cs.height = height;
cs.clip = "rect(0 " + width + " " + height + " 0)";
if (this._viewBox) {
R._engine.setViewBox.apply(this, this._viewBox);
}
return this;
};
R._engine.setViewBox = function (x, y, w, h, fit) {
R.eve("raphael.setViewBox", this, this._viewBox, [x, y, w, h, fit]);
var width = this.width,
height = this.height,
size = 1 / mmax(w / width, h / height),
H, W;
if (fit) {
H = height / h;
W = width / w;
if (w * H < width) {
x -= (width - w * H) / 2 / H;
}
if (h * W < height) {
y -= (height - h * W) / 2 / W;
}
}
this._viewBox = [x, y, w, h, !!fit];
this._viewBoxShift = {
dx: -x,
dy: -y,
scale: size
};
this.forEach(function (el) {
el.transform("...");
});
return this;
};
var createNode;
R._engine.initWin = function (win) {
var doc = win.document;
doc.createStyleSheet().addRule(".rvml", "behavior:url(#default#VML)");
try {
!doc.namespaces.rvml && doc.namespaces.add("rvml", "urn:schemas-microsoft-com:vml");
createNode = function (tagName) {
return doc.createElement('<rvml:' + tagName + ' class="rvml">');
};
} catch (e) {
createNode = function (tagName) {
return doc.createElement('<' + tagName + ' xmlns="urn:schemas-microsoft.com:vml" class="rvml">');
};
}
};
R._engine.initWin(R._g.win);
R._engine.create = function () {
var con = R._getContainer.apply(0, arguments),
container = con.container,
height = con.height,
s,
width = con.width,
x = con.x,
y = con.y;
if (!container) {
throw new Error("VML container not found.");
}
var res = new R._Paper,
c = res.canvas = R._g.doc.createElement("div"),
cs = c.style;
x = x || 0;
y = y || 0;
width = width || 512;
height = height || 342;
res.width = width;
res.height = height;
width == +width && (width += "px");
height == +height && (height += "px");
res.coordsize = zoom * 1e3 + S + zoom * 1e3;
res.coordorigin = "0 0";
res.span = R._g.doc.createElement("span");
res.span.style.cssText = "position:absolute;left:-9999em;top:-9999em;padding:0;margin:0;line-height:1;";
c.appendChild(res.span);
cs.cssText = R.format("top:0;left:0;width:{0};height:{1};display:inline-block;position:relative;clip:rect(0 {0} {1} 0);overflow:hidden", width, height);
if (container == 1) {
R._g.doc.body.appendChild(c);
cs.left = x + "px";
cs.top = y + "px";
cs.position = "absolute";
} else {
if (container.firstChild) {
container.insertBefore(c, container.firstChild);
} else {
container.appendChild(c);
}
}
res.renderfix = function () {};
return res;
};
R.prototype.clear = function () {
R.eve("raphael.clear", this);
this.canvas.innerHTML = E;
this.span = R._g.doc.createElement("span");
this.span.style.cssText = "position:absolute;left:-9999em;top:-9999em;padding:0;margin:0;line-height:1;display:inline;";
this.canvas.appendChild(this.span);
this.bottom = this.top = null;
};
R.prototype.remove = function () {
R.eve("raphael.remove", this);
this.canvas.parentNode.removeChild(this.canvas);
for (var i in this) {
this[i] = typeof this[i] == "function" ? R._removedFactory(i) : null;
}
return true;
};
var setproto = R.st;
for (var method in elproto) if (elproto[has](method) && !setproto[has](method)) {
setproto[method] = (function (methodname) {
return function () {
var arg = arguments;
return this.forEach(function (el) {
el[methodname].apply(el, arg);
});
};
})(method);
}
})();
// EXPOSE
// SVG and VML are appended just before the EXPOSE line
// Even with AMD, Raphael should be defined globally
oldRaphael.was ? (g.win.Raphael = R) : (Raphael = R);
return R;
}));
| CelineBoudier/rapid-router | game/static/game/js/raphael.js | JavaScript | agpl-3.0 | 299,673 |
# -*- coding: utf-8 -*-
##############################################################################
#
# OpenERP, Open Source Management Solution
# Copyright (C) 2004-2010 Tiny SPRL (<http://tiny.be>).
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as
# published by the Free Software Foundation, either version 3 of the
# License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
#
##############################################################################
from datetime import date, datetime
from dateutil import relativedelta
import json
import time
from openerp.osv import fields, osv
from openerp.tools.float_utils import float_compare, float_round
from openerp.tools.translate import _
from openerp.tools import DEFAULT_SERVER_DATETIME_FORMAT, DEFAULT_SERVER_DATE_FORMAT
from openerp.exceptions import Warning
from openerp import SUPERUSER_ID, api
import openerp.addons.decimal_precision as dp
from openerp.addons.procurement import procurement
import logging
_logger = logging.getLogger(__name__)
#----------------------------------------------------------
# Incoterms
#----------------------------------------------------------
class stock_incoterms(osv.osv):
_name = "stock.incoterms"
_description = "Incoterms"
_columns = {
'name': fields.char('Name', required=True, help="Incoterms are series of sales terms. They are used to divide transaction costs and responsibilities between buyer and seller and reflect state-of-the-art transportation practices."),
'code': fields.char('Code', size=3, required=True, help="Incoterm Standard Code"),
'active': fields.boolean('Active', help="By unchecking the active field, you may hide an INCOTERM you will not use."),
}
_defaults = {
'active': True,
}
#----------------------------------------------------------
# Stock Location
#----------------------------------------------------------
class stock_location(osv.osv):
_name = "stock.location"
_description = "Inventory Locations"
_parent_name = "location_id"
_parent_store = True
_parent_order = 'name'
_order = 'parent_left'
_rec_name = 'complete_name'
def _location_owner(self, cr, uid, location, context=None):
''' Return the company owning the location if any '''
return location and (location.usage == 'internal') and location.company_id or False
def _complete_name(self, cr, uid, ids, name, args, context=None):
""" Forms complete name of location from parent location to child location.
@return: Dictionary of values
"""
res = {}
for m in self.browse(cr, uid, ids, context=context):
res[m.id] = m.name
parent = m.location_id
while parent:
res[m.id] = parent.name + ' / ' + res[m.id]
parent = parent.location_id
return res
def _get_sublocations(self, cr, uid, ids, context=None):
""" return all sublocations of the given stock locations (included) """
if context is None:
context = {}
context_with_inactive = context.copy()
context_with_inactive['active_test'] = False
return self.search(cr, uid, [('id', 'child_of', ids)], context=context_with_inactive)
def _name_get(self, cr, uid, location, context=None):
name = location.name
while location.location_id and location.usage != 'view':
location = location.location_id
name = location.name + '/' + name
return name
def name_get(self, cr, uid, ids, context=None):
res = []
for location in self.browse(cr, uid, ids, context=context):
res.append((location.id, self._name_get(cr, uid, location, context=context)))
return res
_columns = {
'name': fields.char('Location Name', required=True, translate=True),
'active': fields.boolean('Active', help="By unchecking the active field, you may hide a location without deleting it."),
'usage': fields.selection([
('supplier', 'Supplier Location'),
('view', 'View'),
('internal', 'Internal Location'),
('customer', 'Customer Location'),
('inventory', 'Inventory'),
('procurement', 'Procurement'),
('production', 'Production'),
('transit', 'Transit Location')],
'Location Type', required=True,
help="""* Supplier Location: Virtual location representing the source location for products coming from your suppliers
\n* View: Virtual location used to create a hierarchical structures for your warehouse, aggregating its child locations ; can't directly contain products
\n* Internal Location: Physical locations inside your own warehouses,
\n* Customer Location: Virtual location representing the destination location for products sent to your customers
\n* Inventory: Virtual location serving as counterpart for inventory operations used to correct stock levels (Physical inventories)
\n* Procurement: Virtual location serving as temporary counterpart for procurement operations when the source (supplier or production) is not known yet. This location should be empty when the procurement scheduler has finished running.
\n* Production: Virtual counterpart location for production operations: this location consumes the raw material and produces finished products
\n* Transit Location: Counterpart location that should be used in inter-companies or inter-warehouses operations
""", select=True),
'complete_name': fields.function(_complete_name, type='char', string="Location Name",
store={'stock.location': (_get_sublocations, ['name', 'location_id', 'active'], 10)}),
'location_id': fields.many2one('stock.location', 'Parent Location', select=True, ondelete='cascade'),
'child_ids': fields.one2many('stock.location', 'location_id', 'Contains'),
'partner_id': fields.many2one('res.partner', 'Owner', help="Owner of the location if not internal"),
'comment': fields.text('Additional Information'),
'posx': fields.integer('Corridor (X)', help="Optional localization details, for information purpose only"),
'posy': fields.integer('Shelves (Y)', help="Optional localization details, for information purpose only"),
'posz': fields.integer('Height (Z)', help="Optional localization details, for information purpose only"),
'parent_left': fields.integer('Left Parent', select=1),
'parent_right': fields.integer('Right Parent', select=1),
'company_id': fields.many2one('res.company', 'Company', select=1, help='Let this field empty if this location is shared between companies'),
'scrap_location': fields.boolean('Is a Scrap Location?', help='Check this box to allow using this location to put scrapped/damaged goods.'),
'removal_strategy_id': fields.many2one('product.removal', 'Removal Strategy', help="Defines the default method used for suggesting the exact location (shelf) where to take the products from, which lot etc. for this location. This method can be enforced at the product category level, and a fallback is made on the parent locations if none is set here."),
'putaway_strategy_id': fields.many2one('product.putaway', 'Put Away Strategy', help="Defines the default method used for suggesting the exact location (shelf) where to store the products. This method can be enforced at the product category level, and a fallback is made on the parent locations if none is set here."),
'loc_barcode': fields.char('Location Barcode'),
}
_defaults = {
'active': True,
'usage': 'internal',
'company_id': lambda self, cr, uid, c: self.pool.get('res.company')._company_default_get(cr, uid, 'stock.location', context=c),
'posx': 0,
'posy': 0,
'posz': 0,
'scrap_location': False,
}
_sql_constraints = [('loc_barcode_company_uniq', 'unique (loc_barcode,company_id)', 'The barcode for a location must be unique per company !')]
def create(self, cr, uid, default, context=None):
if not default.get('loc_barcode', False):
default.update({'loc_barcode': default.get('complete_name', False)})
return super(stock_location, self).create(cr, uid, default, context=context)
def get_putaway_strategy(self, cr, uid, location, product, context=None):
''' Returns the location where the product has to be put, if any compliant putaway strategy is found. Otherwise returns None.'''
putaway_obj = self.pool.get('product.putaway')
loc = location
while loc:
if loc.putaway_strategy_id:
res = putaway_obj.putaway_apply(cr, uid, loc.putaway_strategy_id, product, context=context)
if res:
return res
loc = loc.location_id
def _default_removal_strategy(self, cr, uid, context=None):
return 'fifo'
def get_removal_strategy(self, cr, uid, location, product, context=None):
''' Returns the removal strategy to consider for the given product and location.
:param location: browse record (stock.location)
:param product: browse record (product.product)
:rtype: char
'''
if product.categ_id.removal_strategy_id:
return product.categ_id.removal_strategy_id.method
loc = location
while loc:
if loc.removal_strategy_id:
return loc.removal_strategy_id.method
loc = loc.location_id
return self._default_removal_strategy(cr, uid, context=context)
def get_warehouse(self, cr, uid, location, context=None):
"""
Returns warehouse id of warehouse that contains location
:param location: browse record (stock.location)
"""
wh_obj = self.pool.get("stock.warehouse")
whs = wh_obj.search(cr, uid, [('view_location_id.parent_left', '<=', location.parent_left),
('view_location_id.parent_right', '>=', location.parent_left)], context=context)
return whs and whs[0] or False
#----------------------------------------------------------
# Routes
#----------------------------------------------------------
class stock_location_route(osv.osv):
_name = 'stock.location.route'
_description = "Inventory Routes"
_order = 'sequence'
_columns = {
'name': fields.char('Route Name', required=True),
'sequence': fields.integer('Sequence'),
'pull_ids': fields.one2many('procurement.rule', 'route_id', 'Pull Rules', copy=True),
'active': fields.boolean('Active', help="If the active field is set to False, it will allow you to hide the route without removing it."),
'push_ids': fields.one2many('stock.location.path', 'route_id', 'Push Rules', copy=True),
'product_selectable': fields.boolean('Applicable on Product'),
'product_categ_selectable': fields.boolean('Applicable on Product Category'),
'warehouse_selectable': fields.boolean('Applicable on Warehouse'),
'supplied_wh_id': fields.many2one('stock.warehouse', 'Supplied Warehouse'),
'supplier_wh_id': fields.many2one('stock.warehouse', 'Supplier Warehouse'),
'company_id': fields.many2one('res.company', 'Company', select=1, help='Let this field empty if this route is shared between all companies'),
}
_defaults = {
'sequence': lambda self, cr, uid, ctx: 0,
'active': True,
'product_selectable': True,
'company_id': lambda self, cr, uid, c: self.pool.get('res.company')._company_default_get(cr, uid, 'stock.location.route', context=c),
}
def write(self, cr, uid, ids, vals, context=None):
'''when a route is deactivated, deactivate also its pull and push rules'''
if isinstance(ids, (int, long)):
ids = [ids]
res = super(stock_location_route, self).write(cr, uid, ids, vals, context=context)
if 'active' in vals:
push_ids = []
pull_ids = []
for route in self.browse(cr, uid, ids, context=context):
if route.push_ids:
push_ids += [r.id for r in route.push_ids if r.active != vals['active']]
if route.pull_ids:
pull_ids += [r.id for r in route.pull_ids if r.active != vals['active']]
if push_ids:
self.pool.get('stock.location.path').write(cr, uid, push_ids, {'active': vals['active']}, context=context)
if pull_ids:
self.pool.get('procurement.rule').write(cr, uid, pull_ids, {'active': vals['active']}, context=context)
return res
#----------------------------------------------------------
# Quants
#----------------------------------------------------------
class stock_quant(osv.osv):
"""
Quants are the smallest unit of stock physical instances
"""
_name = "stock.quant"
_description = "Quants"
def _get_quant_name(self, cr, uid, ids, name, args, context=None):
""" Forms complete name of location from parent location to child location.
@return: Dictionary of values
"""
res = {}
for q in self.browse(cr, uid, ids, context=context):
res[q.id] = q.product_id.code or ''
if q.lot_id:
res[q.id] = q.lot_id.name
res[q.id] += ': ' + str(q.qty) + q.product_id.uom_id.name
return res
def _calc_inventory_value(self, cr, uid, ids, name, attr, context=None):
context = dict(context or {})
res = {}
uid_company_id = self.pool.get('res.users').browse(cr, uid, uid, context=context).company_id.id
for quant in self.browse(cr, uid, ids, context=context):
context.pop('force_company', None)
if quant.company_id.id != uid_company_id:
#if the company of the quant is different than the current user company, force the company in the context
#then re-do a browse to read the property fields for the good company.
context['force_company'] = quant.company_id.id
quant = self.browse(cr, uid, quant.id, context=context)
res[quant.id] = self._get_inventory_value(cr, uid, quant, context=context)
return res
def _get_inventory_value(self, cr, uid, quant, context=None):
return quant.product_id.standard_price * quant.qty
_columns = {
'name': fields.function(_get_quant_name, type='char', string='Identifier'),
'product_id': fields.many2one('product.product', 'Product', required=True, ondelete="restrict", readonly=True, select=True),
'location_id': fields.many2one('stock.location', 'Location', required=True, ondelete="restrict", readonly=True, select=True, auto_join=True),
'qty': fields.float('Quantity', required=True, help="Quantity of products in this quant, in the default unit of measure of the product", readonly=True, select=True),
'package_id': fields.many2one('stock.quant.package', string='Package', help="The package containing this quant", readonly=True, select=True),
'packaging_type_id': fields.related('package_id', 'packaging_id', type='many2one', relation='product.packaging', string='Type of packaging', readonly=True, store=True),
'reservation_id': fields.many2one('stock.move', 'Reserved for Move', help="The move the quant is reserved for", readonly=True, select=True),
'lot_id': fields.many2one('stock.production.lot', 'Lot', readonly=True, select=True, ondelete="restrict"),
'cost': fields.float('Unit Cost'),
'owner_id': fields.many2one('res.partner', 'Owner', help="This is the owner of the quant", readonly=True, select=True),
'create_date': fields.datetime('Creation Date', readonly=True),
'in_date': fields.datetime('Incoming Date', readonly=True, select=True),
'history_ids': fields.many2many('stock.move', 'stock_quant_move_rel', 'quant_id', 'move_id', 'Moves', help='Moves that operate(d) on this quant', copy=False),
'company_id': fields.many2one('res.company', 'Company', help="The company to which the quants belong", required=True, readonly=True, select=True),
'inventory_value': fields.function(_calc_inventory_value, string="Inventory Value", type='float', readonly=True),
# Used for negative quants to reconcile after compensated by a new positive one
'propagated_from_id': fields.many2one('stock.quant', 'Linked Quant', help='The negative quant this is coming from', readonly=True, select=True),
'negative_move_id': fields.many2one('stock.move', 'Move Negative Quant', help='If this is a negative quant, this will be the move that caused this negative quant.', readonly=True),
'negative_dest_location_id': fields.related('negative_move_id', 'location_dest_id', type='many2one', relation='stock.location', string="Negative Destination Location", readonly=True,
help="Technical field used to record the destination location of a move that created a negative quant"),
}
_defaults = {
'company_id': lambda self, cr, uid, c: self.pool.get('res.company')._company_default_get(cr, uid, 'stock.quant', context=c),
}
def init(self, cr):
cr.execute('SELECT indexname FROM pg_indexes WHERE indexname = %s', ('stock_quant_product_location_index',))
if not cr.fetchone():
cr.execute('CREATE INDEX stock_quant_product_location_index ON stock_quant (product_id, location_id, company_id, qty, in_date, reservation_id)')
def read_group(self, cr, uid, domain, fields, groupby, offset=0, limit=None, context=None, orderby=False, lazy=True):
''' Overwrite the read_group in order to sum the function field 'inventory_value' in group by'''
res = super(stock_quant, self).read_group(cr, uid, domain, fields, groupby, offset=offset, limit=limit, context=context, orderby=orderby, lazy=lazy)
if 'inventory_value' in fields:
for line in res:
if '__domain' in line:
lines = self.search(cr, uid, line['__domain'], context=context)
inv_value = 0.0
for line2 in self.browse(cr, uid, lines, context=context):
inv_value += line2.inventory_value
line['inventory_value'] = inv_value
return res
def action_view_quant_history(self, cr, uid, ids, context=None):
'''
This function returns an action that display the history of the quant, which
mean all the stock moves that lead to this quant creation with this quant quantity.
'''
mod_obj = self.pool.get('ir.model.data')
act_obj = self.pool.get('ir.actions.act_window')
result = mod_obj.get_object_reference(cr, uid, 'stock', 'action_move_form2')
id = result and result[1] or False
result = act_obj.read(cr, uid, [id], context={})[0]
move_ids = []
for quant in self.browse(cr, uid, ids, context=context):
move_ids += [move.id for move in quant.history_ids]
result['domain'] = "[('id','in',[" + ','.join(map(str, move_ids)) + "])]"
return result
def quants_reserve(self, cr, uid, quants, move, link=False, context=None):
'''This function reserves quants for the given move (and optionally given link). If the total of quantity reserved is enough, the move's state
is also set to 'assigned'
:param quants: list of tuple(quant browse record or None, qty to reserve). If None is given as first tuple element, the item will be ignored. Negative quants should not be received as argument
:param move: browse record
:param link: browse record (stock.move.operation.link)
'''
toreserve = []
reserved_availability = move.reserved_availability
#split quants if needed
for quant, qty in quants:
if qty <= 0.0 or (quant and quant.qty <= 0.0):
raise osv.except_osv(_('Error!'), _('You can not reserve a negative quantity or a negative quant.'))
if not quant:
continue
self._quant_split(cr, uid, quant, qty, context=context)
toreserve.append(quant.id)
reserved_availability += quant.qty
#reserve quants
if toreserve:
self.write(cr, SUPERUSER_ID, toreserve, {'reservation_id': move.id}, context=context)
#if move has a picking_id, write on that picking that pack_operation might have changed and need to be recomputed
if move.picking_id:
self.pool.get('stock.picking').write(cr, uid, [move.picking_id.id], {'recompute_pack_op': True}, context=context)
#check if move'state needs to be set as 'assigned'
rounding = move.product_id.uom_id.rounding
if float_compare(reserved_availability, move.product_qty, precision_rounding=rounding) == 0 and move.state in ('confirmed', 'waiting') :
self.pool.get('stock.move').write(cr, uid, [move.id], {'state': 'assigned'}, context=context)
elif float_compare(reserved_availability, 0, precision_rounding=rounding) > 0 and not move.partially_available:
self.pool.get('stock.move').write(cr, uid, [move.id], {'partially_available': True}, context=context)
def quants_move(self, cr, uid, quants, move, location_to, location_from=False, lot_id=False, owner_id=False, src_package_id=False, dest_package_id=False, context=None):
"""Moves all given stock.quant in the given destination location. Unreserve from current move.
:param quants: list of tuple(browse record(stock.quant) or None, quantity to move)
:param move: browse record (stock.move)
:param location_to: browse record (stock.location) depicting where the quants have to be moved
:param location_from: optional browse record (stock.location) explaining where the quant has to be taken (may differ from the move source location in case a removal strategy applied). This parameter is only used to pass to _quant_create if a negative quant must be created
:param lot_id: ID of the lot that must be set on the quants to move
:param owner_id: ID of the partner that must own the quants to move
:param src_package_id: ID of the package that contains the quants to move
:param dest_package_id: ID of the package that must be set on the moved quant
"""
quants_reconcile = []
to_move_quants = []
self._check_location(cr, uid, location_to, context=context)
for quant, qty in quants:
if not quant:
#If quant is None, we will create a quant to move (and potentially a negative counterpart too)
quant = self._quant_create(cr, uid, qty, move, lot_id=lot_id, owner_id=owner_id, src_package_id=src_package_id, dest_package_id=dest_package_id, force_location_from=location_from, force_location_to=location_to, context=context)
else:
self._quant_split(cr, uid, quant, qty, context=context)
to_move_quants.append(quant)
quants_reconcile.append(quant)
if to_move_quants:
to_recompute_move_ids = [x.reservation_id.id for x in to_move_quants if x.reservation_id and x.reservation_id.id != move.id]
self.move_quants_write(cr, uid, to_move_quants, move, location_to, dest_package_id, context=context)
self.pool.get('stock.move').recalculate_move_state(cr, uid, to_recompute_move_ids, context=context)
if location_to.usage == 'internal':
# Do manual search for quant to avoid full table scan (order by id)
cr.execute("""
SELECT 0 FROM stock_quant, stock_location WHERE product_id = %s AND stock_location.id = stock_quant.location_id AND
((stock_location.parent_left >= %s AND stock_location.parent_left < %s) OR stock_location.id = %s) AND qty < 0.0 LIMIT 1
""", (move.product_id.id, location_to.parent_left, location_to.parent_right, location_to.id))
if cr.fetchone():
for quant in quants_reconcile:
self._quant_reconcile_negative(cr, uid, quant, move, context=context)
def move_quants_write(self, cr, uid, quants, move, location_dest_id, dest_package_id, context=None):
context=context or {}
vals = {'location_id': location_dest_id.id,
'history_ids': [(4, move.id)],
'reservation_id': False}
if not context.get('entire_pack'):
vals.update({'package_id': dest_package_id})
self.write(cr, SUPERUSER_ID, [q.id for q in quants], vals, context=context)
def quants_get_prefered_domain(self, cr, uid, location, product, qty, domain=None, prefered_domain_list=[], restrict_lot_id=False, restrict_partner_id=False, context=None):
''' This function tries to find quants in the given location for the given domain, by trying to first limit
the choice on the quants that match the first item of prefered_domain_list as well. But if the qty requested is not reached
it tries to find the remaining quantity by looping on the prefered_domain_list (tries with the second item and so on).
Make sure the quants aren't found twice => all the domains of prefered_domain_list should be orthogonal
'''
if domain is None:
domain = []
quants = [(None, qty)]
#don't look for quants in location that are of type production, supplier or inventory.
if location.usage in ['inventory', 'production', 'supplier']:
return quants
res_qty = qty
if not prefered_domain_list:
return self.quants_get(cr, uid, location, product, qty, domain=domain, restrict_lot_id=restrict_lot_id, restrict_partner_id=restrict_partner_id, context=context)
for prefered_domain in prefered_domain_list:
res_qty_cmp = float_compare(res_qty, 0, precision_rounding=product.uom_id.rounding)
if res_qty_cmp > 0:
#try to replace the last tuple (None, res_qty) with something that wasn't chosen at first because of the prefered order
quants.pop()
tmp_quants = self.quants_get(cr, uid, location, product, res_qty, domain=domain + prefered_domain, restrict_lot_id=restrict_lot_id, restrict_partner_id=restrict_partner_id, context=context)
for quant in tmp_quants:
if quant[0]:
res_qty -= quant[1]
quants += tmp_quants
return quants
def quants_get(self, cr, uid, location, product, qty, domain=None, restrict_lot_id=False, restrict_partner_id=False, context=None):
"""
Use the removal strategies of product to search for the correct quants
If you inherit, put the super at the end of your method.
:location: browse record of the parent location where the quants have to be found
:product: browse record of the product to find
:qty in UoM of product
"""
result = []
domain = domain or [('qty', '>', 0.0)]
if restrict_partner_id:
domain += [('owner_id', '=', restrict_partner_id)]
if restrict_lot_id:
domain += [('lot_id', '=', restrict_lot_id)]
if location:
removal_strategy = self.pool.get('stock.location').get_removal_strategy(cr, uid, location, product, context=context)
result += self.apply_removal_strategy(cr, uid, location, product, qty, domain, removal_strategy, context=context)
return result
def apply_removal_strategy(self, cr, uid, location, product, quantity, domain, removal_strategy, context=None):
if removal_strategy == 'fifo':
order = 'in_date, id'
return self._quants_get_order(cr, uid, location, product, quantity, domain, order, context=context)
elif removal_strategy == 'lifo':
order = 'in_date desc, id desc'
return self._quants_get_order(cr, uid, location, product, quantity, domain, order, context=context)
raise osv.except_osv(_('Error!'), _('Removal strategy %s not implemented.' % (removal_strategy,)))
def _quant_create(self, cr, uid, qty, move, lot_id=False, owner_id=False, src_package_id=False, dest_package_id=False,
force_location_from=False, force_location_to=False, context=None):
'''Create a quant in the destination location and create a negative quant in the source location if it's an internal location.
'''
if context is None:
context = {}
price_unit = self.pool.get('stock.move').get_price_unit(cr, uid, move, context=context)
location = force_location_to or move.location_dest_id
rounding = move.product_id.uom_id.rounding
vals = {
'product_id': move.product_id.id,
'location_id': location.id,
'qty': float_round(qty, precision_rounding=rounding),
'cost': price_unit,
'history_ids': [(4, move.id)],
'in_date': datetime.now().strftime(DEFAULT_SERVER_DATETIME_FORMAT),
'company_id': move.company_id.id,
'lot_id': lot_id,
'owner_id': owner_id,
'package_id': dest_package_id,
}
if move.location_id.usage == 'internal':
#if we were trying to move something from an internal location and reach here (quant creation),
#it means that a negative quant has to be created as well.
negative_vals = vals.copy()
negative_vals['location_id'] = force_location_from and force_location_from.id or move.location_id.id
negative_vals['qty'] = float_round(-qty, precision_rounding=rounding)
negative_vals['cost'] = price_unit
negative_vals['negative_move_id'] = move.id
negative_vals['package_id'] = src_package_id
negative_quant_id = self.create(cr, SUPERUSER_ID, negative_vals, context=context)
vals.update({'propagated_from_id': negative_quant_id})
#create the quant as superuser, because we want to restrict the creation of quant manually: we should always use this method to create quants
quant_id = self.create(cr, SUPERUSER_ID, vals, context=context)
return self.browse(cr, uid, quant_id, context=context)
def _quant_split(self, cr, uid, quant, qty, context=None):
context = context or {}
rounding = quant.product_id.uom_id.rounding
if float_compare(abs(quant.qty), abs(qty), precision_rounding=rounding) <= 0: # if quant <= qty in abs, take it entirely
return False
qty_round = float_round(qty, precision_rounding=rounding)
new_qty_round = float_round(quant.qty - qty, precision_rounding=rounding)
# Fetch the history_ids manually as it will not do a join with the stock moves then (=> a lot faster)
cr.execute("""SELECT move_id FROM stock_quant_move_rel WHERE quant_id = %s""", (quant.id,))
res = cr.fetchall()
new_quant = self.copy(cr, SUPERUSER_ID, quant.id, default={'qty': new_qty_round, 'history_ids': [(4, x[0]) for x in res]}, context=context)
self.write(cr, SUPERUSER_ID, quant.id, {'qty': qty_round}, context=context)
return self.browse(cr, uid, new_quant, context=context)
def _get_latest_move(self, cr, uid, quant, context=None):
move = False
for m in quant.history_ids:
if not move or m.date > move.date:
move = m
return move
@api.cr_uid_ids_context
def _quants_merge(self, cr, uid, solved_quant_ids, solving_quant, context=None):
path = []
for move in solving_quant.history_ids:
path.append((4, move.id))
self.write(cr, SUPERUSER_ID, solved_quant_ids, {'history_ids': path}, context=context)
def _quant_reconcile_negative(self, cr, uid, quant, move, context=None):
"""
When new quant arrive in a location, try to reconcile it with
negative quants. If it's possible, apply the cost of the new
quant to the conter-part of the negative quant.
"""
solving_quant = quant
dom = [('qty', '<', 0)]
if quant.lot_id:
dom += [('lot_id', '=', quant.lot_id.id)]
dom += [('owner_id', '=', quant.owner_id.id)]
dom += [('package_id', '=', quant.package_id.id)]
dom += [('id', '!=', quant.propagated_from_id.id)]
quants = self.quants_get(cr, uid, quant.location_id, quant.product_id, quant.qty, dom, context=context)
product_uom_rounding = quant.product_id.uom_id.rounding
for quant_neg, qty in quants:
if not quant_neg or not solving_quant:
continue
to_solve_quant_ids = self.search(cr, uid, [('propagated_from_id', '=', quant_neg.id)], context=context)
if not to_solve_quant_ids:
continue
solving_qty = qty
solved_quant_ids = []
for to_solve_quant in self.browse(cr, uid, to_solve_quant_ids, context=context):
if float_compare(solving_qty, 0, precision_rounding=product_uom_rounding) <= 0:
continue
solved_quant_ids.append(to_solve_quant.id)
self._quant_split(cr, uid, to_solve_quant, min(solving_qty, to_solve_quant.qty), context=context)
solving_qty -= min(solving_qty, to_solve_quant.qty)
remaining_solving_quant = self._quant_split(cr, uid, solving_quant, qty, context=context)
remaining_neg_quant = self._quant_split(cr, uid, quant_neg, -qty, context=context)
#if the reconciliation was not complete, we need to link together the remaining parts
if remaining_neg_quant:
remaining_to_solve_quant_ids = self.search(cr, uid, [('propagated_from_id', '=', quant_neg.id), ('id', 'not in', solved_quant_ids)], context=context)
if remaining_to_solve_quant_ids:
self.write(cr, SUPERUSER_ID, remaining_to_solve_quant_ids, {'propagated_from_id': remaining_neg_quant.id}, context=context)
if solving_quant.propagated_from_id and solved_quant_ids:
self.write(cr, SUPERUSER_ID, solved_quant_ids, {'propagated_from_id': solving_quant.propagated_from_id.id}, context=context)
#delete the reconciled quants, as it is replaced by the solved quants
self.unlink(cr, SUPERUSER_ID, [quant_neg.id], context=context)
if solved_quant_ids:
#price update + accounting entries adjustments
self._price_update(cr, uid, solved_quant_ids, solving_quant.cost, context=context)
#merge history (and cost?)
self._quants_merge(cr, uid, solved_quant_ids, solving_quant, context=context)
self.unlink(cr, SUPERUSER_ID, [solving_quant.id], context=context)
solving_quant = remaining_solving_quant
def _price_update(self, cr, uid, ids, newprice, context=None):
self.write(cr, SUPERUSER_ID, ids, {'cost': newprice}, context=context)
def quants_unreserve(self, cr, uid, move, context=None):
related_quants = [x.id for x in move.reserved_quant_ids]
if related_quants:
#if move has a picking_id, write on that picking that pack_operation might have changed and need to be recomputed
if move.picking_id:
self.pool.get('stock.picking').write(cr, uid, [move.picking_id.id], {'recompute_pack_op': True}, context=context)
if move.partially_available:
self.pool.get("stock.move").write(cr, uid, [move.id], {'partially_available': False}, context=context)
self.write(cr, SUPERUSER_ID, related_quants, {'reservation_id': False}, context=context)
def _quants_get_order(self, cr, uid, location, product, quantity, domain=[], orderby='in_date', context=None):
''' Implementation of removal strategies
If it can not reserve, it will return a tuple (None, qty)
'''
if context is None:
context = {}
domain += location and [('location_id', 'child_of', location.id)] or []
domain += [('product_id', '=', product.id)]
if context.get('force_company'):
domain += [('company_id', '=', context.get('force_company'))]
else:
domain += [('company_id', '=', self.pool.get('res.users').browse(cr, uid, uid, context=context).company_id.id)]
res = []
offset = 0
while float_compare(quantity, 0, precision_rounding=product.uom_id.rounding) > 0:
quants = self.search(cr, uid, domain, order=orderby, limit=10, offset=offset, context=context)
if not quants:
res.append((None, quantity))
break
for quant in self.browse(cr, uid, quants, context=context):
rounding = product.uom_id.rounding
if float_compare(quantity, abs(quant.qty), precision_rounding=rounding) >= 0:
res += [(quant, abs(quant.qty))]
quantity -= abs(quant.qty)
elif float_compare(quantity, 0.0, precision_rounding=rounding) != 0:
res += [(quant, quantity)]
quantity = 0
break
offset += 10
return res
def _check_location(self, cr, uid, location, context=None):
if location.usage == 'view':
raise osv.except_osv(_('Error'), _('You cannot move to a location of type view %s.') % (location.name))
return True
#----------------------------------------------------------
# Stock Picking
#----------------------------------------------------------
class stock_picking(osv.osv):
_name = "stock.picking"
_inherit = ['mail.thread']
_description = "Picking List"
_order = "priority desc, date asc, id desc"
def _set_min_date(self, cr, uid, id, field, value, arg, context=None):
move_obj = self.pool.get("stock.move")
if value:
move_ids = [move.id for move in self.browse(cr, uid, id, context=context).move_lines]
move_obj.write(cr, uid, move_ids, {'date_expected': value}, context=context)
def _set_priority(self, cr, uid, id, field, value, arg, context=None):
move_obj = self.pool.get("stock.move")
if value:
move_ids = [move.id for move in self.browse(cr, uid, id, context=context).move_lines]
move_obj.write(cr, uid, move_ids, {'priority': value}, context=context)
def get_min_max_date(self, cr, uid, ids, field_name, arg, context=None):
""" Finds minimum and maximum dates for picking.
@return: Dictionary of values
"""
res = {}
for id in ids:
res[id] = {'min_date': False, 'max_date': False, 'priority': '1'}
if not ids:
return res
cr.execute("""select
picking_id,
min(date_expected),
max(date_expected),
max(priority)
from
stock_move
where
picking_id IN %s
group by
picking_id""", (tuple(ids),))
for pick, dt1, dt2, prio in cr.fetchall():
res[pick]['min_date'] = dt1
res[pick]['max_date'] = dt2
res[pick]['priority'] = prio
return res
def create(self, cr, user, vals, context=None):
context = context or {}
if ('name' not in vals) or (vals.get('name') in ('/', False)):
ptype_id = vals.get('picking_type_id', context.get('default_picking_type_id', False))
sequence_id = self.pool.get('stock.picking.type').browse(cr, user, ptype_id, context=context).sequence_id.id
vals['name'] = self.pool.get('ir.sequence').get_id(cr, user, sequence_id, 'id', context=context)
return super(stock_picking, self).create(cr, user, vals, context)
def _state_get(self, cr, uid, ids, field_name, arg, context=None):
'''The state of a picking depends on the state of its related stock.move
draft: the picking has no line or any one of the lines is draft
done, draft, cancel: all lines are done / draft / cancel
confirmed, waiting, assigned, partially_available depends on move_type (all at once or partial)
'''
res = {}
for pick in self.browse(cr, uid, ids, context=context):
if (not pick.move_lines) or any([x.state == 'draft' for x in pick.move_lines]):
res[pick.id] = 'draft'
continue
if all([x.state == 'cancel' for x in pick.move_lines]):
res[pick.id] = 'cancel'
continue
if all([x.state in ('cancel', 'done') for x in pick.move_lines]):
res[pick.id] = 'done'
continue
order = {'confirmed': 0, 'waiting': 1, 'assigned': 2}
order_inv = {0: 'confirmed', 1: 'waiting', 2: 'assigned'}
lst = [order[x.state] for x in pick.move_lines if x.state not in ('cancel', 'done')]
if pick.move_type == 'one':
res[pick.id] = order_inv[min(lst)]
else:
#we are in the case of partial delivery, so if all move are assigned, picking
#should be assign too, else if one of the move is assigned, or partially available, picking should be
#in partially available state, otherwise, picking is in waiting or confirmed state
res[pick.id] = order_inv[max(lst)]
if not all(x == 2 for x in lst):
if any(x == 2 for x in lst):
res[pick.id] = 'partially_available'
else:
#if all moves aren't assigned, check if we have one product partially available
for move in pick.move_lines:
if move.partially_available:
res[pick.id] = 'partially_available'
break
return res
def _get_pickings(self, cr, uid, ids, context=None):
res = set()
for move in self.browse(cr, uid, ids, context=context):
if move.picking_id:
res.add(move.picking_id.id)
return list(res)
def _get_pickings_dates_priority(self, cr, uid, ids, context=None):
res = set()
for move in self.browse(cr, uid, ids, context=context):
if move.picking_id and (not (move.picking_id.min_date < move.date_expected < move.picking_id.max_date) or move.priority > move.picking_id.priority):
res.add(move.picking_id.id)
return list(res)
def _get_pack_operation_exist(self, cr, uid, ids, field_name, arg, context=None):
res = {}
for pick in self.browse(cr, uid, ids, context=context):
res[pick.id] = False
if pick.pack_operation_ids:
res[pick.id] = True
return res
def _get_quant_reserved_exist(self, cr, uid, ids, field_name, arg, context=None):
res = {}
for pick in self.browse(cr, uid, ids, context=context):
res[pick.id] = False
for move in pick.move_lines:
if move.reserved_quant_ids:
res[pick.id] = True
continue
return res
def check_group_lot(self, cr, uid, context=None):
""" This function will return true if we have the setting to use lots activated. """
return self.pool.get('res.users').has_group(cr, uid, 'stock.group_production_lot')
def check_group_pack(self, cr, uid, context=None):
""" This function will return true if we have the setting to use package activated. """
return self.pool.get('res.users').has_group(cr, uid, 'stock.group_tracking_lot')
def action_assign_owner(self, cr, uid, ids, context=None):
for picking in self.browse(cr, uid, ids, context=context):
packop_ids = [op.id for op in picking.pack_operation_ids]
self.pool.get('stock.pack.operation').write(cr, uid, packop_ids, {'owner_id': picking.owner_id.id}, context=context)
_columns = {
'name': fields.char('Reference', select=True, states={'done': [('readonly', True)], 'cancel': [('readonly', True)]}, copy=False),
'origin': fields.char('Source Document', states={'done': [('readonly', True)], 'cancel': [('readonly', True)]}, help="Reference of the document", select=True),
'backorder_id': fields.many2one('stock.picking', 'Back Order of', states={'done': [('readonly', True)], 'cancel': [('readonly', True)]}, help="If this shipment was split, then this field links to the shipment which contains the already processed part.", select=True, copy=False),
'note': fields.text('Notes'),
'move_type': fields.selection([('direct', 'Partial'), ('one', 'All at once')], 'Delivery Method', required=True, states={'done': [('readonly', True)], 'cancel': [('readonly', True)]}, help="It specifies goods to be deliver partially or all at once"),
'state': fields.function(_state_get, type="selection", copy=False,
store={
'stock.picking': (lambda self, cr, uid, ids, ctx: ids, ['move_type'], 20),
'stock.move': (_get_pickings, ['state', 'picking_id', 'partially_available'], 20)},
selection=[
('draft', 'Draft'),
('cancel', 'Cancelled'),
('waiting', 'Waiting Another Operation'),
('confirmed', 'Waiting Availability'),
('partially_available', 'Partially Available'),
('assigned', 'Ready to Transfer'),
('done', 'Transferred'),
], string='Status', readonly=True, select=True, track_visibility='onchange',
help="""
* Draft: not confirmed yet and will not be scheduled until confirmed\n
* Waiting Another Operation: waiting for another move to proceed before it becomes automatically available (e.g. in Make-To-Order flows)\n
* Waiting Availability: still waiting for the availability of products\n
* Partially Available: some products are available and reserved\n
* Ready to Transfer: products reserved, simply waiting for confirmation.\n
* Transferred: has been processed, can't be modified or cancelled anymore\n
* Cancelled: has been cancelled, can't be confirmed anymore"""
),
'priority': fields.function(get_min_max_date, multi="min_max_date", fnct_inv=_set_priority, type='selection', selection=procurement.PROCUREMENT_PRIORITIES, string='Priority',
store={'stock.move': (_get_pickings_dates_priority, ['priority', 'picking_id'], 20)}, states={'done': [('readonly', True)], 'cancel': [('readonly', True)]}, select=1, help="Priority for this picking. Setting manually a value here would set it as priority for all the moves",
track_visibility='onchange', required=True),
'min_date': fields.function(get_min_max_date, multi="min_max_date", fnct_inv=_set_min_date,
store={'stock.move': (_get_pickings_dates_priority, ['date_expected', 'picking_id'], 20)}, type='datetime', states={'done': [('readonly', True)], 'cancel': [('readonly', True)]}, string='Scheduled Date', select=1, help="Scheduled time for the first part of the shipment to be processed. Setting manually a value here would set it as expected date for all the stock moves.", track_visibility='onchange'),
'max_date': fields.function(get_min_max_date, multi="min_max_date",
store={'stock.move': (_get_pickings_dates_priority, ['date_expected', 'picking_id'], 20)}, type='datetime', string='Max. Expected Date', select=2, help="Scheduled time for the last part of the shipment to be processed"),
'date': fields.datetime('Creation Date', help="Creation Date, usually the time of the order", select=True, states={'done': [('readonly', True)], 'cancel': [('readonly', True)]}, track_visibility='onchange'),
'date_done': fields.datetime('Date of Transfer', help="Date of Completion", states={'done': [('readonly', True)], 'cancel': [('readonly', True)]}, copy=False),
'move_lines': fields.one2many('stock.move', 'picking_id', 'Internal Moves', states={'done': [('readonly', True)], 'cancel': [('readonly', True)]}, copy=True),
'quant_reserved_exist': fields.function(_get_quant_reserved_exist, type='boolean', string='Quant already reserved ?', help='technical field used to know if there is already at least one quant reserved on moves of a given picking'),
'partner_id': fields.many2one('res.partner', 'Partner', states={'done': [('readonly', True)], 'cancel': [('readonly', True)]}),
'company_id': fields.many2one('res.company', 'Company', required=True, select=True, states={'done': [('readonly', True)], 'cancel': [('readonly', True)]}),
'pack_operation_ids': fields.one2many('stock.pack.operation', 'picking_id', states={'done': [('readonly', True)], 'cancel': [('readonly', True)]}, string='Related Packing Operations'),
'pack_operation_exist': fields.function(_get_pack_operation_exist, type='boolean', string='Pack Operation Exists?', help='technical field for attrs in view'),
'picking_type_id': fields.many2one('stock.picking.type', 'Picking Type', states={'done': [('readonly', True)], 'cancel': [('readonly', True)]}, required=True),
'picking_type_code': fields.related('picking_type_id', 'code', type='char', string='Picking Type Code', help="Technical field used to display the correct label on print button in the picking view"),
'owner_id': fields.many2one('res.partner', 'Owner', states={'done': [('readonly', True)], 'cancel': [('readonly', True)]}, help="Default Owner"),
# Used to search on pickings
'product_id': fields.related('move_lines', 'product_id', type='many2one', relation='product.product', string='Product'),
'recompute_pack_op': fields.boolean('Recompute pack operation?', help='True if reserved quants changed, which mean we might need to recompute the package operations', copy=False),
'location_id': fields.related('move_lines', 'location_id', type='many2one', relation='stock.location', string='Location', readonly=True),
'location_dest_id': fields.related('move_lines', 'location_dest_id', type='many2one', relation='stock.location', string='Destination Location', readonly=True),
'group_id': fields.related('move_lines', 'group_id', type='many2one', relation='procurement.group', string='Procurement Group', readonly=True,
store={
'stock.picking': (lambda self, cr, uid, ids, ctx: ids, ['move_lines'], 10),
'stock.move': (_get_pickings, ['group_id', 'picking_id'], 10),
}),
}
_defaults = {
'name': '/',
'state': 'draft',
'move_type': 'direct',
'priority': '1', # normal
'date': fields.datetime.now,
'company_id': lambda self, cr, uid, c: self.pool.get('res.company')._company_default_get(cr, uid, 'stock.picking', context=c),
'recompute_pack_op': True,
}
_sql_constraints = [
('name_uniq', 'unique(name, company_id)', 'Reference must be unique per company!'),
]
def do_print_picking(self, cr, uid, ids, context=None):
'''This function prints the picking list'''
context = dict(context or {}, active_ids=ids)
return self.pool.get("report").get_action(cr, uid, ids, 'stock.report_picking', context=context)
def action_confirm(self, cr, uid, ids, context=None):
todo = []
todo_force_assign = []
for picking in self.browse(cr, uid, ids, context=context):
if picking.location_id.usage in ('supplier', 'inventory', 'production'):
todo_force_assign.append(picking.id)
for r in picking.move_lines:
if r.state == 'draft':
todo.append(r.id)
if len(todo):
self.pool.get('stock.move').action_confirm(cr, uid, todo, context=context)
if todo_force_assign:
self.force_assign(cr, uid, todo_force_assign, context=context)
return True
def action_assign(self, cr, uid, ids, context=None):
""" Check availability of picking moves.
This has the effect of changing the state and reserve quants on available moves, and may
also impact the state of the picking as it is computed based on move's states.
@return: True
"""
for pick in self.browse(cr, uid, ids, context=context):
if pick.state == 'draft':
self.action_confirm(cr, uid, [pick.id], context=context)
#skip the moves that don't need to be checked
move_ids = [x.id for x in pick.move_lines if x.state not in ('draft', 'cancel', 'done')]
if not move_ids:
raise osv.except_osv(_('Warning!'), _('Nothing to check the availability for.'))
self.pool.get('stock.move').action_assign(cr, uid, move_ids, context=context)
return True
def force_assign(self, cr, uid, ids, context=None):
""" Changes state of picking to available if moves are confirmed or waiting.
@return: True
"""
for pick in self.browse(cr, uid, ids, context=context):
move_ids = [x.id for x in pick.move_lines if x.state in ['confirmed', 'waiting']]
self.pool.get('stock.move').force_assign(cr, uid, move_ids, context=context)
#pack_operation might have changed and need to be recomputed
self.write(cr, uid, ids, {'recompute_pack_op': True}, context=context)
return True
def action_cancel(self, cr, uid, ids, context=None):
for pick in self.browse(cr, uid, ids, context=context):
ids2 = [move.id for move in pick.move_lines]
self.pool.get('stock.move').action_cancel(cr, uid, ids2, context)
return True
def action_done(self, cr, uid, ids, context=None):
"""Changes picking state to done by processing the Stock Moves of the Picking
Normally that happens when the button "Done" is pressed on a Picking view.
@return: True
"""
for pick in self.browse(cr, uid, ids, context=context):
todo = []
for move in pick.move_lines:
if move.state == 'draft':
todo.extend(self.pool.get('stock.move').action_confirm(cr, uid, [move.id], context=context))
elif move.state in ('assigned', 'confirmed'):
todo.append(move.id)
if len(todo):
self.pool.get('stock.move').action_done(cr, uid, todo, context=context)
return True
def unlink(self, cr, uid, ids, context=None):
#on picking deletion, cancel its move then unlink them too
move_obj = self.pool.get('stock.move')
context = context or {}
for pick in self.browse(cr, uid, ids, context=context):
move_ids = [move.id for move in pick.move_lines]
move_obj.action_cancel(cr, uid, move_ids, context=context)
move_obj.unlink(cr, uid, move_ids, context=context)
return super(stock_picking, self).unlink(cr, uid, ids, context=context)
def write(self, cr, uid, ids, vals, context=None):
if vals.get('move_lines') and not vals.get('pack_operation_ids'):
# pack operations are directly dependant of move lines, it needs to be recomputed
pack_operation_obj = self.pool['stock.pack.operation']
existing_package_ids = pack_operation_obj.search(cr, uid, [('picking_id', 'in', ids)], context=context)
if existing_package_ids:
pack_operation_obj.unlink(cr, uid, existing_package_ids, context)
res = super(stock_picking, self).write(cr, uid, ids, vals, context=context)
#if we changed the move lines or the pack operations, we need to recompute the remaining quantities of both
if 'move_lines' in vals or 'pack_operation_ids' in vals:
self.do_recompute_remaining_quantities(cr, uid, ids, context=context)
return res
def _create_backorder(self, cr, uid, picking, backorder_moves=[], context=None):
""" Move all non-done lines into a new backorder picking. If the key 'do_only_split' is given in the context, then move all lines not in context.get('split', []) instead of all non-done lines.
"""
if not backorder_moves:
backorder_moves = picking.move_lines
backorder_move_ids = [x.id for x in backorder_moves if x.state not in ('done', 'cancel')]
if 'do_only_split' in context and context['do_only_split']:
backorder_move_ids = [x.id for x in backorder_moves if x.id not in context.get('split', [])]
if backorder_move_ids:
backorder_id = self.copy(cr, uid, picking.id, {
'name': '/',
'move_lines': [],
'pack_operation_ids': [],
'backorder_id': picking.id,
})
backorder = self.browse(cr, uid, backorder_id, context=context)
self.message_post(cr, uid, picking.id, body=_("Back order <em>%s</em> <b>created</b>.") % (backorder.name), context=context)
move_obj = self.pool.get("stock.move")
move_obj.write(cr, uid, backorder_move_ids, {'picking_id': backorder_id}, context=context)
self.write(cr, uid, [picking.id], {'date_done': time.strftime(DEFAULT_SERVER_DATETIME_FORMAT)}, context=context)
self.action_confirm(cr, uid, [backorder_id], context=context)
return backorder_id
return False
@api.cr_uid_ids_context
def recheck_availability(self, cr, uid, picking_ids, context=None):
self.action_assign(cr, uid, picking_ids, context=context)
self.do_prepare_partial(cr, uid, picking_ids, context=context)
def _get_top_level_packages(self, cr, uid, quants_suggested_locations, context=None):
"""This method searches for the higher level packages that can be moved as a single operation, given a list of quants
to move and their suggested destination, and returns the list of matching packages.
"""
# Try to find as much as possible top-level packages that can be moved
pack_obj = self.pool.get("stock.quant.package")
quant_obj = self.pool.get("stock.quant")
top_lvl_packages = set()
quants_to_compare = quants_suggested_locations.keys()
for pack in list(set([x.package_id for x in quants_suggested_locations.keys() if x and x.package_id])):
loop = True
test_pack = pack
good_pack = False
pack_destination = False
while loop:
pack_quants = pack_obj.get_content(cr, uid, [test_pack.id], context=context)
all_in = True
for quant in quant_obj.browse(cr, uid, pack_quants, context=context):
# If the quant is not in the quants to compare and not in the common location
if not quant in quants_to_compare:
all_in = False
break
else:
#if putaway strat apply, the destination location of each quant may be different (and thus the package should not be taken as a single operation)
if not pack_destination:
pack_destination = quants_suggested_locations[quant]
elif pack_destination != quants_suggested_locations[quant]:
all_in = False
break
if all_in:
good_pack = test_pack
if test_pack.parent_id:
test_pack = test_pack.parent_id
else:
#stop the loop when there's no parent package anymore
loop = False
else:
#stop the loop when the package test_pack is not totally reserved for moves of this picking
#(some quants may be reserved for other picking or not reserved at all)
loop = False
if good_pack:
top_lvl_packages.add(good_pack)
return list(top_lvl_packages)
def _prepare_pack_ops(self, cr, uid, picking, quants, forced_qties, context=None):
""" returns a list of dict, ready to be used in create() of stock.pack.operation.
:param picking: browse record (stock.picking)
:param quants: browse record list (stock.quant). List of quants associated to the picking
:param forced_qties: dictionary showing for each product (keys) its corresponding quantity (value) that is not covered by the quants associated to the picking
"""
def _picking_putaway_apply(product):
location = False
# Search putaway strategy
if product_putaway_strats.get(product.id):
location = product_putaway_strats[product.id]
else:
location = self.pool.get('stock.location').get_putaway_strategy(cr, uid, picking.location_dest_id, product, context=context)
product_putaway_strats[product.id] = location
return location or picking.location_dest_id.id
# If we encounter an UoM that is smaller than the default UoM or the one already chosen, use the new one instead.
product_uom = {} # Determines UoM used in pack operations
location_dest_id = None
location_id = None
for move in [x for x in picking.move_lines if x.state not in ('done', 'cancel')]:
if not product_uom.get(move.product_id.id):
product_uom[move.product_id.id] = move.product_id.uom_id
if move.product_uom.id != move.product_id.uom_id.id and move.product_uom.factor > product_uom[move.product_id.id].factor:
product_uom[move.product_id.id] = move.product_uom
if not move.scrapped:
if location_dest_id and move.location_dest_id.id != location_dest_id:
raise Warning(_('The destination location must be the same for all the moves of the picking.'))
location_dest_id = move.location_dest_id.id
if location_id and move.location_id.id != location_id:
raise Warning(_('The source location must be the same for all the moves of the picking.'))
location_id = move.location_id.id
pack_obj = self.pool.get("stock.quant.package")
quant_obj = self.pool.get("stock.quant")
vals = []
qtys_grouped = {}
#for each quant of the picking, find the suggested location
quants_suggested_locations = {}
product_putaway_strats = {}
for quant in quants:
if quant.qty <= 0:
continue
suggested_location_id = _picking_putaway_apply(quant.product_id)
quants_suggested_locations[quant] = suggested_location_id
#find the packages we can movei as a whole
top_lvl_packages = self._get_top_level_packages(cr, uid, quants_suggested_locations, context=context)
# and then create pack operations for the top-level packages found
for pack in top_lvl_packages:
pack_quant_ids = pack_obj.get_content(cr, uid, [pack.id], context=context)
pack_quants = quant_obj.browse(cr, uid, pack_quant_ids, context=context)
vals.append({
'picking_id': picking.id,
'package_id': pack.id,
'product_qty': 1.0,
'location_id': pack.location_id.id,
'location_dest_id': quants_suggested_locations[pack_quants[0]],
'owner_id': pack.owner_id.id,
})
#remove the quants inside the package so that they are excluded from the rest of the computation
for quant in pack_quants:
del quants_suggested_locations[quant]
# Go through all remaining reserved quants and group by product, package, lot, owner, source location and dest location
for quant, dest_location_id in quants_suggested_locations.items():
key = (quant.product_id.id, quant.package_id.id, quant.lot_id.id, quant.owner_id.id, quant.location_id.id, dest_location_id)
if qtys_grouped.get(key):
qtys_grouped[key] += quant.qty
else:
qtys_grouped[key] = quant.qty
# Do the same for the forced quantities (in cases of force_assign or incomming shipment for example)
for product, qty in forced_qties.items():
if qty <= 0:
continue
suggested_location_id = _picking_putaway_apply(product)
key = (product.id, False, False, picking.owner_id.id, picking.location_id.id, suggested_location_id)
if qtys_grouped.get(key):
qtys_grouped[key] += qty
else:
qtys_grouped[key] = qty
# Create the necessary operations for the grouped quants and remaining qtys
uom_obj = self.pool.get('product.uom')
prevals = {}
for key, qty in qtys_grouped.items():
product = self.pool.get("product.product").browse(cr, uid, key[0], context=context)
uom_id = product.uom_id.id
qty_uom = qty
if product_uom.get(key[0]):
uom_id = product_uom[key[0]].id
qty_uom = uom_obj._compute_qty(cr, uid, product.uom_id.id, qty, uom_id)
val_dict = {
'picking_id': picking.id,
'product_qty': qty_uom,
'product_id': key[0],
'package_id': key[1],
'lot_id': key[2],
'owner_id': key[3],
'location_id': key[4],
'location_dest_id': key[5],
'product_uom_id': uom_id,
}
if key[0] in prevals:
prevals[key[0]].append(val_dict)
else:
prevals[key[0]] = [val_dict]
# prevals var holds the operations in order to create them in the same order than the picking stock moves if possible
processed_products = set()
for move in [x for x in picking.move_lines if x.state not in ('done', 'cancel')]:
if move.product_id.id not in processed_products:
vals += prevals.get(move.product_id.id, [])
processed_products.add(move.product_id.id)
return vals
@api.cr_uid_ids_context
def open_barcode_interface(self, cr, uid, picking_ids, context=None):
final_url="/barcode/web/#action=stock.ui&picking_id="+str(picking_ids[0])
return {'type': 'ir.actions.act_url', 'url':final_url, 'target': 'self',}
@api.cr_uid_ids_context
def do_partial_open_barcode(self, cr, uid, picking_ids, context=None):
self.do_prepare_partial(cr, uid, picking_ids, context=context)
return self.open_barcode_interface(cr, uid, picking_ids, context=context)
@api.cr_uid_ids_context
def do_prepare_partial(self, cr, uid, picking_ids, context=None):
context = context or {}
pack_operation_obj = self.pool.get('stock.pack.operation')
#used to avoid recomputing the remaining quantities at each new pack operation created
ctx = context.copy()
ctx['no_recompute'] = True
#get list of existing operations and delete them
existing_package_ids = pack_operation_obj.search(cr, uid, [('picking_id', 'in', picking_ids)], context=context)
if existing_package_ids:
pack_operation_obj.unlink(cr, uid, existing_package_ids, context)
for picking in self.browse(cr, uid, picking_ids, context=context):
forced_qties = {} # Quantity remaining after calculating reserved quants
picking_quants = []
#Calculate packages, reserved quants, qtys of this picking's moves
for move in picking.move_lines:
if move.state not in ('assigned', 'confirmed', 'waiting'):
continue
move_quants = move.reserved_quant_ids
picking_quants += move_quants
forced_qty = (move.state == 'assigned') and move.product_qty - sum([x.qty for x in move_quants]) or 0
#if we used force_assign() on the move, or if the move is incoming, forced_qty > 0
if float_compare(forced_qty, 0, precision_rounding=move.product_id.uom_id.rounding) > 0:
if forced_qties.get(move.product_id):
forced_qties[move.product_id] += forced_qty
else:
forced_qties[move.product_id] = forced_qty
for vals in self._prepare_pack_ops(cr, uid, picking, picking_quants, forced_qties, context=context):
pack_operation_obj.create(cr, uid, vals, context=ctx)
#recompute the remaining quantities all at once
self.do_recompute_remaining_quantities(cr, uid, picking_ids, context=context)
self.write(cr, uid, picking_ids, {'recompute_pack_op': False}, context=context)
@api.cr_uid_ids_context
def do_unreserve(self, cr, uid, picking_ids, context=None):
"""
Will remove all quants for picking in picking_ids
"""
moves_to_unreserve = []
pack_line_to_unreserve = []
for picking in self.browse(cr, uid, picking_ids, context=context):
moves_to_unreserve += [m.id for m in picking.move_lines if m.state not in ('done', 'cancel')]
pack_line_to_unreserve += [p.id for p in picking.pack_operation_ids]
if moves_to_unreserve:
if pack_line_to_unreserve:
self.pool.get('stock.pack.operation').unlink(cr, uid, pack_line_to_unreserve, context=context)
self.pool.get('stock.move').do_unreserve(cr, uid, moves_to_unreserve, context=context)
def recompute_remaining_qty(self, cr, uid, picking, context=None):
def _create_link_for_index(operation_id, index, product_id, qty_to_assign, quant_id=False):
move_dict = prod2move_ids[product_id][index]
qty_on_link = min(move_dict['remaining_qty'], qty_to_assign)
self.pool.get('stock.move.operation.link').create(cr, uid, {'move_id': move_dict['move'].id, 'operation_id': operation_id, 'qty': qty_on_link, 'reserved_quant_id': quant_id}, context=context)
if move_dict['remaining_qty'] == qty_on_link:
prod2move_ids[product_id].pop(index)
else:
move_dict['remaining_qty'] -= qty_on_link
return qty_on_link
def _create_link_for_quant(operation_id, quant, qty):
"""create a link for given operation and reserved move of given quant, for the max quantity possible, and returns this quantity"""
if not quant.reservation_id.id:
return _create_link_for_product(operation_id, quant.product_id.id, qty)
qty_on_link = 0
for i in range(0, len(prod2move_ids[quant.product_id.id])):
if prod2move_ids[quant.product_id.id][i]['move'].id != quant.reservation_id.id:
continue
qty_on_link = _create_link_for_index(operation_id, i, quant.product_id.id, qty, quant_id=quant.id)
break
return qty_on_link
def _create_link_for_product(operation_id, product_id, qty):
'''method that creates the link between a given operation and move(s) of given product, for the given quantity.
Returns True if it was possible to create links for the requested quantity (False if there was not enough quantity on stock moves)'''
qty_to_assign = qty
prod_obj = self.pool.get("product.product")
product = prod_obj.browse(cr, uid, product_id)
rounding = product.uom_id.rounding
qtyassign_cmp = float_compare(qty_to_assign, 0.0, precision_rounding=rounding)
if prod2move_ids.get(product_id):
while prod2move_ids[product_id] and qtyassign_cmp > 0:
qty_on_link = _create_link_for_index(operation_id, 0, product_id, qty_to_assign, quant_id=False)
qty_to_assign -= qty_on_link
qtyassign_cmp = float_compare(qty_to_assign, 0.0, precision_rounding=rounding)
return qtyassign_cmp == 0
uom_obj = self.pool.get('product.uom')
package_obj = self.pool.get('stock.quant.package')
quant_obj = self.pool.get('stock.quant')
link_obj = self.pool.get('stock.move.operation.link')
quants_in_package_done = set()
prod2move_ids = {}
still_to_do = []
#make a dictionary giving for each product, the moves and related quantity that can be used in operation links
for move in [x for x in picking.move_lines if x.state not in ('done', 'cancel')]:
if not prod2move_ids.get(move.product_id.id):
prod2move_ids[move.product_id.id] = [{'move': move, 'remaining_qty': move.product_qty}]
else:
prod2move_ids[move.product_id.id].append({'move': move, 'remaining_qty': move.product_qty})
need_rereserve = False
#sort the operations in order to give higher priority to those with a package, then a serial number
operations = picking.pack_operation_ids
operations = sorted(operations, key=lambda x: ((x.package_id and not x.product_id) and -4 or 0) + (x.package_id and -2 or 0) + (x.lot_id and -1 or 0))
#delete existing operations to start again from scratch
links = link_obj.search(cr, uid, [('operation_id', 'in', [x.id for x in operations])], context=context)
if links:
link_obj.unlink(cr, uid, links, context=context)
#1) first, try to create links when quants can be identified without any doubt
for ops in operations:
#for each operation, create the links with the stock move by seeking on the matching reserved quants,
#and deffer the operation if there is some ambiguity on the move to select
if ops.package_id and not ops.product_id:
#entire package
quant_ids = package_obj.get_content(cr, uid, [ops.package_id.id], context=context)
for quant in quant_obj.browse(cr, uid, quant_ids, context=context):
remaining_qty_on_quant = quant.qty
if quant.reservation_id:
#avoid quants being counted twice
quants_in_package_done.add(quant.id)
qty_on_link = _create_link_for_quant(ops.id, quant, quant.qty)
remaining_qty_on_quant -= qty_on_link
if remaining_qty_on_quant:
still_to_do.append((ops, quant.product_id.id, remaining_qty_on_quant))
need_rereserve = True
elif ops.product_id.id:
#Check moves with same product
qty_to_assign = uom_obj._compute_qty_obj(cr, uid, ops.product_uom_id, ops.product_qty, ops.product_id.uom_id, context=context)
for move_dict in prod2move_ids.get(ops.product_id.id, []):
move = move_dict['move']
for quant in move.reserved_quant_ids:
if not qty_to_assign > 0:
break
if quant.id in quants_in_package_done:
continue
#check if the quant is matching the operation details
if ops.package_id:
flag = quant.package_id and bool(package_obj.search(cr, uid, [('id', 'child_of', [ops.package_id.id])], context=context)) or False
else:
flag = not quant.package_id.id
flag = flag and ((ops.lot_id and ops.lot_id.id == quant.lot_id.id) or not ops.lot_id)
flag = flag and (ops.owner_id.id == quant.owner_id.id)
if flag:
max_qty_on_link = min(quant.qty, qty_to_assign)
qty_on_link = _create_link_for_quant(ops.id, quant, max_qty_on_link)
qty_to_assign -= qty_on_link
qty_assign_cmp = float_compare(qty_to_assign, 0, precision_rounding=ops.product_id.uom_id.rounding)
if qty_assign_cmp > 0:
#qty reserved is less than qty put in operations. We need to create a link but it's deferred after we processed
#all the quants (because they leave no choice on their related move and needs to be processed with higher priority)
still_to_do += [(ops, ops.product_id.id, qty_to_assign)]
need_rereserve = True
#2) then, process the remaining part
all_op_processed = True
for ops, product_id, remaining_qty in still_to_do:
all_op_processed = _create_link_for_product(ops.id, product_id, remaining_qty) and all_op_processed
return (need_rereserve, all_op_processed)
def picking_recompute_remaining_quantities(self, cr, uid, picking, context=None):
need_rereserve = False
all_op_processed = True
if picking.pack_operation_ids:
need_rereserve, all_op_processed = self.recompute_remaining_qty(cr, uid, picking, context=context)
return need_rereserve, all_op_processed
@api.cr_uid_ids_context
def do_recompute_remaining_quantities(self, cr, uid, picking_ids, context=None):
for picking in self.browse(cr, uid, picking_ids, context=context):
if picking.pack_operation_ids:
self.recompute_remaining_qty(cr, uid, picking, context=context)
def _prepare_values_extra_move(self, cr, uid, op, product, remaining_qty, context=None):
"""
Creates an extra move when there is no corresponding original move to be copied
"""
uom_obj = self.pool.get("product.uom")
uom_id = product.uom_id.id
qty = remaining_qty
if op.product_id and op.product_uom_id and op.product_uom_id.id != product.uom_id.id:
if op.product_uom_id.factor > product.uom_id.factor: #If the pack operation's is a smaller unit
uom_id = op.product_uom_id.id
#HALF-UP rounding as only rounding errors will be because of propagation of error from default UoM
qty = uom_obj._compute_qty_obj(cr, uid, product.uom_id, remaining_qty, op.product_uom_id, rounding_method='HALF-UP')
picking = op.picking_id
ref = product.default_code
name = '[' + ref + ']' + ' ' + product.name if ref else product.name
res = {
'picking_id': picking.id,
'location_id': picking.location_id.id,
'location_dest_id': picking.location_dest_id.id,
'product_id': product.id,
'product_uom': uom_id,
'product_uom_qty': qty,
'name': _('Extra Move: ') + name,
'state': 'draft',
'restrict_partner_id': op.owner_id,
}
return res
def _create_extra_moves(self, cr, uid, picking, context=None):
'''This function creates move lines on a picking, at the time of do_transfer, based on
unexpected product transfers (or exceeding quantities) found in the pack operations.
'''
move_obj = self.pool.get('stock.move')
operation_obj = self.pool.get('stock.pack.operation')
moves = []
for op in picking.pack_operation_ids:
for product_id, remaining_qty in operation_obj._get_remaining_prod_quantities(cr, uid, op, context=context).items():
product = self.pool.get('product.product').browse(cr, uid, product_id, context=context)
if float_compare(remaining_qty, 0, precision_rounding=product.uom_id.rounding) > 0:
vals = self._prepare_values_extra_move(cr, uid, op, product, remaining_qty, context=context)
moves.append(move_obj.create(cr, uid, vals, context=context))
if moves:
move_obj.action_confirm(cr, uid, moves, context=context)
return moves
def rereserve_pick(self, cr, uid, ids, context=None):
"""
This can be used to provide a button that rereserves taking into account the existing pack operations
"""
for pick in self.browse(cr, uid, ids, context=context):
self.rereserve_quants(cr, uid, pick, move_ids = [x.id for x in pick.move_lines], context=context)
def rereserve_quants(self, cr, uid, picking, move_ids=[], context=None):
""" Unreserve quants then try to reassign quants."""
stock_move_obj = self.pool.get('stock.move')
if not move_ids:
self.do_unreserve(cr, uid, [picking.id], context=context)
self.action_assign(cr, uid, [picking.id], context=context)
else:
stock_move_obj.do_unreserve(cr, uid, move_ids, context=context)
stock_move_obj.action_assign(cr, uid, move_ids, context=context)
@api.cr_uid_ids_context
def do_enter_transfer_details(self, cr, uid, picking, context=None):
if not context:
context = {}
context.update({
'active_model': self._name,
'active_ids': picking,
'active_id': len(picking) and picking[0] or False
})
created_id = self.pool['stock.transfer_details'].create(cr, uid, {'picking_id': len(picking) and picking[0] or False}, context)
return self.pool['stock.transfer_details'].wizard_view(cr, uid, created_id, context)
@api.cr_uid_ids_context
def do_transfer(self, cr, uid, picking_ids, context=None):
"""
If no pack operation, we do simple action_done of the picking
Otherwise, do the pack operations
"""
if not context:
context = {}
stock_move_obj = self.pool.get('stock.move')
for picking in self.browse(cr, uid, picking_ids, context=context):
if not picking.pack_operation_ids:
self.action_done(cr, uid, [picking.id], context=context)
continue
else:
need_rereserve, all_op_processed = self.picking_recompute_remaining_quantities(cr, uid, picking, context=context)
#create extra moves in the picking (unexpected product moves coming from pack operations)
todo_move_ids = []
if not all_op_processed:
todo_move_ids += self._create_extra_moves(cr, uid, picking, context=context)
#split move lines if needed
toassign_move_ids = []
for move in picking.move_lines:
remaining_qty = move.remaining_qty
if move.state in ('done', 'cancel'):
#ignore stock moves cancelled or already done
continue
elif move.state == 'draft':
toassign_move_ids.append(move.id)
if float_compare(remaining_qty, 0, precision_rounding = move.product_id.uom_id.rounding) == 0:
if move.state in ('draft', 'assigned', 'confirmed'):
todo_move_ids.append(move.id)
elif float_compare(remaining_qty,0, precision_rounding = move.product_id.uom_id.rounding) > 0 and \
float_compare(remaining_qty, move.product_qty, precision_rounding = move.product_id.uom_id.rounding) < 0:
new_move = stock_move_obj.split(cr, uid, move, remaining_qty, context=context)
todo_move_ids.append(move.id)
#Assign move as it was assigned before
toassign_move_ids.append(new_move)
if need_rereserve or not all_op_processed:
if not picking.location_id.usage in ("supplier", "production", "inventory"):
self.rereserve_quants(cr, uid, picking, move_ids=todo_move_ids, context=context)
self.do_recompute_remaining_quantities(cr, uid, [picking.id], context=context)
if todo_move_ids and not context.get('do_only_split'):
self.pool.get('stock.move').action_done(cr, uid, todo_move_ids, context=context)
elif context.get('do_only_split'):
context = dict(context, split=todo_move_ids)
self._create_backorder(cr, uid, picking, context=context)
if toassign_move_ids:
stock_move_obj.action_assign(cr, uid, toassign_move_ids, context=context)
return True
@api.cr_uid_ids_context
def do_split(self, cr, uid, picking_ids, context=None):
""" just split the picking (create a backorder) without making it 'done' """
if context is None:
context = {}
ctx = context.copy()
ctx['do_only_split'] = True
return self.do_transfer(cr, uid, picking_ids, context=ctx)
def get_next_picking_for_ui(self, cr, uid, context=None):
""" returns the next pickings to process. Used in the barcode scanner UI"""
if context is None:
context = {}
domain = [('state', 'in', ('assigned', 'partially_available'))]
if context.get('default_picking_type_id'):
domain.append(('picking_type_id', '=', context['default_picking_type_id']))
return self.search(cr, uid, domain, context=context)
def action_done_from_ui(self, cr, uid, picking_id, context=None):
""" called when button 'done' is pushed in the barcode scanner UI """
#write qty_done into field product_qty for every package_operation before doing the transfer
pack_op_obj = self.pool.get('stock.pack.operation')
for operation in self.browse(cr, uid, picking_id, context=context).pack_operation_ids:
pack_op_obj.write(cr, uid, operation.id, {'product_qty': operation.qty_done}, context=context)
self.do_transfer(cr, uid, [picking_id], context=context)
#return id of next picking to work on
return self.get_next_picking_for_ui(cr, uid, context=context)
@api.cr_uid_ids_context
def action_pack(self, cr, uid, picking_ids, operation_filter_ids=None, context=None):
""" Create a package with the current pack_operation_ids of the picking that aren't yet in a pack.
Used in the barcode scanner UI and the normal interface as well.
operation_filter_ids is used by barcode scanner interface to specify a subset of operation to pack"""
if operation_filter_ids == None:
operation_filter_ids = []
stock_operation_obj = self.pool.get('stock.pack.operation')
package_obj = self.pool.get('stock.quant.package')
stock_move_obj = self.pool.get('stock.move')
package_id = False
for picking_id in picking_ids:
operation_search_domain = [('picking_id', '=', picking_id), ('result_package_id', '=', False)]
if operation_filter_ids != []:
operation_search_domain.append(('id', 'in', operation_filter_ids))
operation_ids = stock_operation_obj.search(cr, uid, operation_search_domain, context=context)
pack_operation_ids = []
if operation_ids:
for operation in stock_operation_obj.browse(cr, uid, operation_ids, context=context):
#If we haven't done all qty in operation, we have to split into 2 operation
op = operation
if (operation.qty_done < operation.product_qty):
new_operation = stock_operation_obj.copy(cr, uid, operation.id, {'product_qty': operation.qty_done,'qty_done': operation.qty_done}, context=context)
stock_operation_obj.write(cr, uid, operation.id, {'product_qty': operation.product_qty - operation.qty_done,'qty_done': 0, 'lot_id': False}, context=context)
op = stock_operation_obj.browse(cr, uid, new_operation, context=context)
pack_operation_ids.append(op.id)
if op.product_id and op.location_id and op.location_dest_id:
stock_move_obj.check_tracking_product(cr, uid, op.product_id, op.lot_id.id, op.location_id, op.location_dest_id, context=context)
package_id = package_obj.create(cr, uid, {}, context=context)
stock_operation_obj.write(cr, uid, pack_operation_ids, {'result_package_id': package_id}, context=context)
return package_id
def process_product_id_from_ui(self, cr, uid, picking_id, product_id, op_id, increment=True, context=None):
return self.pool.get('stock.pack.operation')._search_and_increment(cr, uid, picking_id, [('product_id', '=', product_id),('id', '=', op_id)], increment=increment, context=context)
def process_barcode_from_ui(self, cr, uid, picking_id, barcode_str, visible_op_ids, context=None):
'''This function is called each time there barcode scanner reads an input'''
lot_obj = self.pool.get('stock.production.lot')
package_obj = self.pool.get('stock.quant.package')
product_obj = self.pool.get('product.product')
stock_operation_obj = self.pool.get('stock.pack.operation')
stock_location_obj = self.pool.get('stock.location')
answer = {'filter_loc': False, 'operation_id': False}
#check if the barcode correspond to a location
matching_location_ids = stock_location_obj.search(cr, uid, [('loc_barcode', '=', barcode_str)], context=context)
if matching_location_ids:
#if we have a location, return immediatly with the location name
location = stock_location_obj.browse(cr, uid, matching_location_ids[0], context=None)
answer['filter_loc'] = stock_location_obj._name_get(cr, uid, location, context=None)
answer['filter_loc_id'] = matching_location_ids[0]
return answer
#check if the barcode correspond to a product
matching_product_ids = product_obj.search(cr, uid, ['|', ('ean13', '=', barcode_str), ('default_code', '=', barcode_str)], context=context)
if matching_product_ids:
op_id = stock_operation_obj._search_and_increment(cr, uid, picking_id, [('product_id', '=', matching_product_ids[0])], filter_visible=True, visible_op_ids=visible_op_ids, increment=True, context=context)
answer['operation_id'] = op_id
return answer
#check if the barcode correspond to a lot
matching_lot_ids = lot_obj.search(cr, uid, [('name', '=', barcode_str)], context=context)
if matching_lot_ids:
lot = lot_obj.browse(cr, uid, matching_lot_ids[0], context=context)
op_id = stock_operation_obj._search_and_increment(cr, uid, picking_id, [('product_id', '=', lot.product_id.id), ('lot_id', '=', lot.id)], filter_visible=True, visible_op_ids=visible_op_ids, increment=True, context=context)
answer['operation_id'] = op_id
return answer
#check if the barcode correspond to a package
matching_package_ids = package_obj.search(cr, uid, [('name', '=', barcode_str)], context=context)
if matching_package_ids:
op_id = stock_operation_obj._search_and_increment(cr, uid, picking_id, [('package_id', '=', matching_package_ids[0])], filter_visible=True, visible_op_ids=visible_op_ids, increment=True, context=context)
answer['operation_id'] = op_id
return answer
return answer
class stock_production_lot(osv.osv):
_name = 'stock.production.lot'
_inherit = ['mail.thread']
_description = 'Lot/Serial'
_columns = {
'name': fields.char('Serial Number', required=True, help="Unique Serial Number"),
'ref': fields.char('Internal Reference', help="Internal reference number in case it differs from the manufacturer's serial number"),
'product_id': fields.many2one('product.product', 'Product', required=True, domain=[('type', '<>', 'service')]),
'quant_ids': fields.one2many('stock.quant', 'lot_id', 'Quants', readonly=True),
'create_date': fields.datetime('Creation Date'),
}
_defaults = {
'name': lambda x, y, z, c: x.pool.get('ir.sequence').get(y, z, 'stock.lot.serial'),
'product_id': lambda x, y, z, c: c.get('product_id', False),
}
_sql_constraints = [
('name_ref_uniq', 'unique (name, ref, product_id)', 'The combination of serial number, internal reference and product must be unique !'),
]
def action_traceability(self, cr, uid, ids, context=None):
""" It traces the information of lots
@param self: The object pointer.
@param cr: A database cursor
@param uid: ID of the user currently logged in
@param ids: List of IDs selected
@param context: A standard dictionary
@return: A dictionary of values
"""
quant_obj = self.pool.get("stock.quant")
quants = quant_obj.search(cr, uid, [('lot_id', 'in', ids)], context=context)
moves = set()
for quant in quant_obj.browse(cr, uid, quants, context=context):
moves |= {move.id for move in quant.history_ids}
if moves:
return {
'domain': "[('id','in',[" + ','.join(map(str, list(moves))) + "])]",
'name': _('Traceability'),
'view_mode': 'tree,form',
'view_type': 'form',
'context': {'tree_view_ref': 'stock.view_move_tree'},
'res_model': 'stock.move',
'type': 'ir.actions.act_window',
}
return False
# ----------------------------------------------------
# Move
# ----------------------------------------------------
class stock_move(osv.osv):
_name = "stock.move"
_description = "Stock Move"
_order = 'date_expected desc, id'
_log_create = False
def get_price_unit(self, cr, uid, move, context=None):
""" Returns the unit price to store on the quant """
return move.price_unit or move.product_id.standard_price
def name_get(self, cr, uid, ids, context=None):
res = []
for line in self.browse(cr, uid, ids, context=context):
name = line.location_id.name + ' > ' + line.location_dest_id.name
if line.product_id.code:
name = line.product_id.code + ': ' + name
if line.picking_id.origin:
name = line.picking_id.origin + '/ ' + name
res.append((line.id, name))
return res
def _quantity_normalize(self, cr, uid, ids, name, args, context=None):
uom_obj = self.pool.get('product.uom')
res = {}
for m in self.browse(cr, uid, ids, context=context):
res[m.id] = uom_obj._compute_qty_obj(cr, uid, m.product_uom, m.product_uom_qty, m.product_id.uom_id, context=context)
return res
def _get_remaining_qty(self, cr, uid, ids, field_name, args, context=None):
uom_obj = self.pool.get('product.uom')
res = {}
for move in self.browse(cr, uid, ids, context=context):
qty = move.product_qty
for record in move.linked_move_operation_ids:
qty -= record.qty
# Keeping in product default UoM
res[move.id] = float_round(qty, precision_rounding=move.product_id.uom_id.rounding)
return res
def _get_lot_ids(self, cr, uid, ids, field_name, args, context=None):
res = dict.fromkeys(ids, False)
for move in self.browse(cr, uid, ids, context=context):
if move.state == 'done':
res[move.id] = [q.lot_id.id for q in move.quant_ids if q.lot_id]
else:
res[move.id] = [q.lot_id.id for q in move.reserved_quant_ids if q.lot_id]
return res
def _get_product_availability(self, cr, uid, ids, field_name, args, context=None):
quant_obj = self.pool.get('stock.quant')
res = dict.fromkeys(ids, False)
for move in self.browse(cr, uid, ids, context=context):
if move.state == 'done':
res[move.id] = move.product_qty
else:
sublocation_ids = self.pool.get('stock.location').search(cr, uid, [('id', 'child_of', [move.location_id.id])], context=context)
quant_ids = quant_obj.search(cr, uid, [('location_id', 'in', sublocation_ids), ('product_id', '=', move.product_id.id), ('reservation_id', '=', False)], context=context)
availability = 0
for quant in quant_obj.browse(cr, uid, quant_ids, context=context):
availability += quant.qty
res[move.id] = min(move.product_qty, availability)
return res
def _get_string_qty_information(self, cr, uid, ids, field_name, args, context=None):
settings_obj = self.pool.get('stock.config.settings')
uom_obj = self.pool.get('product.uom')
res = dict.fromkeys(ids, '')
for move in self.browse(cr, uid, ids, context=context):
if move.state in ('draft', 'done', 'cancel') or move.location_id.usage != 'internal':
res[move.id] = '' # 'not applicable' or 'n/a' could work too
continue
total_available = min(move.product_qty, move.reserved_availability + move.availability)
total_available = uom_obj._compute_qty_obj(cr, uid, move.product_id.uom_id, total_available, move.product_uom, context=context)
info = str(total_available)
#look in the settings if we need to display the UoM name or not
config_ids = settings_obj.search(cr, uid, [], limit=1, order='id DESC', context=context)
if config_ids:
stock_settings = settings_obj.browse(cr, uid, config_ids[0], context=context)
if stock_settings.group_uom:
info += ' ' + move.product_uom.name
if move.reserved_availability:
if move.reserved_availability != total_available:
#some of the available quantity is assigned and some are available but not reserved
reserved_available = uom_obj._compute_qty_obj(cr, uid, move.product_id.uom_id, move.reserved_availability, move.product_uom, context=context)
info += _(' (%s reserved)') % str(reserved_available)
else:
#all available quantity is assigned
info += _(' (reserved)')
res[move.id] = info
return res
def _get_reserved_availability(self, cr, uid, ids, field_name, args, context=None):
res = dict.fromkeys(ids, 0)
for move in self.browse(cr, uid, ids, context=context):
res[move.id] = sum([quant.qty for quant in move.reserved_quant_ids])
return res
def _get_move(self, cr, uid, ids, context=None):
res = set()
for quant in self.browse(cr, uid, ids, context=context):
if quant.reservation_id:
res.add(quant.reservation_id.id)
return list(res)
def _get_move_ids(self, cr, uid, ids, context=None):
res = []
for picking in self.browse(cr, uid, ids, context=context):
res += [x.id for x in picking.move_lines]
return res
def _get_moves_from_prod(self, cr, uid, ids, context=None):
if ids:
return self.pool.get('stock.move').search(cr, uid, [('product_id', 'in', ids)], context=context)
return []
def _set_product_qty(self, cr, uid, id, field, value, arg, context=None):
""" The meaning of product_qty field changed lately and is now a functional field computing the quantity
in the default product UoM. This code has been added to raise an error if a write is made given a value
for `product_qty`, where the same write should set the `product_uom_qty` field instead, in order to
detect errors.
"""
raise osv.except_osv(_('Programming Error!'), _('The requested operation cannot be processed because of a programming error setting the `product_qty` field instead of the `product_uom_qty`.'))
_columns = {
'name': fields.char('Description', required=True, select=True),
'priority': fields.selection(procurement.PROCUREMENT_PRIORITIES, 'Priority'),
'create_date': fields.datetime('Creation Date', readonly=True, select=True),
'date': fields.datetime('Date', required=True, select=True, help="Move date: scheduled date until move is done, then date of actual move processing", states={'done': [('readonly', True)]}),
'date_expected': fields.datetime('Expected Date', states={'done': [('readonly', True)]}, required=True, select=True, help="Scheduled date for the processing of this move"),
'product_id': fields.many2one('product.product', 'Product', required=True, select=True, domain=[('type', '<>', 'service')], states={'done': [('readonly', True)]}),
'product_qty': fields.function(_quantity_normalize, fnct_inv=_set_product_qty, type='float', digits=0, store={
_name: (lambda self, cr, uid, ids, c={}: ids, ['product_id', 'product_uom', 'product_uom_qty'], 10),
}, string='Quantity',
help='Quantity in the default UoM of the product'),
'product_uom_qty': fields.float('Quantity', digits_compute=dp.get_precision('Product Unit of Measure'),
required=True, states={'done': [('readonly', True)]},
help="This is the quantity of products from an inventory "
"point of view. For moves in the state 'done', this is the "
"quantity of products that were actually moved. For other "
"moves, this is the quantity of product that is planned to "
"be moved. Lowering this quantity does not generate a "
"backorder. Changing this quantity on assigned moves affects "
"the product reservation, and should be done with care."
),
'product_uom': fields.many2one('product.uom', 'Unit of Measure', required=True, states={'done': [('readonly', True)]}),
'product_uos_qty': fields.float('Quantity (UOS)', digits_compute=dp.get_precision('Product Unit of Measure'), states={'done': [('readonly', True)]}),
'product_uos': fields.many2one('product.uom', 'Product UOS', states={'done': [('readonly', True)]}),
'product_tmpl_id': fields.related('product_id', 'product_tmpl_id', type='many2one', relation='product.template', string='Product Template'),
'product_packaging': fields.many2one('product.packaging', 'Prefered Packaging', help="It specifies attributes of packaging like type, quantity of packaging,etc."),
'location_id': fields.many2one('stock.location', 'Source Location', required=True, select=True, auto_join=True,
states={'done': [('readonly', True)]}, help="Sets a location if you produce at a fixed location. This can be a partner location if you subcontract the manufacturing operations."),
'location_dest_id': fields.many2one('stock.location', 'Destination Location', required=True, states={'done': [('readonly', True)]}, select=True,
auto_join=True, help="Location where the system will stock the finished products."),
'partner_id': fields.many2one('res.partner', 'Destination Address ', states={'done': [('readonly', True)]}, help="Optional address where goods are to be delivered, specifically used for allotment"),
'move_dest_id': fields.many2one('stock.move', 'Destination Move', help="Optional: next stock move when chaining them", select=True, copy=False),
'move_orig_ids': fields.one2many('stock.move', 'move_dest_id', 'Original Move', help="Optional: previous stock move when chaining them", select=True),
'picking_id': fields.many2one('stock.picking', 'Reference', select=True, states={'done': [('readonly', True)]}),
'note': fields.text('Notes'),
'state': fields.selection([('draft', 'New'),
('cancel', 'Cancelled'),
('waiting', 'Waiting Another Move'),
('confirmed', 'Waiting Availability'),
('assigned', 'Available'),
('done', 'Done'),
], 'Status', readonly=True, select=True, copy=False,
help= "* New: When the stock move is created and not yet confirmed.\n"\
"* Waiting Another Move: This state can be seen when a move is waiting for another one, for example in a chained flow.\n"\
"* Waiting Availability: This state is reached when the procurement resolution is not straight forward. It may need the scheduler to run, a component to me manufactured...\n"\
"* Available: When products are reserved, it is set to \'Available\'.\n"\
"* Done: When the shipment is processed, the state is \'Done\'."),
'partially_available': fields.boolean('Partially Available', readonly=True, help="Checks if the move has some stock reserved", copy=False),
'price_unit': fields.float('Unit Price', help="Technical field used to record the product cost set by the user during a picking confirmation (when costing method used is 'average price' or 'real'). Value given in company currency and in product uom."), # as it's a technical field, we intentionally don't provide the digits attribute
'company_id': fields.many2one('res.company', 'Company', required=True, select=True),
'split_from': fields.many2one('stock.move', string="Move Split From", help="Technical field used to track the origin of a split move, which can be useful in case of debug", copy=False),
'backorder_id': fields.related('picking_id', 'backorder_id', type='many2one', relation="stock.picking", string="Back Order of", select=True),
'origin': fields.char("Source"),
'procure_method': fields.selection([('make_to_stock', 'Default: Take From Stock'), ('make_to_order', 'Advanced: Apply Procurement Rules')], 'Supply Method', required=True,
help="""By default, the system will take from the stock in the source location and passively wait for availability. The other possibility allows you to directly create a procurement on the source location (and thus ignore its current stock) to gather products. If we want to chain moves and have this one to wait for the previous, this second option should be chosen."""),
# used for colors in tree views:
'scrapped': fields.related('location_dest_id', 'scrap_location', type='boolean', relation='stock.location', string='Scrapped', readonly=True),
'quant_ids': fields.many2many('stock.quant', 'stock_quant_move_rel', 'move_id', 'quant_id', 'Moved Quants', copy=False),
'reserved_quant_ids': fields.one2many('stock.quant', 'reservation_id', 'Reserved quants'),
'linked_move_operation_ids': fields.one2many('stock.move.operation.link', 'move_id', string='Linked Operations', readonly=True, help='Operations that impact this move for the computation of the remaining quantities'),
'remaining_qty': fields.function(_get_remaining_qty, type='float', string='Remaining Quantity', digits=0,
states={'done': [('readonly', True)]}, help="Remaining Quantity in default UoM according to operations matched with this move"),
'procurement_id': fields.many2one('procurement.order', 'Procurement'),
'group_id': fields.many2one('procurement.group', 'Procurement Group'),
'rule_id': fields.many2one('procurement.rule', 'Procurement Rule', help='The pull rule that created this stock move'),
'push_rule_id': fields.many2one('stock.location.path', 'Push Rule', help='The push rule that created this stock move'),
'propagate': fields.boolean('Propagate cancel and split', help='If checked, when this move is cancelled, cancel the linked move too'),
'picking_type_id': fields.many2one('stock.picking.type', 'Picking Type'),
'inventory_id': fields.many2one('stock.inventory', 'Inventory'),
'lot_ids': fields.function(_get_lot_ids, type='many2many', relation='stock.production.lot', string='Lots'),
'origin_returned_move_id': fields.many2one('stock.move', 'Origin return move', help='move that created the return move', copy=False),
'returned_move_ids': fields.one2many('stock.move', 'origin_returned_move_id', 'All returned moves', help='Optional: all returned moves created from this move'),
'reserved_availability': fields.function(_get_reserved_availability, type='float', string='Quantity Reserved', readonly=True, help='Quantity that has already been reserved for this move'),
'availability': fields.function(_get_product_availability, type='float', string='Quantity Available', readonly=True, help='Quantity in stock that can still be reserved for this move'),
'string_availability_info': fields.function(_get_string_qty_information, type='text', string='Availability', readonly=True, help='Show various information on stock availability for this move'),
'restrict_lot_id': fields.many2one('stock.production.lot', 'Lot', help="Technical field used to depict a restriction on the lot of quants to consider when marking this move as 'done'"),
'restrict_partner_id': fields.many2one('res.partner', 'Owner ', help="Technical field used to depict a restriction on the ownership of quants to consider when marking this move as 'done'"),
'route_ids': fields.many2many('stock.location.route', 'stock_location_route_move', 'move_id', 'route_id', 'Destination route', help="Preferred route to be followed by the procurement order"),
'warehouse_id': fields.many2one('stock.warehouse', 'Warehouse', help="Technical field depicting the warehouse to consider for the route selection on the next procurement (if any)."),
}
def _default_location_destination(self, cr, uid, context=None):
context = context or {}
if context.get('default_picking_type_id', False):
pick_type = self.pool.get('stock.picking.type').browse(cr, uid, context['default_picking_type_id'], context=context)
return pick_type.default_location_dest_id and pick_type.default_location_dest_id.id or False
return False
def _default_location_source(self, cr, uid, context=None):
context = context or {}
if context.get('default_picking_type_id', False):
pick_type = self.pool.get('stock.picking.type').browse(cr, uid, context['default_picking_type_id'], context=context)
return pick_type.default_location_src_id and pick_type.default_location_src_id.id or False
return False
def _default_destination_address(self, cr, uid, context=None):
return False
def _default_group_id(self, cr, uid, context=None):
context = context or {}
if context.get('default_picking_id', False):
picking = self.pool.get('stock.picking').browse(cr, uid, context['default_picking_id'], context=context)
return picking.group_id.id
return False
_defaults = {
'location_id': _default_location_source,
'location_dest_id': _default_location_destination,
'partner_id': _default_destination_address,
'state': 'draft',
'priority': '1',
'product_uom_qty': 1.0,
'scrapped': False,
'date': fields.datetime.now,
'company_id': lambda self, cr, uid, c: self.pool.get('res.company')._company_default_get(cr, uid, 'stock.move', context=c),
'date_expected': fields.datetime.now,
'procure_method': 'make_to_stock',
'propagate': True,
'partially_available': False,
'group_id': _default_group_id,
}
def _check_uom(self, cr, uid, ids, context=None):
for move in self.browse(cr, uid, ids, context=context):
if move.product_id.uom_id.category_id.id != move.product_uom.category_id.id:
return False
return True
_constraints = [
(_check_uom,
'You try to move a product using a UoM that is not compatible with the UoM of the product moved. Please use an UoM in the same UoM category.',
['product_uom']),
]
def init(self, cr):
cr.execute('SELECT indexname FROM pg_indexes WHERE indexname = %s', ('stock_move_product_location_index',))
if not cr.fetchone():
cr.execute('CREATE INDEX stock_move_product_location_index ON stock_move (product_id, location_id, location_dest_id, company_id, state)')
@api.cr_uid_ids_context
def do_unreserve(self, cr, uid, move_ids, context=None):
quant_obj = self.pool.get("stock.quant")
for move in self.browse(cr, uid, move_ids, context=context):
if move.state in ('done', 'cancel'):
raise osv.except_osv(_('Operation Forbidden!'), _('Cannot unreserve a done move'))
quant_obj.quants_unreserve(cr, uid, move, context=context)
if self.find_move_ancestors(cr, uid, move, context=context):
self.write(cr, uid, [move.id], {'state': 'waiting'}, context=context)
else:
self.write(cr, uid, [move.id], {'state': 'confirmed'}, context=context)
def _prepare_procurement_from_move(self, cr, uid, move, context=None):
origin = (move.group_id and (move.group_id.name + ":") or "") + (move.rule_id and move.rule_id.name or move.origin or move.picking_id.name or "/")
group_id = move.group_id and move.group_id.id or False
if move.rule_id:
if move.rule_id.group_propagation_option == 'fixed' and move.rule_id.group_id:
group_id = move.rule_id.group_id.id
elif move.rule_id.group_propagation_option == 'none':
group_id = False
return {
'name': move.rule_id and move.rule_id.name or "/",
'origin': origin,
'company_id': move.company_id and move.company_id.id or False,
'date_planned': move.date,
'product_id': move.product_id.id,
'product_qty': move.product_uom_qty,
'product_uom': move.product_uom.id,
'product_uos_qty': (move.product_uos and move.product_uos_qty) or move.product_uom_qty,
'product_uos': (move.product_uos and move.product_uos.id) or move.product_uom.id,
'location_id': move.location_id.id,
'move_dest_id': move.id,
'group_id': group_id,
'route_ids': [(4, x.id) for x in move.route_ids],
'warehouse_id': move.warehouse_id.id or (move.picking_type_id and move.picking_type_id.warehouse_id.id or False),
'priority': move.priority,
}
def _push_apply(self, cr, uid, moves, context=None):
push_obj = self.pool.get("stock.location.path")
for move in moves:
#1) if the move is already chained, there is no need to check push rules
#2) if the move is a returned move, we don't want to check push rules, as returning a returned move is the only decent way
# to receive goods without triggering the push rules again (which would duplicate chained operations)
if not move.move_dest_id and not move.origin_returned_move_id:
domain = [('location_from_id', '=', move.location_dest_id.id)]
#priority goes to the route defined on the product and product category
route_ids = [x.id for x in move.product_id.route_ids + move.product_id.categ_id.total_route_ids]
rules = push_obj.search(cr, uid, domain + [('route_id', 'in', route_ids)], order='route_sequence, sequence', context=context)
if not rules:
#then we search on the warehouse if a rule can apply
wh_route_ids = []
if move.warehouse_id:
wh_route_ids = [x.id for x in move.warehouse_id.route_ids]
elif move.picking_type_id and move.picking_type_id.warehouse_id:
wh_route_ids = [x.id for x in move.picking_type_id.warehouse_id.route_ids]
if wh_route_ids:
rules = push_obj.search(cr, uid, domain + [('route_id', 'in', wh_route_ids)], order='route_sequence, sequence', context=context)
if not rules:
#if no specialized push rule has been found yet, we try to find a general one (without route)
rules = push_obj.search(cr, uid, domain + [('route_id', '=', False)], order='sequence', context=context)
if rules:
rule = push_obj.browse(cr, uid, rules[0], context=context)
push_obj._apply(cr, uid, rule, move, context=context)
return True
def _create_procurement(self, cr, uid, move, context=None):
""" This will create a procurement order """
return self.pool.get("procurement.order").create(cr, uid, self._prepare_procurement_from_move(cr, uid, move, context=context), context=context)
def _create_procurements(self, cr, uid, moves, context=None):
res = []
for move in moves:
res.append(self._create_procurement(cr, uid, move, context=context))
return res
def write(self, cr, uid, ids, vals, context=None):
if context is None:
context = {}
if isinstance(ids, (int, long)):
ids = [ids]
# Check that we do not modify a stock.move which is done
frozen_fields = set(['product_qty', 'product_uom', 'product_uos_qty', 'product_uos', 'location_id', 'location_dest_id', 'product_id'])
for move in self.browse(cr, uid, ids, context=context):
if move.state == 'done':
if frozen_fields.intersection(vals):
raise osv.except_osv(_('Operation Forbidden!'),
_('Quantities, Units of Measure, Products and Locations cannot be modified on stock moves that have already been processed (except by the Administrator).'))
propagated_changes_dict = {}
#propagation of quantity change
if vals.get('product_uom_qty'):
propagated_changes_dict['product_uom_qty'] = vals['product_uom_qty']
if vals.get('product_uom_id'):
propagated_changes_dict['product_uom_id'] = vals['product_uom_id']
#propagation of expected date:
propagated_date_field = False
if vals.get('date_expected'):
#propagate any manual change of the expected date
propagated_date_field = 'date_expected'
elif (vals.get('state', '') == 'done' and vals.get('date')):
#propagate also any delta observed when setting the move as done
propagated_date_field = 'date'
if not context.get('do_not_propagate', False) and (propagated_date_field or propagated_changes_dict):
#any propagation is (maybe) needed
for move in self.browse(cr, uid, ids, context=context):
if move.move_dest_id and move.propagate:
if 'date_expected' in propagated_changes_dict:
propagated_changes_dict.pop('date_expected')
if propagated_date_field:
current_date = datetime.strptime(move.date_expected, DEFAULT_SERVER_DATETIME_FORMAT)
new_date = datetime.strptime(vals.get(propagated_date_field), DEFAULT_SERVER_DATETIME_FORMAT)
delta = new_date - current_date
if abs(delta.days) >= move.company_id.propagation_minimum_delta:
old_move_date = datetime.strptime(move.move_dest_id.date_expected, DEFAULT_SERVER_DATETIME_FORMAT)
new_move_date = (old_move_date + relativedelta.relativedelta(days=delta.days or 0)).strftime(DEFAULT_SERVER_DATETIME_FORMAT)
propagated_changes_dict['date_expected'] = new_move_date
#For pushed moves as well as for pulled moves, propagate by recursive call of write().
#Note that, for pulled moves we intentionally don't propagate on the procurement.
if propagated_changes_dict:
self.write(cr, uid, [move.move_dest_id.id], propagated_changes_dict, context=context)
return super(stock_move, self).write(cr, uid, ids, vals, context=context)
def onchange_quantity(self, cr, uid, ids, product_id, product_qty, product_uom, product_uos):
""" On change of product quantity finds UoM and UoS quantities
@param product_id: Product id
@param product_qty: Changed Quantity of product
@param product_uom: Unit of measure of product
@param product_uos: Unit of sale of product
@return: Dictionary of values
"""
result = {
'product_uos_qty': 0.00
}
warning = {}
if (not product_id) or (product_qty <= 0.0):
result['product_qty'] = 0.0
return {'value': result}
product_obj = self.pool.get('product.product')
uos_coeff = product_obj.read(cr, uid, product_id, ['uos_coeff'])
# Warn if the quantity was decreased
if ids:
for move in self.read(cr, uid, ids, ['product_qty']):
if product_qty < move['product_qty']:
warning.update({
'title': _('Information'),
'message': _("By changing this quantity here, you accept the "
"new quantity as complete: Odoo will not "
"automatically generate a back order.")})
break
if product_uos and product_uom and (product_uom != product_uos):
result['product_uos_qty'] = product_qty * uos_coeff['uos_coeff']
else:
result['product_uos_qty'] = product_qty
return {'value': result, 'warning': warning}
def onchange_uos_quantity(self, cr, uid, ids, product_id, product_uos_qty,
product_uos, product_uom):
""" On change of product quantity finds UoM and UoS quantities
@param product_id: Product id
@param product_uos_qty: Changed UoS Quantity of product
@param product_uom: Unit of measure of product
@param product_uos: Unit of sale of product
@return: Dictionary of values
"""
result = {
'product_uom_qty': 0.00
}
if (not product_id) or (product_uos_qty <= 0.0):
result['product_uos_qty'] = 0.0
return {'value': result}
product_obj = self.pool.get('product.product')
uos_coeff = product_obj.read(cr, uid, product_id, ['uos_coeff'])
# No warning if the quantity was decreased to avoid double warnings:
# The clients should call onchange_quantity too anyway
if product_uos and product_uom and (product_uom != product_uos):
result['product_uom_qty'] = product_uos_qty / uos_coeff['uos_coeff']
else:
result['product_uom_qty'] = product_uos_qty
return {'value': result}
def onchange_product_id(self, cr, uid, ids, prod_id=False, loc_id=False, loc_dest_id=False, partner_id=False):
""" On change of product id, if finds UoM, UoS, quantity and UoS quantity.
@param prod_id: Changed Product id
@param loc_id: Source location id
@param loc_dest_id: Destination location id
@param partner_id: Address id of partner
@return: Dictionary of values
"""
if not prod_id:
return {}
user = self.pool.get('res.users').browse(cr, uid, uid)
lang = user and user.lang or False
if partner_id:
addr_rec = self.pool.get('res.partner').browse(cr, uid, partner_id)
if addr_rec:
lang = addr_rec and addr_rec.lang or False
ctx = {'lang': lang}
product = self.pool.get('product.product').browse(cr, uid, [prod_id], context=ctx)[0]
uos_id = product.uos_id and product.uos_id.id or False
result = {
'name': product.partner_ref,
'product_uom': product.uom_id.id,
'product_uos': uos_id,
'product_uom_qty': 1.00,
'product_uos_qty': self.pool.get('stock.move').onchange_quantity(cr, uid, ids, prod_id, 1.00, product.uom_id.id, uos_id)['value']['product_uos_qty'],
}
if loc_id:
result['location_id'] = loc_id
if loc_dest_id:
result['location_dest_id'] = loc_dest_id
return {'value': result}
def _prepare_picking_assign(self, cr, uid, move, context=None):
""" Prepares a new picking for this move as it could not be assigned to
another picking. This method is designed to be inherited.
"""
values = {
'origin': move.origin,
'company_id': move.company_id and move.company_id.id or False,
'move_type': move.group_id and move.group_id.move_type or 'direct',
'partner_id': move.partner_id.id or False,
'picking_type_id': move.picking_type_id and move.picking_type_id.id or False,
}
return values
@api.cr_uid_ids_context
def _picking_assign(self, cr, uid, move_ids, procurement_group, location_from, location_to, context=None):
"""Assign a picking on the given move_ids, which is a list of move supposed to share the same procurement_group, location_from and location_to
(and company). Those attributes are also given as parameters.
"""
pick_obj = self.pool.get("stock.picking")
# Use a SQL query as doing with the ORM will split it in different queries with id IN (,,)
# In the next version, the locations on the picking should be stored again.
query = """
SELECT stock_picking.id FROM stock_picking, stock_move
WHERE
stock_picking.state in ('draft', 'confirmed', 'waiting') AND
stock_move.picking_id = stock_picking.id AND
stock_move.location_id = %s AND
stock_move.location_dest_id = %s AND
"""
params = (location_from, location_to)
if not procurement_group:
query += "stock_picking.group_id IS NULL LIMIT 1"
else:
query += "stock_picking.group_id = %s LIMIT 1"
params += (procurement_group,)
cr.execute(query, params)
[pick] = cr.fetchone() or [None]
if not pick:
move = self.browse(cr, uid, move_ids, context=context)[0]
values = self._prepare_picking_assign(cr, uid, move, context=context)
pick = pick_obj.create(cr, uid, values, context=context)
return self.write(cr, uid, move_ids, {'picking_id': pick}, context=context)
def onchange_date(self, cr, uid, ids, date, date_expected, context=None):
""" On change of Scheduled Date gives a Move date.
@param date_expected: Scheduled Date
@param date: Move Date
@return: Move Date
"""
if not date_expected:
date_expected = time.strftime(DEFAULT_SERVER_DATETIME_FORMAT)
return {'value': {'date': date_expected}}
def attribute_price(self, cr, uid, move, context=None):
"""
Attribute price to move, important in inter-company moves or receipts with only one partner
"""
if not move.price_unit:
price = move.product_id.standard_price
self.write(cr, uid, [move.id], {'price_unit': price})
def action_confirm(self, cr, uid, ids, context=None):
""" Confirms stock move or put it in waiting if it's linked to another move.
@return: List of ids.
"""
if not context:
context = {}
if isinstance(ids, (int, long)):
ids = [ids]
states = {
'confirmed': [],
'waiting': []
}
to_assign = {}
for move in self.browse(cr, uid, ids, context=context):
self.attribute_price(cr, uid, move, context=context)
state = 'confirmed'
#if the move is preceeded, then it's waiting (if preceeding move is done, then action_assign has been called already and its state is already available)
if move.move_orig_ids:
state = 'waiting'
#if the move is split and some of the ancestor was preceeded, then it's waiting as well
elif move.split_from:
move2 = move.split_from
while move2 and state != 'waiting':
if move2.move_orig_ids:
state = 'waiting'
move2 = move2.split_from
states[state].append(move.id)
if not move.picking_id and move.picking_type_id:
key = (move.group_id.id, move.location_id.id, move.location_dest_id.id)
if key not in to_assign:
to_assign[key] = []
to_assign[key].append(move.id)
moves = [move for move in self.browse(cr, uid, states['confirmed'], context=context) if move.procure_method == 'make_to_order']
self._create_procurements(cr, uid, moves, context=context)
for move in moves:
states['waiting'].append(move.id)
states['confirmed'].remove(move.id)
for state, write_ids in states.items():
if len(write_ids):
self.write(cr, uid, write_ids, {'state': state})
#assign picking in batch for all confirmed move that share the same details
for key, move_ids in to_assign.items():
procurement_group, location_from, location_to = key
self._picking_assign(cr, uid, move_ids, procurement_group, location_from, location_to, context=context)
moves = self.browse(cr, uid, ids, context=context)
self._push_apply(cr, uid, moves, context=context)
return ids
def force_assign(self, cr, uid, ids, context=None):
""" Changes the state to assigned.
@return: True
"""
return self.write(cr, uid, ids, {'state': 'assigned'}, context=context)
def check_tracking_product(self, cr, uid, product, lot_id, location, location_dest, context=None):
check = False
if product.track_all and not location_dest.usage == 'inventory':
check = True
elif product.track_incoming and location.usage in ('supplier', 'transit', 'inventory') and location_dest.usage == 'internal':
check = True
elif product.track_outgoing and location_dest.usage in ('customer', 'transit') and location.usage == 'internal':
check = True
if check and not lot_id:
raise osv.except_osv(_('Warning!'), _('You must assign a serial number for the product %s') % (product.name))
def check_tracking(self, cr, uid, move, lot_id, context=None):
""" Checks if serial number is assigned to stock move or not and raise an error if it had to.
"""
self.check_tracking_product(cr, uid, move.product_id, lot_id, move.location_id, move.location_dest_id, context=context)
def action_assign(self, cr, uid, ids, context=None):
""" Checks the product type and accordingly writes the state.
"""
context = context or {}
quant_obj = self.pool.get("stock.quant")
to_assign_moves = []
main_domain = {}
todo_moves = []
operations = set()
for move in self.browse(cr, uid, ids, context=context):
if move.state not in ('confirmed', 'waiting', 'assigned'):
continue
if move.location_id.usage in ('supplier', 'inventory', 'production'):
to_assign_moves.append(move.id)
#in case the move is returned, we want to try to find quants before forcing the assignment
if not move.origin_returned_move_id:
continue
if move.product_id.type == 'consu':
to_assign_moves.append(move.id)
continue
else:
todo_moves.append(move)
#we always keep the quants already assigned and try to find the remaining quantity on quants not assigned only
main_domain[move.id] = [('reservation_id', '=', False), ('qty', '>', 0)]
#if the move is preceeded, restrict the choice of quants in the ones moved previously in original move
ancestors = self.find_move_ancestors(cr, uid, move, context=context)
if move.state == 'waiting' and not ancestors:
#if the waiting move hasn't yet any ancestor (PO/MO not confirmed yet), don't find any quant available in stock
main_domain[move.id] += [('id', '=', False)]
elif ancestors:
main_domain[move.id] += [('history_ids', 'in', ancestors)]
#if the move is returned from another, restrict the choice of quants to the ones that follow the returned move
if move.origin_returned_move_id:
main_domain[move.id] += [('history_ids', 'in', move.origin_returned_move_id.id)]
for link in move.linked_move_operation_ids:
operations.add(link.operation_id)
# Check all ops and sort them: we want to process first the packages, then operations with lot then the rest
operations = list(operations)
operations.sort(key=lambda x: ((x.package_id and not x.product_id) and -4 or 0) + (x.package_id and -2 or 0) + (x.lot_id and -1 or 0))
for ops in operations:
#first try to find quants based on specific domains given by linked operations
for record in ops.linked_move_operation_ids:
move = record.move_id
if move.id in main_domain:
domain = main_domain[move.id] + self.pool.get('stock.move.operation.link').get_specific_domain(cr, uid, record, context=context)
qty = record.qty
if qty:
quants = quant_obj.quants_get_prefered_domain(cr, uid, ops.location_id, move.product_id, qty, domain=domain, prefered_domain_list=[], restrict_lot_id=move.restrict_lot_id.id, restrict_partner_id=move.restrict_partner_id.id, context=context)
quant_obj.quants_reserve(cr, uid, quants, move, record, context=context)
for move in todo_moves:
if move.linked_move_operation_ids:
continue
#then if the move isn't totally assigned, try to find quants without any specific domain
if move.state != 'assigned':
qty_already_assigned = move.reserved_availability
qty = move.product_qty - qty_already_assigned
quants = quant_obj.quants_get_prefered_domain(cr, uid, move.location_id, move.product_id, qty, domain=main_domain[move.id], prefered_domain_list=[], restrict_lot_id=move.restrict_lot_id.id, restrict_partner_id=move.restrict_partner_id.id, context=context)
quant_obj.quants_reserve(cr, uid, quants, move, context=context)
#force assignation of consumable products and incoming from supplier/inventory/production
if to_assign_moves:
self.force_assign(cr, uid, to_assign_moves, context=context)
def action_cancel(self, cr, uid, ids, context=None):
""" Cancels the moves and if all moves are cancelled it cancels the picking.
@return: True
"""
procurement_obj = self.pool.get('procurement.order')
context = context or {}
procs_to_check = []
for move in self.browse(cr, uid, ids, context=context):
if move.state == 'done':
raise osv.except_osv(_('Operation Forbidden!'),
_('You cannot cancel a stock move that has been set to \'Done\'.'))
if move.reserved_quant_ids:
self.pool.get("stock.quant").quants_unreserve(cr, uid, move, context=context)
if context.get('cancel_procurement'):
if move.propagate:
procurement_ids = procurement_obj.search(cr, uid, [('move_dest_id', '=', move.id)], context=context)
procurement_obj.cancel(cr, uid, procurement_ids, context=context)
else:
if move.move_dest_id:
if move.propagate:
self.action_cancel(cr, uid, [move.move_dest_id.id], context=context)
elif move.move_dest_id.state == 'waiting':
#If waiting, the chain will be broken and we are not sure if we can still wait for it (=> could take from stock instead)
self.write(cr, uid, [move.move_dest_id.id], {'state': 'confirmed'}, context=context)
if move.procurement_id:
# Does the same as procurement check, only eliminating a refresh
procs_to_check.append(move.procurement_id.id)
res = self.write(cr, uid, ids, {'state': 'cancel', 'move_dest_id': False}, context=context)
if procs_to_check:
procurement_obj.check(cr, uid, procs_to_check, context=context)
return res
def _check_package_from_moves(self, cr, uid, ids, context=None):
pack_obj = self.pool.get("stock.quant.package")
packs = set()
for move in self.browse(cr, uid, ids, context=context):
packs |= set([q.package_id for q in move.quant_ids if q.package_id and q.qty > 0])
return pack_obj._check_location_constraint(cr, uid, list(packs), context=context)
def find_move_ancestors(self, cr, uid, move, context=None):
'''Find the first level ancestors of given move '''
ancestors = []
move2 = move
while move2:
ancestors += [x.id for x in move2.move_orig_ids]
#loop on the split_from to find the ancestor of split moves only if the move has not direct ancestor (priority goes to them)
move2 = not move2.move_orig_ids and move2.split_from or False
return ancestors
@api.cr_uid_ids_context
def recalculate_move_state(self, cr, uid, move_ids, context=None):
'''Recompute the state of moves given because their reserved quants were used to fulfill another operation'''
for move in self.browse(cr, uid, move_ids, context=context):
vals = {}
reserved_quant_ids = move.reserved_quant_ids
if len(reserved_quant_ids) > 0 and not move.partially_available:
vals['partially_available'] = True
if len(reserved_quant_ids) == 0 and move.partially_available:
vals['partially_available'] = False
if move.state == 'assigned':
if self.find_move_ancestors(cr, uid, move, context=context):
vals['state'] = 'waiting'
else:
vals['state'] = 'confirmed'
if vals:
self.write(cr, uid, [move.id], vals, context=context)
def action_done(self, cr, uid, ids, context=None):
""" Process completely the moves given as ids and if all moves are done, it will finish the picking.
"""
context = context or {}
picking_obj = self.pool.get("stock.picking")
quant_obj = self.pool.get("stock.quant")
todo = [move.id for move in self.browse(cr, uid, ids, context=context) if move.state == "draft"]
if todo:
ids = self.action_confirm(cr, uid, todo, context=context)
pickings = set()
procurement_ids = set()
#Search operations that are linked to the moves
operations = set()
move_qty = {}
for move in self.browse(cr, uid, ids, context=context):
move_qty[move.id] = move.product_qty
for link in move.linked_move_operation_ids:
operations.add(link.operation_id)
#Sort operations according to entire packages first, then package + lot, package only, lot only
operations = list(operations)
operations.sort(key=lambda x: ((x.package_id and not x.product_id) and -4 or 0) + (x.package_id and -2 or 0) + (x.lot_id and -1 or 0))
for ops in operations:
if ops.picking_id:
pickings.add(ops.picking_id.id)
main_domain = [('qty', '>', 0)]
for record in ops.linked_move_operation_ids:
move = record.move_id
self.check_tracking(cr, uid, move, not ops.product_id and ops.package_id.id or ops.lot_id.id, context=context)
prefered_domain = [('reservation_id', '=', move.id)]
fallback_domain = [('reservation_id', '=', False)]
fallback_domain2 = ['&', ('reservation_id', '!=', move.id), ('reservation_id', '!=', False)]
prefered_domain_list = [prefered_domain] + [fallback_domain] + [fallback_domain2]
dom = main_domain + self.pool.get('stock.move.operation.link').get_specific_domain(cr, uid, record, context=context)
quants = quant_obj.quants_get_prefered_domain(cr, uid, ops.location_id, move.product_id, record.qty, domain=dom, prefered_domain_list=prefered_domain_list,
restrict_lot_id=move.restrict_lot_id.id, restrict_partner_id=move.restrict_partner_id.id, context=context)
if ops.product_id:
#If a product is given, the result is always put immediately in the result package (if it is False, they are without package)
quant_dest_package_id = ops.result_package_id.id
ctx = context
else:
# When a pack is moved entirely, the quants should not be written anything for the destination package
quant_dest_package_id = False
ctx = context.copy()
ctx['entire_pack'] = True
quant_obj.quants_move(cr, uid, quants, move, ops.location_dest_id, location_from=ops.location_id, lot_id=ops.lot_id.id, owner_id=ops.owner_id.id, src_package_id=ops.package_id.id, dest_package_id=quant_dest_package_id, context=ctx)
# Handle pack in pack
if not ops.product_id and ops.package_id and ops.result_package_id.id != ops.package_id.parent_id.id:
self.pool.get('stock.quant.package').write(cr, SUPERUSER_ID, [ops.package_id.id], {'parent_id': ops.result_package_id.id}, context=context)
if not move_qty.get(move.id):
raise osv.except_osv(_("Error"), _("The roundings of your Unit of Measures %s on the move vs. %s on the product don't allow to do these operations or you are not transferring the picking at once. ") % (move.product_uom.name, move.product_id.uom_id.name))
move_qty[move.id] -= record.qty
#Check for remaining qtys and unreserve/check move_dest_id in
move_dest_ids = set()
for move in self.browse(cr, uid, ids, context=context):
move_qty_cmp = float_compare(move_qty[move.id], 0, precision_rounding=move.product_id.uom_id.rounding)
if move_qty_cmp > 0: # (=In case no pack operations in picking)
main_domain = [('qty', '>', 0)]
prefered_domain = [('reservation_id', '=', move.id)]
fallback_domain = [('reservation_id', '=', False)]
fallback_domain2 = ['&', ('reservation_id', '!=', move.id), ('reservation_id', '!=', False)]
prefered_domain_list = [prefered_domain] + [fallback_domain] + [fallback_domain2]
self.check_tracking(cr, uid, move, move.restrict_lot_id.id, context=context)
qty = move_qty[move.id]
quants = quant_obj.quants_get_prefered_domain(cr, uid, move.location_id, move.product_id, qty, domain=main_domain, prefered_domain_list=prefered_domain_list, restrict_lot_id=move.restrict_lot_id.id, restrict_partner_id=move.restrict_partner_id.id, context=context)
quant_obj.quants_move(cr, uid, quants, move, move.location_dest_id, lot_id=move.restrict_lot_id.id, owner_id=move.restrict_partner_id.id, context=context)
# If the move has a destination, add it to the list to reserve
if move.move_dest_id and move.move_dest_id.state in ('waiting', 'confirmed'):
move_dest_ids.add(move.move_dest_id.id)
if move.procurement_id:
procurement_ids.add(move.procurement_id.id)
#unreserve the quants and make them available for other operations/moves
quant_obj.quants_unreserve(cr, uid, move, context=context)
# Check the packages have been placed in the correct locations
self._check_package_from_moves(cr, uid, ids, context=context)
#set the move as done
self.write(cr, uid, ids, {'state': 'done', 'date': time.strftime(DEFAULT_SERVER_DATETIME_FORMAT)}, context=context)
self.pool.get('procurement.order').check(cr, uid, list(procurement_ids), context=context)
#assign destination moves
if move_dest_ids:
self.action_assign(cr, uid, list(move_dest_ids), context=context)
#check picking state to set the date_done is needed
done_picking = []
for picking in picking_obj.browse(cr, uid, list(pickings), context=context):
if picking.state == 'done' and not picking.date_done:
done_picking.append(picking.id)
if done_picking:
picking_obj.write(cr, uid, done_picking, {'date_done': time.strftime(DEFAULT_SERVER_DATETIME_FORMAT)}, context=context)
return True
def unlink(self, cr, uid, ids, context=None):
context = context or {}
for move in self.browse(cr, uid, ids, context=context):
if move.state not in ('draft', 'cancel'):
raise osv.except_osv(_('User Error!'), _('You can only delete draft moves.'))
return super(stock_move, self).unlink(cr, uid, ids, context=context)
def action_scrap(self, cr, uid, ids, quantity, location_id, restrict_lot_id=False, restrict_partner_id=False, context=None):
""" Move the scrap/damaged product into scrap location
@param cr: the database cursor
@param uid: the user id
@param ids: ids of stock move object to be scrapped
@param quantity : specify scrap qty
@param location_id : specify scrap location
@param context: context arguments
@return: Scraped lines
"""
quant_obj = self.pool.get("stock.quant")
#quantity should be given in MOVE UOM
if quantity <= 0:
raise osv.except_osv(_('Warning!'), _('Please provide a positive quantity to scrap.'))
res = []
for move in self.browse(cr, uid, ids, context=context):
source_location = move.location_id
if move.state == 'done':
source_location = move.location_dest_id
#Previously used to prevent scraping from virtual location but not necessary anymore
#if source_location.usage != 'internal':
#restrict to scrap from a virtual location because it's meaningless and it may introduce errors in stock ('creating' new products from nowhere)
#raise osv.except_osv(_('Error!'), _('Forbidden operation: it is not allowed to scrap products from a virtual location.'))
move_qty = move.product_qty
uos_qty = quantity / move_qty * move.product_uos_qty
default_val = {
'location_id': source_location.id,
'product_uom_qty': quantity,
'product_uos_qty': uos_qty,
'state': move.state,
'scrapped': True,
'location_dest_id': location_id,
'restrict_lot_id': restrict_lot_id,
'restrict_partner_id': restrict_partner_id,
}
new_move = self.copy(cr, uid, move.id, default_val)
res += [new_move]
product_obj = self.pool.get('product.product')
for product in product_obj.browse(cr, uid, [move.product_id.id], context=context):
if move.picking_id:
uom = product.uom_id.name if product.uom_id else ''
message = _("%s %s %s has been <b>moved to</b> scrap.") % (quantity, uom, product.name)
move.picking_id.message_post(body=message)
# We "flag" the quant from which we want to scrap the products. To do so:
# - we select the quants related to the move we scrap from
# - we reserve the quants with the scrapped move
# See self.action_done, et particularly how is defined the "prefered_domain" for clarification
scrap_move = self.browse(cr, uid, new_move, context=context)
if move.state == 'done' and scrap_move.location_id.usage not in ('supplier', 'inventory', 'production'):
domain = [('qty', '>', 0), ('history_ids', 'in', [move.id])]
# We use scrap_move data since a reservation makes sense for a move not already done
quants = quant_obj.quants_get_prefered_domain(cr, uid, scrap_move.location_id,
scrap_move.product_id, quantity, domain=domain, prefered_domain_list=[],
restrict_lot_id=scrap_move.restrict_lot_id.id, restrict_partner_id=scrap_move.restrict_partner_id.id, context=context)
quant_obj.quants_reserve(cr, uid, quants, scrap_move, context=context)
self.action_done(cr, uid, res, context=context)
return res
def split(self, cr, uid, move, qty, restrict_lot_id=False, restrict_partner_id=False, context=None):
""" Splits qty from move move into a new move
:param move: browse record
:param qty: float. quantity to split (given in product UoM)
:param restrict_lot_id: optional production lot that can be given in order to force the new move to restrict its choice of quants to this lot.
:param restrict_partner_id: optional partner that can be given in order to force the new move to restrict its choice of quants to the ones belonging to this partner.
:param context: dictionay. can contains the special key 'source_location_id' in order to force the source location when copying the move
returns the ID of the backorder move created
"""
if move.state in ('done', 'cancel'):
raise osv.except_osv(_('Error'), _('You cannot split a move done'))
if move.state == 'draft':
#we restrict the split of a draft move because if not confirmed yet, it may be replaced by several other moves in
#case of phantom bom (with mrp module). And we don't want to deal with this complexity by copying the product that will explode.
raise osv.except_osv(_('Error'), _('You cannot split a draft move. It needs to be confirmed first.'))
if move.product_qty <= qty or qty == 0:
return move.id
uom_obj = self.pool.get('product.uom')
context = context or {}
#HALF-UP rounding as only rounding errors will be because of propagation of error from default UoM
uom_qty = uom_obj._compute_qty_obj(cr, uid, move.product_id.uom_id, qty, move.product_uom, rounding_method='HALF-UP', context=context)
uos_qty = uom_qty * move.product_uos_qty / move.product_uom_qty
defaults = {
'product_uom_qty': uom_qty,
'product_uos_qty': uos_qty,
'procure_method': 'make_to_stock',
'restrict_lot_id': restrict_lot_id,
'restrict_partner_id': restrict_partner_id,
'split_from': move.id,
'procurement_id': move.procurement_id.id,
'move_dest_id': move.move_dest_id.id,
'origin_returned_move_id': move.origin_returned_move_id.id,
}
if context.get('source_location_id'):
defaults['location_id'] = context['source_location_id']
new_move = self.copy(cr, uid, move.id, defaults, context=context)
ctx = context.copy()
ctx['do_not_propagate'] = True
self.write(cr, uid, [move.id], {
'product_uom_qty': move.product_uom_qty - uom_qty,
'product_uos_qty': move.product_uos_qty - uos_qty,
}, context=ctx)
if move.move_dest_id and move.propagate and move.move_dest_id.state not in ('done', 'cancel'):
new_move_prop = self.split(cr, uid, move.move_dest_id, qty, context=context)
self.write(cr, uid, [new_move], {'move_dest_id': new_move_prop}, context=context)
#returning the first element of list returned by action_confirm is ok because we checked it wouldn't be exploded (and
#thus the result of action_confirm should always be a list of 1 element length)
return self.action_confirm(cr, uid, [new_move], context=context)[0]
def get_code_from_locs(self, cr, uid, move, location_id=False, location_dest_id=False, context=None):
"""
Returns the code the picking type should have. This can easily be used
to check if a move is internal or not
move, location_id and location_dest_id are browse records
"""
code = 'internal'
src_loc = location_id or move.location_id
dest_loc = location_dest_id or move.location_dest_id
if src_loc.usage == 'internal' and dest_loc.usage != 'internal':
code = 'outgoing'
if src_loc.usage != 'internal' and dest_loc.usage == 'internal':
code = 'incoming'
return code
def _get_taxes(self, cr, uid, move, context=None):
return []
class stock_inventory(osv.osv):
_name = "stock.inventory"
_description = "Inventory"
def _get_move_ids_exist(self, cr, uid, ids, field_name, arg, context=None):
res = {}
for inv in self.browse(cr, uid, ids, context=context):
res[inv.id] = False
if inv.move_ids:
res[inv.id] = True
return res
def _get_available_filters(self, cr, uid, context=None):
"""
This function will return the list of filter allowed according to the options checked
in 'Settings\Warehouse'.
:rtype: list of tuple
"""
#default available choices
res_filter = [('none', _('All products')), ('partial', _('Manual Selection of Products')), ('product', _('One product only'))]
settings_obj = self.pool.get('stock.config.settings')
config_ids = settings_obj.search(cr, uid, [], limit=1, order='id DESC', context=context)
#If we don't have updated config until now, all fields are by default false and so should be not dipslayed
if not config_ids:
return res_filter
stock_settings = settings_obj.browse(cr, uid, config_ids[0], context=context)
if stock_settings.group_stock_tracking_owner:
res_filter.append(('owner', _('One owner only')))
res_filter.append(('product_owner', _('One product for a specific owner')))
if stock_settings.group_stock_tracking_lot:
res_filter.append(('lot', _('One Lot/Serial Number')))
if stock_settings.group_stock_packaging:
res_filter.append(('pack', _('A Pack')))
return res_filter
def _get_total_qty(self, cr, uid, ids, field_name, args, context=None):
res = {}
for inv in self.browse(cr, uid, ids, context=context):
res[inv.id] = sum([x.product_qty for x in inv.line_ids])
return res
INVENTORY_STATE_SELECTION = [
('draft', 'Draft'),
('cancel', 'Cancelled'),
('confirm', 'In Progress'),
('done', 'Validated'),
]
_columns = {
'name': fields.char('Inventory Reference', required=True, readonly=True, states={'draft': [('readonly', False)]}, help="Inventory Name."),
'date': fields.datetime('Inventory Date', required=True, readonly=True, help="The date that will be used for the stock level check of the products and the validation of the stock move related to this inventory."),
'line_ids': fields.one2many('stock.inventory.line', 'inventory_id', 'Inventories', readonly=False, states={'done': [('readonly', True)]}, help="Inventory Lines.", copy=True),
'move_ids': fields.one2many('stock.move', 'inventory_id', 'Created Moves', help="Inventory Moves.", states={'done': [('readonly', True)]}),
'state': fields.selection(INVENTORY_STATE_SELECTION, 'Status', readonly=True, select=True, copy=False),
'company_id': fields.many2one('res.company', 'Company', required=True, select=True, readonly=True, states={'draft': [('readonly', False)]}),
'location_id': fields.many2one('stock.location', 'Inventoried Location', required=True, readonly=True, states={'draft': [('readonly', False)]}),
'product_id': fields.many2one('product.product', 'Inventoried Product', readonly=True, states={'draft': [('readonly', False)]}, help="Specify Product to focus your inventory on a particular Product."),
'package_id': fields.many2one('stock.quant.package', 'Inventoried Pack', readonly=True, states={'draft': [('readonly', False)]}, help="Specify Pack to focus your inventory on a particular Pack."),
'partner_id': fields.many2one('res.partner', 'Inventoried Owner', readonly=True, states={'draft': [('readonly', False)]}, help="Specify Owner to focus your inventory on a particular Owner."),
'lot_id': fields.many2one('stock.production.lot', 'Inventoried Lot/Serial Number', readonly=True, states={'draft': [('readonly', False)]}, help="Specify Lot/Serial Number to focus your inventory on a particular Lot/Serial Number.", copy=False),
'move_ids_exist': fields.function(_get_move_ids_exist, type='boolean', string=' Stock Move Exists?', help='technical field for attrs in view'),
'filter': fields.selection(_get_available_filters, 'Inventory of', required=True,
help="If you do an entire inventory, you can choose 'All Products' and it will prefill the inventory with the current stock. If you only do some products "\
"(e.g. Cycle Counting) you can choose 'Manual Selection of Products' and the system won't propose anything. You can also let the "\
"system propose for a single product / lot /... "),
'total_qty': fields.function(_get_total_qty, type="float"),
}
def _default_stock_location(self, cr, uid, context=None):
try:
warehouse = self.pool.get('ir.model.data').get_object(cr, uid, 'stock', 'warehouse0')
return warehouse.lot_stock_id.id
except:
return False
_defaults = {
'date': fields.datetime.now,
'state': 'draft',
'company_id': lambda self, cr, uid, c: self.pool.get('res.company')._company_default_get(cr, uid, 'stock.inventory', context=c),
'location_id': _default_stock_location,
'filter': 'none',
}
def reset_real_qty(self, cr, uid, ids, context=None):
inventory = self.browse(cr, uid, ids[0], context=context)
line_ids = [line.id for line in inventory.line_ids]
self.pool.get('stock.inventory.line').write(cr, uid, line_ids, {'product_qty': 0})
return True
def action_done(self, cr, uid, ids, context=None):
""" Finish the inventory
@return: True
"""
for inv in self.browse(cr, uid, ids, context=context):
for inventory_line in inv.line_ids:
if inventory_line.product_qty < 0 and inventory_line.product_qty != inventory_line.theoretical_qty:
raise osv.except_osv(_('Warning'), _('You cannot set a negative product quantity in an inventory line:\n\t%s - qty: %s' % (inventory_line.product_id.name, inventory_line.product_qty)))
self.action_check(cr, uid, [inv.id], context=context)
self.write(cr, uid, [inv.id], {'state': 'done'}, context=context)
self.post_inventory(cr, uid, inv, context=context)
return True
def post_inventory(self, cr, uid, inv, context=None):
#The inventory is posted as a single step which means quants cannot be moved from an internal location to another using an inventory
#as they will be moved to inventory loss, and other quants will be created to the encoded quant location. This is a normal behavior
#as quants cannot be reuse from inventory location (users can still manually move the products before/after the inventory if they want).
move_obj = self.pool.get('stock.move')
move_obj.action_done(cr, uid, [x.id for x in inv.move_ids if x.state != 'done'], context=context)
def action_check(self, cr, uid, ids, context=None):
""" Checks the inventory and computes the stock move to do
@return: True
"""
inventory_line_obj = self.pool.get('stock.inventory.line')
stock_move_obj = self.pool.get('stock.move')
for inventory in self.browse(cr, uid, ids, context=context):
#first remove the existing stock moves linked to this inventory
move_ids = [move.id for move in inventory.move_ids]
stock_move_obj.unlink(cr, uid, move_ids, context=context)
for line in inventory.line_ids:
#compare the checked quantities on inventory lines to the theorical one
stock_move = inventory_line_obj._resolve_inventory_line(cr, uid, line, context=context)
def action_cancel_draft(self, cr, uid, ids, context=None):
""" Cancels the stock move and change inventory state to draft.
@return: True
"""
for inv in self.browse(cr, uid, ids, context=context):
self.write(cr, uid, [inv.id], {'line_ids': [(5,)]}, context=context)
self.pool.get('stock.move').action_cancel(cr, uid, [x.id for x in inv.move_ids], context=context)
self.write(cr, uid, [inv.id], {'state': 'draft'}, context=context)
return True
def action_cancel_inventory(self, cr, uid, ids, context=None):
self.action_cancel_draft(cr, uid, ids, context=context)
def prepare_inventory(self, cr, uid, ids, context=None):
inventory_line_obj = self.pool.get('stock.inventory.line')
for inventory in self.browse(cr, uid, ids, context=context):
# If there are inventory lines already (e.g. from import), respect those and set their theoretical qty
line_ids = [line.id for line in inventory.line_ids]
if not line_ids and inventory.filter != 'partial':
#compute the inventory lines and create them
vals = self._get_inventory_lines(cr, uid, inventory, context=context)
for product_line in vals:
inventory_line_obj.create(cr, uid, product_line, context=context)
return self.write(cr, uid, ids, {'state': 'confirm', 'date': time.strftime(DEFAULT_SERVER_DATETIME_FORMAT)})
def _get_inventory_lines(self, cr, uid, inventory, context=None):
location_obj = self.pool.get('stock.location')
product_obj = self.pool.get('product.product')
location_ids = location_obj.search(cr, uid, [('id', 'child_of', [inventory.location_id.id])], context=context)
domain = ' location_id in %s'
args = (tuple(location_ids),)
if inventory.partner_id:
domain += ' and owner_id = %s'
args += (inventory.partner_id.id,)
if inventory.lot_id:
domain += ' and lot_id = %s'
args += (inventory.lot_id.id,)
if inventory.product_id:
domain += ' and product_id = %s'
args += (inventory.product_id.id,)
if inventory.package_id:
domain += ' and package_id = %s'
args += (inventory.package_id.id,)
cr.execute('''
SELECT product_id, sum(qty) as product_qty, location_id, lot_id as prod_lot_id, package_id, owner_id as partner_id
FROM stock_quant WHERE''' + domain + '''
GROUP BY product_id, location_id, lot_id, package_id, partner_id
''', args)
vals = []
for product_line in cr.dictfetchall():
#replace the None the dictionary by False, because falsy values are tested later on
for key, value in product_line.items():
if not value:
product_line[key] = False
product_line['inventory_id'] = inventory.id
product_line['theoretical_qty'] = product_line['product_qty']
if product_line['product_id']:
product = product_obj.browse(cr, uid, product_line['product_id'], context=context)
product_line['product_uom_id'] = product.uom_id.id
vals.append(product_line)
return vals
def _check_filter_product(self, cr, uid, ids, context=None):
for inventory in self.browse(cr, uid, ids, context=context):
if inventory.filter == 'none' and inventory.product_id and inventory.location_id and inventory.lot_id:
return True
if inventory.filter not in ('product', 'product_owner') and inventory.product_id:
return False
if inventory.filter != 'lot' and inventory.lot_id:
return False
if inventory.filter not in ('owner', 'product_owner') and inventory.partner_id:
return False
if inventory.filter != 'pack' and inventory.package_id:
return False
return True
def onchange_filter(self, cr, uid, ids, filter, context=None):
to_clean = { 'value': {} }
if filter not in ('product', 'product_owner'):
to_clean['value']['product_id'] = False
if filter != 'lot':
to_clean['value']['lot_id'] = False
if filter not in ('owner', 'product_owner'):
to_clean['value']['partner_id'] = False
if filter != 'pack':
to_clean['value']['package_id'] = False
return to_clean
_constraints = [
(_check_filter_product, 'The selected inventory options are not coherent.',
['filter', 'product_id', 'lot_id', 'partner_id', 'package_id']),
]
class stock_inventory_line(osv.osv):
_name = "stock.inventory.line"
_description = "Inventory Line"
_order = "inventory_id, location_name, product_code, product_name, prodlot_name"
def _get_product_name_change(self, cr, uid, ids, context=None):
return self.pool.get('stock.inventory.line').search(cr, uid, [('product_id', 'in', ids)], context=context)
def _get_location_change(self, cr, uid, ids, context=None):
return self.pool.get('stock.inventory.line').search(cr, uid, [('location_id', 'in', ids)], context=context)
def _get_prodlot_change(self, cr, uid, ids, context=None):
return self.pool.get('stock.inventory.line').search(cr, uid, [('prod_lot_id', 'in', ids)], context=context)
def _get_theoretical_qty(self, cr, uid, ids, name, args, context=None):
res = {}
quant_obj = self.pool["stock.quant"]
uom_obj = self.pool["product.uom"]
for line in self.browse(cr, uid, ids, context=context):
quant_ids = self._get_quants(cr, uid, line, context=context)
quants = quant_obj.browse(cr, uid, quant_ids, context=context)
tot_qty = sum([x.qty for x in quants])
if line.product_uom_id and line.product_id.uom_id.id != line.product_uom_id.id:
tot_qty = uom_obj._compute_qty_obj(cr, uid, line.product_id.uom_id, tot_qty, line.product_uom_id, context=context)
res[line.id] = tot_qty
return res
_columns = {
'inventory_id': fields.many2one('stock.inventory', 'Inventory', ondelete='cascade', select=True),
'location_id': fields.many2one('stock.location', 'Location', required=True, select=True),
'product_id': fields.many2one('product.product', 'Product', required=True, select=True),
'package_id': fields.many2one('stock.quant.package', 'Pack', select=True),
'product_uom_id': fields.many2one('product.uom', 'Product Unit of Measure', required=True),
'product_qty': fields.float('Checked Quantity', digits_compute=dp.get_precision('Product Unit of Measure')),
'company_id': fields.related('inventory_id', 'company_id', type='many2one', relation='res.company', string='Company', store=True, select=True, readonly=True),
'prod_lot_id': fields.many2one('stock.production.lot', 'Serial Number', domain="[('product_id','=',product_id)]"),
'state': fields.related('inventory_id', 'state', type='char', string='Status', readonly=True),
'theoretical_qty': fields.function(_get_theoretical_qty, type='float', digits_compute=dp.get_precision('Product Unit of Measure'),
store={'stock.inventory.line': (lambda self, cr, uid, ids, c={}: ids, ['location_id', 'product_id', 'package_id', 'product_uom_id', 'company_id', 'prod_lot_id', 'partner_id'], 20),},
readonly=True, string="Theoretical Quantity"),
'partner_id': fields.many2one('res.partner', 'Owner'),
'product_name': fields.related('product_id', 'name', type='char', string='Product Name', store={
'product.product': (_get_product_name_change, ['name', 'default_code'], 20),
'stock.inventory.line': (lambda self, cr, uid, ids, c={}: ids, ['product_id'], 20),}),
'product_code': fields.related('product_id', 'default_code', type='char', string='Product Code', store={
'product.product': (_get_product_name_change, ['name', 'default_code'], 20),
'stock.inventory.line': (lambda self, cr, uid, ids, c={}: ids, ['product_id'], 20),}),
'location_name': fields.related('location_id', 'complete_name', type='char', string='Location Name', store={
'stock.location': (_get_location_change, ['name', 'location_id', 'active'], 20),
'stock.inventory.line': (lambda self, cr, uid, ids, c={}: ids, ['location_id'], 20),}),
'prodlot_name': fields.related('prod_lot_id', 'name', type='char', string='Serial Number Name', store={
'stock.production.lot': (_get_prodlot_change, ['name'], 20),
'stock.inventory.line': (lambda self, cr, uid, ids, c={}: ids, ['prod_lot_id'], 20),}),
}
_defaults = {
'product_qty': 0,
'product_uom_id': lambda self, cr, uid, ctx=None: self.pool['ir.model.data'].get_object_reference(cr, uid, 'product', 'product_uom_unit')[1]
}
def _get_quants(self, cr, uid, line, context=None):
quant_obj = self.pool["stock.quant"]
dom = [('company_id', '=', line.company_id.id), ('location_id', '=', line.location_id.id), ('lot_id', '=', line.prod_lot_id.id),
('product_id','=', line.product_id.id), ('owner_id', '=', line.partner_id.id), ('package_id', '=', line.package_id.id)]
quants = quant_obj.search(cr, uid, dom, context=context)
return quants
def onchange_createline(self, cr, uid, ids, location_id=False, product_id=False, uom_id=False, package_id=False, prod_lot_id=False, partner_id=False, company_id=False, context=None):
quant_obj = self.pool["stock.quant"]
uom_obj = self.pool["product.uom"]
res = {'value': {}}
# If no UoM already put the default UoM of the product
if product_id:
product = self.pool.get('product.product').browse(cr, uid, product_id, context=context)
uom = self.pool['product.uom'].browse(cr, uid, uom_id, context=context)
if product.uom_id.category_id.id != uom.category_id.id:
res['value']['product_uom_id'] = product.uom_id.id
res['domain'] = {'product_uom_id': [('category_id','=',product.uom_id.category_id.id)]}
uom_id = product.uom_id.id
# Calculate theoretical quantity by searching the quants as in quants_get
if product_id and location_id:
product = self.pool.get('product.product').browse(cr, uid, product_id, context=context)
if not company_id:
company_id = self.pool.get('res.users').browse(cr, uid, uid, context=context).company_id.id
dom = [('company_id', '=', company_id), ('location_id', '=', location_id), ('lot_id', '=', prod_lot_id),
('product_id','=', product_id), ('owner_id', '=', partner_id), ('package_id', '=', package_id)]
quants = quant_obj.search(cr, uid, dom, context=context)
th_qty = sum([x.qty for x in quant_obj.browse(cr, uid, quants, context=context)])
if product_id and uom_id and product.uom_id.id != uom_id:
th_qty = uom_obj._compute_qty(cr, uid, product.uom_id.id, th_qty, uom_id)
res['value']['theoretical_qty'] = th_qty
res['value']['product_qty'] = th_qty
return res
def _resolve_inventory_line(self, cr, uid, inventory_line, context=None):
stock_move_obj = self.pool.get('stock.move')
quant_obj = self.pool.get('stock.quant')
diff = inventory_line.theoretical_qty - inventory_line.product_qty
if not diff:
return
#each theorical_lines where difference between theoretical and checked quantities is not 0 is a line for which we need to create a stock move
vals = {
'name': _('INV:') + (inventory_line.inventory_id.name or ''),
'product_id': inventory_line.product_id.id,
'product_uom': inventory_line.product_uom_id.id,
'date': inventory_line.inventory_id.date,
'company_id': inventory_line.inventory_id.company_id.id,
'inventory_id': inventory_line.inventory_id.id,
'state': 'confirmed',
'restrict_lot_id': inventory_line.prod_lot_id.id,
'restrict_partner_id': inventory_line.partner_id.id,
}
inventory_location_id = inventory_line.product_id.property_stock_inventory.id
if diff < 0:
#found more than expected
vals['location_id'] = inventory_location_id
vals['location_dest_id'] = inventory_line.location_id.id
vals['product_uom_qty'] = -diff
else:
#found less than expected
vals['location_id'] = inventory_line.location_id.id
vals['location_dest_id'] = inventory_location_id
vals['product_uom_qty'] = diff
move_id = stock_move_obj.create(cr, uid, vals, context=context)
move = stock_move_obj.browse(cr, uid, move_id, context=context)
if diff > 0:
domain = [('qty', '>', 0.0), ('package_id', '=', inventory_line.package_id.id), ('lot_id', '=', inventory_line.prod_lot_id.id), ('location_id', '=', inventory_line.location_id.id)]
preferred_domain_list = [[('reservation_id', '=', False)], [('reservation_id.inventory_id', '!=', inventory_line.inventory_id.id)]]
quants = quant_obj.quants_get_prefered_domain(cr, uid, move.location_id, move.product_id, move.product_qty, domain=domain, prefered_domain_list=preferred_domain_list, restrict_partner_id=move.restrict_partner_id.id, context=context)
quant_obj.quants_reserve(cr, uid, quants, move, context=context)
elif inventory_line.package_id:
stock_move_obj.action_done(cr, uid, move_id, context=context)
quants = [x.id for x in move.quant_ids]
quant_obj.write(cr, uid, quants, {'package_id': inventory_line.package_id.id}, context=context)
res = quant_obj.search(cr, uid, [('qty', '<', 0.0), ('product_id', '=', move.product_id.id),
('location_id', '=', move.location_dest_id.id), ('package_id', '!=', False)], limit=1, context=context)
if res:
for quant in move.quant_ids:
if quant.location_id.id == move.location_dest_id.id: #To avoid we take a quant that was reconcile already
quant_obj._quant_reconcile_negative(cr, uid, quant, move, context=context)
return move_id
# Should be left out in next version
def restrict_change(self, cr, uid, ids, theoretical_qty, context=None):
return {}
# Should be left out in next version
def on_change_product_id(self, cr, uid, ids, product, uom, theoretical_qty, context=None):
""" Changes UoM
@param location_id: Location id
@param product: Changed product_id
@param uom: UoM product
@return: Dictionary of changed values
"""
if not product:
return {'value': {'product_uom_id': False}}
obj_product = self.pool.get('product.product').browse(cr, uid, product, context=context)
return {'value': {'product_uom_id': uom or obj_product.uom_id.id}}
#----------------------------------------------------------
# Stock Warehouse
#----------------------------------------------------------
class stock_warehouse(osv.osv):
_name = "stock.warehouse"
_description = "Warehouse"
_columns = {
'name': fields.char('Warehouse Name', required=True, select=True),
'company_id': fields.many2one('res.company', 'Company', required=True, readonly=True, select=True),
'partner_id': fields.many2one('res.partner', 'Address'),
'view_location_id': fields.many2one('stock.location', 'View Location', required=True, domain=[('usage', '=', 'view')]),
'lot_stock_id': fields.many2one('stock.location', 'Location Stock', domain=[('usage', '=', 'internal')], required=True),
'code': fields.char('Short Name', size=5, required=True, help="Short name used to identify your warehouse"),
'route_ids': fields.many2many('stock.location.route', 'stock_route_warehouse', 'warehouse_id', 'route_id', 'Routes', domain="[('warehouse_selectable', '=', True)]", help='Defaults routes through the warehouse'),
'reception_steps': fields.selection([
('one_step', 'Receive goods directly in stock (1 step)'),
('two_steps', 'Unload in input location then go to stock (2 steps)'),
('three_steps', 'Unload in input location, go through a quality control before being admitted in stock (3 steps)')], 'Incoming Shipments',
help="Default incoming route to follow", required=True),
'delivery_steps': fields.selection([
('ship_only', 'Ship directly from stock (Ship only)'),
('pick_ship', 'Bring goods to output location before shipping (Pick + Ship)'),
('pick_pack_ship', 'Make packages into a dedicated location, then bring them to the output location for shipping (Pick + Pack + Ship)')], 'Outgoing Shippings',
help="Default outgoing route to follow", required=True),
'wh_input_stock_loc_id': fields.many2one('stock.location', 'Input Location'),
'wh_qc_stock_loc_id': fields.many2one('stock.location', 'Quality Control Location'),
'wh_output_stock_loc_id': fields.many2one('stock.location', 'Output Location'),
'wh_pack_stock_loc_id': fields.many2one('stock.location', 'Packing Location'),
'mto_pull_id': fields.many2one('procurement.rule', 'MTO rule'),
'pick_type_id': fields.many2one('stock.picking.type', 'Pick Type'),
'pack_type_id': fields.many2one('stock.picking.type', 'Pack Type'),
'out_type_id': fields.many2one('stock.picking.type', 'Out Type'),
'in_type_id': fields.many2one('stock.picking.type', 'In Type'),
'int_type_id': fields.many2one('stock.picking.type', 'Internal Type'),
'crossdock_route_id': fields.many2one('stock.location.route', 'Crossdock Route'),
'reception_route_id': fields.many2one('stock.location.route', 'Receipt Route'),
'delivery_route_id': fields.many2one('stock.location.route', 'Delivery Route'),
'resupply_from_wh': fields.boolean('Resupply From Other Warehouses'),
'resupply_wh_ids': fields.many2many('stock.warehouse', 'stock_wh_resupply_table', 'supplied_wh_id', 'supplier_wh_id', 'Resupply Warehouses'),
'resupply_route_ids': fields.one2many('stock.location.route', 'supplied_wh_id', 'Resupply Routes',
help="Routes will be created for these resupply warehouses and you can select them on products and product categories"),
'default_resupply_wh_id': fields.many2one('stock.warehouse', 'Default Resupply Warehouse', help="Goods will always be resupplied from this warehouse"),
}
def onchange_filter_default_resupply_wh_id(self, cr, uid, ids, default_resupply_wh_id, resupply_wh_ids, context=None):
resupply_wh_ids = set([x['id'] for x in (self.resolve_2many_commands(cr, uid, 'resupply_wh_ids', resupply_wh_ids, ['id']))])
if default_resupply_wh_id: #If we are removing the default resupply, we don't have default_resupply_wh_id
resupply_wh_ids.add(default_resupply_wh_id)
resupply_wh_ids = list(resupply_wh_ids)
return {'value': {'resupply_wh_ids': resupply_wh_ids}}
def _get_external_transit_location(self, cr, uid, warehouse, context=None):
''' returns browse record of inter company transit location, if found'''
data_obj = self.pool.get('ir.model.data')
location_obj = self.pool.get('stock.location')
try:
inter_wh_loc = data_obj.get_object_reference(cr, uid, 'stock', 'stock_location_inter_wh')[1]
except:
return False
return location_obj.browse(cr, uid, inter_wh_loc, context=context)
def _get_inter_wh_route(self, cr, uid, warehouse, wh, context=None):
return {
'name': _('%s: Supply Product from %s') % (warehouse.name, wh.name),
'warehouse_selectable': False,
'product_selectable': True,
'product_categ_selectable': True,
'supplied_wh_id': warehouse.id,
'supplier_wh_id': wh.id,
}
def _create_resupply_routes(self, cr, uid, warehouse, supplier_warehouses, default_resupply_wh, context=None):
route_obj = self.pool.get('stock.location.route')
pull_obj = self.pool.get('procurement.rule')
#create route selectable on the product to resupply the warehouse from another one
external_transit_location = self._get_external_transit_location(cr, uid, warehouse, context=context)
internal_transit_location = warehouse.company_id.internal_transit_location_id
input_loc = warehouse.wh_input_stock_loc_id
if warehouse.reception_steps == 'one_step':
input_loc = warehouse.lot_stock_id
for wh in supplier_warehouses:
transit_location = wh.company_id.id == warehouse.company_id.id and internal_transit_location or external_transit_location
if transit_location:
output_loc = wh.wh_output_stock_loc_id
if wh.delivery_steps == 'ship_only':
output_loc = wh.lot_stock_id
# Create extra MTO rule (only for 'ship only' because in the other cases MTO rules already exists)
mto_pull_vals = self._get_mto_pull_rule(cr, uid, wh, [(output_loc, transit_location, wh.out_type_id.id)], context=context)[0]
pull_obj.create(cr, uid, mto_pull_vals, context=context)
inter_wh_route_vals = self._get_inter_wh_route(cr, uid, warehouse, wh, context=context)
inter_wh_route_id = route_obj.create(cr, uid, vals=inter_wh_route_vals, context=context)
values = [(output_loc, transit_location, wh.out_type_id.id, wh), (transit_location, input_loc, warehouse.in_type_id.id, warehouse)]
pull_rules_list = self._get_supply_pull_rules(cr, uid, wh.id, values, inter_wh_route_id, context=context)
for pull_rule in pull_rules_list:
pull_obj.create(cr, uid, vals=pull_rule, context=context)
#if the warehouse is also set as default resupply method, assign this route automatically to the warehouse
if default_resupply_wh and default_resupply_wh.id == wh.id:
self.write(cr, uid, [warehouse.id], {'route_ids': [(4, inter_wh_route_id)]}, context=context)
_defaults = {
'company_id': lambda self, cr, uid, c: self.pool.get('res.company')._company_default_get(cr, uid, 'stock.inventory', context=c),
'reception_steps': 'one_step',
'delivery_steps': 'ship_only',
}
_sql_constraints = [
('warehouse_name_uniq', 'unique(name, company_id)', 'The name of the warehouse must be unique per company!'),
('warehouse_code_uniq', 'unique(code, company_id)', 'The code of the warehouse must be unique per company!'),
]
def _get_partner_locations(self, cr, uid, ids, context=None):
''' returns a tuple made of the browse record of customer location and the browse record of supplier location'''
data_obj = self.pool.get('ir.model.data')
location_obj = self.pool.get('stock.location')
try:
customer_loc = data_obj.get_object_reference(cr, uid, 'stock', 'stock_location_customers')[1]
supplier_loc = data_obj.get_object_reference(cr, uid, 'stock', 'stock_location_suppliers')[1]
except:
customer_loc = location_obj.search(cr, uid, [('usage', '=', 'customer')], context=context)
customer_loc = customer_loc and customer_loc[0] or False
supplier_loc = location_obj.search(cr, uid, [('usage', '=', 'supplier')], context=context)
supplier_loc = supplier_loc and supplier_loc[0] or False
if not (customer_loc and supplier_loc):
raise osv.except_osv(_('Error!'), _('Can\'t find any customer or supplier location.'))
return location_obj.browse(cr, uid, [customer_loc, supplier_loc], context=context)
def _location_used(self, cr, uid, location_id, warehouse, context=None):
pull_obj = self.pool['procurement.rule']
push_obj = self.pool['stock.location.path']
pulls = pull_obj.search(cr, uid, ['&', ('route_id', 'not in', [x.id for x in warehouse.route_ids]), '|', ('location_src_id', '=', location_id), ('location_id', '=', location_id)], context=context)
pushs = push_obj.search(cr, uid, ['&', ('route_id', 'not in', [x.id for x in warehouse.route_ids]), '|', ('location_from_id', '=', location_id), ('location_dest_id', '=', location_id)], context=context)
if pulls or pushs:
return True
return False
def switch_location(self, cr, uid, ids, warehouse, new_reception_step=False, new_delivery_step=False, context=None):
location_obj = self.pool.get('stock.location')
new_reception_step = new_reception_step or warehouse.reception_steps
new_delivery_step = new_delivery_step or warehouse.delivery_steps
if warehouse.reception_steps != new_reception_step:
if not self._location_used(cr, uid, warehouse.wh_input_stock_loc_id.id, warehouse, context=context):
location_obj.write(cr, uid, [warehouse.wh_input_stock_loc_id.id, warehouse.wh_qc_stock_loc_id.id], {'active': False}, context=context)
if new_reception_step != 'one_step':
location_obj.write(cr, uid, warehouse.wh_input_stock_loc_id.id, {'active': True}, context=context)
if new_reception_step == 'three_steps':
location_obj.write(cr, uid, warehouse.wh_qc_stock_loc_id.id, {'active': True}, context=context)
if warehouse.delivery_steps != new_delivery_step:
if not self._location_used(cr, uid, warehouse.wh_output_stock_loc_id.id, warehouse, context=context):
location_obj.write(cr, uid, [warehouse.wh_output_stock_loc_id.id], {'active': False}, context=context)
if not self._location_used(cr, uid, warehouse.wh_pack_stock_loc_id.id, warehouse, context=context):
location_obj.write(cr, uid, [warehouse.wh_pack_stock_loc_id.id], {'active': False}, context=context)
if new_delivery_step != 'ship_only':
location_obj.write(cr, uid, warehouse.wh_output_stock_loc_id.id, {'active': True}, context=context)
if new_delivery_step == 'pick_pack_ship':
location_obj.write(cr, uid, warehouse.wh_pack_stock_loc_id.id, {'active': True}, context=context)
return True
def _get_reception_delivery_route(self, cr, uid, warehouse, route_name, context=None):
return {
'name': self._format_routename(cr, uid, warehouse, route_name, context=context),
'product_categ_selectable': True,
'product_selectable': False,
'sequence': 10,
}
def _get_supply_pull_rules(self, cr, uid, supply_warehouse, values, new_route_id, context=None):
pull_rules_list = []
for from_loc, dest_loc, pick_type_id, warehouse in values:
pull_rules_list.append({
'name': self._format_rulename(cr, uid, warehouse, from_loc, dest_loc, context=context),
'location_src_id': from_loc.id,
'location_id': dest_loc.id,
'route_id': new_route_id,
'action': 'move',
'picking_type_id': pick_type_id,
'procure_method': warehouse.lot_stock_id.id != from_loc.id and 'make_to_order' or 'make_to_stock', # first part of the resuply route is MTS
'warehouse_id': warehouse.id,
'propagate_warehouse_id': supply_warehouse,
})
return pull_rules_list
def _get_push_pull_rules(self, cr, uid, warehouse, active, values, new_route_id, context=None):
first_rule = True
push_rules_list = []
pull_rules_list = []
for from_loc, dest_loc, pick_type_id in values:
push_rules_list.append({
'name': self._format_rulename(cr, uid, warehouse, from_loc, dest_loc, context=context),
'location_from_id': from_loc.id,
'location_dest_id': dest_loc.id,
'route_id': new_route_id,
'auto': 'manual',
'picking_type_id': pick_type_id,
'active': active,
'warehouse_id': warehouse.id,
})
pull_rules_list.append({
'name': self._format_rulename(cr, uid, warehouse, from_loc, dest_loc, context=context),
'location_src_id': from_loc.id,
'location_id': dest_loc.id,
'route_id': new_route_id,
'action': 'move',
'picking_type_id': pick_type_id,
'procure_method': first_rule is True and 'make_to_stock' or 'make_to_order',
'active': active,
'warehouse_id': warehouse.id,
})
first_rule = False
return push_rules_list, pull_rules_list
def _get_mto_route(self, cr, uid, context=None):
route_obj = self.pool.get('stock.location.route')
data_obj = self.pool.get('ir.model.data')
try:
mto_route_id = data_obj.get_object_reference(cr, uid, 'stock', 'route_warehouse0_mto')[1]
except:
mto_route_id = route_obj.search(cr, uid, [('name', 'like', _('Make To Order'))], context=context)
mto_route_id = mto_route_id and mto_route_id[0] or False
if not mto_route_id:
raise osv.except_osv(_('Error!'), _('Can\'t find any generic Make To Order route.'))
return mto_route_id
def _check_remove_mto_resupply_rules(self, cr, uid, warehouse, context=None):
""" Checks that the moves from the different """
pull_obj = self.pool.get('procurement.rule')
mto_route_id = self._get_mto_route(cr, uid, context=context)
rules = pull_obj.search(cr, uid, ['&', ('location_src_id', '=', warehouse.lot_stock_id.id), ('location_id.usage', '=', 'transit')], context=context)
pull_obj.unlink(cr, uid, rules, context=context)
def _get_mto_pull_rule(self, cr, uid, warehouse, values, context=None):
mto_route_id = self._get_mto_route(cr, uid, context=context)
res = []
for value in values:
from_loc, dest_loc, pick_type_id = value
res += [{
'name': self._format_rulename(cr, uid, warehouse, from_loc, dest_loc, context=context) + _(' MTO'),
'location_src_id': from_loc.id,
'location_id': dest_loc.id,
'route_id': mto_route_id,
'action': 'move',
'picking_type_id': pick_type_id,
'procure_method': 'make_to_order',
'active': True,
'warehouse_id': warehouse.id,
}]
return res
def _get_crossdock_route(self, cr, uid, warehouse, route_name, context=None):
return {
'name': self._format_routename(cr, uid, warehouse, route_name, context=context),
'warehouse_selectable': False,
'product_selectable': True,
'product_categ_selectable': True,
'active': warehouse.delivery_steps != 'ship_only' and warehouse.reception_steps != 'one_step',
'sequence': 20,
}
def create_routes(self, cr, uid, ids, warehouse, context=None):
wh_route_ids = []
route_obj = self.pool.get('stock.location.route')
pull_obj = self.pool.get('procurement.rule')
push_obj = self.pool.get('stock.location.path')
routes_dict = self.get_routes_dict(cr, uid, ids, warehouse, context=context)
#create reception route and rules
route_name, values = routes_dict[warehouse.reception_steps]
route_vals = self._get_reception_delivery_route(cr, uid, warehouse, route_name, context=context)
reception_route_id = route_obj.create(cr, uid, route_vals, context=context)
wh_route_ids.append((4, reception_route_id))
push_rules_list, pull_rules_list = self._get_push_pull_rules(cr, uid, warehouse, True, values, reception_route_id, context=context)
#create the push/pull rules
for push_rule in push_rules_list:
push_obj.create(cr, uid, vals=push_rule, context=context)
for pull_rule in pull_rules_list:
#all pull rules in reception route are mto, because we don't want to wait for the scheduler to trigger an orderpoint on input location
pull_rule['procure_method'] = 'make_to_order'
pull_obj.create(cr, uid, vals=pull_rule, context=context)
#create MTS route and pull rules for delivery and a specific route MTO to be set on the product
route_name, values = routes_dict[warehouse.delivery_steps]
route_vals = self._get_reception_delivery_route(cr, uid, warehouse, route_name, context=context)
#create the route and its pull rules
delivery_route_id = route_obj.create(cr, uid, route_vals, context=context)
wh_route_ids.append((4, delivery_route_id))
dummy, pull_rules_list = self._get_push_pull_rules(cr, uid, warehouse, True, values, delivery_route_id, context=context)
for pull_rule in pull_rules_list:
pull_obj.create(cr, uid, vals=pull_rule, context=context)
#create MTO pull rule and link it to the generic MTO route
mto_pull_vals = self._get_mto_pull_rule(cr, uid, warehouse, values, context=context)[0]
mto_pull_id = pull_obj.create(cr, uid, mto_pull_vals, context=context)
#create a route for cross dock operations, that can be set on products and product categories
route_name, values = routes_dict['crossdock']
crossdock_route_vals = self._get_crossdock_route(cr, uid, warehouse, route_name, context=context)
crossdock_route_id = route_obj.create(cr, uid, vals=crossdock_route_vals, context=context)
wh_route_ids.append((4, crossdock_route_id))
dummy, pull_rules_list = self._get_push_pull_rules(cr, uid, warehouse, warehouse.delivery_steps != 'ship_only' and warehouse.reception_steps != 'one_step', values, crossdock_route_id, context=context)
for pull_rule in pull_rules_list:
# Fixed cross-dock is logically mto
pull_rule['procure_method'] = 'make_to_order'
pull_obj.create(cr, uid, vals=pull_rule, context=context)
#create route selectable on the product to resupply the warehouse from another one
self._create_resupply_routes(cr, uid, warehouse, warehouse.resupply_wh_ids, warehouse.default_resupply_wh_id, context=context)
#return routes and mto pull rule to store on the warehouse
return {
'route_ids': wh_route_ids,
'mto_pull_id': mto_pull_id,
'reception_route_id': reception_route_id,
'delivery_route_id': delivery_route_id,
'crossdock_route_id': crossdock_route_id,
}
def change_route(self, cr, uid, ids, warehouse, new_reception_step=False, new_delivery_step=False, context=None):
picking_type_obj = self.pool.get('stock.picking.type')
pull_obj = self.pool.get('procurement.rule')
push_obj = self.pool.get('stock.location.path')
route_obj = self.pool.get('stock.location.route')
new_reception_step = new_reception_step or warehouse.reception_steps
new_delivery_step = new_delivery_step or warehouse.delivery_steps
#change the default source and destination location and (de)activate picking types
input_loc = warehouse.wh_input_stock_loc_id
if new_reception_step == 'one_step':
input_loc = warehouse.lot_stock_id
output_loc = warehouse.wh_output_stock_loc_id
if new_delivery_step == 'ship_only':
output_loc = warehouse.lot_stock_id
picking_type_obj.write(cr, uid, warehouse.in_type_id.id, {'default_location_dest_id': input_loc.id}, context=context)
picking_type_obj.write(cr, uid, warehouse.out_type_id.id, {'default_location_src_id': output_loc.id}, context=context)
picking_type_obj.write(cr, uid, warehouse.pick_type_id.id, {
'active': new_delivery_step != 'ship_only',
'default_location_dest_id': output_loc.id if new_delivery_step == 'pick_ship' else warehouse.wh_pack_stock_loc_id.id,
}, context=context)
picking_type_obj.write(cr, uid, warehouse.pack_type_id.id, {'active': new_delivery_step == 'pick_pack_ship'}, context=context)
routes_dict = self.get_routes_dict(cr, uid, ids, warehouse, context=context)
#update delivery route and rules: unlink the existing rules of the warehouse delivery route and recreate it
pull_obj.unlink(cr, uid, [pu.id for pu in warehouse.delivery_route_id.pull_ids], context=context)
route_name, values = routes_dict[new_delivery_step]
route_obj.write(cr, uid, warehouse.delivery_route_id.id, {'name': self._format_routename(cr, uid, warehouse, route_name, context=context)}, context=context)
dummy, pull_rules_list = self._get_push_pull_rules(cr, uid, warehouse, True, values, warehouse.delivery_route_id.id, context=context)
#create the pull rules
for pull_rule in pull_rules_list:
pull_obj.create(cr, uid, vals=pull_rule, context=context)
#update receipt route and rules: unlink the existing rules of the warehouse receipt route and recreate it
pull_obj.unlink(cr, uid, [pu.id for pu in warehouse.reception_route_id.pull_ids], context=context)
push_obj.unlink(cr, uid, [pu.id for pu in warehouse.reception_route_id.push_ids], context=context)
route_name, values = routes_dict[new_reception_step]
route_obj.write(cr, uid, warehouse.reception_route_id.id, {'name': self._format_routename(cr, uid, warehouse, route_name, context=context)}, context=context)
push_rules_list, pull_rules_list = self._get_push_pull_rules(cr, uid, warehouse, True, values, warehouse.reception_route_id.id, context=context)
#create the push/pull rules
for push_rule in push_rules_list:
push_obj.create(cr, uid, vals=push_rule, context=context)
for pull_rule in pull_rules_list:
#all pull rules in receipt route are mto, because we don't want to wait for the scheduler to trigger an orderpoint on input location
pull_rule['procure_method'] = 'make_to_order'
pull_obj.create(cr, uid, vals=pull_rule, context=context)
route_obj.write(cr, uid, warehouse.crossdock_route_id.id, {'active': new_reception_step != 'one_step' and new_delivery_step != 'ship_only'}, context=context)
#change MTO rule
dummy, values = routes_dict[new_delivery_step]
mto_pull_vals = self._get_mto_pull_rule(cr, uid, warehouse, values, context=context)[0]
pull_obj.write(cr, uid, warehouse.mto_pull_id.id, mto_pull_vals, context=context)
return True
def create_sequences_and_picking_types(self, cr, uid, warehouse, context=None):
seq_obj = self.pool.get('ir.sequence')
picking_type_obj = self.pool.get('stock.picking.type')
#create new sequences
in_seq_id = seq_obj.create(cr, SUPERUSER_ID, values={'name': warehouse.name + _(' Sequence in'), 'prefix': warehouse.code + '/IN/', 'padding': 5}, context=context)
out_seq_id = seq_obj.create(cr, SUPERUSER_ID, values={'name': warehouse.name + _(' Sequence out'), 'prefix': warehouse.code + '/OUT/', 'padding': 5}, context=context)
pack_seq_id = seq_obj.create(cr, SUPERUSER_ID, values={'name': warehouse.name + _(' Sequence packing'), 'prefix': warehouse.code + '/PACK/', 'padding': 5}, context=context)
pick_seq_id = seq_obj.create(cr, SUPERUSER_ID, values={'name': warehouse.name + _(' Sequence picking'), 'prefix': warehouse.code + '/PICK/', 'padding': 5}, context=context)
int_seq_id = seq_obj.create(cr, SUPERUSER_ID, values={'name': warehouse.name + _(' Sequence internal'), 'prefix': warehouse.code + '/INT/', 'padding': 5}, context=context)
wh_stock_loc = warehouse.lot_stock_id
wh_input_stock_loc = warehouse.wh_input_stock_loc_id
wh_output_stock_loc = warehouse.wh_output_stock_loc_id
wh_pack_stock_loc = warehouse.wh_pack_stock_loc_id
#fetch customer and supplier locations, for references
customer_loc, supplier_loc = self._get_partner_locations(cr, uid, warehouse.id, context=context)
#create in, out, internal picking types for warehouse
input_loc = wh_input_stock_loc
if warehouse.reception_steps == 'one_step':
input_loc = wh_stock_loc
output_loc = wh_output_stock_loc
if warehouse.delivery_steps == 'ship_only':
output_loc = wh_stock_loc
#choose the next available color for the picking types of this warehouse
color = 0
available_colors = [c%9 for c in range(3, 12)] # put flashy colors first
all_used_colors = self.pool.get('stock.picking.type').search_read(cr, uid, [('warehouse_id', '!=', False), ('color', '!=', False)], ['color'], order='color')
#don't use sets to preserve the list order
for x in all_used_colors:
if x['color'] in available_colors:
available_colors.remove(x['color'])
if available_colors:
color = available_colors[0]
#order the picking types with a sequence allowing to have the following suit for each warehouse: reception, internal, pick, pack, ship.
max_sequence = self.pool.get('stock.picking.type').search_read(cr, uid, [], ['sequence'], order='sequence desc')
max_sequence = max_sequence and max_sequence[0]['sequence'] or 0
in_type_id = picking_type_obj.create(cr, uid, vals={
'name': _('Receipts'),
'warehouse_id': warehouse.id,
'code': 'incoming',
'sequence_id': in_seq_id,
'default_location_src_id': supplier_loc.id,
'default_location_dest_id': input_loc.id,
'sequence': max_sequence + 1,
'color': color}, context=context)
out_type_id = picking_type_obj.create(cr, uid, vals={
'name': _('Delivery Orders'),
'warehouse_id': warehouse.id,
'code': 'outgoing',
'sequence_id': out_seq_id,
'return_picking_type_id': in_type_id,
'default_location_src_id': output_loc.id,
'default_location_dest_id': customer_loc.id,
'sequence': max_sequence + 4,
'color': color}, context=context)
picking_type_obj.write(cr, uid, [in_type_id], {'return_picking_type_id': out_type_id}, context=context)
int_type_id = picking_type_obj.create(cr, uid, vals={
'name': _('Internal Transfers'),
'warehouse_id': warehouse.id,
'code': 'internal',
'sequence_id': int_seq_id,
'default_location_src_id': wh_stock_loc.id,
'default_location_dest_id': wh_stock_loc.id,
'active': True,
'sequence': max_sequence + 2,
'color': color}, context=context)
pack_type_id = picking_type_obj.create(cr, uid, vals={
'name': _('Pack'),
'warehouse_id': warehouse.id,
'code': 'internal',
'sequence_id': pack_seq_id,
'default_location_src_id': wh_pack_stock_loc.id,
'default_location_dest_id': output_loc.id,
'active': warehouse.delivery_steps == 'pick_pack_ship',
'sequence': max_sequence + 3,
'color': color}, context=context)
pick_type_id = picking_type_obj.create(cr, uid, vals={
'name': _('Pick'),
'warehouse_id': warehouse.id,
'code': 'internal',
'sequence_id': pick_seq_id,
'default_location_src_id': wh_stock_loc.id,
'default_location_dest_id': output_loc.id if warehouse.delivery_steps == 'pick_ship' else wh_pack_stock_loc.id,
'active': warehouse.delivery_steps != 'ship_only',
'sequence': max_sequence + 2,
'color': color}, context=context)
#write picking types on WH
vals = {
'in_type_id': in_type_id,
'out_type_id': out_type_id,
'pack_type_id': pack_type_id,
'pick_type_id': pick_type_id,
'int_type_id': int_type_id,
}
super(stock_warehouse, self).write(cr, uid, warehouse.id, vals=vals, context=context)
def create(self, cr, uid, vals, context=None):
if context is None:
context = {}
if vals is None:
vals = {}
data_obj = self.pool.get('ir.model.data')
seq_obj = self.pool.get('ir.sequence')
picking_type_obj = self.pool.get('stock.picking.type')
location_obj = self.pool.get('stock.location')
#create view location for warehouse
loc_vals = {
'name': _(vals.get('code')),
'usage': 'view',
'location_id': data_obj.get_object_reference(cr, uid, 'stock', 'stock_location_locations')[1],
}
if vals.get('company_id'):
loc_vals['company_id'] = vals.get('company_id')
wh_loc_id = location_obj.create(cr, uid, loc_vals, context=context)
vals['view_location_id'] = wh_loc_id
#create all location
def_values = self.default_get(cr, uid, {'reception_steps', 'delivery_steps'})
reception_steps = vals.get('reception_steps', def_values['reception_steps'])
delivery_steps = vals.get('delivery_steps', def_values['delivery_steps'])
context_with_inactive = context.copy()
context_with_inactive['active_test'] = False
sub_locations = [
{'name': _('Stock'), 'active': True, 'field': 'lot_stock_id'},
{'name': _('Input'), 'active': reception_steps != 'one_step', 'field': 'wh_input_stock_loc_id'},
{'name': _('Quality Control'), 'active': reception_steps == 'three_steps', 'field': 'wh_qc_stock_loc_id'},
{'name': _('Output'), 'active': delivery_steps != 'ship_only', 'field': 'wh_output_stock_loc_id'},
{'name': _('Packing Zone'), 'active': delivery_steps == 'pick_pack_ship', 'field': 'wh_pack_stock_loc_id'},
]
for values in sub_locations:
loc_vals = {
'name': values['name'],
'usage': 'internal',
'location_id': wh_loc_id,
'active': values['active'],
}
if vals.get('company_id'):
loc_vals['company_id'] = vals.get('company_id')
location_id = location_obj.create(cr, uid, loc_vals, context=context_with_inactive)
vals[values['field']] = location_id
#create WH
new_id = super(stock_warehouse, self).create(cr, uid, vals=vals, context=context)
warehouse = self.browse(cr, uid, new_id, context=context)
self.create_sequences_and_picking_types(cr, uid, warehouse, context=context)
#create routes and push/pull rules
new_objects_dict = self.create_routes(cr, uid, new_id, warehouse, context=context)
self.write(cr, uid, warehouse.id, new_objects_dict, context=context)
return new_id
def _format_rulename(self, cr, uid, obj, from_loc, dest_loc, context=None):
return obj.code + ': ' + from_loc.name + ' -> ' + dest_loc.name
def _format_routename(self, cr, uid, obj, name, context=None):
return obj.name + ': ' + name
def get_routes_dict(self, cr, uid, ids, warehouse, context=None):
#fetch customer and supplier locations, for references
customer_loc, supplier_loc = self._get_partner_locations(cr, uid, ids, context=context)
return {
'one_step': (_('Receipt in 1 step'), []),
'two_steps': (_('Receipt in 2 steps'), [(warehouse.wh_input_stock_loc_id, warehouse.lot_stock_id, warehouse.int_type_id.id)]),
'three_steps': (_('Receipt in 3 steps'), [(warehouse.wh_input_stock_loc_id, warehouse.wh_qc_stock_loc_id, warehouse.int_type_id.id), (warehouse.wh_qc_stock_loc_id, warehouse.lot_stock_id, warehouse.int_type_id.id)]),
'crossdock': (_('Cross-Dock'), [(warehouse.wh_input_stock_loc_id, warehouse.wh_output_stock_loc_id, warehouse.int_type_id.id), (warehouse.wh_output_stock_loc_id, customer_loc, warehouse.out_type_id.id)]),
'ship_only': (_('Ship Only'), [(warehouse.lot_stock_id, customer_loc, warehouse.out_type_id.id)]),
'pick_ship': (_('Pick + Ship'), [(warehouse.lot_stock_id, warehouse.wh_output_stock_loc_id, warehouse.pick_type_id.id), (warehouse.wh_output_stock_loc_id, customer_loc, warehouse.out_type_id.id)]),
'pick_pack_ship': (_('Pick + Pack + Ship'), [(warehouse.lot_stock_id, warehouse.wh_pack_stock_loc_id, warehouse.pick_type_id.id), (warehouse.wh_pack_stock_loc_id, warehouse.wh_output_stock_loc_id, warehouse.pack_type_id.id), (warehouse.wh_output_stock_loc_id, customer_loc, warehouse.out_type_id.id)]),
}
def _handle_renaming(self, cr, uid, warehouse, name, code, context=None):
location_obj = self.pool.get('stock.location')
route_obj = self.pool.get('stock.location.route')
pull_obj = self.pool.get('procurement.rule')
push_obj = self.pool.get('stock.location.path')
#rename location
location_id = warehouse.lot_stock_id.location_id.id
location_obj.write(cr, uid, location_id, {'name': code}, context=context)
#rename route and push-pull rules
for route in warehouse.route_ids:
route_obj.write(cr, uid, route.id, {'name': route.name.replace(warehouse.name, name, 1)}, context=context)
for pull in route.pull_ids:
pull_obj.write(cr, uid, pull.id, {'name': pull.name.replace(warehouse.name, name, 1)}, context=context)
for push in route.push_ids:
push_obj.write(cr, uid, push.id, {'name': pull.name.replace(warehouse.name, name, 1)}, context=context)
#change the mto pull rule name
if warehouse.mto_pull_id.id:
pull_obj.write(cr, uid, warehouse.mto_pull_id.id, {'name': warehouse.mto_pull_id.name.replace(warehouse.name, name, 1)}, context=context)
def _check_delivery_resupply(self, cr, uid, warehouse, new_location, change_to_multiple, context=None):
""" Will check if the resupply routes from this warehouse follow the changes of number of delivery steps """
#Check routes that are being delivered by this warehouse and change the rule going to transit location
route_obj = self.pool.get("stock.location.route")
pull_obj = self.pool.get("procurement.rule")
routes = route_obj.search(cr, uid, [('supplier_wh_id','=', warehouse.id)], context=context)
pulls = pull_obj.search(cr, uid, ['&', ('route_id', 'in', routes), ('location_id.usage', '=', 'transit')], context=context)
if pulls:
pull_obj.write(cr, uid, pulls, {'location_src_id': new_location, 'procure_method': change_to_multiple and "make_to_order" or "make_to_stock"}, context=context)
# Create or clean MTO rules
mto_route_id = self._get_mto_route(cr, uid, context=context)
if not change_to_multiple:
# If single delivery we should create the necessary MTO rules for the resupply
# pulls = pull_obj.search(cr, uid, ['&', ('route_id', '=', mto_route_id), ('location_id.usage', '=', 'transit'), ('location_src_id', '=', warehouse.lot_stock_id.id)], context=context)
pull_recs = pull_obj.browse(cr, uid, pulls, context=context)
transfer_locs = list(set([x.location_id for x in pull_recs]))
vals = [(warehouse.lot_stock_id , x, warehouse.out_type_id.id) for x in transfer_locs]
mto_pull_vals = self._get_mto_pull_rule(cr, uid, warehouse, vals, context=context)
for mto_pull_val in mto_pull_vals:
pull_obj.create(cr, uid, mto_pull_val, context=context)
else:
# We need to delete all the MTO pull rules, otherwise they risk to be used in the system
pulls = pull_obj.search(cr, uid, ['&', ('route_id', '=', mto_route_id), ('location_id.usage', '=', 'transit'), ('location_src_id', '=', warehouse.lot_stock_id.id)], context=context)
if pulls:
pull_obj.unlink(cr, uid, pulls, context=context)
def _check_reception_resupply(self, cr, uid, warehouse, new_location, context=None):
"""
Will check if the resupply routes to this warehouse follow the changes of number of receipt steps
"""
#Check routes that are being delivered by this warehouse and change the rule coming from transit location
route_obj = self.pool.get("stock.location.route")
pull_obj = self.pool.get("procurement.rule")
routes = route_obj.search(cr, uid, [('supplied_wh_id','=', warehouse.id)], context=context)
pulls= pull_obj.search(cr, uid, ['&', ('route_id', 'in', routes), ('location_src_id.usage', '=', 'transit')])
if pulls:
pull_obj.write(cr, uid, pulls, {'location_id': new_location}, context=context)
def _check_resupply(self, cr, uid, warehouse, reception_new, delivery_new, context=None):
if reception_new:
old_val = warehouse.reception_steps
new_val = reception_new
change_to_one = (old_val != 'one_step' and new_val == 'one_step')
change_to_multiple = (old_val == 'one_step' and new_val != 'one_step')
if change_to_one or change_to_multiple:
new_location = change_to_one and warehouse.lot_stock_id.id or warehouse.wh_input_stock_loc_id.id
self._check_reception_resupply(cr, uid, warehouse, new_location, context=context)
if delivery_new:
old_val = warehouse.delivery_steps
new_val = delivery_new
change_to_one = (old_val != 'ship_only' and new_val == 'ship_only')
change_to_multiple = (old_val == 'ship_only' and new_val != 'ship_only')
if change_to_one or change_to_multiple:
new_location = change_to_one and warehouse.lot_stock_id.id or warehouse.wh_output_stock_loc_id.id
self._check_delivery_resupply(cr, uid, warehouse, new_location, change_to_multiple, context=context)
def write(self, cr, uid, ids, vals, context=None):
if context is None:
context = {}
if isinstance(ids, (int, long)):
ids = [ids]
seq_obj = self.pool.get('ir.sequence')
route_obj = self.pool.get('stock.location.route')
context_with_inactive = context.copy()
context_with_inactive['active_test'] = False
for warehouse in self.browse(cr, uid, ids, context=context_with_inactive):
#first of all, check if we need to delete and recreate route
if vals.get('reception_steps') or vals.get('delivery_steps'):
#activate and deactivate location according to reception and delivery option
self.switch_location(cr, uid, warehouse.id, warehouse, vals.get('reception_steps', False), vals.get('delivery_steps', False), context=context)
# switch between route
self.change_route(cr, uid, ids, warehouse, vals.get('reception_steps', False), vals.get('delivery_steps', False), context=context_with_inactive)
# Check if we need to change something to resupply warehouses and associated MTO rules
self._check_resupply(cr, uid, warehouse, vals.get('reception_steps'), vals.get('delivery_steps'), context=context)
if vals.get('code') or vals.get('name'):
name = warehouse.name
#rename sequence
if vals.get('name'):
name = vals.get('name', warehouse.name)
self._handle_renaming(cr, uid, warehouse, name, vals.get('code', warehouse.code), context=context_with_inactive)
if warehouse.in_type_id:
seq_obj.write(cr, uid, warehouse.in_type_id.sequence_id.id, {'name': name + _(' Sequence in'), 'prefix': vals.get('code', warehouse.code) + '\IN\\'}, context=context)
seq_obj.write(cr, uid, warehouse.out_type_id.sequence_id.id, {'name': name + _(' Sequence out'), 'prefix': vals.get('code', warehouse.code) + '\OUT\\'}, context=context)
seq_obj.write(cr, uid, warehouse.pack_type_id.sequence_id.id, {'name': name + _(' Sequence packing'), 'prefix': vals.get('code', warehouse.code) + '\PACK\\'}, context=context)
seq_obj.write(cr, uid, warehouse.pick_type_id.sequence_id.id, {'name': name + _(' Sequence picking'), 'prefix': vals.get('code', warehouse.code) + '\PICK\\'}, context=context)
seq_obj.write(cr, uid, warehouse.int_type_id.sequence_id.id, {'name': name + _(' Sequence internal'), 'prefix': vals.get('code', warehouse.code) + '\INT\\'}, context=context)
if vals.get('resupply_wh_ids') and not vals.get('resupply_route_ids'):
for cmd in vals.get('resupply_wh_ids'):
if cmd[0] == 6:
new_ids = set(cmd[2])
old_ids = set([wh.id for wh in warehouse.resupply_wh_ids])
to_add_wh_ids = new_ids - old_ids
if to_add_wh_ids:
supplier_warehouses = self.browse(cr, uid, list(to_add_wh_ids), context=context)
self._create_resupply_routes(cr, uid, warehouse, supplier_warehouses, warehouse.default_resupply_wh_id, context=context)
to_remove_wh_ids = old_ids - new_ids
if to_remove_wh_ids:
to_remove_route_ids = route_obj.search(cr, uid, [('supplied_wh_id', '=', warehouse.id), ('supplier_wh_id', 'in', list(to_remove_wh_ids))], context=context)
if to_remove_route_ids:
route_obj.unlink(cr, uid, to_remove_route_ids, context=context)
else:
#not implemented
pass
if 'default_resupply_wh_id' in vals:
if vals.get('default_resupply_wh_id') == warehouse.id:
raise osv.except_osv(_('Warning'),_('The default resupply warehouse should be different than the warehouse itself!'))
if warehouse.default_resupply_wh_id:
#remove the existing resupplying route on the warehouse
to_remove_route_ids = route_obj.search(cr, uid, [('supplied_wh_id', '=', warehouse.id), ('supplier_wh_id', '=', warehouse.default_resupply_wh_id.id)], context=context)
for inter_wh_route_id in to_remove_route_ids:
self.write(cr, uid, [warehouse.id], {'route_ids': [(3, inter_wh_route_id)]})
if vals.get('default_resupply_wh_id'):
#assign the new resupplying route on all products
to_assign_route_ids = route_obj.search(cr, uid, [('supplied_wh_id', '=', warehouse.id), ('supplier_wh_id', '=', vals.get('default_resupply_wh_id'))], context=context)
for inter_wh_route_id in to_assign_route_ids:
self.write(cr, uid, [warehouse.id], {'route_ids': [(4, inter_wh_route_id)]})
return super(stock_warehouse, self).write(cr, uid, ids, vals=vals, context=context)
def get_all_routes_for_wh(self, cr, uid, warehouse, context=None):
route_obj = self.pool.get("stock.location.route")
all_routes = [route.id for route in warehouse.route_ids]
all_routes += route_obj.search(cr, uid, [('supplied_wh_id', '=', warehouse.id)], context=context)
all_routes += [warehouse.mto_pull_id.route_id.id]
return all_routes
def view_all_routes_for_wh(self, cr, uid, ids, context=None):
all_routes = []
for wh in self.browse(cr, uid, ids, context=context):
all_routes += self.get_all_routes_for_wh(cr, uid, wh, context=context)
domain = [('id', 'in', all_routes)]
return {
'name': _('Warehouse\'s Routes'),
'domain': domain,
'res_model': 'stock.location.route',
'type': 'ir.actions.act_window',
'view_id': False,
'view_mode': 'tree,form',
'view_type': 'form',
'limit': 20
}
class stock_location_path(osv.osv):
_name = "stock.location.path"
_description = "Pushed Flows"
_order = "name"
def _get_rules(self, cr, uid, ids, context=None):
res = []
for route in self.browse(cr, uid, ids, context=context):
res += [x.id for x in route.push_ids]
return res
_columns = {
'name': fields.char('Operation Name', required=True),
'company_id': fields.many2one('res.company', 'Company'),
'route_id': fields.many2one('stock.location.route', 'Route'),
'location_from_id': fields.many2one('stock.location', 'Source Location', ondelete='cascade', select=1, required=True),
'location_dest_id': fields.many2one('stock.location', 'Destination Location', ondelete='cascade', select=1, required=True),
'delay': fields.integer('Delay (days)', help="Number of days to do this transition"),
'picking_type_id': fields.many2one('stock.picking.type', 'Type of the new Operation', required=True, help="This is the picking type associated with the different pickings"),
'auto': fields.selection(
[('auto','Automatic Move'), ('manual','Manual Operation'),('transparent','Automatic No Step Added')],
'Automatic Move',
required=True, select=1,
help="This is used to define paths the product has to follow within the location tree.\n" \
"The 'Automatic Move' value will create a stock move after the current one that will be "\
"validated automatically. With 'Manual Operation', the stock move has to be validated "\
"by a worker. With 'Automatic No Step Added', the location is replaced in the original move."
),
'propagate': fields.boolean('Propagate cancel and split', help='If checked, when the previous move is cancelled or split, the move generated by this move will too'),
'active': fields.boolean('Active', help="If unchecked, it will allow you to hide the rule without removing it."),
'warehouse_id': fields.many2one('stock.warehouse', 'Warehouse'),
'route_sequence': fields.related('route_id', 'sequence', string='Route Sequence',
store={
'stock.location.route': (_get_rules, ['sequence'], 10),
'stock.location.path': (lambda self, cr, uid, ids, c={}: ids, ['route_id'], 10),
}),
'sequence': fields.integer('Sequence'),
}
_defaults = {
'auto': 'auto',
'delay': 0,
'company_id': lambda self, cr, uid, c: self.pool.get('res.company')._company_default_get(cr, uid, 'procurement.order', context=c),
'propagate': True,
'active': True,
}
def _prepare_push_apply(self, cr, uid, rule, move, context=None):
newdate = (datetime.strptime(move.date_expected, DEFAULT_SERVER_DATETIME_FORMAT) + relativedelta.relativedelta(days=rule.delay or 0)).strftime(DEFAULT_SERVER_DATETIME_FORMAT)
return {
'origin': move.origin or move.picking_id.name or "/",
'location_id': move.location_dest_id.id,
'location_dest_id': rule.location_dest_id.id,
'date': newdate,
'company_id': rule.company_id and rule.company_id.id or False,
'date_expected': newdate,
'picking_id': False,
'picking_type_id': rule.picking_type_id and rule.picking_type_id.id or False,
'propagate': rule.propagate,
'push_rule_id': rule.id,
'warehouse_id': rule.warehouse_id and rule.warehouse_id.id or False,
}
def _apply(self, cr, uid, rule, move, context=None):
move_obj = self.pool.get('stock.move')
newdate = (datetime.strptime(move.date_expected, DEFAULT_SERVER_DATETIME_FORMAT) + relativedelta.relativedelta(days=rule.delay or 0)).strftime(DEFAULT_SERVER_DATETIME_FORMAT)
if rule.auto == 'transparent':
old_dest_location = move.location_dest_id.id
move_obj.write(cr, uid, [move.id], {
'date': newdate,
'date_expected': newdate,
'location_dest_id': rule.location_dest_id.id
})
#avoid looping if a push rule is not well configured
if rule.location_dest_id.id != old_dest_location:
#call again push_apply to see if a next step is defined
move_obj._push_apply(cr, uid, [move], context=context)
else:
vals = self._prepare_push_apply(cr, uid, rule, move, context=context)
move_id = move_obj.copy(cr, uid, move.id, vals, context=context)
move_obj.write(cr, uid, [move.id], {
'move_dest_id': move_id,
})
move_obj.action_confirm(cr, uid, [move_id], context=None)
# -------------------------
# Packaging related stuff
# -------------------------
from openerp.report import report_sxw
class stock_package(osv.osv):
"""
These are the packages, containing quants and/or other packages
"""
_name = "stock.quant.package"
_description = "Physical Packages"
_parent_name = "parent_id"
_parent_store = True
_parent_order = 'name'
_order = 'parent_left'
def name_get(self, cr, uid, ids, context=None):
res = self._complete_name(cr, uid, ids, 'complete_name', None, context=context)
return res.items()
def _complete_name(self, cr, uid, ids, name, args, context=None):
""" Forms complete name of location from parent location to child location.
@return: Dictionary of values
"""
res = {}
for m in self.browse(cr, uid, ids, context=context):
res[m.id] = m.name
parent = m.parent_id
while parent:
res[m.id] = parent.name + ' / ' + res[m.id]
parent = parent.parent_id
return res
def _get_packages(self, cr, uid, ids, context=None):
"""Returns packages from quants for store"""
res = set()
for quant in self.browse(cr, uid, ids, context=context):
pack = quant.package_id
while pack:
res.add(pack.id)
pack = pack.parent_id
return list(res)
def _get_package_info(self, cr, uid, ids, name, args, context=None):
quant_obj = self.pool.get("stock.quant")
default_company_id = self.pool.get('res.users').browse(cr, uid, uid, context=context).company_id.id
res = dict((res_id, {'location_id': False, 'company_id': default_company_id, 'owner_id': False}) for res_id in ids)
for pack in self.browse(cr, uid, ids, context=context):
quants = quant_obj.search(cr, uid, [('package_id', 'child_of', pack.id)], context=context)
if quants:
quant = quant_obj.browse(cr, uid, quants[0], context=context)
res[pack.id]['location_id'] = quant.location_id.id
res[pack.id]['owner_id'] = quant.owner_id.id
res[pack.id]['company_id'] = quant.company_id.id
else:
res[pack.id]['location_id'] = False
res[pack.id]['owner_id'] = False
res[pack.id]['company_id'] = False
return res
def _get_packages_to_relocate(self, cr, uid, ids, context=None):
res = set()
for pack in self.browse(cr, uid, ids, context=context):
res.add(pack.id)
if pack.parent_id:
res.add(pack.parent_id.id)
return list(res)
_columns = {
'name': fields.char('Package Reference', select=True, copy=False),
'complete_name': fields.function(_complete_name, type='char', string="Package Name",),
'parent_left': fields.integer('Left Parent', select=1),
'parent_right': fields.integer('Right Parent', select=1),
'packaging_id': fields.many2one('product.packaging', 'Packaging', help="This field should be completed only if everything inside the package share the same product, otherwise it doesn't really makes sense.", select=True),
'ul_id': fields.many2one('product.ul', 'Logistic Unit'),
'location_id': fields.function(_get_package_info, type='many2one', relation='stock.location', string='Location', multi="package",
store={
'stock.quant': (_get_packages, ['location_id'], 10),
'stock.quant.package': (_get_packages_to_relocate, ['quant_ids', 'children_ids', 'parent_id'], 10),
}, readonly=True, select=True),
'quant_ids': fields.one2many('stock.quant', 'package_id', 'Bulk Content', readonly=True),
'parent_id': fields.many2one('stock.quant.package', 'Parent Package', help="The package containing this item", ondelete='restrict', readonly=True),
'children_ids': fields.one2many('stock.quant.package', 'parent_id', 'Contained Packages', readonly=True),
'company_id': fields.function(_get_package_info, type="many2one", relation='res.company', string='Company', multi="package",
store={
'stock.quant': (_get_packages, ['company_id'], 10),
'stock.quant.package': (_get_packages_to_relocate, ['quant_ids', 'children_ids', 'parent_id'], 10),
}, readonly=True, select=True),
'owner_id': fields.function(_get_package_info, type='many2one', relation='res.partner', string='Owner', multi="package",
store={
'stock.quant': (_get_packages, ['owner_id'], 10),
'stock.quant.package': (_get_packages_to_relocate, ['quant_ids', 'children_ids', 'parent_id'], 10),
}, readonly=True, select=True),
}
_defaults = {
'name': lambda self, cr, uid, context: self.pool.get('ir.sequence').get(cr, uid, 'stock.quant.package') or _('Unknown Pack')
}
def _check_location_constraint(self, cr, uid, packs, context=None):
'''checks that all quants in a package are stored in the same location. This function cannot be used
as a constraint because it needs to be checked on pack operations (they may not call write on the
package)
'''
quant_obj = self.pool.get('stock.quant')
for pack in packs:
parent = pack
while parent.parent_id:
parent = parent.parent_id
quant_ids = self.get_content(cr, uid, [parent.id], context=context)
quants = [x for x in quant_obj.browse(cr, uid, quant_ids, context=context) if x.qty > 0]
location_id = quants and quants[0].location_id.id or False
if not [quant.location_id.id == location_id for quant in quants]:
raise osv.except_osv(_('Error'), _('Everything inside a package should be in the same location'))
return True
def action_print(self, cr, uid, ids, context=None):
context = dict(context or {}, active_ids=ids)
return self.pool.get("report").get_action(cr, uid, ids, 'stock.report_package_barcode_small', context=context)
def unpack(self, cr, uid, ids, context=None):
quant_obj = self.pool.get('stock.quant')
for package in self.browse(cr, uid, ids, context=context):
quant_ids = [quant.id for quant in package.quant_ids]
quant_obj.write(cr, uid, quant_ids, {'package_id': package.parent_id.id or False}, context=context)
children_package_ids = [child_package.id for child_package in package.children_ids]
self.write(cr, uid, children_package_ids, {'parent_id': package.parent_id.id or False}, context=context)
#delete current package since it contains nothing anymore
self.unlink(cr, uid, ids, context=context)
return self.pool.get('ir.actions.act_window').for_xml_id(cr, uid, 'stock', 'action_package_view', context=context)
def get_content(self, cr, uid, ids, context=None):
child_package_ids = self.search(cr, uid, [('id', 'child_of', ids)], context=context)
return self.pool.get('stock.quant').search(cr, uid, [('package_id', 'in', child_package_ids)], context=context)
def get_content_package(self, cr, uid, ids, context=None):
quants_ids = self.get_content(cr, uid, ids, context=context)
res = self.pool.get('ir.actions.act_window').for_xml_id(cr, uid, 'stock', 'quantsact', context=context)
res['domain'] = [('id', 'in', quants_ids)]
return res
def _get_product_total_qty(self, cr, uid, package_record, product_id, context=None):
''' find the total of given product 'product_id' inside the given package 'package_id'''
quant_obj = self.pool.get('stock.quant')
all_quant_ids = self.get_content(cr, uid, [package_record.id], context=context)
total = 0
for quant in quant_obj.browse(cr, uid, all_quant_ids, context=context):
if quant.product_id.id == product_id:
total += quant.qty
return total
def _get_all_products_quantities(self, cr, uid, package_id, context=None):
'''This function computes the different product quantities for the given package
'''
quant_obj = self.pool.get('stock.quant')
res = {}
for quant in quant_obj.browse(cr, uid, self.get_content(cr, uid, package_id, context=context)):
if quant.product_id.id not in res:
res[quant.product_id.id] = 0
res[quant.product_id.id] += quant.qty
return res
def copy_pack(self, cr, uid, id, default_pack_values=None, default=None, context=None):
stock_pack_operation_obj = self.pool.get('stock.pack.operation')
if default is None:
default = {}
new_package_id = self.copy(cr, uid, id, default_pack_values, context=context)
default['result_package_id'] = new_package_id
op_ids = stock_pack_operation_obj.search(cr, uid, [('result_package_id', '=', id)], context=context)
for op_id in op_ids:
stock_pack_operation_obj.copy(cr, uid, op_id, default, context=context)
class stock_pack_operation(osv.osv):
_name = "stock.pack.operation"
_description = "Packing Operation"
def _get_remaining_prod_quantities(self, cr, uid, operation, context=None):
'''Get the remaining quantities per product on an operation with a package. This function returns a dictionary'''
#if the operation doesn't concern a package, it's not relevant to call this function
if not operation.package_id or operation.product_id:
return {operation.product_id.id: operation.remaining_qty}
#get the total of products the package contains
res = self.pool.get('stock.quant.package')._get_all_products_quantities(cr, uid, operation.package_id.id, context=context)
#reduce by the quantities linked to a move
for record in operation.linked_move_operation_ids:
if record.move_id.product_id.id not in res:
res[record.move_id.product_id.id] = 0
res[record.move_id.product_id.id] -= record.qty
return res
def _get_remaining_qty(self, cr, uid, ids, name, args, context=None):
uom_obj = self.pool.get('product.uom')
res = {}
for ops in self.browse(cr, uid, ids, context=context):
res[ops.id] = 0
if ops.package_id and not ops.product_id:
#dont try to compute the remaining quantity for packages because it's not relevant (a package could include different products).
#should use _get_remaining_prod_quantities instead
continue
else:
qty = ops.product_qty
if ops.product_uom_id:
qty = uom_obj._compute_qty_obj(cr, uid, ops.product_uom_id, ops.product_qty, ops.product_id.uom_id, context=context)
for record in ops.linked_move_operation_ids:
qty -= record.qty
res[ops.id] = float_round(qty, precision_rounding=ops.product_id.uom_id.rounding)
return res
def product_id_change(self, cr, uid, ids, product_id, product_uom_id, product_qty, context=None):
res = self.on_change_tests(cr, uid, ids, product_id, product_uom_id, product_qty, context=context)
if product_id and not product_uom_id:
product = self.pool.get('product.product').browse(cr, uid, product_id, context=context)
res['value']['product_uom_id'] = product.uom_id.id
return res
def on_change_tests(self, cr, uid, ids, product_id, product_uom_id, product_qty, context=None):
res = {'value': {}}
uom_obj = self.pool.get('product.uom')
if product_id:
product = self.pool.get('product.product').browse(cr, uid, product_id, context=context)
product_uom_id = product_uom_id or product.uom_id.id
selected_uom = uom_obj.browse(cr, uid, product_uom_id, context=context)
if selected_uom.category_id.id != product.uom_id.category_id.id:
res['warning'] = {
'title': _('Warning: wrong UoM!'),
'message': _('The selected UoM for product %s is not compatible with the UoM set on the product form. \nPlease choose an UoM within the same UoM category.') % (product.name)
}
if product_qty and 'warning' not in res:
rounded_qty = uom_obj._compute_qty(cr, uid, product_uom_id, product_qty, product_uom_id, round=True)
if rounded_qty != product_qty:
res['warning'] = {
'title': _('Warning: wrong quantity!'),
'message': _('The chosen quantity for product %s is not compatible with the UoM rounding. It will be automatically converted at confirmation') % (product.name)
}
return res
_columns = {
'picking_id': fields.many2one('stock.picking', 'Stock Picking', help='The stock operation where the packing has been made', required=True),
'product_id': fields.many2one('product.product', 'Product', ondelete="CASCADE"), # 1
'product_uom_id': fields.many2one('product.uom', 'Product Unit of Measure'),
'product_qty': fields.float('Quantity', digits_compute=dp.get_precision('Product Unit of Measure'), required=True),
'qty_done': fields.float('Quantity Processed', digits_compute=dp.get_precision('Product Unit of Measure')),
'package_id': fields.many2one('stock.quant.package', 'Source Package'), # 2
'lot_id': fields.many2one('stock.production.lot', 'Lot/Serial Number'),
'result_package_id': fields.many2one('stock.quant.package', 'Destination Package', help="If set, the operations are packed into this package", required=False, ondelete='cascade'),
'date': fields.datetime('Date', required=True),
'owner_id': fields.many2one('res.partner', 'Owner', help="Owner of the quants"),
#'update_cost': fields.boolean('Need cost update'),
'cost': fields.float("Cost", help="Unit Cost for this product line"),
'currency': fields.many2one('res.currency', string="Currency", help="Currency in which Unit cost is expressed", ondelete='CASCADE'),
'linked_move_operation_ids': fields.one2many('stock.move.operation.link', 'operation_id', string='Linked Moves', readonly=True, help='Moves impacted by this operation for the computation of the remaining quantities'),
'remaining_qty': fields.function(_get_remaining_qty, type='float', digits = 0, string="Remaining Qty", help="Remaining quantity in default UoM according to moves matched with this operation. "),
'location_id': fields.many2one('stock.location', 'Source Location', required=True),
'location_dest_id': fields.many2one('stock.location', 'Destination Location', required=True),
'processed': fields.selection([('true','Yes'), ('false','No')],'Has been processed?', required=True),
}
_defaults = {
'date': fields.date.context_today,
'qty_done': 0,
'processed': lambda *a: 'false',
}
def write(self, cr, uid, ids, vals, context=None):
context = context or {}
res = super(stock_pack_operation, self).write(cr, uid, ids, vals, context=context)
if isinstance(ids, (int, long)):
ids = [ids]
if not context.get("no_recompute"):
pickings = vals.get('picking_id') and [vals['picking_id']] or list(set([x.picking_id.id for x in self.browse(cr, uid, ids, context=context)]))
self.pool.get("stock.picking").do_recompute_remaining_quantities(cr, uid, pickings, context=context)
return res
def create(self, cr, uid, vals, context=None):
context = context or {}
res_id = super(stock_pack_operation, self).create(cr, uid, vals, context=context)
if vals.get("picking_id") and not context.get("no_recompute"):
self.pool.get("stock.picking").do_recompute_remaining_quantities(cr, uid, [vals['picking_id']], context=context)
return res_id
def action_drop_down(self, cr, uid, ids, context=None):
''' Used by barcode interface to say that pack_operation has been moved from src location
to destination location, if qty_done is less than product_qty than we have to split the
operation in two to process the one with the qty moved
'''
processed_ids = []
move_obj = self.pool.get("stock.move")
for pack_op in self.browse(cr, uid, ids, context=None):
if pack_op.product_id and pack_op.location_id and pack_op.location_dest_id:
move_obj.check_tracking_product(cr, uid, pack_op.product_id, pack_op.lot_id.id, pack_op.location_id, pack_op.location_dest_id, context=context)
op = pack_op.id
if pack_op.qty_done < pack_op.product_qty:
# we split the operation in two
op = self.copy(cr, uid, pack_op.id, {'product_qty': pack_op.qty_done, 'qty_done': pack_op.qty_done}, context=context)
self.write(cr, uid, [pack_op.id], {'product_qty': pack_op.product_qty - pack_op.qty_done, 'qty_done': 0, 'lot_id': False}, context=context)
processed_ids.append(op)
self.write(cr, uid, processed_ids, {'processed': 'true'}, context=context)
def create_and_assign_lot(self, cr, uid, id, name, context=None):
''' Used by barcode interface to create a new lot and assign it to the operation
'''
obj = self.browse(cr,uid,id,context)
product_id = obj.product_id.id
val = {'product_id': product_id}
new_lot_id = False
if name:
lots = self.pool.get('stock.production.lot').search(cr, uid, ['&', ('name', '=', name), ('product_id', '=', product_id)], context=context)
if lots:
new_lot_id = lots[0]
val.update({'name': name})
if not new_lot_id:
new_lot_id = self.pool.get('stock.production.lot').create(cr, uid, val, context=context)
self.write(cr, uid, id, {'lot_id': new_lot_id}, context=context)
def _search_and_increment(self, cr, uid, picking_id, domain, filter_visible=False, visible_op_ids=False, increment=True, context=None):
'''Search for an operation with given 'domain' in a picking, if it exists increment the qty (+1) otherwise create it
:param domain: list of tuple directly reusable as a domain
context can receive a key 'current_package_id' with the package to consider for this operation
returns True
'''
if context is None:
context = {}
#if current_package_id is given in the context, we increase the number of items in this package
package_clause = [('result_package_id', '=', context.get('current_package_id', False))]
existing_operation_ids = self.search(cr, uid, [('picking_id', '=', picking_id)] + domain + package_clause, context=context)
todo_operation_ids = []
if existing_operation_ids:
if filter_visible:
todo_operation_ids = [val for val in existing_operation_ids if val in visible_op_ids]
else:
todo_operation_ids = existing_operation_ids
if todo_operation_ids:
#existing operation found for the given domain and picking => increment its quantity
operation_id = todo_operation_ids[0]
op_obj = self.browse(cr, uid, operation_id, context=context)
qty = op_obj.qty_done
if increment:
qty += 1
else:
qty -= 1 if qty >= 1 else 0
if qty == 0 and op_obj.product_qty == 0:
#we have a line with 0 qty set, so delete it
self.unlink(cr, uid, [operation_id], context=context)
return False
self.write(cr, uid, [operation_id], {'qty_done': qty}, context=context)
else:
#no existing operation found for the given domain and picking => create a new one
picking_obj = self.pool.get("stock.picking")
picking = picking_obj.browse(cr, uid, picking_id, context=context)
values = {
'picking_id': picking_id,
'product_qty': 0,
'location_id': picking.location_id.id,
'location_dest_id': picking.location_dest_id.id,
'qty_done': 1,
}
for key in domain:
var_name, dummy, value = key
uom_id = False
if var_name == 'product_id':
uom_id = self.pool.get('product.product').browse(cr, uid, value, context=context).uom_id.id
update_dict = {var_name: value}
if uom_id:
update_dict['product_uom_id'] = uom_id
values.update(update_dict)
operation_id = self.create(cr, uid, values, context=context)
return operation_id
class stock_move_operation_link(osv.osv):
"""
Table making the link between stock.moves and stock.pack.operations to compute the remaining quantities on each of these objects
"""
_name = "stock.move.operation.link"
_description = "Link between stock moves and pack operations"
_columns = {
'qty': fields.float('Quantity', help="Quantity of products to consider when talking about the contribution of this pack operation towards the remaining quantity of the move (and inverse). Given in the product main uom."),
'operation_id': fields.many2one('stock.pack.operation', 'Operation', required=True, ondelete="cascade"),
'move_id': fields.many2one('stock.move', 'Move', required=True, ondelete="cascade"),
'reserved_quant_id': fields.many2one('stock.quant', 'Reserved Quant', help="Technical field containing the quant that created this link between an operation and a stock move. Used at the stock_move_obj.action_done() time to avoid seeking a matching quant again"),
}
def get_specific_domain(self, cr, uid, record, context=None):
'''Returns the specific domain to consider for quant selection in action_assign() or action_done() of stock.move,
having the record given as parameter making the link between the stock move and a pack operation'''
op = record.operation_id
domain = []
if op.package_id and op.product_id:
#if removing a product from a box, we restrict the choice of quants to this box
domain.append(('package_id', '=', op.package_id.id))
elif op.package_id:
#if moving a box, we allow to take everything from inside boxes as well
domain.append(('package_id', 'child_of', [op.package_id.id]))
else:
#if not given any information about package, we don't open boxes
domain.append(('package_id', '=', False))
#if lot info is given, we restrict choice to this lot otherwise we can take any
if op.lot_id:
domain.append(('lot_id', '=', op.lot_id.id))
#if owner info is given, we restrict to this owner otherwise we restrict to no owner
if op.owner_id:
domain.append(('owner_id', '=', op.owner_id.id))
else:
domain.append(('owner_id', '=', False))
return domain
class stock_warehouse_orderpoint(osv.osv):
"""
Defines Minimum stock rules.
"""
_name = "stock.warehouse.orderpoint"
_description = "Minimum Inventory Rule"
def subtract_procurements(self, cr, uid, orderpoint, context=None):
'''This function returns quantity of product that needs to be deducted from the orderpoint computed quantity because there's already a procurement created with aim to fulfill it.
'''
qty = 0
uom_obj = self.pool.get("product.uom")
for procurement in orderpoint.procurement_ids:
if procurement.state in ('cancel', 'done'):
continue
procurement_qty = uom_obj._compute_qty_obj(cr, uid, procurement.product_uom, procurement.product_qty, procurement.product_id.uom_id, context=context)
for move in procurement.move_ids:
#need to add the moves in draft as they aren't in the virtual quantity + moves that have not been created yet
if move.state not in ('draft'):
#if move is already confirmed, assigned or done, the virtual stock is already taking this into account so it shouldn't be deducted
procurement_qty -= move.product_qty
qty += procurement_qty
return qty
def _check_product_uom(self, cr, uid, ids, context=None):
'''
Check if the UoM has the same category as the product standard UoM
'''
if not context:
context = {}
for rule in self.browse(cr, uid, ids, context=context):
if rule.product_id.uom_id.category_id.id != rule.product_uom.category_id.id:
return False
return True
def action_view_proc_to_process(self, cr, uid, ids, context=None):
act_obj = self.pool.get('ir.actions.act_window')
mod_obj = self.pool.get('ir.model.data')
proc_ids = self.pool.get('procurement.order').search(cr, uid, [('orderpoint_id', 'in', ids), ('state', 'not in', ('done', 'cancel'))], context=context)
result = mod_obj.get_object_reference(cr, uid, 'procurement', 'do_view_procurements')
if not result:
return False
result = act_obj.read(cr, uid, [result[1]], context=context)[0]
result['domain'] = "[('id', 'in', [" + ','.join(map(str, proc_ids)) + "])]"
return result
_columns = {
'name': fields.char('Name', required=True, copy=False),
'active': fields.boolean('Active', help="If the active field is set to False, it will allow you to hide the orderpoint without removing it."),
'logic': fields.selection([('max', 'Order to Max'), ('price', 'Best price (not yet active!)')], 'Reordering Mode', required=True),
'warehouse_id': fields.many2one('stock.warehouse', 'Warehouse', required=True, ondelete="cascade"),
'location_id': fields.many2one('stock.location', 'Location', required=True, ondelete="cascade"),
'product_id': fields.many2one('product.product', 'Product', required=True, ondelete='cascade', domain=[('type', '=', 'product')]),
'product_uom': fields.related('product_id', 'uom_id', type='many2one', relation='product.uom', string='Product Unit of Measure', readonly=True, required=True),
'product_min_qty': fields.float('Minimum Quantity', required=True,
digits_compute=dp.get_precision('Product Unit of Measure'),
help="When the virtual stock goes below the Min Quantity specified for this field, Odoo generates "\
"a procurement to bring the forecasted quantity to the Max Quantity."),
'product_max_qty': fields.float('Maximum Quantity', required=True,
digits_compute=dp.get_precision('Product Unit of Measure'),
help="When the virtual stock goes below the Min Quantity, Odoo generates "\
"a procurement to bring the forecasted quantity to the Quantity specified as Max Quantity."),
'qty_multiple': fields.float('Qty Multiple', required=True,
digits_compute=dp.get_precision('Product Unit of Measure'),
help="The procurement quantity will be rounded up to this multiple. If it is 0, the exact quantity will be used. "),
'procurement_ids': fields.one2many('procurement.order', 'orderpoint_id', 'Created Procurements'),
'group_id': fields.many2one('procurement.group', 'Procurement Group', help="Moves created through this orderpoint will be put in this procurement group. If none is given, the moves generated by procurement rules will be grouped into one big picking.", copy=False),
'company_id': fields.many2one('res.company', 'Company', required=True),
}
_defaults = {
'active': lambda *a: 1,
'logic': lambda *a: 'max',
'qty_multiple': lambda *a: 1,
'name': lambda self, cr, uid, context: self.pool.get('ir.sequence').get(cr, uid, 'stock.orderpoint') or '',
'product_uom': lambda self, cr, uid, context: context.get('product_uom', False),
'company_id': lambda self, cr, uid, context: self.pool.get('res.company')._company_default_get(cr, uid, 'stock.warehouse.orderpoint', context=context)
}
_sql_constraints = [
('qty_multiple_check', 'CHECK( qty_multiple >= 0 )', 'Qty Multiple must be greater than or equal to zero.'),
]
_constraints = [
(_check_product_uom, 'You have to select a product unit of measure in the same category than the default unit of measure of the product', ['product_id', 'product_uom']),
]
def default_get(self, cr, uid, fields, context=None):
warehouse_obj = self.pool.get('stock.warehouse')
res = super(stock_warehouse_orderpoint, self).default_get(cr, uid, fields, context)
# default 'warehouse_id' and 'location_id'
if 'warehouse_id' not in res:
warehouse_ids = res.get('company_id') and warehouse_obj.search(cr, uid, [('company_id', '=', res['company_id'])], limit=1, context=context) or []
res['warehouse_id'] = warehouse_ids and warehouse_ids[0] or False
if 'location_id' not in res:
res['location_id'] = res.get('warehouse_id') and warehouse_obj.browse(cr, uid, res['warehouse_id'], context).lot_stock_id.id or False
return res
def onchange_warehouse_id(self, cr, uid, ids, warehouse_id, context=None):
""" Finds location id for changed warehouse.
@param warehouse_id: Changed id of warehouse.
@return: Dictionary of values.
"""
if warehouse_id:
w = self.pool.get('stock.warehouse').browse(cr, uid, warehouse_id, context=context)
v = {'location_id': w.lot_stock_id.id}
return {'value': v}
return {}
def onchange_product_id(self, cr, uid, ids, product_id, context=None):
""" Finds UoM for changed product.
@param product_id: Changed id of product.
@return: Dictionary of values.
"""
if product_id:
prod = self.pool.get('product.product').browse(cr, uid, product_id, context=context)
d = {'product_uom': [('category_id', '=', prod.uom_id.category_id.id)]}
v = {'product_uom': prod.uom_id.id}
return {'value': v, 'domain': d}
return {'domain': {'product_uom': []}}
class stock_picking_type(osv.osv):
_name = "stock.picking.type"
_description = "The picking type determines the picking view"
_order = 'sequence'
def open_barcode_interface(self, cr, uid, ids, context=None):
final_url = "/barcode/web/#action=stock.ui&picking_type_id=" + str(ids[0]) if len(ids) else '0'
return {'type': 'ir.actions.act_url', 'url': final_url, 'target': 'self'}
def _get_tristate_values(self, cr, uid, ids, field_name, arg, context=None):
picking_obj = self.pool.get('stock.picking')
res = {}
for picking_type_id in ids:
#get last 10 pickings of this type
picking_ids = picking_obj.search(cr, uid, [('picking_type_id', '=', picking_type_id), ('state', '=', 'done')], order='date_done desc', limit=10, context=context)
tristates = []
for picking in picking_obj.browse(cr, uid, picking_ids, context=context):
if picking.date_done > picking.date:
tristates.insert(0, {'tooltip': picking.name or '' + ": " + _('Late'), 'value': -1})
elif picking.backorder_id:
tristates.insert(0, {'tooltip': picking.name or '' + ": " + _('Backorder exists'), 'value': 0})
else:
tristates.insert(0, {'tooltip': picking.name or '' + ": " + _('OK'), 'value': 1})
res[picking_type_id] = json.dumps(tristates)
return res
def _get_picking_count(self, cr, uid, ids, field_names, arg, context=None):
obj = self.pool.get('stock.picking')
domains = {
'count_picking_draft': [('state', '=', 'draft')],
'count_picking_waiting': [('state', '=', 'confirmed')],
'count_picking_ready': [('state', 'in', ('assigned', 'partially_available'))],
'count_picking': [('state', 'in', ('assigned', 'waiting', 'confirmed', 'partially_available'))],
'count_picking_late': [('min_date', '<', time.strftime(DEFAULT_SERVER_DATETIME_FORMAT)), ('state', 'in', ('assigned', 'waiting', 'confirmed', 'partially_available'))],
'count_picking_backorders': [('backorder_id', '!=', False), ('state', 'in', ('confirmed', 'assigned', 'waiting', 'partially_available'))],
}
result = {}
for field in domains:
data = obj.read_group(cr, uid, domains[field] +
[('state', 'not in', ('done', 'cancel')), ('picking_type_id', 'in', ids)],
['picking_type_id'], ['picking_type_id'], context=context)
count = dict(map(lambda x: (x['picking_type_id'] and x['picking_type_id'][0], x['picking_type_id_count']), data))
for tid in ids:
result.setdefault(tid, {})[field] = count.get(tid, 0)
for tid in ids:
if result[tid]['count_picking']:
result[tid]['rate_picking_late'] = result[tid]['count_picking_late'] * 100 / result[tid]['count_picking']
result[tid]['rate_picking_backorders'] = result[tid]['count_picking_backorders'] * 100 / result[tid]['count_picking']
else:
result[tid]['rate_picking_late'] = 0
result[tid]['rate_picking_backorders'] = 0
return result
def onchange_picking_code(self, cr, uid, ids, picking_code=False):
if not picking_code:
return False
obj_data = self.pool.get('ir.model.data')
stock_loc = obj_data.xmlid_to_res_id(cr, uid, 'stock.stock_location_stock')
result = {
'default_location_src_id': stock_loc,
'default_location_dest_id': stock_loc,
}
if picking_code == 'incoming':
result['default_location_src_id'] = obj_data.xmlid_to_res_id(cr, uid, 'stock.stock_location_suppliers')
elif picking_code == 'outgoing':
result['default_location_dest_id'] = obj_data.xmlid_to_res_id(cr, uid, 'stock.stock_location_customers')
return {'value': result}
def _get_name(self, cr, uid, ids, field_names, arg, context=None):
return dict(self.name_get(cr, uid, ids, context=context))
def name_get(self, cr, uid, ids, context=None):
"""Overides orm name_get method to display 'Warehouse_name: PickingType_name' """
if context is None:
context = {}
if not isinstance(ids, list):
ids = [ids]
res = []
if not ids:
return res
for record in self.browse(cr, uid, ids, context=context):
name = record.name
if record.warehouse_id:
name = record.warehouse_id.name + ': ' +name
if context.get('special_shortened_wh_name'):
if record.warehouse_id:
name = record.warehouse_id.name
else:
name = _('Customer') + ' (' + record.name + ')'
res.append((record.id, name))
return res
def _default_warehouse(self, cr, uid, context=None):
user = self.pool.get('res.users').browse(cr, uid, uid, context)
res = self.pool.get('stock.warehouse').search(cr, uid, [('company_id', '=', user.company_id.id)], limit=1, context=context)
return res and res[0] or False
_columns = {
'name': fields.char('Picking Type Name', translate=True, required=True),
'complete_name': fields.function(_get_name, type='char', string='Name'),
'color': fields.integer('Color'),
'sequence': fields.integer('Sequence', help="Used to order the 'All Operations' kanban view"),
'sequence_id': fields.many2one('ir.sequence', 'Reference Sequence', required=True),
'default_location_src_id': fields.many2one('stock.location', 'Default Source Location'),
'default_location_dest_id': fields.many2one('stock.location', 'Default Destination Location'),
'code': fields.selection([('incoming', 'Suppliers'), ('outgoing', 'Customers'), ('internal', 'Internal')], 'Type of Operation', required=True),
'return_picking_type_id': fields.many2one('stock.picking.type', 'Picking Type for Returns'),
'warehouse_id': fields.many2one('stock.warehouse', 'Warehouse', ondelete='cascade'),
'active': fields.boolean('Active'),
# Statistics for the kanban view
'last_done_picking': fields.function(_get_tristate_values,
type='char',
string='Last 10 Done Pickings'),
'count_picking_draft': fields.function(_get_picking_count,
type='integer', multi='_get_picking_count'),
'count_picking_ready': fields.function(_get_picking_count,
type='integer', multi='_get_picking_count'),
'count_picking': fields.function(_get_picking_count,
type='integer', multi='_get_picking_count'),
'count_picking_waiting': fields.function(_get_picking_count,
type='integer', multi='_get_picking_count'),
'count_picking_late': fields.function(_get_picking_count,
type='integer', multi='_get_picking_count'),
'count_picking_backorders': fields.function(_get_picking_count,
type='integer', multi='_get_picking_count'),
'rate_picking_late': fields.function(_get_picking_count,
type='integer', multi='_get_picking_count'),
'rate_picking_backorders': fields.function(_get_picking_count,
type='integer', multi='_get_picking_count'),
}
_defaults = {
'warehouse_id': _default_warehouse,
'active': True,
}
# vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4:
| oliverhr/odoo | addons/stock/stock.py | Python | agpl-3.0 | 269,349 |
<?php
/**
* Shopware 5
* Copyright (c) shopware AG
*
* According to our dual licensing model, this program can be used either
* under the terms of the GNU Affero General Public License, version 3,
* or under a proprietary license.
*
* The texts of the GNU Affero General Public License with an additional
* permission and of our proprietary license can be found at and
* in the LICENSE file you have received along with this program.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* "Shopware" is a registered trademark of shopware AG.
* The licensing of the program under the AGPLv3 does not imply a
* trademark license. Therefore any rights, title and interest in
* our trademarks remain entirely with us.
*/
class Shopware_Controllers_Api_Translations extends Shopware_Controllers_Api_Rest
{
/**
* @var \Shopware\Components\Api\Resource\Translation
*/
protected $resource = null;
public function init()
{
$this->resource = \Shopware\Components\Api\Manager::getResource('translation');
}
public function preDispatch()
{
parent::preDispatch();
// We still support the old behavior
$request = $this->Request();
$localeId = $request->getPost('localeId');
if ($localeId !== null) {
$request->setPost('shopId', $localeId);
$request->setPost('localeId', null);
}
}
/**
* Get list of translations
*
* GET /api/translations/
*/
public function indexAction()
{
$limit = (int) $this->Request()->getParam('limit', 1000);
$offset = (int) $this->Request()->getParam('start', 0);
$sort = $this->Request()->getParam('sort', []);
$filter = $this->Request()->getParam('filter', []);
$result = $this->resource->getList($offset, $limit, $filter, $sort);
$this->View()->assign($result);
$this->View()->assign('success', true);
}
/**
* Create new translation
*
* POST /api/translations
*/
public function postAction()
{
$useNumberAsId = (bool) $this->Request()->getParam('useNumberAsId', 0);
$params = $this->Request()->getPost();
if ($useNumberAsId) {
$translation = $this->resource->createByNumber($params);
} else {
$translation = $this->resource->create($params);
}
$location = $this->apiBaseUrl . 'translations/' . $translation->getId();
$data = [
'id' => $translation->getId(),
'location' => $location,
];
$this->View()->assign(['success' => true, 'data' => $data]);
$this->Response()->setHeader('Location', $location);
}
/**
* Update translation
*
* PUT /api/translations/{id}
*/
public function putAction()
{
$useNumberAsId = (bool) $this->Request()->getParam('useNumberAsId', 0);
$id = $this->Request()->getParam('id');
$params = $this->Request()->getPost();
if ($useNumberAsId) {
$translation = $this->resource->updateByNumber($id, $params);
} else {
$translation = $this->resource->update($id, $params);
}
$location = $this->apiBaseUrl . 'translations/' . $translation->getId();
$data = [
'id' => $translation->getId(),
'location' => $location,
];
$this->View()->assign(['success' => true, 'data' => $data]);
}
/**
* Delete translation
*
* DELETE /api/translation/{id}
*/
public function deleteAction()
{
$id = $this->Request()->getParam('id');
$data = $this->Request()->getParams();
$useNumberAsId = (bool) $this->Request()->getParam('useNumberAsId', 0);
if ($useNumberAsId) {
$this->resource->deleteByNumber($id, $data);
} else {
$this->resource->delete($id, $data);
}
$this->View()->assign(['success' => true]);
}
}
| wlwwt/shopware | engine/Shopware/Controllers/Api/Translations.php | PHP | agpl-3.0 | 4,215 |
require File.expand_path(File.dirname(__FILE__) + '/helpers/speed_grader_common')
describe "speed grader submissions" do
it_should_behave_like "in-process server selenium tests"
before (:each) do
stub_kaltura
course_with_teacher_logged_in
outcome_with_rubric
@assignment = @course.assignments.create(:name => 'assignment with rubric', :points_possible => 10)
@association = @rubric.associate_with(@assignment, @course, :purpose => 'grading')
end
context "as a teacher" do
it "should display submission of first student and then second student" do
student_submission
#create initial data for second student
@student_2 = User.create!(:name => 'student 2')
@student_2.register
@student_2.pseudonyms.create!(:unique_id => 'student2@example.com', :password => 'qwerty', :password_confirmation => 'qwerty')
@course.enroll_user(@student_2, "StudentEnrollment", :enrollment_state => 'active')
@submission_2 = @assignment.submit_homework(@student_2, :body => 'second student submission text')
get "/courses/#{@course.id}/gradebook/speed_grader?assignment_id=#{@assignment.id}#%7B%22student_id%22%3A#{@submission.student.id}%7D"
keep_trying_until { f('#speedgrader_iframe') }
#check for assignment title
f('#assignment_url').should include_text(@assignment.title)
#check for assignment text in speed grader iframe
def check_first_student
f('#combo_box_container .ui-selectmenu-item-header').should include_text(@student.name)
in_frame 'speedgrader_iframe' do
f('#main').should include_text(@submission.body)
end
end
def check_second_student
f('#combo_box_container .ui-selectmenu-item-header').should include_text(@student_2.name)
in_frame 'speedgrader_iframe' do
f('#main').should include_text(@submission_2.body)
end
end
if f('#combo_box_container .ui-selectmenu-item-header').text.include?(@student_2.name)
check_second_student
f('#gradebook_header .next').click
wait_for_ajax_requests
check_first_student
else
check_first_student
f('#gradebook_header .next').click
wait_for_ajax_requests
check_second_student
end
end
it "should not error if there are no submissions" do
student_in_course
get "/courses/#{@course.id}/gradebook/speed_grader?assignment_id=#{@assignment.id}"
wait_for_ajax_requests
driver.execute_script("return INST.errorCount").should == 0
end
it "should have a submission_history after a submitting a comment" do
# a student without a submission
@student_2 = User.create!(:name => 'student 2')
@student_2.register
@student_2.pseudonyms.create!(:unique_id => 'student2@example.com', :password => 'qwerty', :password_confirmation => 'qwerty')
@course.enroll_user(@student_2, "StudentEnrollment", :enrollment_state => 'active')
get "/courses/#{@course.id}/gradebook/speed_grader?assignment_id=#{@assignment.id}"
wait_for_ajax_requests
#add comment
f('#add_a_comment > textarea').send_keys('grader comment')
submit_form('#add_a_comment')
keep_trying_until { f('#comments > .comment').should be_displayed }
# the ajax from that add comment form comes back without a submission_history, the js should mimic it.
driver.execute_script('return jsonData.studentsWithSubmissions[0].submission.submission_history.length').should == 1
end
it "should display submission late notice message" do
@assignment.due_at = Time.now - 2.days
@assignment.save!
student_submission
get "/courses/#{@course.id}/gradebook/speed_grader?assignment_id=#{@assignment.id}"
keep_trying_until { f('#speedgrader_iframe') }
f('#submission_late_notice').should be_displayed
end
it "should not display a late message if an assignment has been overridden" do
@assignment.update_attribute(:due_at, Time.now - 2.days)
override = @assignment.assignment_overrides.build
override.due_at = Time.now + 2.days
override.due_at_overridden = true
override.set = @course.course_sections.first
override.save!
student_submission
get "/courses/#{@course.id}/gradebook/speed_grader?assignment_id=#{@assignment.id}"
keep_trying_until { f('#speedgrader_iframe') }
f('#submission_late_notice').should_not be_displayed
end
it "should display no submission message if student does not make a submission" do
@student = user_with_pseudonym(:active_user => true, :username => 'student@example.com', :password => 'qwerty')
@course.enroll_user(@student, "StudentEnrollment", :enrollment_state => 'active')
get "/courses/#{@course.id}/gradebook/speed_grader?assignment_id=#{@assignment.id}"
keep_trying_until do
f('#submissions_container').should
include_text(I18n.t('headers.no_submission', "This student does not have a submission for this assignment"))
fj('#this_student_does_not_have_a_submission').should be_displayed
end
end
it "should handle versions correctly" do
submission1 = student_submission(:username => "student1@example.com", :body => 'first student, first version')
submission2 = student_submission(:username => "student2@example.com", :body => 'second student')
submission3 = student_submission(:username => "student3@example.com", :body => 'third student')
# This is "no submissions" guy
submission3.delete
submission1.submitted_at = 10.minutes.from_now
submission1.body = 'first student, second version'
submission1.with_versioning(:explicit => true) { submission1.save }
get "/courses/#{@course.id}/gradebook/speed_grader?assignment_id=#{@assignment.id}"
wait_for_ajaximations
# The first user should have multiple submissions. We want to make sure we go through the first student
# because the original bug was caused by a user with multiple versions putting data on the page that
# was carried through to other students, ones with only 1 version.
f('#submission_to_view').find_elements(:css, 'option').length.should == 2
in_frame 'speedgrader_iframe' do
f('#content').should include_text('first student, second version')
end
click_option('#submission_to_view', '0', :value)
wait_for_ajaximations
in_frame 'speedgrader_iframe' do
wait_for_ajaximations
f('#content').should include_text('first student, first version')
end
f('#gradebook_header .next').click
wait_for_ajaximations
# The second user just has one, and grading the user shouldn't trigger a page error.
# (In the original bug, it would trigger a change on the select box for choosing submission versions,
# which had another student's data in it, so it would try to load a version that didn't exist.)
f('#submission_to_view').find_elements(:css, 'option').length.should == 1
f('#grade_container').find_element(:css, 'input').send_keys("5\n")
wait_for_ajaximations
in_frame 'speedgrader_iframe' do
f('#content').should include_text('second student')
end
submission2.reload.score.should == 5
f('#gradebook_header .next').click
wait_for_ajaximations
f('#this_student_does_not_have_a_submission').should be_displayed
end
it "should leave the full rubric open when switching submissions" do
student_submission(:username => "student1@example.com")
student_submission(:username => "student2@example.com")
get "/courses/#{@course.id}/gradebook/speed_grader?assignment_id=#{@assignment.id}"
wait_for_ajaximations
keep_trying_until { f('.toggle_full_rubric').should be_displayed }
f('.toggle_full_rubric').click
wait_for_ajaximations
rubric = f('#rubric_full')
rubric.should be_displayed
first_criterion = rubric.find_element(:id, "criterion_#{@rubric.criteria[0][:id]}")
first_criterion.find_element(:css, '.ratings .edge_rating').click
second_criterion = rubric.find_element(:id, "criterion_#{@rubric.criteria[1][:id]}")
second_criterion.find_element(:css, '.ratings .edge_rating').click
rubric.find_element(:css, '.rubric_total').should include_text('8')
f('#rubric_full .save_rubric_button').click
wait_for_ajaximations
f('.toggle_full_rubric').click
wait_for_ajaximations
f("#criterion_#{@rubric.criteria[0][:id]} input.criterion_points").should have_attribute("value", "3")
f("#criterion_#{@rubric.criteria[1][:id]} input.criterion_points").should have_attribute("value", "5")
f('#gradebook_header .next').click
wait_for_ajaximations
f('#rubric_full').should be_displayed
f("#criterion_#{@rubric.criteria[0][:id]} input.criterion_points").should have_attribute("value", "")
f("#criterion_#{@rubric.criteria[1][:id]} input.criterion_points").should have_attribute("value", "")
f('#gradebook_header .prev').click
wait_for_ajaximations
f('#rubric_full').should be_displayed
f("#criterion_#{@rubric.criteria[0][:id]} input.criterion_points").should have_attribute("value", "3")
f("#criterion_#{@rubric.criteria[1][:id]} input.criterion_points").should have_attribute("value", "5")
end
it "should highlight submitted assignments and not non-submitted assignments for students" do
pending('upgrade')
student_submission
create_and_enroll_students(1)
get "/courses/#{@course.id}/gradebook/speed_grader?assignment_id=#{@assignment.id}"
keep_trying_until { f('#speedgrader_iframe').should be_displayed }
#check for assignment title
f('#assignment_url').should include_text(@assignment.title)
ff("#students_selectmenu-menu li")[0].should have_class("not_submitted")
ff("#students_selectmenu-menu li")[1].should have_class("not_graded")
end
it "should display image submission in browser" do
filename, fullpath, data = get_file("graded.png")
create_and_enroll_students(1)
@assignment.submission_types ='online_upload'
@assignment.save!
add_attachment_student_assignment(filename, @students[0], fullpath)
get "/courses/#{@course.id}/gradebook/speed_grader?assignment_id=#{@assignment.id}"
keep_trying_until { f('#speedgrader_iframe').should be_displayed }
in_frame("speedgrader_iframe") do
#validates the image\attachment is inside the iframe as expected
f(".decoded").attribute("src").should include_text("download")
end
end
it "should successfully download attachments" do
filename, fullpath, data = get_file("testfile1.txt")
create_and_enroll_students(1)
@assignment.submission_types ='online_upload'
@assignment.save!
add_attachment_student_assignment(filename, @students[0], fullpath)
get "/courses/#{@course.id}/gradebook/speed_grader?assignment_id=#{@assignment.id}"
keep_trying_until { f('#speedgrader_iframe').should be_displayed }
f(".submission-file-download").click
#this assertion verifies the attachment was opened since its a .txt it just renders in the browser
keep_trying_until { f("body pre").should include_text("63f46f1c") }
end
context "turnitin" do
before(:each) do
@assignment.turnitin_enabled = true
@assignment.save!
end
it "should display a pending icon if submission status is pending" do
student_submission
set_turnitin_asset(@submission, {:status => 'pending'})
get "/courses/#{@course.id}/gradebook/speed_grader?assignment_id=#{@assignment.id}"
wait_for_ajaximations
turnitin_icon = f('#grade_container .submission_pending')
turnitin_icon.should_not be_nil
turnitin_icon.click
wait_for_ajaximations
f('#grade_container .turnitin_info').should_not be_nil
end
it "should display a score if submission has a similarity score" do
student_submission
set_turnitin_asset(@submission, {:similarity_score => 96, :state => 'failure', :status => 'scored'})
get "/courses/#{@course.id}/gradebook/speed_grader?assignment_id=#{@assignment.id}"
wait_for_ajaximations
f('#grade_container .turnitin_similarity_score').should include_text "96%"
end
it "should display an error icon if submission status is error" do
student_submission
set_turnitin_asset(@submission, {:status => 'error'})
get "/courses/#{@course.id}/gradebook/speed_grader?assignment_id=#{@assignment.id}"
wait_for_ajaximations
turnitin_icon = f('#grade_container .submission_error')
turnitin_icon.should_not be_nil
turnitin_icon.click
wait_for_ajaximations
f('#grade_container .turnitin_info').should_not be_nil
f('#grade_container .turnitin_resubmit_button').should_not be_nil
end
it "should show turnitin score for attached files" do
@user = user_with_pseudonym({:active_user => true, :username => 'student@example.com', :password => 'qwerty'})
attachment1 = @user.attachments.new :filename => "homework1.doc"
attachment1.content_type = "application/msword"
attachment1.size = 10093
attachment1.save!
attachment2 = @user.attachments.new :filename => "homework2.doc"
attachment2.content_type = "application/msword"
attachment2.size = 10093
attachment2.save!
student_submission({:user => @user, :submission_type => :online_upload, :attachments => [attachment1, attachment2]})
set_turnitin_asset(attachment1, {:similarity_score => 96, :state => 'failure', :status => 'scored'})
set_turnitin_asset(attachment2, {:status => 'pending'})
get "/courses/#{@course.id}/gradebook/speed_grader?assignment_id=#{@assignment.id}"
wait_for_ajaximations
ff('#submission_files_list .turnitin_similarity_score').map(&:text).join.should match /96%/
f('#submission_files_list .submission_pending').should_not be_nil
end
it "should successfully schedule resubmit when button is clicked" do
student_submission
set_turnitin_asset(@submission, {:status => 'error'})
get "/courses/#{@course.id}/gradebook/speed_grader?assignment_id=#{@assignment.id}"
wait_for_ajaximations
f('#grade_container .submission_error').click
wait_for_ajaximations
expect_new_page_load { f('#grade_container .turnitin_resubmit_button').click}
wait_for_ajaximations
Delayed::Job.find_by_tag('Submission#submit_to_turnitin').should_not be_nil
f('#grade_container .submission_pending').should_not be_nil
end
end
end
end
| wimemx/Canvas | spec/selenium/teacher_speed_grader_submission_spec.rb | Ruby | agpl-3.0 | 14,418 |
// Copyright 2020 Canonical Ltd.
// Licensed under the AGPLv3, see LICENCE file for details.
package provider
import (
"context"
"sync"
"time"
jujuclock "github.com/juju/clock"
"github.com/juju/errors"
apiextensionsv1 "k8s.io/apiextensions-apiserver/pkg/apis/apiextensions/v1"
k8slabels "k8s.io/apimachinery/pkg/labels"
"github.com/juju/juju/caas/kubernetes/provider/utils"
"github.com/juju/juju/core/watcher"
)
func (k *kubernetesClient) deleteClusterScopeResourcesModelTeardown(ctx context.Context, wg *sync.WaitGroup, errChan chan<- error) {
defer wg.Done()
labels := utils.LabelsForModel(k.CurrentModel(), k.IsLegacyLabels())
selector := k8slabels.NewSelector().Add(
labelSetToRequirements(labels)...,
)
// TODO(caas): Fix to only delete cluster wide resources created by this controller.
tasks := []teardownResources{
k.deleteClusterRoleBindingsModelTeardown,
k.deleteClusterRolesModelTeardown,
k.deleteClusterScopeAPIExtensionResourcesModelTeardown,
k.deleteMutatingWebhookConfigurationsModelTeardown,
k.deleteValidatingWebhookConfigurationsModelTeardown,
k.deleteStorageClassesModelTeardown,
}
var subwg sync.WaitGroup
subwg.Add(len(tasks))
defer subwg.Wait()
for _, f := range tasks {
go f(ctx, selector, k.clock, &subwg, errChan)
}
}
type teardownResources func(
context.Context,
k8slabels.Selector,
jujuclock.Clock,
*sync.WaitGroup,
chan<- error,
)
func (k *kubernetesClient) deleteClusterRoleBindingsModelTeardown(
ctx context.Context,
selector k8slabels.Selector,
clk jujuclock.Clock,
wg *sync.WaitGroup,
errChan chan<- error,
) {
ensureResourcesDeletedFunc(ctx, selector, clk, wg, errChan,
k.deleteClusterRoleBindings, func(selector k8slabels.Selector) error {
_, err := k.listClusterRoleBindings(selector)
return err
},
)
}
func (k *kubernetesClient) deleteClusterRolesModelTeardown(
ctx context.Context,
selector k8slabels.Selector,
clk jujuclock.Clock,
wg *sync.WaitGroup,
errChan chan<- error,
) {
ensureResourcesDeletedFunc(ctx, selector, clk, wg, errChan,
k.deleteClusterRoles, func(selector k8slabels.Selector) error {
_, err := k.listClusterRoles(selector)
return err
},
)
}
func (k *kubernetesClient) deleteClusterScopeAPIExtensionResourcesModelTeardown(
ctx context.Context,
selector k8slabels.Selector,
clk jujuclock.Clock,
wg *sync.WaitGroup,
errChan chan<- error,
) {
defer wg.Done()
var subwg sync.WaitGroup
subwg.Add(2)
defer subwg.Wait()
selector = mergeSelectors(selector, lifecycleModelTeardownSelector)
// Delete CRs first then CRDs.
k.deleteClusterScopeCustomResourcesModelTeardown(ctx, selector, clk, &subwg, errChan)
k.deleteCustomResourceDefinitionsModelTeardown(ctx, selector, clk, &subwg, errChan)
}
func (k *kubernetesClient) deleteClusterScopeCustomResourcesModelTeardown(
ctx context.Context,
selector k8slabels.Selector,
clk jujuclock.Clock,
wg *sync.WaitGroup,
errChan chan<- error,
) {
getSelector := func(crd apiextensionsv1.CustomResourceDefinition) k8slabels.Selector {
if !isCRDScopeNamespaced(crd.Spec.Scope) {
// We only delete cluster scope CRs here, namespaced CRs are deleted by namespace destroy process.
return selector
}
return k8slabels.NewSelector()
}
ensureResourcesDeletedFunc(ctx, selector, clk, wg, errChan,
func(_ k8slabels.Selector) error {
return k.deleteCustomResources(getSelector)
},
func(_ k8slabels.Selector) error {
_, err := k.listCustomResources(getSelector)
return err
},
)
}
func (k *kubernetesClient) deleteCustomResourceDefinitionsModelTeardown(
ctx context.Context,
selector k8slabels.Selector,
clk jujuclock.Clock,
wg *sync.WaitGroup,
errChan chan<- error,
) {
ensureResourcesDeletedFunc(ctx, selector, clk, wg, errChan,
k.deleteCustomResourceDefinitions, func(selector k8slabels.Selector) error {
_, err := k.listCustomResourceDefinitions(selector)
return err
},
)
}
func (k *kubernetesClient) deleteMutatingWebhookConfigurationsModelTeardown(
ctx context.Context,
selector k8slabels.Selector,
clk jujuclock.Clock,
wg *sync.WaitGroup,
errChan chan<- error,
) {
ensureResourcesDeletedFunc(ctx, selector, clk, wg, errChan,
k.deleteMutatingWebhookConfigurations, func(selector k8slabels.Selector) error {
_, err := k.listMutatingWebhookConfigurations(selector)
return err
},
)
}
func (k *kubernetesClient) deleteValidatingWebhookConfigurationsModelTeardown(
ctx context.Context,
selector k8slabels.Selector,
clk jujuclock.Clock,
wg *sync.WaitGroup,
errChan chan<- error,
) {
ensureResourcesDeletedFunc(ctx, selector, clk, wg, errChan,
k.deleteValidatingWebhookConfigurations, func(selector k8slabels.Selector) error {
_, err := k.listValidatingWebhookConfigurations(selector)
return err
},
)
}
func (k *kubernetesClient) deleteStorageClassesModelTeardown(
ctx context.Context,
selector k8slabels.Selector,
clk jujuclock.Clock,
wg *sync.WaitGroup,
errChan chan<- error,
) {
ensureResourcesDeletedFunc(ctx, selector, clk, wg, errChan,
k.deleteStorageClasses, func(selector k8slabels.Selector) error {
_, err := k.listStorageClasses(selector)
return err
},
)
}
type deleterChecker func(k8slabels.Selector) error
func ensureResourcesDeletedFunc(
ctx context.Context,
selector k8slabels.Selector,
clk jujuclock.Clock,
wg *sync.WaitGroup,
errChan chan<- error,
deleter, checker deleterChecker,
) {
defer wg.Done()
var err error
defer func() {
if err != nil {
select {
case errChan <- err:
default:
}
}
}()
if err = deleter(selector); err != nil {
if errors.IsNotFound(err) {
err = nil
}
return
}
interval := 1 * time.Second
ticker := clk.NewTimer(interval)
defer ticker.Stop()
for {
select {
case <-ctx.Done():
err = errors.Trace(ctx.Err())
return
case <-ticker.Chan():
err = checker(selector)
if errors.IsNotFound(err) {
// Deleted already.
err = nil
return
}
if err != nil {
err = errors.Trace(err)
return
}
}
// Keep checking.
ticker.Reset(interval)
}
}
func (k *kubernetesClient) deleteNamespaceModelTeardown(ctx context.Context, wg *sync.WaitGroup, errChan chan<- error) {
defer wg.Done()
var err error
defer func() {
if err != nil {
select {
case errChan <- err:
default:
}
}
}()
var w watcher.NotifyWatcher
if w, err = k.WatchNamespace(); err != nil {
err = errors.Annotatef(err, "watching namespace %q", k.namespace)
return
}
defer w.Kill()
if err = k.deleteNamespace(); err != nil {
err = errors.Annotatef(err, "deleting model namespace %q", k.namespace)
return
}
for {
select {
case <-ctx.Done():
err = errors.Annotatef(ctx.Err(), "tearing down namespace %q", k.namespace)
return
case <-w.Changes():
// Ensures the namespace to be deleted - notfound error expected.
_, err = k.GetNamespace(k.namespace)
if errors.IsNotFound(err) {
// Namespace has been deleted.
err = nil
return
}
if err != nil {
err = errors.Trace(err)
return
}
logger.Debugf("namespace %q is still been terminating", k.namespace)
}
}
}
| freyes/juju | caas/kubernetes/provider/teardown.go | GO | agpl-3.0 | 7,094 |
class RemoveEmailFromPerson < ActiveRecord::Migration[5.0]
def change
remove_column :people, :email, :string
end
end
| advocacycommons/advocacycommons | db/migrate/20170504155342_remove_email_from_person.rb | Ruby | agpl-3.0 | 125 |
package com.temenos.interaction.core.command;
/*
* #%L
* interaction-core
* %%
* Copyright (C) 2012 - 2013 Temenos Holdings N.V.
* %%
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
* #L%
*/
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.ws.rs.core.HttpHeaders;
import javax.ws.rs.core.MultivaluedMap;
import javax.ws.rs.core.UriInfo;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.temenos.interaction.core.entity.EntityMetadata;
import com.temenos.interaction.core.entity.Metadata;
import com.temenos.interaction.core.hypermedia.Link;
import com.temenos.interaction.core.hypermedia.ResourceState;
import com.temenos.interaction.core.resource.RESTResource;
import com.temenos.interaction.core.rim.AcceptLanguageHeaderParser;
import com.temenos.interaction.core.rim.HTTPHypermediaRIM;
/**
* This object holds the execution context for processing of the
* interaction commands. {@link InteractionCommand}
* @author aphethean
*/
public class InteractionContext {
private final static Logger logger = LoggerFactory.getLogger(InteractionContext.class);
/**
* The default path element key used if no other is specified when defining the resource.
*/
public final static String DEFAULT_ID_PATH_ELEMENT = "id";
/* Execution context */
private final UriInfo uriInfo;
private final HttpHeaders headers;
private final MultivaluedMap<String, String> inQueryParameters;
private final MultivaluedMap<String, String> pathParameters;
private final ResourceState currentState;
private final Metadata metadata;
private Map<String, String> outQueryParameters = new HashMap<String,String>();
private ResourceState targetState;
private Link linkUsed;
private InteractionException exception;
/* Command context */
private RESTResource resource;
private Map<String, Object> attributes = new HashMap<String, Object>();
private String preconditionIfMatch = null;
private List<String> preferredLanguages = new ArrayList<String>();
private final Map<String, String> responseHeaders = new HashMap<String, String>();
/**
* Construct the context for execution of an interaction.
* @see HTTPHypermediaRIM for pre and post conditions of this InteractionContext
* following the execution of a command.
* @invariant pathParameters not null
* @invariant queryParameters not null
* @invariant currentState not null
* @param uri used to relate responses to initial uri for caching purposes
* @param pathParameters
* @param queryParameters
*/
public InteractionContext(final UriInfo uri, final HttpHeaders headers, final MultivaluedMap<String, String> pathParameters, final MultivaluedMap<String, String> queryParameters, final ResourceState currentState, final Metadata metadata) {
this.uriInfo = uri;
this.headers = headers;
this.pathParameters = pathParameters;
this.inQueryParameters = queryParameters;
this.currentState = currentState;
this.metadata = metadata;
assert(pathParameters != null);
assert(queryParameters != null);
// TODO, should be able to enable this assertion, its just that a lot of tests currently mock this 'new InteractionContext'
// assert(currentState != null);
assert(metadata != null);
}
/**
* Shallow copy constructor with extra parameters to override final attributes.
* Note uriInfo not retained since responses produced will not be valid for original request.
* @param ctx interaction context
* @param headers HttpHeaders
* @param pathParameters new path parameters or null to not override
* @param queryParameters new query parameters or null to not override
* @param currentState new current state or null to not override
*/
public InteractionContext(InteractionContext ctx, final HttpHeaders headers, final MultivaluedMap<String, String> pathParameters, final MultivaluedMap<String, String> queryParameters, final ResourceState currentState) {
this.uriInfo = null;
this.headers = headers != null ? headers : ctx.getHeaders();
this.pathParameters = pathParameters != null ? pathParameters : ctx.pathParameters;
this.inQueryParameters = queryParameters != null ? queryParameters : ctx.inQueryParameters;
this.outQueryParameters.putAll(ctx.outQueryParameters);
this.currentState = currentState != null ? currentState : ctx.currentState;
this.metadata = ctx.metadata;
this.resource = ctx.resource;
this.targetState = ctx.targetState;
this.linkUsed = ctx.linkUsed;
this.exception = ctx.exception;
this.attributes = ctx.attributes;
}
/**
* Uri for the request, used for caching
* @return
*/
public Object getRequestUri() {
return (this.uriInfo==null?null:this.uriInfo.getRequestUri());
}
/**
* <p>The query part of the uri (after the '?')</p>
* URI query parameters as a result of jax-rs {@link UriInfo#getQueryParameters(true)}
*/
public MultivaluedMap<String, String> getQueryParameters() {
return inQueryParameters;
}
/**
* <p>the path part of the uri (up to the '?')</p>
* URI path parameters as a result of jax-rs {@link UriInfo#getPathParameters(true)}
*/
public MultivaluedMap<String, String> getPathParameters() {
return pathParameters;
}
/**
* The Uri of the current request
* @return
*/
public UriInfo getUriInfo() {
return uriInfo;
}
/**
* The HTTP headers of the current request.
* @return
*/
public HttpHeaders getHeaders() {
return headers;
}
/**
* The HTTP headers to be set in the response.
* @return
*/
public Map<String,String> getResponseHeaders() {
return responseHeaders;
}
/**
* The object form of the resource this interaction is dealing with.
* @return
*/
public RESTResource getResource() {
return resource;
}
/**
* In terms of the hypermedia interactions this is the current application state.
* @return
*/
public ResourceState getCurrentState() {
return currentState;
}
/**
* @see InteractionContext#getResource()
* @param resource
*/
public void setResource(RESTResource resource) {
this.resource = resource;
}
public ResourceState getTargetState() {
return targetState;
}
public void setTargetState(ResourceState targetState) {
this.targetState = targetState;
}
public Link getLinkUsed() {
return linkUsed;
}
public void setLinkUsed(Link linkUsed) {
this.linkUsed = linkUsed;
}
public String getId() {
String id = null;
if (pathParameters != null) {
id = pathParameters.getFirst(DEFAULT_ID_PATH_ELEMENT);
if (id == null) {
if (getCurrentState().getPathIdParameter() != null) {
id = pathParameters.getFirst(getCurrentState().getPathIdParameter());
} else {
EntityMetadata entityMetadata = metadata.getEntityMetadata(getCurrentState().getEntityName());
if (entityMetadata != null) {
List<String> idFields = entityMetadata.getIdFields();
// TODO add support for composite ids
assert(idFields.size() == 1) : "ERROR we currently only support simple ids";
if ( idFields.size() == 1 )
id = pathParameters.getFirst(idFields.get(0));
}
}
}
for (String pathParam : pathParameters.keySet()) {
logger.debug("PathParam " + pathParam + ":" + pathParameters.get(pathParam));
}
}
return id;
}
/**
* Store an attribute in this interaction context.
* @param name
* @param value
*/
public void setAttribute(String name, Object value) {
attributes.put(name, value);
}
/**
* Retrieve an attribute from this interaction context.
* @param name
* @return
*/
public Object getAttribute(String name) {
return attributes.get(name);
}
/**
* Returns the metadata from this interaction context
* @return metadata
*/
public Metadata getMetadata() {
return metadata;
}
/**
* Obtain the last exception
* @return exception
*/
public InteractionException getException() {
return exception;
}
/**
* Set an exception
* @param exception exception
*/
public void setException(InteractionException exception) {
this.exception = exception;
}
/**
* Get If-Match precondition
* @return If-Match precondition
*/
public String getPreconditionIfMatch() {
return preconditionIfMatch;
}
/**
* Set the If-Match precondition
* @param preconditionIfMatch If-Match precondition
*/
public void setPreconditionIfMatch(String preconditionIfMatch) {
this.preconditionIfMatch = preconditionIfMatch;
}
/**
* Sets the http header AcceptLanguage value to the context.
* @param acceptLanguageValue
*/
public void setAcceptLanguage(String acceptLanguageValue) {
preferredLanguages = new AcceptLanguageHeaderParser(acceptLanguageValue).getLanguageCodes();
}
/**
* Returns the list of language codes in the order of their preference.
* @return language codes
*/
public List<String> getLanguagePreference(){
return preferredLanguages;
}
/**
* Returns any query parameters, added by the resource's command, that should be dynamically
* added to the response links
*
* @return the outQueryParameters
*/
public Map<String, String> getOutQueryParameters() {
return outQueryParameters;
}
}
| iris-scrum-1/IRIS | interaction-core/src/main/java/com/temenos/interaction/core/command/InteractionContext.java | Java | agpl-3.0 | 9,983 |
/******************************************************************************
* $Id: iomhelper.cpp 10645 2007-01-18 02:22:39Z warmerdam $
*
* Project: Interlis 1/2 Translator
* Purpose: Implementation of ILI1Reader class.
* Author: Pirmin Kalberer, Sourcepole AG
*
******************************************************************************
* Copyright (c) 2004, Pirmin Kalberer, Sourcepole AG
*
* Permission is hereby granted, free of charge, to any person obtaining a
* copy of this software and associated documentation files (the "Software"),
* to deal in the Software without restriction, including without limitation
* the rights to use, copy, modify, merge, publish, distribute, sublicense,
* and/or sell copies of the Software, and to permit persons to whom the
* Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included
* in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
* OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
* THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
* DEALINGS IN THE SOFTWARE.
****************************************************************************/
#include "iomhelper.h"
#include "cpl_port.h"
CPL_CVSID("$Id: iomhelper.cpp 10645 2007-01-18 02:22:39Z warmerdam $");
IOM_OBJECT GetAttrObj(IOM_BASKET model, IOM_OBJECT obj, const char* attrname) {
IOM_OBJECT attrobj = iom_getattrobj(obj, attrname, 0);
if (attrobj == NULL) return NULL;
const char *refoid=iom_getobjectrefoid(attrobj);
if (refoid == NULL) return NULL;
return iom_getobject(model, refoid);
}
int GetAttrObjPos(IOM_OBJECT obj, const char* attrname) {
IOM_OBJECT attrobj = iom_getattrobj(obj, attrname, 0);
if (attrobj == NULL) return -1;
return iom_getobjectreforderpos(attrobj);
}
const char* GetAttrObjName(IOM_BASKET model, IOM_OBJECT obj, const char* attrname) {
return iom_getattrvalue(GetAttrObj(model, obj, attrname), "name");
}
IOM_OBJECT GetTypeObj(IOM_BASKET model, IOM_OBJECT obj) {
IOM_OBJECT typeobj = GetAttrObj(model, obj, "type");
if (typeobj && EQUAL(iom_getobjecttag(typeobj), "iom04.metamodel.TypeAlias")) {
typeobj = GetTypeObj(model, GetAttrObj(model, typeobj, "aliasing"));
}
return typeobj;
}
const char* GetTypeName(IOM_BASKET model, IOM_OBJECT obj) {
IOM_OBJECT typeobj = GetTypeObj(model, obj);
if (typeobj == NULL) return "(null)";
return iom_getobjecttag(typeobj);
}
unsigned int GetCoordDim(IOM_BASKET model, IOM_OBJECT typeobj) {
unsigned int dim = 0;
//find attribute of this type with highest orderpos
IOM_ITERATOR modelelei=iom_iteratorobject(model);
IOM_OBJECT modelele=iom_nextobject(modelelei);
while(modelele){
const char *tag=iom_getobjecttag(modelele);
if (tag && EQUAL(tag,"iom04.metamodel.NumericType")) {
if (GetAttrObj(model, modelele, "coordType") == typeobj) {
unsigned int orderpos = GetAttrObjPos(modelele, "coordType");
if (orderpos > dim) dim = orderpos;
}
}
iom_releaseobject(modelele);
modelele=iom_nextobject(modelelei);
}
iom_releaseiterator(modelelei);
return dim;
}
const char* GetAttrObjName(IOM_BASKET model, const char* tagname) {
const char* result = NULL;
IOM_ITERATOR modelelei = iom_iteratorobject(model);
IOM_OBJECT modelele = iom_nextobject(modelelei);
while (modelele && result == NULL)
{
if(EQUAL(iom_getobjecttag(modelele), tagname)){
// get name of topic
result = iom_getattrvalue(modelele, "name");
}
iom_releaseobject(modelele);
modelele=iom_nextobject(modelelei);
}
iom_releaseiterator(modelelei);
return result;
}
| AsherBond/MondocosmOS | gdal/ogr/ogrsf_frmts/ili/iomhelper.cpp | C++ | agpl-3.0 | 4,073 |
/**
* Copyright (C) 2001-2015 by RapidMiner and the contributors
*
* Complete list of developers available at our web site:
*
* http://rapidminer.com
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see http://www.gnu.org/licenses/.
*/
package com.rapidminer.gui.new_plotter.engine.jfreechart.legend;
import java.awt.Color;
import java.awt.Font;
import java.awt.LinearGradientPaint;
import java.awt.Paint;
import java.awt.Rectangle;
import java.awt.Shape;
import java.awt.geom.Rectangle2D;
import org.jfree.chart.LegendItem;
import org.jfree.chart.LegendItemSource;
import org.jfree.chart.block.Arrangement;
import org.jfree.chart.block.Block;
import org.jfree.chart.block.BlockContainer;
import org.jfree.chart.block.BorderArrangement;
import org.jfree.chart.block.CenterArrangement;
import org.jfree.chart.block.LabelBlock;
import org.jfree.chart.title.LegendGraphic;
import org.jfree.chart.title.LegendItemBlockContainer;
import org.jfree.chart.title.LegendTitle;
import org.jfree.ui.RectangleEdge;
/**
* This class is the GUI container for all legend items.
*
* @author Marius Helf
*
*/
public class SmartLegendTitle extends LegendTitle {
private static final long serialVersionUID = 1L;
public SmartLegendTitle(LegendItemSource source, Arrangement hLayout, Arrangement vLayout) {
super(source, hLayout, vLayout);
}
public SmartLegendTitle(LegendItemSource source) {
super(source);
}
@Override
protected Block createLegendItemBlock(LegendItem item) {
if (item instanceof FlankedShapeLegendItem) {
return createFlankedShapeLegendItem((FlankedShapeLegendItem) item);
} else {
return createDefaultLegendItem(item);
}
}
private Block createDefaultLegendItem(LegendItem item) {
BlockContainer result = null;
Shape shape = item.getShape();
if (shape == null) {
shape = new Rectangle();
}
LegendGraphic lg = new LegendGraphic(shape, item.getFillPaint());
lg.setFillPaintTransformer(item.getFillPaintTransformer());
lg.setShapeFilled(item.isShapeFilled());
lg.setLine(item.getLine());
lg.setLineStroke(item.getLineStroke());
lg.setLinePaint(item.getLinePaint());
lg.setLineVisible(item.isLineVisible());
lg.setShapeVisible(item.isShapeVisible());
lg.setShapeOutlineVisible(item.isShapeOutlineVisible());
lg.setOutlinePaint(item.getOutlinePaint());
lg.setOutlineStroke(item.getOutlineStroke());
lg.setPadding(getLegendItemGraphicPadding());
LegendItemBlockContainer legendItem = new LegendItemBlockContainer(new BorderArrangement(), item.getDataset(),
item.getSeriesKey());
lg.setShapeAnchor(getLegendItemGraphicAnchor());
lg.setShapeLocation(getLegendItemGraphicLocation());
legendItem.add(lg, getLegendItemGraphicEdge());
Font textFont = item.getLabelFont();
if (textFont == null) {
textFont = getItemFont();
}
Paint textPaint = item.getLabelPaint();
if (textPaint == null) {
textPaint = getItemPaint();
}
LabelBlock labelBlock = new LabelBlock(item.getLabel(), textFont, textPaint);
labelBlock.setPadding(getItemLabelPadding());
legendItem.add(labelBlock);
legendItem.setToolTipText(item.getToolTipText());
legendItem.setURLText(item.getURLText());
result = new BlockContainer(new CenterArrangement());
result.add(legendItem);
return result;
}
private Block createFlankedShapeLegendItem(FlankedShapeLegendItem item) {
BlockContainer result = null;
LegendGraphic lg = new CustomLegendGraphic(item.getShape(), item.getFillPaint());
lg.setFillPaintTransformer(item.getFillPaintTransformer());
lg.setShapeFilled(item.isShapeFilled());
lg.setLine(item.getLine());
lg.setLineStroke(item.getLineStroke());
lg.setLinePaint(item.getLinePaint());
lg.setLineVisible(item.isLineVisible());
lg.setShapeVisible(item.isShapeVisible());
lg.setShapeOutlineVisible(item.isShapeOutlineVisible());
lg.setOutlinePaint(item.getOutlinePaint());
lg.setOutlineStroke(item.getOutlineStroke());
lg.setPadding(this.getLegendItemGraphicPadding());
LegendItemBlockContainer legendItem = new LegendItemBlockContainer(new BorderArrangement(), item.getDataset(),
item.getSeriesKey());
Font textFont = item.getLabelFont();
if (textFont == null) {
textFont = getItemFont();
}
Paint textPaint = item.getLabelPaint();
if (textPaint == null) {
textPaint = getItemPaint();
}
ColoredBlockContainer graphicsContainer = new ColoredBlockContainer(new Color(0, 0, 0, 0), new BorderArrangement());
LabelBlock labelBlock;
Font smallerTextFont = textFont.deriveFont(textFont.getSize() * .8f);
Font labelTextFont = textFont;
labelBlock = new LabelBlock(item.getLeftShapeLabel(), smallerTextFont, textPaint);
graphicsContainer.add(labelBlock, RectangleEdge.LEFT);
graphicsContainer.add(lg, null);
labelBlock = new LabelBlock(item.getRightShapeLabel(), smallerTextFont, textPaint);
graphicsContainer.add(labelBlock, RectangleEdge.RIGHT);
legendItem.add(graphicsContainer, getLegendItemGraphicEdge());
labelBlock = new LabelBlock(item.getLabel(), labelTextFont, textPaint);
labelBlock.setPadding(getItemLabelPadding());
legendItem.add(labelBlock);
legendItem.setToolTipText(item.getToolTipText());
legendItem.setURLText(item.getURLText());
result = new BlockContainer(new CenterArrangement());
result.add(legendItem);
return result;
}
public static Paint transformLinearGradient(LinearGradientPaint paint, Shape target) {
Rectangle2D bounds = target.getBounds2D();
float left = (float) bounds.getMinX();
float right = (float) bounds.getMaxX();
LinearGradientPaint newPaint = new LinearGradientPaint(left, 0, right, 0, paint.getFractions(), paint.getColors());
return newPaint;
}
}
| brtonnies/rapidminer-studio | src/main/java/com/rapidminer/gui/new_plotter/engine/jfreechart/legend/SmartLegendTitle.java | Java | agpl-3.0 | 6,443 |
<?php
if(!defined('sugarEntry') || !sugarEntry) die('Not A Valid Entry Point');
/*********************************************************************************
* SugarCRM Community Edition is a customer relationship management program developed by
* SugarCRM, Inc. Copyright (C) 2004-2011 SugarCRM Inc.
*
* This program is free software; you can redistribute it and/or modify it under
* the terms of the GNU Affero General Public License version 3 as published by the
* Free Software Foundation with the addition of the following permission added
* to Section 15 as permitted in Section 7(a): FOR ANY PART OF THE COVERED WORK
* IN WHICH THE COPYRIGHT IS OWNED BY SUGARCRM, SUGARCRM DISCLAIMS THE WARRANTY
* OF NON INFRINGEMENT OF THIRD PARTY RIGHTS.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
* FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more
* details.
*
* You should have received a copy of the GNU Affero General Public License along with
* this program; if not, see http://www.gnu.org/licenses or write to the Free
* Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
* 02110-1301 USA.
*
* You can contact SugarCRM, Inc. headquarters at 10050 North Wolfe Road,
* SW2-130, Cupertino, CA 95014, USA. or at email address contact@sugarcrm.com.
*
* The interactive user interfaces in modified source and object code versions
* of this program must display Appropriate Legal Notices, as required under
* Section 5 of the GNU Affero General Public License version 3.
*
* In accordance with Section 7(b) of the GNU Affero General Public License version 3,
* these Appropriate Legal Notices must retain the display of the "Powered by
* SugarCRM" logo. If the display of the logo is not reasonably feasible for
* technical reasons, the Appropriate Legal Notices must display the words
* "Powered by SugarCRM".
********************************************************************************/
/*********************************************************************************
* Description: Handles getting a list of fields to duplicate check and doing the duplicate checks
* Portions created by SugarCRM are Copyright (C) SugarCRM, Inc.
* All Rights Reserved.
********************************************************************************/
class ImportDuplicateCheck
{
/**
* Private reference to the bean we're dealing with
*/
private $_focus;
/*
* holds current field when a duplicate has been found
*/
public $_dupedFields =array();
/**
* Constructor
*
* @param object $focus bean
*/
public function __construct(
&$focus
)
{
$this->_focus = &$focus;
}
/**
* Returns an array of indices for the current module
*
* @return array
*/
private function _getIndexVardefs()
{
$indexes = $this->_focus->getIndices();
//grab any custom indexes if they exist
if($this->_focus->hasCustomFields()){
$custmIndexes = $this->_focus->db->helper->get_indices($this->_focus->table_name.'_cstm');
$indexes = array_merge($custmIndexes,$indexes);
}
if ( $this->_focus->getFieldDefinition('email1') )
$indexes[] = array(
'name' => 'special_idx_email1',
'type' => 'index',
'fields' => array('email1')
);
if ( $this->_focus->getFieldDefinition('email2') )
$indexes[] = array(
'name' => 'special_idx_email2',
'type' => 'index',
'fields' => array('email2')
);
return $indexes;
}
/**
* Returns an array with an element for each index
*
* @return array
*/
public function getDuplicateCheckIndexes()
{
$super_language_pack = sugarArrayMerge(
return_module_language($GLOBALS['current_language'], $this->_focus->module_dir),
$GLOBALS['app_strings']
);
$index_array = array();
foreach ($this->_getIndexVardefs() as $index){
if ($index['type'] == "index"){
$labelsArray = array();
foreach ($index['fields'] as $field){
if ($field == 'deleted') continue;
$fieldDef = $this->_focus->getFieldDefinition($field);
if ( isset($fieldDef['vname']) && isset($super_language_pack[$fieldDef['vname']]) )
$labelsArray[$fieldDef['name']] = $super_language_pack[$fieldDef['vname']];
else
$labelsArray[$fieldDef['name']] = $fieldDef['name'];
}
$index_array[$index['name']] = str_replace(":", "",implode(", ",$labelsArray));
}
}
return $index_array;
}
/**
* Checks to see if the given bean is a duplicate based off the given fields
*
* @param array $indexlist
* @return bool true if this bean is a duplicate or false if it isn't
*/
public function isADuplicateRecordByFields($fieldList)
{
foreach($fieldList as $field)
{
if ( $field == 'email1' || $field == 'email2' )
{
$emailAddress = new SugarEmailAddress();
$email = $field;
if ( $emailAddress->getCountEmailAddressByBean($this->_focus->$email,$this->_focus,($field == 'email1')) > 0 )
return true;
}
else
{
$index_fields = array('deleted' => '0');
if( is_array($field) )
{
foreach($field as $tmpField)
{
if ($tmpField == 'deleted')
continue;
if (strlen($this->_focus->$tmpField) > 0)
$index_fields[$tmpField] = $this->_focus->$tmpField;
}
}
elseif($field != 'deleted' && strlen($this->_focus->$field) > 0)
$index_fields[$field] = $this->_focus->$field;
if ( count($index_fields) <= 1 )
continue;
$newfocus = loadBean($this->_focus->module_dir);
$result = $newfocus->retrieve_by_string_fields($index_fields,true);
if ( !is_null($result) )
return true;
}
}
return false;
}
/**
* Checks to see if the given bean is a duplicate based off the given indexes
*
* @param array $indexlist
* @return bool true if this bean is a duplicate or false if it isn't
*/
public function isADuplicateRecord( $indexlist )
{
//lets strip the indexes of the name field in the value and leave only the index name
$origIndexList = $indexlist;
$indexlist=array();
$fieldlist=array();
$customIndexlist=array();
foreach($origIndexList as $iv){
if(empty($iv)) continue;
$field_index_array = explode('::',$iv);
if($field_index_array[0] == 'customfield'){
//this is a custom field, so place in custom array
$customIndexlist[] = $field_index_array[1];
}else{
//this is not a custom field, so place in index list
$indexlist[] = $field_index_array[0];
$fieldlist[] = $field_index_array[1];
}
}
//if full_name is set, then manually search on the first and last name fields before iterating through rest of fields
//this is a special handling of the name fields on people objects, the rest of the fields are checked individually
if(in_array('full_name',$indexlist)){
$newfocus = loadBean($this->_focus->module_dir);
$result = $newfocus->retrieve_by_string_fields(array('deleted' =>'0', 'first_name'=>$this->_focus->first_name, 'last_name'=>$this->_focus->last_name),true);
if ( !is_null($result) ){
//set dupe field to full_name and name fields
$this->_dupedFields[] = 'full_name';
$this->_dupedFields[] = 'first_name';
$this->_dupedFields[] = 'last_name';
}
}
// loop through var def indexes and compare with selected indexes
foreach ($this->_getIndexVardefs() as $index){
// if we get an index not in the indexlist, loop
if ( !in_array($index['name'],$indexlist) )
continue;
// This handles the special case of duplicate email checking
if ( $index['name'] == 'special_idx_email1' || $index['name'] == 'special_idx_email2' ) {
$emailAddress = new SugarEmailAddress();
$email = $index['fields'][0];
if ( $emailAddress->getCountEmailAddressByBean(
$this->_focus->$email,
$this->_focus,
($index['name'] == 'special_idx_email1')
) > 0 ){ foreach($index['fields'] as $field){
if($field !='deleted')
$this->_dupedFields[] = $field;
}
}
}
// Adds a hook so you can define a method in the bean to handle dupe checking
elseif ( isset($index['dupeCheckFunction']) ) {
$functionName = substr_replace($index['dupeCheckFunction'],'',0,9);
if ( method_exists($this->_focus,$functionName) )
return $this->_focus->$functionName($index);
}
else {
$index_fields = array('deleted' => '0');
//search only for the field we have selected
foreach($index['fields'] as $field){
if ($field == 'deleted' || !in_array($field,$fieldlist))
continue;
if (!in_array($field,$index_fields))
if (isset($this->_focus->$field) && strlen($this->_focus->$field) > 0)
$index_fields[$field] = $this->_focus->$field;
}
// if there are no valid fields in the index field list, loop
if ( count($index_fields) <= 1 )
continue;
$newfocus = loadBean($this->_focus->module_dir);
$result = $newfocus->retrieve_by_string_fields($index_fields,true);
if ( !is_null($result) ){
//remove deleted as a duped field
unset($index_fields['deleted']);
//create string based on array of dupe fields
$this->_dupedFields = array_merge(array_keys($index_fields),$this->_dupedFields);
}
}
}
//return true if any dupes were found
if(!empty($this->_dupedFields)){
return true;
}
return false;
}
public function getDuplicateCheckIndexedFiles()
{
require_once('include/export_utils.php');
$import_fields = $this->_focus->get_importable_fields();
$importable_keys = array_keys($import_fields);//
$index_array = array();
$fields_used = array();
$mstr_exclude_array = array('all'=>array('team_set_id','id','deleted'),'contacts'=>array('email2'), array('leads'=>'reports_to_id'), array('prospects'=>'tracker_key'));
//create exclude array from subset of applicable mstr_exclude_array elements
$exclude_array = isset($mstr_exclude_array[strtolower($this->_focus->module_dir)])?array_merge($mstr_exclude_array[strtolower($this->_focus->module_dir)], $mstr_exclude_array['all']) : $mstr_exclude_array['all'];
//process all fields belonging to indexes
foreach ($this->_getIndexVardefs() as $index){
if ($index['type'] == "index"){
foreach ($index['fields'] as $field){
$fieldName='';
//skip this field if it is the deleted field, not in the importable keys array, or a field in the exclude array
if (!in_array($field, $importable_keys) || in_array($field, $exclude_array)) continue;
$fieldDef = $this->_focus->getFieldDefinition($field);
//skip if this field is already defined (from another index)
if (in_array($fieldDef['name'],$fields_used)) continue;
//get the proper export label
$fieldName = translateForExport($fieldDef['name'],$this->_focus);
$index_array[$index['name'].'::'.$fieldDef['name']] = $fieldName;
$fields_used[] = $fieldDef['name'];
}
}
}
//special handling for beans with first_name and last_name
if(in_array('first_name', $fields_used) && in_array('last_name', $fields_used)){
//since both full name and last name fields have been mapped, add full name index
$index_array['full_name::full_name'] = translateForExport('full_name',$this->_focus);
$fields_used[] = 'full_name';
}
asort($index_array);
return $index_array;
}
}
?> | shahrooz33ce/sugarcrm | modules/Import/ImportDuplicateCheck.php | PHP | agpl-3.0 | 13,601 |
import datetime
import sqlalchemy.orm.exc
from nylas.logging import get_logger
log = get_logger()
from inbox.auth.oauth import OAuthAuthHandler
from inbox.basicauth import OAuthError
from inbox.models import Namespace
from inbox.config import config
from inbox.models.backends.outlook import OutlookAccount
from inbox.models.backends.oauth import token_manager
from inbox.util.url import url_concat
PROVIDER = '_outlook'
AUTH_HANDLER_CLS = '_OutlookAuthHandler'
# Outlook OAuth app credentials
OAUTH_CLIENT_ID = config.get_required('MS_LIVE_OAUTH_CLIENT_ID')
OAUTH_CLIENT_SECRET = config.get_required('MS_LIVE_OAUTH_CLIENT_SECRET')
OAUTH_REDIRECT_URI = config.get_required('MS_LIVE_OAUTH_REDIRECT_URI')
OAUTH_AUTHENTICATE_URL = 'https://login.live.com/oauth20_authorize.srf'
OAUTH_ACCESS_TOKEN_URL = 'https://login.live.com/oauth20_token.srf'
OAUTH_USER_INFO_URL = 'https://apis.live.net/v5.0/me'
OAUTH_BASE_URL = 'https://apis.live.net/v5.0/'
OAUTH_SCOPE = ' '.join([
'wl.basic', # Read access for basic profile info + contacts
'wl.offline_access', # ability to read / update user's info at any time
'wl.emails', # Read access to user's email addresses
'wl.imap']) # R/W access to user's email using IMAP / SMTP
class _OutlookAuthHandler(OAuthAuthHandler):
OAUTH_CLIENT_ID = OAUTH_CLIENT_ID
OAUTH_CLIENT_SECRET = OAUTH_CLIENT_SECRET
OAUTH_REDIRECT_URI = OAUTH_REDIRECT_URI
OAUTH_AUTHENTICATE_URL = OAUTH_AUTHENTICATE_URL
OAUTH_ACCESS_TOKEN_URL = OAUTH_ACCESS_TOKEN_URL
OAUTH_USER_INFO_URL = OAUTH_USER_INFO_URL
OAUTH_BASE_URL = OAUTH_BASE_URL
OAUTH_SCOPE = OAUTH_SCOPE
def create_account(self, db_session, email_address, response):
email_address = response.get('emails')['account']
try:
account = db_session.query(OutlookAccount).filter_by(
email_address=email_address).one()
except sqlalchemy.orm.exc.NoResultFound:
namespace = Namespace()
account = OutlookAccount(namespace=namespace)
account.refresh_token = response['refresh_token']
account.date = datetime.datetime.utcnow()
tok = response.get('access_token')
expires_in = response.get('expires_in')
token_manager.cache_token(account, tok, expires_in)
account.scope = response.get('scope')
account.email_address = email_address
account.o_id_token = response.get('user_id')
account.o_id = response.get('id')
account.name = response.get('name')
account.gender = response.get('gender')
account.link = response.get('link')
account.locale = response.get('locale')
# Unlike Gmail, Outlook doesn't return the client_id and secret here
account.client_id = OAUTH_CLIENT_ID
account.client_secret = OAUTH_CLIENT_SECRET
# Ensure account has sync enabled.
account.enable_sync()
return account
def validate_token(self, access_token):
return self._get_user_info(access_token)
def interactive_auth(self, email_address=None):
url_args = {'redirect_uri': self.OAUTH_REDIRECT_URI,
'client_id': self.OAUTH_CLIENT_ID,
'response_type': 'code',
'scope': self.OAUTH_SCOPE,
'access_type': 'offline'}
url = url_concat(self.OAUTH_AUTHENTICATE_URL, url_args)
print ('Please visit the following url to allow access to this '
'application. The response will provide '
'code=[AUTHORIZATION_CODE]&lc=XXXX in the location. Paste the'
' AUTHORIZATION_CODE here:')
print '\n{}'.format(url)
while True:
auth_code = raw_input('Enter authorization code: ').strip()
try:
auth_response = self._get_authenticated_user(auth_code)
return auth_response
except OAuthError:
print '\nInvalid authorization code, try again...\n'
auth_code = None
| Eagles2F/sync-engine | inbox/auth/_outlook.py | Python | agpl-3.0 | 4,066 |
/**
MIT License http://www.opensource.org/licenses/mit-license.php
Author Igor Vladyka <igor.vladyka@gmail.com> (https://github.com/Igor-Vladyka/leaflet.browser.print)
**/
L.Control.BrowserPrint.Utils = {
_ignoreArray: [],
_cloneFactoryArray: [],
_cloneRendererArray: [],
_knownRenderers: {},
cloneOptions: function(options) {
var utils = this;
var retOptions = {};
for (var name in options) {
var item = options[name];
if (item && item.clone) {
retOptions[name] = item.clone();
} else if (item && item.onAdd) {
retOptions[name] = utils.cloneLayer(item);
} else {
retOptions[name] = item;
}
}
return retOptions;
},
cloneBasicOptionsWithoutLayers: function(options) {
var retOptions = {};
var optionNames = Object.getOwnPropertyNames(options);
if (optionNames.length) {
for (var i = 0; i < optionNames.length; i++) {
var optName = optionNames[i];
if (optName && optName != "layers") {
retOptions[optName] = options[optName];
}
}
return this.cloneOptions(retOptions);
}
return retOptions;
},
cloneInnerLayers: function (layer) {
var utils = this;
var layers = [];
layer.eachLayer(function (inner) {
var l = utils.cloneLayer(inner);
if (l) {
layers.push(l);
}
});
return layers;
},
initialize: function () {
this._knownRenderers = {};
// Renderers
this.registerRenderer(L.SVG, 'L.SVG');
this.registerRenderer(L.Canvas, 'L.Canvas');
this.registerLayer(L.TileLayer.WMS, 'L.TileLayer.WMS', function(layer, utils) { return L.tileLayer.wms(layer._url, utils.cloneOptions(layer.options)); });
this.registerLayer(L.TileLayer, 'L.TileLayer', function(layer, utils) { return L.tileLayer(layer._url, utils.cloneOptions(layer.options)); });
this.registerLayer(L.GridLayer, 'L.GridLayer', function(layer, utils) { return L.gridLayer(utils.cloneOptions(layer.options)); });
this.registerLayer(L.ImageOverlay, 'L.ImageOverlay', function(layer, utils) { return L.imageOverlay(layer._url, layer._bounds, utils.cloneOptions(layer.options)); });
this.registerLayer(L.Marker, 'L.Marker', function(layer, utils) { return L.marker(layer.getLatLng(), utils.cloneOptions(layer.options)); });
this.registerLayer(L.Popup, 'L.Popup', function(layer, utils) { return L.popup(utils.cloneOptions(layer.options)).setLatLng(layer.getLatLng()).setContent(layer.getContent()); });
this.registerLayer(L.Circle, 'L.Circle', function(layer, utils) { return L.circle(layer.getLatLng(), layer.getRadius(), utils.cloneOptions(layer.options)); });
this.registerLayer(L.CircleMarker, 'L.CircleMarker', function(layer, utils) { return L.circleMarker(layer.getLatLng(), utils.cloneOptions(layer.options)); });
this.registerLayer(L.Rectangle, 'L.Rectangle', function(layer, utils) { return L.rectangle(layer.getBounds(), utils.cloneOptions(layer.options)); });
this.registerLayer(L.Polygon, 'L.Polygon', function(layer, utils) { return L.polygon(layer.getLatLngs(), utils.cloneOptions(layer.options)); });
// MultiPolyline is removed in leaflet 1.0.0
this.registerLayer(L.MultiPolyline, 'L.MultiPolyline', function(layer, utils) { return L.polyline(layer.getLatLngs(), utils.cloneOptions(layer.options)); });
// MultiPolygon is removed in leaflet 1.0.0
this.registerLayer(L.MultiPolygon, 'L.MultiPolygon', function(layer, utils) { return L.multiPolygon(layer.getLatLngs(), utils.cloneOptions(layer.options)); });
this.registerLayer(L.Polyline, 'L.Polyline', function(layer, utils) { return L.polyline(layer.getLatLngs(), utils.cloneOptions(layer.options)); });
this.registerLayer(L.GeoJSON, 'L.GeoJSON', function(layer, utils) { return L.geoJson(layer.toGeoJSON(), utils.cloneOptions(layer.options)); });
this.registerIgnoreLayer(L.FeatureGroup, 'L.FeatureGroup');
this.registerIgnoreLayer(L.LayerGroup, 'L.LayerGroup');
// There is no point to clone tooltips here; L.tooltip(options);
this.registerLayer(L.Tooltip, 'L.Tooltip', function(){ return null; });
},
_register: function(array, type, identifier, builderFunction) {
if (type &&
!array.filter(function(l){ return l.identifier === identifier; }).length) {
array.push({
type: type,
identifier: identifier,
builder: builderFunction || function (layer) { return new type(layer.options); }
});
}
},
registerLayer: function(type, identifier, builderFunction) {
this._register(this._cloneFactoryArray, type, identifier, builderFunction);
},
registerRenderer: function(type, identifier, builderFunction) {
this._register(this._cloneRendererArray, type, identifier, builderFunction);
},
registerIgnoreLayer: function(type, identifier) {
this._register(this._ignoreArray, type, identifier);
},
cloneLayer: function(layer) {
if (!layer) return null;
// First we check if this layer is actual renderer
var renderer = this.__getRenderer(layer);
if (renderer) {
return renderer;
}
var factoryObject;
if (layer._group) { // Exceptional check for L.MarkerClusterGroup
factoryObject = this.__getFactoryObject(layer._group, true);
} else {
factoryObject = this.__getFactoryObject(layer);
}
// We clone and recreate layer if it's simple overlay
if (factoryObject) {
factoryObject = factoryObject.builder(layer, this);
}
return factoryObject;
},
getType: function(layer) {
if (!layer) return null;
var factoryObject = this.__getFactoryObject(layer);
if (factoryObject) {
factoryObject = factoryObject.identifier;
}
return factoryObject;
},
__getRenderer: function(oldRenderer) {
var renderer = this._knownRenderers[oldRenderer._leaflet_id];
if (!renderer) {
for (var i = 0; i < this._cloneRendererArray.length; i++) {
var factoryObject = this._cloneRendererArray[i];
if (oldRenderer instanceof factoryObject.type) {
this._knownRenderers[oldRenderer._leaflet_id] = factoryObject.builder(oldRenderer.options);
break;
}
}
renderer = this._knownRenderers[oldRenderer._leaflet_id];
}
return renderer;
},
__getFactoryObject: function (layer, skipIgnore) {
if (!skipIgnore) {
for (var i = 0; i < this._ignoreArray.length; i++) {
var ignoreObject = this._ignoreArray[i];
if (ignoreObject.type && layer instanceof ignoreObject.type) {
return null;
}
}
}
for (var i = 0; i < this._cloneFactoryArray.length; i++) {
var factoryObject = this._cloneFactoryArray[i];
if (factoryObject.type && layer instanceof factoryObject.type) {
return factoryObject;
}
}
for (var i = 0; i < this._cloneRendererArray.length; i++) {
var factoryObject = this._cloneRendererArray[i];
if (factoryObject.type && layer instanceof factoryObject.type) {
return null;
}
}
this.__unknownLayer__();
return null;
},
__unknownLayer__: function(){
console.warn('Unknown layer, cannot clone this layer. Leaflet version: ' + L.version);
console.info('For additional information please refer to documentation on: https://github.com/Igor-Vladyka/leaflet.browser.print.');
console.info('-------------------------------------------------------------------------------------------------------------------');
}
};
| Irstea/collec | display/node_modules/leaflet.browser.print/src/leaflet.browser.print.utils.js | JavaScript | agpl-3.0 | 7,246 |
# frozen_string_literal: true
require 'rails_helper'
RSpec.describe 'Crops', type: :request do
subject { JSON.parse response.body }
let(:headers) { { 'Accept' => 'application/vnd.api+json' } }
let!(:crop) { FactoryBot.create :crop }
let(:crop_encoded_as_json_api) do
{ "id" => crop.id.to_s,
"type" => "crops",
"links" => { "self" => resource_url },
"attributes" => attributes,
"relationships" => {
"plantings" => plantings_as_json_api,
"parent" => parent_as_json_api,
"harvests" => harvests_as_json_api,
"seeds" => seeds_as_json_api,
"photos" => photos_as_json_api
} }
end
let(:resource_url) { "http://www.example.com/api/v1/crops/#{crop.id}" }
let(:seeds_as_json_api) do
{ "links" =>
{ "self" => "#{resource_url}/relationships/seeds",
"related" => "#{resource_url}/seeds" } }
end
let(:harvests_as_json_api) do
{ "links" =>
{ "self" => "#{resource_url}/relationships/harvests",
"related" => "#{resource_url}/harvests" } }
end
let(:parent_as_json_api) do
{ "links" =>
{ "self" => "#{resource_url}/relationships/parent",
"related" => "#{resource_url}/parent" } }
end
let(:plantings_as_json_api) do
{ "links" =>
{ "self" =>
"#{resource_url}/relationships/plantings",
"related" => "#{resource_url}/plantings" } }
end
let(:photos_as_json_api) do
{ "links" =>
{ "self" => "#{resource_url}/relationships/photos",
"related" => "#{resource_url}/photos" } }
end
let(:attributes) do
{
"name" => crop.name,
"en-wikipedia-url" => crop.en_wikipedia_url,
"perennial" => false,
"median-lifespan" => nil,
"median-days-to-first-harvest" => nil,
"median-days-to-last-harvest" => nil
}
end
describe '#index' do
before { get '/api/v1/crops', params: {}, headers: headers }
it { expect(subject['data']).to include(crop_encoded_as_json_api) }
end
describe '#show' do
before { get "/api/v1/crops/#{crop.id}", params: {}, headers: headers }
it { expect(subject['data']['attributes']).to eq(attributes) }
it { expect(subject['data']['relationships']).to include("plantings" => plantings_as_json_api) }
it { expect(subject['data']['relationships']).to include("harvests" => harvests_as_json_api) }
it { expect(subject['data']['relationships']).to include("seeds" => seeds_as_json_api) }
it { expect(subject['data']['relationships']).to include("photos" => photos_as_json_api) }
it { expect(subject['data']['relationships']).to include("parent" => parent_as_json_api) }
it { expect(subject['data']).to eq(crop_encoded_as_json_api) }
end
it '#create' do
expect do
post '/api/v1/crops', params: { 'crop' => { 'name' => 'can i make this' } }, headers: headers
end.to raise_error ActionController::RoutingError
end
it '#update' do
expect do
post "/api/v1/crops/#{crop.id}", params: { 'crop' => { 'name' => 'can i modify this' } }, headers: headers
end.to raise_error ActionController::RoutingError
end
it '#delete' do
expect do
delete "/api/v1/crops/#{crop.id}", params: {}, headers: headers
end.to raise_error ActionController::RoutingError
end
end
| Br3nda/growstuff | spec/requests/api/v1/crop_request_spec.rb | Ruby | agpl-3.0 | 3,570 |
<?php
/* vim: set expandtab tabstop=4 shiftwidth=4 softtabstop=4: */
/**
* This file is part of Onlogistics, a web based ERP and supply chain
* management application.
*
* Copyright (C) 2003-2008 ATEOR
*
* This program is free software: you can redistribute it and/or modify it
* under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or (at your
* option) any later version.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public
* License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
* PHP version 5.1.0+
*
* @package Onlogistics
* @author ATEOR dev team <dev@ateor.com>
* @copyright 2003-2008 ATEOR <contact@ateor.com>
* @license http://www.fsf.org/licensing/licenses/agpl-3.0.html GNU AGPL
* @version SVN: $Id$
* @link http://www.onlogistics.org
* @link http://onlogistics.googlecode.com
* @since File available since release 0.1.0
* @filesource
*/
class GridColumnOrderWOOpeTaskList extends AbstractGridColumn {
/**
* Constructor
*
* @access protected
*/
function GridColumnOrderWOOpeTaskList($title = '', $params = array()) {
parent::__construct($title, $params);
}
function Render($object) {
require_once('Objects/WorkOrder.php');
$WorkOrderState = Tools::getValueFromMacro($object, '%OwnerWorkerOrder.State%');
if ($WorkOrderState == WorkOrder::WORK_ORDER_STATE_FULL) { // si le WO associe est cloture
if (0 == $object->GetOrderInWorkOrder() || is_Null($object->GetOrderInWorkOrder())) {
$output = _('N/A');
} else {
$output = $object->GetOrderInWorkOrder();
}
} else { // si pas cloture, on propose de le modifier: input text
if (0 == $object->GetOrderInWorkOrder() || is_Null($object->GetOrderInWorkOrder())) {
$output = '<input type="text" name="orderInWO[]" size="3" value="">';
} else {
$output = '<input type="text" name="orderInWO[]" size="3" value="' . $object->GetOrderInWorkOrder() . '">';
}
$output .= '<input type="hidden" name="OpeId[]" value="' . $object->GetId() . '">';
}
return $output;
}
}
?>
| danilo-cesar/onlogistics | lib/CustomGrid/Columns/GridColumnOrderWOOpeTaskList.php | PHP | agpl-3.0 | 2,613 |
<?
// The source code packaged with this file is Free Software, Copyright (C) 2005 by
// Ricardo Galli <gallir at uib dot es>.
// It's licensed under the AFFERO GENERAL PUBLIC LICENSE unless stated otherwise.
// You can get copies of the licenses here:
// http://www.affero.org/oagpl.html
// AFFERO GENERAL PUBLIC LICENSE is also included in the file called "COPYING".
include('config.php');
include(mnminclude.'html1.php');
$globals['ads'] = true;
$sql = "SELECT link_id FROM links WHERE link_date > date_sub(now(), interval 48 hour) and link_negatives > 0 and link_karma < 0 ORDER BY link_karma ASC LIMIT 50 ";
do_header(_('las peores :-)'));
/*** SIDEBAR ****/
echo '<div id="sidebar">';
do_banner_right();
do_best_stories();
do_best_comments();
do_vertical_tags('published');
echo '</div>' . "\n";
/*** END SIDEBAR ***/
echo '<div id="newswrap">'."\n";
echo '<div class="topheading"><h2>'._('¿noticias?').' :-) </h2></div>';
$link = new Link;
$links = $db->get_results($sql);
if ($links) {
foreach($links as $dblink) {
$link->id=$dblink->link_id;
$link->read();
$link->print_summary('short');
}
}
echo '</div>';
do_footer();
?>
| angelaparicio/contenidoextra.es | topshames.php | PHP | agpl-3.0 | 1,156 |
/****************************************************************/
/* DO NOT MODIFY THIS HEADER */
/* MOOSE - Multiphysics Object Oriented Simulation Environment */
/* */
/* (c) 2010 Battelle Energy Alliance, LLC */
/* ALL RIGHTS RESERVED */
/* */
/* Prepared by Battelle Energy Alliance, LLC */
/* Under Contract No. DE-AC07-05ID14517 */
/* With the U. S. Department of Energy */
/* */
/* See COPYRIGHT for full restrictions */
/****************************************************************/
#include "ElementalVariableValue.h"
// MOOSE includes
#include "MooseMesh.h"
#include "MooseVariable.h"
#include "SubProblem.h"
template <>
InputParameters
validParams<ElementalVariableValue>()
{
InputParameters params = validParams<GeneralPostprocessor>();
params.addRequiredParam<VariableName>("variable", "The variable to be monitored");
params.addRequiredParam<unsigned int>("elementid", "The ID of the element where we monitor");
params.addClassDescription("Outputs an elemental variable value at a particular location");
return params;
}
ElementalVariableValue::ElementalVariableValue(const InputParameters & parameters)
: GeneralPostprocessor(parameters),
_mesh(_subproblem.mesh()),
_var_name(parameters.get<VariableName>("variable")),
_element(_mesh.getMesh().query_elem_ptr(parameters.get<unsigned int>("elementid")))
{
// This class may be too dangerous to use if renumbering is enabled,
// as the nodeid parameter obviously depends on a particular
// numbering.
if (_mesh.getMesh().allow_renumbering())
mooseError("ElementalVariableValue should only be used when node renumbering is disabled.");
}
Real
ElementalVariableValue::getValue()
{
Real value = 0;
if (_element && (_element->processor_id() == processor_id()))
{
_subproblem.prepare(_element, _tid);
_subproblem.reinitElem(_element, _tid);
MooseVariable & var = _subproblem.getVariable(_tid, _var_name);
const VariableValue & u = var.sln();
unsigned int n = u.size();
for (unsigned int i = 0; i < n; i++)
value += u[i];
value /= n;
}
gatherSum(value);
return value;
}
| Chuban/moose | framework/src/postprocessors/ElementalVariableValue.C | C++ | lgpl-2.1 | 2,498 |
/****************************************************************/
/* MOOSE - Multiphysics Object Oriented Simulation Environment */
/* */
/* All contents are licensed under LGPL V2.1 */
/* See LICENSE for full restrictions */
/****************************************************************/
#include "HyperElasticPhaseFieldIsoDamage.h"
template<>
InputParameters validParams<HyperElasticPhaseFieldIsoDamage>()
{
InputParameters params = validParams<FiniteStrainHyperElasticViscoPlastic>();
params.addParam<bool>("numerical_stiffness", false, "Flag for numerical stiffness");
params.addParam<Real>("damage_stiffness", 1e-8, "Avoid zero after complete damage");
params.addParam<Real>("zero_tol", 1e-12, "Tolerance for numerical zero");
params.addParam<Real>("zero_perturb", 1e-8, "Perturbation value when strain value less than numerical zero");
params.addParam<Real>("perturbation_scale_factor", 1e-5, "Perturbation scale factor");
params.addRequiredCoupledVar("c", "Damage variable");
params.addClassDescription("Computes damaged stress and energy in the intermediate configuration assuming isotropy");
return params;
}
HyperElasticPhaseFieldIsoDamage::HyperElasticPhaseFieldIsoDamage(const InputParameters & parameters) :
FiniteStrainHyperElasticViscoPlastic(parameters),
_num_stiffness(getParam<bool>("numerical_stiffness")),
_kdamage(getParam<Real>("damage_stiffness")),
_zero_tol(getParam<Real>("zero_tol")),
_zero_pert(getParam<Real>("zero_perturb")),
_pert_val(getParam<Real>("perturbation_scale_factor")),
_c(coupledValue("c")),
_save_state(false),
_G0(declareProperty<Real>(_base_name + "G0")),
_dG0_dstrain(declareProperty<RankTwoTensor>(_base_name + "dG0_dstrain")),
_dstress_dc(declarePropertyDerivative<RankTwoTensor>(_base_name + "stress", getVar("c", 0)->name())),
_etens(LIBMESH_DIM)
{
}
void
HyperElasticPhaseFieldIsoDamage::computePK2StressAndDerivative()
{
computeElasticStrain();
_save_state = true;
computeDamageStress();
_pk2[_qp] = _pk2_tmp;
_save_state = false;
if (_num_stiffness)
computeNumStiffness();
if (_num_stiffness)
_dpk2_dce = _dpk2_dee * _dee_dce;
_dce_dfe.zero();
for (unsigned int i = 0; i < LIBMESH_DIM; ++i)
for (unsigned int j = 0; j < LIBMESH_DIM; ++j)
for (unsigned int k = 0; k < LIBMESH_DIM; ++k)
{
_dce_dfe(i, j, k, i) = _dce_dfe(i, j, k, i) + _fe(k, j);
_dce_dfe(i, j, k, j) = _dce_dfe(i, j, k, j) + _fe(k, i);
}
_dpk2_dfe = _dpk2_dce * _dce_dfe;
}
void
HyperElasticPhaseFieldIsoDamage::computeDamageStress()
{
Real lambda = _elasticity_tensor[_qp](0, 0, 1, 1);
Real mu = _elasticity_tensor[_qp](0, 1, 0, 1);
Real c = _c[_qp];
Real xfac = std::pow(1.0-c, 2.0) + _kdamage;
std::vector<Real> w;
RankTwoTensor evec;
_ee.symmetricEigenvaluesEigenvectors(w, evec);
for (unsigned int i = 0; i < LIBMESH_DIM; ++i)
_etens[i].vectorOuterProduct(evec.column(i), evec.column(i));
Real etr = 0.0;
for (unsigned int i = 0; i < LIBMESH_DIM; ++i)
etr += w[i];
Real etrpos=(std::abs(etr)+etr)/2.0;
Real etrneg=(std::abs(etr)-etr)/2.0;
RankTwoTensor pk2pos, pk2neg;
for (unsigned int i = 0; i < LIBMESH_DIM; ++i)
{
pk2pos += _etens[i] * (lambda * etrpos + 2.0 * mu * (std::abs(w[i]) + w[i])/2.0);
pk2neg += _etens[i] * (lambda * etrneg + 2.0 * mu * (std::abs(w[i]) - w[i])/2.0);
}
_pk2_tmp = pk2pos * xfac - pk2neg;
if (_save_state)
{
std::vector<Real> epos(LIBMESH_DIM);
for (unsigned int i = 0; i < LIBMESH_DIM; ++i)
epos[i] = (std::abs(w[i]) + w[i])/2.0;
_G0[_qp] = 0.0;
for (unsigned int i = 0; i < LIBMESH_DIM; ++i)
_G0[_qp] += std::pow(epos[i], 2.0);
_G0[_qp] *= mu;
_G0[_qp] += lambda * std::pow(etrpos, 2.0)/2.0;
_dG0_dee = pk2pos;
_dpk2_dc = -pk2pos * (2.0 * (1.0-c));
}
}
void
HyperElasticPhaseFieldIsoDamage::computeNumStiffness()
{
RankTwoTensor ee_tmp;
for (unsigned int i = 0; i < LIBMESH_DIM; ++i)
for (unsigned int j = i; j < LIBMESH_DIM; ++j)
{
Real ee_pert = _zero_pert;
if (std::abs(_ee(i, j)) > _zero_tol)
ee_pert = _pert_val * std::abs(_ee(i, j));
ee_tmp = _ee;
_ee(i, j) += ee_pert;
computeDamageStress();
for (unsigned int k = 0; k < LIBMESH_DIM; ++k)
for (unsigned int l = 0; l < LIBMESH_DIM; ++l)
{
_dpk2_dee(k, l, i, j) = (_pk2_tmp(k, l) - _pk2[_qp](k, l))/ee_pert;
_dpk2_dee(k, l, j, i) = (_pk2_tmp(k, l) - _pk2[_qp](k, l))/ee_pert;
}
_ee = ee_tmp;
}
}
void
HyperElasticPhaseFieldIsoDamage::computeQpJacobian()
{
FiniteStrainHyperElasticViscoPlastic::computeQpJacobian();
RankTwoTensor dG0_dce = _dee_dce.innerProductTranspose(_dG0_dee);
RankTwoTensor dG0_dfe = _dce_dfe.innerProductTranspose(dG0_dce);
RankTwoTensor dG0_df = _dfe_df.innerProductTranspose(dG0_dfe);
_dG0_dstrain[_qp] = _df_dstretch_inc.innerProductTranspose(dG0_df);
_dstress_dc[_qp] = _fe.mixedProductIkJl(_fe) * _dpk2_dc;
}
| jhbradley/moose | modules/tensor_mechanics/src/materials/HyperElasticPhaseFieldIsoDamage.C | C++ | lgpl-2.1 | 5,142 |
package railo.runtime.db;
import java.sql.SQLException;
import java.util.Map;
import railo.runtime.op.Caster;
class OLDDCStack {
private Item item;
private Map transactionItem=null;
private DatasourceConnectionPool pool;
OLDDCStack(DatasourceConnectionPool pool) {
this.pool=pool;
}
public synchronized void add(int pid,DatasourceConnection dc){
if(pid==0)
item=new Item(item,dc);
else {
transactionItem.put(Caster.toInteger(pid), dc);
}
}
public synchronized DatasourceConnection get(int pid){
DatasourceConnection rtn;
if(pid!=0) {
rtn = (DatasourceConnection) transactionItem.remove(Caster.toInteger(pid));
if(rtn!=null) {
try {
if(!rtn.getConnection().isClosed())
return rtn;
}
catch (SQLException e) {}
}
}
if(item==null) return null;
rtn = item.dc;
item=item.prev;
try {
if(!rtn.getConnection().isClosed())
return rtn;
}
catch (SQLException e) {}
return null;
}
public synchronized boolean isEmpty(int pid){
return item==null&&!transactionItem.containsKey(Caster.toInteger(pid));
}
public synchronized boolean _isEmpty(int pid){
if(pid!=0) {
return transactionItem.containsKey(Caster.toInteger(pid));
}
return item==null;
}
public synchronized int size(){
int count=0;
Item i = item;
while(i!=null){
count++;
i=i.prev;
}
return count;
}
class Item {
private DatasourceConnection dc;
private Item prev;
private int count=1;
public Item(Item item,DatasourceConnection dc) {
this.prev=item;
this.dc=dc;
if(prev!=null)count=prev.count+1;
}
public String toString(){
return "("+prev+")<-"+count;
}
}
public synchronized void clear() {
try {
clear(item,null);
}
catch (SQLException e) {}
}
public synchronized void clear(int pid) {
DatasourceConnection dc = (DatasourceConnection) transactionItem.remove(Caster.toInteger(pid));
if(dc!=null)add(0, dc);
}
private void clear(Item current,Item next) throws SQLException {
if(current==null) return;
if((current.dc.isTimeout() || current.dc.getConnection().isClosed())) {
if(!current.dc.getConnection().isClosed()){
try {
current.dc.getConnection().close();
}
catch (SQLException e) {}
}
if(next==null)item=current.prev;
else {
next.prev=current.prev;
}
clear(current.prev,next);
}
else clear(current.prev,current);
}
/*public int inc() {
return ++count;
}
public boolean isWaiting() {
return count>0;
}
public int dec() {
return --count;
}*/
}
| JordanReiter/railo | railo-java/railo-core/src/railo/runtime/db/OLDDCStack.java | Java | lgpl-2.1 | 2,614 |
/**************************************************************************
**
** Copyright (C) 2015 BogDan Vatra <bog_dan_ro@yahoo.com>
** Contact: http://www.qt.io/licensing
**
** This file is part of Qt Creator.
**
** Commercial License Usage
** Licensees holding valid commercial Qt licenses may use this file in
** accordance with the commercial license agreement provided with the
** Software or, alternatively, in accordance with the terms contained in
** a written agreement between you and The Qt Company. For licensing terms and
** conditions see http://www.qt.io/terms-conditions. For further information
** use the contact form at http://www.qt.io/contact-us.
**
** GNU Lesser General Public License Usage
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 or version 3 as published by the Free
** Software Foundation and appearing in the file LICENSE.LGPLv21 and
** LICENSE.LGPLv3 included in the packaging of this file. Please review the
** following information to ensure the GNU Lesser General Public License
** requirements will be met: https://www.gnu.org/licenses/lgpl.html and
** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, The Qt Company gives you certain additional
** rights. These rights are described in The Qt Company LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
****************************************************************************/
#include "androidpackageinstallationstep.h"
#include <android/androidconstants.h>
#include <android/androidmanager.h>
#include <projectexplorer/buildsteplist.h>
#include <projectexplorer/target.h>
#include <projectexplorer/buildconfiguration.h>
#include <projectexplorer/toolchain.h>
#include <projectexplorer/kitinformation.h>
#include <projectexplorer/gnumakeparser.h>
#include <utils/hostosinfo.h>
#include <QDir>
using namespace QmakeAndroidSupport::Internal;
const Core::Id AndroidPackageInstallationStep::Id = Core::Id("Qt4ProjectManager.AndroidPackageInstallationStep");
AndroidPackageInstallationStep::AndroidPackageInstallationStep(ProjectExplorer::BuildStepList *bsl)
: AbstractProcessStep(bsl, Id)
{
const QString name = tr("Copy application data");
setDefaultDisplayName(name);
setDisplayName(name);
}
AndroidPackageInstallationStep::AndroidPackageInstallationStep(ProjectExplorer::BuildStepList *bc, AndroidPackageInstallationStep *other)
: AbstractProcessStep(bc, other)
{ }
bool AndroidPackageInstallationStep::init()
{
ProjectExplorer::BuildConfiguration *bc = buildConfiguration();
QString dirPath = bc->buildDirectory().appendPath(QLatin1String(Android::Constants::ANDROID_BUILDDIRECTORY)).toString();
if (Utils::HostOsInfo::isWindowsHost())
if (bc->environment().searchInPath(QLatin1String("sh.exe")).isEmpty())
dirPath = QDir::toNativeSeparators(dirPath);
ProjectExplorer::ToolChain *tc
= ProjectExplorer::ToolChainKitInformation::toolChain(target()->kit());
ProjectExplorer::ProcessParameters *pp = processParameters();
pp->setMacroExpander(bc->macroExpander());
pp->setWorkingDirectory(bc->buildDirectory().toString());
pp->setCommand(tc->makeCommand(bc->environment()));
Utils::Environment env = bc->environment();
// Force output to english for the parsers. Do this here and not in the toolchain's
// addToEnvironment() to not screw up the users run environment.
env.set(QLatin1String("LC_ALL"), QLatin1String("C"));
pp->setEnvironment(env);
pp->setArguments(QString::fromLatin1("INSTALL_ROOT=\"%1\" install").arg(dirPath));
pp->resolveAll();
setOutputParser(new ProjectExplorer::GnuMakeParser());
ProjectExplorer::IOutputParser *parser = target()->kit()->createOutputParser();
if (parser)
appendOutputParser(parser);
outputParser()->setWorkingDirectory(pp->effectiveWorkingDirectory());
m_androidDirsToClean.clear();
// don't remove gradle's cache, it takes ages to rebuild it.
if (!QFile::exists(dirPath + QLatin1String("/build.xml")) && Android::AndroidManager::useGradle(target())) {
m_androidDirsToClean << dirPath + QLatin1String("/assets");
m_androidDirsToClean << dirPath + QLatin1String("/libs");
} else {
m_androidDirsToClean << dirPath;
}
return AbstractProcessStep::init();
}
void AndroidPackageInstallationStep::run(QFutureInterface<bool> &fi)
{
QString error;
foreach (const QString &dir, m_androidDirsToClean) {
Utils::FileName androidDir = Utils::FileName::fromString(dir);
if (!dir.isEmpty() && androidDir.exists()) {
emit addOutput(tr("Removing directory %1").arg(dir), MessageOutput);
if (!Utils::FileUtils::removeRecursively(androidDir, &error)) {
emit addOutput(error, ErrorOutput);
fi.reportResult(false);
emit finished();
return;
}
}
}
AbstractProcessStep::run(fi);
}
ProjectExplorer::BuildStepConfigWidget *AndroidPackageInstallationStep::createConfigWidget()
{
return new AndroidPackageInstallationStepWidget(this);
}
bool AndroidPackageInstallationStep::immutable() const
{
return true;
}
//
// AndroidPackageInstallationStepWidget
//
AndroidPackageInstallationStepWidget::AndroidPackageInstallationStepWidget(AndroidPackageInstallationStep *step)
: m_step(step)
{
}
QString AndroidPackageInstallationStepWidget::summaryText() const
{
return tr("<b>Make install</b>");
}
QString AndroidPackageInstallationStepWidget::displayName() const
{
return tr("Make install");
}
bool AndroidPackageInstallationStepWidget::showWidget() const
{
return false;
}
| danimo/qt-creator | src/plugins/qmakeandroidsupport/androidpackageinstallationstep.cpp | C++ | lgpl-2.1 | 5,802 |
/****************************************************************************
**
** Copyright (C) 2015 The Qt Company Ltd.
** Contact: http://www.qt.io/licensing
**
** This file is part of Qt Creator.
**
** Commercial License Usage
** Licensees holding valid commercial Qt licenses may use this file in
** accordance with the commercial license agreement provided with the
** Software or, alternatively, in accordance with the terms contained in
** a written agreement between you and The Qt Company. For licensing terms and
** conditions see http://www.qt.io/terms-conditions. For further information
** use the contact form at http://www.qt.io/contact-us.
**
** GNU Lesser General Public License Usage
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 or version 3 as published by the Free
** Software Foundation and appearing in the file LICENSE.LGPLv21 and
** LICENSE.LGPLv3 included in the packaging of this file. Please review the
** following information to ensure the GNU Lesser General Public License
** requirements will be met: https://www.gnu.org/licenses/lgpl.html and
** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, The Qt Company gives you certain additional
** rights. These rights are described in The Qt Company LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
****************************************************************************/
#include "qbspropertylineedit.h"
#include <utils/qtcprocess.h>
#include <QStringList>
namespace QbsProjectManager {
namespace Internal {
QbsPropertyLineEdit::QbsPropertyLineEdit(QWidget *parent) :
Utils::FancyLineEdit(parent)
{ }
QList<QPair<QString, QString> > QbsPropertyLineEdit::properties() const
{
return m_propertyCache;
}
bool QbsPropertyLineEdit::validate(const QString &value, QString *errorMessage) const
{
Utils::QtcProcess::SplitError err;
QStringList argList = Utils::QtcProcess::splitArgs(value, Utils::HostOsInfo::hostOs(), false, &err);
if (err != Utils::QtcProcess::SplitOk) {
if (errorMessage)
*errorMessage = tr("Could not split properties.");
return false;
}
QList<QPair<QString, QString> > properties;
foreach (const QString &arg, argList) {
int pos = arg.indexOf(QLatin1Char(':'));
QString key;
QString value;
if (pos > 0) {
key = arg.left(pos);
value = arg.mid(pos + 1);
properties.append(qMakePair(key, value));
} else {
if (errorMessage)
*errorMessage = tr("No ':' found in property definition.");
return false;
}
}
if (m_propertyCache != properties) {
m_propertyCache = properties;
emit propertiesChanged();
}
return true;
}
} // namespace Internal
} // namespace QbsProjectManager
| Distrotech/qtcreator | src/plugins/qbsprojectmanager/qbspropertylineedit.cpp | C++ | lgpl-2.1 | 2,955 |
#!/usr/bin/env python
'''
Copyright (C) 2005 Aaron Spike, aaron@ekips.org
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
'''
import random, math, inkex, cubicsuperpath
def randomize((x, y), rx, ry, norm):
if norm:
r = abs(random.normalvariate(0.0,0.5*max(rx, ry)))
else:
r = random.uniform(0.0,max(rx, ry))
a = random.uniform(0.0,2*math.pi)
x += math.cos(a)*rx
y += math.sin(a)*ry
return [x, y]
class RadiusRandomize(inkex.Effect):
def __init__(self):
inkex.Effect.__init__(self)
self.OptionParser.add_option("--title")
self.OptionParser.add_option("-x", "--radiusx",
action="store", type="float",
dest="radiusx", default=10.0,
help="Randomly move nodes and handles within this radius, X")
self.OptionParser.add_option("-y", "--radiusy",
action="store", type="float",
dest="radiusy", default=10.0,
help="Randomly move nodes and handles within this radius, Y")
self.OptionParser.add_option("-c", "--ctrl",
action="store", type="inkbool",
dest="ctrl", default=True,
help="Randomize control points")
self.OptionParser.add_option("-e", "--end",
action="store", type="inkbool",
dest="end", default=True,
help="Randomize nodes")
self.OptionParser.add_option("-n", "--norm",
action="store", type="inkbool",
dest="norm", default=True,
help="Use normal distribution")
def effect(self):
for id, node in self.selected.iteritems():
if node.tag == inkex.addNS('path','svg'):
d = node.get('d')
p = cubicsuperpath.parsePath(d)
for subpath in p:
for csp in subpath:
if self.options.end:
delta=randomize([0,0], self.options.radiusx, self.options.radiusy, self.options.norm)
csp[0][0]+=delta[0]
csp[0][1]+=delta[1]
csp[1][0]+=delta[0]
csp[1][1]+=delta[1]
csp[2][0]+=delta[0]
csp[2][1]+=delta[1]
if self.options.ctrl:
csp[0]=randomize(csp[0], self.options.radiusx, self.options.radiusy, self.options.norm)
csp[2]=randomize(csp[2], self.options.radiusx, self.options.radiusy, self.options.norm)
node.set('d',cubicsuperpath.formatPath(p))
if __name__ == '__main__':
e = RadiusRandomize()
e.affect()
# vim: expandtab shiftwidth=4 tabstop=8 softtabstop=4 encoding=utf-8 textwidth=99
| step21/inkscape-osx-packaging-native | packaging/macosx/Inkscape.app/Contents/Resources/extensions/radiusrand.py | Python | lgpl-2.1 | 3,583 |
# Copyright 2013-2021 Lawrence Livermore National Security, LLC and other
# Spack Project Developers. See the top-level COPYRIGHT file for details.
#
# SPDX-License-Identifier: (Apache-2.0 OR MIT)
import os
from spack import *
class Vasp(MakefilePackage):
"""
The Vienna Ab initio Simulation Package (VASP)
is a computer program for atomic scale materials modelling,
e.g. electronic structure calculations
and quantum-mechanical molecular dynamics, from first principles.
"""
homepage = "https://vasp.at"
url = "file://{0}/vasp.5.4.4.pl2.tgz".format(os.getcwd())
manual_download = True
version('6.2.0', sha256='49e7ba351bd634bc5f5f67a8ef1e38e64e772857a1c02f602828898a84197e25')
version('6.1.1', sha256='e37a4dfad09d3ad0410833bcd55af6b599179a085299026992c2d8e319bf6927')
version('5.4.4.pl2', sha256='98f75fd75399a23d76d060a6155f4416b340a1704f256a00146f89024035bc8e')
version('5.4.4', sha256='5bd2449462386f01e575f9adf629c08cb03a13142806ffb6a71309ca4431cfb3')
resource(name='vaspsol',
git='https://github.com/henniggroup/VASPsol.git',
tag='V1.0',
when='+vaspsol')
variant('openmp', default=False,
description='Enable openmp build')
variant('scalapack', default=False,
description='Enables build with SCALAPACK')
variant('cuda', default=False,
description='Enables running on Nvidia GPUs')
variant('vaspsol', default=False,
description='Enable VASPsol implicit solvation model\n'
'https://github.com/henniggroup/VASPsol')
depends_on('rsync', type='build')
depends_on('blas')
depends_on('lapack')
depends_on('fftw-api')
depends_on('mpi', type=('build', 'link', 'run'))
depends_on('scalapack', when='+scalapack')
depends_on('cuda', when='+cuda')
depends_on('qd', when='%nvhpc')
conflicts('%gcc@:8', msg='GFortran before 9.x does not support all features needed to build VASP')
conflicts('+vaspsol', when='+cuda', msg='+vaspsol only available for CPU')
conflicts('+openmp', when='@:6.1.1', msg='openmp support started from 6.2')
parallel = False
def edit(self, spec, prefix):
if '%gcc' in spec:
if '+openmp' in spec:
make_include = join_path('arch', 'makefile.include.linux_gnu_omp')
else:
make_include = join_path('arch', 'makefile.include.linux_gnu')
elif '%nvhpc' in spec:
make_include = join_path('arch', 'makefile.include.linux_pgi')
filter_file('-pgc++libs', '-c++libs', make_include, string=True)
filter_file('pgcc', spack_cc, make_include)
filter_file('pgc++', spack_cxx, make_include, string=True)
filter_file('pgfortran', spack_fc, make_include)
filter_file('/opt/pgi/qd-2.3.17/install/include',
spec['qd'].prefix.include, make_include)
filter_file('/opt/pgi/qd-2.3.17/install/lib',
spec['qd'].prefix.lib, make_include)
elif '%aocc' in spec:
if '+openmp' in spec:
copy(
join_path('arch', 'makefile.include.linux_gnu_omp'),
join_path('arch', 'makefile.include.linux_aocc_omp')
)
make_include = join_path('arch', 'makefile.include.linux_aocc_omp')
else:
copy(
join_path('arch', 'makefile.include.linux_gnu'),
join_path('arch', 'makefile.include.linux_aocc')
)
make_include = join_path('arch', 'makefile.include.linux_aocc')
filter_file(
'gcc', '{0} {1}'.format(spack_cc, '-Mfree'),
make_include, string=True
)
filter_file('g++', spack_cxx, make_include, string=True)
filter_file('^CFLAGS_LIB[ ]{0,}=.*$',
'CFLAGS_LIB = -O3', make_include)
filter_file('^FFLAGS_LIB[ ]{0,}=.*$',
'FFLAGS_LIB = -O2', make_include)
filter_file('^OFLAG[ ]{0,}=.*$',
'OFLAG = -O3', make_include)
filter_file('^FC[ ]{0,}=.*$',
'FC = {0}'.format(spec['mpi'].mpifc),
make_include, string=True)
filter_file('^FCL[ ]{0,}=.*$',
'FCL = {0}'.format(spec['mpi'].mpifc),
make_include, string=True)
else:
if '+openmp' in spec:
make_include = join_path('arch',
'makefile.include.linux_{0}_omp'.
format(spec.compiler.name))
else:
make_include = join_path('arch',
'makefile.include.linux_' +
spec.compiler.name)
os.rename(make_include, 'makefile.include')
# This bunch of 'filter_file()' is to make these options settable
# as environment variables
filter_file('^CPP_OPTIONS[ ]{0,}=[ ]{0,}',
'CPP_OPTIONS ?= ',
'makefile.include')
filter_file('^FFLAGS[ ]{0,}=[ ]{0,}',
'FFLAGS ?= ',
'makefile.include')
filter_file('^LIBDIR[ ]{0,}=.*$', '', 'makefile.include')
filter_file('^BLAS[ ]{0,}=.*$', 'BLAS ?=', 'makefile.include')
filter_file('^LAPACK[ ]{0,}=.*$', 'LAPACK ?=', 'makefile.include')
filter_file('^FFTW[ ]{0,}?=.*$', 'FFTW ?=', 'makefile.include')
filter_file('^MPI_INC[ ]{0,}=.*$', 'MPI_INC ?=', 'makefile.include')
filter_file('-DscaLAPACK.*$\n', '', 'makefile.include')
filter_file('^SCALAPACK[ ]{0,}=.*$', 'SCALAPACK ?=', 'makefile.include')
if '+cuda' in spec:
filter_file('^OBJECTS_GPU[ ]{0,}=.*$',
'OBJECTS_GPU ?=',
'makefile.include')
filter_file('^CPP_GPU[ ]{0,}=.*$',
'CPP_GPU ?=',
'makefile.include')
filter_file('^CFLAGS[ ]{0,}=.*$',
'CFLAGS ?=',
'makefile.include')
if '+vaspsol' in spec:
copy('VASPsol/src/solvation.F', 'src/')
def setup_build_environment(self, spack_env):
spec = self.spec
cpp_options = ['-DMPI -DMPI_BLOCK=8000',
'-Duse_collective', '-DCACHE_SIZE=4000',
'-Davoidalloc', '-Duse_bse_te',
'-Dtbdyn', '-Duse_shmem']
if '%nvhpc' in self.spec:
cpp_options.extend(['-DHOST=\\"LinuxPGI\\"', '-DPGI16',
'-Dqd_emulate'])
elif '%aocc' in self.spec:
cpp_options.extend(['-DHOST=\\"LinuxGNU\\"',
'-Dfock_dblbuf'])
if '+openmp' in self.spec:
cpp_options.extend(['-D_OPENMP'])
else:
cpp_options.append('-DHOST=\\"LinuxGNU\\"')
if self.spec.satisfies('@6:'):
cpp_options.append('-Dvasp6')
cflags = ['-fPIC', '-DADD_']
fflags = []
if '%gcc' in spec or '%intel' in spec:
fflags.append('-w')
elif '%nvhpc' in spec:
fflags.extend(['-Mnoupcase', '-Mbackslash', '-Mlarge_arrays'])
elif '%aocc' in spec:
fflags.extend(['-fno-fortran-main', '-Mbackslash', '-ffast-math'])
spack_env.set('BLAS', spec['blas'].libs.ld_flags)
spack_env.set('LAPACK', spec['lapack'].libs.ld_flags)
spack_env.set('FFTW', spec['fftw-api'].prefix)
spack_env.set('MPI_INC', spec['mpi'].prefix.include)
if '%nvhpc' in spec:
spack_env.set('QD', spec['qd'].prefix)
if '+scalapack' in spec:
cpp_options.append('-DscaLAPACK')
spack_env.set('SCALAPACK', spec['scalapack'].libs.ld_flags)
if '+cuda' in spec:
cpp_gpu = ['-DCUDA_GPU', '-DRPROMU_CPROJ_OVERLAP',
'-DCUFFT_MIN=28', '-DUSE_PINNED_MEMORY']
objects_gpu = ['fftmpiw.o', 'fftmpi_map.o', 'fft3dlib.o',
'fftw3d_gpu.o', 'fftmpiw_gpu.o']
cflags.extend(['-DGPUSHMEM=300', '-DHAVE_CUBLAS'])
spack_env.set('CUDA_ROOT', spec['cuda'].prefix)
spack_env.set('CPP_GPU', ' '.join(cpp_gpu))
spack_env.set('OBJECTS_GPU', ' '.join(objects_gpu))
if '+vaspsol' in spec:
cpp_options.append('-Dsol_compat')
if spec.satisfies('%gcc@10:'):
fflags.append('-fallow-argument-mismatch')
# Finally
spack_env.set('CPP_OPTIONS', ' '.join(cpp_options))
spack_env.set('CFLAGS', ' '.join(cflags))
spack_env.set('FFLAGS', ' '.join(fflags))
def build(self, spec, prefix):
if '+cuda' in self.spec:
make('gpu', 'gpu_ncl')
else:
make('std', 'gam', 'ncl')
def install(self, spec, prefix):
install_tree('bin/', prefix.bin)
| LLNL/spack | var/spack/repos/builtin/packages/vasp/package.py | Python | lgpl-2.1 | 9,155 |