code
stringlengths
3
1.05M
repo_name
stringlengths
4
116
path
stringlengths
3
942
language
stringclasses
30 values
license
stringclasses
15 values
size
int32
3
1.05M
<html> <head> <title>In costruzione</title> <style> .underconstruction { display: block; background: rgb(255,255,255); background-image: url("../imgs/underConstruction.png"); background-position: 0 center; background-repeat: no-repeat; color: black; font-size: 20px; line-height: 80px; text-weight: bold; position: fixed; top: 60px; right: 200px; -webkit-transform: rotate(6deg); width: 205px; margin-right: -147px; height: 80px; margin-top: -40px; padding-left: 110px; border: 4px dotted black; border-radius: 12px; z-index: 1000; -webkit-animation: myfirst 2s; } </style> </head> <body> <div class='underconstruction'>Lavori in corso!</div> <a class="usermail" href="{{ logsession|safe }}" title="Esegui il logout">Benvenuto {{ username|safe }}</a> <p>L&apos;accesso a questa web-app &egrave; limitato a pochi utenti</p> </body> </html>
vncnz/howmuch
html/underconstruction.html
HTML
gpl-2.0
924
<?php /** * OG behavior handler. */ class OgBehaviorHandler extends EntityReference_BehaviorHandler_Abstract { /** * Implements EntityReference_BehaviorHandler_Abstract::access(). */ public function access($field, $instance) { return $field['settings']['handler'] == 'og' || strpos($field['settings']['handler'], 'og_') === 0; } /** * Implements EntityReference_BehaviorHandler_Abstract::load(). */ public function load($entity_type, $entities, $field, $instances, $langcode, &$items) { // Get the OG memberships from the field. $field_name = $field['field_name']; $target_type = $field['settings']['target_type']; foreach ($entities as $entity) { $wrapper = entity_metadata_wrapper($entity_type, $entity); if (empty($wrapper->{$field_name})) { // If the entity belongs to a bundle that was deleted, return early. continue; } $id = $wrapper->getIdentifier(); $items[$id] = array(); $gids = og_get_entity_groups($entity_type, $entity, array(), $field_name); if (empty($gids[$target_type])) { continue; } foreach ($gids[$target_type] as $gid) { $items[$id][] = array( 'target_id' => $gid, ); } } } /** * Implements EntityReference_BehaviorHandler_Abstract::insert(). */ public function insert($entity_type, $entity, $field, $instance, $langcode, &$items) { if (!empty($entity->skip_og_membership)) { return; } $this->OgMembershipCrud($entity_type, $entity, $field, $instance, $langcode, $items); $items = array(); } /** * Implements EntityReference_BehaviorHandler_Abstract::access(). */ public function update($entity_type, $entity, $field, $instance, $langcode, &$items) { if (!empty($entity->skip_og_membership)) { return; } $this->OgMembershipCrud($entity_type, $entity, $field, $instance, $langcode, $items); $items = array(); } /** * Implements EntityReference_BehaviorHandler_Abstract::Delete() * * CRUD memberships from field, or if entity is marked for deleteing, * delete all the OG membership related to it. * * @see og_entity_delete(). */ public function delete($entity_type, $entity, $field, $instance, $langcode, &$items) { if (!empty($entity->skip_og_membership)) { return; } if (!empty($entity->delete_og_membership)) { // Delete all OG memberships related to this entity. $og_memberships = array(); foreach (og_get_entity_groups($entity_type, $entity) as $group_type => $ids) { $og_memberships = array_merge($og_memberships, array_keys($ids)); } if ($og_memberships) { og_membership_delete_multiple($og_memberships); } } else { $this->OgMembershipCrud($entity_type, $entity, $field, $instance, $langcode, $items); } } /** * Create, update or delete OG membership based on field values. */ public function OgMembershipCrud($entity_type, $entity, $field, $instance, $langcode, &$items) { if (!user_access('administer group') && !field_access('edit', $field, $entity_type, $entity)) { // User has no access to field. return; } if (!$diff = $this->groupAudiencegetDiff($entity_type, $entity, $field, $instance, $langcode, $items)) { return; } $field_name = $field['field_name']; $group_type = $field['settings']['target_type']; $diff += array('insert' => array(), 'delete' => array()); // Delete first, so we don't trigger cardinality errors. if ($diff['delete']) { og_membership_delete_multiple($diff['delete']); } if (!$diff['insert']) { return; } // Prepare an array with the membership state, if it was provided in the widget. $states = array(); foreach ($items as $item) { $gid = $item['target_id']; if (empty($item['state']) || !in_array($gid, $diff['insert'])) { // State isn't provided, or not an "insert" operation. continue; } $states[$gid] = $item['state']; } foreach ($diff['insert'] as $gid) { $values = array( 'entity_type' => $entity_type, 'entity' => $entity, 'field_name' => $field_name, ); if (!empty($states[$gid])) { $values['state'] = $states[$gid]; } og_group($group_type, $gid, $values); } } /** * Get the difference in group audience for a saved field. * * @return * Array with all the differences, or an empty array if none found. */ public function groupAudiencegetDiff($entity_type, $entity, $field, $instance, $langcode, $items) { $return = FALSE; $field_name = $field['field_name']; $wrapper = entity_metadata_wrapper($entity_type, $entity); $og_memberships = $wrapper->{$field_name . '__og_membership'}->value(); $new_memberships = array(); foreach ($items as $item) { $new_memberships[$item['target_id']] = TRUE; } foreach ($og_memberships as $og_membership) { $gid = $og_membership->gid; if (empty($new_memberships[$gid])) { // Membership was deleted. if ($og_membership->entity_type == 'user') { // Make sure this is not the group manager, if exists. $group = entity_load_single($og_membership->group_type, $og_membership->gid); if (!empty($group->uid) && $group->uid == $og_membership->etid) { continue; } } $return['delete'][] = $og_membership->id; unset($new_memberships[$gid]); } else { // Existing membership. unset($new_memberships[$gid]); } } if ($new_memberships) { // New memberships. $return['insert'] = array_keys($new_memberships); } return $return; } /** * Implements EntityReference_BehaviorHandler_Abstract::views_data_alter(). */ public function views_data_alter(&$data, $field) { // We need to override the default EntityReference table settings when OG // behavior is being used. if (og_is_group_audience_field($field['field_name'])) { $entity_types = array_keys($field['bundles']); // We need to join the base table for the entities // that this field is attached to. foreach ($entity_types as $entity_type) { $entity_info = entity_get_info($entity_type); $data['og_membership'] = array( 'table' => array( 'join' => array( $entity_info['base table'] => array( // Join entity base table on its id field with left_field. 'left_field' => $entity_info['entity keys']['id'], 'field' => 'etid', 'extra' => array( 0 => array( 'field' => 'entity_type', 'value' => $entity_type, ), ), ), ), ), // Copy the original config from the table definition. $field['field_name'] => $data['field_data_' . $field['field_name']][$field['field_name']], $field['field_name'] . '_target_id' => $data['field_data_' . $field['field_name']][$field['field_name'] . '_target_id'], ); // Change config with settings from og_membership table. foreach (array('filter', 'argument', 'sort') as $op) { $data['og_membership'][$field['field_name'] . '_target_id'][$op]['field'] = 'gid'; $data['og_membership'][$field['field_name'] . '_target_id'][$op]['table'] = 'og_membership'; unset($data['og_membership'][$field['field_name'] . '_target_id'][$op]['additional fields']); } } // Get rid of the original table configs. unset($data['field_data_' . $field['field_name']]); unset($data['field_revision_' . $field['field_name']]); } } /** * Implements EntityReference_BehaviorHandler_Abstract::validate(). * * Re-build $errors array to be keyed correctly by "default" and "admin" field * modes. * * @todo: Try to get the correct delta so we can highlight the invalid * reference. * * @see entityreference_field_validate(). */ public function validate($entity_type, $entity, $field, $instance, $langcode, $items, &$errors) { $new_errors = array(); $values = array('default' => array(), 'admin' => array()); $item = reset($items); if (!empty($item['field_mode'])) { // This is a complex widget with "default" and "admin" field modes. foreach ($items as $item) { $values[$item['field_mode']][] = $item['target_id']; } } else { foreach ($items as $item) { if (!entityreference_field_is_empty($item, $field) && $item['target_id'] !== NULL) { $values['default'][] = $item['target_id']; } } } $field_name = $field['field_name']; foreach ($values as $field_mode => $ids) { if (!$ids) { continue; } if ($field_mode == 'admin' && !user_access('administer group')) { // No need to validate the admin, as the user has no access to it. continue; } $instance['field_mode'] = $field_mode; $valid_ids = entityreference_get_selection_handler($field, $instance, $entity_type, $entity)->validateReferencableEntities($ids); if ($invalid_entities = array_diff($ids, $valid_ids)) { foreach ($invalid_entities as $id) { $new_errors[$field_mode][] = array( 'error' => 'og_invalid_entity', 'message' => t('The referenced group (@type: @id) is invalid.', array('@type' => $field['settings']['target_type'], '@id' => $id)), ); } } } if ($new_errors) { og_field_widget_register_errors($field_name, $new_errors); // We throw an exception ourself, as we unset the $errors array. throw new FieldValidationException($new_errors); } // Errors for this field now handled, removing from the referenced array. unset($errors[$field_name]); } }
codifi/mukurtucms
sites/all/modules/contrib/og/plugins/entityreference/behavior/OgBehaviorHandler.class.php
PHP
gpl-2.0
10,070
// // OFAlertView.h // Offliner // // Created by Guillaume on 02/08/2014. // Copyright (c) 2014 Guillaume Cendre. All rights reserved. // #import <UIKit/UIKit.h> @interface OFAlertView : UIView - (id)initWithOrigin:(CGPoint)origin options:(NSArray*)options andTitle:(NSString*)title; @end
chlkbumper/offliner-ios
Offliner/OFAlertView.h
C
gpl-2.0
298
require File.expand_path('../boot', __FILE__) require 'rails/all' # Require the gems listed in Gemfile, including any gems # you've limited to :test, :development, or :production. Bundler.require(*Rails.groups) module Spoodle class Application < Rails::Application # Settings in config/environments/* take precedence over those specified here. # Application configuration should go into files in config/initializers # -- all .rb files in that directory are automatically loaded. # Set Time.zone default to the specified zone and make Active Record auto-convert to this zone. # Run "rake -D time" for a list of tasks for finding time zone names. Default is UTC. config.time_zone = 'Bern' # The default locale is :en and all translations from config/locales/*.rb,yml are auto loaded. # config.i18n.load_path += Dir[Rails.root.join('my', 'locales', '*.{rb,yml}').to_s] # config.i18n.default_locale = :de end end
ASE-2014/spoodle
config/application.rb
Ruby
gpl-2.0
954
using System; using System.Diagnostics; namespace Lumpn.Profiling { public sealed class Recorder { private readonly Stopwatch stopwatch = new Stopwatch(); private readonly string name; public Recorder(string name) { this.name = name; } public void Reset() { stopwatch.Reset(); } public void Begin() { stopwatch.Start(); } public void End() { stopwatch.Stop(); } public void Submit() { Profiler.AddSample(name, stopwatch.ElapsedTicks); } } }
lumpn/infinite-zelda
Lumpn.Profiling/Recorder.cs
C#
gpl-2.0
658
/* @(#)cvmod.c 2.7 00/12/03 Copyright 1986, 1995 J. Schilling */ /* * Copyright (c) 1986, 1995 J. Schilling */ /* * 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, 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; see the file COPYING. If not, write to * the Free Software Foundation, 675 Mass Ave, Cambridge, MA 02139, USA. */ #include "io.h" #ifndef O_BINARY #define O_BINARY 0 #endif #ifndef O_LARGEFILE #define O_LARGEFILE 0 #endif EXPORT int _cvmod(mode, omode, flag) const char *mode; int *omode; int *flag; { while (*mode){ switch (*mode) { case 'r': *omode |= O_RDONLY; *flag |= FI_READ; break; case 'w': *omode |= O_WRONLY; *flag |= FI_WRITE; break; case 'e': *omode |= O_EXCL; break; case 'c': *omode |= O_CREAT; *flag |= FI_CREATE; break; case 't': *omode |= O_TRUNC; *flag |= FI_TRUNC; break; case 'a': *omode |= O_APPEND; *flag |= FI_APPEND; break; case 'u': *flag |= FI_UNBUF; break; /* dummy on UNIX */ case 'b': *omode |= O_BINARY; *flag |= FI_BINARY; break; /* * XXX do we need this ? * XXX May this be a problem? */ case 'l': *omode |= O_LARGEFILE; break; default: raisecond(_badmode, 0L); return 0; } mode++; } if (*flag & FI_READ && *flag & FI_WRITE) { *omode &= ~(O_RDONLY|O_WRONLY); *omode |= O_RDWR; } return 1; }
ronys/count
lib/stdio/cvmod.c
C
gpl-2.0
1,825
<?php /** * * */ /** * Import SQL data. * * @param string $args as the queries of sql data , you could use file get contents to read data args * @param string/array $tables_whitelist 'all' = all tables; array('tbl1',...) = only listet tables * @param string $dbhost database host * @param string $dbuser database user * @param string $dbpass database password * @param string $dbname database name * * @return string complete if complete */ function database_import( $args, $tables_whitelist, $dbhost, $dbuser, $dbpass, $dbname ) { // check mysqli extension installed if ( !function_exists('mysqli_connect') ) { die('This scripts need mysql extension to be running properly! Please resolve!'); } $mysqli = @new mysqli( $dbhost, $dbuser, $dbpass, $dbname ); if ( $mysqli->connect_error ) { print_r( $mysqli->connect_error ); return false; } // DROP all tables (be carefull...) $mysqli->query('SET foreign_key_checks = 0'); if ( $result = $mysqli->query("SHOW TABLES") ) { while ( $row = $result->fetch_array(MYSQLI_NUM) ) { if ( $tables_whitelist=='all' || in_array($row[0], (array)$tables_whitelist) ) { $mysqli->query('DROP TABLE IF EXISTS '.$row[0]); } } } $mysqli->query('SET foreign_key_checks = 1'); $querycount = 11; $queryerrors = ''; $lines = (array) $args; if ( is_string( $args ) ) { $lines = array( $args ) ; } if ( ! $lines ) { return 'cannot execute ' . $args; } $scriptfile = false; foreach ($lines as $line) { $line = trim( $line ); // if have -- comments add enters if (substr( $line, 0, 2 ) == '--') { $line = "\n" . $line; } if (substr( $line, 0, 2 ) != '--') { $scriptfile .= ' ' . $line; continue; } } $queries = explode( ';', $scriptfile ); foreach ($queries as $query) { $query = trim( $query ); ++$querycount; if ( $query == '' ) { continue; } if ( ! $mysqli->query( $query ) ) { $queryerrors .= 'Line ' . $querycount . ' - ' . $mysqli->error . '<br />'; continue; } } if ( $queryerrors ) { return 'There was an error on File: ' . $filename . '<br />' . $queryerrors; } if( $mysqli && ! $mysqli->error ) { @$mysqli->close(); } return 'Complete dumping database!'; } /** * Export SQL data. * * if directory writable will be make directory inside of directory if not exist, else will be die * * @param string directory, as the directory to put file * @param string $outname as file name just the name * @param string/array $tables_whitelist 'all' = all tables; array('tbl1',...) = only listet tables * @param string $dbhost database host * @param string $dbuser database user * @param string $dbpass database password * @param string $dbname database name * */ function database_backup( $directory, $outname, $tables_whitelist, $dbhost, $dbuser, $dbpass, $dbname ) { // check mysqli extension installed if ( !function_exists('mysqli_connect') ) { die('This scripts need mysql extension to be running properly! Please resolve!'); } $mysqli = @new mysqli($dbhost, $dbuser, $dbpass, $dbname); if ( $mysqli->connect_error ) { print_r( $mysqli->connect_error ); return false; } $dir = $directory; $result = '<p>Could not create backup directory on :'.$dir.' Please Please make sure you have set Directory on 755 or 777 for a while.</p>'; $res = true; if ( !is_dir( $dir ) ) { if( !@mkdir( $dir, 755 ) ) { $res = false; } } $n = 1; if ( $res ) { $name = $outname.'_'.date('Y-m-d-H-i-s'); $fullname = $dir.'/'.$name.'.sql'; # full structures if ( !$mysqli->error ) { $sql = "SHOW TABLES"; $show = $mysqli->query($sql); while ( $row = $show->fetch_array() ) { if ( $tables_whitelist=='all' || in_array($row[0], (array)$tables_whitelist) ) { $tables[] = $row[0]; } } if ( !empty( $tables ) ) { // Cycle through $return = ''; foreach ( $tables as $table ) { $result = $mysqli->query('SELECT * FROM '.$table); $num_fields = $result->field_count; $row2 = $mysqli->query('SHOW CREATE TABLE '.$table ); $row2 = $row2->fetch_row(); $return .= "\n -- --------------------------------------------------------- -- -- Table structure for table : `{$table}` -- -- --------------------------------------------------------- ".$row2[1].";\n"; for ($i = 0; $i < $num_fields; $i++) { $n = 1 ; while ( $row = $result->fetch_row() ) { if ( $n++ == 1 ) { # set the first statements $return .= " -- -- Dumping data for table `{$table}` -- "; /** * Get structural of fields each tables */ $array_field = array(); #reset ! important to resetting when loop while ( $field = $result->fetch_field() ) # get field { $array_field[] = '`'.$field->name.'`'; } $array_f[$table] = $array_field; // $array_f = $array_f; # endwhile $array_field = implode(', ', $array_f[$table]); #implode arrays $return .= "INSERT INTO `{$table}` ({$array_field}) VALUES\n("; } else { $return .= '('; } for ($j=0; $j<$num_fields; $j++) { $row[$j] = str_replace('\'','\'\'', preg_replace("/\n/","\\n", $row[$j] ) ); if ( isset( $row[$j] ) ) { $return .= is_numeric( $row[$j] ) ? $row[$j] : '\''.$row[$j].'\'' ; } else { $return.= '\'\''; } if ( $j<($num_fields-1) ) { $return.= ', '; } } $return.= "),\n"; } # check matching @preg_match("/\),\n/", $return, $match, false, -3); # check match if ( isset( $match[0] ) ) { $return = substr_replace( $return, ";\n", -2); } } $return .= "\n"; } $return = "-- --------------------------------------------------------- -- -- Simple SQL Dump -- -- -- Host Connection Info: ".$mysqli->host_info." -- Generation Time: ".date('F d, Y \a\t H:i A ( e )')." -- Server version: ".$mysqli->server_info." -- PHP Version: ".PHP_VERSION." -- -- ---------------------------------------------------------\n\n SET SQL_MODE = \"NO_AUTO_VALUE_ON_ZERO\"; SET time_zone = \"+00:00\"; /*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */; /*!40101 SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS */; /*!40101 SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION */; /*!40101 SET NAMES utf8 */; ".$return." /*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */; /*!40101 SET CHARACTER_SET_RESULTS=@OLD_CHARACTER_SET_RESULTS */; /*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */;"; # end values result if( @file_put_contents( $fullname, $return ) ) { # 9 as compression levels $result = $name.'.sql'; # show the name } else { $result = '<p>Error when saving the export.</p>'; } } else { $result = '<p>Error when executing database query to export.</p>'.$mysqli->error; } } } else { $result = '<p>Wrong mysqli input</p>'; } if( $mysqli && ! $mysqli->error ) { @$mysqli->close(); } return $result; }
Vegvisir/Nami
tools/db/database.func.php
PHP
gpl-2.0
6,970
#pragma once namespace Calculator { using namespace System; using namespace System::ComponentModel; using namespace System::Collections; using namespace System::Windows::Forms; using namespace System::Data; using namespace System::Drawing; /// <summary> /// Summary for Form1 /// /// WARNING: If you change the name of this class, you will need to change the /// 'Resource File Name' property for the managed resource compiler tool /// associated with all .resx files this class depends on. Otherwise, /// the designers will not be able to interact properly with localized /// resources associated with this form. /// </summary> public ref class Form1 : public System::Windows::Forms::Form { public: Form1(void) { InitializeComponent(); // //TODO: Add the constructor code here // } protected: /// <summary> /// Clean up any resources being used. /// </summary> ~Form1() { if (components) { delete components; } } private: System::Windows::Forms::Button^ button1; protected: private: System::Windows::Forms::Button^ button3; private: System::Windows::Forms::Button^ button4; private: System::Windows::Forms::Button^ button5; private: System::Windows::Forms::Button^ button6; private: System::Windows::Forms::Button^ button7; private: System::Windows::Forms::Button^ button8; private: System::Windows::Forms::Button^ button9; private: System::Windows::Forms::Button^ button10; private: System::Windows::Forms::Button^ button11; private: System::Windows::Forms::Button^ button12; private: System::Windows::Forms::Label^ label1; private: System::Windows::Forms::Button^ button13; private: System::Windows::Forms::Button^ button14; private: System::Windows::Forms::Button^ button15; private: System::Windows::Forms::Button^ button16; private: System::Windows::Forms::Button^ button2; private: System::Windows::Forms::Button^ button17; private: System::Windows::Forms::Button^ button18; private: System::Windows::Forms::Button^ button19; private: System::Windows::Forms::Button^ button20; private: /// <summary> /// Required designer variable. /// </summary> System::ComponentModel::Container ^components; #pragma region Windows Form Designer generated code /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// </summary> void InitializeComponent(void) { this->button1 = (gcnew System::Windows::Forms::Button()); this->button3 = (gcnew System::Windows::Forms::Button()); this->button4 = (gcnew System::Windows::Forms::Button()); this->button5 = (gcnew System::Windows::Forms::Button()); this->button6 = (gcnew System::Windows::Forms::Button()); this->button7 = (gcnew System::Windows::Forms::Button()); this->button8 = (gcnew System::Windows::Forms::Button()); this->button9 = (gcnew System::Windows::Forms::Button()); this->button10 = (gcnew System::Windows::Forms::Button()); this->button11 = (gcnew System::Windows::Forms::Button()); this->button12 = (gcnew System::Windows::Forms::Button()); this->label1 = (gcnew System::Windows::Forms::Label()); this->button13 = (gcnew System::Windows::Forms::Button()); this->button14 = (gcnew System::Windows::Forms::Button()); this->button15 = (gcnew System::Windows::Forms::Button()); this->button16 = (gcnew System::Windows::Forms::Button()); this->button2 = (gcnew System::Windows::Forms::Button()); this->button17 = (gcnew System::Windows::Forms::Button()); this->button18 = (gcnew System::Windows::Forms::Button()); this->button19 = (gcnew System::Windows::Forms::Button()); this->button20 = (gcnew System::Windows::Forms::Button()); this->SuspendLayout(); // // button1 // this->button1->Location = System::Drawing::Point(12, 93); this->button1->Name = L"button1"; this->button1->Size = System::Drawing::Size(60, 33); this->button1->TabIndex = 0; this->button1->Text = L"1"; this->button1->UseVisualStyleBackColor = true; this->button1->Click += gcnew System::EventHandler(this, &Form1::button1_Click); // // button3 // this->button3->Location = System::Drawing::Point(144, 93); this->button3->Name = L"button3"; this->button3->Size = System::Drawing::Size(60, 33); this->button3->TabIndex = 2; this->button3->Text = L"3"; this->button3->UseVisualStyleBackColor = true; this->button3->Click += gcnew System::EventHandler(this, &Form1::button3_Click); // // button4 // this->button4->Location = System::Drawing::Point(12, 132); this->button4->Name = L"button4"; this->button4->Size = System::Drawing::Size(60, 33); this->button4->TabIndex = 3; this->button4->Text = L"4"; this->button4->UseVisualStyleBackColor = true; this->button4->Click += gcnew System::EventHandler(this, &Form1::button4_Click); // // button5 // this->button5->Location = System::Drawing::Point(78, 132); this->button5->Name = L"button5"; this->button5->Size = System::Drawing::Size(60, 33); this->button5->TabIndex = 4; this->button5->Text = L"5"; this->button5->UseVisualStyleBackColor = true; this->button5->Click += gcnew System::EventHandler(this, &Form1::button5_Click); // // button6 // this->button6->Location = System::Drawing::Point(144, 132); this->button6->Name = L"button6"; this->button6->Size = System::Drawing::Size(60, 33); this->button6->TabIndex = 5; this->button6->Text = L"6"; this->button6->UseVisualStyleBackColor = true; this->button6->Click += gcnew System::EventHandler(this, &Form1::button6_Click); // // button7 // this->button7->Location = System::Drawing::Point(12, 171); this->button7->Name = L"button7"; this->button7->Size = System::Drawing::Size(60, 33); this->button7->TabIndex = 6; this->button7->Text = L"7"; this->button7->UseVisualStyleBackColor = true; this->button7->Click += gcnew System::EventHandler(this, &Form1::button7_Click); // // button8 // this->button8->Location = System::Drawing::Point(78, 171); this->button8->Name = L"button8"; this->button8->Size = System::Drawing::Size(60, 33); this->button8->TabIndex = 7; this->button8->Text = L"8"; this->button8->UseVisualStyleBackColor = true; this->button8->Click += gcnew System::EventHandler(this, &Form1::button8_Click); // // button9 // this->button9->Location = System::Drawing::Point(144, 171); this->button9->Name = L"button9"; this->button9->Size = System::Drawing::Size(60, 33); this->button9->TabIndex = 8; this->button9->Text = L"9"; this->button9->UseVisualStyleBackColor = true; this->button9->Click += gcnew System::EventHandler(this, &Form1::button9_Click); // // button10 // this->button10->Location = System::Drawing::Point(12, 210); this->button10->Name = L"button10"; this->button10->Size = System::Drawing::Size(60, 33); this->button10->TabIndex = 9; this->button10->Text = L","; this->button10->UseVisualStyleBackColor = true; this->button10->Click += gcnew System::EventHandler(this, &Form1::button10_Click); this->commaIsClickble = true; // // button11 // this->button11->Location = System::Drawing::Point(78, 210); this->button11->Name = L"button11"; this->button11->Size = System::Drawing::Size(60, 33); this->button11->TabIndex = 10; this->button11->Text = L"0"; this->button11->UseVisualStyleBackColor = true; this->button11->Click += gcnew System::EventHandler(this, &Form1::button11_Click); // // button12 // this->button12->Location = System::Drawing::Point(144, 210); this->button12->Name = L"button12"; this->button12->Size = System::Drawing::Size(60, 33); this->button12->TabIndex = 11; this->button12->Text = L"="; this->button12->UseVisualStyleBackColor = true; this->button12->Click += gcnew System::EventHandler(this, &Form1::button12_Click); // // label1 // this->label1->AutoSize = true; this->label1->BackColor = System::Drawing::Color::Transparent; this->label1->BorderStyle = System::Windows::Forms::BorderStyle::Fixed3D; this->label1->Font = (gcnew System::Drawing::Font(L"Microsoft Sans Serif", 8, System::Drawing::FontStyle::Bold, System::Drawing::GraphicsUnit::Millimeter, static_cast<System::Byte>(204))); this->label1->ForeColor = System::Drawing::Color::CornflowerBlue; this->label1->Location = System::Drawing::Point(22, 9); this->label1->MinimumSize = System::Drawing::Size(250, 30); this->label1->Name = L"label1"; this->label1->RightToLeft = System::Windows::Forms::RightToLeft::No; this->label1->Size = System::Drawing::Size(250, 37); this->label1->TabIndex = 12; this->label1->Text = L"0"; this->label1->TextAlign = System::Drawing::ContentAlignment::MiddleRight; this->label1->Click += gcnew System::EventHandler(this, &Form1::label1_Click); // // button13 // this->button13->Location = System::Drawing::Point(212, 93); this->button13->Name = L"button13"; this->button13->Size = System::Drawing::Size(60, 33); this->button13->TabIndex = 13; this->button13->Text = L"+"; this->button13->UseVisualStyleBackColor = true; this->button13->Click += gcnew System::EventHandler(this, &Form1::button13_Click); // // button14 // this->button14->Location = System::Drawing::Point(212, 132); this->button14->Name = L"button14"; this->button14->Size = System::Drawing::Size(60, 33); this->button14->TabIndex = 14; this->button14->Text = L"-"; this->button14->UseVisualStyleBackColor = true; this->button14->Click += gcnew System::EventHandler(this, &Form1::button14_Click); // // button15 // this->button15->Location = System::Drawing::Point(212, 171); this->button15->Name = L"button15"; this->button15->Size = System::Drawing::Size(60, 33); this->button15->TabIndex = 15; this->button15->Text = L"*"; this->button15->UseVisualStyleBackColor = true; this->button15->Click += gcnew System::EventHandler(this, &Form1::button15_Click); // // button16 // this->button16->Location = System::Drawing::Point(212, 210); this->button16->Name = L"button16"; this->button16->Size = System::Drawing::Size(60, 33); this->button16->TabIndex = 16; this->button16->Text = L"/"; this->button16->UseVisualStyleBackColor = true; this->button16->Click += gcnew System::EventHandler(this, &Form1::button16_Click); // // button2 // this->button2->Location = System::Drawing::Point(78, 93); this->button2->Name = L"button2"; this->button2->Size = System::Drawing::Size(60, 33); this->button2->TabIndex = 17; this->button2->Text = L"2"; this->button2->UseVisualStyleBackColor = true; this->button2->Click += gcnew System::EventHandler(this, &Form1::button2_Click); // // button17 // this->button17->Location = System::Drawing::Point(212, 54); this->button17->Name = L"button17"; this->button17->Size = System::Drawing::Size(60, 33); this->button17->TabIndex = 18; this->button17->Text = L"C"; this->button17->UseVisualStyleBackColor = true; this->button17->Click += gcnew System::EventHandler(this, &Form1::button17_Click); // // button18 // this->button18->Location = System::Drawing::Point(146, 54); this->button18->Name = L"button18"; this->button18->Size = System::Drawing::Size(60, 33); this->button18->TabIndex = 19; this->button18->Text = L"^n"; this->button18->UseVisualStyleBackColor = true; this->button18->Click += gcnew System::EventHandler(this, &Form1::button18_Click); // // button19 // this->button19->Location = System::Drawing::Point(78, 54); this->button19->Name = L"button19"; this->button19->Size = System::Drawing::Size(60, 33); this->button19->TabIndex = 20; this->button19->Text = L"Soon"; this->button19->UseVisualStyleBackColor = true; this->button19->Click += gcnew System::EventHandler(this, &Form1::button19_Click); // // button20 // this->button20->Location = System::Drawing::Point(12, 54); this->button20->Name = L"button20"; this->button20->Size = System::Drawing::Size(60, 33); this->button20->TabIndex = 21; this->button20->Text = L"Soon"; this->button20->UseVisualStyleBackColor = true; this->button20->Click += gcnew System::EventHandler(this, &Form1::button20_Click); // // Form1 // this->AutoScaleDimensions = System::Drawing::SizeF(6, 13); this->AutoScaleMode = System::Windows::Forms::AutoScaleMode::Font; this->ClientSize = System::Drawing::Size(284, 262); this->Controls->Add(this->button20); this->Controls->Add(this->button19); this->Controls->Add(this->button18); this->Controls->Add(this->button17); this->Controls->Add(this->button2); this->Controls->Add(this->button16); this->Controls->Add(this->button15); this->Controls->Add(this->button14); this->Controls->Add(this->button13); this->Controls->Add(this->label1); this->Controls->Add(this->button12); this->Controls->Add(this->button11); this->Controls->Add(this->button10); this->Controls->Add(this->button9); this->Controls->Add(this->button8); this->Controls->Add(this->button7); this->Controls->Add(this->button6); this->Controls->Add(this->button5); this->Controls->Add(this->button4); this->Controls->Add(this->button3); this->Controls->Add(this->button1); this->Name = L"Form1"; this->Text = L"Form1"; this->ResumeLayout(false); this->PerformLayout(); } #pragma endregion private: double currentNum; private: double firstNum; private: enum class Actions { PLUS, MINUS, MULTIPLY, BAJANAC, POWER}; private: Actions action; private: Boolean cleanable; private: Boolean commaIsClickble; private: static const int CORRECT_SIZE = 10; private: System::Void label1_Click(System::Object^ sender, System::EventArgs^ e) { } private: System::Void button1_Click(System::Object^ sender, System::EventArgs^ e) { this->increaseNumber("1"); } private: System::Void button2_Click(System::Object^ sender, System::EventArgs^ e) { this->increaseNumber("2"); } private: System::Void button3_Click(System::Object^ sender, System::EventArgs^ e) { this->increaseNumber("3"); } private: System::Void button4_Click(System::Object^ sender, System::EventArgs^ e) { this->increaseNumber("4"); } private: System::Void button5_Click(System::Object^ sender, System::EventArgs^ e) { this->increaseNumber("5"); } private: System::Void button6_Click(System::Object^ sender, System::EventArgs^ e) { this->increaseNumber("6"); } private: System::Void button7_Click(System::Object^ sender, System::EventArgs^ e) { this->increaseNumber("7"); } private: System::Void button8_Click(System::Object^ sender, System::EventArgs^ e) { this->increaseNumber("8"); } private: System::Void button9_Click(System::Object^ sender, System::EventArgs^ e) { this->increaseNumber("9"); } private: System::Void button11_Click(System::Object^ sender, System::EventArgs^ e) { this->increaseNumber("0"); } // button for ',' sign private: System::Void button10_Click(System::Object^ sender, System::EventArgs^ e) { if(this->commaIsClickble) { this->increaseNumber(","); this->commaIsClickble = false; } } // increases the label1's value by the given value. private: System::Void increaseNumber(String^ num) { if(this->cleanable) { this->label1->Text = "0"; this->cleanable = false; } if (this->labelContentIsCorrect()) { if ("0" == this->label1->Text) { if("," == num) { this->label1->Text += num; } else { this->label1->Text = num; } } else { this->label1->Text += num; } this->currentNum = Convert::ToDouble(this->label1->Text); } } private: System::Double checkResultCorrectation(Double result) { String^ resultStr = Convert::ToString(result); // while result is incorrect while(resultStr->Length > CORRECT_SIZE) { //result = Convert::ToDouble(resultStr->Substring(0,CORRECT_SIZE)); if(Convert::ToInt16(resultStr[CORRECT_SIZE]) >= 5) { if(resultStr->Contains(",")) { //TODO: handle the case } else { //TODO: handle the case //result = System::Math::Pow(result, CORRECT_SIZE) - 1; } } resultStr = Convert::ToString(result); } return result; } // TODO: Add comment private: System::Boolean labelContentIsCorrect() { // if label content is incorrect if(this->label1->Text->Length >= CORRECT_SIZE) { return false; } return true; } // click on '=' button private: System::Void button12_Click(System::Object^ sender, System::EventArgs^ e) { double result; switch ( this->action ) { case Actions::PLUS: result = this->firstNum + this->currentNum; break; case Actions::MINUS: result = this->firstNum - this->currentNum; break; case Actions::MULTIPLY: result = this->firstNum * this->currentNum; break; case Actions::BAJANAC: result = this->firstNum / this->currentNum; break; case Actions::POWER: result = System::Math::Pow(this->firstNum, this->currentNum); break; default: //handle this case. ; } //result = this->checkResultCorrectation(result); this->label1->Text = Convert::ToString(result); this->currentNum = result; resetSomeValue(); } //TODO: rename this function. private: System::Void resetSomeValue() { this->cleanable = true; this->commaIsClickble = true; } // click on '+' button private: System::Void button13_Click(System::Object^ sender, System::EventArgs^ e) { this->firstNum = this->currentNum; resetSomeValue(); this->action = Actions::PLUS; } // click on '-' button private: System::Void button14_Click(System::Object^ sender, System::EventArgs^ e) { this->firstNum = this->currentNum; resetSomeValue(); this->action = Actions::MINUS; } // click on '*' button private: System::Void button15_Click(System::Object^ sender, System::EventArgs^ e) { this->firstNum = this->currentNum; resetSomeValue(); this->action = Actions::MULTIPLY; } // click on '/' button private: System::Void button16_Click(System::Object^ sender, System::EventArgs^ e) { this->firstNum = this->currentNum; resetSomeValue(); this->action = Actions::BAJANAC; } // click on 'clear' button private: System::Void button17_Click(System::Object^ sender, System::EventArgs^ e) { this->label1->Text = "0"; resetSomeValue(); this->firstNum = 0; this->currentNum = 0; } // click on '^n' button private: System::Void button18_Click(System::Object^ sender, System::EventArgs^ e) { this->firstNum = this->currentNum; resetSomeValue(); this->action = Actions::POWER; } private: System::Void button19_Click(System::Object^ sender, System::EventArgs^ e) { } private: System::Void button20_Click(System::Object^ sender, System::EventArgs^ e) { } }; }
M7Arman/Calculator
Calculator/Form1.h
C
gpl-2.0
19,254
!COMPILER-GENERATED INTERFACE MODULE: Fri Mar 11 15:46:19 2016 MODULE INPUT1__genmod INTERFACE SUBROUTINE INPUT1 END SUBROUTINE INPUT1 END INTERFACE END MODULE INPUT1__genmod
lanucara/specfem3d_globe_cineca
obj/input1__genmod.f90
FORTRAN
gpl-2.0
245
<?php /** * Uses the Porter Stemmer algorithm to find word roots. * * Adapted from Joomla com_finder component. * Based on the Porter stemmer algorithm: * <https://tartarus.org/martin/PorterStemmer/c.txt> * * @author Lee Garner <lee@leegarner.com> * @copyright Copyright (C) 2017 Lee Garner <lee@leegarner.com> * @copyright Copyright (C) 2005 - 2017 Open Source Matters, Inc. All rights reserved. * @package searcher * @version 0.0.1 * @license http://opensource.org/licenses/gpl-2.0.php * GNU Public License v2 or later * @filesource */ namespace Searcher; /** * Porter English stemmer class for the Finder indexer package. * * This class was adapted from one written by Richard Heyes. * See copyright and link information above. */ class StemmerPorter_en extends Stemmer { /** * Regex for matching a consonant. * @var string */ private static $regex_consonant = '(?:[bcdfghjklmnpqrstvwxz]|(?<=[aeiou])y|^y)'; /** * Regex for matching a vowel * @var string */ private static $regex_vowel = '(?:[aeiou]|(?<![aeiou])y)'; /** * Method to stem a token and return the root. * * @param string $token The token to stem. * @param string $lang The language of the token. * @return string The root token. */ public function stem($token, $lang='en') { global $_CONF; // Check if the token is long enough to merit stemming. if (strlen($token) <= self::$min_word_len) { return $token; } // Check if the language is English or All. /*if ($lang !== 'en' && $lang != '*') { return $token; }*/ // Stem the token if it is not in the cache. if (!isset($this->cache[$lang][$token])) { // Stem the token. $result = trim($token); $result = self::step1ab($result); $result = self::step1c($result); $result = self::step2($result); $result = self::step3($result); $result = self::step4($result); $result = self::step5($result); $result = trim($result); // Add the token to the cache. $this->cache[$lang][$token] = $result; } return $this->cache[$lang][$token]; } /** * step1ab() gets rid of plurals and -ed or -ing. e.g. * * caresses -> caress * ponies -> poni * ties -> ti * caress -> caress * cats -> cat * * feed -> feed * agreed -> agree * disabled -> disable * * matting -> mat * mating -> mate * meeting -> meet * milling -> mill * messing -> mess * meetings -> meet * * @param string $word The token to stem. * @return string */ private static function step1ab($word) { // Part a if (substr($word, -1) == 's') { self::replace($word, 'sses', 'ss') or self::replace($word, 'ies', 'i') or self::replace($word, 'ss', 'ss') or self::replace($word, 's', ''); } // Part b if (substr($word, -2, 1) != 'e' or !self::replace($word, 'eed', 'ee', 0)) { // First rule $v = self::$regex_vowel; // Words ending with ing and ed // Note use of && and OR, for precedence reasons if (preg_match("#$v+#", substr($word, 0, -3)) && self::replace($word, 'ing', '') or preg_match("#$v+#", substr($word, 0, -2)) && self::replace($word, 'ed', '')) { // If one of above two test successful if (!self::replace($word, 'at', 'ate') and !self::replace($word, 'bl', 'ble') and !self::replace($word, 'iz', 'ize')) { // Double consonant ending if (self::doubleConsonant($word) and substr($word, -2) != 'll' and substr($word, -2) != 'ss' and substr($word, -2) != 'zz') { $word = substr($word, 0, -1); } elseif (self::m($word) == 1 and self::cvc($word)) { $word .= 'e'; } } } } return $word; } /** * step1c() turns terminal y to i when there is another vowel in the stem. * * @param string $word The token to stem. * @return string */ private static function step1c($word) { $v = self::$regex_vowel; if (substr($word, -1) == 'y' && preg_match("#$v+#", substr($word, 0, -1))) { self::replace($word, 'y', 'i'); } return $word; } /** * step2() maps double suffices to single ones. so -izationi * ( = -ize plus -ation) maps to -ize etc. * Note that the string before the suffix must give m() > 0. * * @param string $word The token to stem. * @return string */ private static function step2($word) { switch (substr($word, -2, 1)) { case 'a': self::replace($word, 'ational', 'ate', 0) or self::replace($word, 'tional', 'tion', 0); break; case 'c': self::replace($word, 'enci', 'ence', 0) or self::replace($word, 'anci', 'ance', 0); break; case 'e': self::replace($word, 'izer', 'ize', 0); break; case 'g': self::replace($word, 'logi', 'log', 0); break; case 'l': self::replace($word, 'entli', 'ent', 0) or self::replace($word, 'ousli', 'ous', 0) or self::replace($word, 'alli', 'al', 0) or self::replace($word, 'bli', 'ble', 0) or self::replace($word, 'eli', 'e', 0); break; case 'o': self::replace($word, 'ization', 'ize', 0) or self::replace($word, 'ation', 'ate', 0) or self::replace($word, 'ator', 'ate', 0); break; case 's': self::replace($word, 'iveness', 'ive', 0) or self::replace($word, 'fulness', 'ful', 0) or self::replace($word, 'ousness', 'ous', 0) or self::replace($word, 'alism', 'al', 0); break; case 't': self::replace($word, 'biliti', 'ble', 0) or self::replace($word, 'aliti', 'al', 0) or self::replace($word, 'iviti', 'ive', 0); break; } return $word; } /** * step3() deals with -ic-, -full, -ness etc. similar strategy to step2. * * @param string $word The token to stem. * @return string */ private static function step3($word) { switch (substr($word, -2, 1)) { case 'a': self::replace($word, 'ical', 'ic', 0); break; case 's': self::replace($word, 'ness', '', 0); break; case 't': self::replace($word, 'icate', 'ic', 0) or self::replace($word, 'iciti', 'ic', 0); break; case 'u': self::replace($word, 'ful', '', 0); break; case 'v': self::replace($word, 'ative', '', 0); break; case 'z': self::replace($word, 'alize', 'al', 0); break; } return $word; } /** * step4() takes off -ant, -ence etc., in context <c>vcvc<v>. * * @param string $word The token to stem. * @return string */ private static function step4($word) { switch (substr($word, -2, 1)) { case 'a': self::replace($word, 'al', '', 1); break; case 'c': self::replace($word, 'ance', '', 1) or self::replace($word, 'ence', '', 1); break; case 'e': self::replace($word, 'er', '', 1); break; case 'i': self::replace($word, 'ic', '', 1); break; case 'l': self::replace($word, 'able', '', 1) or self::replace($word, 'ible', '', 1); break; case 'n': self::replace($word, 'ant', '', 1) or self::replace($word, 'ement', '', 1) or self::replace($word, 'ment', '', 1) or self::replace($word, 'ent', '', 1); break; case 'o': if (substr($word, -4) == 'tion' or substr($word, -4) == 'sion') { self::replace($word, 'ion', '', 1); } else { self::replace($word, 'ou', '', 1); } break; case 's': self::replace($word, 'ism', '', 1); break; case 't': self::replace($word, 'ate', '', 1) or self::replace($word, 'iti', '', 1); break; case 'u': self::replace($word, 'ous', '', 1); break; case 'v': self::replace($word, 'ive', '', 1); break; case 'z': self::replace($word, 'ize', '', 1); break; } return $word; } /** * step5() removes a final -e if m() > 1, and changes -ll to -l if m() > 1. * * @param string $word The token to stem. * @return string */ private static function step5($word) { // Part a if (substr($word, -1) == 'e') { if (self::m(substr($word, 0, -1)) > 1) { self::replace($word, 'e', ''); } elseif (self::m(substr($word, 0, -1)) == 1) { if (!self::cvc(substr($word, 0, -1))) { self::replace($word, 'e', ''); } } } // Part b if (self::m($word) > 1 and self::doubleConsonant($word) and substr($word, -1) == 'l') { $word = substr($word, 0, -1); } return $word; } /** * Replaces the first string with the second, at the end of the string. If * third arg is given, then the preceding string must match that m count * at least. * * @param string &$str String to check * @param string $check Ending to check for * @param string $repl Replacement string * @param integer $m Optional minimum number of m() to meet * * @return boolean Whether the $check string was at the end * of the $str string. True does not necessarily mean * that it was replaced. */ private static function replace(&$str, $check, $repl, $m = null) { $len = 0 - strlen($check); if (substr($str, $len) == $check) { $substr = substr($str, 0, $len); if (is_null($m) or self::m($substr) > $m) { $str = $substr . $repl; } return true; } return false; } /** * m() - measures the number of consonant sequences in $str. if c is * a consonant sequence and v a vowel sequence, and <..> indicates * arbitrary presence, * * <c><v> gives 0 * <c>vc<v> gives 1 * <c>vcvc<v> gives 2 * <c>vcvcvc<v> gives 3 * * @param string $str The string to return the m count for * @return integer The m count */ private static function m($str) { $c = self::$regex_consonant; $v = self::$regex_vowel; $str = preg_replace("#^$c+#", '', $str); $str = preg_replace("#$v+$#", '', $str); preg_match_all("#($v+$c+)#", $str, $matches); return count($matches[1]); } /** * Returns true/false as to whether the given string contains two * of the same consonant next to each other at the end of the string. * * @param string $str String to check * @return boolean Result */ private static function doubleConsonant($str) { $c = self::$regex_consonant; return preg_match("#$c{2}$#", $str, $matches) and $matches[0]{0} == $matches[0]{1}; } /** * Checks for ending CVC sequence where second C is not W, X or Y * * @param string $str String to check * @return boolean Result */ private static function cvc($str) { $c = self::$regex_consonant; $v = self::$regex_vowel; return preg_match("#($c$v$c)$#", $str, $matches) && strlen($matches[1]) == 3 && $matches[1]{2} != 'w' && $matches[1]{2} != 'x' && $matches[1]{2} != 'y'; } } ?>
glFusion/searcher
classes/stemmer/Porter_en.class.php
PHP
gpl-2.0
13,378
package ch.logixisland.anuto.view.game; import android.app.Activity; import android.os.Bundle; import android.os.Handler; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.Button; import android.widget.TextView; import java.util.List; import ch.logixisland.anuto.AnutoApplication; import ch.logixisland.anuto.GameFactory; import ch.logixisland.anuto.R; import ch.logixisland.anuto.business.tower.TowerControl; import ch.logixisland.anuto.business.tower.TowerInfo; import ch.logixisland.anuto.business.tower.TowerSelector; import ch.logixisland.anuto.entity.tower.TowerInfoValue; import ch.logixisland.anuto.entity.tower.TowerStrategy; import ch.logixisland.anuto.util.StringUtils; import ch.logixisland.anuto.view.AnutoFragment; public class TowerInfoFragment extends AnutoFragment implements View.OnClickListener, TowerSelector.TowerInfoView { private final TowerSelector mTowerSelector; private final TowerControl mTowerControl; private Handler mHandler; private TextView txt_level; private TextView[] txt_property = new TextView[5]; private TextView[] txt_property_text = new TextView[5]; private Button btn_strategy; private Button btn_lock_target; private Button btn_enhance; private Button btn_upgrade; private Button btn_sell; private boolean mVisible = true; public TowerInfoFragment() { GameFactory factory = AnutoApplication.getInstance().getGameFactory(); mTowerSelector = factory.getTowerSelector(); mTowerControl = factory.getTowerControl(); } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View v = inflater.inflate(R.layout.fragment_tower_info, container, false); txt_level = (TextView) v.findViewById(R.id.txt_level); txt_property[0] = (TextView) v.findViewById(R.id.txt_property1); txt_property[1] = (TextView) v.findViewById(R.id.txt_property2); txt_property[2] = (TextView) v.findViewById(R.id.txt_property3); txt_property[3] = (TextView) v.findViewById(R.id.txt_property4); txt_property[4] = (TextView) v.findViewById(R.id.txt_property5); TextView txt_level_text = (TextView) v.findViewById(R.id.txt_level_text); txt_level_text.setText(getResources().getString(R.string.level) + ":"); txt_property_text[0] = (TextView) v.findViewById(R.id.txt_property_text1); txt_property_text[1] = (TextView) v.findViewById(R.id.txt_property_text2); txt_property_text[2] = (TextView) v.findViewById(R.id.txt_property_text3); txt_property_text[3] = (TextView) v.findViewById(R.id.txt_property_text4); txt_property_text[4] = (TextView) v.findViewById(R.id.txt_property_text5); btn_strategy = (Button) v.findViewById(R.id.btn_strategy); btn_lock_target = (Button) v.findViewById(R.id.btn_lock_target); btn_upgrade = (Button) v.findViewById(R.id.btn_upgrade); btn_enhance = (Button) v.findViewById(R.id.btn_enhance); btn_sell = (Button) v.findViewById(R.id.btn_sell); btn_strategy.setOnClickListener(this); btn_lock_target.setOnClickListener(this); btn_enhance.setOnClickListener(this); btn_upgrade.setOnClickListener(this); btn_sell.setOnClickListener(this); mHandler = new Handler(); return v; } @Override public void onViewCreated(View view, Bundle savedInstanceState) { super.onViewCreated(view, savedInstanceState); TowerInfo towerInfo = mTowerSelector.getTowerInfo(); if (towerInfo != null) { refresh(towerInfo); show(); } } @Override public void onAttach(Activity activity) { super.onAttach(activity); mTowerSelector.setTowerInfoView(this); hide(); } @Override public void onDetach() { super.onDetach(); mTowerSelector.setTowerInfoView(null); mHandler.removeCallbacksAndMessages(null); } @Override public void onClick(View v) { if (v == btn_strategy) { mTowerControl.cycleTowerStrategy(); } if (v == btn_lock_target) { mTowerControl.toggleLockTarget(); } if (v == btn_enhance) { mTowerControl.enhanceTower(); } if (v == btn_upgrade) { mTowerControl.upgradeTower(); } if (v == btn_sell) { mTowerControl.sellTower(); } } @Override public void showTowerInfo(final TowerInfo towerInfo) { mHandler.post(new Runnable() { @Override public void run() { show(); refresh(towerInfo); } }); } @Override public void hideTowerInfo() { mHandler.post(new Runnable() { @Override public void run() { hide(); } }); } private void show() { if (!mVisible) { updateMenuTransparency(); getFragmentManager().beginTransaction() .show(this) .commitAllowingStateLoss(); mVisible = true; } } private void hide() { if (mVisible) { getFragmentManager().beginTransaction() .hide(this) .commitAllowingStateLoss(); mVisible = false; } } private void refresh(TowerInfo towerInfo) { txt_level.setText(towerInfo.getLevel() + " / " + towerInfo.getLevelMax()); List<TowerInfoValue> properties = towerInfo.getProperties(); for (int i = 0; i < properties.size(); i++) { TowerInfoValue property = properties.get(i); txt_property_text[i].setText(getString(property.getTextId()) + ":"); txt_property[i].setText(StringUtils.formatSuffix(property.getValue())); } for (int i = properties.size(); i < txt_property.length; i++) { txt_property_text[i].setText(""); txt_property[i].setText(""); } if (towerInfo.getEnhanceCost() > 0) { btn_enhance.setText(StringUtils.formatSwitchButton( getString(R.string.enhance), StringUtils.formatSuffix(towerInfo.getEnhanceCost())) ); } else { btn_enhance.setText(getString(R.string.enhance)); } if (towerInfo.getUpgradeCost() > 0) { btn_upgrade.setText(StringUtils.formatSwitchButton( getString(R.string.upgrade), StringUtils.formatSuffix(towerInfo.getUpgradeCost())) ); } else { btn_upgrade.setText(getString(R.string.upgrade)); } btn_sell.setText(StringUtils.formatSwitchButton( getString(R.string.sell), StringUtils.formatSuffix(towerInfo.getValue())) ); btn_upgrade.setEnabled(towerInfo.isUpgradeable()); btn_enhance.setEnabled(towerInfo.isEnhanceable()); btn_sell.setEnabled(towerInfo.isSellable()); if (towerInfo.canLockTarget()) { btn_lock_target.setText(StringUtils.formatSwitchButton( getString(R.string.lock_target), StringUtils.formatBoolean(towerInfo.doesLockTarget(), getResources())) ); btn_lock_target.setEnabled(true); } else { btn_lock_target.setText(getString(R.string.lock_target)); btn_lock_target.setEnabled(false); } if (towerInfo.hasStrategy()) { btn_strategy.setText(StringUtils.formatSwitchButton( getString(R.string.strategy), getStrategyString(towerInfo.getStrategy())) ); btn_strategy.setEnabled(true); } else { btn_strategy.setText(getString(R.string.strategy)); btn_strategy.setEnabled(false); } } private String getStrategyString(TowerStrategy strategy) { switch (strategy) { case Closest: return getString(R.string.strategy_closest); case Weakest: return getString(R.string.strategy_weakest); case Strongest: return getString(R.string.strategy_strongest); case First: return getString(R.string.strategy_first); case Last: return getString(R.string.strategy_last); } throw new RuntimeException("Unknown strategy!"); } }
oojeiph/android-anuto
app/src/main/java/ch/logixisland/anuto/view/game/TowerInfoFragment.java
Java
gpl-2.0
8,699
//***************************************************************************** // // File Name : 'global.h' // Title : AVR project global include // Author : Pascal Stang // Created : 7/12/2001 // Revised : 9/30/2002 // Version : 1.1 // Target MCU : Atmel AVR series // Editor Tabs : 4 // // Description : This include file is designed to contain items useful to all // code files and projects. // // This code is distributed under the GNU Public License // which can be found at http://www.gnu.org/licenses/gpl.txt // //***************************************************************************** #ifndef GLOBAL_H #define GLOBAL_H // global AVRLIB defines #include "avrlibdefs.h" // global AVRLIB types definitions #include "avrlibtypes.h" // project/system dependent defines #define RPRINTF_COMPLEX // CPU clock speed //#define F_CPU 16000000 // 16MHz processor //#define F_CPU 14745000 // 14.745MHz processor //#define F_CPU 8000000 // 8MHz processor //#define F_CPU 7372800 // 7.37MHz processor //#define F_CPU 4000000 // 4MHz processor //#define F_CPU 3686400 // 3.69MHz processor #define CYCLES_PER_US ((F_CPU+500000)/1000000) // cpu cycles per microsecond #endif
ConiKost/GLCD2USB
ks0108/global.h
C
gpl-2.0
1,369
/* * drivers/i2c/busses/i2c-tegra.c * * Copyright (C) 2010 Google, Inc. * Author: Colin Cross <ccross@android.com> * * Copyright (C) 2010-2016 NVIDIA Corporation. All rights reserved. * * This software is licensed under the terms of the GNU General Public * License version 2, as published by the Free Software Foundation, and * may be copied, distributed, and modified under those terms. * * 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. * */ #include <linux/kernel.h> #include <linux/init.h> #include <linux/platform_device.h> #include <linux/clk.h> #include <linux/err.h> #include <linux/i2c.h> #include <linux/i2c-algo-bit.h> #include <linux/i2c-gpio.h> #include <linux/io.h> #include <linux/interrupt.h> #include <linux/gpio.h> #include <linux/delay.h> #include <linux/pm_runtime.h> #include <linux/slab.h> #include <linux/i2c-tegra.h> #include <linux/of_device.h> #include <linux/of_gpio.h> #include <linux/of_i2c.h> #include <linux/module.h> #include <linux/clk/tegra.h> #include <linux/spinlock.h> #include <linux/clk/tegra.h> #include <linux/tegra-pm.h> #include <linux/pinctrl/consumer.h> #include <linux/pinctrl/pinconf-tegra.h> #include <linux/tegra_prod.h> #include <asm/unaligned.h> #define TEGRA_I2C_TIMEOUT (msecs_to_jiffies(1000)) #define TEGRA_I2C_RETRIES 3 #define BYTES_PER_FIFO_WORD 4 #define I2C_CNFG 0x000 #define I2C_CNFG_DEBOUNCE_CNT_SHIFT 12 #define I2C_CNFG_PACKET_MODE_EN (1<<10) #define I2C_CNFG_NEW_MASTER_FSM (1<<11) #define I2C_CNFG_MULTI_MASTER_MODE (1<<17) #define I2C_STATUS 0x01C #define I2C_STATUS_BUSY (1<<8) #define I2C_SL_CNFG 0x020 #define I2C_SL_CNFG_NACK (1<<1) #define I2C_SL_CNFG_NEWSL (1<<2) #define I2C_SL_ADDR1 0x02c #define I2C_SL_ADDR2 0x030 #define I2C_TX_FIFO 0x050 #define I2C_RX_FIFO 0x054 #define I2C_PACKET_TRANSFER_STATUS 0x058 #define I2C_FIFO_CONTROL 0x05c #define I2C_FIFO_CONTROL_TX_FLUSH (1<<1) #define I2C_FIFO_CONTROL_RX_FLUSH (1<<0) #define I2C_FIFO_CONTROL_TX_TRIG_SHIFT 5 #define I2C_FIFO_CONTROL_RX_TRIG_SHIFT 2 #define I2C_FIFO_STATUS 0x060 #define I2C_FIFO_STATUS_TX_MASK 0xF0 #define I2C_FIFO_STATUS_TX_SHIFT 4 #define I2C_FIFO_STATUS_RX_MASK 0x0F #define I2C_FIFO_STATUS_RX_SHIFT 0 #define I2C_INT_MASK 0x064 #define I2C_INT_STATUS 0x068 #define I2C_INT_BUS_CLEAR_DONE (1<<11) #define I2C_INT_PACKET_XFER_COMPLETE (1<<7) #define I2C_INT_ALL_PACKETS_XFER_COMPLETE (1<<6) #define I2C_INT_TX_FIFO_OVERFLOW (1<<5) #define I2C_INT_RX_FIFO_UNDERFLOW (1<<4) #define I2C_INT_NO_ACK (1<<3) #define I2C_INT_ARBITRATION_LOST (1<<2) #define I2C_INT_TX_FIFO_DATA_REQ (1<<1) #define I2C_INT_RX_FIFO_DATA_REQ (1<<0) #define I2C_CLK_DIVISOR 0x06c #define I2C_CLK_DIVISOR_STD_FAST_MODE_SHIFT 16 #define I2C_CLK_MULTIPLIER_STD_FAST_MODE 8 #define DVC_CTRL_REG1 0x000 #define DVC_CTRL_REG1_INTR_EN (1<<10) #define DVC_CTRL_REG2 0x004 #define DVC_CTRL_REG3 0x008 #define DVC_CTRL_REG3_SW_PROG (1<<26) #define DVC_CTRL_REG3_I2C_DONE_INTR_EN (1<<30) #define DVC_STATUS 0x00c #define DVC_STATUS_I2C_DONE_INTR (1<<30) #define I2C_ERR_NONE 0x00 #define I2C_ERR_NO_ACK 0x01 #define I2C_ERR_ARBITRATION_LOST 0x02 #define I2C_ERR_UNKNOWN_INTERRUPT 0x04 #define I2C_ERR_UNEXPECTED_STATUS 0x08 #define PACKET_HEADER0_HEADER_SIZE_SHIFT 28 #define PACKET_HEADER0_PACKET_ID_SHIFT 16 #define PACKET_HEADER0_CONT_ID_SHIFT 12 #define PACKET_HEADER0_CONT_ID_MASK 0xF #define PACKET_HEADER0_PROTOCOL_I2C (1<<4) #define I2C_HEADER_HIGHSPEED_MODE (1<<22) #define I2C_HEADER_CONT_ON_NAK (1<<21) #define I2C_HEADER_SEND_START_BYTE (1<<20) #define I2C_HEADER_READ (1<<19) #define I2C_HEADER_10BIT_ADDR (1<<18) #define I2C_HEADER_IE_ENABLE (1<<17) #define I2C_HEADER_REPEAT_START (1<<16) #define I2C_HEADER_CONTINUE_XFER (1<<15) #define I2C_HEADER_MASTER_ADDR_SHIFT 12 #define I2C_HEADER_SLAVE_ADDR_SHIFT 1 #define I2C_BUS_CLEAR_CNFG 0x084 #define I2C_BC_SCLK_THRESHOLD (9<<16) #define I2C_BC_STOP_COND (1<<2) #define I2C_BC_TERMINATE (1<<1) #define I2C_BC_ENABLE (1<<0) #define I2C_BUS_CLEAR_STATUS 0x088 #define I2C_BC_STATUS (1<<0) #define I2C_CONFIG_LOAD 0x08C #define I2C_MSTR_CONFIG_LOAD (1 << 0) #define I2C_SLV_CONFIG_LOAD (1 << 1) #define I2C_TIMEOUT_CONFIG_LOAD (1 << 2) #define SL_ADDR1(addr) (addr & 0xff) #define SL_ADDR2(addr) ((addr >> 8) & 0xff) #define MAX_BUSCLEAR_CLOCK (9 * 8 + 1) #define I2C_MAX_TRANSFER_LEN 4096 /* * msg_end_type: The bus control which need to be send at end of transfer. * @MSG_END_STOP: Send stop pulse at end of transfer. * @MSG_END_REPEAT_START: Send repeat start at end of transfer. * @MSG_END_CONTINUE: The following on message is coming and so do not send * stop or repeat start. */ enum msg_end_type { MSG_END_STOP, MSG_END_REPEAT_START, MSG_END_CONTINUE, }; struct tegra_i2c_chipdata { bool timeout_irq_occurs_before_bus_inactive; bool has_xfer_complete_interrupt; bool has_hw_arb_support; bool has_fast_clock; bool has_clk_divisor_std_fast_mode; bool has_continue_xfer_support; u16 clk_divisor_std_fast_mode; u16 clk_divisor_fast_plus_mode; u16 clk_divisor_hs_mode; int clk_multiplier_hs_mode; bool has_config_load_reg; bool has_multi_master_en_bit; }; /** * struct tegra_i2c_dev - per device i2c context * @dev: device reference for power management * @adapter: core i2c layer adapter information * @div_clk: clock reference for div clock of i2c controller. * @fast_clk: clock reference for fast clock of i2c controller. * @base: ioremapped registers cookie * @cont_id: i2c controller id, used for for packet header * @irq: irq number of transfer complete interrupt * @is_dvc: identifies the DVC i2c controller, has a different register layout * @msg_complete: transfer completion notifier * @msg_err: error code for completed message * @msg_buf: pointer to current message data * @msg_buf_remaining: size of unsent data in the message buffer * @msg_read: identifies read transfers * @bus_clk_rate: current i2c bus clock rate * @is_suspended: prevents i2c controller accesses after suspend is called */ struct tegra_i2c_dev { struct device *dev; struct i2c_adapter adapter; struct clk *div_clk; struct clk *fast_clk; bool needs_cl_dvfs_clock; struct clk *dvfs_ref_clk; struct clk *dvfs_soc_clk; spinlock_t fifo_lock; spinlock_t mem_lock; void __iomem *base; int cont_id; int irq; bool irq_disabled; int is_dvc; struct completion msg_complete; int msg_err; int next_msg_err; u8 *msg_buf; u8 *next_msg_buf; u32 packet_header; u32 next_packet_header; u32 payload_size; u32 next_payload_size; u32 io_header; u32 next_io_header; size_t msg_buf_remaining; size_t next_msg_buf_remaining; int msg_read; int next_msg_read; struct i2c_msg *msgs; int msg_add; int next_msg_add; int msgs_num; unsigned long bus_clk_rate; bool is_suspended; u16 slave_addr; bool is_clkon_always; bool is_interruptable_xfer; bool is_high_speed_enable; u16 hs_master_code; u16 clk_divisor_non_hs_mode; bool use_single_xfer_complete; const struct tegra_i2c_chipdata *chipdata; int scl_gpio; int sda_gpio; struct i2c_algo_bit_data bit_data; const struct i2c_algorithm *bit_algo; bool bit_banging_xfer_after_shutdown; bool is_shutdown; struct notifier_block pm_nb; struct tegra_prod_list *prod_list; }; static void dvc_writel(struct tegra_i2c_dev *i2c_dev, u32 val, unsigned long reg) { writel(val, i2c_dev->base + reg); } static u32 dvc_readl(struct tegra_i2c_dev *i2c_dev, unsigned long reg) { return readl(i2c_dev->base + reg); } static void dvc_i2c_mask_irq(struct tegra_i2c_dev *i2c_dev, u32 mask) { u32 int_mask = dvc_readl(i2c_dev, DVC_CTRL_REG3); int_mask &= ~mask; dvc_writel(i2c_dev, int_mask, DVC_CTRL_REG3); } static void dvc_i2c_unmask_irq(struct tegra_i2c_dev *i2c_dev, u32 mask) { u32 int_mask = dvc_readl(i2c_dev, DVC_CTRL_REG3); int_mask |= mask; dvc_writel(i2c_dev, int_mask, DVC_CTRL_REG3); } /* * i2c_writel and i2c_readl will offset the register if necessary to talk * to the I2C block inside the DVC block */ static unsigned long tegra_i2c_reg_addr(struct tegra_i2c_dev *i2c_dev, unsigned long reg) { if (i2c_dev->is_dvc) reg += (reg >= I2C_TX_FIFO) ? 0x10 : 0x40; return reg; } static void i2c_writel(struct tegra_i2c_dev *i2c_dev, u32 val, unsigned long reg) { writel(val, i2c_dev->base + tegra_i2c_reg_addr(i2c_dev, reg)); /* Read back register to make sure that register writes completed */ if (reg != I2C_TX_FIFO) readl(i2c_dev->base + tegra_i2c_reg_addr(i2c_dev, reg)); } static u32 i2c_readl(struct tegra_i2c_dev *i2c_dev, unsigned long reg) { return readl(i2c_dev->base + tegra_i2c_reg_addr(i2c_dev, reg)); } static void i2c_writesl(struct tegra_i2c_dev *i2c_dev, void *data, unsigned long reg, int len) { u32 *buf = data; unsigned long flags = 0; if (!i2c_dev->is_interruptable_xfer) spin_lock_irqsave(&i2c_dev->mem_lock, flags); while (len--) writel(*buf++, i2c_dev->base + tegra_i2c_reg_addr(i2c_dev, reg)); if (!i2c_dev->is_interruptable_xfer) spin_unlock_irqrestore(&i2c_dev->mem_lock, flags); } static void i2c_readsl(struct tegra_i2c_dev *i2c_dev, void *data, unsigned long reg, int len) { u32 *buf = data; unsigned long flags = 0; if (!i2c_dev->is_interruptable_xfer) spin_lock_irqsave(&i2c_dev->mem_lock, flags); while (len--) *buf++ = readl(i2c_dev->base + tegra_i2c_reg_addr(i2c_dev, reg)); if (!i2c_dev->is_interruptable_xfer) spin_unlock_irqrestore(&i2c_dev->mem_lock, flags); } static inline void tegra_i2c_gpio_setscl(void *data, int state) { struct tegra_i2c_dev *i2c_dev = data; gpio_set_value(i2c_dev->scl_gpio, state); } static inline int tegra_i2c_gpio_getscl(void *data) { struct tegra_i2c_dev *i2c_dev = data; return gpio_get_value(i2c_dev->scl_gpio); } static inline void tegra_i2c_gpio_setsda(void *data, int state) { struct tegra_i2c_dev *i2c_dev = data; gpio_set_value(i2c_dev->sda_gpio, state); } static inline int tegra_i2c_gpio_getsda(void *data) { struct tegra_i2c_dev *i2c_dev = data; return gpio_get_value(i2c_dev->sda_gpio); } static int tegra_i2c_gpio_request(struct tegra_i2c_dev *i2c_dev) { int ret; ret = gpio_request_one(i2c_dev->scl_gpio, GPIOF_OUT_INIT_HIGH | GPIOF_OPEN_DRAIN, "i2c-gpio-scl"); if (ret < 0) { dev_err(i2c_dev->dev, "GPIO request for gpio %d failed %d\n", i2c_dev->scl_gpio, ret); return ret; } ret = gpio_request_one(i2c_dev->sda_gpio, GPIOF_OUT_INIT_HIGH | GPIOF_OPEN_DRAIN, "i2c-gpio-sda"); if (ret < 0) { dev_err(i2c_dev->dev, "GPIO request for gpio %d failed %d\n", i2c_dev->sda_gpio, ret); gpio_free(i2c_dev->scl_gpio); return ret; } return ret; } static void tegra_i2c_gpio_free(struct tegra_i2c_dev *i2c_dev) { gpio_free(i2c_dev->scl_gpio); gpio_free(i2c_dev->sda_gpio); } static int tegra_i2c_gpio_xfer(struct i2c_adapter *adap, struct i2c_msg msgs[], int num) { struct tegra_i2c_dev *i2c_dev = i2c_get_adapdata(adap); int ret; ret = tegra_i2c_gpio_request(i2c_dev); if (ret < 0) return ret; ret = i2c_dev->bit_algo->master_xfer(adap, msgs, num); if (ret < 0) dev_err(i2c_dev->dev, "i2c-bit-algo xfer failed %d\n", ret); tegra_i2c_gpio_free(i2c_dev); return ret; } static int tegra_i2c_gpio_init(struct tegra_i2c_dev *i2c_dev) { struct i2c_algo_bit_data *bit_data = &i2c_dev->bit_data; bit_data->setsda = tegra_i2c_gpio_setsda; bit_data->getsda = tegra_i2c_gpio_getsda; bit_data->setscl = tegra_i2c_gpio_setscl; bit_data->getscl = tegra_i2c_gpio_getscl; bit_data->data = i2c_dev; bit_data->udelay = 20; /* 50KHz */ bit_data->timeout = HZ; /* 10 ms*/ i2c_dev->bit_algo = &i2c_bit_algo; i2c_dev->adapter.algo_data = bit_data; return 0; } static void tegra_i2c_mask_irq(struct tegra_i2c_dev *i2c_dev, u32 mask) { u32 int_mask = i2c_readl(i2c_dev, I2C_INT_MASK); int_mask &= ~mask; i2c_writel(i2c_dev, int_mask, I2C_INT_MASK); } static void tegra_i2c_unmask_irq(struct tegra_i2c_dev *i2c_dev, u32 mask) { u32 int_mask = i2c_readl(i2c_dev, I2C_INT_MASK); int_mask |= mask; i2c_writel(i2c_dev, int_mask, I2C_INT_MASK); } static int tegra_i2c_flush_fifos(struct tegra_i2c_dev *i2c_dev) { unsigned long timeout = jiffies + HZ; u32 val = i2c_readl(i2c_dev, I2C_FIFO_CONTROL); val |= I2C_FIFO_CONTROL_TX_FLUSH | I2C_FIFO_CONTROL_RX_FLUSH; i2c_writel(i2c_dev, val, I2C_FIFO_CONTROL); while (i2c_readl(i2c_dev, I2C_FIFO_CONTROL) & (I2C_FIFO_CONTROL_TX_FLUSH | I2C_FIFO_CONTROL_RX_FLUSH)) { if (time_after(jiffies, timeout)) { dev_warn(i2c_dev->dev, "timeout waiting for fifo flush\n"); return -ETIMEDOUT; } msleep(1); } return 0; } static int tegra_i2c_empty_rx_fifo(struct tegra_i2c_dev *i2c_dev) { u32 val; int rx_fifo_avail; u8 *buf = i2c_dev->msg_buf; size_t buf_remaining = i2c_dev->msg_buf_remaining; int words_to_transfer; val = i2c_readl(i2c_dev, I2C_FIFO_STATUS); rx_fifo_avail = (val & I2C_FIFO_STATUS_RX_MASK) >> I2C_FIFO_STATUS_RX_SHIFT; /* Rounds down to not include partial word at the end of buf */ words_to_transfer = buf_remaining / BYTES_PER_FIFO_WORD; if (words_to_transfer > rx_fifo_avail) words_to_transfer = rx_fifo_avail; i2c_readsl(i2c_dev, buf, I2C_RX_FIFO, words_to_transfer); buf += words_to_transfer * BYTES_PER_FIFO_WORD; buf_remaining -= words_to_transfer * BYTES_PER_FIFO_WORD; rx_fifo_avail -= words_to_transfer; /* * If there is a partial word at the end of buf, handle it manually to * prevent overwriting past the end of buf */ if (rx_fifo_avail > 0 && buf_remaining > 0) { BUG_ON(buf_remaining > 3); val = i2c_readl(i2c_dev, I2C_RX_FIFO); memcpy(buf, &val, buf_remaining); buf_remaining = 0; rx_fifo_avail--; } BUG_ON(rx_fifo_avail > 0 && buf_remaining > 0); i2c_dev->msg_buf_remaining = buf_remaining; i2c_dev->msg_buf = buf; return 0; } static int tegra_i2c_fill_tx_fifo(struct tegra_i2c_dev *i2c_dev) { u32 val; int tx_fifo_avail; u8 *buf; size_t buf_remaining; int words_to_transfer; if (!i2c_dev->msg_buf_remaining) return 0; buf = i2c_dev->msg_buf; buf_remaining = i2c_dev->msg_buf_remaining; val = i2c_readl(i2c_dev, I2C_FIFO_STATUS); tx_fifo_avail = (val & I2C_FIFO_STATUS_TX_MASK) >> I2C_FIFO_STATUS_TX_SHIFT; /* Rounds down to not include partial word at the end of buf */ words_to_transfer = buf_remaining / BYTES_PER_FIFO_WORD; /* It's very common to have < 4 bytes, so optimize that case. */ if (words_to_transfer) { if (words_to_transfer > tx_fifo_avail) words_to_transfer = tx_fifo_avail; /* * Update state before writing to FIFO. If this casues us * to finish writing all bytes (AKA buf_remaining goes to 0) we * have a potential for an interrupt (PACKET_XFER_COMPLETE is * not maskable). We need to make sure that the isr sees * buf_remaining as 0 and doesn't call us back re-entrantly. */ buf_remaining -= words_to_transfer * BYTES_PER_FIFO_WORD; tx_fifo_avail -= words_to_transfer; i2c_dev->msg_buf_remaining = buf_remaining; i2c_dev->msg_buf = buf + words_to_transfer * BYTES_PER_FIFO_WORD; barrier(); i2c_writesl(i2c_dev, buf, I2C_TX_FIFO, words_to_transfer); buf += words_to_transfer * BYTES_PER_FIFO_WORD; } /* * If there is a partial word at the end of buf, handle it manually to * prevent reading past the end of buf, which could cross a page * boundary and fault. */ if (tx_fifo_avail > 0 && buf_remaining > 0) { if (buf_remaining > 3) { dev_err(i2c_dev->dev, "Remaining buffer more than 3 %zd\n", buf_remaining); BUG(); } memcpy(&val, buf, buf_remaining); /* Again update before writing to FIFO to make sure isr sees. */ i2c_dev->msg_buf_remaining = 0; i2c_dev->msg_buf = NULL; barrier(); i2c_writel(i2c_dev, val, I2C_TX_FIFO); } return 0; } /* * One of the Tegra I2C blocks is inside the DVC (Digital Voltage Controller) * block. This block is identical to the rest of the I2C blocks, except that * it only supports master mode, it has registers moved around, and it needs * some extra init to get it into I2C mode. The register moves are handled * by i2c_readl and i2c_writel */ static void tegra_dvc_init(struct tegra_i2c_dev *i2c_dev) { u32 val = 0; val = dvc_readl(i2c_dev, DVC_CTRL_REG3); val |= DVC_CTRL_REG3_SW_PROG; dvc_writel(i2c_dev, val, DVC_CTRL_REG3); val = dvc_readl(i2c_dev, DVC_CTRL_REG1); val |= DVC_CTRL_REG1_INTR_EN; dvc_writel(i2c_dev, val, DVC_CTRL_REG1); } static void tegra_i2c_slave_init(struct tegra_i2c_dev *i2c_dev) { u32 val = I2C_SL_CNFG_NEWSL | I2C_SL_CNFG_NACK; i2c_writel(i2c_dev, val, I2C_SL_CNFG); if (i2c_dev->slave_addr) { u16 addr = i2c_dev->slave_addr; i2c_writel(i2c_dev, SL_ADDR1(addr), I2C_SL_ADDR1); i2c_writel(i2c_dev, SL_ADDR2(addr), I2C_SL_ADDR2); } } static inline int tegra_i2c_clock_enable(struct tegra_i2c_dev *i2c_dev) { int ret; if (i2c_dev->needs_cl_dvfs_clock) { ret = clk_prepare_enable(i2c_dev->dvfs_soc_clk); if (ret < 0) { dev_err(i2c_dev->dev, "Error in enabling dvfs soc clock %d\n", ret); return ret; } ret = clk_prepare_enable(i2c_dev->dvfs_ref_clk); if (ret < 0) { dev_err(i2c_dev->dev, "Error in enabling dvfs ref clock %d\n", ret); goto ref_clk_err; } } if (i2c_dev->chipdata->has_fast_clock) { ret = clk_prepare_enable(i2c_dev->fast_clk); if (ret < 0) { dev_err(i2c_dev->dev, "Enabling fast clk failed, err %d\n", ret); goto fast_clk_err; } } ret = clk_prepare_enable(i2c_dev->div_clk); if (ret < 0) { dev_err(i2c_dev->dev, "Enabling div clk failed, err %d\n", ret); goto div_clk_err; } return 0; div_clk_err: if (i2c_dev->chipdata->has_fast_clock) clk_disable_unprepare(i2c_dev->fast_clk); fast_clk_err: if (i2c_dev->needs_cl_dvfs_clock) clk_disable_unprepare(i2c_dev->dvfs_ref_clk); ref_clk_err: if (i2c_dev->needs_cl_dvfs_clock) clk_disable_unprepare(i2c_dev->dvfs_soc_clk); return ret; } static inline void tegra_i2c_clock_disable(struct tegra_i2c_dev *i2c_dev) { clk_disable_unprepare(i2c_dev->div_clk); if (i2c_dev->chipdata->has_fast_clock) clk_disable_unprepare(i2c_dev->fast_clk); if (i2c_dev->needs_cl_dvfs_clock) { clk_disable_unprepare(i2c_dev->dvfs_soc_clk); clk_disable_unprepare(i2c_dev->dvfs_ref_clk); } } static int tegra_i2c_set_clk_rate(struct tegra_i2c_dev *i2c_dev) { u32 clk_multiplier; int ret; if (i2c_dev->is_high_speed_enable) clk_multiplier = i2c_dev->chipdata->clk_multiplier_hs_mode * (i2c_dev->chipdata->clk_divisor_hs_mode + 1); else clk_multiplier = I2C_CLK_MULTIPLIER_STD_FAST_MODE * (i2c_dev->clk_divisor_non_hs_mode + 1); ret = clk_set_rate(i2c_dev->div_clk, i2c_dev->bus_clk_rate * clk_multiplier); if (ret < 0) { dev_err(i2c_dev->dev, "set clock rate %lu failed: %d\n", i2c_dev->bus_clk_rate * clk_multiplier, ret); return ret; } return ret; } static int tegra_i2c_init(struct tegra_i2c_dev *i2c_dev) { u32 val; int err = 0; u32 clk_divisor = 0; unsigned long timeout; err = tegra_i2c_clock_enable(i2c_dev); if (err < 0) { dev_err(i2c_dev->dev, "Clock enable failed %d\n", err); return err; } tegra_periph_reset_assert(i2c_dev->div_clk); udelay(2); tegra_periph_reset_deassert(i2c_dev->div_clk); if (i2c_dev->is_dvc) tegra_dvc_init(i2c_dev); val = I2C_CNFG_NEW_MASTER_FSM; if (!i2c_dev->is_high_speed_enable) val |= (0x2 << I2C_CNFG_DEBOUNCE_CNT_SHIFT); i2c_writel(i2c_dev, val, I2C_CNFG); i2c_writel(i2c_dev, 0, I2C_INT_MASK); err = tegra_i2c_set_clk_rate(i2c_dev); if (err < 0) return err; clk_divisor |= i2c_dev->chipdata->clk_divisor_hs_mode; if (i2c_dev->chipdata->has_clk_divisor_std_fast_mode) clk_divisor |= i2c_dev->clk_divisor_non_hs_mode << I2C_CLK_DIVISOR_STD_FAST_MODE_SHIFT; i2c_writel(i2c_dev, clk_divisor, I2C_CLK_DIVISOR); if (!i2c_dev->is_dvc) { u32 sl_cfg = i2c_readl(i2c_dev, I2C_SL_CNFG); sl_cfg |= I2C_SL_CNFG_NACK | I2C_SL_CNFG_NEWSL; i2c_writel(i2c_dev, sl_cfg, I2C_SL_CNFG); i2c_writel(i2c_dev, 0xfc, I2C_SL_ADDR1); i2c_writel(i2c_dev, 0x00, I2C_SL_ADDR2); } val = 7 << I2C_FIFO_CONTROL_TX_TRIG_SHIFT | 0 << I2C_FIFO_CONTROL_RX_TRIG_SHIFT; i2c_writel(i2c_dev, val, I2C_FIFO_CONTROL); if (!i2c_dev->is_dvc) tegra_i2c_slave_init(i2c_dev); if (tegra_i2c_flush_fifos(i2c_dev)) err = -ETIMEDOUT; if (i2c_dev->chipdata->has_config_load_reg) { i2c_writel(i2c_dev, I2C_MSTR_CONFIG_LOAD, I2C_CONFIG_LOAD); timeout = jiffies + msecs_to_jiffies(1000); while (i2c_readl(i2c_dev, I2C_CONFIG_LOAD) != 0) { if (time_after(jiffies, timeout)) { dev_warn(i2c_dev->dev, "timeout waiting for config load\n"); return -ETIMEDOUT; } msleep(1); } } tegra_prod_set_list(&i2c_dev->base, i2c_dev->prod_list); tegra_i2c_clock_disable(i2c_dev); if (i2c_dev->irq_disabled) { i2c_dev->irq_disabled = 0; enable_irq(i2c_dev->irq); } return err; } static int tegra_i2c_copy_next_to_current(struct tegra_i2c_dev *i2c_dev) { i2c_dev->msg_buf = i2c_dev->next_msg_buf; i2c_dev->msg_buf_remaining = i2c_dev->next_msg_buf_remaining; i2c_dev->msg_err = i2c_dev->next_msg_err; i2c_dev->msg_read = i2c_dev->next_msg_read; i2c_dev->msg_add = i2c_dev->next_msg_add; i2c_dev->packet_header = i2c_dev->next_packet_header; i2c_dev->io_header = i2c_dev->next_io_header; i2c_dev->payload_size = i2c_dev->next_payload_size; return 0; } static irqreturn_t tegra_i2c_isr(int irq, void *dev_id) { u32 status; unsigned long flags = 0; const u32 status_err = I2C_INT_NO_ACK | I2C_INT_ARBITRATION_LOST | I2C_INT_TX_FIFO_OVERFLOW; struct tegra_i2c_dev *i2c_dev = dev_id; u32 mask; status = i2c_readl(i2c_dev, I2C_INT_STATUS); if (status == 0) { dev_dbg(i2c_dev->dev, "unknown interrupt Add 0x%02x\n", i2c_dev->msg_add); i2c_dev->msg_err |= I2C_ERR_UNKNOWN_INTERRUPT; if (!i2c_dev->irq_disabled) { disable_irq_nosync(i2c_dev->irq); i2c_dev->irq_disabled = 1; } /* Clear all interrupts */ status = 0xFFFFFFFFU; goto err; } if (unlikely(status & status_err)) { dev_dbg(i2c_dev->dev, "I2c error status 0x%08x\n", status); if (status & I2C_INT_NO_ACK) { i2c_dev->msg_err |= I2C_ERR_NO_ACK; dev_dbg(i2c_dev->dev, "no acknowledge from address" " 0x%x\n", i2c_dev->msg_add); dev_dbg(i2c_dev->dev, "Packet status 0x%08x\n", i2c_readl(i2c_dev, I2C_PACKET_TRANSFER_STATUS)); } if (status & I2C_INT_ARBITRATION_LOST) { i2c_dev->msg_err |= I2C_ERR_ARBITRATION_LOST; dev_dbg(i2c_dev->dev, "arbitration lost during " " communicate to add 0x%x\n", i2c_dev->msg_add); dev_dbg(i2c_dev->dev, "Packet status 0x%08x\n", i2c_readl(i2c_dev, I2C_PACKET_TRANSFER_STATUS)); } if (status & I2C_INT_TX_FIFO_OVERFLOW) { i2c_dev->msg_err |= I2C_INT_TX_FIFO_OVERFLOW; dev_dbg(i2c_dev->dev, "Tx fifo overflow during " " communicate to add 0x%x\n", i2c_dev->msg_add); dev_dbg(i2c_dev->dev, "Packet status 0x%08x\n", i2c_readl(i2c_dev, I2C_PACKET_TRANSFER_STATUS)); } goto err; } if (i2c_dev->chipdata->has_hw_arb_support && (status & I2C_INT_BUS_CLEAR_DONE)) goto err; if (unlikely((i2c_readl(i2c_dev, I2C_STATUS) & I2C_STATUS_BUSY) && (status == I2C_INT_TX_FIFO_DATA_REQ) && i2c_dev->msg_read && i2c_dev->msg_buf_remaining)) { dev_dbg(i2c_dev->dev, "unexpected status\n"); i2c_dev->msg_err |= I2C_ERR_UNEXPECTED_STATUS; if (!i2c_dev->irq_disabled) { disable_irq_nosync(i2c_dev->irq); i2c_dev->irq_disabled = 1; } goto err; } if (i2c_dev->msg_read && (status & I2C_INT_RX_FIFO_DATA_REQ)) { if (i2c_dev->msg_buf_remaining) tegra_i2c_empty_rx_fifo(i2c_dev); else { dev_err(i2c_dev->dev, "--- register dump for buffer remain == 0----\n"); dev_err(i2c_dev->dev, "I2C_CNFG - 0x%x\n", i2c_readl(i2c_dev, I2C_CNFG)); dev_err(i2c_dev->dev, "I2C_PACKET_TRANSFER_STATUS - 0x%x\n", i2c_readl(i2c_dev, I2C_PACKET_TRANSFER_STATUS)); dev_err(i2c_dev->dev, "I2C_FIFO_CONTROL - 0x%x\n", i2c_readl(i2c_dev, I2C_FIFO_CONTROL)); dev_err(i2c_dev->dev, "I2C_FIFO_STATUS - 0x%x\n", i2c_readl(i2c_dev, I2C_FIFO_STATUS)); dev_err(i2c_dev->dev, "I2C_INT_MASK - 0x%x\n", i2c_readl(i2c_dev, I2C_INT_MASK)); dev_err(i2c_dev->dev, "I2C_INT_STATUS - 0x%x\n", i2c_readl(i2c_dev, I2C_INT_STATUS)); dev_err(i2c_dev->dev, "msg_err - 0x%x, msg_read - 0x%x, msg_add - 0x%x\n", i2c_dev->msg_err, i2c_dev->msg_read, i2c_dev->msg_add); if (i2c_dev->msgs) { struct i2c_msg *msgs = i2c_dev->msgs; int i; for (i = 0; i < i2c_dev->msgs_num; i++) dev_err(i2c_dev->dev, "msgs[%d] %c, addr=0x%04x, len=%d\n", i, (msgs[i].flags & I2C_M_RD) ? 'R' : 'W', msgs[i].addr, msgs[i].len); } BUG(); } } if (!i2c_dev->msg_read && (status & I2C_INT_TX_FIFO_DATA_REQ)) { if (i2c_dev->msg_buf_remaining) { if (!i2c_dev->is_interruptable_xfer) spin_lock_irqsave(&i2c_dev->fifo_lock, flags); tegra_i2c_fill_tx_fifo(i2c_dev); if (!i2c_dev->is_interruptable_xfer) spin_unlock_irqrestore(&i2c_dev->fifo_lock, flags); } else tegra_i2c_mask_irq(i2c_dev, I2C_INT_TX_FIFO_DATA_REQ); } i2c_writel(i2c_dev, status, I2C_INT_STATUS); if (i2c_dev->is_dvc) dvc_writel(i2c_dev, DVC_STATUS_I2C_DONE_INTR, DVC_STATUS); if (status & I2C_INT_ALL_PACKETS_XFER_COMPLETE) { BUG_ON(i2c_dev->msg_buf_remaining); complete(&i2c_dev->msg_complete); } else if ((status & I2C_INT_PACKET_XFER_COMPLETE) && i2c_dev->use_single_xfer_complete) { BUG_ON(i2c_dev->msg_buf_remaining); complete(&i2c_dev->msg_complete); } return IRQ_HANDLED; err: dev_dbg(i2c_dev->dev, "reg: 0x%08x 0x%08x 0x%08x 0x%08x\n", i2c_readl(i2c_dev, I2C_CNFG), i2c_readl(i2c_dev, I2C_STATUS), i2c_readl(i2c_dev, I2C_INT_STATUS), i2c_readl(i2c_dev, I2C_PACKET_TRANSFER_STATUS)); dev_dbg(i2c_dev->dev, "packet: 0x%08x %u 0x%08x\n", i2c_dev->packet_header, i2c_dev->payload_size, i2c_dev->io_header); if (i2c_dev->msgs) { struct i2c_msg *msgs = i2c_dev->msgs; int i; for (i = 0; i < i2c_dev->msgs_num; i++) dev_dbg(i2c_dev->dev, "msgs[%d] %c, addr=0x%04x, len=%d\n", i, (msgs[i].flags & I2C_M_RD) ? 'R' : 'W', msgs[i].addr, msgs[i].len); } mask = I2C_INT_NO_ACK | I2C_INT_ARBITRATION_LOST | I2C_INT_PACKET_XFER_COMPLETE | I2C_INT_TX_FIFO_DATA_REQ | I2C_INT_RX_FIFO_DATA_REQ | I2C_INT_TX_FIFO_OVERFLOW; i2c_writel(i2c_dev, status, I2C_INT_STATUS); if (i2c_dev->chipdata->has_xfer_complete_interrupt) mask |= I2C_INT_ALL_PACKETS_XFER_COMPLETE; if (!(i2c_dev->use_single_xfer_complete && i2c_dev->chipdata->has_xfer_complete_interrupt)) mask |= I2C_INT_ALL_PACKETS_XFER_COMPLETE; if (i2c_dev->chipdata->has_hw_arb_support) mask |= I2C_INT_BUS_CLEAR_DONE; /* An error occurred, mask all interrupts */ tegra_i2c_mask_irq(i2c_dev, mask); /* An error occured, mask dvc interrupt */ if (i2c_dev->is_dvc) { dvc_i2c_mask_irq(i2c_dev, DVC_CTRL_REG3_I2C_DONE_INTR_EN); dvc_writel(i2c_dev, DVC_STATUS_I2C_DONE_INTR, DVC_STATUS); } complete(&i2c_dev->msg_complete); return IRQ_HANDLED; } static int tegra_i2c_send_next_read_msg_pkt_header(struct tegra_i2c_dev *i2c_dev, struct i2c_msg *next_msg, enum msg_end_type end_state) { i2c_dev->next_msg_buf = next_msg->buf; i2c_dev->next_msg_buf_remaining = next_msg->len; i2c_dev->next_msg_err = I2C_ERR_NONE; i2c_dev->next_msg_read = 1; i2c_dev->next_msg_add = next_msg->addr; i2c_dev->next_packet_header = (0 << PACKET_HEADER0_HEADER_SIZE_SHIFT) | PACKET_HEADER0_PROTOCOL_I2C | (i2c_dev->cont_id << PACKET_HEADER0_CONT_ID_SHIFT) | (1 << PACKET_HEADER0_PACKET_ID_SHIFT); i2c_writel(i2c_dev, i2c_dev->next_packet_header, I2C_TX_FIFO); i2c_dev->next_payload_size = next_msg->len - 1; i2c_writel(i2c_dev, i2c_dev->next_payload_size, I2C_TX_FIFO); i2c_dev->next_io_header = I2C_HEADER_IE_ENABLE; if (end_state == MSG_END_CONTINUE) i2c_dev->next_io_header |= I2C_HEADER_CONTINUE_XFER; else if (end_state == MSG_END_REPEAT_START) i2c_dev->next_io_header |= I2C_HEADER_REPEAT_START; if (next_msg->flags & I2C_M_TEN) { i2c_dev->next_io_header |= next_msg->addr; i2c_dev->next_io_header |= I2C_HEADER_10BIT_ADDR; } else { i2c_dev->next_io_header |= (next_msg->addr << I2C_HEADER_SLAVE_ADDR_SHIFT); } if (next_msg->flags & I2C_M_IGNORE_NAK) i2c_dev->next_io_header |= I2C_HEADER_CONT_ON_NAK; i2c_dev->next_io_header |= I2C_HEADER_READ; if (i2c_dev->is_high_speed_enable) { i2c_dev->next_io_header |= I2C_HEADER_HIGHSPEED_MODE; i2c_dev->next_io_header |= ((i2c_dev->hs_master_code & 0x7) << I2C_HEADER_MASTER_ADDR_SHIFT); } i2c_writel(i2c_dev, i2c_dev->next_io_header, I2C_TX_FIFO); return 0; } static int tegra_i2c_xfer_msg(struct tegra_i2c_dev *i2c_dev, struct i2c_msg *msg, enum msg_end_type end_state, struct i2c_msg *next_msg, enum msg_end_type next_msg_end_state) { u32 int_mask; int ret; unsigned long flags = 0; unsigned long timeout; u32 cnfg; u32 val; if (msg->len == 0) return -EINVAL; tegra_i2c_flush_fifos(i2c_dev); i2c_dev->msg_buf = msg->buf; i2c_dev->msg_buf_remaining = msg->len; i2c_dev->msg_err = I2C_ERR_NONE; i2c_dev->msg_read = (msg->flags & I2C_M_RD); INIT_COMPLETION(i2c_dev->msg_complete); if (!i2c_dev->is_interruptable_xfer) spin_lock_irqsave(&i2c_dev->fifo_lock, flags); cnfg = I2C_CNFG_NEW_MASTER_FSM | I2C_CNFG_PACKET_MODE_EN; if (i2c_dev->chipdata->has_multi_master_en_bit) cnfg |= I2C_CNFG_MULTI_MASTER_MODE; if (!i2c_dev->is_high_speed_enable) cnfg |= (0x2 << I2C_CNFG_DEBOUNCE_CNT_SHIFT); i2c_writel(i2c_dev, cnfg, I2C_CNFG); if (i2c_dev->chipdata->has_config_load_reg) { i2c_writel(i2c_dev, I2C_MSTR_CONFIG_LOAD, I2C_CONFIG_LOAD); timeout = jiffies + msecs_to_jiffies(1000); while (i2c_readl(i2c_dev, I2C_CONFIG_LOAD) != 0) { if (time_after(jiffies, timeout)) { dev_warn(i2c_dev->dev, "timeout config_load"); if (!i2c_dev->is_interruptable_xfer) spin_unlock_irqrestore(&i2c_dev->fifo_lock, flags); return -ETIMEDOUT; } udelay(2); } } i2c_writel(i2c_dev, 0, I2C_INT_MASK); val = 7 << I2C_FIFO_CONTROL_TX_TRIG_SHIFT | 0 << I2C_FIFO_CONTROL_RX_TRIG_SHIFT; i2c_writel(i2c_dev, val, I2C_FIFO_CONTROL); i2c_dev->msg_add = msg->addr; i2c_dev->packet_header = (0 << PACKET_HEADER0_HEADER_SIZE_SHIFT) | PACKET_HEADER0_PROTOCOL_I2C | (i2c_dev->cont_id << PACKET_HEADER0_CONT_ID_SHIFT) | (1 << PACKET_HEADER0_PACKET_ID_SHIFT); i2c_writel(i2c_dev, i2c_dev->packet_header, I2C_TX_FIFO); i2c_dev->payload_size = msg->len - 1; i2c_writel(i2c_dev, i2c_dev->payload_size, I2C_TX_FIFO); i2c_dev->use_single_xfer_complete = true; i2c_dev->io_header = 0; if (next_msg == NULL) i2c_dev->io_header = I2C_HEADER_IE_ENABLE; if (end_state == MSG_END_CONTINUE) i2c_dev->io_header |= I2C_HEADER_CONTINUE_XFER; else if (end_state == MSG_END_REPEAT_START) i2c_dev->io_header |= I2C_HEADER_REPEAT_START; if (msg->flags & I2C_M_TEN) { i2c_dev->io_header |= msg->addr; i2c_dev->io_header |= I2C_HEADER_10BIT_ADDR; } else { i2c_dev->io_header |= msg->addr << I2C_HEADER_SLAVE_ADDR_SHIFT; } if (msg->flags & I2C_M_IGNORE_NAK) i2c_dev->io_header |= I2C_HEADER_CONT_ON_NAK; if (msg->flags & I2C_M_RD) i2c_dev->io_header |= I2C_HEADER_READ; if (i2c_dev->is_high_speed_enable) { i2c_dev->io_header |= I2C_HEADER_HIGHSPEED_MODE; i2c_dev->io_header |= ((i2c_dev->hs_master_code & 0x7) << I2C_HEADER_MASTER_ADDR_SHIFT); } i2c_writel(i2c_dev, i2c_dev->io_header, I2C_TX_FIFO); if (!(msg->flags & I2C_M_RD)) tegra_i2c_fill_tx_fifo(i2c_dev); if (i2c_dev->is_dvc) dvc_i2c_unmask_irq(i2c_dev, DVC_CTRL_REG3_I2C_DONE_INTR_EN); int_mask = I2C_INT_NO_ACK | I2C_INT_ARBITRATION_LOST | I2C_INT_TX_FIFO_OVERFLOW; if (i2c_dev->chipdata->has_xfer_complete_interrupt) int_mask |= I2C_INT_PACKET_XFER_COMPLETE; if (i2c_dev->chipdata->has_xfer_complete_interrupt) int_mask |= I2C_INT_ALL_PACKETS_XFER_COMPLETE; if (msg->flags & I2C_M_RD) int_mask |= I2C_INT_RX_FIFO_DATA_REQ; else if (i2c_dev->msg_buf_remaining) int_mask |= I2C_INT_TX_FIFO_DATA_REQ; if (next_msg != NULL) { tegra_i2c_send_next_read_msg_pkt_header(i2c_dev, next_msg, next_msg_end_state); tegra_i2c_copy_next_to_current(i2c_dev); int_mask |= I2C_INT_RX_FIFO_DATA_REQ; i2c_dev->use_single_xfer_complete = false; } if (!(i2c_dev->use_single_xfer_complete && i2c_dev->chipdata->has_xfer_complete_interrupt)) int_mask |= I2C_INT_ALL_PACKETS_XFER_COMPLETE; if (!i2c_dev->is_interruptable_xfer) spin_unlock_irqrestore(&i2c_dev->fifo_lock, flags); tegra_i2c_unmask_irq(i2c_dev, int_mask); dev_dbg(i2c_dev->dev, "unmasked irq: %02x\n", i2c_readl(i2c_dev, I2C_INT_MASK)); ret = wait_for_completion_timeout(&i2c_dev->msg_complete, TEGRA_I2C_TIMEOUT); if (ret == 0) { dev_err(i2c_dev->dev, "--- register dump for debugging ----\n"); dev_err(i2c_dev->dev, "I2C_CNFG - 0x%x\n", i2c_readl(i2c_dev, I2C_CNFG)); dev_err(i2c_dev->dev, "I2C_PACKET_TRANSFER_STATUS - 0x%x\n", i2c_readl(i2c_dev, I2C_PACKET_TRANSFER_STATUS)); dev_err(i2c_dev->dev, "I2C_FIFO_CONTROL - 0x%x\n", i2c_readl(i2c_dev, I2C_FIFO_CONTROL)); dev_err(i2c_dev->dev, "I2C_FIFO_STATUS - 0x%x\n", i2c_readl(i2c_dev, I2C_FIFO_STATUS)); dev_err(i2c_dev->dev, "I2C_INT_MASK - 0x%x\n", i2c_readl(i2c_dev, I2C_INT_MASK)); dev_err(i2c_dev->dev, "I2C_INT_STATUS - 0x%x\n", i2c_readl(i2c_dev, I2C_INT_STATUS)); dev_err(i2c_dev->dev, "msg->len - %d\n", msg->len); dev_err(i2c_dev->dev, "is_msg_write - %d\n", !(msg->flags & I2C_M_RD)); if (next_msg != NULL) { dev_err(i2c_dev->dev, "next_msg->len - %d\n", next_msg->len); dev_err(i2c_dev->dev, "is_next_msg_write - %d\n", !(next_msg->flags & I2C_M_RD)); } dev_err(i2c_dev->dev, "buf_remaining - %zd\n", i2c_dev->msg_buf_remaining); } tegra_i2c_mask_irq(i2c_dev, int_mask); if (i2c_dev->is_dvc) dvc_i2c_mask_irq(i2c_dev, DVC_CTRL_REG3_I2C_DONE_INTR_EN); cnfg = i2c_readl(i2c_dev, I2C_CNFG); if (cnfg & I2C_CNFG_PACKET_MODE_EN) i2c_writel(i2c_dev, cnfg & (~I2C_CNFG_PACKET_MODE_EN), I2C_CNFG); else dev_err(i2c_dev->dev, "i2c_cnfg PACKET_MODE_EN not set\n"); if (i2c_dev->chipdata->has_config_load_reg) { i2c_writel(i2c_dev, I2C_MSTR_CONFIG_LOAD, I2C_CONFIG_LOAD); timeout = jiffies + msecs_to_jiffies(1000); while (i2c_readl(i2c_dev, I2C_CONFIG_LOAD) != 0) { if (time_after(jiffies, timeout)) { dev_warn(i2c_dev->dev, "timeout config_load"); return -ETIMEDOUT; } udelay(2); } } if (ret == 0) { dev_err(i2c_dev->dev, "i2c transfer timed out, addr 0x%04x, data 0x%02x\n", msg->addr, msg->buf[0]); ret = tegra_i2c_init(i2c_dev); if (!ret) ret = -ETIMEDOUT; else WARN_ON(1); return ret; } dev_dbg(i2c_dev->dev, "transfer complete: %d %d %d\n", ret, completion_done(&i2c_dev->msg_complete), i2c_dev->msg_err); if (likely(i2c_dev->msg_err == I2C_ERR_NONE)) return 0; /* Prints errors */ if (i2c_dev->msg_err & I2C_ERR_UNKNOWN_INTERRUPT) dev_warn(i2c_dev->dev, "unknown interrupt Add 0x%02x\n", i2c_dev->msg_add); if (i2c_dev->msg_err & I2C_ERR_NO_ACK) dev_warn(i2c_dev->dev, "no acknowledge from address 0x%x\n", i2c_dev->msg_add); if (i2c_dev->msg_err & I2C_ERR_ARBITRATION_LOST) dev_warn(i2c_dev->dev, "arb lost in communicate to add 0x%x\n", i2c_dev->msg_add); if (i2c_dev->msg_err & I2C_INT_TX_FIFO_OVERFLOW) dev_warn(i2c_dev->dev, "Tx fifo overflow to add 0x%x\n", i2c_dev->msg_add); if (i2c_dev->msg_err & I2C_ERR_UNEXPECTED_STATUS) dev_warn(i2c_dev->dev, "unexpected status to add 0x%x\n", i2c_dev->msg_add); if ((i2c_dev->chipdata->timeout_irq_occurs_before_bus_inactive) && (i2c_dev->msg_err == I2C_ERR_NO_ACK)) { /* * In NACK error condition resetting of I2C controller happens * before STOP condition is properly completed by I2C controller, * so wait for 2 clock cycle to complete STOP condition. */ udelay(DIV_ROUND_UP(2 * 1000000, i2c_dev->bus_clk_rate)); } /* * NACK interrupt is generated before the I2C controller generates the * STOP condition on the bus. So wait for 2 clock periods before resetting * the controller so that STOP condition has been delivered properly. */ if (i2c_dev->msg_err == I2C_ERR_NO_ACK) udelay(DIV_ROUND_UP(2 * 1000000, i2c_dev->bus_clk_rate)); ret = tegra_i2c_init(i2c_dev); if (ret) { WARN_ON(1); return ret; } /* Arbitration Lost occurs, Start recovery */ if (i2c_dev->msg_err == I2C_ERR_ARBITRATION_LOST) { if (i2c_dev->chipdata->has_hw_arb_support) { INIT_COMPLETION(i2c_dev->msg_complete); i2c_writel(i2c_dev, I2C_BC_ENABLE | I2C_BC_SCLK_THRESHOLD | I2C_BC_STOP_COND | I2C_BC_TERMINATE , I2C_BUS_CLEAR_CNFG); if (i2c_dev->chipdata->has_config_load_reg) { i2c_writel(i2c_dev, I2C_MSTR_CONFIG_LOAD, I2C_CONFIG_LOAD); timeout = jiffies + msecs_to_jiffies(1000); while (i2c_readl(i2c_dev, I2C_CONFIG_LOAD) != 0) { if (time_after(jiffies, timeout)) { dev_warn(i2c_dev->dev, "timeout config_load"); return -ETIMEDOUT; } msleep(1); } } tegra_i2c_unmask_irq(i2c_dev, I2C_INT_BUS_CLEAR_DONE); wait_for_completion_timeout(&i2c_dev->msg_complete, TEGRA_I2C_TIMEOUT); if (!(i2c_readl(i2c_dev, I2C_BUS_CLEAR_STATUS) & I2C_BC_STATUS)) dev_warn(i2c_dev->dev, "Un-recovered Arbitration lost\n"); } else { i2c_algo_busclear_gpio(i2c_dev->dev, i2c_dev->scl_gpio, GPIOF_OPEN_DRAIN, i2c_dev->sda_gpio,GPIOF_OPEN_DRAIN, MAX_BUSCLEAR_CLOCK, 100000); } return -EAGAIN; } if (i2c_dev->msg_err == I2C_ERR_NO_ACK) return -EREMOTEIO; if (i2c_dev->msg_err & I2C_ERR_UNEXPECTED_STATUS) return -EAGAIN; return -EIO; } static int tegra_i2c_split_i2c_msg_xfer(struct tegra_i2c_dev *i2c_dev, struct i2c_msg *msg, enum msg_end_type end_type, enum msg_end_type next_msg_end_type) { int size, len, ret; struct i2c_msg temp_msg; u8 *buf = msg->buf; enum msg_end_type temp_end_type; size = msg->len; temp_msg.flags = msg->flags; temp_msg.addr = msg->addr; temp_end_type = end_type; do { temp_msg.buf = buf; len = min(size, I2C_MAX_TRANSFER_LEN); temp_msg.len = len; size -= len; if ((len == I2C_MAX_TRANSFER_LEN) && size) end_type = MSG_END_CONTINUE; else end_type = temp_end_type; ret = tegra_i2c_xfer_msg(i2c_dev, &temp_msg, end_type, NULL, next_msg_end_type); if (ret) return ret; buf += len; } while (size != 0); return ret; } static int tegra_i2c_xfer(struct i2c_adapter *adap, struct i2c_msg msgs[], int num) { struct tegra_i2c_dev *i2c_dev = i2c_get_adapdata(adap); int i; int ret = 0; BUG_ON(!rt_mutex_is_locked(&(adap->bus_lock))); if (i2c_dev->is_suspended) return -EBUSY; if ((i2c_dev->is_shutdown || adap->atomic_xfer_only) && i2c_dev->bit_banging_xfer_after_shutdown) return tegra_i2c_gpio_xfer(adap, msgs, num); if (adap->atomic_xfer_only) return -EBUSY; if (adap->bus_clk_rate != i2c_dev->bus_clk_rate) { i2c_dev->bus_clk_rate = adap->bus_clk_rate; ret = tegra_i2c_set_clk_rate(i2c_dev); if (ret < 0) return ret; } i2c_dev->msgs = msgs; i2c_dev->msgs_num = num; pm_runtime_get_sync(&adap->dev); ret = tegra_i2c_clock_enable(i2c_dev); if (ret < 0) { dev_err(i2c_dev->dev, "Clock enable failed %d\n", ret); pm_runtime_put(&adap->dev); return ret; } for (i = 0; i < num; i++) { enum msg_end_type end_type = MSG_END_STOP; enum msg_end_type next_msg_end_type = MSG_END_STOP; if (i < (num - 1)) { if (msgs[i + 1].flags & I2C_M_NOSTART) end_type = MSG_END_CONTINUE; else end_type = MSG_END_REPEAT_START; if (i < num - 2) { if (msgs[i + 2].flags & I2C_M_NOSTART) next_msg_end_type = MSG_END_CONTINUE; else next_msg_end_type = MSG_END_REPEAT_START; } if ((!(msgs[i].flags & I2C_M_RD)) && (msgs[i].len <= 8) && (msgs[i+1].flags & I2C_M_RD) && (msgs[i+1].len <= I2C_MAX_TRANSFER_LEN) && (next_msg_end_type != MSG_END_CONTINUE) && (end_type == MSG_END_REPEAT_START)) { ret = tegra_i2c_xfer_msg(i2c_dev, &msgs[i], end_type, &msgs[i+1], next_msg_end_type); if (ret) break; i++; } else { if (msgs[i].len > I2C_MAX_TRANSFER_LEN) { ret = tegra_i2c_split_i2c_msg_xfer(i2c_dev, &msgs[i], end_type, next_msg_end_type); if (ret) break; } else { ret = tegra_i2c_xfer_msg(i2c_dev, &msgs[i], end_type, NULL, next_msg_end_type); if (ret) break; } } } else { if (msgs[i].len > I2C_MAX_TRANSFER_LEN) { ret = tegra_i2c_split_i2c_msg_xfer(i2c_dev, &msgs[i], end_type, next_msg_end_type); if (ret) break; } else { ret = tegra_i2c_xfer_msg(i2c_dev, &msgs[i], end_type, NULL, next_msg_end_type); if (ret) break; } } } tegra_i2c_clock_disable(i2c_dev); pm_runtime_put(&adap->dev); i2c_dev->msgs = NULL; i2c_dev->msgs_num = 0; return ret ?: i; } static u32 tegra_i2c_func(struct i2c_adapter *adap) { struct tegra_i2c_dev *i2c_dev = i2c_get_adapdata(adap); u32 ret = I2C_FUNC_I2C | I2C_FUNC_SMBUS_EMUL | I2C_FUNC_10BIT_ADDR | I2C_FUNC_PROTOCOL_MANGLING; if (i2c_dev->chipdata->has_continue_xfer_support) ret |= I2C_FUNC_NOSTART; return ret; } static const struct i2c_algorithm tegra_i2c_algo = { .master_xfer = tegra_i2c_xfer, .functionality = tegra_i2c_func, }; static int tegra_i2c_pm_notifier(struct notifier_block *nb, unsigned long event, void *data); static struct tegra_i2c_platform_data *parse_i2c_tegra_dt( struct platform_device *pdev) { struct tegra_i2c_platform_data *pdata; struct device_node *np = pdev->dev.of_node; u32 prop; pdata = devm_kzalloc(&pdev->dev, sizeof(*pdata), GFP_KERNEL); if (!pdata) return ERR_PTR(-ENOMEM); if (!of_property_read_u32(np, "clock-frequency", &prop)) pdata->bus_clk_rate = prop; pdata->is_clkon_always = of_property_read_bool(np, "nvidia,clock-always-on"); if (!of_property_read_u32(np, "nvidia,hs-master-code", &prop)) { pdata->hs_master_code = prop; pdata->is_high_speed_enable = true; } pdata->is_interruptable_xfer = of_property_read_bool(np, "nvidia,interruptable-transfer"); pdata->needs_cl_dvfs_clock = of_property_read_bool(np, "nvidia,require-cldvfs-clock"); pdata->bit_banging_xfer_after_shutdown = of_property_read_bool(np, "nvidia,bit-banging-xfer-after-shutdown"); pdata->scl_gpio = of_get_named_gpio(np, "scl-gpio", 0); pdata->sda_gpio = of_get_named_gpio(np, "sda-gpio", 0); pdata->is_dvc = of_device_is_compatible(np, "nvidia,tegra20-i2c-dvc"); /* Default configuration for device tree initiated driver */ pdata->slave_addr = 0xFC; return pdata; } static struct tegra_i2c_chipdata tegra20_i2c_chipdata = { .timeout_irq_occurs_before_bus_inactive = true, .has_xfer_complete_interrupt = false, .has_continue_xfer_support = false, .has_hw_arb_support = false, .has_fast_clock = true, .has_clk_divisor_std_fast_mode = false, .clk_divisor_std_fast_mode = 0, .clk_divisor_hs_mode = 3, .clk_multiplier_hs_mode = 12, .has_config_load_reg = false, .has_multi_master_en_bit = false, }; static struct tegra_i2c_chipdata tegra30_i2c_chipdata = { .timeout_irq_occurs_before_bus_inactive = true, .has_xfer_complete_interrupt = false, .has_continue_xfer_support = true, .has_hw_arb_support = false, .has_fast_clock = true, .has_clk_divisor_std_fast_mode = false, .clk_divisor_std_fast_mode = 0, .clk_divisor_hs_mode = 3, .clk_multiplier_hs_mode = 12, .has_config_load_reg = false, .has_multi_master_en_bit = false, }; static struct tegra_i2c_chipdata tegra114_i2c_chipdata = { .timeout_irq_occurs_before_bus_inactive = false, .has_xfer_complete_interrupt = true, .has_continue_xfer_support = true, .has_hw_arb_support = true, .has_fast_clock = false, .has_clk_divisor_std_fast_mode = true, .clk_divisor_std_fast_mode = 0x19, .clk_divisor_fast_plus_mode = 0x10, .clk_divisor_hs_mode = 1, .clk_multiplier_hs_mode = 3, .has_config_load_reg = false, .has_multi_master_en_bit = false, }; static struct tegra_i2c_chipdata tegra148_i2c_chipdata = { .timeout_irq_occurs_before_bus_inactive = false, .has_xfer_complete_interrupt = true, .has_continue_xfer_support = true, .has_hw_arb_support = true, .has_fast_clock = false, .has_clk_divisor_std_fast_mode = true, .clk_divisor_std_fast_mode = 0x19, .clk_divisor_fast_plus_mode = 0x19, .clk_divisor_hs_mode = 2, .clk_multiplier_hs_mode = 13, .has_config_load_reg = true, .has_multi_master_en_bit = false, }; static struct tegra_i2c_chipdata tegra124_i2c_chipdata = { .timeout_irq_occurs_before_bus_inactive = false, .has_xfer_complete_interrupt = true, .has_continue_xfer_support = true, .has_hw_arb_support = true, .has_fast_clock = false, .has_clk_divisor_std_fast_mode = true, .clk_divisor_std_fast_mode = 0x19, .clk_divisor_fast_plus_mode = 0x10, .clk_divisor_hs_mode = 2, .clk_multiplier_hs_mode = 13, .has_config_load_reg = true, .has_multi_master_en_bit = false, }; static struct tegra_i2c_chipdata tegra210_i2c_chipdata = { .timeout_irq_occurs_before_bus_inactive = false, .has_xfer_complete_interrupt = true, .has_continue_xfer_support = true, .has_hw_arb_support = true, .has_fast_clock = false, .has_clk_divisor_std_fast_mode = true, .clk_divisor_std_fast_mode = 0x19, .clk_divisor_fast_plus_mode = 0x10, .clk_divisor_hs_mode = 2, .clk_multiplier_hs_mode = 13, .has_config_load_reg = true, .has_multi_master_en_bit = true, }; /* Match table for of_platform binding */ static const struct of_device_id tegra_i2c_of_match[] = { { .compatible = "nvidia,tegra210-i2c", .data = &tegra210_i2c_chipdata, }, { .compatible = "nvidia,tegra124-i2c", .data = &tegra124_i2c_chipdata, }, { .compatible = "nvidia,tegra148-i2c", .data = &tegra148_i2c_chipdata, }, { .compatible = "nvidia,tegra114-i2c", .data = &tegra114_i2c_chipdata, }, { .compatible = "nvidia,tegra30-i2c", .data = &tegra30_i2c_chipdata, }, { .compatible = "nvidia,tegra20-i2c", .data = &tegra20_i2c_chipdata, }, { .compatible = "nvidia,tegra20-i2c-dvc", .data = &tegra20_i2c_chipdata, }, {}, }; MODULE_DEVICE_TABLE(of, tegra_i2c_of_match); static struct platform_device_id tegra_i2c_devtype[] = { { .name = "tegra-i2c", .driver_data = (unsigned long)&tegra30_i2c_chipdata, }, { .name = "tegra20-i2c", .driver_data = (unsigned long)&tegra20_i2c_chipdata, }, { .name = "tegra30-i2c", .driver_data = (unsigned long)&tegra30_i2c_chipdata, }, { .name = "tegra11-i2c", .driver_data = (unsigned long)&tegra114_i2c_chipdata, }, { .name = "tegra14-i2c", .driver_data = (unsigned long)&tegra148_i2c_chipdata, }, { .name = "tegra12-i2c", .driver_data = (unsigned long)&tegra124_i2c_chipdata, }, { .name = "tegra21-i2c", .driver_data = (unsigned long)&tegra210_i2c_chipdata, }, }; static int tegra_i2c_probe(struct platform_device *pdev) { struct tegra_i2c_dev *i2c_dev; struct tegra_i2c_platform_data *pdata = pdev->dev.platform_data; struct resource *res; struct clk *div_clk; struct clk *fast_clk = NULL; struct clk *dvfs_ref_clk = NULL; struct clk *dvfs_soc_clk = NULL; void __iomem *base; int irq; int ret = 0; const struct tegra_i2c_chipdata *chip_data = NULL; const struct of_device_id *match; int bus_num = -1; struct pinctrl *pin; struct pinctrl_state *s; char prod_name[15]; if (pdev->dev.of_node) { match = of_match_device(of_match_ptr(tegra_i2c_of_match), &pdev->dev); if (!match) { dev_err(&pdev->dev, "Device Not matching\n"); return -ENODEV; } chip_data = match->data; if (!pdata) pdata = parse_i2c_tegra_dt(pdev); } else { chip_data = (struct tegra_i2c_chipdata *)pdev->id_entry->driver_data; bus_num = pdev->id; } if (IS_ERR(pdata) || !pdata || !chip_data) { dev_err(&pdev->dev, "no platform/chip data?\n"); return IS_ERR(pdata) ? PTR_ERR(pdata) : -ENODEV; } res = platform_get_resource(pdev, IORESOURCE_MEM, 0); if (!res) { dev_err(&pdev->dev, "no mem resource\n"); return -EINVAL; } base = devm_ioremap_resource(&pdev->dev, res); if (IS_ERR(base)) return PTR_ERR(base); res = platform_get_resource(pdev, IORESOURCE_IRQ, 0); if (!res) { dev_err(&pdev->dev, "no irq resource\n"); return -EINVAL; } irq = res->start; i2c_dev = devm_kzalloc(&pdev->dev, sizeof(*i2c_dev), GFP_KERNEL); if (!i2c_dev) { dev_err(&pdev->dev, "Could not allocate struct tegra_i2c_dev"); return -ENOMEM; } i2c_dev->chipdata = chip_data; i2c_dev->needs_cl_dvfs_clock = pdata->needs_cl_dvfs_clock; i2c_dev->is_interruptable_xfer = pdata->is_interruptable_xfer; div_clk = devm_clk_get(&pdev->dev, "div-clk"); if (IS_ERR(div_clk)) { dev_err(&pdev->dev, "missing controller clock"); return PTR_ERR(div_clk); } if (i2c_dev->chipdata->has_fast_clock) { fast_clk = devm_clk_get(&pdev->dev, "fast-clk"); if (IS_ERR(fast_clk)) { dev_err(&pdev->dev, "missing bus clock"); return PTR_ERR(fast_clk); } } if (i2c_dev->needs_cl_dvfs_clock) { dvfs_ref_clk = devm_clk_get(&pdev->dev, "cl_dvfs_ref"); if (IS_ERR(dvfs_ref_clk)) { dev_err(&pdev->dev, "missing cl_dvfs_ref clock"); return PTR_ERR(dvfs_ref_clk); } i2c_dev->dvfs_ref_clk = dvfs_ref_clk; dvfs_soc_clk = devm_clk_get(&pdev->dev, "cl_dvfs_soc"); if (IS_ERR(dvfs_soc_clk)) { dev_err(&pdev->dev, "missing cl_dvfs_soc clock"); return PTR_ERR(dvfs_soc_clk); } i2c_dev->dvfs_soc_clk = dvfs_soc_clk; } if (pdata->is_high_speed_enable) { pin = devm_pinctrl_get(&pdev->dev); if (IS_ERR(pin)) { dev_warn(&pdev->dev, "Missing pinctrl device\n"); goto skip_pinctrl; } s = pinctrl_lookup_state(pin, "hs_mode"); if (IS_ERR(s)) { dev_warn(&pdev->dev, "Missing hs_mode state\n"); goto skip_pinctrl; } ret = pinctrl_select_state(pin, s); if (ret < 0) dev_err(&pdev->dev, "setting state failed\n"); } skip_pinctrl: i2c_dev->base = base; i2c_dev->div_clk = div_clk; if (i2c_dev->chipdata->has_fast_clock) i2c_dev->fast_clk = fast_clk; i2c_dev->irq = irq; i2c_dev->dev = &pdev->dev; i2c_dev->is_clkon_always = pdata->is_clkon_always; i2c_dev->bus_clk_rate = pdata->bus_clk_rate ? pdata->bus_clk_rate: 100000; i2c_dev->is_high_speed_enable = pdata->is_high_speed_enable; i2c_dev->clk_divisor_non_hs_mode = i2c_dev->chipdata->clk_divisor_std_fast_mode; if (i2c_dev->bus_clk_rate == 1000000) i2c_dev->clk_divisor_non_hs_mode = i2c_dev->chipdata->clk_divisor_fast_plus_mode; i2c_dev->msgs = NULL; i2c_dev->msgs_num = 0; i2c_dev->is_dvc = pdata->is_dvc; i2c_dev->slave_addr = pdata->slave_addr; i2c_dev->hs_master_code = pdata->hs_master_code; i2c_dev->bit_banging_xfer_after_shutdown = pdata->bit_banging_xfer_after_shutdown; init_completion(&i2c_dev->msg_complete); spin_lock_init(&i2c_dev->fifo_lock); spin_lock_init(&i2c_dev->mem_lock); if (pdev->dev.of_node) i2c_dev->prod_list = tegra_prod_init(pdev->dev.of_node); if (IS_ERR(i2c_dev->prod_list)) i2c_dev->prod_list = NULL; platform_set_drvdata(pdev, i2c_dev); if (i2c_dev->is_clkon_always) tegra_i2c_clock_enable(i2c_dev); ret = tegra_i2c_init(i2c_dev); if (ret) { dev_err(&pdev->dev, "Failed to initialize i2c controller"); goto err; } ret = devm_request_irq(&pdev->dev, i2c_dev->irq, tegra_i2c_isr, IRQF_NO_SUSPEND, dev_name(&pdev->dev), i2c_dev); if (ret) { dev_err(&pdev->dev, "Failed to request irq %i\n", i2c_dev->irq); goto err; } pm_runtime_enable(&pdev->dev); i2c_dev->scl_gpio = pdata->scl_gpio; i2c_dev->sda_gpio = pdata->sda_gpio; i2c_set_adapdata(&i2c_dev->adapter, i2c_dev); i2c_dev->adapter.owner = THIS_MODULE; i2c_dev->adapter.class = I2C_CLASS_HWMON; strlcpy(i2c_dev->adapter.name, "Tegra I2C adapter", sizeof(i2c_dev->adapter.name)); i2c_dev->adapter.bus_clk_rate = i2c_dev->bus_clk_rate; i2c_dev->adapter.algo = &tegra_i2c_algo; i2c_dev->adapter.dev.parent = &pdev->dev; i2c_dev->adapter.nr = bus_num; i2c_dev->adapter.dev.of_node = pdev->dev.of_node; if (pdata->retries) i2c_dev->adapter.retries = pdata->retries; else i2c_dev->adapter.retries = TEGRA_I2C_RETRIES; if (pdata->timeout) i2c_dev->adapter.timeout = pdata->timeout; ret = i2c_add_numbered_adapter(&i2c_dev->adapter); if (ret) { dev_err(&pdev->dev, "Failed to add I2C adapter\n"); goto err; } i2c_dev->cont_id = i2c_dev->adapter.nr & PACKET_HEADER0_CONT_ID_MASK; if (pdata->is_high_speed_enable) { sprintf(prod_name, "i2c%d_hs_prod", i2c_dev->cont_id); ret = tegra_pinctrl_config_prod(&pdev->dev, prod_name); if (ret < 0) dev_warn(&pdev->dev, "Failed to set %s setting\n", prod_name); } i2c_dev->pm_nb.notifier_call = tegra_i2c_pm_notifier; tegra_register_pm_notifier(&i2c_dev->pm_nb); of_i2c_register_devices(&i2c_dev->adapter); pm_runtime_enable(&i2c_dev->adapter.dev); tegra_i2c_gpio_init(i2c_dev); return 0; err: tegra_prod_release(&i2c_dev->prod_list); return ret; } static int tegra_i2c_remove(struct platform_device *pdev) { struct tegra_i2c_dev *i2c_dev = platform_get_drvdata(pdev); tegra_unregister_pm_notifier(&i2c_dev->pm_nb); i2c_del_adapter(&i2c_dev->adapter); pm_runtime_disable(&i2c_dev->adapter.dev); if (i2c_dev->is_clkon_always) tegra_i2c_clock_disable(i2c_dev); pm_runtime_disable(&pdev->dev); tegra_prod_release(&i2c_dev->prod_list); return 0; } static void tegra_i2c_shutdown(struct platform_device *pdev) { struct tegra_i2c_dev *i2c_dev = platform_get_drvdata(pdev); dev_info(i2c_dev->dev, "Shutting down\n"); i2c_shutdown_adapter(&i2c_dev->adapter); i2c_dev->is_shutdown = true; } #ifdef CONFIG_PM_SLEEP static int __tegra_i2c_suspend_noirq_late(struct tegra_i2c_dev *i2c_dev) { i2c_dev->is_suspended = true; if (i2c_dev->is_clkon_always) tegra_i2c_clock_disable(i2c_dev); return 0; } static int tegra_i2c_suspend_noirq_late(struct device *dev) { struct platform_device *pdev = to_platform_device(dev); struct tegra_i2c_dev *i2c_dev = platform_get_drvdata(pdev); i2c_lock_adapter(&i2c_dev->adapter); __tegra_i2c_suspend_noirq_late(i2c_dev); i2c_unlock_adapter(&i2c_dev->adapter); return 0; } static int __tegra_i2c_resume_noirq_early(struct tegra_i2c_dev *i2c_dev) { int ret; if (i2c_dev->is_clkon_always) tegra_i2c_clock_enable(i2c_dev); ret = tegra_i2c_init(i2c_dev); if (ret) return ret; i2c_dev->is_suspended = false; return 0; } static int tegra_i2c_resume_noirq_early(struct device *dev) { struct platform_device *pdev = to_platform_device(dev); struct tegra_i2c_dev *i2c_dev = platform_get_drvdata(pdev); i2c_lock_adapter(&i2c_dev->adapter); __tegra_i2c_resume_noirq_early(i2c_dev); i2c_unlock_adapter(&i2c_dev->adapter); return 0; } static int tegra_i2c_pm_notifier(struct notifier_block *nb, unsigned long event, void *data) { struct tegra_i2c_dev *i2c_dev = container_of(nb, struct tegra_i2c_dev, pm_nb); if (event == TEGRA_PM_SUSPEND) __tegra_i2c_suspend_noirq_late(i2c_dev); else if (event == TEGRA_PM_RESUME) __tegra_i2c_resume_noirq_early(i2c_dev); return NOTIFY_OK; } static const struct dev_pm_ops tegra_i2c_pm = { .suspend_noirq_late = tegra_i2c_suspend_noirq_late, .resume_noirq_early = tegra_i2c_resume_noirq_early, }; #define TEGRA_I2C_PM (&tegra_i2c_pm) #else #define TEGRA_I2C_PM NULL static int tegra_i2c_pm_notifier(struct notifier_block *nb, unsigned long event, void *data) { return NOTIFY_OK; } #endif static struct platform_driver tegra_i2c_driver = { .probe = tegra_i2c_probe, .remove = tegra_i2c_remove, .late_shutdown = tegra_i2c_shutdown, .id_table = tegra_i2c_devtype, .driver = { .name = "tegra-i2c", .owner = THIS_MODULE, .of_match_table = of_match_ptr(tegra_i2c_of_match), .pm = TEGRA_I2C_PM, }, }; static int __init tegra_i2c_init_driver(void) { return platform_driver_register(&tegra_i2c_driver); } static void __exit tegra_i2c_exit_driver(void) { platform_driver_unregister(&tegra_i2c_driver); } subsys_initcall(tegra_i2c_init_driver); module_exit(tegra_i2c_exit_driver); MODULE_DESCRIPTION("nVidia Tegra2 I2C Bus Controller driver"); MODULE_AUTHOR("Colin Cross"); MODULE_LICENSE("GPL v2");
InES-HPMM/linux-l4t
drivers/i2c/busses/i2c-tegra.c
C
gpl-2.0
56,211
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <!--NewPage--> <HTML> <HEAD> <!-- Generated by javadoc (build 1.6.0_37) on Fri Apr 18 13:26:10 BST 2014 --> <META http-equiv="Content-Type" content="text/html; charset=utf-8"> <TITLE> DirectionFinderAdaptor (leJOS EV3 API documentation) </TITLE> <META NAME="date" CONTENT="2014-04-18"> <LINK REL ="stylesheet" TYPE="text/css" HREF="../../stylesheet.css" TITLE="Style"> <SCRIPT type="text/javascript"> function windowTitle() { if (location.href.indexOf('is-external=true') == -1) { parent.document.title="DirectionFinderAdaptor (leJOS EV3 API documentation)"; } } </SCRIPT> <NOSCRIPT> </NOSCRIPT> </HEAD> <BODY BGCOLOR="white" onload="windowTitle();"> <HR> <!-- ========= START OF TOP NAVBAR ======= --> <A NAME="navbar_top"><!-- --></A> <A HREF="#skip-navbar_top" title="Skip navigation links"></A> <TABLE BORDER="0" WIDTH="100%" CELLPADDING="1" CELLSPACING="0" SUMMARY=""> <TR> <TD COLSPAN=2 BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A NAME="navbar_top_firstrow"><!-- --></A> <TABLE BORDER="0" CELLPADDING="0" CELLSPACING="3" SUMMARY=""> <TR ALIGN="center" VALIGN="top"> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../overview-summary.html"><FONT CLASS="NavBarFont1"><B>Overview</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="package-summary.html"><FONT CLASS="NavBarFont1"><B>Package</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#FFFFFF" CLASS="NavBarCell1Rev"> &nbsp;<FONT CLASS="NavBarFont1Rev"><B>Class</B></FONT>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="package-tree.html"><FONT CLASS="NavBarFont1"><B>Tree</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../deprecated-list.html"><FONT CLASS="NavBarFont1"><B>Deprecated</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../index-all.html"><FONT CLASS="NavBarFont1"><B>Index</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../help-doc.html"><FONT CLASS="NavBarFont1"><B>Help</B></FONT></A>&nbsp;</TD> </TR> </TABLE> </TD> <TD ALIGN="right" VALIGN="top" ROWSPAN=3><EM> </EM> </TD> </TR> <TR> <TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2"> &nbsp;<A HREF="../../lejos/robotics/DirectionFinder.html" title="interface in lejos.robotics"><B>PREV CLASS</B></A>&nbsp; &nbsp;<A HREF="../../lejos/robotics/Encoder.html" title="interface in lejos.robotics"><B>NEXT CLASS</B></A></FONT></TD> <TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2"> <A HREF="../../index.html?lejos/robotics/DirectionFinderAdaptor.html" target="_top"><B>FRAMES</B></A> &nbsp; &nbsp;<A HREF="DirectionFinderAdaptor.html" target="_top"><B>NO FRAMES</B></A> &nbsp; &nbsp;<SCRIPT type="text/javascript"> <!-- if(window==top) { document.writeln('<A HREF="../../allclasses-noframe.html"><B>All Classes</B></A>'); } //--> </SCRIPT> <NOSCRIPT> <A HREF="../../allclasses-noframe.html"><B>All Classes</B></A> </NOSCRIPT> </FONT></TD> </TR> <TR> <TD VALIGN="top" CLASS="NavBarCell3"><FONT SIZE="-2"> SUMMARY:&nbsp;NESTED&nbsp;|&nbsp;FIELD&nbsp;|&nbsp;<A HREF="#constructor_summary">CONSTR</A>&nbsp;|&nbsp;<A HREF="#method_summary">METHOD</A></FONT></TD> <TD VALIGN="top" CLASS="NavBarCell3"><FONT SIZE="-2"> DETAIL:&nbsp;FIELD&nbsp;|&nbsp;<A HREF="#constructor_detail">CONSTR</A>&nbsp;|&nbsp;<A HREF="#method_detail">METHOD</A></FONT></TD> </TR> </TABLE> <A NAME="skip-navbar_top"></A> <!-- ========= END OF TOP NAVBAR ========= --> <HR> <!-- ======== START OF CLASS DATA ======== --> <H2> <FONT SIZE="-1"> lejos.robotics</FONT> <BR> Class DirectionFinderAdaptor</H2> <PRE> java.lang.Object <IMG SRC="../../resources/inherit.gif" ALT="extended by "><B>lejos.robotics.DirectionFinderAdaptor</B> </PRE> <DL> <DT><B>All Implemented Interfaces:</B> <DD><A HREF="../../lejos/robotics/Calibrate.html" title="interface in lejos.robotics">Calibrate</A>, <A HREF="../../lejos/robotics/DirectionFinder.html" title="interface in lejos.robotics">DirectionFinder</A></DD> </DL> <HR> <DL> <DT><PRE>public class <B>DirectionFinderAdaptor</B><DT>extends java.lang.Object<DT>implements <A HREF="../../lejos/robotics/DirectionFinder.html" title="interface in lejos.robotics">DirectionFinder</A></DL> </PRE> <P> <HR> <P> <!-- ======== CONSTRUCTOR SUMMARY ======== --> <A NAME="constructor_summary"><!-- --></A> <TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY=""> <TR BGCOLOR="#CCCCFF" CLASS="TableHeadingColor"> <TH ALIGN="left" COLSPAN="2"><FONT SIZE="+2"> <B>Constructor Summary</B></FONT></TH> </TR> <TR BGCOLOR="white" CLASS="TableRowColor"> <TD><CODE><B><A HREF="../../lejos/robotics/DirectionFinderAdaptor.html#DirectionFinderAdaptor(lejos.robotics.SampleProvider)">DirectionFinderAdaptor</A></B>(<A HREF="../../lejos/robotics/SampleProvider.html" title="interface in lejos.robotics">SampleProvider</A>&nbsp;provider)</CODE> <BR> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</TD> </TR> </TABLE> &nbsp; <!-- ========== METHOD SUMMARY =========== --> <A NAME="method_summary"><!-- --></A> <TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY=""> <TR BGCOLOR="#CCCCFF" CLASS="TableHeadingColor"> <TH ALIGN="left" COLSPAN="2"><FONT SIZE="+2"> <B>Method Summary</B></FONT></TH> </TR> <TR BGCOLOR="white" CLASS="TableRowColor"> <TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1"> <CODE>&nbsp;float</CODE></FONT></TD> <TD><CODE><B><A HREF="../../lejos/robotics/DirectionFinderAdaptor.html#getDegreesCartesian()">getDegreesCartesian</A></B>()</CODE> <BR> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;Compass readings increase clockwise from 0 to 360, but Cartesian coordinate systems increase counter-clockwise.</TD> </TR> <TR BGCOLOR="white" CLASS="TableRowColor"> <TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1"> <CODE>&nbsp;void</CODE></FONT></TD> <TD><CODE><B><A HREF="../../lejos/robotics/DirectionFinderAdaptor.html#resetCartesianZero()">resetCartesianZero</A></B>()</CODE> <BR> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;Changes the current direction the compass is facing into the zero angle.</TD> </TR> <TR BGCOLOR="white" CLASS="TableRowColor"> <TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1"> <CODE>&nbsp;void</CODE></FONT></TD> <TD><CODE><B><A HREF="../../lejos/robotics/DirectionFinderAdaptor.html#startCalibration()">startCalibration</A></B>()</CODE> <BR> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;Starts calibration.</TD> </TR> <TR BGCOLOR="white" CLASS="TableRowColor"> <TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1"> <CODE>&nbsp;void</CODE></FONT></TD> <TD><CODE><B><A HREF="../../lejos/robotics/DirectionFinderAdaptor.html#stopCalibration()">stopCalibration</A></B>()</CODE> <BR> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;Ends calibration sequence.</TD> </TR> </TABLE> &nbsp;<A NAME="methods_inherited_from_class_java.lang.Object"><!-- --></A> <TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY=""> <TR BGCOLOR="#EEEEFF" CLASS="TableSubHeadingColor"> <TH ALIGN="left"><B>Methods inherited from class java.lang.Object</B></TH> </TR> <TR BGCOLOR="white" CLASS="TableRowColor"> <TD><CODE>clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait</CODE></TD> </TR> </TABLE> &nbsp; <P> <!-- ========= CONSTRUCTOR DETAIL ======== --> <A NAME="constructor_detail"><!-- --></A> <TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY=""> <TR BGCOLOR="#CCCCFF" CLASS="TableHeadingColor"> <TH ALIGN="left" COLSPAN="1"><FONT SIZE="+2"> <B>Constructor Detail</B></FONT></TH> </TR> </TABLE> <A NAME="DirectionFinderAdaptor(lejos.robotics.SampleProvider)"><!-- --></A><H3> DirectionFinderAdaptor</H3> <PRE> public <B>DirectionFinderAdaptor</B>(<A HREF="../../lejos/robotics/SampleProvider.html" title="interface in lejos.robotics">SampleProvider</A>&nbsp;provider)</PRE> <DL> </DL> <!-- ============ METHOD DETAIL ========== --> <A NAME="method_detail"><!-- --></A> <TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY=""> <TR BGCOLOR="#CCCCFF" CLASS="TableHeadingColor"> <TH ALIGN="left" COLSPAN="1"><FONT SIZE="+2"> <B>Method Detail</B></FONT></TH> </TR> </TABLE> <A NAME="getDegreesCartesian()"><!-- --></A><H3> getDegreesCartesian</H3> <PRE> public float <B>getDegreesCartesian</B>()</PRE> <DL> <DD><B>Description copied from interface: <CODE><A HREF="../../lejos/robotics/DirectionFinder.html#getDegreesCartesian()">DirectionFinder</A></CODE></B></DD> <DD>Compass readings increase clockwise from 0 to 360, but Cartesian coordinate systems increase counter-clockwise. This method returns the Cartesian compass reading. Also, the resetCartesianZero() method can be used to designate any direction as zero, rather than relying on North as being zero. <P> <DD><DL> <DT><B>Specified by:</B><DD><CODE><A HREF="../../lejos/robotics/DirectionFinder.html#getDegreesCartesian()">getDegreesCartesian</A></CODE> in interface <CODE><A HREF="../../lejos/robotics/DirectionFinder.html" title="interface in lejos.robotics">DirectionFinder</A></CODE></DL> </DD> <DD><DL> <DT><B>Returns:</B><DD>Cartesian direction. Between 0 and 360, excluding 360. Values increase counter-clockwise.</DL> </DD> </DL> <HR> <A NAME="startCalibration()"><!-- --></A><H3> startCalibration</H3> <PRE> public void <B>startCalibration</B>()</PRE> <DL> <DD><B>Description copied from interface: <CODE><A HREF="../../lejos/robotics/Calibrate.html#startCalibration()">Calibrate</A></CODE></B></DD> <DD>Starts calibration. Must call stopCalibration() when done. <P> <DD><DL> <DT><B>Specified by:</B><DD><CODE><A HREF="../../lejos/robotics/Calibrate.html#startCalibration()">startCalibration</A></CODE> in interface <CODE><A HREF="../../lejos/robotics/Calibrate.html" title="interface in lejos.robotics">Calibrate</A></CODE></DL> </DD> <DD><DL> </DL> </DD> </DL> <HR> <A NAME="stopCalibration()"><!-- --></A><H3> stopCalibration</H3> <PRE> public void <B>stopCalibration</B>()</PRE> <DL> <DD><B>Description copied from interface: <CODE><A HREF="../../lejos/robotics/Calibrate.html#stopCalibration()">Calibrate</A></CODE></B></DD> <DD>Ends calibration sequence. <P> <DD><DL> <DT><B>Specified by:</B><DD><CODE><A HREF="../../lejos/robotics/Calibrate.html#stopCalibration()">stopCalibration</A></CODE> in interface <CODE><A HREF="../../lejos/robotics/Calibrate.html" title="interface in lejos.robotics">Calibrate</A></CODE></DL> </DD> <DD><DL> </DL> </DD> </DL> <HR> <A NAME="resetCartesianZero()"><!-- --></A><H3> resetCartesianZero</H3> <PRE> public void <B>resetCartesianZero</B>()</PRE> <DL> <DD><B>Description copied from interface: <CODE><A HREF="../../lejos/robotics/DirectionFinder.html#resetCartesianZero()">DirectionFinder</A></CODE></B></DD> <DD>Changes the current direction the compass is facing into the zero angle. <P> <DD><DL> <DT><B>Specified by:</B><DD><CODE><A HREF="../../lejos/robotics/DirectionFinder.html#resetCartesianZero()">resetCartesianZero</A></CODE> in interface <CODE><A HREF="../../lejos/robotics/DirectionFinder.html" title="interface in lejos.robotics">DirectionFinder</A></CODE></DL> </DD> <DD><DL> </DL> </DD> </DL> <!-- ========= END OF CLASS DATA ========= --> <HR> <!-- ======= START OF BOTTOM NAVBAR ====== --> <A NAME="navbar_bottom"><!-- --></A> <A HREF="#skip-navbar_bottom" title="Skip navigation links"></A> <TABLE BORDER="0" WIDTH="100%" CELLPADDING="1" CELLSPACING="0" SUMMARY=""> <TR> <TD COLSPAN=2 BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A NAME="navbar_bottom_firstrow"><!-- --></A> <TABLE BORDER="0" CELLPADDING="0" CELLSPACING="3" SUMMARY=""> <TR ALIGN="center" VALIGN="top"> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../overview-summary.html"><FONT CLASS="NavBarFont1"><B>Overview</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="package-summary.html"><FONT CLASS="NavBarFont1"><B>Package</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#FFFFFF" CLASS="NavBarCell1Rev"> &nbsp;<FONT CLASS="NavBarFont1Rev"><B>Class</B></FONT>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="package-tree.html"><FONT CLASS="NavBarFont1"><B>Tree</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../deprecated-list.html"><FONT CLASS="NavBarFont1"><B>Deprecated</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../index-all.html"><FONT CLASS="NavBarFont1"><B>Index</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../help-doc.html"><FONT CLASS="NavBarFont1"><B>Help</B></FONT></A>&nbsp;</TD> </TR> </TABLE> </TD> <TD ALIGN="right" VALIGN="top" ROWSPAN=3><EM> </EM> </TD> </TR> <TR> <TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2"> &nbsp;<A HREF="../../lejos/robotics/DirectionFinder.html" title="interface in lejos.robotics"><B>PREV CLASS</B></A>&nbsp; &nbsp;<A HREF="../../lejos/robotics/Encoder.html" title="interface in lejos.robotics"><B>NEXT CLASS</B></A></FONT></TD> <TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2"> <A HREF="../../index.html?lejos/robotics/DirectionFinderAdaptor.html" target="_top"><B>FRAMES</B></A> &nbsp; &nbsp;<A HREF="DirectionFinderAdaptor.html" target="_top"><B>NO FRAMES</B></A> &nbsp; &nbsp;<SCRIPT type="text/javascript"> <!-- if(window==top) { document.writeln('<A HREF="../../allclasses-noframe.html"><B>All Classes</B></A>'); } //--> </SCRIPT> <NOSCRIPT> <A HREF="../../allclasses-noframe.html"><B>All Classes</B></A> </NOSCRIPT> </FONT></TD> </TR> <TR> <TD VALIGN="top" CLASS="NavBarCell3"><FONT SIZE="-2"> SUMMARY:&nbsp;NESTED&nbsp;|&nbsp;FIELD&nbsp;|&nbsp;<A HREF="#constructor_summary">CONSTR</A>&nbsp;|&nbsp;<A HREF="#method_summary">METHOD</A></FONT></TD> <TD VALIGN="top" CLASS="NavBarCell3"><FONT SIZE="-2"> DETAIL:&nbsp;FIELD&nbsp;|&nbsp;<A HREF="#constructor_detail">CONSTR</A>&nbsp;|&nbsp;<A HREF="#method_detail">METHOD</A></FONT></TD> </TR> </TABLE> <A NAME="skip-navbar_bottom"></A> <!-- ======== END OF BOTTOM NAVBAR ======= --> <HR> </BODY> </HTML>
zmint/galileo
lib/leJOS_EV3_0.8.1-beta/docs/ev3/lejos/robotics/DirectionFinderAdaptor.html
HTML
gpl-2.0
14,245
/** * @file flightBoard.h * @author Michael Baxter <20503664@student.uwa.edu.au> * @date 10-9-2014 * @version 1.6 * * Class used to control flight board. * * * Example usage follows: * ---------------------- * * Construct FlightBoard object and start daemons: * * FlightBoard fb = FlightBoard(); * if(fb.setup() != FB_OK) { * //Problem with the flightboard: quit or fix it. * } * fb.start(); * * Create a FB_Data struct and save/upload flight instructions: * * FB_Data course1 = {0, 0, 0, 0}; * fb.setFB_Data(&course1); * * FB_Data course2; * fb.getFB_Data(&course2); * course2.elevator = 50; * fb.setFB_Data(&course2); * * fb.setFB_Data(&course1); * * Send stop command when finished program: * * fb.stop(); * * * NOTE: DO NOT CALL fb.close(). This quits the servoblaster daemon and the copter falls out of the sky. * **/ #ifndef __FLIGHTBOARD_H_INCLUDED__ #define __FLIGHTBOARD_H_INCLUDED__ #include "logger.h" #define FB_OK 0 /** * @struct FB_Data * * Struct used to store flight board commands. **/ typedef struct { int aileron; int elevator; int rudder; int gimbal; } FB_Data; /** * @class FlightBoard * * Class used to send commands to the flight board. * * Commands must be sent in the form of a FB_Data struct, and sent by address. **/ class FlightBoard { public: /** * Constructor for the FlightBoard object **/ FlightBoard(void); /** * Copy constructor **/ FlightBoard(const FlightBoard&); /** * Destructor **/ virtual ~FlightBoard(void); /** * Setup flight board for use. * * Starts ServoBlaster daemon and starts logging commands. * * @return FB_OK (=0) if set up okay, -1 otherwise. **/ int setup(void); /** * Starts the flight board. * * Need to start flight board to send commands. * * @return FB_OK (=0) if started okay, -1 otherwise. **/ int start(void); /** * Stops the flight board. * * Tells the copter to stop (all chanels to 0) and prevents further commands until filght board is started again. * * @return FB_OK (=0) if stopped okay, -1 otherwise. **/ int stop(void); /** * Closes the flight board. * * This method stops ServoBlaster. Do not call this method while in flight. The copter will fall out of the sky. * * @return FB_OK (=0) if closed okay, -1 otherwise. **/ int close(void); /** * Gets last flight board command sent to flight board. * * The FlightBoard object saves a copy of the last command sent. This method clones that data into a FB_Data struct. * * @param *command pointer to struct to save copy of last command to. * @return FB_OK (=0) if okay, -1 otherwise. **/ int getFB_Data(FB_Data*); /** * Sends a command to the flight board. * * First create a FB_Data struct containing the desired channel values (-100 to 100 for A, E and R, 0 to 90 for G). * * @param *command pointer to struct containing flight board command. * @return FB_OK (=0) if okay, -1 otherwise. **/ int setFB_Data(FB_Data*); private: FB_Data currentData; bool ready; bool running; Logger* log; }; #endif //__FLIGHTBOARD_H_INCLUDED__
crazyoldmans/picopter
base/include/flightBoard.h
C
gpl-2.0
3,196
<?php /** * Created by PhpStorm. * User: mglaman * Date: 9/2/15 * Time: 12:39 AM */ namespace mglaman\Docker; /** * Class Docker * @package mglaman\Docker */ class Docker extends DockerBase { /** * {@inheritdoc} */ public static function command() { return 'docker'; } /** * @return bool */ public static function exists() { return self::runCommand('-v')->isSuccessful(); } /** * @return bool * @throws \Exception */ public static function available() { return self::runCommand('ps')->isSuccessful(); } /** * @param $name * @param $port * @param string $protocol * * @return string */ public static function getContainerPort($name, $port, $protocol = 'tcp') { // Easier to run this than dig through JSON object. $cmd = self::runCommand('inspect', [ "--format='{{(index (index .NetworkSettings.Ports \"{$port}/{$protocol}\") 0).HostPort}}", $name ]); return preg_replace('/[^0-9,.]+/i', '', $cmd->getOutput()); } /** * Run a command in a new container. * * @param array $args * @param null $callback * @return \Symfony\Component\Process\Process * @throws \Exception */ public static function run(array $args, $callback = null) { return self::runCommand('run', $args, $callback); } /** * Start one or more stopped containers. * * @param array $args * @param null $callback * @return \Symfony\Component\Process\Process * @throws \Exception */ public static function start(array $args, $callback = null) { return self::runCommand('start', $args, $callback); } /** * Stop a running container. * * @param array $args * @param null $callback * @return \Symfony\Component\Process\Process * @throws \Exception */ public static function stop(array $args, $callback = null) { return self::runCommand('stop', $args, $callback); } /** * Removes a container. * * @param array $args * @param null $callback * * @return \Symfony\Component\Process\Process * @throws \Exception */ public static function rm(array $args, $callback = null) { return self::runCommand('rm', $args, $callback); } /** * Pull image or repository from registry. * * @param array $args * @param null $callback * * @return \Symfony\Component\Process\Process * @throws \Exception */ public static function pull(array $args, $callback = null) { return self::runCommand('pull', $args, $callback); } /** * Return low-level information on a container or image. * * @param array $args * @param bool|false $raw * @param null $callback * @return mixed|\Symfony\Component\Process\Process * @throws \Exception */ public static function inspect(array $args, $raw = false, $callback = null) { $process = self::runCommand('inspect', $args, $callback); if ($process->isSuccessful() && !$raw) { $decoded = json_decode($process->getOutput()); return reset($decoded); } return $process; } }
mglaman/docker-helper
src/Docker.php
PHP
gpl-2.0
3,379
# # # GLOBAL Makefile for FIASCO # enviroment DFLBUILDDIR := build ALLBUILDDIR := build-all RANDBUILDDIR := build-rand TEMPLDIR := src/templates MAKEFILETEMPL := $(TEMPLDIR)/Makefile.builddir.templ MANSUBDIRS := man INSTALLSUBDIRS := $(MANSUBDIRS) CLEANSUBDIRS := $(MANSUBDIRS) $(wildcard $(DFLBUILDDIR)) CONFIG_FILE := $(TEMPLDIR)/globalconfig.out TEST_TEMPLATES := $(patsubst $(CONFIG_FILE).%,%,$(wildcard $(CONFIG_FILE).*)) TEST_TEMPLATES := $(if $(TEMPLATE_FILTER),$(filter $(TEMPLATE_FILTER),$(TEST_TEMPLATES)),$(TEST_TEMPLATES)) DFL_TEMPLATE := ia32-1 PL ?= 1 getdir = $(shell \ bd="$(1)"; \ if [ "$${bd\#/}" = "$$bd" -a \ "$${bd\#*..}" = "$$bd" ]; then \ relp=".."; \ while [ "$${bd\#*/}" != "$$bd" ]; do \ relp="$$relp/.."; \ bd="$${bd\#*/}"; \ done; \ echo "$$relp"; \ else \ pwd; \ fi \ ) buildmakefile = mkdir -p "$(1)"; \ perl -p -i -e '$$s = "$(CURDIR)/src"; s/\@SRCDIR\@/$$s/' \ < $(MAKEFILETEMPL) > $(1)/Makefile ifneq ($(strip $(B)),) BUILDDIR := $(B) endif ifneq ($(strip $(BUILDDIR)),) builddir: @echo "Creating build directory \"$(BUILDDIR)\"..." @if [ -e "$(BUILDDIR)" ]; then \ echo "Already exists, aborting."; \ exit 1; \ fi @$(call buildmakefile,$(BUILDDIR)) @echo "done." endif ifneq ($(strip $(T)),) this: set -e; \ test -f $(TEMPLDIR)/globalconfig.out.$(T); \ bdir=T-$(DFLBUILDDIR)-$(T); \ rm -rf $$bdir; \ $(call buildmakefile,T-$(DFLBUILDDIR)-$(T)); \ cp $(TEMPLDIR)/globalconfig.out.$(T) $$bdir/globalconfig.out; \ $(MAKE) -C $$bdir endif $(DFLBUILDDIR): fiasco.builddir.create $(MAKE) -C $@ -j$(PL) all: fiasco man clean cleanall: set -e; for i in $(CLEANSUBDIRS); do $(MAKE) -C $$i $@; done purge: cleanall $(RM) -r $(DFLBUILDDIR) man: set -e; for i in $(MANSUBDIRS); do $(MAKE) -C $$i; done fiasco.builddir.create: [ -e $(DFLBUILDDIR)/Makefile ] || \ ($(call buildmakefile,$(DFLBUILDDIR))) [ -f $(DFLBUILDDIR)/globalconfig.out ] || { \ cp $(TEMPLDIR)/globalconfig.out.$(DFL_TEMPLATE) \ $(DFLBUILDDIR)/globalconfig.out; \ } config $(filter config %config,$(MAKECMDGOALS)): fiasco.builddir.create $(MAKE) -C $(DFLBUILDDIR) $@ fiasco: fiasco.builddir.create $(MAKE) -C $(DFLBUILDDIR) -j$(PL) checkall l4check: error=0; \ $(RM) -r $(ALLBUILDDIR); \ for X in $(TEST_TEMPLATES); do \ echo -e "\n= Building configuration: $$X\n\n"; \ $(call buildmakefile,$(ALLBUILDDIR)/$$X); \ cp $(TEMPLDIR)/globalconfig.out.$$X \ $(ALLBUILDDIR)/$$X/globalconfig.out; \ if $(MAKE) -C $(ALLBUILDDIR)/$$X -j$(PL); then \ [ -z "$(KEEP_BUILD_DIRS)" ] && \ $(RM) -r $(ALLBUILDDIR)/$$X; \ else \ error=$$?; \ failed="$$failed $$X"; \ fi \ done; \ rmdir $(ALLBUILDDIR) >/dev/null 2>&1; \ [ "$$failed" ] && echo -e "\nFailed configurations:$$failed"; \ exit $$error; checkallp: $(RM) -r $(ALLBUILDDIR) $(MAKE) dobuildparallel SHELL=bash .PHONY: dobuildparallel checkallp dobuildparallel: $(addprefix $(ALLBUILDDIR)/,$(TEST_TEMPLATES)) error=0; \ echo "======================================================"; \ for d in $(TEST_TEMPLATES); do \ if [ -e $(ALLBUILDDIR)/$$d/build.failed ]; then \ error=1; failed="$$failed $$d"; \ fi; \ done; \ for f in $$failed; do echo "====== Failed Build Log: $$f ======"; \ tail -60 $(ALLBUILDDIR)/$$f/build.log; \ done; \ rmdir $(ALLBUILDDIR) >/dev/null 2>&1; \ [ "$$failed" ] && echo -e "\nFailed configurations:$$failed"; \ exit $$error; $(addprefix $(ALLBUILDDIR)/,$(TEST_TEMPLATES)): $(call buildmakefile,$@) cp $(TEMPLDIR)/globalconfig.out.$(patsubst $(ALLBUILDDIR)/%,%,$@) \ $@/globalconfig.out $(MAKE) -C $@ 2>&1 | tee $@/build.log; \ if [ $${PIPESTATUS[0]} = 0 ]; \ then [ -z "$(KEEP_BUILD_DIRS)" ] && $(RM) -r $@; \ else echo $${PIPESTATUS[0]} > $@/build.failed; fi list: @echo "Templates:" @echo $(TEST_TEMPLATES) randcheck: $(RM) -r $(RANDBUILDDIR); \ $(call buildmakefile,$(RANDBUILDDIR)/b); \ while true; do \ $(RM) $(RANDBUILDDIR)/b/globalconfig.out; \ $(MAKE) -C $(RANDBUILDDIR)/b randconfig; \ fn=$$(cat $(RANDBUILDDIR)/b/globalconfig.out \ | grep -e "^CONFIG_" | sort | sha1sum \ | cut -f1 -d\ ); \ if [ -e "ok-$$fn" -o -e "failed-$$fn" ]; then \ echo "Configuration $$fn already checked." \ continue; \ fi; \ if $(MAKE) -C $(RANDBUILDDIR)/b -j$(PL); then \ cp $(RANDBUILDDIR)/b/globalconfig.out \ $(RANDBUILDDIR)/ok-$$fn; \ else \ [ -n "$$STOP_ON_ERROR" ] && exit 1; \ cp -a $(RANDBUILDDIR)/b \ $(RANDBUILDDIR)/failed-$$fn; \ fi; \ done randcheckstop: $(MAKE) STOP_ON_ERROR=1 randcheck randcheckagain: for f in $(RANDBUILDDIR)/failed-*; do \ if $(MAKE) -C $$f -j$(PL); then \ $(RM) -rf $$f; \ else \ [ -n "$$STOP_ON_ERROR" ] && exit 1; \ fi \ done randcheckagainstop: $(MAKE) STOP_ON_ERROR=1 randcheckagain help: @echo @echo "fiasco Builds the default configuration ($(DFL_TEMPLATE))" @echo "T=template Build a certain configuration" @echo "checkall Build all template configurations in one go" @echo "list List templates" @echo @echo "config menuconfig xconfig oldconfig" @echo " Configure kernel in \"$(DFLBUILDDIR)\"" @echo "$(DFLBUILDDIR) Build kernel in \"$(DFLBUILDDIR)\"" @echo "clean cleanall clean or cleanall in \"$(CLEANSUBDIRS)\"" @echo "purge cleanall, remove \"$(DFLBUILDDIR)\" and build helper" @echo @echo "Creating a custom kernel:" @echo @echo " Create a build directory with:" @echo " make BUILDDIR=builddir" @echo " Then build the kernel:" @echo " cd builddir" @echo " make config" @echo " make" @echo @echo "Call \"make help\" in the build directory for more information on build targets." @echo @echo "Default target: $(DFLBUILDDIR)" @echo .PHONY: man install clean cleanall fiasco.builddir.create fiasco \ l4check checkall config oldconfig menuconfig nconfig xconfig \ randcheck randcheckstop help
soap-DEIM/fiasco
Makefile
Makefile
gpl-2.0
7,488
<!DOCTYPE html> <!--[if lt IE 7]> <html class="no-js lt-ie9 lt-ie8 lt-ie7"> <![endif]--> <!--[if IE 7]> <html class="no-js lt-ie9 lt-ie8"> <![endif]--> <!--[if IE 8]> <html class="no-js lt-ie9"> <![endif]--> <!--[if gt IE 8]><!--> <html class="no-js"> <!--<![endif]--> <head> <meta charset="utf-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1"> <title></title> <meta name="description" content=""> <meta name="viewport" content="width=device-width"> <!-- Place favicon.ico and apple-touch-icon.png in the root directory --> <link rel="stylesheet" href="css/normalize.css"> <link rel="stylesheet" href="css/main.css"> <link rel="stylesheet" href="css/ui.css"> <link rel="stylesheet" href="css/areacolors.css"> <link rel="stylesheet" href="css/bootstrap.min.css"> <link rel="stylesheet" href="css/layout.css"> <script src="js/vendor/modernizr-2.6.2.min.js"></script> </head> <body> <!--[if lt IE 7]> <p class="chromeframe">You are using an outdated browser. <a href="http://browsehappy.com/">Upgrade your browser today</a> or <a href="http://www.google.com/chromeframe/?redirect=true">install Google Chrome Frame</a> to better experience this site.</p> <![endif]--> <!-- Add your site or application content here --> <div class="page liquid"> <div class="head"> <div id="ctmlbanner"> </div> </div> <div class="body"> <div class="leftCol"> </div> <div id='map'> </div> <div class="main" id="blob"> </div> </div> </div> <script src="//ajax.googleapis.com/ajax/libs/jquery/1.8.1/jquery.min.js"></script> <script>window.jQuery || document.write('<script src="js/vendor/jquery-1.8.1.min.js"><\/script>')</script> <script src='js/vendor/plugins.js'></script> <script language="javascript" type="text/javascript" src="js/vendor/bootstrap.min.js"></script> <script src='http://www.ctmlabs.net/ctmlabs/js/common.js'> </script> <script src='//www.ctmlabs.net/js/ctmlabs-banner.js?appname=CTMLabs&amp;redmineproject=CARB&amp;apphelp=.%2fhelp%2fhelp.html&amp;appcontact=.%2fhelp%2fabout.html%23getting-more-information'></script> <script type='text/javascript' src='js/vendor/ui.js'></script> <script type='text/javascript' src='js/vendor/async.min.js'></script> <script type='text/javascript' src='js/vendor/lodash.min.js'></script> <script language='javascript' type='text/javascript' src='/d3/d3.v2.min.js'> </script> <script language='javascript' type='text/javascript' src='js/vendor/polymaps.min.js'> </script> <script type='text/javascript' src='js/util.js'></script> <script type='text/javascript' src='js/map.js'></script> <!-- Google Analytics: change UA-XXXXX-X to be your site's ID. --> <script> var _gaq=[['_setAccount','UA-30207196-1'],['_trackPageview'],['_setDomainName', '.ctmlabs.net']]; (function(d,t){var g=d.createElement(t),s=d.getElementsByTagName(t)[0]; g.src=('https:'==location.protocol?'//ssl':'//www')+'.google-analytics.com/ga.js'; s.parentNode.insertBefore(g,s)}(document,'script')); </script> </body> </html>
jmarca/hpms_locator
hpms/index.html
HTML
gpl-2.0
3,320
REM Load key C:\Users\Jendrik\Downloads\pageant.exe C:\Users\Jendrik\private-key.ppk REM Update RedNotebook code bzr update C:\Users\Jendrik\RedNotebook C:\Python27\Scripts\py.test.exe C:\Users\Jendrik\RedNotebook\tests python build-translations.py python remove-build-dirs.py python C:\pyinstaller\pyinstaller.py rednotebook.spec dist\rednotebook.exe
davidbrenner/rednotebook
win/build-exe.bat
Batchfile
gpl-2.0
357
/* * Copyright (c) 2014, 2016, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. * * This code 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 * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ package com.oracle.graal.nodes.cfg; import com.oracle.graal.compiler.common.LocationIdentity; import com.oracle.graal.compiler.common.cfg.Loop; import com.oracle.graal.nodes.LoopBeginNode; public final class HIRLoop extends Loop<Block> { private LocationSet killLocations; protected HIRLoop(Loop<Block> parent, int index, Block header) { super(parent, index, header); } @Override public long numBackedges() { return ((LoopBeginNode) getHeader().getBeginNode()).loopEnds().count(); } public LocationSet getKillLocations() { if (killLocations == null) { killLocations = new LocationSet(); for (Block b : this.getBlocks()) { if (b.getLoop() == this) { killLocations.addAll(b.getKillLocations()); if (killLocations.isAny()) { break; } } } } for (Loop<Block> child : this.getChildren()) { if (killLocations.isAny()) { break; } killLocations.addAll(((HIRLoop) child).getKillLocations()); } return killLocations; } public boolean canKill(LocationIdentity location) { return getKillLocations().contains(location); } }
zapster/graal-core
graal/com.oracle.graal.nodes/src/com/oracle/graal/nodes/cfg/HIRLoop.java
Java
gpl-2.0
2,382
/**************************************************************************** ** ** Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies). ** All rights reserved. ** Contact: Nokia Corporation (qt-info@nokia.com) ** ** This file is part of the QtGui module of the Qt Toolkit. ** ** $QT_BEGIN_LICENSE:LGPL$ ** Commercial Usage ** Licensees holding valid Qt Commercial licenses may use this file in ** accordance with the Qt Commercial License Agreement provided with the ** Software or, alternatively, in accordance with the terms contained in ** a written agreement between you and Nokia. ** ** 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 as published by the Free Software ** Foundation and appearing in the file LICENSE.LGPL included in the ** packaging of this file. Please review the following information to ** ensure the GNU Lesser General Public License version 2.1 requirements ** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. ** ** In addition, as a special exception, Nokia gives you certain additional ** rights. These rights are described in the Nokia Qt LGPL Exception ** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. ** ** GNU General Public License Usage ** Alternatively, this file may be used under the terms of the GNU ** General Public License version 3.0 as published by the Free Software ** Foundation and appearing in the file LICENSE.GPL included in the ** packaging of this file. Please review the following information to ** ensure the GNU General Public License version 3.0 requirements will be ** met: http://www.gnu.org/copyleft/gpl.html. ** ** If you have questions regarding the use of this file, please contact ** Nokia at qt-info@nokia.com. ** $QT_END_LICENSE$ ** ****************************************************************************/ #include "qpainter.h" #include "qevent.h" #include "qdrawutil.h" #include "qapplication.h" #include "qabstractbutton.h" #include "qstyle.h" #include "qstyleoption.h" #include <limits.h> #include "qaction.h" #include "qclipboard.h" #include <qdebug.h> #include <qurl.h> #include "qlabel_p.h" #include "private/qstylesheetstyle_p.h" QT_BEGIN_NAMESPACE /*! \class QLabel \brief The QLabel widget provides a text or image display. \ingroup basicwidgets \ingroup text \mainclass QLabel is used for displaying text or an image. No user interaction functionality is provided. The visual appearance of the label can be configured in various ways, and it can be used for specifying a focus mnemonic key for another widget. A QLabel can contain any of the following content types: \table \header \o Content \o Setting \row \o Plain text \o Pass a QString to setText(). \row \o Rich text \o Pass a QString that contains rich text to setText(). \row \o A pixmap \o Pass a QPixmap to setPixmap(). \row \o A movie \o Pass a QMovie to setMovie(). \row \o A number \o Pass an \e int or a \e double to setNum(), which converts the number to plain text. \row \o Nothing \o The same as an empty plain text. This is the default. Set by clear(). \endtable When the content is changed using any of these functions, any previous content is cleared. By default, labels display \l{alignment}{left-aligned, vertically-centered} text and images, where any tabs in the text to be displayed are \l{Qt::TextExpandTabs}{automatically expanded}. However, the look of a QLabel can be adjusted and fine-tuned in several ways. The positioning of the content within the QLabel widget area can be tuned with setAlignment() and setIndent(). Text content can also wrap lines along word boundaries with setWordWrap(). For example, this code sets up a sunken panel with a two-line text in the bottom right corner (both lines being flush with the right side of the label): \snippet doc/src/snippets/code/src_gui_widgets_qlabel.cpp 0 The properties and functions QLabel inherits from QFrame can also be used to specify the widget frame to be used for any given label. A QLabel is often used as a label for an interactive widget. For this use QLabel provides a useful mechanism for adding an mnemonic (see QKeySequence) that will set the keyboard focus to the other widget (called the QLabel's "buddy"). For example: \snippet doc/src/snippets/code/src_gui_widgets_qlabel.cpp 1 In this example, keyboard focus is transferred to the label's buddy (the QLineEdit) when the user presses Alt+P. If the buddy was a button (inheriting from QAbstractButton), triggering the mnemonic would emulate a button click. \table 100% \row \o \inlineimage macintosh-label.png Screenshot of a Macintosh style label \o A label shown in the \l{Macintosh Style Widget Gallery}{Macintosh widget style}. \row \o \inlineimage plastique-label.png Screenshot of a Plastique style label \o A label shown in the \l{Plastique Style Widget Gallery}{Plastique widget style}. \row \o \inlineimage windowsxp-label.png Screenshot of a Windows XP style label \o A label shown in the \l{Windows XP Style Widget Gallery}{Windows XP widget style}. \endtable \sa QLineEdit, QTextEdit, QPixmap, QMovie, {fowler}{GUI Design Handbook: Label} */ #ifndef QT_NO_PICTURE /*! Returns the label's picture or 0 if the label doesn't have a picture. */ const QPicture *QLabel::picture() const { Q_D(const QLabel); return d->picture; } #endif /*! Constructs an empty label. The \a parent and widget flag \a f, arguments are passed to the QFrame constructor. \sa setAlignment(), setFrameStyle(), setIndent() */ QLabel::QLabel(QWidget *parent, Qt::WindowFlags f) : QFrame(*new QLabelPrivate(), parent, f) { Q_D(QLabel); d->init(); } /*! Constructs a label that displays the text, \a text. The \a parent and widget flag \a f, arguments are passed to the QFrame constructor. \sa setText(), setAlignment(), setFrameStyle(), setIndent() */ QLabel::QLabel(const QString &text, QWidget *parent, Qt::WindowFlags f) : QFrame(*new QLabelPrivate(), parent, f) { Q_D(QLabel); d->init(); setText(text); } #ifdef QT3_SUPPORT /*! \obsolete Constructs an empty label. The \a parent, \a name and widget flag \a f, arguments are passed to the QFrame constructor. \sa setAlignment(), setFrameStyle(), setIndent() */ QLabel::QLabel(QWidget *parent, const char *name, Qt::WindowFlags f) : QFrame(*new QLabelPrivate(), parent, f) { Q_D(QLabel); if (name) setObjectName(QString::fromAscii(name)); d->init(); } /*! \obsolete Constructs a label that displays the text, \a text. The \a parent, \a name and widget flag \a f, arguments are passed to the QFrame constructor. \sa setText(), setAlignment(), setFrameStyle(), setIndent() */ QLabel::QLabel(const QString &text, QWidget *parent, const char *name, Qt::WindowFlags f) : QFrame(*new QLabelPrivate(), parent, f) { Q_D(QLabel); if (name) setObjectName(QString::fromAscii(name)); d->init(); setText(text); } /*! \obsolete Constructs a label that displays the text \a text. The label has a buddy widget, \a buddy. If the \a text contains an underlined letter (a letter preceded by an ampersand, \&), when the user presses Alt+ the underlined letter, focus is passed to the buddy widget. The \a parent, \a name and widget flag, \a f, arguments are passed to the QFrame constructor. \sa setText(), setBuddy(), setAlignment(), setFrameStyle(), setIndent() */ QLabel::QLabel(QWidget *buddy, const QString &text, QWidget *parent, const char *name, Qt::WindowFlags f) : QFrame(*new QLabelPrivate(), parent, f) { Q_D(QLabel); if (name) setObjectName(QString::fromAscii(name)); d->init(); #ifndef QT_NO_SHORTCUT setBuddy(buddy); #endif setText(text); } #endif //QT3_SUPPORT /*! Destroys the label. */ QLabel::~QLabel() { Q_D(QLabel); d->clearContents(); } void QLabelPrivate::init() { Q_Q(QLabel); valid_hints = false; margin = 0; #ifndef QT_NO_MOVIE movie = 0; #endif #ifndef QT_NO_SHORTCUT shortcutId = 0; #endif pixmap = 0; scaledpixmap = 0; cachedimage = 0; #ifndef QT_NO_PICTURE picture = 0; #endif align = Qt::AlignLeft | Qt::AlignVCenter | Qt::TextExpandTabs; indent = -1; scaledcontents = false; textLayoutDirty = false; textDirty = false; textformat = Qt::AutoText; control = 0; textInteractionFlags = Qt::LinksAccessibleByMouse; isRichText = false; isTextLabel = false; q->setSizePolicy(QSizePolicy(QSizePolicy::Preferred, QSizePolicy::Preferred, QSizePolicy::Label)); #ifndef QT_NO_CURSOR validCursor = false; onAnchor = false; #endif openExternalLinks = false; setLayoutItemMargins(QStyle::SE_LabelLayoutItem); } /*! \property QLabel::text \brief the label's text If no text has been set this will return an empty string. Setting the text clears any previous content. The text will be interpreted either as plain text or as rich text, depending on the text format setting; see setTextFormat(). The default setting is Qt::AutoText; i.e. QLabel will try to auto-detect the format of the text set. If a buddy has been set, the buddy mnemonic key is updated from the new text. Note that QLabel is well-suited to display small rich text documents, such as small documents that get their document specific settings (font, text color, link color) from the label's palette and font properties. For large documents, use QTextEdit in read-only mode instead. QTextEdit can also provide a scroll bar when necessary. \note This function enables mouse tracking if \a text contains rich text. \sa setTextFormat(), setBuddy(), alignment */ void QLabel::setText(const QString &text) { Q_D(QLabel); if (d->text == text) return; QTextControl *oldControl = d->control; d->control = 0; d->clearContents(); d->text = text; d->isTextLabel = true; d->textDirty = true; d->isRichText = d->textformat == Qt::RichText || (d->textformat == Qt::AutoText && Qt::mightBeRichText(d->text)); d->control = oldControl; if (d->needTextControl()) { d->ensureTextControl(); } else { delete d->control; d->control = 0; } if (d->isRichText) { setMouseTracking(true); } else { // Note: mouse tracking not disabled intentionally } #ifndef QT_NO_SHORTCUT if (d->buddy) d->updateShortcut(); #endif d->updateLabel(); } QString QLabel::text() const { Q_D(const QLabel); return d->text; } /*! Clears any label contents. */ void QLabel::clear() { Q_D(QLabel); d->clearContents(); d->updateLabel(); } /*! \property QLabel::pixmap \brief the label's pixmap If no pixmap has been set this will return 0. Setting the pixmap clears any previous content. The buddy shortcut, if any, is disabled. */ void QLabel::setPixmap(const QPixmap &pixmap) { Q_D(QLabel); if (!d->pixmap || d->pixmap->cacheKey() != pixmap.cacheKey()) { d->clearContents(); d->pixmap = new QPixmap(pixmap); } if (d->pixmap->depth() == 1 && !d->pixmap->mask()) d->pixmap->setMask(*((QBitmap *)d->pixmap)); d->updateLabel(); } const QPixmap *QLabel::pixmap() const { Q_D(const QLabel); return d->pixmap; } #ifndef QT_NO_PICTURE /*! Sets the label contents to \a picture. Any previous content is cleared. The buddy shortcut, if any, is disabled. \sa picture(), setBuddy() */ void QLabel::setPicture(const QPicture &picture) { Q_D(QLabel); d->clearContents(); d->picture = new QPicture(picture); d->updateLabel(); } #endif // QT_NO_PICTURE /*! Sets the label contents to plain text containing the textual representation of integer \a num. Any previous content is cleared. Does nothing if the integer's string representation is the same as the current contents of the label. The buddy shortcut, if any, is disabled. \sa setText(), QString::setNum(), setBuddy() */ void QLabel::setNum(int num) { QString str; str.setNum(num); setText(str); } /*! \overload Sets the label contents to plain text containing the textual representation of double \a num. Any previous content is cleared. Does nothing if the double's string representation is the same as the current contents of the label. The buddy shortcut, if any, is disabled. \sa setText(), QString::setNum(), setBuddy() */ void QLabel::setNum(double num) { QString str; str.setNum(num); setText(str); } /*! \property QLabel::alignment \brief the alignment of the label's contents By default, the contents of the label are left-aligned and vertically-centered. \sa text */ void QLabel::setAlignment(Qt::Alignment alignment) { Q_D(QLabel); if (alignment == (d->align & (Qt::AlignVertical_Mask|Qt::AlignHorizontal_Mask))) return; d->align = (d->align & ~(Qt::AlignVertical_Mask|Qt::AlignHorizontal_Mask)) | (alignment & (Qt::AlignVertical_Mask|Qt::AlignHorizontal_Mask)); d->updateLabel(); } #ifdef QT3_SUPPORT /*! Use setAlignment(Qt::Alignment) instead. If \a alignment specifies text flags as well, use setTextFormat() to set those. */ void QLabel::setAlignment(int alignment) { Q_D(QLabel); d->align = alignment & ~(Qt::AlignVertical_Mask|Qt::AlignHorizontal_Mask|Qt::TextWordWrap); setAlignment(Qt::Alignment(QFlag(alignment))); } #endif Qt::Alignment QLabel::alignment() const { Q_D(const QLabel); return QFlag(d->align & (Qt::AlignVertical_Mask|Qt::AlignHorizontal_Mask)); } /*! \property QLabel::wordWrap \brief the label's word-wrapping policy If this property is true then label text is wrapped where necessary at word-breaks; otherwise it is not wrapped at all. By default, word wrap is disabled. \sa text */ void QLabel::setWordWrap(bool on) { Q_D(QLabel); if (on) d->align |= Qt::TextWordWrap; else d->align &= ~Qt::TextWordWrap; d->updateLabel(); } bool QLabel::wordWrap() const { Q_D(const QLabel); return d->align & Qt::TextWordWrap; } /*! \property QLabel::indent \brief the label's text indent in pixels If a label displays text, the indent applies to the left edge if alignment() is Qt::AlignLeft, to the right edge if alignment() is Qt::AlignRight, to the top edge if alignment() is Qt::AlignTop, and to to the bottom edge if alignment() is Qt::AlignBottom. If indent is negative, or if no indent has been set, the label computes the effective indent as follows: If frameWidth() is 0, the effective indent becomes 0. If frameWidth() is greater than 0, the effective indent becomes half the width of the "x" character of the widget's current font(). By default, the indent is -1, meaning that an effective indent is calculating in the manner described above. \sa alignment, margin, frameWidth(), font() */ void QLabel::setIndent(int indent) { Q_D(QLabel); d->indent = indent; d->updateLabel(); } int QLabel::indent() const { Q_D(const QLabel); return d->indent; } /*! \property QLabel::margin \brief the width of the margin The margin is the distance between the innermost pixel of the frame and the outermost pixel of contents. The default margin is 0. \sa indent */ int QLabel::margin() const { Q_D(const QLabel); return d->margin; } void QLabel::setMargin(int margin) { Q_D(QLabel); if (d->margin == margin) return; d->margin = margin; d->updateLabel(); } /*! Returns the size that will be used if the width of the label is \a w. If \a w is -1, the sizeHint() is returned. If \a w is 0 minimumSizeHint() is returned */ QSize QLabelPrivate::sizeForWidth(int w) const { Q_Q(const QLabel); if(q->minimumWidth() > 0) w = qMax(w, q->minimumWidth()); QSize contentsMargin(leftmargin + rightmargin, topmargin + bottommargin); QRect br; int hextra = 2 * margin; int vextra = hextra; QFontMetrics fm = q->fontMetrics(); if (pixmap && !pixmap->isNull()) br = pixmap->rect(); #ifndef QT_NO_PICTURE else if (picture && !picture->isNull()) br = picture->boundingRect(); #endif #ifndef QT_NO_MOVIE else if (movie && !movie->currentPixmap().isNull()) br = movie->currentPixmap().rect(); #endif else if (isTextLabel) { int align = QStyle::visualAlignment(q->layoutDirection(), QFlag(this->align)); // Add indentation int m = indent; if (m < 0 && q->frameWidth()) // no indent, but we do have a frame m = fm.width(QLatin1Char('x')) - margin*2; if (m > 0) { if ((align & Qt::AlignLeft) || (align & Qt::AlignRight)) hextra += m; if ((align & Qt::AlignTop) || (align & Qt::AlignBottom)) vextra += m; } if (control) { ensureTextLayouted(); const qreal oldTextWidth = control->textWidth(); // Calculate the length of document if w is the width if (align & Qt::TextWordWrap) { if (w >= 0) { w = qMax(w-hextra-contentsMargin.width(), 0); // strip margin and indent control->setTextWidth(w); } else { control->adjustSize(); } } else { control->setTextWidth(-1); } br = QRect(QPoint(0, 0), control->size().toSize()); // restore state control->setTextWidth(oldTextWidth); } else { // Turn off center alignment in order to avoid rounding errors for centering, // since centering involves a division by 2. At the end, all we want is the size. int flags = align & ~(Qt::AlignVCenter | Qt::AlignHCenter); if (hasShortcut) { flags |= Qt::TextShowMnemonic; QStyleOption opt; opt.initFrom(q); if (!q->style()->styleHint(QStyle::SH_UnderlineShortcut, &opt, q)) flags |= Qt::TextHideMnemonic; } bool tryWidth = (w < 0) && (align & Qt::TextWordWrap); if (tryWidth) w = fm.averageCharWidth() * 80; else if (w < 0) w = 2000; w -= (hextra + contentsMargin.width()); br = fm.boundingRect(0, 0, w ,2000, flags, text); if (tryWidth && br.height() < 4*fm.lineSpacing() && br.width() > w/2) br = fm.boundingRect(0, 0, w/2, 2000, flags, text); if (tryWidth && br.height() < 2*fm.lineSpacing() && br.width() > w/4) br = fm.boundingRect(0, 0, w/4, 2000, flags, text); } } else { br = QRect(QPoint(0, 0), QSize(fm.averageCharWidth(), fm.lineSpacing())); } const QSize contentsSize(br.width() + hextra, br.height() + vextra); return (contentsSize + contentsMargin).expandedTo(q->minimumSize()); } /*! \reimp */ int QLabel::heightForWidth(int w) const { Q_D(const QLabel); if (d->isTextLabel) return d->sizeForWidth(w).height(); return QWidget::heightForWidth(w); } /*! \property QLabel::openExternalLinks \since 4.2 Specifies whether QLabel should automatically open links using QDesktopServices::openUrl() instead of emitting the linkActivated() signal. \bold{Note:} The textInteractionFlags set on the label need to include either LinksAccessibleByMouse or LinksAccessibleByKeyboard. The default value is false. \sa textInteractionFlags() */ bool QLabel::openExternalLinks() const { Q_D(const QLabel); return d->openExternalLinks; } void QLabel::setOpenExternalLinks(bool open) { Q_D(QLabel); d->openExternalLinks = open; if (d->control) d->control->setOpenExternalLinks(open); } /*! \property QLabel::textInteractionFlags \since 4.2 Specifies how the label should interact with user input if it displays text. If the flags contain Qt::LinksAccessibleByKeyboard the focus policy is also automatically set to Qt::StrongFocus. If Qt::TextSelectableByKeyboard is set then the focus policy is set to Qt::ClickFocus. The default value is Qt::LinksAccessibleByMouse. */ void QLabel::setTextInteractionFlags(Qt::TextInteractionFlags flags) { Q_D(QLabel); if (d->textInteractionFlags == flags) return; d->textInteractionFlags = flags; if (flags & Qt::LinksAccessibleByKeyboard) setFocusPolicy(Qt::StrongFocus); else if (flags & (Qt::TextSelectableByKeyboard | Qt::TextSelectableByMouse)) setFocusPolicy(Qt::ClickFocus); else setFocusPolicy(Qt::NoFocus); if (d->needTextControl()) { d->ensureTextControl(); } else { delete d->control; d->control = 0; } if (d->control) d->control->setTextInteractionFlags(d->textInteractionFlags); } Qt::TextInteractionFlags QLabel::textInteractionFlags() const { Q_D(const QLabel); return d->textInteractionFlags; } /*!\reimp */ QSize QLabel::sizeHint() const { Q_D(const QLabel); if (!d->valid_hints) (void) QLabel::minimumSizeHint(); return d->sh; } /*! \reimp */ QSize QLabel::minimumSizeHint() const { Q_D(const QLabel); if (d->valid_hints) { if (d->sizePolicy == sizePolicy()) return d->msh; } ensurePolished(); d->valid_hints = true; d->sh = d->sizeForWidth(-1); // wrap ? golden ratio : min doc size QSize msh(-1, -1); if (!d->isTextLabel) { msh = d->sh; } else { msh.rheight() = d->sizeForWidth(QWIDGETSIZE_MAX).height(); // height for one line msh.rwidth() = d->sizeForWidth(0).width(); // wrap ? size of biggest word : min doc size if (d->sh.height() < msh.height()) msh.rheight() = d->sh.height(); } d->msh = msh; d->sizePolicy = sizePolicy(); return msh; } /*!\reimp */ void QLabel::mousePressEvent(QMouseEvent *ev) { Q_D(QLabel); d->sendControlEvent(ev); } /*!\reimp */ void QLabel::mouseMoveEvent(QMouseEvent *ev) { Q_D(QLabel); d->sendControlEvent(ev); } /*!\reimp */ void QLabel::mouseReleaseEvent(QMouseEvent *ev) { Q_D(QLabel); d->sendControlEvent(ev); } /*!\reimp */ void QLabel::contextMenuEvent(QContextMenuEvent *ev) { #ifdef QT_NO_CONTEXTMENU Q_UNUSED(ev); #else Q_D(QLabel); if (!d->isTextLabel) { ev->ignore(); return; } QMenu *menu = d->createStandardContextMenu(ev->pos()); if (!menu) { ev->ignore(); return; } ev->accept(); menu->exec(ev->globalPos()); delete menu; #endif } /*! \reimp */ void QLabel::focusInEvent(QFocusEvent *ev) { Q_D(QLabel); if (d->isTextLabel) { d->ensureTextControl(); d->sendControlEvent(ev); } QFrame::focusInEvent(ev); } /*! \reimp */ void QLabel::focusOutEvent(QFocusEvent *ev) { Q_D(QLabel); d->sendControlEvent(ev); QFrame::focusOutEvent(ev); } /*!\reimp */ bool QLabel::focusNextPrevChild(bool next) { Q_D(QLabel); if (d->control && d->control->setFocusToNextOrPreviousAnchor(next)) return true; return QFrame::focusNextPrevChild(next); } /*!\reimp */ void QLabel::keyPressEvent(QKeyEvent *ev) { Q_D(QLabel); d->sendControlEvent(ev); } /*!\reimp */ bool QLabel::event(QEvent *e) { Q_D(QLabel); QEvent::Type type = e->type(); #ifndef QT_NO_SHORTCUT if (type == QEvent::Shortcut) { QShortcutEvent *se = static_cast<QShortcutEvent *>(e); if (se->shortcutId() == d->shortcutId) { QWidget * w = d->buddy; QAbstractButton *button = qobject_cast<QAbstractButton *>(w); if (w->focusPolicy() != Qt::NoFocus) w->setFocus(Qt::ShortcutFocusReason); if (button && !se->isAmbiguous()) button->animateClick(); else window()->setAttribute(Qt::WA_KeyboardFocusChange); return true; } } else #endif if (type == QEvent::Resize) { if (d->control) d->textLayoutDirty = true; } else if (e->type() == QEvent::StyleChange #ifdef Q_WS_MAC || e->type() == QEvent::MacSizeChange #endif ) { d->setLayoutItemMargins(QStyle::SE_LabelLayoutItem); d->updateLabel(); } return QFrame::event(e); } /*!\reimp */ void QLabel::paintEvent(QPaintEvent *) { Q_D(QLabel); QStyle *style = QWidget::style(); QPainter painter(this); drawFrame(&painter); QRect cr = contentsRect(); cr.adjust(d->margin, d->margin, -d->margin, -d->margin); int align = QStyle::visualAlignment(layoutDirection(), QFlag(d->align)); #ifndef QT_NO_MOVIE if (d->movie) { if (d->scaledcontents) style->drawItemPixmap(&painter, cr, align, d->movie->currentPixmap().scaled(cr.size())); else style->drawItemPixmap(&painter, cr, align, d->movie->currentPixmap()); } else #endif if (d->isTextLabel) { QRectF lr = d->layoutRect(); if (d->control) { #ifndef QT_NO_SHORTCUT const bool underline = (bool)style->styleHint(QStyle::SH_UnderlineShortcut, 0, this, 0); if (d->shortcutId != 0 && underline != d->shortcutCursor.charFormat().fontUnderline()) { QTextCharFormat fmt; fmt.setFontUnderline(underline); d->shortcutCursor.mergeCharFormat(fmt); } #endif d->ensureTextLayouted(); QAbstractTextDocumentLayout::PaintContext context; QStyleOption opt(0); opt.init(this); if (!isEnabled() && style->styleHint(QStyle::SH_EtchDisabledText, &opt, this)) { context.palette = palette(); context.palette.setColor(QPalette::Text, context.palette.light().color()); painter.save(); painter.translate(lr.x() + 1, lr.y() + 1); painter.setClipRect(lr.translated(-lr.x() - 1, -lr.y() - 1)); QAbstractTextDocumentLayout *layout = d->control->document()->documentLayout(); layout->draw(&painter, context); painter.restore(); } // Adjust the palette context.palette = palette(); #ifndef QT_NO_STYLE_STYLESHEET if (QStyleSheetStyle* cssStyle = qobject_cast<QStyleSheetStyle*>(style)) { cssStyle->focusPalette(this, &opt, &context.palette); } #endif if (foregroundRole() != QPalette::Text && isEnabled()) context.palette.setColor(QPalette::Text, context.palette.color(foregroundRole())); painter.save(); painter.translate(lr.topLeft()); painter.setClipRect(lr.translated(-lr.x(), -lr.y())); d->control->setPalette(context.palette); d->control->drawContents(&painter, QRectF(), this); painter.restore(); } else { int flags = align; if (d->hasShortcut) { flags |= Qt::TextShowMnemonic; QStyleOption opt; opt.initFrom(this); if (!style->styleHint(QStyle::SH_UnderlineShortcut, &opt, this)) flags |= Qt::TextHideMnemonic; } style->drawItemText(&painter, lr.toRect(), flags, palette(), isEnabled(), d->text, foregroundRole()); } } else #ifndef QT_NO_PICTURE if (d->picture) { QRect br = d->picture->boundingRect(); int rw = br.width(); int rh = br.height(); if (d->scaledcontents) { painter.save(); painter.translate(cr.x(), cr.y()); painter.scale((double)cr.width()/rw, (double)cr.height()/rh); painter.drawPicture(-br.x(), -br.y(), *d->picture); painter.restore(); } else { int xo = 0; int yo = 0; if (align & Qt::AlignVCenter) yo = (cr.height()-rh)/2; else if (align & Qt::AlignBottom) yo = cr.height()-rh; if (align & Qt::AlignRight) xo = cr.width()-rw; else if (align & Qt::AlignHCenter) xo = (cr.width()-rw)/2; painter.drawPicture(cr.x()+xo-br.x(), cr.y()+yo-br.y(), *d->picture); } } else #endif if (d->pixmap && !d->pixmap->isNull()) { QPixmap pix; if (d->scaledcontents) { if (!d->scaledpixmap || d->scaledpixmap->size() != cr.size()) { if (!d->cachedimage) d->cachedimage = new QImage(d->pixmap->toImage()); delete d->scaledpixmap; d->scaledpixmap = new QPixmap(QPixmap::fromImage(d->cachedimage->scaled(cr.size(),Qt::IgnoreAspectRatio,Qt::SmoothTransformation))); } pix = *d->scaledpixmap; } else pix = *d->pixmap; QStyleOption opt; opt.initFrom(this); if (!isEnabled()) pix = style->generatedIconPixmap(QIcon::Disabled, pix, &opt); style->drawItemPixmap(&painter, cr, align, pix); } } /*! Updates the label, but not the frame. */ void QLabelPrivate::updateLabel() { Q_Q(QLabel); valid_hints = false; if (isTextLabel) { QSizePolicy policy = q->sizePolicy(); const bool wrap = align & Qt::TextWordWrap; policy.setHeightForWidth(wrap); if (policy != q->sizePolicy()) // ### should be replaced by WA_WState_OwnSizePolicy idiom q->setSizePolicy(policy); textLayoutDirty = true; } q->updateGeometry(); q->update(q->contentsRect()); } #ifndef QT_NO_SHORTCUT /*! Sets this label's buddy to \a buddy. When the user presses the shortcut key indicated by this label, the keyboard focus is transferred to the label's buddy widget. The buddy mechanism is only available for QLabels that contain text in which one character is prefixed with an ampersand, '&'. This character is set as the shortcut key. See the \l QKeySequence::mnemonic() documentation for details (to display an actual ampersand, use '&&'). In a dialog, you might create two data entry widgets and a label for each, and set up the geometry layout so each label is just to the left of its data entry widget (its "buddy"), for example: \snippet doc/src/snippets/code/src_gui_widgets_qlabel.cpp 2 With the code above, the focus jumps to the Name field when the user presses Alt+N, and to the Phone field when the user presses Alt+P. To unset a previously set buddy, call this function with \a buddy set to 0. \sa buddy(), setText(), QShortcut, setAlignment() */ void QLabel::setBuddy(QWidget *buddy) { Q_D(QLabel); d->buddy = buddy; if (d->isTextLabel) { if (d->shortcutId) releaseShortcut(d->shortcutId); d->shortcutId = 0; d->textDirty = true; if (buddy) d->updateShortcut(); // grab new shortcut d->updateLabel(); } } /*! Returns this label's buddy, or 0 if no buddy is currently set. \sa setBuddy() */ QWidget * QLabel::buddy() const { Q_D(const QLabel); return d->buddy; } void QLabelPrivate::updateShortcut() { Q_Q(QLabel); Q_ASSERT(shortcutId == 0); // Introduce an extra boolean to indicate the presence of a shortcut in the // text. We cannot use the shortcutId itself because on the mac mnemonics are // off by default, so QKeySequence::mnemonic always returns an empty sequence. // But then we do want to hide the ampersands, so we can't use shortcutId. hasShortcut = false; if (control) { ensureTextPopulated(); // Underline the first character that follows an ampersand shortcutCursor = control->document()->find(QLatin1String("&")); if (shortcutCursor.isNull()) return; hasShortcut = true; shortcutId = q->grabShortcut(QKeySequence::mnemonic(text)); shortcutCursor.deleteChar(); // remove the ampersand shortcutCursor.movePosition(QTextCursor::NextCharacter, QTextCursor::KeepAnchor); } else { if (!text.contains(QLatin1String("&"))) return; hasShortcut = true; shortcutId = q->grabShortcut(QKeySequence::mnemonic(text)); } } #endif // QT_NO_SHORTCUT #ifndef QT_NO_MOVIE void QLabelPrivate::_q_movieUpdated(const QRect& rect) { Q_Q(QLabel); if (movie && movie->isValid()) { QRect r; if (scaledcontents) { QRect cr = q->contentsRect(); QRect pixmapRect(cr.topLeft(), movie->currentPixmap().size()); if (pixmapRect.isEmpty()) return; r.setRect(cr.left(), cr.top(), (rect.width() * cr.width()) / pixmapRect.width(), (rect.height() * cr.height()) / pixmapRect.height()); } else { r = q->style()->itemPixmapRect(q->contentsRect(), align, movie->currentPixmap()); r.translate(rect.x(), rect.y()); r.setWidth(qMin(r.width(), rect.width())); r.setHeight(qMin(r.height(), rect.height())); } q->update(r); } } void QLabelPrivate::_q_movieResized(const QSize& size) { Q_Q(QLabel); q->update(); //we need to refresh the whole background in case the new size is smaler valid_hints = false; _q_movieUpdated(QRect(QPoint(0,0), size)); q->updateGeometry(); } /*! Sets the label contents to \a movie. Any previous content is cleared. The label does NOT take ownership of the movie. The buddy shortcut, if any, is disabled. \sa movie(), setBuddy() */ void QLabel::setMovie(QMovie *movie) { Q_D(QLabel); d->clearContents(); if (!movie) return; d->movie = movie; connect(movie, SIGNAL(resized(QSize)), this, SLOT(_q_movieResized(QSize))); connect(movie, SIGNAL(updated(QRect)), this, SLOT(_q_movieUpdated(QRect))); // Assume that if the movie is running, // resize/update signals will come soon enough if (movie->state() != QMovie::Running) d->updateLabel(); } #endif // QT_NO_MOVIE /*! \internal Clears any contents, without updating/repainting the label. */ void QLabelPrivate::clearContents() { delete control; control = 0; isTextLabel = false; hasShortcut = false; #ifndef QT_NO_PICTURE delete picture; picture = 0; #endif delete scaledpixmap; scaledpixmap = 0; delete cachedimage; cachedimage = 0; delete pixmap; pixmap = 0; text.clear(); Q_Q(QLabel); #ifndef QT_NO_SHORTCUT if (shortcutId) q->releaseShortcut(shortcutId); shortcutId = 0; #endif #ifndef QT_NO_MOVIE if (movie) { QObject::disconnect(movie, SIGNAL(resized(QSize)), q, SLOT(_q_movieResized(QSize))); QObject::disconnect(movie, SIGNAL(updated(QRect)), q, SLOT(_q_movieUpdated(QRect))); } movie = 0; #endif #ifndef QT_NO_CURSOR if (onAnchor) { if (validCursor) q->setCursor(cursor); else q->unsetCursor(); } validCursor = false; onAnchor = false; #endif } #ifndef QT_NO_MOVIE /*! Returns a pointer to the label's movie, or 0 if no movie has been set. \sa setMovie() */ QMovie *QLabel::movie() const { Q_D(const QLabel); return d->movie; } #endif // QT_NO_MOVIE /*! \property QLabel::textFormat \brief the label's text format See the Qt::TextFormat enum for an explanation of the possible options. The default format is Qt::AutoText. \sa text() */ Qt::TextFormat QLabel::textFormat() const { Q_D(const QLabel); return d->textformat; } void QLabel::setTextFormat(Qt::TextFormat format) { Q_D(QLabel); if (format != d->textformat) { d->textformat = format; QString t = d->text; if (!t.isNull()) { d->text.clear(); setText(t); } } } /*! \reimp */ void QLabel::changeEvent(QEvent *ev) { Q_D(QLabel); if(ev->type() == QEvent::FontChange || ev->type() == QEvent::ApplicationFontChange) { if (d->isTextLabel) { if (d->control) d->control->document()->setDefaultFont(font()); d->updateLabel(); } } else if (ev->type() == QEvent::PaletteChange && d->control) { d->control->setPalette(palette()); } else if (ev->type() == QEvent::ContentsRectChange) { d->updateLabel(); } else if (ev->type() == QEvent::LayoutDirectionChange) { if (d->isTextLabel && d->control) { d->sendControlEvent(ev); } } QFrame::changeEvent(ev); } /*! \property QLabel::scaledContents \brief whether the label will scale its contents to fill all available space. When enabled and the label shows a pixmap, it will scale the pixmap to fill the available space. This property's default is false. */ bool QLabel::hasScaledContents() const { Q_D(const QLabel); return d->scaledcontents; } void QLabel::setScaledContents(bool enable) { Q_D(QLabel); if ((bool)d->scaledcontents == enable) return; d->scaledcontents = enable; if (!enable) { delete d->scaledpixmap; d->scaledpixmap = 0; delete d->cachedimage; d->cachedimage = 0; } update(contentsRect()); } /*! \fn void QLabel::setAlignment(Qt::AlignmentFlag flag) \internal Without this function, a call to e.g. setAlignment(Qt::AlignTop) results in the \c QT3_SUPPORT function setAlignment(int) being called, rather than setAlignment(Qt::Alignment). */ // Returns the rect that is available for us to draw the document QRect QLabelPrivate::documentRect() const { Q_Q(const QLabel); Q_ASSERT_X(isTextLabel, "documentRect", "document rect called for label that is not a text label!"); QRect cr = q->contentsRect(); cr.adjust(margin, margin, -margin, -margin); const int align = QStyle::visualAlignment(q->layoutDirection(), QFlag(this->align)); int m = indent; if (m < 0 && q->frameWidth()) // no indent, but we do have a frame m = q->fontMetrics().width(QLatin1Char('x')) / 2 - margin; if (m > 0) { if (align & Qt::AlignLeft) cr.setLeft(cr.left() + m); if (align & Qt::AlignRight) cr.setRight(cr.right() - m); if (align & Qt::AlignTop) cr.setTop(cr.top() + m); if (align & Qt::AlignBottom) cr.setBottom(cr.bottom() - m); } return cr; } void QLabelPrivate::ensureTextPopulated() const { if (!textDirty) return; if (control) { QTextDocument *doc = control->document(); if (textDirty) { #ifndef QT_NO_TEXTHTMLPARSER if (isRichText) doc->setHtml(text); else doc->setPlainText(text); #else doc->setPlainText(text); #endif doc->setUndoRedoEnabled(false); } } textDirty = false; } void QLabelPrivate::ensureTextLayouted() const { if (!textLayoutDirty) return; ensureTextPopulated(); Q_Q(const QLabel); if (control) { QTextDocument *doc = control->document(); QTextOption opt = doc->defaultTextOption(); opt.setAlignment(QFlag(this->align)); if (this->align & Qt::TextWordWrap) opt.setWrapMode(QTextOption::WordWrap); else opt.setWrapMode(QTextOption::ManualWrap); opt.setTextDirection(q->layoutDirection()); doc->setDefaultTextOption(opt); QTextFrameFormat fmt = doc->rootFrame()->frameFormat(); fmt.setMargin(0); doc->rootFrame()->setFrameFormat(fmt); doc->setTextWidth(documentRect().width()); } textLayoutDirty = false; } void QLabelPrivate::ensureTextControl() const { Q_Q(const QLabel); if (!isTextLabel) return; if (!control) { control = new QTextControl(const_cast<QLabel *>(q)); control->document()->setUndoRedoEnabled(false); control->document()->setDefaultFont(q->font()); control->setTextInteractionFlags(textInteractionFlags); control->setOpenExternalLinks(openExternalLinks); control->setPalette(q->palette()); control->setFocus(q->hasFocus()); QObject::connect(control, SIGNAL(updateRequest(QRectF)), q, SLOT(update())); QObject::connect(control, SIGNAL(linkHovered(QString)), q, SLOT(_q_linkHovered(QString))); QObject::connect(control, SIGNAL(linkActivated(QString)), q, SIGNAL(linkActivated(QString))); textLayoutDirty = true; textDirty = true; } } void QLabelPrivate::sendControlEvent(QEvent *e) { Q_Q(QLabel); if (!isTextLabel || !control || textInteractionFlags == Qt::NoTextInteraction) { e->ignore(); return; } control->processEvent(e, -layoutRect().topLeft(), q); } void QLabelPrivate::_q_linkHovered(const QString &anchor) { Q_Q(QLabel); #ifndef QT_NO_CURSOR if (anchor.isEmpty()) { // restore cursor if (validCursor) q->setCursor(cursor); else q->unsetCursor(); onAnchor = false; } else if (!onAnchor) { validCursor = q->testAttribute(Qt::WA_SetCursor); if (validCursor) { cursor = q->cursor(); } q->setCursor(Qt::PointingHandCursor); onAnchor = true; } #endif emit q->linkHovered(anchor); } // Return the layout rect - this is the rect that is given to the layout painting code // This may be different from the document rect since vertical alignment is not // done by the text layout code QRectF QLabelPrivate::layoutRect() const { QRectF cr = documentRect(); if (!control) return cr; ensureTextLayouted(); // Caculate y position manually qreal rh = control->document()->documentLayout()->documentSize().height(); qreal yo = 0; if (align & Qt::AlignVCenter) yo = qMax((cr.height()-rh)/2, qreal(0)); else if (align & Qt::AlignBottom) yo = qMax(cr.height()-rh, qreal(0)); return QRectF(cr.x(), yo + cr.y(), cr.width(), cr.height()); } // Returns the point in the document rect adjusted with p QPoint QLabelPrivate::layoutPoint(const QPoint& p) const { QRect lr = layoutRect().toRect(); return p - lr.topLeft(); } #ifndef QT_NO_CONTEXTMENU QMenu *QLabelPrivate::createStandardContextMenu(const QPoint &pos) { QString linkToCopy; QPoint p; if (control && isRichText) { p = layoutPoint(pos); linkToCopy = control->document()->documentLayout()->anchorAt(p); } if (linkToCopy.isEmpty() && !control) return 0; return control->createStandardContextMenu(p, q_func()); } #endif /*! \fn void QLabel::linkHovered(const QString &link) \since 4.2 This signal is emitted when the user hovers over a link. The URL referred to by the anchor is passed in \a link. \sa linkActivated() */ /*! \fn void QLabel::linkActivated(const QString &link) \since 4.2 This signal is emitted when the user clicks a link. The URL referred to by the anchor is passed in \a link. \sa linkHovered() */ QT_END_NAMESPACE #include "moc_qlabel.cpp"
librelab/qtmoko-test
qtopiacore/qt/src/gui/widgets/qlabel.cpp
C++
gpl-2.0
44,261
<?php /** * DmMediaTable * * This class has been auto-generated by the Doctrine ORM Framework */ class DmMediaTable extends PluginDmMediaTable { /** * Returns an instance of this class. * * @return DmMediaTable The table object */ public static function getInstance() { return Doctrine_Core::getTable('DmMedia'); } }
Teplitsa/bquest.ru
lib/model/doctrine/dmCorePlugin/DmMediaTable.class.php
PHP
gpl-2.0
366
/* * Copyright by iNet Solutions 2008. * * http://www.truthinet.com.vn/licenses */ Ext.onReady(function(){ var activeMenu; function createMenu(name){ var el = Ext.get(name+'-link'); if (!el) return; var tid = 0, menu, doc = Ext.getDoc(); var handleOver = function(e, t){ if(t != el.dom && t != menu.dom && !e.within(el) && !e.within(menu)){ hideMenu(); } }; var hideMenu = function(){ if(menu){ menu.hide(); el.setStyle('text-decoration', ''); doc.un('mouseover', handleOver); doc.un('mousedown', handleDown); } } var handleDown = function(e){ if(!e.within(menu)){ hideMenu(); } } var showMenu = function(){ clearTimeout(tid); tid = 0; if (!menu) { menu = new Ext.Layer({shadow:'sides',hideMode: 'display'}, name+'-menu'); } menu.hideMenu = hideMenu; menu.el = el; if(activeMenu && menu != activeMenu){ activeMenu.hideMenu(); } activeMenu = menu; if (!menu.isVisible()) { menu.show(); menu.alignTo(el, 'tl-bl?'); menu.sync(); el.setStyle('text-decoration', 'underline'); doc.on('mouseover', handleOver, null, {buffer:150}); doc.on('mousedown', handleDown); } } el.on('mouseover', function(e){ if(!tid){ tid = showMenu.defer(150); } }); el.on('mouseout', function(e){ if(tid && !e.within(el, true)){ clearTimeout(tid); tid = 0; } }); } createMenu('iwebos'); createMenu('home'); createMenu('document'); createMenu('calendar'); createMenu('mail'); createMenu('administrator'); createMenu('contact'); createMenu('paperwork'); // expanders Ext.getBody().on('click', function(e, t){ t = Ext.get(t); e.stopEvent(); var bd = t.next('div.expandable-body'); bd.enableDisplayMode(); var bdi = bd.first(); var expanded = bd.isVisible(); if(expanded){ bd.hide(); }else{ bdi.hide(); bd.show(); bdi.slideIn('l', {duration:0.2, stopFx: true, easing:'easeOut'}); } t.update(!expanded ? 'Hide details' : 'Show details'); }, null, {delegate:'a.expander'}); });
inetcloud/iMail
source/mail-admin/js/inet/ui/common/menu/Menu.js
JavaScript
gpl-2.0
2,082
# -*- encoding: utf-8 -*- ############################################################################## # # OpenERP, Open Source Management Solution # Copyright (C) 2004-2009 Tiny SPRL (<http://tiny.be>). All Rights Reserved # d$ # # 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/>. # ############################################################################## from openerp.osv import fields, osv from openerp.tools.translate import _ class stock_incoterms(osv.Model): """ stock_incoterm """ _inherit = 'stock.incoterms' _columns = { 'description': fields.text('Description', help='Formal description for this incoterm.'), }
3dfxsoftware/cbss-addons
incoterm_ext/incoterm.py
Python
gpl-2.0
1,298
{% extends 'admin/base.html' %} {% block stage %} <style type="text/css"> .display{ display: none; } </style> <!-- main content starts here--> <div class="panel panel-default"> <div class="panel-heading"> <h3 class="panel-title">BlogPost Limit</h3> </div> <div class="panel-body"> <fieldset> <form method="POST" id="blogpostlimitform"> {% csrf_token %} <div class="form-group"> <label for="exampleInputEmail">Min Blogposts</label> <input type="number" class="form-control" id="min_published_blogs" name="min_published_blogs" min='0' value="{{ users.0.min_published_blogs }}"> </div> <div class="form-group"> <label for="exampleInputEmail">Max Blogposts</label> <input type="number" class="form-control" id="max_published_blogs" name="max_published_blogs" min='0' value="{{ users.0.max_published_blogs }}"> </div> <div class="save-btn"> <i class="fa fa-floppy-o"></i> <input type="submit" value="Save" class="save" id="search_lessons"> </div> </form> <div class="all_urls display"> </div> </fieldset> </div> </div> <!-- main content ends here--> <script type="text/javascript"> $ = jQuery; $("form#blogpostlimitform").submit(function(e) { e.preventDefault(); $.post(".", $("form#blogpostlimitform").serialize(), function(msg) { console.log(msg) $('p.failure').remove(); $('.all_urls').hide() if (msg.error) { $('#max_published_blogs').after('<p class="failure">' + msg.response + '</p>'); } else { alert(msg.response) window.location = "/portal/" } }, 'json'); }); </script> {% endblock %}
MicroPyramid/MicroSite
templates/admin/blog_post_limit.html
HTML
gpl-2.0
1,737
/** * Copyright (c) 2001-2002. Department of Family Medicine, McMaster University. All Rights Reserved. * This software is published under the GPL GNU General Public License. * 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. * * This software was written for the * Department of Family Medicine * McMaster University * Hamilton * Ontario, Canada */ package oscar.oscarWaitingList.util; import java.util.Date; import java.util.List; import org.oscarehr.common.dao.WaitingListDao; import org.oscarehr.common.model.WaitingList; import org.oscarehr.util.MiscUtils; import org.oscarehr.util.SpringUtils; import oscar.util.ConversionUtils; public class WLWaitingListUtil { // Modified this method in Feb 2007 to ensure that all records cannot be deleted except hidden. static public synchronized void removeFromWaitingList(String waitingListID, String demographicNo) { MiscUtils.getLogger().debug("WLWaitingListUtil.removeFromWaitingList(): removing waiting list: " + waitingListID + " for patient " + demographicNo); WaitingListDao dao = SpringUtils.getBean(WaitingListDao.class); for (WaitingList wl : dao.findByWaitingListIdAndDemographicId(ConversionUtils.fromIntString(waitingListID), ConversionUtils.fromIntString(demographicNo))) { wl.setHistory(true); dao.merge(wl); } rePositionWaitingList(waitingListID); } static public synchronized void add2WaitingList(String waitingListID, String waitingListNote, String demographicNo, String onListSince) { MiscUtils.getLogger().debug("WLWaitingListUtil.add2WaitingList(): adding to waitingList: " + waitingListID + " for patient " + demographicNo); boolean emptyIds = waitingListID.equalsIgnoreCase("0") || demographicNo.equalsIgnoreCase("0"); if (emptyIds) { MiscUtils.getLogger().debug("Ids are not proper - exiting"); return; } WaitingListDao dao = SpringUtils.getBean(WaitingListDao.class); int maxPosition = dao.getMaxPosition(ConversionUtils.fromIntString(waitingListID)); WaitingList list = new WaitingList(); list.setListId(maxPosition); list.setDemographicNo(ConversionUtils.fromIntString(demographicNo)); list.setNote(waitingListNote); if (onListSince == null || onListSince.length() <= 0) { list.setOnListSince(new Date()); } else { list.setOnListSince(ConversionUtils.fromDateString(onListSince)); } list.setPosition(maxPosition + 1); list.setHistory(false); dao.persist(list); // update the waiting list positions rePositionWaitingList(waitingListID); } /* * This method adds the Waiting List note to the same position in the waitingList table but do not delete previous ones - later on DisplayWaitingList.jsp will display only the most current Waiting List Note record. */ static public synchronized void updateWaitingListRecord(String waitingListID, String waitingListNote, String demographicNo, String onListSince) { MiscUtils.getLogger().debug("WLWaitingListUtil.updateWaitingListRecord(): waitingListID: " + waitingListID + " for patient " + demographicNo); boolean isWatingIdSet = !waitingListID.equalsIgnoreCase("0") && !demographicNo.equalsIgnoreCase("0"); if (!isWatingIdSet) return; WaitingListDao dao = SpringUtils.getBean(WaitingListDao.class); List<WaitingList> waitingLists = dao.findByWaitingListIdAndDemographicId(ConversionUtils.fromIntString(waitingListID), ConversionUtils.fromIntString(demographicNo)); if (waitingLists.isEmpty()) return; long pos = 1; for (WaitingList wl : waitingLists) { pos = wl.getPosition(); } // set all previous records 'is_history' fielf to 'N' --> to keep as record but never display for (WaitingList wl : waitingLists) { wl.setHistory(true); dao.merge(wl); } WaitingList wl = new WaitingList(); wl.setListId(ConversionUtils.fromIntString(waitingListID)); wl.setDemographicNo(ConversionUtils.fromIntString(demographicNo)); wl.setNote(waitingListNote); wl.setPosition(pos); wl.setOnListSince(ConversionUtils.fromDateString(onListSince)); wl.setHistory(false); dao.saveEntity(wl); // update the waiting list positions rePositionWaitingList(waitingListID); } /* * This method adds the Waiting List note to the same position in the waitingList table but do not delete previous ones - later on DisplayWaitingList.jsp will display only the most current Waiting List Note record. */ static public synchronized void updateWaitingList(String id, String waitingListID, String waitingListNote, String demographicNo, String onListSince) { MiscUtils.getLogger().debug("WLWaitingListUtil.updateWaitingList(): waitingListID: " + waitingListID + " for patient " + demographicNo); boolean idsSet = !waitingListID.equalsIgnoreCase("0") && !demographicNo.equalsIgnoreCase("0"); if (!idsSet) { MiscUtils.getLogger().debug("Ids are not set - exiting"); return; } boolean wlIdsSet = (id != null && !id.equals("")); if (!wlIdsSet) { MiscUtils.getLogger().debug("Waiting list id is not set"); return; } WaitingListDao dao = SpringUtils.getBean(WaitingListDao.class); WaitingList waitingListEntry = dao.find(ConversionUtils.fromIntString(id)); if (waitingListEntry == null) { MiscUtils.getLogger().debug("Unable to fetch waiting list with id " + id); return; } waitingListEntry.setListId(ConversionUtils.fromIntString(waitingListID)); waitingListEntry.setNote(waitingListNote); waitingListEntry.setOnListSince(ConversionUtils.fromDateString(onListSince)); dao.merge(waitingListEntry); } public static void rePositionWaitingList(String waitingListID) { int i = 1; WaitingListDao dao = SpringUtils.getBean(WaitingListDao.class); for (WaitingList waitingList : dao.findByWaitingListId(ConversionUtils.fromIntString(waitingListID))) { waitingList.setPosition(i); dao.merge(waitingList); i++; } } }
hexbinary/landing
src/main/java/oscar/oscarWaitingList/util/WLWaitingListUtil.java
Java
gpl-2.0
6,477
<?php $db = mysql_connect("localhost","root",""); mysql_select_db("asterisk"); // Астериск по каким то непонятным причинам сбрасывает в cdr одинаковые записи без forkcdr и т.д. // задача найти их и убрать. //проверка на трансфер $transfer = array(); $q = " select c.id, c.calldate, c.src, c.channel, c.lastdata, c.duration, c.billsec, c.disposition, c.uniqueid from cdr as c left join stat as s on c.id=s.cdrid where c.lastapp='Transferred Call' and c.calldate>='2010-04-01 00:00:00';"; //and // s.id is NULL; //"; $r = mysql_query($q); $n = mysql_num_rows($r); for($i=0;$i<$n;$i++) { list($id,$cd,$src, $ch, $ldata,$dur,$bs,$disp,$uid) = mysql_fetch_array($r); $transfer[$ch] = $id.';;'.$cd.';;'.$src.';;'.$ldata.';;'.$dur.';;'.$bs.';;'.$disp.';;'.$uid; } print_r($transfer); $q = " select c.id as cdrid, c.dcontext as dcontext, c.calldate as calldate, c.src as src, c.dst as dst, c.channel as channel, c.dstchannel as dstchannel, c.duration as duration, c.billsec as billsec, c.disposition as disposition, c.uniqueid as uniqueid, s.id as sid from cdr as c left join stat as s on c.id=s.cdrid where s.id is NULL"; //echo $q."<br>"; $r = mysql_query($q); $n = mysql_num_rows($r); echo date("Y-m-d H:i:s: ").$n."\n"; //$n = 30; $io = ''; $cdrid = 0; $cd = ''; for($i=0;$i<$n;$i++) { $row = mysql_fetch_array($r); //print_r($row); $cdrid = $row['cdrid']; if(substr($row['dcontext'],0,2) == "ip" || $row['dcontext']=='inbound') // ip - old, inbound - new $io = "in"; if(substr($row['dcontext'],0,1) == "c" || substr($row['dcontext'],0,1) == "p") $io = "out"; $cd = $row['calldate']; $src = $row['src']; $dst = $row['dst']; $kod = '-1'; //самая главная штука :) -1 = не обсчитан //$chars = preg_split('//', $str, -1, PREG_SPLIT_NO_EMPTY); $aa = preg_split('/-/', $row['channel'], -1, PREG_SPLIT_NO_EMPTY); $ch = $aa[0]; $aa = preg_split('/-/', $row['dstchannel'], -1, PREG_SPLIT_NO_EMPTY); $dstch = $aa[0]; $duration = $row['duration']; $billsec = $row['billsec']; $cause = $row['disposition']; $uid = $row['uniqueid']; //$tr = isset($transfer[$row['dstchannel']]); $tr = 0; $qt=''; /*if(isset($transfer[$row['dstchannel']])){ $tch = $row['dstchannel']; $a = str_getcsv($transfer[$tch],';;'); list($tid,$tcd,$tsrc,$tldata,$tdur,$tbs,$tdisp,$tuid) = $a; if($tcd==$cd){ //у нас есть трансфер $qt = "insert into stat values(0,$tid,'tr','$cd',NOW(),'$tsrc','$dst','$kod','$ch','$tldata','$tdur','$tbs','$tdisp','$tuid','0.00','0.00');"; echo $qt."\n"; $kod = -5; } }*/ $qu = "insert into stat values(0,$cdrid,'$io','$cd',NOW(),'$src','$dst','$kod','$ch','$dstch','$duration','$billsec','$cause','$uid','0.00','0.00');"; $ru = mysql_query($qu); if($kod==-5) $rt = mysql_query($qt); //if(isset($transfer[$row['dstchannel']])) echo $qu."\n"; //echo '<br><br>'; } mysql_close($db); function str_getcsv($p,$d) { return preg_split("/$d/", $p); } ?>
Calc86/tel
cron/unique.php
PHP
gpl-2.0
3,241
-- Creature Spawn: General Nazgrim SET @CGUID := 1349; DELETE FROM creature WHERE guid=@CGUID-0; DELETE FROM creature WHERE id=54870; INSERT INTO creature (guid, id, map, spawnmask, position_x, position_y, position_z, orientation, spawntimesecs) VALUES (@CGUID-0, 54870, 1, 1, 1668.33, -4350.26, 26.3507, 2.83324, 300);
ProjectSkyfire/SkyFire.548
sql/old/5.4.8/world/SFDB_release_19.5_to_20.2/2019_10_21_00_world.sql
SQL
gpl-2.0
320
Imports System Imports System.Web.UI Imports System.Web.UI.WebControls Namespace Kartris ''' <summary> ''' Overrides the default table layout of the <see cref="System.Web.UI.WebControls.RadioButtonList"/> ''' control, to a XHTML unordered list layout (structural markup). ''' </summary> Public Class RadioButtonListAdapter Inherits System.Web.UI.WebControls.Adapters.WebControlAdapter Private Const WRAPPER_CSS_CLASS As String = "Kartris-RadioButtonList" Private Const ITEM_CSS_CLASS As String = "Kartris-RadioButtonList-Item" Protected Overloads Overrides Sub RenderBeginTag(ByVal writer As HtmlTextWriter) ' Div writer.AddAttribute(HtmlTextWriterAttribute.[Class], WRAPPER_CSS_CLASS) writer.AddAttribute(HtmlTextWriterAttribute.Id, Me.Control.ClientID) writer.RenderBeginTag(HtmlTextWriterTag.Div) writer.Indent += 1 ' Ul If Not String.IsNullOrEmpty(Me.Control.CssClass) Then writer.AddAttribute(HtmlTextWriterAttribute.[Class], Me.Control.CssClass) End If writer.RenderBeginTag(HtmlTextWriterTag.Ul) End Sub Protected Overloads Overrides Sub RenderEndTag(ByVal writer As HtmlTextWriter) writer.RenderEndTag() ' Ul writer.Indent -= 1 writer.RenderEndTag() ' Div End Sub Protected Overloads Overrides Sub RenderContents(ByVal writer As HtmlTextWriter) Dim buttonList As RadioButtonList = TryCast(Me.Control, RadioButtonList) If buttonList IsNot Nothing Then For Each li As ListItem In buttonList.Items Dim itemClientID As String = Helpers.GetListItemClientID(buttonList, li) ' Li writer.AddAttribute(HtmlTextWriterAttribute.[Class], ITEM_CSS_CLASS) writer.RenderBeginTag(HtmlTextWriterTag.Li) If buttonList.TextAlign = TextAlign.Right Then RenderRadioButtonListInput(writer, buttonList, li) RenderRadioButtonListLabel(writer, buttonList, li) Else ' TextAlign.Left RenderRadioButtonListLabel(writer, buttonList, li) RenderRadioButtonListInput(writer, buttonList, li) End If writer.RenderEndTag() ' </li> If Me.Page IsNot Nothing Then Page.ClientScript.RegisterForEventValidation(buttonList.UniqueID, li.Value) End If Next If Me.Page IsNot Nothing Then Page.ClientScript.RegisterForEventValidation(buttonList.UniqueID) End If End If End Sub Private Sub RenderRadioButtonListInput(ByVal writer As HtmlTextWriter, ByVal buttonList As RadioButtonList, ByVal li As ListItem) ' Input writer.AddAttribute(HtmlTextWriterAttribute.Id, Helpers.GetListItemClientID(buttonList, li)) writer.AddAttribute(HtmlTextWriterAttribute.Type, "radio") writer.AddAttribute(HtmlTextWriterAttribute.Name, buttonList.UniqueID) writer.AddAttribute(HtmlTextWriterAttribute.Value, li.Value) If li.Selected Then writer.AddAttribute(HtmlTextWriterAttribute.Checked, "checked") End If If li.Enabled = False OrElse buttonList.Enabled = False Then writer.AddAttribute(HtmlTextWriterAttribute.Disabled, "disabled") End If If li.Enabled = True AndAlso buttonList.Enabled = True AndAlso buttonList.AutoPostBack Then writer.AddAttribute(HtmlTextWriterAttribute.Onclick, [String].Format("setTimeout('__doPostBack(\'{0}\',\'\')', 0)", Helpers.GetListItemUniqueID(buttonList, li))) End If writer.RenderBeginTag(HtmlTextWriterTag.Input) writer.RenderEndTag() ' </input> End Sub Private Sub RenderRadioButtonListLabel(ByVal writer As HtmlTextWriter, ByVal buttonList As RadioButtonList, ByVal li As ListItem) ' Label writer.AddAttribute("for", Helpers.GetListItemClientID(buttonList, li)) writer.RenderBeginTag(HtmlTextWriterTag.Label) writer.Write(li.Text) writer.RenderEndTag() ' </label> End Sub End Class End Namespace
cactusoft/kartris
App_Code/CSSAdapters/RadioButtonListAdaptor.vb
Visual Basic
gpl-2.0
4,676
<?php /* * Styles and scripts registration and enqueuing * * @package mantra * @subpackage Functions */ // Adding the viewport meta if the mobile view has been enabled if($mantra_mobile=="Enable") add_action('wp_head', 'mantra_mobile_meta'); function mantra_mobile_meta() { global $mantra_options; foreach ($mantra_options as $key => $value) { ${"$key"} = $value ; } echo '<meta name="viewport" content="width=device-width, user-scalable=no, initial-scale=1.0, minimum-scale=1.0, maximum-scale=1.0">'; } // Loading mantra css style function mantra_style() { global $mantra_options; foreach ($mantra_options as $key => $value) { ${"$key"} = $value ; } // Loading the style.css wp_register_style( 'mantras', get_stylesheet_uri() ); wp_enqueue_style( 'mantras'); } // Loading google font styles function mantra_google_styles() { global $mantra_options; foreach ($mantra_options as $key => $value) { ${"$key"} = $value ; } wp_register_style( 'mantra_googlefont', esc_attr($mantra_googlefont2 )); wp_register_style( 'mantra_googlefonttitle', esc_attr($mantra_googlefonttitle2 )); wp_register_style( 'mantra_googlefontside',esc_attr($mantra_googlefontside2) ); wp_register_style( 'mantra_googlefontsubheader', esc_attr($mantra_googlefontsubheader2) ); wp_enqueue_style( 'mantra_googlefont'); wp_enqueue_style( 'mantra_googlefonttitle'); wp_enqueue_style( 'mantra_googlefontside'); wp_enqueue_style( 'mantra_googlefontsubheader'); // Loading the style-mobile.css if the mobile view is enabled if($mantra_mobile=="Enable") { wp_register_style( 'mantra-mobile', get_template_directory_uri() . '/style-mobile.css' ); wp_enqueue_style( 'mantra-mobile');} } // CSS loading and hook into wp_enque_scripts add_action('wp_print_styles', 'mantra_style',1 ); add_action('wp_head', 'mantra_custom_styles' ,8); if($mantra_customcss!="/* Mantra Custom CSS */") add_action('wp_head', 'mantra_customcss',9); add_action('wp_head', 'mantra_google_styles'); // JS loading and hook into wp_enque_scripts add_action('wp_head', 'mantra_customjs' ); // Scripts loading and hook into wp_enque_scripts function mantra_scripts_method() { global $mantra_options; foreach ($mantra_options as $key => $value) { ${"$key"} = $value ; } // If frontend - load the js for the menu and the social icons animations if ( !is_admin() ) { wp_register_script('cryout-frontend',get_template_directory_uri() . '/js/frontend.js', array('jquery') ); wp_enqueue_script('cryout-frontend'); // If mantra from page is enabled and the current page is home page - load the nivo slider js if($mantra_frontpage == "Enable" && is_front_page()) { wp_register_script('cryout-nivoSlider',get_template_directory_uri() . '/js/nivo-slider.js', array('jquery')); wp_enqueue_script('cryout-nivoSlider'); } } /* We add some JavaScript to pages with the comment form * to support sites with threaded comments (when in use). */ if ( is_singular() && get_option( 'thread_comments' ) ) wp_enqueue_script( 'comment-reply' ); } add_action('wp_enqueue_scripts', 'mantra_scripts_method'); /** * Adding CSS3 PIE behavior to elements that need it */ function mantra_ie_pie() { echo ' <!--[if lte IE 8]> <style type="text/css" media="screen"> #access ul li, .edit-link a , #footer-widget-area .widget-title, .entry-meta,.entry-meta .comments-link, .short-button-light, .short-button-dark ,.short-button-color ,blockquote { position:relative; behavior: url('.get_template_directory_uri().'/js/PIE/PIE.php); } #access ul ul { -pie-box-shadow:0px 5px 5px #999; } #access ul li.current_page_item, #access ul li.current-menu-item , #access ul li ,#access ul ul ,#access ul ul li, .commentlist li.comment ,.commentlist .avatar, .contentsearch #searchsubmit , .widget_search #s, #search #s , .widget_search #searchsubmit , .nivo-caption, .theme-default .nivoSlider { behavior: url('.get_template_directory_uri().'/js/PIE/PIE.php); } </style> <![endif]--> '; } add_action('wp_head', 'mantra_ie_pie', 10); ?>
DanielMSchmidt/stadtfest-theme
wp-content/themes/mantra/includes/theme-styles.php
PHP
gpl-2.0
4,286
DATABASE=postgis_topo_regress PSQL=psql all: @echo "Use 'make check' to run all tests" # TODO: make edit_topology.sql into a proper test edit: $(PSQL) -X -f edit_topology.sql $(DATABASE) topo_predicates.sql: predicates.sql.in @cpp -P -traditional-cpp predicates.sql.in | sed -e 's:@COLUMN@:feature:g;s:@SCHEMA@:topology.:g' > topo_predicates.sql load_topology.sql: load_topology.sql.in @cpp -P -traditional-cpp load_topology.sql.in | sed -e 's:@SRID@:-1:g' > load_topology.sql load_topology-4326.sql: load_topology.sql.in @cpp -P -traditional-cpp load_topology.sql.in | sed -e 's:@SRID@:4326:g' > load_topology-4326.sql clean distclean: rm -f topo_predicates.sql load_topology.sql load_topology-4326.sql TESTS = regress/legacy_validate.sql regress/legacy_predicate.sql \ regress/legacy_invalid.sql regress/sqlmm.sql \ regress/legacy_query.sql regress/addnode.sql \ regress/addedge.sql regress/addface.sql \ regress/addface2.5d.sql \ regress/polygonize.sql \ regress/st_addisoedge.sql \ regress/st_addisonode.sql \ regress/st_addedgemodface.sql \ regress/st_addedgenewfaces.sql \ regress/st_changeedgegeom.sql \ regress/st_createtopogeo.sql \ regress/st_getfacegeometry.sql \ regress/st_getfaceedges.sql \ regress/st_modedgeheal.sql \ regress/st_newedgeheal.sql \ regress/st_remedgenewface.sql \ regress/st_remedgemodface.sql \ regress/topoelement.sql \ regress/topoelementarray_agg.sql \ regress/topo2.5d.sql \ regress/droptopology.sql \ regress/copytopology.sql \ regress/createtopogeom.sql \ regress/createtopology.sql \ regress/gml.sql \ regress/getnodebypoint.sql \ regress/getedgebypoint.sql \ regress/getfacebypoint.sql \ regress/getringedges.sql \ regress/layertrigger.sql check: topo_predicates.sql load_topology.sql load_topology-4326.sql $(MAKE) -C ../../regress postgis.sql staged-install @USE_VERSION=$(POSTGIS_PGSQL_VERSION) ../../regress/run_test $(RUNTESTFLAGS) --topology $(TESTS)
netconstructor/postgis
topology/test/Makefile
Makefile
gpl-2.0
1,948
// OGLTexture.cpp // KlayGE OpenGLÎÆÀíÀà ʵÏÖÎļþ // Ver 3.12.0 // °æÈ¨ËùÓÐ(C) ¹¨ÃôÃô, 2003-2007 // Homepage: http://www.klayge.org // // 3.9.0 // Ö§³ÖTexture Array (2009.8.5) // // 3.6.0 // ÓÃpbo¼ÓËÙ (2007.3.13) // // 2.7.0 // Ôö¼ÓÁËAddressingMode, FilteringºÍAnisotropy (2005.6.27) // Ôö¼ÓÁËMaxMipLevelºÍMipMapLodBias (2005.6.28) // // 2.3.0 // Ôö¼ÓÁËCopyToMemory (2005.2.6) // // Ð޸ļǼ ///////////////////////////////////////////////////////////////////////////////// #include <KlayGE/KlayGE.hpp> #include <KFL/ErrorHandling.hpp> #include <KFL/Math.hpp> #include <KlayGE/RenderEngine.hpp> #include <KlayGE/RenderFactory.hpp> #include <KlayGE/Texture.hpp> #include <cstring> #include <glloader/glloader.h> #include <KlayGE/OpenGL/OGLRenderEngine.hpp> #include <KlayGE/OpenGL/OGLUtil.hpp> #include <KlayGE/OpenGL/OGLTexture.hpp> namespace KlayGE { OGLTexture::OGLTexture(TextureType type, uint32_t array_size, uint32_t sample_count, uint32_t sample_quality, uint32_t access_hint) : Texture(type, sample_count, sample_quality, access_hint), hw_res_ready_(false) { array_size_ = array_size; switch (type_) { case TT_1D: if (array_size > 1) { target_type_ = GL_TEXTURE_1D_ARRAY; } else { target_type_ = GL_TEXTURE_1D; } break; case TT_2D: if (array_size > 1) { target_type_ = GL_TEXTURE_2D_ARRAY; } else { target_type_ = GL_TEXTURE_2D; } break; case TT_3D: target_type_ = GL_TEXTURE_3D; break; case TT_Cube: if (array_size > 1) { target_type_ = GL_TEXTURE_CUBE_MAP_ARRAY; } else { target_type_ = GL_TEXTURE_CUBE_MAP; } break; default: KFL_UNREACHABLE("Invalid texture type"); } if (sample_count_ <= 1) { if (glloader_GL_VERSION_4_5() || glloader_GL_ARB_direct_state_access()) { glCreateTextures(target_type_, 1, &texture_); } else if (glloader_GL_EXT_direct_state_access()) { glGenTextures(1, &texture_); } else { glGenTextures(1, &texture_); glBindTexture(target_type_, texture_); } } else { glGenRenderbuffers(1, &texture_); } } OGLTexture::~OGLTexture() { this->DeleteHWResource(); if (Context::Instance().RenderFactoryValid()) { auto& re = checked_cast<OGLRenderEngine&>(Context::Instance().RenderFactoryInstance().RenderEngineInstance()); re.DeleteBuffers(1, &pbo_); } else { glDeleteBuffers(1, &pbo_); } if (sample_count_ <= 1) { if (Context::Instance().RenderFactoryValid()) { auto& re = checked_cast<OGLRenderEngine&>(Context::Instance().RenderFactoryInstance().RenderEngineInstance()); re.DeleteTextures(1, &texture_); } else { glDeleteTextures(1, &texture_); } } else { glDeleteRenderbuffers(1, &texture_); } } std::wstring const & OGLTexture::Name() const { static const std::wstring name(L"OpenGL Texture"); return name; } uint32_t OGLTexture::Width(uint32_t level) const { KFL_UNUSED(level); BOOST_ASSERT(level < num_mip_maps_); return 1; } uint32_t OGLTexture::Height(uint32_t level) const { KFL_UNUSED(level); BOOST_ASSERT(level < num_mip_maps_); return 1; } uint32_t OGLTexture::Depth(uint32_t level) const { KFL_UNUSED(level); BOOST_ASSERT(level < num_mip_maps_); return 1; } void OGLTexture::CopyToSubTexture1D(Texture& target, uint32_t dst_array_index, uint32_t dst_level, uint32_t dst_x_offset, uint32_t dst_width, uint32_t src_array_index, uint32_t src_level, uint32_t src_x_offset, uint32_t src_width, TextureFilter filter) { KFL_UNUSED(target); KFL_UNUSED(dst_array_index); KFL_UNUSED(dst_level); KFL_UNUSED(dst_x_offset); KFL_UNUSED(dst_width); KFL_UNUSED(src_array_index); KFL_UNUSED(src_level); KFL_UNUSED(src_x_offset); KFL_UNUSED(src_width); KFL_UNUSED(filter); KFL_UNREACHABLE("Can't be called"); } void OGLTexture::CopyToSubTexture2D(Texture& target, uint32_t dst_array_index, uint32_t dst_level, uint32_t dst_x_offset, uint32_t dst_y_offset, uint32_t dst_width, uint32_t dst_height, uint32_t src_array_index, uint32_t src_level, uint32_t src_x_offset, uint32_t src_y_offset, uint32_t src_width, uint32_t src_height, TextureFilter filter) { KFL_UNUSED(target); KFL_UNUSED(dst_array_index); KFL_UNUSED(dst_level); KFL_UNUSED(dst_x_offset); KFL_UNUSED(dst_y_offset); KFL_UNUSED(dst_width); KFL_UNUSED(dst_height); KFL_UNUSED(src_array_index); KFL_UNUSED(src_level); KFL_UNUSED(src_x_offset); KFL_UNUSED(src_y_offset); KFL_UNUSED(src_width); KFL_UNUSED(src_height); KFL_UNUSED(filter); KFL_UNREACHABLE("Can't be called"); } void OGLTexture::CopyToSubTexture3D(Texture& target, uint32_t dst_array_index, uint32_t dst_level, uint32_t dst_x_offset, uint32_t dst_y_offset, uint32_t dst_z_offset, uint32_t dst_width, uint32_t dst_height, uint32_t dst_depth, uint32_t src_array_index, uint32_t src_level, uint32_t src_x_offset, uint32_t src_y_offset, uint32_t src_z_offset, uint32_t src_width, uint32_t src_height, uint32_t src_depth, TextureFilter filter) { KFL_UNUSED(target); KFL_UNUSED(dst_array_index); KFL_UNUSED(dst_level); KFL_UNUSED(dst_x_offset); KFL_UNUSED(dst_y_offset); KFL_UNUSED(dst_z_offset); KFL_UNUSED(dst_width); KFL_UNUSED(dst_height); KFL_UNUSED(dst_depth); KFL_UNUSED(src_array_index); KFL_UNUSED(src_level); KFL_UNUSED(src_x_offset); KFL_UNUSED(src_y_offset); KFL_UNUSED(src_z_offset); KFL_UNUSED(src_width); KFL_UNUSED(src_height); KFL_UNUSED(src_depth); KFL_UNUSED(filter); KFL_UNREACHABLE("Can't be called"); } void OGLTexture::CopyToSubTextureCube(Texture& target, uint32_t dst_array_index, CubeFaces dst_face, uint32_t dst_level, uint32_t dst_x_offset, uint32_t dst_y_offset, uint32_t dst_width, uint32_t dst_height, uint32_t src_array_index, CubeFaces src_face, uint32_t src_level, uint32_t src_x_offset, uint32_t src_y_offset, uint32_t src_width, uint32_t src_height, TextureFilter filter) { KFL_UNUSED(target); KFL_UNUSED(dst_array_index); KFL_UNUSED(dst_face); KFL_UNUSED(dst_level); KFL_UNUSED(dst_x_offset); KFL_UNUSED(dst_y_offset); KFL_UNUSED(dst_width); KFL_UNUSED(dst_height); KFL_UNUSED(src_array_index); KFL_UNUSED(src_face); KFL_UNUSED(src_level); KFL_UNUSED(src_x_offset); KFL_UNUSED(src_y_offset); KFL_UNUSED(src_width); KFL_UNUSED(src_height); KFL_UNUSED(filter); KFL_UNREACHABLE("Can't be called"); } void OGLTexture::Map1D(uint32_t array_index, uint32_t level, TextureMapAccess tma, uint32_t x_offset, uint32_t width, void*& data) { KFL_UNUSED(array_index); KFL_UNUSED(level); KFL_UNUSED(tma); KFL_UNUSED(x_offset); KFL_UNUSED(width); KFL_UNUSED(data); KFL_UNREACHABLE("Can't be called"); } void OGLTexture::Map2D(uint32_t array_index, uint32_t level, TextureMapAccess tma, uint32_t x_offset, uint32_t y_offset, uint32_t width, uint32_t height, void*& data, uint32_t& row_pitch) { KFL_UNUSED(array_index); KFL_UNUSED(level); KFL_UNUSED(tma); KFL_UNUSED(x_offset); KFL_UNUSED(y_offset); KFL_UNUSED(width); KFL_UNUSED(height); KFL_UNUSED(data); KFL_UNUSED(row_pitch); KFL_UNREACHABLE("Can't be called"); } void OGLTexture::Map3D(uint32_t array_index, uint32_t level, TextureMapAccess tma, uint32_t x_offset, uint32_t y_offset, uint32_t z_offset, uint32_t width, uint32_t height, uint32_t depth, void*& data, uint32_t& row_pitch, uint32_t& slice_pitch) { KFL_UNUSED(array_index); KFL_UNUSED(level); KFL_UNUSED(tma); KFL_UNUSED(x_offset); KFL_UNUSED(y_offset); KFL_UNUSED(z_offset); KFL_UNUSED(width); KFL_UNUSED(height); KFL_UNUSED(depth); KFL_UNUSED(data); KFL_UNUSED(row_pitch); KFL_UNUSED(slice_pitch); KFL_UNREACHABLE("Can't be called"); } void OGLTexture::MapCube(uint32_t array_index, CubeFaces face, uint32_t level, TextureMapAccess tma, uint32_t x_offset, uint32_t y_offset, uint32_t width, uint32_t height, void*& data, uint32_t& row_pitch) { KFL_UNUSED(array_index); KFL_UNUSED(face); KFL_UNUSED(level); KFL_UNUSED(tma); KFL_UNUSED(x_offset); KFL_UNUSED(y_offset); KFL_UNUSED(width); KFL_UNUSED(height); KFL_UNUSED(data); KFL_UNUSED(row_pitch); KFL_UNREACHABLE("Can't be called"); } void OGLTexture::Unmap1D(uint32_t array_index, uint32_t level) { KFL_UNUSED(array_index); KFL_UNUSED(level); KFL_UNREACHABLE("Can't be called"); } void OGLTexture::Unmap2D(uint32_t array_index, uint32_t level) { KFL_UNUSED(array_index); KFL_UNUSED(level); KFL_UNREACHABLE("Can't be called"); } void OGLTexture::Unmap3D(uint32_t array_index, uint32_t level) { KFL_UNUSED(array_index); KFL_UNUSED(level); KFL_UNREACHABLE("Can't be called"); } void OGLTexture::UnmapCube(uint32_t array_index, CubeFaces face, uint32_t level) { KFL_UNUSED(array_index); KFL_UNUSED(face); KFL_UNUSED(level); KFL_UNREACHABLE("Can't be called"); } bool OGLTexture::HwBuildMipSubLevels(TextureFilter filter) { if (IsDepthFormat(format_) || (ChannelType<0>(format_) == ECT_UInt) || (ChannelType<0>(format_) == ECT_SInt)) { if (filter != TextureFilter::Point) { return false; } } else { if (filter != TextureFilter::Linear) { return false; } } if (glloader_GL_VERSION_4_5() || glloader_GL_ARB_direct_state_access()) { glGenerateTextureMipmap(texture_); } else if (glloader_GL_EXT_direct_state_access()) { glGenerateTextureMipmapEXT(texture_, target_type_); } else { auto& re = checked_cast<OGLRenderEngine&>(Context::Instance().RenderFactoryInstance().RenderEngineInstance()); re.BindTexture(0, target_type_, texture_); glGenerateMipmap(target_type_); } return true; } void OGLTexture::TexParameteri(GLenum pname, GLint param) { auto iter = tex_param_i_.find(pname); if ((iter == tex_param_i_.end()) || (iter->second != param)) { if (glloader_GL_VERSION_4_5() || glloader_GL_ARB_direct_state_access()) { glTextureParameteri(texture_, pname, param); } else if (glloader_GL_EXT_direct_state_access()) { glTextureParameteriEXT(texture_, target_type_, pname, param); } else { auto& re = checked_cast<OGLRenderEngine&>(Context::Instance().RenderFactoryInstance().RenderEngineInstance()); re.BindTexture(0, target_type_, texture_); glTexParameteri(target_type_, pname, param); } tex_param_i_[pname] = param; } } void OGLTexture::TexParameterf(GLenum pname, GLfloat param) { auto iter = tex_param_f_.find(pname); if ((iter == tex_param_f_.end()) || (iter->second != param)) { if (glloader_GL_VERSION_4_5() || glloader_GL_ARB_direct_state_access()) { glTextureParameterf(texture_, pname, param); } else if (glloader_GL_EXT_direct_state_access()) { glTextureParameterfEXT(texture_, target_type_, pname, param); } else { auto& re = checked_cast<OGLRenderEngine&>(Context::Instance().RenderFactoryInstance().RenderEngineInstance()); re.BindTexture(0, target_type_, texture_); glTexParameterf(target_type_, pname, param); } tex_param_f_[pname] = param; } } void OGLTexture::TexParameterfv(GLenum pname, GLfloat const * param) { float4 const f4_param(param); auto iter = tex_param_fv_.find(pname); if ((iter == tex_param_fv_.end()) || (iter->second != f4_param)) { if (glloader_GL_VERSION_4_5() || glloader_GL_ARB_direct_state_access()) { glTextureParameterfv(texture_, pname, param); } else if (glloader_GL_EXT_direct_state_access()) { glTextureParameterfvEXT(texture_, target_type_, pname, param); } else { auto& re = checked_cast<OGLRenderEngine&>(Context::Instance().RenderFactoryInstance().RenderEngineInstance()); re.BindTexture(0, target_type_, texture_); glTexParameterfv(target_type_, pname, param); } tex_param_fv_[pname] = f4_param; } } ElementFormat OGLTexture::SRGBToRGB(ElementFormat pf) { switch (pf) { case EF_ARGB8_SRGB: return EF_ARGB8; case EF_BC1_SRGB: return EF_BC1; case EF_BC2_SRGB: return EF_BC2; case EF_BC3_SRGB: return EF_BC3; default: return pf; } } void OGLTexture::DeleteHWResource() { hw_res_ready_ = false; } bool OGLTexture::HWResourceReady() const { return hw_res_ready_; } void OGLTexture::UpdateSubresource1D(uint32_t array_index, uint32_t level, uint32_t x_offset, uint32_t width, void const * data) { KFL_UNUSED(array_index); KFL_UNUSED(level); KFL_UNUSED(x_offset); KFL_UNUSED(width); KFL_UNUSED(data); KFL_UNREACHABLE("Can't be called"); } void OGLTexture::UpdateSubresource2D(uint32_t array_index, uint32_t level, uint32_t x_offset, uint32_t y_offset, uint32_t width, uint32_t height, void const * data, uint32_t row_pitch) { KFL_UNUSED(array_index); KFL_UNUSED(level); KFL_UNUSED(x_offset); KFL_UNUSED(y_offset); KFL_UNUSED(width); KFL_UNUSED(height); KFL_UNUSED(data); KFL_UNUSED(row_pitch); KFL_UNREACHABLE("Can't be called"); } void OGLTexture::UpdateSubresource3D(uint32_t array_index, uint32_t level, uint32_t x_offset, uint32_t y_offset, uint32_t z_offset, uint32_t width, uint32_t height, uint32_t depth, void const * data, uint32_t row_pitch, uint32_t slice_pitch) { KFL_UNUSED(array_index); KFL_UNUSED(level); KFL_UNUSED(x_offset); KFL_UNUSED(y_offset); KFL_UNUSED(z_offset); KFL_UNUSED(width); KFL_UNUSED(height); KFL_UNUSED(depth); KFL_UNUSED(data); KFL_UNUSED(row_pitch); KFL_UNUSED(slice_pitch); KFL_UNREACHABLE("Can't be called"); } void OGLTexture::UpdateSubresourceCube(uint32_t array_index, Texture::CubeFaces face, uint32_t level, uint32_t x_offset, uint32_t y_offset, uint32_t width, uint32_t height, void const * data, uint32_t row_pitch) { KFL_UNUSED(array_index); KFL_UNUSED(face); KFL_UNUSED(level); KFL_UNUSED(x_offset); KFL_UNUSED(y_offset); KFL_UNUSED(width); KFL_UNUSED(height); KFL_UNUSED(data); KFL_UNUSED(row_pitch); KFL_UNREACHABLE("Can't be called"); } }
gongminmin/KlayGE
KlayGE/Plugins/Src/Render/OpenGL/OGLTexture.cpp
C++
gpl-2.0
14,017
<?php function tzs_front_end_user_products_handler($atts) { // Определяем атрибуты // [tzs-view-user-products user_id="1"] - указываем на странице раздела // [tzs-view-products] - указываем на страницах подразделов extract( shortcode_atts( array( 'user_id' => '0', ), $atts, 'tzs-view-user-products' ) ); ob_start(); $sql1 = ' AND user_id='.$user_id; global $wpdb; $page = current_page_number(); $url = current_page_url(); $pp = TZS_RECORDS_PER_PAGE; $sql = "SELECT COUNT(*) as cnt FROM ".TZS_PRODUCTS_TABLE." WHERE active=1 $sql1 "; $res = $wpdb->get_row($sql); if (count($res) == 0 && $wpdb->last_error != null) { print_error('Не удалось отобразить список товаров. Свяжитесь, пожалуйста, с администрацией сайта -count'); } else { $records = $res->cnt; $pages = ceil($records / $pp); if ($pages == 0) $pages = 1; if ($page > $pages) $page = $pages; $from = ($page-1) * $pp; $sql = "SELECT * FROM ".TZS_PRODUCTS_TABLE." WHERE active=1 $sql1 ORDER BY created DESC LIMIT $from,$pp; "; $res = $wpdb->get_results($sql); if (count($res) == 0 && $wpdb->last_error != null) { print_error('Не удалось отобразить список товаров. Свяжитесь, пожалуйста, с администрацией сайта - record'); } else { if (count($res) == 0) { ?> <div style="clear: both;"></div> <div class="errors"> <div id="info error">По Вашему запросу ничего не найдено.</div> </div> <?php } else { ?> <div> <table id="tbl_products"> <tr> <th id="tbl_products_id">Номер</th> <th id="tbl_products_img">Фото</th> <th id="tbl_products_dtc">Дата размещения</th> <th id="title">Описание товара</th> <th id="price">Стоимость товара</th> <th id="descr">Форма оплаты</th> <th id="cities">Город</th> <th id="comm">Комментарии</th> </tr> <?php foreach ( $res as $row ) { ?> <tr rid="<?php echo $row->id;?>"> <td><?php echo $row->id;?></td> <td> <?php if (strlen($row->image_id_lists) > 0) { //$img_names = explode(';', $row->pictures); $main_image_id = $row->main_image_id; // Вначале выведем главное изображение $attachment_info = wp_get_attachment_image_src($main_image_id, 'thumbnail'); if ($attachment_info !== false) { //if (file_exists(ABSPATH . $img_names[0])) { //echo '<img src="'.get_site_url().'/'.$img_names[0].'" alt="">'; echo '<img src="'.$attachment_info[0].'" alt="">'; // width="50px" height="50px" } else { echo '&nbsp;'; } } else { echo '&nbsp;'; } ?> </td> <td><?php echo convert_date($row->created); ?></td> <td><?php echo htmlspecialchars($row->title);?></td> <td><?php echo $row->price." ".$GLOBALS['tzs_pr_curr'][$row->currency];?></td> <td><?php echo $GLOBALS['tzs_pr_payment'][$row->payment];?></td> <td><?php echo tzs_city_to_str($row->from_cid, $row->from_rid, $row->from_sid, $row->city_from);?></td> <td><?php echo htmlspecialchars($row->comment);?></td> </tr> <?php } ?> </table> </div> <?php } build_pages_footer($page, $pages); } } //// ?> <script src="/wp-content/plugins/tzs/assets/js/search.js"></script> <script> var post = []; <?php echo "// POST dump here\n"; foreach ($_POST as $key => $value) { echo "post[".tzs_encode2($key)."] = ".tzs_encode2($value).";\n"; } if (!isset($_POST['type_id'])) { echo "post[".tzs_encode2("type_id")."] = ".tzs_encode2($p_id).";\n"; } if (!isset($_POST['cur_type_id'])) { echo "post[".tzs_encode2("cur_type_id")."] = ".tzs_encode2($p_id).";\n"; } ?> function showSearchDialog() { doSearchDialog('products', post, null); //doSearchDialog('auctions', post, null); } jQuery(document).ready(function(){ jQuery('#tbl_products').on('click', 'td', function(e) { var nonclickable = 'true' == e.delegateTarget.rows[0].cells[this.cellIndex].getAttribute('nonclickable'); var id = this.parentNode.getAttribute("rid"); if (!nonclickable) document.location = "/account/view-product/?id="+id; }); hijackLinks(post); }); </script> <?php //// $output = ob_get_contents(); ob_end_clean(); return $output; } ?>
serker72/T3S_Old
wp-content/plugins/tzs/front-end/tzs.user.products.php
PHP
gpl-2.0
6,919
<?php /* @author : Giriraj Namachivayam @date : Apr 25, 2013 @demourl : http://ngiriraj.com/socialMedia/oauthlogin/ @license : Free to use, */ include "socialmedia_oauth_connect.php"; $oauth = new socialmedia_oauth_connect(); $oauth->provider="DeviantArt"; $oauth->client_id = "396"; $oauth->client_secret = "xxxxxxxxxxxxxxxxxxxxxxxxx"; $oauth->redirect_uri ="http://ngiriraj.com/socialMedia/oauthlogin/deviantart.php"; $oauth->Initialize(); $code = ($_REQUEST["code"]) ? ($_REQUEST["code"]) : ""; if(empty($code)) { $oauth->Authorize(); }else{ $oauth->code = $code; # $oauth->getAccessToken(); $getData = json_decode($oauth->getUserProfile()); $oauth->debugJson($getData); } ?>
phoenixz/base
data/plugins/socialmedia-oauth-login/deviantart.php
PHP
gpl-2.0
703
<!DOCTYPE html> <html lang="zh-cn"> <!-- Mirrored from www.w3school.com.cn/tiy/t.asp?f=hdom_frame_contentdocument by HTTrack Website Copier/3.x [XR&CO'2014], Wed, 02 Dec 2015 06:49:07 GMT --> <!-- Added by HTTrack --><meta http-equiv="content-type" content="text/html;charset=GB2312" /><!-- /Added by HTTrack --> <head> <meta charset="utf-8" /> <meta name="robots" content="all" /> <meta name="author" content="w3school.com.cn" /> <link rel="stylesheet" type="text/css" href="tc.css" /> <title>W3School在线测试工具 V2</title> </head> <body id="editor"> <div id="wrapper"> <div id="header"> <h1>W3School TIY</h1> <div id="ad"> <script type="text/javascript"><!-- google_ad_client = "pub-3381531532877742"; /* 728x90, tiy_big */ google_ad_slot = "7947784850"; google_ad_width = 728; google_ad_height = 90; //--> </script> <script type="text/javascript" src="../../pagead2.googlesyndication.com/pagead/f.txt"> </script> </div> </div> <form action="http://www.w3school.com.cn/tiy/v.asp" method="post" id="tryitform" name="tryitform" onSubmit="validateForm();" target="i"> <div id="butt"> <input type="button" value="提交代码" onClick="submitTryit()"> </div> <div id="CodeArea"> <h2>编辑您的代码:</h2> <textarea id="TestCode" wrap="logical"> <html> <frameset id="myFrameset" cols="50%,50%"> <frame id="leftFrame" src="../example/hdom/frame_cdoc.html"> <frame id="rightFrame" src="../example/hdom/frame_a.html"> </frameset> <!-- Mirrored from www.w3school.com.cn/tiy/t.asp?f=hdom_frame_contentdocument by HTTrack Website Copier/3.x [XR&CO'2014], Wed, 02 Dec 2015 06:49:07 GMT --> </html> </textarea> </div> <input type="hidden" id="code" name="code" /> <input type="hidden" id="bt" name="bt" /> </form> <div id="result"> <h2>查看结果:</h2> <iframe frameborder="0" name="i" src="loadtext6d6d.html?f=hdom_frame_contentdocument"></iframe> </div> <div id="footer"> <p>请在上面的文本框中编辑您的代码,然后单击提交按钮测试结果。<a href="../index-2.html" title="W3School 在线教程">w3school.com.cn</a></p> </div> </div> <script type="text/javascript"> function submitTryit() { var t=document.getElementById("TestCode").value; t=t.replace(/=/gi,"w3equalsign"); t=t.replace(/script/gi,"w3scrw3ipttag"); document.getElementById("code").value=t; document.getElementById("tryitform").action="v.html"; validateForm(); document.getElementById("tryitform").submit(); } function validateForm() { var code=document.getElementById("code").value; if (code.length>5000) { document.getElementById("code").value="<h1>Error</h1>"; } } </script> </body> </html>
platinhom/ManualHom
Coding/W3School/W3CN/www.w3school.com.cn/tiy/t6d6d.html
HTML
gpl-2.0
2,615
/* ################################################################################## # # Moto Animation System (http://motoanim.sf.net) # Copyleft (C) 2008 Konstantin Evdokimenko a.k.a Qew[erty] (qewerty@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 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. # ################################################################################## */ /* WARNING! Simple timeline only for testing. */ #ifndef __MOTO_TIMELINE_H__ #define __MOTO_TIMELINE_H__ #include <gtk/gtk.h> #include "libmoto/moto-scene-node.h" G_BEGIN_DECLS typedef struct _MotoTimeline MotoTimeline; typedef struct _MotoTimelineClass MotoTimelineClass; typedef struct _MotoTimelinePriv MotoTimelinePriv; /* class MotoTimeline */ struct _MotoTimeline { GtkDrawingArea parent; MotoTimelinePriv *priv; }; struct _MotoTimelineClass { GtkDrawingAreaClass parent; }; GType moto_timeline_get_type(void); #define MOTO_TYPE_TIMELINE (moto_timeline_get_type()) #define MOTO_TIMELINE(obj) (G_TYPE_CHECK_INSTANCE_CAST ((obj), MOTO_TYPE_TIMELINE, MotoTimeline)) #define MOTO_TIMELINE_CLASS(klass) (G_TYPE_CHECK_CLASS_CAST ((klass), MOTO_TYPE_TIMELINE, MotoTimelineClass)) #define MOTO_IS_TIMELINE(obj) (G_TYPE_CHECK_INSTANCE_TYPE ((obj),MOTO_TYPE_TIMELINE)) #define MOTO_IS_TIMELINE_CLASS(klass) (G_TYPE_CHECK_CLASS_TYPE ((klass),MOTO_TYPE_TIMELINE)) #define MOTO_TIMELINE_GET_CLASS(obj) (G_TYPE_INSTANCE_GET_CLASS ((obj),MOTO_TYPE_TIMELINE, MotoTimelineClass)) GtkWidget *moto_timeline_new(MotoSceneNode *scene_node); G_END_DECLS #endif /* __MOTO_TIMELINE_H__ */
qewerty/moto.old
src/libmotogui/moto-timeline.h
C
gpl-2.0
2,225
<?php /** * @copyright Copyright (C) eZ Systems AS. All rights reserved. * @license For full copyright and license information view LICENSE file distributed with this source code. */ namespace eZ\Bundle\EzPublishIOBundle\DependencyInjection\Factory; use League\Flysystem\Adapter\Local; /** * Builds a Local Flysystem Adapter instance with the given permissions configuration. */ class LocalAdapterFactory { /** * @param string $rootDir * @param int $filesPermissions Permissions used when creating files. Example: 0640. * @param int $directoriesPermissions Permissions when creating directories. Example: 0750. * * @return Local */ public function build($rootDir, $filesPermissions, $directoriesPermissions) { return new Local( $rootDir, LOCK_EX, Local::DISALLOW_LINKS, ['file' => ['public' => $filesPermissions], 'dir' => ['public' => $directoriesPermissions]] ); } }
ezsystems/ezpublish-kernel
eZ/Bundle/EzPublishIOBundle/DependencyInjection/Factory/LocalAdapterFactory.php
PHP
gpl-2.0
987
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Reflection { public class Student { public string FirstName { get; set; } public string LastName { get; set; } public int Age { get; set; } public Dictionary<string, int> Grades { get; set; } public Student(string first, string last) { this.FirstName = first; this.LastName = last; this.Grades = new Dictionary<string, int>(); } public void AddGrade(string course, int grade) { this.Grades.Add(course,grade); } } }
Omri27/AfekaTorrent
Reflection/Student.cs
C#
gpl-2.0
689
#ifndef mackie_surface_h #define mackie_surface_h #include <stdint.h> #include <sigc++/trackable.h> #include "pbd/signals.h" #include "pbd/xml++.h" #include "midi++/types.h" #include "ardour/types.h" #include "control_protocol/types.h" #include "controls.h" #include "types.h" #include "jog_wheel.h" namespace MIDI { class Parser; } namespace ARDOUR { class Stripable; class Port; } class MidiByteArray; namespace ArdourSurface { class US2400Protocol; namespace US2400 { class MackieButtonHandler; class SurfacePort; class MackieMidiBuilder; class Button; class Meter; class Fader; class Jog; class Pot; class Led; class Surface : public PBD::ScopedConnectionList, public sigc::trackable { public: Surface (US2400Protocol&, const std::string& name, uint32_t number, surface_type_t stype); virtual ~Surface(); surface_type_t type() const { return _stype; } uint32_t number() const { return _number; } const std::string& name() { return _name; } void connected (); bool active() const { return _active; } typedef std::vector<Control*> Controls; Controls controls; std::map<int,Fader*> faders; std::map<int,Pot*> pots; std::map<int,Button*> buttons; // index is device-DEPENDENT std::map<int,Led*> leds; std::map<int,Meter*> meters; std::map<int,Control*> controls_by_device_independent_id; US2400::JogWheel* jog_wheel() const { return _jog_wheel; } Fader* master_fader() const { return _master_fader; } /// The collection of all numbered strips. typedef std::vector<Strip*> Strips; Strips strips; uint32_t n_strips (bool with_locked_strips = true) const; Strip* nth_strip (uint32_t n) const; bool stripable_is_locked_to_strip (boost::shared_ptr<ARDOUR::Stripable>) const; bool stripable_is_mapped (boost::shared_ptr<ARDOUR::Stripable>) const; /// This collection owns the groups typedef std::map<std::string,Group*> Groups; Groups groups; SurfacePort& port() const { return *_port; } void map_stripables (const std::vector<boost::shared_ptr<ARDOUR::Stripable> >&); void update_strip_selection (); const MidiByteArray& sysex_hdr() const; void periodic (ARDOUR::microseconds_t now_usecs); void redisplay (ARDOUR::microseconds_t now_usecs, bool force); void hui_heartbeat (); void handle_midi_pitchbend_message (MIDI::Parser&, MIDI::pitchbend_t, uint32_t channel_id); void handle_midi_controller_message (MIDI::Parser&, MIDI::EventTwoBytes*); void handle_midi_note_on_message (MIDI::Parser&, MIDI::EventTwoBytes*); /// Connect the any signal from the parser to handle_midi_any /// unless it's already connected void connect_to_signals (); /// write a sysex message void write_sysex (const MidiByteArray& mba); void write_sysex (MIDI::byte msg); /// proxy write for port void write (const MidiByteArray&); /// display an indicator of the first switched-in Route. Do nothing by default. void display_bank_start (uint32_t /*current_bank*/); /// called from US2400Protocol::zero_all to turn things off void zero_all (); void zero_controls (); /// turn off leds around the jog wheel. This is for surfaces that use a pot /// pretending to be a jog wheel. void blank_jog_ring (); /// sends MCP "reset" message to surface void reset (); void recalibrate_faders (); void toggle_backlight (); void set_touch_sensitivity (int); /** This is used to calculate the clicks per second that define a transport speed of 1.0 for the jog wheel. 100.0 is 10 clicks per second, 50.5 is 5 clicks per second. */ float scrub_scaling_factor() const; /** The scaling factor function for speed increase and decrease. At low transport speeds this should return a small value, for high transport speeds, this should return an exponentially larger value. This provides high definition control at low speeds and quick speed changes to/from higher speeds. */ float scaled_delta (float delta, float current_speed); void subview_mode_changed (); US2400Protocol& mcp() const { return _mcp; } void next_jog_mode (); void set_jog_mode (US2400::JogWheel::Mode); void notify_metering_state_changed(); void turn_it_on (); bool connection_handler (boost::weak_ptr<ARDOUR::Port>, std::string name1, boost::weak_ptr<ARDOUR::Port>, std::string name2, bool); void master_monitor_may_have_changed (); XMLNode& get_state (); int set_state (const XMLNode&, int version); private: US2400Protocol& _mcp; SurfacePort* _port; surface_type_t _stype; uint32_t _number; std::string _name; bool _active; bool _connected; US2400::JogWheel* _jog_wheel; Fader* _master_fader; float _last_master_gain_written; PBD::ScopedConnection master_connection; bool _joystick_active; void handle_midi_sysex (MIDI::Parser&, MIDI::byte *, size_t count); MidiByteArray host_connection_query (MidiByteArray& bytes); MidiByteArray host_connection_confirmation (const MidiByteArray& bytes); void say_hello (); void init_controls (); void init_strips (uint32_t n); void setup_master (); void master_gain_changed (); enum ConnectionState { InputConnected = 0x1, OutputConnected = 0x2 }; int connection_state; public: /* IP MIDI devices need to keep a handle on this and destroy it */ GSource* input_source; }; } } #endif
johannes-mueller/ardour
libs/surfaces/us2400/surface.h
C
gpl-2.0
5,364
/* * kernel/sched/core.c * * Kernel scheduler and related syscalls * * Copyright (C) 1991-2002 Linus Torvalds * * 1996-12-23 Modified by Dave Grothe to fix bugs in semaphores and * make semaphores SMP safe * 1998-11-19 Implemented schedule_timeout() and related stuff * by Andrea Arcangeli * 2002-01-04 New ultra-scalable O(1) scheduler by Ingo Molnar: * hybrid priority-list and round-robin design with * an array-switch method of distributing timeslices * and per-CPU runqueues. Cleanups and useful suggestions * by Davide Libenzi, preemptible kernel bits by Robert Love. * 2003-09-03 Interactivity tuning by Con Kolivas. * 2004-04-02 Scheduler domains code by Nick Piggin * 2007-04-15 Work begun on replacing all interactivity tuning with a * fair scheduling design by Con Kolivas. * 2007-05-05 Load balancing (smp-nice) and other improvements * by Peter Williams * 2007-05-06 Interactivity improvements to CFS by Mike Galbraith * 2007-07-01 Group scheduling enhancements by Srivatsa Vaddagiri * 2007-11-29 RT balancing improvements by Steven Rostedt, Gregory Haskins, * Thomas Gleixner, Mike Kravetz */ #include <linux/mm.h> #include <linux/module.h> #include <linux/nmi.h> #include <linux/init.h> #include <linux/uaccess.h> #include <linux/highmem.h> #include <asm/mmu_context.h> #include <linux/interrupt.h> #include <linux/capability.h> #include <linux/completion.h> #include <linux/kernel_stat.h> #include <linux/debug_locks.h> #include <linux/perf_event.h> #include <linux/security.h> #include <linux/notifier.h> #include <linux/profile.h> #include <linux/freezer.h> #include <linux/vmalloc.h> #include <linux/blkdev.h> #include <linux/delay.h> #include <linux/pid_namespace.h> #include <linux/smp.h> #include <linux/threads.h> #include <linux/timer.h> #include <linux/rcupdate.h> #include <linux/cpu.h> #include <linux/cpuset.h> #include <linux/percpu.h> #include <linux/proc_fs.h> #include <linux/seq_file.h> #include <linux/sysctl.h> #include <linux/syscalls.h> #include <linux/times.h> #include <linux/tsacct_kern.h> #include <linux/kprobes.h> #include <linux/delayacct.h> #include <linux/unistd.h> #include <linux/pagemap.h> #include <linux/hrtimer.h> #include <linux/tick.h> #include <linux/debugfs.h> #include <linux/ctype.h> #include <linux/ftrace.h> #include <linux/slab.h> #include <linux/init_task.h> #include <linux/binfmts.h> #include <asm/switch_to.h> #include <asm/tlb.h> #include <asm/irq_regs.h> #include <asm/mutex.h> #ifdef CONFIG_PARAVIRT #include <asm/paravirt.h> #endif #include "sched.h" #include "../workqueue_sched.h" #include "../smpboot.h" #define CREATE_TRACE_POINTS #include <trace/events/sched.h> ATOMIC_NOTIFIER_HEAD(migration_notifier_head); void start_bandwidth_timer(struct hrtimer *period_timer, ktime_t period) { unsigned long delta; ktime_t soft, hard, now; for (;;) { if (hrtimer_active(period_timer)) break; now = hrtimer_cb_get_time(period_timer); hrtimer_forward(period_timer, now, period); soft = hrtimer_get_softexpires(period_timer); hard = hrtimer_get_expires(period_timer); delta = ktime_to_ns(ktime_sub(hard, soft)); __hrtimer_start_range_ns(period_timer, soft, delta, HRTIMER_MODE_ABS_PINNED, 0); } } DEFINE_MUTEX(sched_domains_mutex); DEFINE_PER_CPU_SHARED_ALIGNED(struct rq, runqueues); static void update_rq_clock_task(struct rq *rq, s64 delta); void update_rq_clock(struct rq *rq) { s64 delta; if (rq->skip_clock_update > 0) return; delta = sched_clock_cpu(cpu_of(rq)) - rq->clock; rq->clock += delta; update_rq_clock_task(rq, delta); } /* * Debugging: various feature bits */ #define SCHED_FEAT(name, enabled) \ (1UL << __SCHED_FEAT_##name) * enabled | const_debug unsigned int sysctl_sched_features = #include "features.h" 0; #undef SCHED_FEAT #ifdef CONFIG_SCHED_DEBUG #define SCHED_FEAT(name, enabled) \ #name , static __read_mostly char *sched_feat_names[] = { #include "features.h" NULL }; #undef SCHED_FEAT static int sched_feat_show(struct seq_file *m, void *v) { int i; for (i = 0; i < __SCHED_FEAT_NR; i++) { if (!(sysctl_sched_features & (1UL << i))) seq_puts(m, "NO_"); seq_printf(m, "%s ", sched_feat_names[i]); } seq_puts(m, "\n"); return 0; } #ifdef HAVE_JUMP_LABEL #define jump_label_key__true STATIC_KEY_INIT_TRUE #define jump_label_key__false STATIC_KEY_INIT_FALSE #define SCHED_FEAT(name, enabled) \ jump_label_key__##enabled , struct static_key sched_feat_keys[__SCHED_FEAT_NR] = { #include "features.h" }; #undef SCHED_FEAT static void sched_feat_disable(int i) { if (static_key_enabled(&sched_feat_keys[i])) static_key_slow_dec(&sched_feat_keys[i]); } static void sched_feat_enable(int i) { if (!static_key_enabled(&sched_feat_keys[i])) static_key_slow_inc(&sched_feat_keys[i]); } #else static void sched_feat_disable(int i) { }; static void sched_feat_enable(int i) { }; #endif /* HAVE_JUMP_LABEL */ static ssize_t sched_feat_write(struct file *filp, const char __user *ubuf, size_t cnt, loff_t *ppos) { char buf[64]; char *cmp; int neg = 0; int i; if (cnt > 63) cnt = 63; if (copy_from_user(&buf, ubuf, cnt)) return -EFAULT; buf[cnt] = 0; cmp = strstrip(buf); if (strncmp(cmp, "NO_", 3) == 0) { neg = 1; cmp += 3; } for (i = 0; i < __SCHED_FEAT_NR; i++) { if (strcmp(cmp, sched_feat_names[i]) == 0) { if (neg) { sysctl_sched_features &= ~(1UL << i); sched_feat_disable(i); } else { sysctl_sched_features |= (1UL << i); sched_feat_enable(i); } break; } } if (i == __SCHED_FEAT_NR) return -EINVAL; *ppos += cnt; return cnt; } static int sched_feat_open(struct inode *inode, struct file *filp) { return single_open(filp, sched_feat_show, NULL); } static const struct file_operations sched_feat_fops = { .open = sched_feat_open, .write = sched_feat_write, .read = seq_read, .llseek = seq_lseek, .release = single_release, }; static __init int sched_init_debug(void) { debugfs_create_file("sched_features", 0644, NULL, NULL, &sched_feat_fops); return 0; } late_initcall(sched_init_debug); #endif /* CONFIG_SCHED_DEBUG */ /* * Number of tasks to iterate in a single balance run. * Limited because this is done with IRQs disabled. */ const_debug unsigned int sysctl_sched_nr_migrate = 32; /* * period over which we average the RT time consumption, measured * in ms. * * default: 1s */ const_debug unsigned int sysctl_sched_time_avg = MSEC_PER_SEC; /* * period over which we measure -rt task cpu usage in us. * default: 1s */ unsigned int sysctl_sched_rt_period = 1000000; __read_mostly int scheduler_running; /* * part of the period that we allow rt tasks to run in us. * default: 0.95s */ int sysctl_sched_rt_runtime = 950000; /* * __task_rq_lock - lock the rq @p resides on. */ static inline struct rq *__task_rq_lock(struct task_struct *p) __acquires(rq->lock) { struct rq *rq; lockdep_assert_held(&p->pi_lock); for (;;) { rq = task_rq(p); raw_spin_lock(&rq->lock); if (likely(rq == task_rq(p))) return rq; raw_spin_unlock(&rq->lock); } } /* * task_rq_lock - lock p->pi_lock and lock the rq @p resides on. */ static struct rq *task_rq_lock(struct task_struct *p, unsigned long *flags) __acquires(p->pi_lock) __acquires(rq->lock) { struct rq *rq; for (;;) { raw_spin_lock_irqsave(&p->pi_lock, *flags); rq = task_rq(p); raw_spin_lock(&rq->lock); if (likely(rq == task_rq(p))) return rq; raw_spin_unlock(&rq->lock); raw_spin_unlock_irqrestore(&p->pi_lock, *flags); } } static void __task_rq_unlock(struct rq *rq) __releases(rq->lock) { raw_spin_unlock(&rq->lock); } static inline void task_rq_unlock(struct rq *rq, struct task_struct *p, unsigned long *flags) __releases(rq->lock) __releases(p->pi_lock) { raw_spin_unlock(&rq->lock); raw_spin_unlock_irqrestore(&p->pi_lock, *flags); } /* * this_rq_lock - lock this runqueue and disable interrupts. */ static struct rq *this_rq_lock(void) __acquires(rq->lock) { struct rq *rq; local_irq_disable(); rq = this_rq(); raw_spin_lock(&rq->lock); return rq; } #ifdef CONFIG_SCHED_HRTICK /* * Use HR-timers to deliver accurate preemption points. * * Its all a bit involved since we cannot program an hrt while holding the * rq->lock. So what we do is store a state in in rq->hrtick_* and ask for a * reschedule event. * * When we get rescheduled we reprogram the hrtick_timer outside of the * rq->lock. */ static void hrtick_clear(struct rq *rq) { if (hrtimer_active(&rq->hrtick_timer)) hrtimer_cancel(&rq->hrtick_timer); } /* * High-resolution timer tick. * Runs from hardirq context with interrupts disabled. */ static enum hrtimer_restart hrtick(struct hrtimer *timer) { struct rq *rq = container_of(timer, struct rq, hrtick_timer); WARN_ON_ONCE(cpu_of(rq) != smp_processor_id()); raw_spin_lock(&rq->lock); update_rq_clock(rq); rq->curr->sched_class->task_tick(rq, rq->curr, 1); raw_spin_unlock(&rq->lock); return HRTIMER_NORESTART; } #ifdef CONFIG_SMP /* * called from hardirq (IPI) context */ static void __hrtick_start(void *arg) { struct rq *rq = arg; struct hrtimer *timer = &rq->hrtick_timer; ktime_t soft, hard; unsigned long delta; soft = hrtimer_get_softexpires(timer); hard = hrtimer_get_expires(timer); delta = ktime_to_ns(ktime_sub(hard, soft)); raw_spin_lock(&rq->lock); __hrtimer_start_range_ns(timer, soft, delta, HRTIMER_MODE_ABS, 0); rq->hrtick_csd_pending = 0; raw_spin_unlock(&rq->lock); } /* * Called to set the hrtick timer state. * * called with rq->lock held and irqs disabled */ void hrtick_start(struct rq *rq, u64 delay) { struct hrtimer *timer = &rq->hrtick_timer; ktime_t time = ktime_add_ns(timer->base->get_time(), delay); hrtimer_set_expires(timer, time); if (rq == this_rq()) { __hrtimer_start_range_ns(timer, ns_to_ktime(delay), 0, HRTIMER_MODE_REL_PINNED, 0); } else if (!rq->hrtick_csd_pending) { __smp_call_function_single(cpu_of(rq), &rq->hrtick_csd, 0); rq->hrtick_csd_pending = 1; } } static int hotplug_hrtick(struct notifier_block *nfb, unsigned long action, void *hcpu) { int cpu = (int)(long)hcpu; switch (action) { case CPU_UP_CANCELED: case CPU_UP_CANCELED_FROZEN: case CPU_DOWN_PREPARE: case CPU_DOWN_PREPARE_FROZEN: case CPU_DEAD: case CPU_DEAD_FROZEN: hrtick_clear(cpu_rq(cpu)); return NOTIFY_OK; } return NOTIFY_DONE; } static __init void init_hrtick(void) { hotcpu_notifier(hotplug_hrtick, 0); } #else /* * Called to set the hrtick timer state. * * called with rq->lock held and irqs disabled */ void hrtick_start(struct rq *rq, u64 delay) { __hrtimer_start_range_ns(&rq->hrtick_timer, ns_to_ktime(delay), 0, HRTIMER_MODE_REL_PINNED, 0); } static inline void init_hrtick(void) { } #endif /* CONFIG_SMP */ static void init_rq_hrtick(struct rq *rq) { #ifdef CONFIG_SMP rq->hrtick_csd_pending = 0; rq->hrtick_csd.flags = 0; rq->hrtick_csd.func = __hrtick_start; rq->hrtick_csd.info = rq; #endif hrtimer_init(&rq->hrtick_timer, CLOCK_MONOTONIC, HRTIMER_MODE_REL); rq->hrtick_timer.function = hrtick; } #else /* CONFIG_SCHED_HRTICK */ static inline void hrtick_clear(struct rq *rq) { } static inline void init_rq_hrtick(struct rq *rq) { } static inline void init_hrtick(void) { } #endif /* CONFIG_SCHED_HRTICK */ /* * resched_task - mark a task 'to be rescheduled now'. * * On UP this means the setting of the need_resched flag, on SMP it * might also involve a cross-CPU call to trigger the scheduler on * the target CPU. */ #ifdef CONFIG_SMP #ifndef tsk_is_polling #define tsk_is_polling(t) test_tsk_thread_flag(t, TIF_POLLING_NRFLAG) #endif void resched_task(struct task_struct *p) { int cpu; assert_raw_spin_locked(&task_rq(p)->lock); if (test_tsk_need_resched(p)) return; set_tsk_need_resched(p); cpu = task_cpu(p); if (cpu == smp_processor_id()) return; /* NEED_RESCHED must be visible before we test polling */ smp_mb(); if (!tsk_is_polling(p)) smp_send_reschedule(cpu); } void resched_cpu(int cpu) { struct rq *rq = cpu_rq(cpu); unsigned long flags; if (!raw_spin_trylock_irqsave(&rq->lock, flags)) return; resched_task(cpu_curr(cpu)); raw_spin_unlock_irqrestore(&rq->lock, flags); } #ifdef CONFIG_NO_HZ /* * In the semi idle case, use the nearest busy cpu for migrating timers * from an idle cpu. This is good for power-savings. * * We don't do similar optimization for completely idle system, as * selecting an idle cpu will add more delays to the timers than intended * (as that cpu's timer base may not be uptodate wrt jiffies etc). */ int get_nohz_timer_target(void) { int cpu = smp_processor_id(); int i; struct sched_domain *sd; rcu_read_lock(); for_each_domain(cpu, sd) { for_each_cpu(i, sched_domain_span(sd)) { if (!idle_cpu(i)) { cpu = i; goto unlock; } } } unlock: rcu_read_unlock(); return cpu; } /* * When add_timer_on() enqueues a timer into the timer wheel of an * idle CPU then this timer might expire before the next timer event * which is scheduled to wake up that CPU. In case of a completely * idle system the next event might even be infinite time into the * future. wake_up_idle_cpu() ensures that the CPU is woken up and * leaves the inner idle loop so the newly added timer is taken into * account when the CPU goes back to idle and evaluates the timer * wheel for the next timer event. */ void wake_up_idle_cpu(int cpu) { struct rq *rq = cpu_rq(cpu); if (cpu == smp_processor_id()) return; /* * This is safe, as this function is called with the timer * wheel base lock of (cpu) held. When the CPU is on the way * to idle and has not yet set rq->curr to idle then it will * be serialized on the timer wheel base lock and take the new * timer into account automatically. */ if (rq->curr != rq->idle) return; /* * We can set TIF_RESCHED on the idle task of the other CPU * lockless. The worst case is that the other CPU runs the * idle task through an additional NOOP schedule() */ set_tsk_need_resched(rq->idle); /* NEED_RESCHED must be visible before we test polling */ smp_mb(); if (!tsk_is_polling(rq->idle)) smp_send_reschedule(cpu); } static inline bool got_nohz_idle_kick(void) { int cpu = smp_processor_id(); if (!test_bit(NOHZ_BALANCE_KICK, nohz_flags(cpu))) return false; if (idle_cpu(cpu) && !need_resched()) return true; /* * We can't run Idle Load Balance on this CPU for this time so we * cancel it and clear NOHZ_BALANCE_KICK */ clear_bit(NOHZ_BALANCE_KICK, nohz_flags(cpu)); return false; } #else /* CONFIG_NO_HZ */ static inline bool got_nohz_idle_kick(void) { return false; } #endif /* CONFIG_NO_HZ */ void sched_avg_update(struct rq *rq) { s64 period = sched_avg_period(); while ((s64)(rq->clock - rq->age_stamp) > period) { /* * Inline assembly required to prevent the compiler * optimising this loop into a divmod call. * See __iter_div_u64_rem() for another example of this. */ asm("" : "+rm" (rq->age_stamp)); rq->age_stamp += period; rq->rt_avg /= 2; } } #else /* !CONFIG_SMP */ void resched_task(struct task_struct *p) { assert_raw_spin_locked(&task_rq(p)->lock); set_tsk_need_resched(p); } #endif /* CONFIG_SMP */ #if defined(CONFIG_RT_GROUP_SCHED) || (defined(CONFIG_FAIR_GROUP_SCHED) && \ (defined(CONFIG_SMP) || defined(CONFIG_CFS_BANDWIDTH))) /* * Iterate task_group tree rooted at *from, calling @down when first entering a * node and @up when leaving it for the final time. * * Caller must hold rcu_lock or sufficient equivalent. */ int walk_tg_tree_from(struct task_group *from, tg_visitor down, tg_visitor up, void *data) { struct task_group *parent, *child; int ret; parent = from; down: ret = (*down)(parent, data); if (ret) goto out; list_for_each_entry_rcu(child, &parent->children, siblings) { parent = child; goto down; up: continue; } ret = (*up)(parent, data); if (ret || parent == from) goto out; child = parent; parent = parent->parent; if (parent) goto up; out: return ret; } int tg_nop(struct task_group *tg, void *data) { return 0; } #endif static void set_load_weight(struct task_struct *p) { int prio = p->static_prio - MAX_RT_PRIO; struct load_weight *load = &p->se.load; /* * SCHED_IDLE tasks get minimal weight: */ if (p->policy == SCHED_IDLE) { load->weight = scale_load(WEIGHT_IDLEPRIO); load->inv_weight = WMULT_IDLEPRIO; return; } load->weight = scale_load(prio_to_weight[prio]); load->inv_weight = prio_to_wmult[prio]; } static void enqueue_task(struct rq *rq, struct task_struct *p, int flags) { update_rq_clock(rq); sched_info_queued(p); p->sched_class->enqueue_task(rq, p, flags); trace_sched_enq_deq_task(p, 1); } static void dequeue_task(struct rq *rq, struct task_struct *p, int flags) { update_rq_clock(rq); sched_info_dequeued(p); p->sched_class->dequeue_task(rq, p, flags); trace_sched_enq_deq_task(p, 0); } void activate_task(struct rq *rq, struct task_struct *p, int flags) { if (task_contributes_to_load(p)) rq->nr_uninterruptible--; enqueue_task(rq, p, flags); } void deactivate_task(struct rq *rq, struct task_struct *p, int flags) { if (task_contributes_to_load(p)) rq->nr_uninterruptible++; dequeue_task(rq, p, flags); } #ifdef CONFIG_IRQ_TIME_ACCOUNTING /* * There are no locks covering percpu hardirq/softirq time. * They are only modified in account_system_vtime, on corresponding CPU * with interrupts disabled. So, writes are safe. * They are read and saved off onto struct rq in update_rq_clock(). * This may result in other CPU reading this CPU's irq time and can * race with irq/account_system_vtime on this CPU. We would either get old * or new value with a side effect of accounting a slice of irq time to wrong * task when irq is in progress while we read rq->clock. That is a worthy * compromise in place of having locks on each irq in account_system_time. */ static DEFINE_PER_CPU(u64, cpu_hardirq_time); static DEFINE_PER_CPU(u64, cpu_softirq_time); static DEFINE_PER_CPU(u64, irq_start_time); static int sched_clock_irqtime; void enable_sched_clock_irqtime(void) { sched_clock_irqtime = 1; } void disable_sched_clock_irqtime(void) { sched_clock_irqtime = 0; } #ifndef CONFIG_64BIT static DEFINE_PER_CPU(seqcount_t, irq_time_seq); static inline void irq_time_write_begin(void) { __this_cpu_inc(irq_time_seq.sequence); smp_wmb(); } static inline void irq_time_write_end(void) { smp_wmb(); __this_cpu_inc(irq_time_seq.sequence); } static inline u64 irq_time_read(int cpu) { u64 irq_time; unsigned seq; do { seq = read_seqcount_begin(&per_cpu(irq_time_seq, cpu)); irq_time = per_cpu(cpu_softirq_time, cpu) + per_cpu(cpu_hardirq_time, cpu); } while (read_seqcount_retry(&per_cpu(irq_time_seq, cpu), seq)); return irq_time; } #else /* CONFIG_64BIT */ static inline void irq_time_write_begin(void) { } static inline void irq_time_write_end(void) { } static inline u64 irq_time_read(int cpu) { return per_cpu(cpu_softirq_time, cpu) + per_cpu(cpu_hardirq_time, cpu); } #endif /* CONFIG_64BIT */ /* * Called before incrementing preempt_count on {soft,}irq_enter * and before decrementing preempt_count on {soft,}irq_exit. */ void account_system_vtime(struct task_struct *curr) { unsigned long flags; s64 delta; int cpu; if (!sched_clock_irqtime) return; local_irq_save(flags); cpu = smp_processor_id(); delta = sched_clock_cpu(cpu) - __this_cpu_read(irq_start_time); __this_cpu_add(irq_start_time, delta); irq_time_write_begin(); /* * We do not account for softirq time from ksoftirqd here. * We want to continue accounting softirq time to ksoftirqd thread * in that case, so as not to confuse scheduler with a special task * that do not consume any time, but still wants to run. */ if (hardirq_count()) __this_cpu_add(cpu_hardirq_time, delta); else if (in_serving_softirq() && curr != this_cpu_ksoftirqd()) __this_cpu_add(cpu_softirq_time, delta); irq_time_write_end(); local_irq_restore(flags); } EXPORT_SYMBOL_GPL(account_system_vtime); #endif /* CONFIG_IRQ_TIME_ACCOUNTING */ #ifdef CONFIG_PARAVIRT static inline u64 steal_ticks(u64 steal) { if (unlikely(steal > NSEC_PER_SEC)) return div_u64(steal, TICK_NSEC); return __iter_div_u64_rem(steal, TICK_NSEC, &steal); } #endif static void update_rq_clock_task(struct rq *rq, s64 delta) { /* * In theory, the compile should just see 0 here, and optimize out the call * to sched_rt_avg_update. But I don't trust it... */ #if defined(CONFIG_IRQ_TIME_ACCOUNTING) || defined(CONFIG_PARAVIRT_TIME_ACCOUNTING) s64 steal = 0, irq_delta = 0; #endif #ifdef CONFIG_IRQ_TIME_ACCOUNTING irq_delta = irq_time_read(cpu_of(rq)) - rq->prev_irq_time; /* * Since irq_time is only updated on {soft,}irq_exit, we might run into * this case when a previous update_rq_clock() happened inside a * {soft,}irq region. * * When this happens, we stop ->clock_task and only update the * prev_irq_time stamp to account for the part that fit, so that a next * update will consume the rest. This ensures ->clock_task is * monotonic. * * It does however cause some slight miss-attribution of {soft,}irq * time, a more accurate solution would be to update the irq_time using * the current rq->clock timestamp, except that would require using * atomic ops. */ if (irq_delta > delta) irq_delta = delta; rq->prev_irq_time += irq_delta; delta -= irq_delta; #endif #ifdef CONFIG_PARAVIRT_TIME_ACCOUNTING if (static_key_false((&paravirt_steal_rq_enabled))) { u64 st; steal = paravirt_steal_clock(cpu_of(rq)); steal -= rq->prev_steal_time_rq; if (unlikely(steal > delta)) steal = delta; st = steal_ticks(steal); steal = st * TICK_NSEC; rq->prev_steal_time_rq += steal; delta -= steal; } #endif rq->clock_task += delta; #if defined(CONFIG_IRQ_TIME_ACCOUNTING) || defined(CONFIG_PARAVIRT_TIME_ACCOUNTING) if ((irq_delta + steal) && sched_feat(NONTASK_POWER)) sched_rt_avg_update(rq, irq_delta + steal); #endif } #ifdef CONFIG_IRQ_TIME_ACCOUNTING static int irqtime_account_hi_update(void) { u64 *cpustat = kcpustat_this_cpu->cpustat; unsigned long flags; u64 latest_ns; int ret = 0; local_irq_save(flags); latest_ns = this_cpu_read(cpu_hardirq_time); if (nsecs_to_cputime64(latest_ns) > cpustat[CPUTIME_IRQ]) ret = 1; local_irq_restore(flags); return ret; } static int irqtime_account_si_update(void) { u64 *cpustat = kcpustat_this_cpu->cpustat; unsigned long flags; u64 latest_ns; int ret = 0; local_irq_save(flags); latest_ns = this_cpu_read(cpu_softirq_time); if (nsecs_to_cputime64(latest_ns) > cpustat[CPUTIME_SOFTIRQ]) ret = 1; local_irq_restore(flags); return ret; } #else /* CONFIG_IRQ_TIME_ACCOUNTING */ #define sched_clock_irqtime (0) #endif void sched_set_stop_task(int cpu, struct task_struct *stop) { struct sched_param param = { .sched_priority = MAX_RT_PRIO - 1 }; struct task_struct *old_stop = cpu_rq(cpu)->stop; if (stop) { /* * Make it appear like a SCHED_FIFO task, its something * userspace knows about and won't get confused about. * * Also, it will make PI more or less work without too * much confusion -- but then, stop work should not * rely on PI working anyway. */ sched_setscheduler_nocheck(stop, SCHED_FIFO, &param); stop->sched_class = &stop_sched_class; } cpu_rq(cpu)->stop = stop; if (old_stop) { /* * Reset it back to a normal scheduling class so that * it can die in pieces. */ old_stop->sched_class = &rt_sched_class; } } /* * __normal_prio - return the priority that is based on the static prio */ static inline int __normal_prio(struct task_struct *p) { return p->static_prio; } /* * Calculate the expected normal priority: i.e. priority * without taking RT-inheritance into account. Might be * boosted by interactivity modifiers. Changes upon fork, * setprio syscalls, and whenever the interactivity * estimator recalculates. */ static inline int normal_prio(struct task_struct *p) { int prio; if (task_has_rt_policy(p)) prio = MAX_RT_PRIO-1 - p->rt_priority; else prio = __normal_prio(p); return prio; } /* * Calculate the current priority, i.e. the priority * taken into account by the scheduler. This value might * be boosted by RT tasks, or might be boosted by * interactivity modifiers. Will be RT if the task got * RT-boosted. If not then it returns p->normal_prio. */ static int effective_prio(struct task_struct *p) { p->normal_prio = normal_prio(p); /* * If we are RT tasks or we were boosted to RT priority, * keep the priority unchanged. Otherwise, update priority * to the normal priority: */ if (!rt_prio(p->prio)) return p->normal_prio; return p->prio; } /** * task_curr - is this task currently executing on a CPU? * @p: the task in question. */ inline int task_curr(const struct task_struct *p) { return cpu_curr(task_cpu(p)) == p; } static inline void check_class_changed(struct rq *rq, struct task_struct *p, const struct sched_class *prev_class, int oldprio) { if (prev_class != p->sched_class) { if (prev_class->switched_from) prev_class->switched_from(rq, p); p->sched_class->switched_to(rq, p); } else if (oldprio != p->prio) p->sched_class->prio_changed(rq, p, oldprio); } void check_preempt_curr(struct rq *rq, struct task_struct *p, int flags) { const struct sched_class *class; if (p->sched_class == rq->curr->sched_class) { rq->curr->sched_class->check_preempt_curr(rq, p, flags); } else { for_each_class(class) { if (class == rq->curr->sched_class) break; if (class == p->sched_class) { resched_task(rq->curr); break; } } } /* * A queue event has occurred, and we're going to schedule. In * this case, we can save a useless back to back clock update. */ if (rq->curr->on_rq && test_tsk_need_resched(rq->curr)) rq->skip_clock_update = 1; } #ifdef CONFIG_SMP void set_task_cpu(struct task_struct *p, unsigned int new_cpu) { #ifdef CONFIG_SCHED_DEBUG /* * We should never call set_task_cpu() on a blocked task, * ttwu() will sort out the placement. */ WARN_ON_ONCE(p->state != TASK_RUNNING && p->state != TASK_WAKING && !(task_thread_info(p)->preempt_count & PREEMPT_ACTIVE)); #ifdef CONFIG_LOCKDEP /* * The caller should hold either p->pi_lock or rq->lock, when changing * a task's CPU. ->pi_lock for waking tasks, rq->lock for runnable tasks. * * sched_move_task() holds both and thus holding either pins the cgroup, * see task_group(). * * Furthermore, all task_rq users should acquire both locks, see * task_rq_lock(). */ WARN_ON_ONCE(debug_locks && !(lockdep_is_held(&p->pi_lock) || lockdep_is_held(&task_rq(p)->lock))); #endif #endif trace_sched_migrate_task(p, new_cpu); if (task_cpu(p) != new_cpu) { p->se.nr_migrations++; perf_sw_event(PERF_COUNT_SW_CPU_MIGRATIONS, 1, NULL, 0); } __set_task_cpu(p, new_cpu); } struct migration_arg { struct task_struct *task; int dest_cpu; }; static int migration_cpu_stop(void *data); /* * wait_task_inactive - wait for a thread to unschedule. * * If @match_state is nonzero, it's the @p->state value just checked and * not expected to change. If it changes, i.e. @p might have woken up, * then return zero. When we succeed in waiting for @p to be off its CPU, * we return a positive number (its total switch count). If a second call * a short while later returns the same number, the caller can be sure that * @p has remained unscheduled the whole time. * * The caller must ensure that the task *will* unschedule sometime soon, * else this function might spin for a *long* time. This function can't * be called with interrupts off, or it may introduce deadlock with * smp_call_function() if an IPI is sent by the same process we are * waiting to become inactive. */ unsigned long wait_task_inactive(struct task_struct *p, long match_state) { unsigned long flags; int running, on_rq; unsigned long ncsw; struct rq *rq; for (;;) { /* * We do the initial early heuristics without holding * any task-queue locks at all. We'll only try to get * the runqueue lock when things look like they will * work out! */ rq = task_rq(p); /* * If the task is actively running on another CPU * still, just relax and busy-wait without holding * any locks. * * NOTE! Since we don't hold any locks, it's not * even sure that "rq" stays as the right runqueue! * But we don't care, since "task_running()" will * return false if the runqueue has changed and p * is actually now running somewhere else! */ while (task_running(rq, p)) { if (match_state && unlikely(p->state != match_state)) return 0; cpu_relax(); } /* * Ok, time to look more closely! We need the rq * lock now, to be *sure*. If we're wrong, we'll * just go back and repeat. */ rq = task_rq_lock(p, &flags); trace_sched_wait_task(p); running = task_running(rq, p); on_rq = p->on_rq; ncsw = 0; if (!match_state || p->state == match_state) ncsw = p->nvcsw | LONG_MIN; /* sets MSB */ task_rq_unlock(rq, p, &flags); /* * If it changed from the expected state, bail out now. */ if (unlikely(!ncsw)) break; /* * Was it really running after all now that we * checked with the proper locks actually held? * * Oops. Go back and try again.. */ if (unlikely(running)) { cpu_relax(); continue; } /* * It's not enough that it's not actively running, * it must be off the runqueue _entirely_, and not * preempted! * * So if it was still runnable (but just not actively * running right now), it's preempted, and we should * yield - it could be a while. */ if (unlikely(on_rq)) { ktime_t to = ktime_set(0, NSEC_PER_MSEC); set_current_state(TASK_UNINTERRUPTIBLE); schedule_hrtimeout(&to, HRTIMER_MODE_REL); continue; } /* * Ahh, all good. It wasn't running, and it wasn't * runnable, which means that it will never become * running in the future either. We're all done! */ break; } return ncsw; } /*** * kick_process - kick a running thread to enter/exit the kernel * @p: the to-be-kicked thread * * Cause a process which is running on another CPU to enter * kernel-mode, without any delay. (to get signals handled.) * * NOTE: this function doesn't have to take the runqueue lock, * because all it wants to ensure is that the remote task enters * the kernel. If the IPI races and the task has been migrated * to another CPU then no harm is done and the purpose has been * achieved as well. */ void kick_process(struct task_struct *p) { int cpu; preempt_disable(); cpu = task_cpu(p); if ((cpu != smp_processor_id()) && task_curr(p)) smp_send_reschedule(cpu); preempt_enable(); } EXPORT_SYMBOL_GPL(kick_process); #endif /* CONFIG_SMP */ #ifdef CONFIG_SMP /* * ->cpus_allowed is protected by both rq->lock and p->pi_lock */ static int select_fallback_rq(int cpu, struct task_struct *p) { const struct cpumask *nodemask = cpumask_of_node(cpu_to_node(cpu)); enum { cpuset, possible, fail } state = cpuset; int dest_cpu; /* Look for allowed, online CPU in same node. */ for_each_cpu(dest_cpu, nodemask) { if (!cpu_online(dest_cpu)) continue; if (!cpu_active(dest_cpu)) continue; if (cpumask_test_cpu(dest_cpu, tsk_cpus_allowed(p))) return dest_cpu; } for (;;) { /* Any allowed, online CPU? */ for_each_cpu(dest_cpu, tsk_cpus_allowed(p)) { if (!cpu_online(dest_cpu)) continue; if (!cpu_active(dest_cpu)) continue; goto out; } switch (state) { case cpuset: /* No more Mr. Nice Guy. */ cpuset_cpus_allowed_fallback(p); state = possible; break; case possible: do_set_cpus_allowed(p, cpu_possible_mask); state = fail; break; case fail: BUG(); break; } } out: if (state != cpuset) { /* * Don't tell them about moving exiting tasks or * kernel threads (both mm NULL), since they never * leave kernel. */ if (p->mm && printk_ratelimit()) { printk_sched("process %d (%s) no longer affine to cpu%d\n", task_pid_nr(p), p->comm, cpu); } } return dest_cpu; } /* * The caller (fork, wakeup) owns p->pi_lock, ->cpus_allowed is stable. */ static inline int select_task_rq(struct task_struct *p, int sd_flags, int wake_flags) { int cpu = p->sched_class->select_task_rq(p, sd_flags, wake_flags); /* * In order not to call set_task_cpu() on a blocking task we need * to rely on ttwu() to place the task on a valid ->cpus_allowed * cpu. * * Since this is common to all placement strategies, this lives here. * * [ this allows ->select_task() to simply return task_cpu(p) and * not worry about this generic constraint ] */ if (unlikely(!cpumask_test_cpu(cpu, tsk_cpus_allowed(p)) || !cpu_online(cpu))) cpu = select_fallback_rq(task_cpu(p), p); return cpu; } static void update_avg(u64 *avg, u64 sample) { s64 diff = sample - *avg; *avg += diff >> 3; } #endif static void ttwu_stat(struct task_struct *p, int cpu, int wake_flags) { #ifdef CONFIG_SCHEDSTATS struct rq *rq = this_rq(); #ifdef CONFIG_SMP int this_cpu = smp_processor_id(); if (cpu == this_cpu) { schedstat_inc(rq, ttwu_local); schedstat_inc(p, se.statistics.nr_wakeups_local); } else { struct sched_domain *sd; schedstat_inc(p, se.statistics.nr_wakeups_remote); rcu_read_lock(); for_each_domain(this_cpu, sd) { if (cpumask_test_cpu(cpu, sched_domain_span(sd))) { schedstat_inc(sd, ttwu_wake_remote); break; } } rcu_read_unlock(); } if (wake_flags & WF_MIGRATED) schedstat_inc(p, se.statistics.nr_wakeups_migrate); #endif /* CONFIG_SMP */ schedstat_inc(rq, ttwu_count); schedstat_inc(p, se.statistics.nr_wakeups); if (wake_flags & WF_SYNC) schedstat_inc(p, se.statistics.nr_wakeups_sync); #endif /* CONFIG_SCHEDSTATS */ } static void ttwu_activate(struct rq *rq, struct task_struct *p, int en_flags) { activate_task(rq, p, en_flags); p->on_rq = 1; /* if a worker is waking up, notify workqueue */ if (p->flags & PF_WQ_WORKER) wq_worker_waking_up(p, cpu_of(rq)); } /* * Mark the task runnable and perform wakeup-preemption. */ static void ttwu_do_wakeup(struct rq *rq, struct task_struct *p, int wake_flags) { trace_sched_wakeup(p, true); check_preempt_curr(rq, p, wake_flags); p->state = TASK_RUNNING; #ifdef CONFIG_SMP if (p->sched_class->task_woken) p->sched_class->task_woken(rq, p); if (rq->idle_stamp) { u64 delta = rq->clock - rq->idle_stamp; u64 max = 2*sysctl_sched_migration_cost; if (delta > max) rq->avg_idle = max; else update_avg(&rq->avg_idle, delta); rq->idle_stamp = 0; } #endif } static void ttwu_do_activate(struct rq *rq, struct task_struct *p, int wake_flags) { #ifdef CONFIG_SMP if (p->sched_contributes_to_load) rq->nr_uninterruptible--; #endif ttwu_activate(rq, p, ENQUEUE_WAKEUP | ENQUEUE_WAKING); ttwu_do_wakeup(rq, p, wake_flags); } /* * Called in case the task @p isn't fully descheduled from its runqueue, * in this case we must do a remote wakeup. Its a 'light' wakeup though, * since all we need to do is flip p->state to TASK_RUNNING, since * the task is still ->on_rq. */ static int ttwu_remote(struct task_struct *p, int wake_flags) { struct rq *rq; int ret = 0; rq = __task_rq_lock(p); if (p->on_rq) { ttwu_do_wakeup(rq, p, wake_flags); ret = 1; } __task_rq_unlock(rq); return ret; } #ifdef CONFIG_SMP static void sched_ttwu_pending(void) { struct rq *rq = this_rq(); struct llist_node *llist = llist_del_all(&rq->wake_list); struct task_struct *p; raw_spin_lock(&rq->lock); while (llist) { p = llist_entry(llist, struct task_struct, wake_entry); llist = llist_next(llist); ttwu_do_activate(rq, p, 0); } raw_spin_unlock(&rq->lock); } void scheduler_ipi(void) { if (llist_empty(&this_rq()->wake_list) && !got_nohz_idle_kick()) return; /* * Not all reschedule IPI handlers call irq_enter/irq_exit, since * traditionally all their work was done from the interrupt return * path. Now that we actually do some work, we need to make sure * we do call them. * * Some archs already do call them, luckily irq_enter/exit nest * properly. * * Arguably we should visit all archs and update all handlers, * however a fair share of IPIs are still resched only so this would * somewhat pessimize the simple resched case. */ irq_enter(); sched_ttwu_pending(); /* * Check if someone kicked us for doing the nohz idle load balance. */ if (unlikely(got_nohz_idle_kick())) { this_rq()->idle_balance = 1; raise_softirq_irqoff(SCHED_SOFTIRQ); } irq_exit(); } static void ttwu_queue_remote(struct task_struct *p, int cpu) { if (llist_add(&p->wake_entry, &cpu_rq(cpu)->wake_list)) smp_send_reschedule(cpu); } #ifdef __ARCH_WANT_INTERRUPTS_ON_CTXSW static int ttwu_activate_remote(struct task_struct *p, int wake_flags) { struct rq *rq; int ret = 0; rq = __task_rq_lock(p); if (p->on_cpu) { ttwu_activate(rq, p, ENQUEUE_WAKEUP); ttwu_do_wakeup(rq, p, wake_flags); ret = 1; } __task_rq_unlock(rq); return ret; } #endif /* __ARCH_WANT_INTERRUPTS_ON_CTXSW */ bool cpus_share_cache(int this_cpu, int that_cpu) { return per_cpu(sd_llc_id, this_cpu) == per_cpu(sd_llc_id, that_cpu); } #endif /* CONFIG_SMP */ static void ttwu_queue(struct task_struct *p, int cpu) { struct rq *rq = cpu_rq(cpu); #if defined(CONFIG_SMP) if (sched_feat(TTWU_QUEUE) && !cpus_share_cache(smp_processor_id(), cpu)) { sched_clock_cpu(cpu); /* sync clocks x-cpu */ ttwu_queue_remote(p, cpu); return; } #endif raw_spin_lock(&rq->lock); ttwu_do_activate(rq, p, 0); raw_spin_unlock(&rq->lock); } /** * try_to_wake_up - wake up a thread * @p: the thread to be awakened * @state: the mask of task states that can be woken * @wake_flags: wake modifier flags (WF_*) * * Put it on the run-queue if it's not already there. The "current" * thread is always on the run-queue (except when the actual * re-schedule is in progress), and as such you're allowed to do * the simpler "current->state = TASK_RUNNING" to mark yourself * runnable without the overhead of this. * * Returns %true if @p was woken up, %false if it was already running * or @state didn't match @p's state. */ static int try_to_wake_up(struct task_struct *p, unsigned int state, int wake_flags) { unsigned long flags; int cpu, src_cpu, success = 0; int notify = 0; smp_wmb(); raw_spin_lock_irqsave(&p->pi_lock, flags); src_cpu = cpu = task_cpu(p); if (!(p->state & state)) goto out; success = 1; /* we're going to change ->state */ if (p->on_rq && ttwu_remote(p, wake_flags)) goto stat; #ifdef CONFIG_SMP /* * If the owning (remote) cpu is still in the middle of schedule() with * this task as prev, wait until its done referencing the task. */ while (p->on_cpu) { #ifdef __ARCH_WANT_INTERRUPTS_ON_CTXSW /* * In case the architecture enables interrupts in * context_switch(), we cannot busy wait, since that * would lead to deadlocks when an interrupt hits and * tries to wake up @prev. So bail and do a complete * remote wakeup. */ if (ttwu_activate_remote(p, wake_flags)) goto stat; #else cpu_relax(); #endif } /* * Pairs with the smp_wmb() in finish_lock_switch(). */ smp_rmb(); p->sched_contributes_to_load = !!task_contributes_to_load(p); p->state = TASK_WAKING; if (p->sched_class->task_waking) p->sched_class->task_waking(p); cpu = select_task_rq(p, SD_BALANCE_WAKE, wake_flags); /* Refresh src_cpu as it could have changed since we last read it */ src_cpu = task_cpu(p); if (src_cpu != cpu) { wake_flags |= WF_MIGRATED; set_task_cpu(p, cpu); } #endif /* CONFIG_SMP */ ttwu_queue(p, cpu); stat: ttwu_stat(p, cpu, wake_flags); if (src_cpu != cpu && task_notify_on_migrate(p)) notify = 1; out: raw_spin_unlock_irqrestore(&p->pi_lock, flags); if (notify) atomic_notifier_call_chain(&migration_notifier_head, cpu, (void *)src_cpu); return success; } /** * try_to_wake_up_local - try to wake up a local task with rq lock held * @p: the thread to be awakened * * Put @p on the run-queue if it's not already there. The caller must * ensure that this_rq() is locked, @p is bound to this_rq() and not * the current task. */ static void try_to_wake_up_local(struct task_struct *p) { struct rq *rq = task_rq(p); if (rq != this_rq() || p == current) { printk_sched("%s: Failed to wakeup task %d (%s), rq = %p, this_rq = %p, p = %p, current = %p\n", __func__, task_pid_nr(p), p->comm, rq, this_rq(), p, current); return; } lockdep_assert_held(&rq->lock); if (!raw_spin_trylock(&p->pi_lock)) { raw_spin_unlock(&rq->lock); raw_spin_lock(&p->pi_lock); raw_spin_lock(&rq->lock); } if (!(p->state & TASK_NORMAL)) goto out; if (!p->on_rq) ttwu_activate(rq, p, ENQUEUE_WAKEUP); ttwu_do_wakeup(rq, p, 0); ttwu_stat(p, smp_processor_id(), 0); out: raw_spin_unlock(&p->pi_lock); } /** * wake_up_process - Wake up a specific process * @p: The process to be woken up. * * Attempt to wake up the nominated process and move it to the set of runnable * processes. Returns 1 if the process was woken up, 0 if it was already * running. * * It may be assumed that this function implies a write memory barrier before * changing the task state if and only if any tasks are woken up. */ int wake_up_process(struct task_struct *p) { WARN_ON(task_is_stopped_or_traced(p)); return try_to_wake_up(p, TASK_NORMAL, 0); } EXPORT_SYMBOL(wake_up_process); int wake_up_state(struct task_struct *p, unsigned int state) { return try_to_wake_up(p, state, 0); } /* * Perform scheduler related setup for a newly forked process p. * p is forked by current. * * __sched_fork() is basic setup used by init_idle() too: */ static void __sched_fork(struct task_struct *p) { p->on_rq = 0; p->se.on_rq = 0; p->se.exec_start = 0; p->se.sum_exec_runtime = 0; p->se.prev_sum_exec_runtime = 0; p->se.nr_migrations = 0; p->se.vruntime = 0; INIT_LIST_HEAD(&p->se.group_node); #ifdef CONFIG_SCHEDSTATS memset(&p->se.statistics, 0, sizeof(p->se.statistics)); #endif INIT_LIST_HEAD(&p->rt.run_list); #ifdef CONFIG_PREEMPT_NOTIFIERS INIT_HLIST_HEAD(&p->preempt_notifiers); #endif } /* * fork()/clone()-time setup: */ void sched_fork(struct task_struct *p) { unsigned long flags; int cpu = get_cpu(); __sched_fork(p); /* * We mark the process as running here. This guarantees that * nobody will actually run it, and a signal or other external * event cannot wake it up and insert it on the runqueue either. */ p->state = TASK_RUNNING; /* * Make sure we do not leak PI boosting priority to the child. */ p->prio = current->normal_prio; /* * Revert to default priority/policy on fork if requested. */ if (unlikely(p->sched_reset_on_fork)) { if (task_has_rt_policy(p)) { p->policy = SCHED_NORMAL; p->static_prio = NICE_TO_PRIO(0); p->rt_priority = 0; } else if (PRIO_TO_NICE(p->static_prio) < 0) p->static_prio = NICE_TO_PRIO(0); p->prio = p->normal_prio = __normal_prio(p); set_load_weight(p); /* * We don't need the reset flag anymore after the fork. It has * fulfilled its duty: */ p->sched_reset_on_fork = 0; } if (!rt_prio(p->prio)) p->sched_class = &fair_sched_class; if (p->sched_class->task_fork) p->sched_class->task_fork(p); /* * The child is not yet in the pid-hash so no cgroup attach races, * and the cgroup is pinned to this child due to cgroup_fork() * is ran before sched_fork(). * * Silence PROVE_RCU. */ raw_spin_lock_irqsave(&p->pi_lock, flags); set_task_cpu(p, cpu); raw_spin_unlock_irqrestore(&p->pi_lock, flags); #if defined(CONFIG_SCHEDSTATS) || defined(CONFIG_TASK_DELAY_ACCT) if (likely(sched_info_on())) memset(&p->sched_info, 0, sizeof(p->sched_info)); #endif #if defined(CONFIG_SMP) p->on_cpu = 0; #endif #ifdef CONFIG_PREEMPT_COUNT /* Want to start with kernel preemption disabled. */ task_thread_info(p)->preempt_count = 1; #endif #ifdef CONFIG_SMP plist_node_init(&p->pushable_tasks, MAX_PRIO); #endif put_cpu(); } /* * wake_up_new_task - wake up a newly created task for the first time. * * This function will do some initial scheduler statistics housekeeping * that must be done for every newly created context, then puts the task * on the runqueue and wakes it. */ void wake_up_new_task(struct task_struct *p) { unsigned long flags; struct rq *rq; raw_spin_lock_irqsave(&p->pi_lock, flags); #ifdef CONFIG_SMP /* * Fork balancing, do it here and not earlier because: * - cpus_allowed can change in the fork path * - any previously selected cpu might disappear through hotplug */ set_task_cpu(p, select_task_rq(p, SD_BALANCE_FORK, 0)); #endif rq = __task_rq_lock(p); activate_task(rq, p, 0); p->on_rq = 1; trace_sched_wakeup_new(p, true); check_preempt_curr(rq, p, WF_FORK); #ifdef CONFIG_SMP if (p->sched_class->task_woken) p->sched_class->task_woken(rq, p); #endif task_rq_unlock(rq, p, &flags); } #ifdef CONFIG_PREEMPT_NOTIFIERS /** * preempt_notifier_register - tell me when current is being preempted & rescheduled * @notifier: notifier struct to register */ void preempt_notifier_register(struct preempt_notifier *notifier) { hlist_add_head(&notifier->link, &current->preempt_notifiers); } EXPORT_SYMBOL_GPL(preempt_notifier_register); /** * preempt_notifier_unregister - no longer interested in preemption notifications * @notifier: notifier struct to unregister * * This is safe to call from within a preemption notifier. */ void preempt_notifier_unregister(struct preempt_notifier *notifier) { hlist_del(&notifier->link); } EXPORT_SYMBOL_GPL(preempt_notifier_unregister); static void fire_sched_in_preempt_notifiers(struct task_struct *curr) { struct preempt_notifier *notifier; struct hlist_node *node; hlist_for_each_entry(notifier, node, &curr->preempt_notifiers, link) notifier->ops->sched_in(notifier, raw_smp_processor_id()); } static void fire_sched_out_preempt_notifiers(struct task_struct *curr, struct task_struct *next) { struct preempt_notifier *notifier; struct hlist_node *node; hlist_for_each_entry(notifier, node, &curr->preempt_notifiers, link) notifier->ops->sched_out(notifier, next); } #else /* !CONFIG_PREEMPT_NOTIFIERS */ static void fire_sched_in_preempt_notifiers(struct task_struct *curr) { } static void fire_sched_out_preempt_notifiers(struct task_struct *curr, struct task_struct *next) { } #endif /* CONFIG_PREEMPT_NOTIFIERS */ /** * prepare_task_switch - prepare to switch tasks * @rq: the runqueue preparing to switch * @prev: the current task that is being switched out * @next: the task we are going to switch to. * * This is called with the rq lock held and interrupts off. It must * be paired with a subsequent finish_task_switch after the context * switch. * * prepare_task_switch sets up locking and calls architecture specific * hooks. */ static inline void prepare_task_switch(struct rq *rq, struct task_struct *prev, struct task_struct *next) { sched_info_switch(prev, next); perf_event_task_sched_out(prev, next); fire_sched_out_preempt_notifiers(prev, next); prepare_lock_switch(rq, next); prepare_arch_switch(next); trace_sched_switch(prev, next); } /** * finish_task_switch - clean up after a task-switch * @rq: runqueue associated with task-switch * @prev: the thread we just switched away from. * * finish_task_switch must be called after the context switch, paired * with a prepare_task_switch call before the context switch. * finish_task_switch will reconcile locking set up by prepare_task_switch, * and do any other architecture-specific cleanup actions. * * Note that we may have delayed dropping an mm in context_switch(). If * so, we finish that here outside of the runqueue lock. (Doing it * with the lock held can cause deadlocks; see schedule() for * details.) */ static void finish_task_switch(struct rq *rq, struct task_struct *prev) __releases(rq->lock) { struct mm_struct *mm = rq->prev_mm; long prev_state; rq->prev_mm = NULL; /* * A task struct has one reference for the use as "current". * If a task dies, then it sets TASK_DEAD in tsk->state and calls * schedule one last time. The schedule call will never return, and * the scheduled task must drop that reference. * The test for TASK_DEAD must occur while the runqueue locks are * still held, otherwise prev could be scheduled on another cpu, die * there before we look at prev->state, and then the reference would * be dropped twice. * Manfred Spraul <manfred@colorfullife.com> */ prev_state = prev->state; finish_arch_switch(prev); #ifdef __ARCH_WANT_INTERRUPTS_ON_CTXSW local_irq_disable(); #endif /* __ARCH_WANT_INTERRUPTS_ON_CTXSW */ perf_event_task_sched_in(prev, current); #ifdef __ARCH_WANT_INTERRUPTS_ON_CTXSW local_irq_enable(); #endif /* __ARCH_WANT_INTERRUPTS_ON_CTXSW */ finish_lock_switch(rq, prev); finish_arch_post_lock_switch(); fire_sched_in_preempt_notifiers(current); if (mm) mmdrop(mm); if (unlikely(prev_state == TASK_DEAD)) { /* * Remove function-return probe instances associated with this * task and put them back on the free list. */ kprobe_flush_task(prev); put_task_struct(prev); } } #ifdef CONFIG_SMP /* assumes rq->lock is held */ static inline void pre_schedule(struct rq *rq, struct task_struct *prev) { if (prev->sched_class->pre_schedule) prev->sched_class->pre_schedule(rq, prev); } /* rq->lock is NOT held, but preemption is disabled */ static inline void post_schedule(struct rq *rq) { if (rq->post_schedule) { unsigned long flags; raw_spin_lock_irqsave(&rq->lock, flags); if (rq->curr->sched_class->post_schedule) rq->curr->sched_class->post_schedule(rq); raw_spin_unlock_irqrestore(&rq->lock, flags); rq->post_schedule = 0; } } #else static inline void pre_schedule(struct rq *rq, struct task_struct *p) { } static inline void post_schedule(struct rq *rq) { } #endif /** * schedule_tail - first thing a freshly forked thread must call. * @prev: the thread we just switched away from. */ asmlinkage void schedule_tail(struct task_struct *prev) __releases(rq->lock) { struct rq *rq = this_rq(); finish_task_switch(rq, prev); /* * FIXME: do we need to worry about rq being invalidated by the * task_switch? */ post_schedule(rq); #ifdef __ARCH_WANT_UNLOCKED_CTXSW /* In this case, finish_task_switch does not reenable preemption */ preempt_enable(); #endif if (current->set_child_tid) put_user(task_pid_vnr(current), current->set_child_tid); } /* * context_switch - switch to the new MM and the new * thread's register state. */ static inline void context_switch(struct rq *rq, struct task_struct *prev, struct task_struct *next) { struct mm_struct *mm, *oldmm; prepare_task_switch(rq, prev, next); mm = next->mm; oldmm = prev->active_mm; /* * For paravirt, this is coupled with an exit in switch_to to * combine the page table reload and the switch backend into * one hypercall. */ arch_start_context_switch(prev); if (!mm) { next->active_mm = oldmm; atomic_inc(&oldmm->mm_count); enter_lazy_tlb(oldmm, next); } else switch_mm(oldmm, mm, next); if (!prev->mm) { prev->active_mm = NULL; rq->prev_mm = oldmm; } /* * Since the runqueue lock will be released by the next * task (which is an invalid locking op but in the case * of the scheduler it's an obvious special-case), so we * do an early lockdep release here: */ #ifndef __ARCH_WANT_UNLOCKED_CTXSW spin_release(&rq->lock.dep_map, 1, _THIS_IP_); #endif /* Here we just switch the register state and the stack. */ switch_to(prev, next, prev); barrier(); /* * this_rq must be evaluated again because prev may have moved * CPUs since it called schedule(), thus the 'rq' on its stack * frame will be invalid. */ finish_task_switch(this_rq(), prev); } /* * nr_running, nr_uninterruptible and nr_context_switches: * * externally visible scheduler statistics: current number of runnable * threads, current number of uninterruptible-sleeping threads, total * number of context switches performed since bootup. */ unsigned long nr_running(void) { unsigned long i, sum = 0; for_each_online_cpu(i) sum += cpu_rq(i)->nr_running; return sum; } unsigned long nr_uninterruptible(void) { unsigned long i, sum = 0; for_each_possible_cpu(i) sum += cpu_rq(i)->nr_uninterruptible; /* * Since we read the counters lockless, it might be slightly * inaccurate. Do not allow it to go below zero though: */ if (unlikely((long)sum < 0)) sum = 0; return sum; } unsigned long long nr_context_switches(void) { int i; unsigned long long sum = 0; for_each_possible_cpu(i) sum += cpu_rq(i)->nr_switches; return sum; } unsigned long nr_iowait(void) { unsigned long i, sum = 0; for_each_possible_cpu(i) sum += atomic_read(&cpu_rq(i)->nr_iowait); return sum; } unsigned long nr_iowait_cpu(int cpu) { struct rq *this = cpu_rq(cpu); return atomic_read(&this->nr_iowait); } unsigned long this_cpu_load(void) { struct rq *this = this_rq(); return this->cpu_load[0]; } /* * Global load-average calculations * * We take a distributed and async approach to calculating the global load-avg * in order to minimize overhead. * * The global load average is an exponentially decaying average of nr_running + * nr_uninterruptible. * * Once every LOAD_FREQ: * * nr_active = 0; * for_each_possible_cpu(cpu) * nr_active += cpu_of(cpu)->nr_running + cpu_of(cpu)->nr_uninterruptible; * * avenrun[n] = avenrun[0] * exp_n + nr_active * (1 - exp_n) * * Due to a number of reasons the above turns in the mess below: * * - for_each_possible_cpu() is prohibitively expensive on machines with * serious number of cpus, therefore we need to take a distributed approach * to calculating nr_active. * * \Sum_i x_i(t) = \Sum_i x_i(t) - x_i(t_0) | x_i(t_0) := 0 * = \Sum_i { \Sum_j=1 x_i(t_j) - x_i(t_j-1) } * * So assuming nr_active := 0 when we start out -- true per definition, we * can simply take per-cpu deltas and fold those into a global accumulate * to obtain the same result. See calc_load_fold_active(). * * Furthermore, in order to avoid synchronizing all per-cpu delta folding * across the machine, we assume 10 ticks is sufficient time for every * cpu to have completed this task. * * This places an upper-bound on the IRQ-off latency of the machine. Then * again, being late doesn't loose the delta, just wrecks the sample. * * - cpu_rq()->nr_uninterruptible isn't accurately tracked per-cpu because * this would add another cross-cpu cacheline miss and atomic operation * to the wakeup path. Instead we increment on whatever cpu the task ran * when it went into uninterruptible state and decrement on whatever cpu * did the wakeup. This means that only the sum of nr_uninterruptible over * all cpus yields the correct result. * * This covers the NO_HZ=n code, for extra head-aches, see the comment below. */ /* Variables and functions for calc_load */ static atomic_long_t calc_load_tasks; static unsigned long calc_load_update; unsigned long avenrun[3]; EXPORT_SYMBOL(avenrun); /* should be removed */ /** * get_avenrun - get the load average array * @loads: pointer to dest load array * @offset: offset to add * @shift: shift count to shift the result left * * These values are estimates at best, so no need for locking. */ void get_avenrun(unsigned long *loads, unsigned long offset, int shift) { loads[0] = (avenrun[0] + offset) << shift; loads[1] = (avenrun[1] + offset) << shift; loads[2] = (avenrun[2] + offset) << shift; } static long calc_load_fold_active(struct rq *this_rq) { long nr_active, delta = 0; nr_active = this_rq->nr_running; nr_active += (long) this_rq->nr_uninterruptible; if (nr_active != this_rq->calc_load_active) { delta = nr_active - this_rq->calc_load_active; this_rq->calc_load_active = nr_active; } return delta; } /* * a1 = a0 * e + a * (1 - e) */ static unsigned long calc_load(unsigned long load, unsigned long exp, unsigned long active) { load *= exp; load += active * (FIXED_1 - exp); load += 1UL << (FSHIFT - 1); return load >> FSHIFT; } #ifdef CONFIG_NO_HZ /* * Handle NO_HZ for the global load-average. * * Since the above described distributed algorithm to compute the global * load-average relies on per-cpu sampling from the tick, it is affected by * NO_HZ. * * The basic idea is to fold the nr_active delta into a global idle-delta upon * entering NO_HZ state such that we can include this as an 'extra' cpu delta * when we read the global state. * * Obviously reality has to ruin such a delightfully simple scheme: * * - When we go NO_HZ idle during the window, we can negate our sample * contribution, causing under-accounting. * * We avoid this by keeping two idle-delta counters and flipping them * when the window starts, thus separating old and new NO_HZ load. * * The only trick is the slight shift in index flip for read vs write. * * 0s 5s 10s 15s * +10 +10 +10 +10 * |-|-----------|-|-----------|-|-----------|-| * r:0 0 1 1 0 0 1 1 0 * w:0 1 1 0 0 1 1 0 0 * * This ensures we'll fold the old idle contribution in this window while * accumlating the new one. * * - When we wake up from NO_HZ idle during the window, we push up our * contribution, since we effectively move our sample point to a known * busy state. * * This is solved by pushing the window forward, and thus skipping the * sample, for this cpu (effectively using the idle-delta for this cpu which * was in effect at the time the window opened). This also solves the issue * of having to deal with a cpu having been in NOHZ idle for multiple * LOAD_FREQ intervals. * * When making the ILB scale, we should try to pull this in as well. */ static atomic_long_t calc_load_idle[2]; static int calc_load_idx; static inline int calc_load_write_idx(void) { int idx = calc_load_idx; /* * See calc_global_nohz(), if we observe the new index, we also * need to observe the new update time. */ smp_rmb(); /* * If the folding window started, make sure we start writing in the * next idle-delta. */ if (!time_before(jiffies, calc_load_update)) idx++; return idx & 1; } static inline int calc_load_read_idx(void) { return calc_load_idx & 1; } void calc_load_enter_idle(void) { struct rq *this_rq = this_rq(); long delta; /* * We're going into NOHZ mode, if there's any pending delta, fold it * into the pending idle delta. */ delta = calc_load_fold_active(this_rq); if (delta) { int idx = calc_load_write_idx(); atomic_long_add(delta, &calc_load_idle[idx]); } } void calc_load_exit_idle(void) { struct rq *this_rq = this_rq(); /* * If we're still before the sample window, we're done. */ if (time_before(jiffies, this_rq->calc_load_update)) return; /* * We woke inside or after the sample window, this means we're already * accounted through the nohz accounting, so skip the entire deal and * sync up for the next window. */ this_rq->calc_load_update = calc_load_update; if (time_before(jiffies, this_rq->calc_load_update + 10)) this_rq->calc_load_update += LOAD_FREQ; } static long calc_load_fold_idle(void) { int idx = calc_load_read_idx(); long delta = 0; if (atomic_long_read(&calc_load_idle[idx])) delta = atomic_long_xchg(&calc_load_idle[idx], 0); return delta; } /** * fixed_power_int - compute: x^n, in O(log n) time * * @x: base of the power * @frac_bits: fractional bits of @x * @n: power to raise @x to. * * By exploiting the relation between the definition of the natural power * function: x^n := x*x*...*x (x multiplied by itself for n times), and * the binary encoding of numbers used by computers: n := \Sum n_i * 2^i, * (where: n_i \elem {0, 1}, the binary vector representing n), * we find: x^n := x^(\Sum n_i * 2^i) := \Prod x^(n_i * 2^i), which is * of course trivially computable in O(log_2 n), the length of our binary * vector. */ static unsigned long fixed_power_int(unsigned long x, unsigned int frac_bits, unsigned int n) { unsigned long result = 1UL << frac_bits; if (n) for (;;) { if (n & 1) { result *= x; result += 1UL << (frac_bits - 1); result >>= frac_bits; } n >>= 1; if (!n) break; x *= x; x += 1UL << (frac_bits - 1); x >>= frac_bits; } return result; } /* * a1 = a0 * e + a * (1 - e) * * a2 = a1 * e + a * (1 - e) * = (a0 * e + a * (1 - e)) * e + a * (1 - e) * = a0 * e^2 + a * (1 - e) * (1 + e) * * a3 = a2 * e + a * (1 - e) * = (a0 * e^2 + a * (1 - e) * (1 + e)) * e + a * (1 - e) * = a0 * e^3 + a * (1 - e) * (1 + e + e^2) * * ... * * an = a0 * e^n + a * (1 - e) * (1 + e + ... + e^n-1) [1] * = a0 * e^n + a * (1 - e) * (1 - e^n)/(1 - e) * = a0 * e^n + a * (1 - e^n) * * [1] application of the geometric series: * * n 1 - x^(n+1) * S_n := \Sum x^i = ------------- * i=0 1 - x */ static unsigned long calc_load_n(unsigned long load, unsigned long exp, unsigned long active, unsigned int n) { return calc_load(load, fixed_power_int(exp, FSHIFT, n), active); } /* * NO_HZ can leave us missing all per-cpu ticks calling * calc_load_account_active(), but since an idle CPU folds its delta into * calc_load_tasks_idle per calc_load_account_idle(), all we need to do is fold * in the pending idle delta if our idle period crossed a load cycle boundary. * * Once we've updated the global active value, we need to apply the exponential * weights adjusted to the number of cycles missed. */ static void calc_global_nohz(void) { long delta, active, n; if (!time_before(jiffies, calc_load_update + 10)) { /* * Catch-up, fold however many we are behind still */ delta = jiffies - calc_load_update - 10; n = 1 + (delta / LOAD_FREQ); active = atomic_long_read(&calc_load_tasks); active = active > 0 ? active * FIXED_1 : 0; avenrun[0] = calc_load_n(avenrun[0], EXP_1, active, n); avenrun[1] = calc_load_n(avenrun[1], EXP_5, active, n); avenrun[2] = calc_load_n(avenrun[2], EXP_15, active, n); calc_load_update += n * LOAD_FREQ; } /* * Flip the idle index... * * Make sure we first write the new time then flip the index, so that * calc_load_write_idx() will see the new time when it reads the new * index, this avoids a double flip messing things up. */ smp_wmb(); calc_load_idx++; } #else /* !CONFIG_NO_HZ */ static inline long calc_load_fold_idle(void) { return 0; } static inline void calc_global_nohz(void) { } #endif /* CONFIG_NO_HZ */ /* * calc_load - update the avenrun load estimates 10 ticks after the * CPUs have updated calc_load_tasks. */ void calc_global_load(unsigned long ticks) { long active, delta; if (time_before(jiffies, calc_load_update + 10)) return; /* * Fold the 'old' idle-delta to include all NO_HZ cpus. */ delta = calc_load_fold_idle(); if (delta) atomic_long_add(delta, &calc_load_tasks); active = atomic_long_read(&calc_load_tasks); active = active > 0 ? active * FIXED_1 : 0; avenrun[0] = calc_load(avenrun[0], EXP_1, active); avenrun[1] = calc_load(avenrun[1], EXP_5, active); avenrun[2] = calc_load(avenrun[2], EXP_15, active); calc_load_update += LOAD_FREQ; /* * In case we idled for multiple LOAD_FREQ intervals, catch up in bulk. */ calc_global_nohz(); } /* * Called from update_cpu_load() to periodically update this CPU's * active count. */ static void calc_load_account_active(struct rq *this_rq) { long delta; if (time_before(jiffies, this_rq->calc_load_update)) return; delta = calc_load_fold_active(this_rq); if (delta) atomic_long_add(delta, &calc_load_tasks); this_rq->calc_load_update += LOAD_FREQ; } /* * End of global load-average stuff */ /* * The exact cpuload at various idx values, calculated at every tick would be * load = (2^idx - 1) / 2^idx * load + 1 / 2^idx * cur_load * * If a cpu misses updates for n-1 ticks (as it was idle) and update gets called * on nth tick when cpu may be busy, then we have: * load = ((2^idx - 1) / 2^idx)^(n-1) * load * load = (2^idx - 1) / 2^idx) * load + 1 / 2^idx * cur_load * * decay_load_missed() below does efficient calculation of * load = ((2^idx - 1) / 2^idx)^(n-1) * load * avoiding 0..n-1 loop doing load = ((2^idx - 1) / 2^idx) * load * * The calculation is approximated on a 128 point scale. * degrade_zero_ticks is the number of ticks after which load at any * particular idx is approximated to be zero. * degrade_factor is a precomputed table, a row for each load idx. * Each column corresponds to degradation factor for a power of two ticks, * based on 128 point scale. * Example: * row 2, col 3 (=12) says that the degradation at load idx 2 after * 8 ticks is 12/128 (which is an approximation of exact factor 3^8/4^8). * * With this power of 2 load factors, we can degrade the load n times * by looking at 1 bits in n and doing as many mult/shift instead of * n mult/shifts needed by the exact degradation. */ #define DEGRADE_SHIFT 7 static const unsigned char degrade_zero_ticks[CPU_LOAD_IDX_MAX] = {0, 8, 32, 64, 128}; static const unsigned char degrade_factor[CPU_LOAD_IDX_MAX][DEGRADE_SHIFT + 1] = { {0, 0, 0, 0, 0, 0, 0, 0}, {64, 32, 8, 0, 0, 0, 0, 0}, {96, 72, 40, 12, 1, 0, 0}, {112, 98, 75, 43, 15, 1, 0}, {120, 112, 98, 76, 45, 16, 2} }; /* * Update cpu_load for any missed ticks, due to tickless idle. The backlog * would be when CPU is idle and so we just decay the old load without * adding any new load. */ static unsigned long decay_load_missed(unsigned long load, unsigned long missed_updates, int idx) { int j = 0; if (!missed_updates) return load; if (missed_updates >= degrade_zero_ticks[idx]) return 0; if (idx == 1) return load >> missed_updates; while (missed_updates) { if (missed_updates % 2) load = (load * degrade_factor[idx][j]) >> DEGRADE_SHIFT; missed_updates >>= 1; j++; } return load; } /* * Update rq->cpu_load[] statistics. This function is usually called every * scheduler tick (TICK_NSEC). With tickless idle this will not be called * every tick. We fix it up based on jiffies. */ static void __update_cpu_load(struct rq *this_rq, unsigned long this_load, unsigned long pending_updates) { int i, scale; this_rq->nr_load_updates++; /* Update our load: */ this_rq->cpu_load[0] = this_load; /* Fasttrack for idx 0 */ for (i = 1, scale = 2; i < CPU_LOAD_IDX_MAX; i++, scale += scale) { unsigned long old_load, new_load; /* scale is effectively 1 << i now, and >> i divides by scale */ old_load = this_rq->cpu_load[i]; old_load = decay_load_missed(old_load, pending_updates - 1, i); new_load = this_load; /* * Round up the averaging division if load is increasing. This * prevents us from getting stuck on 9 if the load is 10, for * example. */ if (new_load > old_load) new_load += scale - 1; this_rq->cpu_load[i] = (old_load * (scale - 1) + new_load) >> i; } sched_avg_update(this_rq); } #ifdef CONFIG_NO_HZ /* * There is no sane way to deal with nohz on smp when using jiffies because the * cpu doing the jiffies update might drift wrt the cpu doing the jiffy reading * causing off-by-one errors in observed deltas; {0,2} instead of {1,1}. * * Therefore we cannot use the delta approach from the regular tick since that * would seriously skew the load calculation. However we'll make do for those * updates happening while idle (nohz_idle_balance) or coming out of idle * (tick_nohz_idle_exit). * * This means we might still be one tick off for nohz periods. */ /* * Called from nohz_idle_balance() to update the load ratings before doing the * idle balance. */ void update_idle_cpu_load(struct rq *this_rq) { unsigned long curr_jiffies = ACCESS_ONCE(jiffies); unsigned long load = this_rq->load.weight; unsigned long pending_updates; /* * bail if there's load or we're actually up-to-date. */ if (load || curr_jiffies == this_rq->last_load_update_tick) return; pending_updates = curr_jiffies - this_rq->last_load_update_tick; this_rq->last_load_update_tick = curr_jiffies; __update_cpu_load(this_rq, load, pending_updates); } /* * Called from tick_nohz_idle_exit() -- try and fix up the ticks we missed. */ void update_cpu_load_nohz(void) { struct rq *this_rq = this_rq(); unsigned long curr_jiffies = ACCESS_ONCE(jiffies); unsigned long pending_updates; if (curr_jiffies == this_rq->last_load_update_tick) return; raw_spin_lock(&this_rq->lock); pending_updates = curr_jiffies - this_rq->last_load_update_tick; if (pending_updates) { this_rq->last_load_update_tick = curr_jiffies; /* * We were idle, this means load 0, the current load might be * !0 due to remote wakeups and the sort. */ __update_cpu_load(this_rq, 0, pending_updates); } raw_spin_unlock(&this_rq->lock); } #endif /* CONFIG_NO_HZ */ /* * Called from scheduler_tick() */ static void update_cpu_load_active(struct rq *this_rq) { /* * See the mess around update_idle_cpu_load() / update_cpu_load_nohz(). */ this_rq->last_load_update_tick = jiffies; __update_cpu_load(this_rq, this_rq->load.weight, 1); calc_load_account_active(this_rq); } #ifdef CONFIG_SMP /* * sched_exec - execve() is a valuable balancing opportunity, because at * this point the task has the smallest effective memory and cache footprint. */ void sched_exec(void) { struct task_struct *p = current; unsigned long flags; int dest_cpu; raw_spin_lock_irqsave(&p->pi_lock, flags); dest_cpu = p->sched_class->select_task_rq(p, SD_BALANCE_EXEC, 0); if (dest_cpu == smp_processor_id()) goto unlock; if (likely(cpu_active(dest_cpu))) { struct migration_arg arg = { p, dest_cpu }; raw_spin_unlock_irqrestore(&p->pi_lock, flags); stop_one_cpu(task_cpu(p), migration_cpu_stop, &arg); return; } unlock: raw_spin_unlock_irqrestore(&p->pi_lock, flags); } #endif DEFINE_PER_CPU(struct kernel_stat, kstat); DEFINE_PER_CPU(struct kernel_cpustat, kernel_cpustat); EXPORT_PER_CPU_SYMBOL(kstat); EXPORT_PER_CPU_SYMBOL(kernel_cpustat); /* * Return any ns on the sched_clock that have not yet been accounted in * @p in case that task is currently running. * * Called with task_rq_lock() held on @rq. */ static u64 do_task_delta_exec(struct task_struct *p, struct rq *rq) { u64 ns = 0; if (task_current(rq, p)) { update_rq_clock(rq); ns = rq->clock_task - p->se.exec_start; if ((s64)ns < 0) ns = 0; } return ns; } unsigned long long task_delta_exec(struct task_struct *p) { unsigned long flags; struct rq *rq; u64 ns = 0; rq = task_rq_lock(p, &flags); ns = do_task_delta_exec(p, rq); task_rq_unlock(rq, p, &flags); return ns; } /* * Return accounted runtime for the task. * In case the task is currently running, return the runtime plus current's * pending runtime that have not been accounted yet. */ unsigned long long task_sched_runtime(struct task_struct *p) { unsigned long flags; struct rq *rq; u64 ns = 0; rq = task_rq_lock(p, &flags); ns = p->se.sum_exec_runtime + do_task_delta_exec(p, rq); task_rq_unlock(rq, p, &flags); return ns; } #ifdef CONFIG_CGROUP_CPUACCT struct cgroup_subsys cpuacct_subsys; struct cpuacct root_cpuacct; #endif static inline void task_group_account_field(struct task_struct *p, int index, u64 tmp) { #ifdef CONFIG_CGROUP_CPUACCT struct kernel_cpustat *kcpustat; struct cpuacct *ca; #endif /* * Since all updates are sure to touch the root cgroup, we * get ourselves ahead and touch it first. If the root cgroup * is the only cgroup, then nothing else should be necessary. * */ __get_cpu_var(kernel_cpustat).cpustat[index] += tmp; #ifdef CONFIG_CGROUP_CPUACCT if (unlikely(!cpuacct_subsys.active)) return; rcu_read_lock(); ca = task_ca(p); while (ca && (ca != &root_cpuacct)) { kcpustat = this_cpu_ptr(ca->cpustat); kcpustat->cpustat[index] += tmp; ca = parent_ca(ca); } rcu_read_unlock(); #endif } /* * Account user cpu time to a process. * @p: the process that the cpu time gets accounted to * @cputime: the cpu time spent in user space since the last update * @cputime_scaled: cputime scaled by cpu frequency */ void account_user_time(struct task_struct *p, cputime_t cputime, cputime_t cputime_scaled) { int index; /* Add user time to process. */ p->utime += cputime; p->utimescaled += cputime_scaled; account_group_user_time(p, cputime); index = (TASK_NICE(p) > 0) ? CPUTIME_NICE : CPUTIME_USER; /* Add user time to cpustat. */ task_group_account_field(p, index, (__force u64) cputime); /* Account for user time used */ acct_update_integrals(p); } /* * Account guest cpu time to a process. * @p: the process that the cpu time gets accounted to * @cputime: the cpu time spent in virtual machine since the last update * @cputime_scaled: cputime scaled by cpu frequency */ static void account_guest_time(struct task_struct *p, cputime_t cputime, cputime_t cputime_scaled) { u64 *cpustat = kcpustat_this_cpu->cpustat; /* Add guest time to process. */ p->utime += cputime; p->utimescaled += cputime_scaled; account_group_user_time(p, cputime); p->gtime += cputime; /* Add guest time to cpustat. */ if (TASK_NICE(p) > 0) { cpustat[CPUTIME_NICE] += (__force u64) cputime; cpustat[CPUTIME_GUEST_NICE] += (__force u64) cputime; } else { cpustat[CPUTIME_USER] += (__force u64) cputime; cpustat[CPUTIME_GUEST] += (__force u64) cputime; } } /* * Account system cpu time to a process and desired cpustat field * @p: the process that the cpu time gets accounted to * @cputime: the cpu time spent in kernel space since the last update * @cputime_scaled: cputime scaled by cpu frequency * @target_cputime64: pointer to cpustat field that has to be updated */ static inline void __account_system_time(struct task_struct *p, cputime_t cputime, cputime_t cputime_scaled, int index) { /* Add system time to process. */ p->stime += cputime; p->stimescaled += cputime_scaled; account_group_system_time(p, cputime); /* Add system time to cpustat. */ task_group_account_field(p, index, (__force u64) cputime); /* Account for system time used */ acct_update_integrals(p); } /* * Account system cpu time to a process. * @p: the process that the cpu time gets accounted to * @hardirq_offset: the offset to subtract from hardirq_count() * @cputime: the cpu time spent in kernel space since the last update * @cputime_scaled: cputime scaled by cpu frequency */ void account_system_time(struct task_struct *p, int hardirq_offset, cputime_t cputime, cputime_t cputime_scaled) { int index; if ((p->flags & PF_VCPU) && (irq_count() - hardirq_offset == 0)) { account_guest_time(p, cputime, cputime_scaled); return; } if (hardirq_count() - hardirq_offset) index = CPUTIME_IRQ; else if (in_serving_softirq()) index = CPUTIME_SOFTIRQ; else index = CPUTIME_SYSTEM; __account_system_time(p, cputime, cputime_scaled, index); } /* * Account for involuntary wait time. * @cputime: the cpu time spent in involuntary wait */ void account_steal_time(cputime_t cputime) { u64 *cpustat = kcpustat_this_cpu->cpustat; cpustat[CPUTIME_STEAL] += (__force u64) cputime; } /* * Account for idle time. * @cputime: the cpu time spent in idle wait */ void account_idle_time(cputime_t cputime) { u64 *cpustat = kcpustat_this_cpu->cpustat; struct rq *rq = this_rq(); if (atomic_read(&rq->nr_iowait) > 0) cpustat[CPUTIME_IOWAIT] += (__force u64) cputime; else cpustat[CPUTIME_IDLE] += (__force u64) cputime; } static __always_inline bool steal_account_process_tick(void) { #ifdef CONFIG_PARAVIRT if (static_key_false(&paravirt_steal_enabled)) { u64 steal, st = 0; steal = paravirt_steal_clock(smp_processor_id()); steal -= this_rq()->prev_steal_time; st = steal_ticks(steal); this_rq()->prev_steal_time += st * TICK_NSEC; account_steal_time(st); return st; } #endif return false; } #ifndef CONFIG_VIRT_CPU_ACCOUNTING #ifdef CONFIG_IRQ_TIME_ACCOUNTING /* * Account a tick to a process and cpustat * @p: the process that the cpu time gets accounted to * @user_tick: is the tick from userspace * @rq: the pointer to rq * * Tick demultiplexing follows the order * - pending hardirq update * - pending softirq update * - user_time * - idle_time * - system time * - check for guest_time * - else account as system_time * * Check for hardirq is done both for system and user time as there is * no timer going off while we are on hardirq and hence we may never get an * opportunity to update it solely in system time. * p->stime and friends are only updated on system time and not on irq * softirq as those do not count in task exec_runtime any more. */ static void irqtime_account_process_tick(struct task_struct *p, int user_tick, struct rq *rq) { cputime_t one_jiffy_scaled = cputime_to_scaled(cputime_one_jiffy); u64 *cpustat = kcpustat_this_cpu->cpustat; if (steal_account_process_tick()) return; if (irqtime_account_hi_update()) { cpustat[CPUTIME_IRQ] += (__force u64) cputime_one_jiffy; } else if (irqtime_account_si_update()) { cpustat[CPUTIME_SOFTIRQ] += (__force u64) cputime_one_jiffy; } else if (this_cpu_ksoftirqd() == p) { /* * ksoftirqd time do not get accounted in cpu_softirq_time. * So, we have to handle it separately here. * Also, p->stime needs to be updated for ksoftirqd. */ __account_system_time(p, cputime_one_jiffy, one_jiffy_scaled, CPUTIME_SOFTIRQ); } else if (user_tick) { account_user_time(p, cputime_one_jiffy, one_jiffy_scaled); } else if (p == rq->idle) { account_idle_time(cputime_one_jiffy); } else if (p->flags & PF_VCPU) { /* System time or guest time */ account_guest_time(p, cputime_one_jiffy, one_jiffy_scaled); } else { __account_system_time(p, cputime_one_jiffy, one_jiffy_scaled, CPUTIME_SYSTEM); } } static void irqtime_account_idle_ticks(int ticks) { int i; struct rq *rq = this_rq(); for (i = 0; i < ticks; i++) irqtime_account_process_tick(current, 0, rq); } #else /* CONFIG_IRQ_TIME_ACCOUNTING */ static void irqtime_account_idle_ticks(int ticks) {} static void irqtime_account_process_tick(struct task_struct *p, int user_tick, struct rq *rq) {} #endif /* CONFIG_IRQ_TIME_ACCOUNTING */ /* * Account a single tick of cpu time. * @p: the process that the cpu time gets accounted to * @user_tick: indicates if the tick is a user or a system tick */ void account_process_tick(struct task_struct *p, int user_tick) { cputime_t one_jiffy_scaled = cputime_to_scaled(cputime_one_jiffy); struct rq *rq = this_rq(); if (sched_clock_irqtime) { irqtime_account_process_tick(p, user_tick, rq); return; } if (steal_account_process_tick()) return; if (user_tick) account_user_time(p, cputime_one_jiffy, one_jiffy_scaled); else if ((p != rq->idle) || (irq_count() != HARDIRQ_OFFSET)) account_system_time(p, HARDIRQ_OFFSET, cputime_one_jiffy, one_jiffy_scaled); else account_idle_time(cputime_one_jiffy); } /* * Account multiple ticks of steal time. * @p: the process from which the cpu time has been stolen * @ticks: number of stolen ticks */ void account_steal_ticks(unsigned long ticks) { account_steal_time(jiffies_to_cputime(ticks)); } /* * Account multiple ticks of idle time. * @ticks: number of stolen ticks */ void account_idle_ticks(unsigned long ticks) { if (sched_clock_irqtime) { irqtime_account_idle_ticks(ticks); return; } account_idle_time(jiffies_to_cputime(ticks)); } #endif /* * Use precise platform statistics if available: */ #ifdef CONFIG_VIRT_CPU_ACCOUNTING void task_times(struct task_struct *p, cputime_t *ut, cputime_t *st) { *ut = p->utime; *st = p->stime; } void thread_group_times(struct task_struct *p, cputime_t *ut, cputime_t *st) { struct task_cputime cputime; thread_group_cputime(p, &cputime); *ut = cputime.utime; *st = cputime.stime; } #else #ifndef nsecs_to_cputime # define nsecs_to_cputime(__nsecs) nsecs_to_jiffies(__nsecs) #endif static cputime_t scale_utime(cputime_t utime, cputime_t rtime, cputime_t total) { u64 temp = (__force u64) rtime; temp *= (__force u64) utime; if (sizeof(cputime_t) == 4) temp = div_u64(temp, (__force u32) total); else temp = div64_u64(temp, (__force u64) total); return (__force cputime_t) temp; } void task_times(struct task_struct *p, cputime_t *ut, cputime_t *st) { cputime_t rtime, utime = p->utime, total = utime + p->stime; /* * Use CFS's precise accounting: */ rtime = nsecs_to_cputime(p->se.sum_exec_runtime); if (total) utime = scale_utime(utime, rtime, total); else utime = rtime; /* * Compare with previous values, to keep monotonicity: */ p->prev_utime = max(p->prev_utime, utime); p->prev_stime = max(p->prev_stime, rtime - p->prev_utime); *ut = p->prev_utime; *st = p->prev_stime; } /* * Must be called with siglock held. */ void thread_group_times(struct task_struct *p, cputime_t *ut, cputime_t *st) { struct signal_struct *sig = p->signal; struct task_cputime cputime; cputime_t rtime, utime, total; thread_group_cputime(p, &cputime); total = cputime.utime + cputime.stime; rtime = nsecs_to_cputime(cputime.sum_exec_runtime); if (total) utime = scale_utime(cputime.utime, rtime, total); else utime = rtime; sig->prev_utime = max(sig->prev_utime, utime); sig->prev_stime = max(sig->prev_stime, rtime - sig->prev_utime); *ut = sig->prev_utime; *st = sig->prev_stime; } #endif /* * This function gets called by the timer code, with HZ frequency. * We call it with interrupts disabled. */ void scheduler_tick(void) { int cpu = smp_processor_id(); struct rq *rq = cpu_rq(cpu); struct task_struct *curr = rq->curr; sched_clock_tick(); raw_spin_lock(&rq->lock); update_rq_clock(rq); update_cpu_load_active(rq); curr->sched_class->task_tick(rq, curr, 0); raw_spin_unlock(&rq->lock); perf_event_task_tick(); #ifdef CONFIG_SMP rq->idle_balance = idle_cpu(cpu); trigger_load_balance(rq, cpu); #endif } notrace unsigned long get_parent_ip(unsigned long addr) { if (in_lock_functions(addr)) { addr = CALLER_ADDR2; if (in_lock_functions(addr)) addr = CALLER_ADDR3; } return addr; } #if defined(CONFIG_PREEMPT) && (defined(CONFIG_DEBUG_PREEMPT) || \ defined(CONFIG_PREEMPT_TRACER)) void __kprobes add_preempt_count(int val) { #ifdef CONFIG_DEBUG_PREEMPT /* * Underflow? */ if (DEBUG_LOCKS_WARN_ON((preempt_count() < 0))) return; #endif preempt_count() += val; #ifdef CONFIG_DEBUG_PREEMPT /* * Spinlock count overflowing soon? */ DEBUG_LOCKS_WARN_ON((preempt_count() & PREEMPT_MASK) >= PREEMPT_MASK - 10); #endif if (preempt_count() == val) trace_preempt_off(CALLER_ADDR0, get_parent_ip(CALLER_ADDR1)); } EXPORT_SYMBOL(add_preempt_count); void __kprobes sub_preempt_count(int val) { #ifdef CONFIG_DEBUG_PREEMPT /* * Underflow? */ if (DEBUG_LOCKS_WARN_ON(val > preempt_count())) return; /* * Is the spinlock portion underflowing? */ if (DEBUG_LOCKS_WARN_ON((val < PREEMPT_MASK) && !(preempt_count() & PREEMPT_MASK))) return; #endif if (preempt_count() == val) trace_preempt_on(CALLER_ADDR0, get_parent_ip(CALLER_ADDR1)); preempt_count() -= val; } EXPORT_SYMBOL(sub_preempt_count); #endif /* * Print scheduling while atomic bug: */ static noinline void __schedule_bug(struct task_struct *prev) { if (oops_in_progress) return; printk(KERN_ERR "BUG: scheduling while atomic: %s/%d/0x%08x\n", prev->comm, prev->pid, preempt_count()); debug_show_held_locks(prev); print_modules(); if (irqs_disabled()) print_irqtrace_events(prev); dump_stack(); } /* * Various schedule()-time debugging checks and statistics: */ static inline void schedule_debug(struct task_struct *prev) { /* * Test if we are atomic. Since do_exit() needs to call into * schedule() atomically, we ignore that path for now. * Otherwise, whine if we are scheduling when we should not be. */ if (unlikely(in_atomic_preempt_off() && !prev->exit_state)) __schedule_bug(prev); rcu_sleep_check(); profile_hit(SCHED_PROFILING, __builtin_return_address(0)); schedstat_inc(this_rq(), sched_count); } static void put_prev_task(struct rq *rq, struct task_struct *prev) { if (prev->on_rq || rq->skip_clock_update < 0) update_rq_clock(rq); prev->sched_class->put_prev_task(rq, prev); } /* * Pick up the highest-prio task: */ static inline struct task_struct * pick_next_task(struct rq *rq) { const struct sched_class *class; struct task_struct *p; /* * Optimization: we know that if all tasks are in * the fair class we can call that function directly: */ if (likely(rq->nr_running == rq->cfs.h_nr_running)) { p = fair_sched_class.pick_next_task(rq); if (likely(p)) return p; } for_each_class(class) { p = class->pick_next_task(rq); if (p) return p; } BUG(); /* the idle class will always have a runnable task */ } /* * __schedule() is the main scheduler function. */ static void __sched __schedule(void) { struct task_struct *prev, *next; unsigned long *switch_count; struct rq *rq; int cpu; need_resched: preempt_disable(); cpu = smp_processor_id(); rq = cpu_rq(cpu); rcu_note_context_switch(cpu); prev = rq->curr; schedule_debug(prev); if (sched_feat(HRTICK)) hrtick_clear(rq); raw_spin_lock_irq(&rq->lock); switch_count = &prev->nivcsw; if (prev->state && !(preempt_count() & PREEMPT_ACTIVE)) { if (unlikely(signal_pending_state(prev->state, prev))) { prev->state = TASK_RUNNING; } else { deactivate_task(rq, prev, DEQUEUE_SLEEP); prev->on_rq = 0; /* * If a worker went to sleep, notify and ask workqueue * whether it wants to wake up a task to maintain * concurrency. */ if (prev->flags & PF_WQ_WORKER) { struct task_struct *to_wakeup; to_wakeup = wq_worker_sleeping(prev, cpu); if (to_wakeup) try_to_wake_up_local(to_wakeup); } } switch_count = &prev->nvcsw; } pre_schedule(rq, prev); if (unlikely(!rq->nr_running)) idle_balance(cpu, rq); put_prev_task(rq, prev); next = pick_next_task(rq); clear_tsk_need_resched(prev); rq->skip_clock_update = 0; if (likely(prev != next)) { rq->nr_switches++; rq->curr = next; ++*switch_count; context_switch(rq, prev, next); /* unlocks the rq */ /* * The context switch have flipped the stack from under us * and restored the local variables which were saved when * this task called schedule() in the past. prev == current * is still correct, but it can be moved to another cpu/rq. */ cpu = smp_processor_id(); rq = cpu_rq(cpu); } else raw_spin_unlock_irq(&rq->lock); post_schedule(rq); sched_preempt_enable_no_resched(); if (need_resched()) goto need_resched; } static inline void sched_submit_work(struct task_struct *tsk) { if (!tsk->state || tsk_is_pi_blocked(tsk)) return; /* * If we are going to sleep and we have plugged IO queued, * make sure to submit it to avoid deadlocks. */ if (blk_needs_flush_plug(tsk)) blk_schedule_flush_plug(tsk); } asmlinkage void __sched schedule(void) { struct task_struct *tsk = current; sched_submit_work(tsk); __schedule(); } EXPORT_SYMBOL(schedule); /** * schedule_preempt_disabled - called with preemption disabled * * Returns with preemption disabled. Note: preempt_count must be 1 */ void __sched schedule_preempt_disabled(void) { sched_preempt_enable_no_resched(); schedule(); preempt_disable(); } #ifdef CONFIG_MUTEX_SPIN_ON_OWNER static inline bool owner_running(struct mutex *lock, struct task_struct *owner) { if (lock->owner != owner) return false; /* * Ensure we emit the owner->on_cpu, dereference _after_ checking * lock->owner still matches owner, if that fails, owner might * point to free()d memory, if it still matches, the rcu_read_lock() * ensures the memory stays valid. */ barrier(); return owner->on_cpu; } /* * Look out! "owner" is an entirely speculative pointer * access and not reliable. */ int mutex_spin_on_owner(struct mutex *lock, struct task_struct *owner) { if (!sched_feat(OWNER_SPIN)) return 0; rcu_read_lock(); while (owner_running(lock, owner)) { if (need_resched()) break; arch_mutex_cpu_relax(); } rcu_read_unlock(); /* * We break out the loop above on need_resched() and when the * owner changed, which is a sign for heavy contention. Return * success only when lock->owner is NULL. */ return lock->owner == NULL; } #endif #ifdef CONFIG_PREEMPT /* * this is the entry point to schedule() from in-kernel preemption * off of preempt_enable. Kernel preemptions off return from interrupt * occur there and call schedule directly. */ asmlinkage void __sched notrace preempt_schedule(void) { struct thread_info *ti = current_thread_info(); /* * If there is a non-zero preempt_count or interrupts are disabled, * we do not want to preempt the current task. Just return.. */ if (likely(ti->preempt_count || irqs_disabled())) return; do { add_preempt_count_notrace(PREEMPT_ACTIVE); __schedule(); sub_preempt_count_notrace(PREEMPT_ACTIVE); /* * Check again in case we missed a preemption opportunity * between schedule and now. */ barrier(); } while (need_resched()); } EXPORT_SYMBOL(preempt_schedule); /* * this is the entry point to schedule() from kernel preemption * off of irq context. * Note, that this is called and return with irqs disabled. This will * protect us against recursive calling from irq. */ asmlinkage void __sched preempt_schedule_irq(void) { struct thread_info *ti = current_thread_info(); /* Catch callers which need to be fixed */ BUG_ON(ti->preempt_count || !irqs_disabled()); do { add_preempt_count(PREEMPT_ACTIVE); local_irq_enable(); __schedule(); local_irq_disable(); sub_preempt_count(PREEMPT_ACTIVE); /* * Check again in case we missed a preemption opportunity * between schedule and now. */ barrier(); } while (need_resched()); } #endif /* CONFIG_PREEMPT */ int default_wake_function(wait_queue_t *curr, unsigned mode, int wake_flags, void *key) { return try_to_wake_up(curr->private, mode, wake_flags); } EXPORT_SYMBOL(default_wake_function); /* * The core wakeup function. Non-exclusive wakeups (nr_exclusive == 0) just * wake everything up. If it's an exclusive wakeup (nr_exclusive == small +ve * number) then we wake all the non-exclusive tasks and one exclusive task. * * There are circumstances in which we can try to wake a task which has already * started to run but is not in state TASK_RUNNING. try_to_wake_up() returns * zero in this (rare) case, and we handle it by continuing to scan the queue. */ static void __wake_up_common(wait_queue_head_t *q, unsigned int mode, int nr_exclusive, int wake_flags, void *key) { wait_queue_t *curr, *next; list_for_each_entry_safe(curr, next, &q->task_list, task_list) { unsigned flags = curr->flags; if (curr->func(curr, mode, wake_flags, key) && (flags & WQ_FLAG_EXCLUSIVE) && !--nr_exclusive) break; } } /** * __wake_up - wake up threads blocked on a waitqueue. * @q: the waitqueue * @mode: which threads * @nr_exclusive: how many wake-one or wake-many threads to wake up * @key: is directly passed to the wakeup function * * It may be assumed that this function implies a write memory barrier before * changing the task state if and only if any tasks are woken up. */ void __wake_up(wait_queue_head_t *q, unsigned int mode, int nr_exclusive, void *key) { unsigned long flags; spin_lock_irqsave(&q->lock, flags); __wake_up_common(q, mode, nr_exclusive, 0, key); spin_unlock_irqrestore(&q->lock, flags); } EXPORT_SYMBOL(__wake_up); /* * Same as __wake_up but called with the spinlock in wait_queue_head_t held. */ void __wake_up_locked(wait_queue_head_t *q, unsigned int mode, int nr) { __wake_up_common(q, mode, nr, 0, NULL); } EXPORT_SYMBOL_GPL(__wake_up_locked); void __wake_up_locked_key(wait_queue_head_t *q, unsigned int mode, void *key) { __wake_up_common(q, mode, 1, 0, key); } EXPORT_SYMBOL_GPL(__wake_up_locked_key); /** * __wake_up_sync_key - wake up threads blocked on a waitqueue. * @q: the waitqueue * @mode: which threads * @nr_exclusive: how many wake-one or wake-many threads to wake up * @key: opaque value to be passed to wakeup targets * * The sync wakeup differs that the waker knows that it will schedule * away soon, so while the target thread will be woken up, it will not * be migrated to another CPU - ie. the two threads are 'synchronized' * with each other. This can prevent needless bouncing between CPUs. * * On UP it can prevent extra preemption. * * It may be assumed that this function implies a write memory barrier before * changing the task state if and only if any tasks are woken up. */ void __wake_up_sync_key(wait_queue_head_t *q, unsigned int mode, int nr_exclusive, void *key) { unsigned long flags; int wake_flags = WF_SYNC; if (unlikely(!q)) return; if (unlikely(!nr_exclusive)) wake_flags = 0; spin_lock_irqsave(&q->lock, flags); __wake_up_common(q, mode, nr_exclusive, wake_flags, key); spin_unlock_irqrestore(&q->lock, flags); } EXPORT_SYMBOL_GPL(__wake_up_sync_key); /* * __wake_up_sync - see __wake_up_sync_key() */ void __wake_up_sync(wait_queue_head_t *q, unsigned int mode, int nr_exclusive) { __wake_up_sync_key(q, mode, nr_exclusive, NULL); } EXPORT_SYMBOL_GPL(__wake_up_sync); /* For internal use only */ /** * complete: - signals a single thread waiting on this completion * @x: holds the state of this particular completion * * This will wake up a single thread waiting on this completion. Threads will be * awakened in the same order in which they were queued. * * See also complete_all(), wait_for_completion() and related routines. * * It may be assumed that this function implies a write memory barrier before * changing the task state if and only if any tasks are woken up. */ void complete(struct completion *x) { unsigned long flags; spin_lock_irqsave(&x->wait.lock, flags); x->done++; __wake_up_common(&x->wait, TASK_NORMAL, 1, 0, NULL); spin_unlock_irqrestore(&x->wait.lock, flags); } EXPORT_SYMBOL(complete); /** * complete_all: - signals all threads waiting on this completion * @x: holds the state of this particular completion * * This will wake up all threads waiting on this particular completion event. * * It may be assumed that this function implies a write memory barrier before * changing the task state if and only if any tasks are woken up. */ void complete_all(struct completion *x) { unsigned long flags; spin_lock_irqsave(&x->wait.lock, flags); x->done += UINT_MAX/2; __wake_up_common(&x->wait, TASK_NORMAL, 0, 0, NULL); spin_unlock_irqrestore(&x->wait.lock, flags); } EXPORT_SYMBOL(complete_all); static inline long __sched do_wait_for_common(struct completion *x, long timeout, int state, int iowait) { if (!x->done) { DECLARE_WAITQUEUE(wait, current); __add_wait_queue_tail_exclusive(&x->wait, &wait); do { if (signal_pending_state(state, current)) { timeout = -ERESTARTSYS; break; } __set_current_state(state); spin_unlock_irq(&x->wait.lock); if (iowait) timeout = io_schedule_timeout(timeout); else timeout = schedule_timeout(timeout); spin_lock_irq(&x->wait.lock); } while (!x->done && timeout); __remove_wait_queue(&x->wait, &wait); if (!x->done) return timeout; } x->done--; return timeout ?: 1; } static long __sched wait_for_common(struct completion *x, long timeout, int state, int iowait) { might_sleep(); spin_lock_irq(&x->wait.lock); timeout = do_wait_for_common(x, timeout, state, iowait); spin_unlock_irq(&x->wait.lock); return timeout; } /** * wait_for_completion: - waits for completion of a task * @x: holds the state of this particular completion * * This waits to be signaled for completion of a specific task. It is NOT * interruptible and there is no timeout. * * See also similar routines (i.e. wait_for_completion_timeout()) with timeout * and interrupt capability. Also see complete(). */ void __sched wait_for_completion(struct completion *x) { wait_for_common(x, MAX_SCHEDULE_TIMEOUT, TASK_UNINTERRUPTIBLE, 0); } EXPORT_SYMBOL(wait_for_completion); /** * wait_for_completion_io: - waits for completion of a task * @x: holds the state of this particular completion * * This waits for completion of a specific task to be signaled. Treats any * sleeping as waiting for IO for the purposes of process accounting. */ void __sched wait_for_completion_io(struct completion *x) { wait_for_common(x, MAX_SCHEDULE_TIMEOUT, TASK_UNINTERRUPTIBLE, 1); } EXPORT_SYMBOL(wait_for_completion_io); /** * wait_for_completion_timeout: - waits for completion of a task (w/timeout) * @x: holds the state of this particular completion * @timeout: timeout value in jiffies * * This waits for either a completion of a specific task to be signaled or for a * specified timeout to expire. The timeout is in jiffies. It is not * interruptible. * * The return value is 0 if timed out, and positive (at least 1, or number of * jiffies left till timeout) if completed. */ unsigned long __sched wait_for_completion_timeout(struct completion *x, unsigned long timeout) { return wait_for_common(x, timeout, TASK_UNINTERRUPTIBLE, 0); } EXPORT_SYMBOL(wait_for_completion_timeout); /** * wait_for_completion_interruptible: - waits for completion of a task (w/intr) * @x: holds the state of this particular completion * * This waits for completion of a specific task to be signaled. It is * interruptible. * * The return value is -ERESTARTSYS if interrupted, 0 if completed. */ int __sched wait_for_completion_interruptible(struct completion *x) { long t = wait_for_common(x, MAX_SCHEDULE_TIMEOUT, TASK_INTERRUPTIBLE, 0); if (t == -ERESTARTSYS) return t; return 0; } EXPORT_SYMBOL(wait_for_completion_interruptible); /** * wait_for_completion_interruptible_timeout: - waits for completion (w/(to,intr)) * @x: holds the state of this particular completion * @timeout: timeout value in jiffies * * This waits for either a completion of a specific task to be signaled or for a * specified timeout to expire. It is interruptible. The timeout is in jiffies. * * The return value is -ERESTARTSYS if interrupted, 0 if timed out, * positive (at least 1, or number of jiffies left till timeout) if completed. */ long __sched wait_for_completion_interruptible_timeout(struct completion *x, unsigned long timeout) { return wait_for_common(x, timeout, TASK_INTERRUPTIBLE, 0); } EXPORT_SYMBOL(wait_for_completion_interruptible_timeout); /** * wait_for_completion_killable: - waits for completion of a task (killable) * @x: holds the state of this particular completion * * This waits to be signaled for completion of a specific task. It can be * interrupted by a kill signal. * * The return value is -ERESTARTSYS if interrupted, 0 if completed. */ int __sched wait_for_completion_killable(struct completion *x) { long t = wait_for_common(x, MAX_SCHEDULE_TIMEOUT, TASK_KILLABLE, 0); if (t == -ERESTARTSYS) return t; return 0; } EXPORT_SYMBOL(wait_for_completion_killable); /** * wait_for_completion_killable_timeout: - waits for completion of a task (w/(to,killable)) * @x: holds the state of this particular completion * @timeout: timeout value in jiffies * * This waits for either a completion of a specific task to be * signaled or for a specified timeout to expire. It can be * interrupted by a kill signal. The timeout is in jiffies. * * The return value is -ERESTARTSYS if interrupted, 0 if timed out, * positive (at least 1, or number of jiffies left till timeout) if completed. */ long __sched wait_for_completion_killable_timeout(struct completion *x, unsigned long timeout) { return wait_for_common(x, timeout, TASK_KILLABLE, 0); } EXPORT_SYMBOL(wait_for_completion_killable_timeout); /** * try_wait_for_completion - try to decrement a completion without blocking * @x: completion structure * * Returns: 0 if a decrement cannot be done without blocking * 1 if a decrement succeeded. * * If a completion is being used as a counting completion, * attempt to decrement the counter without blocking. This * enables us to avoid waiting if the resource the completion * is protecting is not available. */ bool try_wait_for_completion(struct completion *x) { unsigned long flags; int ret = 1; spin_lock_irqsave(&x->wait.lock, flags); if (!x->done) ret = 0; else x->done--; spin_unlock_irqrestore(&x->wait.lock, flags); return ret; } EXPORT_SYMBOL(try_wait_for_completion); /** * completion_done - Test to see if a completion has any waiters * @x: completion structure * * Returns: 0 if there are waiters (wait_for_completion() in progress) * 1 if there are no waiters. * */ bool completion_done(struct completion *x) { unsigned long flags; int ret = 1; spin_lock_irqsave(&x->wait.lock, flags); if (!x->done) ret = 0; spin_unlock_irqrestore(&x->wait.lock, flags); return ret; } EXPORT_SYMBOL(completion_done); static long __sched sleep_on_common(wait_queue_head_t *q, int state, long timeout) { unsigned long flags; wait_queue_t wait; init_waitqueue_entry(&wait, current); __set_current_state(state); spin_lock_irqsave(&q->lock, flags); __add_wait_queue(q, &wait); spin_unlock(&q->lock); timeout = schedule_timeout(timeout); spin_lock_irq(&q->lock); __remove_wait_queue(q, &wait); spin_unlock_irqrestore(&q->lock, flags); return timeout; } void __sched interruptible_sleep_on(wait_queue_head_t *q) { sleep_on_common(q, TASK_INTERRUPTIBLE, MAX_SCHEDULE_TIMEOUT); } EXPORT_SYMBOL(interruptible_sleep_on); long __sched interruptible_sleep_on_timeout(wait_queue_head_t *q, long timeout) { return sleep_on_common(q, TASK_INTERRUPTIBLE, timeout); } EXPORT_SYMBOL(interruptible_sleep_on_timeout); void __sched sleep_on(wait_queue_head_t *q) { sleep_on_common(q, TASK_UNINTERRUPTIBLE, MAX_SCHEDULE_TIMEOUT); } EXPORT_SYMBOL(sleep_on); long __sched sleep_on_timeout(wait_queue_head_t *q, long timeout) { return sleep_on_common(q, TASK_UNINTERRUPTIBLE, timeout); } EXPORT_SYMBOL(sleep_on_timeout); #ifdef CONFIG_RT_MUTEXES /* * rt_mutex_setprio - set the current priority of a task * @p: task * @prio: prio value (kernel-internal form) * * This function changes the 'effective' priority of a task. It does * not touch ->normal_prio like __setscheduler(). * * Used by the rt_mutex code to implement priority inheritance logic. */ void rt_mutex_setprio(struct task_struct *p, int prio) { int oldprio, on_rq, running; struct rq *rq; const struct sched_class *prev_class; BUG_ON(prio < 0 || prio > MAX_PRIO); rq = __task_rq_lock(p); /* * Idle task boosting is a nono in general. There is one * exception, when PREEMPT_RT and NOHZ is active: * * The idle task calls get_next_timer_interrupt() and holds * the timer wheel base->lock on the CPU and another CPU wants * to access the timer (probably to cancel it). We can safely * ignore the boosting request, as the idle CPU runs this code * with interrupts disabled and will complete the lock * protected section without being interrupted. So there is no * real need to boost. */ if (unlikely(p == rq->idle)) { WARN_ON(p != rq->curr); WARN_ON(p->pi_blocked_on); goto out_unlock; } trace_sched_pi_setprio(p, prio); oldprio = p->prio; prev_class = p->sched_class; on_rq = p->on_rq; running = task_current(rq, p); if (on_rq) dequeue_task(rq, p, 0); if (running) p->sched_class->put_prev_task(rq, p); if (rt_prio(prio)) p->sched_class = &rt_sched_class; else p->sched_class = &fair_sched_class; p->prio = prio; if (running) p->sched_class->set_curr_task(rq); if (on_rq) enqueue_task(rq, p, oldprio < prio ? ENQUEUE_HEAD : 0); check_class_changed(rq, p, prev_class, oldprio); out_unlock: __task_rq_unlock(rq); } #endif void set_user_nice(struct task_struct *p, long nice) { int old_prio, delta, on_rq; unsigned long flags; struct rq *rq; if (TASK_NICE(p) == nice || nice < -20 || nice > 19) return; /* * We have to be careful, if called from sys_setpriority(), * the task might be in the middle of scheduling on another CPU. */ rq = task_rq_lock(p, &flags); /* * The RT priorities are set via sched_setscheduler(), but we still * allow the 'normal' nice value to be set - but as expected * it wont have any effect on scheduling until the task is * SCHED_FIFO/SCHED_RR: */ if (task_has_rt_policy(p)) { p->static_prio = NICE_TO_PRIO(nice); goto out_unlock; } on_rq = p->on_rq; if (on_rq) dequeue_task(rq, p, 0); p->static_prio = NICE_TO_PRIO(nice); set_load_weight(p); old_prio = p->prio; p->prio = effective_prio(p); delta = p->prio - old_prio; if (on_rq) { enqueue_task(rq, p, 0); /* * If the task increased its priority or is running and * lowered its priority, then reschedule its CPU: */ if (delta < 0 || (delta > 0 && task_running(rq, p))) resched_task(rq->curr); } out_unlock: task_rq_unlock(rq, p, &flags); } EXPORT_SYMBOL(set_user_nice); /* * can_nice - check if a task can reduce its nice value * @p: task * @nice: nice value */ int can_nice(const struct task_struct *p, const int nice) { /* convert nice value [19,-20] to rlimit style value [1,40] */ int nice_rlim = 20 - nice; return (nice_rlim <= task_rlimit(p, RLIMIT_NICE) || capable(CAP_SYS_NICE)); } #ifdef __ARCH_WANT_SYS_NICE /* * sys_nice - change the priority of the current process. * @increment: priority increment * * sys_setpriority is a more generic, but much slower function that * does similar things. */ SYSCALL_DEFINE1(nice, int, increment) { long nice, retval; /* * Setpriority might change our priority at the same moment. * We don't have to worry. Conceptually one call occurs first * and we have a single winner. */ if (increment < -40) increment = -40; if (increment > 40) increment = 40; nice = TASK_NICE(current) + increment; if (nice < -20) nice = -20; if (nice > 19) nice = 19; if (increment < 0 && !can_nice(current, nice)) return -EPERM; retval = security_task_setnice(current, nice); if (retval) return retval; set_user_nice(current, nice); return 0; } #endif /** * task_prio - return the priority value of a given task. * @p: the task in question. * * This is the priority value as seen by users in /proc. * RT tasks are offset by -200. Normal tasks are centered * around 0, value goes from -16 to +15. */ int task_prio(const struct task_struct *p) { return p->prio - MAX_RT_PRIO; } /** * task_nice - return the nice value of a given task. * @p: the task in question. */ int task_nice(const struct task_struct *p) { return TASK_NICE(p); } EXPORT_SYMBOL(task_nice); /** * idle_cpu - is a given cpu idle currently? * @cpu: the processor in question. */ int idle_cpu(int cpu) { struct rq *rq = cpu_rq(cpu); if (rq->curr != rq->idle) return 0; if (rq->nr_running) return 0; #ifdef CONFIG_SMP if (!llist_empty(&rq->wake_list)) return 0; #endif return 1; } /** * idle_task - return the idle task for a given cpu. * @cpu: the processor in question. */ struct task_struct *idle_task(int cpu) { return cpu_rq(cpu)->idle; } /** * find_process_by_pid - find a process with a matching PID value. * @pid: the pid in question. */ static struct task_struct *find_process_by_pid(pid_t pid) { return pid ? find_task_by_vpid(pid) : current; } /* Actually do priority change: must hold rq lock. */ static void __setscheduler(struct rq *rq, struct task_struct *p, int policy, int prio) { p->policy = policy; p->rt_priority = prio; p->normal_prio = normal_prio(p); /* we are holding p->pi_lock already */ p->prio = rt_mutex_getprio(p); if (rt_prio(p->prio)) p->sched_class = &rt_sched_class; else p->sched_class = &fair_sched_class; set_load_weight(p); } /* * check the target process has a UID that matches the current process's */ static bool check_same_owner(struct task_struct *p) { const struct cred *cred = current_cred(), *pcred; bool match; rcu_read_lock(); pcred = __task_cred(p); if (cred->user->user_ns == pcred->user->user_ns) match = (cred->euid == pcred->euid || cred->euid == pcred->uid); else match = false; rcu_read_unlock(); return match; } static int __sched_setscheduler(struct task_struct *p, int policy, const struct sched_param *param, bool user) { int retval, oldprio, oldpolicy = -1, on_rq, running; unsigned long flags; const struct sched_class *prev_class; struct rq *rq; int reset_on_fork; /* may grab non-irq protected spin_locks */ BUG_ON(in_interrupt()); recheck: /* double check policy once rq lock held */ if (policy < 0) { reset_on_fork = p->sched_reset_on_fork; policy = oldpolicy = p->policy; } else { reset_on_fork = !!(policy & SCHED_RESET_ON_FORK); policy &= ~SCHED_RESET_ON_FORK; if (policy != SCHED_FIFO && policy != SCHED_RR && policy != SCHED_NORMAL && policy != SCHED_BATCH && policy != SCHED_IDLE) return -EINVAL; } /* * Valid priorities for SCHED_FIFO and SCHED_RR are * 1..MAX_USER_RT_PRIO-1, valid priority for SCHED_NORMAL, * SCHED_BATCH and SCHED_IDLE is 0. */ if (param->sched_priority < 0 || (p->mm && param->sched_priority > MAX_USER_RT_PRIO-1) || (!p->mm && param->sched_priority > MAX_RT_PRIO-1)) return -EINVAL; if (rt_policy(policy) != (param->sched_priority != 0)) return -EINVAL; /* * Allow unprivileged RT tasks to decrease priority: */ if (user && !capable(CAP_SYS_NICE)) { if (rt_policy(policy)) { unsigned long rlim_rtprio = task_rlimit(p, RLIMIT_RTPRIO); /* can't set/change the rt policy */ if (policy != p->policy && !rlim_rtprio) return -EPERM; /* can't increase priority */ if (param->sched_priority > p->rt_priority && param->sched_priority > rlim_rtprio) return -EPERM; } /* * Treat SCHED_IDLE as nice 20. Only allow a switch to * SCHED_NORMAL if the RLIMIT_NICE would normally permit it. */ if (p->policy == SCHED_IDLE && policy != SCHED_IDLE) { if (!can_nice(p, TASK_NICE(p))) return -EPERM; } /* can't change other user's priorities */ if (!check_same_owner(p)) return -EPERM; /* Normal users shall not reset the sched_reset_on_fork flag */ if (p->sched_reset_on_fork && !reset_on_fork) return -EPERM; } if (user) { retval = security_task_setscheduler(p); if (retval) return retval; } /* * make sure no PI-waiters arrive (or leave) while we are * changing the priority of the task: * * To be able to change p->policy safely, the appropriate * runqueue lock must be held. */ rq = task_rq_lock(p, &flags); /* * Changing the policy of the stop threads its a very bad idea */ if (p == rq->stop) { task_rq_unlock(rq, p, &flags); return -EINVAL; } /* * If not changing anything there's no need to proceed further: */ if (unlikely(policy == p->policy && (!rt_policy(policy) || param->sched_priority == p->rt_priority))) { __task_rq_unlock(rq); raw_spin_unlock_irqrestore(&p->pi_lock, flags); return 0; } #ifdef CONFIG_RT_GROUP_SCHED if (user) { /* * Do not allow realtime tasks into groups that have no runtime * assigned. */ if (rt_bandwidth_enabled() && rt_policy(policy) && task_group(p)->rt_bandwidth.rt_runtime == 0 && !task_group_is_autogroup(task_group(p))) { task_rq_unlock(rq, p, &flags); return -EPERM; } } #endif /* recheck policy now with rq lock held */ if (unlikely(oldpolicy != -1 && oldpolicy != p->policy)) { policy = oldpolicy = -1; task_rq_unlock(rq, p, &flags); goto recheck; } on_rq = p->on_rq; running = task_current(rq, p); if (on_rq) dequeue_task(rq, p, 0); if (running) p->sched_class->put_prev_task(rq, p); p->sched_reset_on_fork = reset_on_fork; oldprio = p->prio; prev_class = p->sched_class; __setscheduler(rq, p, policy, param->sched_priority); if (running) p->sched_class->set_curr_task(rq); if (on_rq) enqueue_task(rq, p, 0); check_class_changed(rq, p, prev_class, oldprio); task_rq_unlock(rq, p, &flags); rt_mutex_adjust_pi(p); return 0; } /** * sched_setscheduler - change the scheduling policy and/or RT priority of a thread. * @p: the task in question. * @policy: new policy. * @param: structure containing the new RT priority. * * NOTE that the task may be already dead. */ int sched_setscheduler(struct task_struct *p, int policy, const struct sched_param *param) { return __sched_setscheduler(p, policy, param, true); } EXPORT_SYMBOL_GPL(sched_setscheduler); /** * sched_setscheduler_nocheck - change the scheduling policy and/or RT priority of a thread from kernelspace. * @p: the task in question. * @policy: new policy. * @param: structure containing the new RT priority. * * Just like sched_setscheduler, only don't bother checking if the * current context has permission. For example, this is needed in * stop_machine(): we create temporary high priority worker threads, * but our caller might not have that capability. */ int sched_setscheduler_nocheck(struct task_struct *p, int policy, const struct sched_param *param) { return __sched_setscheduler(p, policy, param, false); } static int do_sched_setscheduler(pid_t pid, int policy, struct sched_param __user *param) { struct sched_param lparam; struct task_struct *p; int retval; if (!param || pid < 0) return -EINVAL; if (copy_from_user(&lparam, param, sizeof(struct sched_param))) return -EFAULT; rcu_read_lock(); retval = -ESRCH; p = find_process_by_pid(pid); if (p != NULL) retval = sched_setscheduler(p, policy, &lparam); rcu_read_unlock(); return retval; } /** * sys_sched_setscheduler - set/change the scheduler policy and RT priority * @pid: the pid in question. * @policy: new policy. * @param: structure containing the new RT priority. */ SYSCALL_DEFINE3(sched_setscheduler, pid_t, pid, int, policy, struct sched_param __user *, param) { /* negative values for policy are not valid */ if (policy < 0) return -EINVAL; return do_sched_setscheduler(pid, policy, param); } /** * sys_sched_setparam - set/change the RT priority of a thread * @pid: the pid in question. * @param: structure containing the new RT priority. */ SYSCALL_DEFINE2(sched_setparam, pid_t, pid, struct sched_param __user *, param) { return do_sched_setscheduler(pid, -1, param); } /** * sys_sched_getscheduler - get the policy (scheduling class) of a thread * @pid: the pid in question. */ SYSCALL_DEFINE1(sched_getscheduler, pid_t, pid) { struct task_struct *p; int retval; if (pid < 0) return -EINVAL; retval = -ESRCH; rcu_read_lock(); p = find_process_by_pid(pid); if (p) { retval = security_task_getscheduler(p); if (!retval) retval = p->policy | (p->sched_reset_on_fork ? SCHED_RESET_ON_FORK : 0); } rcu_read_unlock(); return retval; } /** * sys_sched_getparam - get the RT priority of a thread * @pid: the pid in question. * @param: structure containing the RT priority. */ SYSCALL_DEFINE2(sched_getparam, pid_t, pid, struct sched_param __user *, param) { struct sched_param lp; struct task_struct *p; int retval; if (!param || pid < 0) return -EINVAL; rcu_read_lock(); p = find_process_by_pid(pid); retval = -ESRCH; if (!p) goto out_unlock; retval = security_task_getscheduler(p); if (retval) goto out_unlock; lp.sched_priority = p->rt_priority; rcu_read_unlock(); /* * This one might sleep, we cannot do it with a spinlock held ... */ retval = copy_to_user(param, &lp, sizeof(*param)) ? -EFAULT : 0; return retval; out_unlock: rcu_read_unlock(); return retval; } long sched_setaffinity(pid_t pid, const struct cpumask *in_mask) { cpumask_var_t cpus_allowed, new_mask; struct task_struct *p; int retval; get_online_cpus(); rcu_read_lock(); p = find_process_by_pid(pid); if (!p) { rcu_read_unlock(); put_online_cpus(); return -ESRCH; } /* Prevent p going away */ get_task_struct(p); rcu_read_unlock(); if (!alloc_cpumask_var(&cpus_allowed, GFP_KERNEL)) { retval = -ENOMEM; goto out_put_task; } if (!alloc_cpumask_var(&new_mask, GFP_KERNEL)) { retval = -ENOMEM; goto out_free_cpus_allowed; } retval = -EPERM; if (!check_same_owner(p) && !ns_capable(task_user_ns(p), CAP_SYS_NICE)) goto out_unlock; retval = security_task_setscheduler(p); if (retval) goto out_unlock; cpuset_cpus_allowed(p, cpus_allowed); cpumask_and(new_mask, in_mask, cpus_allowed); again: retval = set_cpus_allowed_ptr(p, new_mask); if (!retval) { cpuset_cpus_allowed(p, cpus_allowed); if (!cpumask_subset(new_mask, cpus_allowed)) { /* * We must have raced with a concurrent cpuset * update. Just reset the cpus_allowed to the * cpuset's cpus_allowed */ cpumask_copy(new_mask, cpus_allowed); goto again; } } out_unlock: free_cpumask_var(new_mask); out_free_cpus_allowed: free_cpumask_var(cpus_allowed); out_put_task: put_task_struct(p); put_online_cpus(); return retval; } static int get_user_cpu_mask(unsigned long __user *user_mask_ptr, unsigned len, struct cpumask *new_mask) { if (len < cpumask_size()) cpumask_clear(new_mask); else if (len > cpumask_size()) len = cpumask_size(); return copy_from_user(new_mask, user_mask_ptr, len) ? -EFAULT : 0; } /** * sys_sched_setaffinity - set the cpu affinity of a process * @pid: pid of the process * @len: length in bytes of the bitmask pointed to by user_mask_ptr * @user_mask_ptr: user-space pointer to the new cpu mask */ SYSCALL_DEFINE3(sched_setaffinity, pid_t, pid, unsigned int, len, unsigned long __user *, user_mask_ptr) { cpumask_var_t new_mask; int retval; if (!alloc_cpumask_var(&new_mask, GFP_KERNEL)) return -ENOMEM; retval = get_user_cpu_mask(user_mask_ptr, len, new_mask); if (retval == 0) retval = sched_setaffinity(pid, new_mask); free_cpumask_var(new_mask); return retval; } long sched_getaffinity(pid_t pid, struct cpumask *mask) { struct task_struct *p; unsigned long flags; int retval; get_online_cpus(); rcu_read_lock(); retval = -ESRCH; p = find_process_by_pid(pid); if (!p) goto out_unlock; retval = security_task_getscheduler(p); if (retval) goto out_unlock; raw_spin_lock_irqsave(&p->pi_lock, flags); cpumask_and(mask, &p->cpus_allowed, cpu_online_mask); raw_spin_unlock_irqrestore(&p->pi_lock, flags); out_unlock: rcu_read_unlock(); put_online_cpus(); return retval; } /** * sys_sched_getaffinity - get the cpu affinity of a process * @pid: pid of the process * @len: length in bytes of the bitmask pointed to by user_mask_ptr * @user_mask_ptr: user-space pointer to hold the current cpu mask */ SYSCALL_DEFINE3(sched_getaffinity, pid_t, pid, unsigned int, len, unsigned long __user *, user_mask_ptr) { int ret; cpumask_var_t mask; if ((len * BITS_PER_BYTE) < nr_cpu_ids) return -EINVAL; if (len & (sizeof(unsigned long)-1)) return -EINVAL; if (!alloc_cpumask_var(&mask, GFP_KERNEL)) return -ENOMEM; ret = sched_getaffinity(pid, mask); if (ret == 0) { size_t retlen = min_t(size_t, len, cpumask_size()); if (copy_to_user(user_mask_ptr, mask, retlen)) ret = -EFAULT; else ret = retlen; } free_cpumask_var(mask); return ret; } /** * sys_sched_yield - yield the current processor to other threads. * * This function yields the current CPU to other tasks. If there are no * other threads running on this CPU then this function will return. */ SYSCALL_DEFINE0(sched_yield) { struct rq *rq = this_rq_lock(); schedstat_inc(rq, yld_count); current->sched_class->yield_task(rq); /* * Since we are going to call schedule() anyway, there's * no need to preempt or enable interrupts: */ __release(rq->lock); spin_release(&rq->lock.dep_map, 1, _THIS_IP_); do_raw_spin_unlock(&rq->lock); sched_preempt_enable_no_resched(); schedule(); return 0; } static inline int should_resched(void) { return need_resched() && !(preempt_count() & PREEMPT_ACTIVE); } static void __cond_resched(void) { add_preempt_count(PREEMPT_ACTIVE); __schedule(); sub_preempt_count(PREEMPT_ACTIVE); } int __sched _cond_resched(void) { if (should_resched()) { __cond_resched(); return 1; } return 0; } EXPORT_SYMBOL(_cond_resched); /* * __cond_resched_lock() - if a reschedule is pending, drop the given lock, * call schedule, and on return reacquire the lock. * * This works OK both with and without CONFIG_PREEMPT. We do strange low-level * operations here to prevent schedule() from being called twice (once via * spin_unlock(), once by hand). */ int __cond_resched_lock(spinlock_t *lock) { int resched = should_resched(); int ret = 0; lockdep_assert_held(lock); if (spin_needbreak(lock) || resched) { spin_unlock(lock); if (resched) __cond_resched(); else cpu_relax(); ret = 1; spin_lock(lock); } return ret; } EXPORT_SYMBOL(__cond_resched_lock); int __sched __cond_resched_softirq(void) { BUG_ON(!in_softirq()); if (should_resched()) { local_bh_enable(); __cond_resched(); local_bh_disable(); return 1; } return 0; } EXPORT_SYMBOL(__cond_resched_softirq); /** * yield - yield the current processor to other threads. * * Do not ever use this function, there's a 99% chance you're doing it wrong. * * The scheduler is at all times free to pick the calling task as the most * eligible task to run, if removing the yield() call from your code breaks * it, its already broken. * * Typical broken usage is: * * while (!event) * yield(); * * where one assumes that yield() will let 'the other' process run that will * make event true. If the current task is a SCHED_FIFO task that will never * happen. Never use yield() as a progress guarantee!! * * If you want to use yield() to wait for something, use wait_event(). * If you want to use yield() to be 'nice' for others, use cond_resched(). * If you still want to use yield(), do not! */ void __sched yield(void) { set_current_state(TASK_RUNNING); sys_sched_yield(); } EXPORT_SYMBOL(yield); /** * yield_to - yield the current processor to another thread in * your thread group, or accelerate that thread toward the * processor it's on. * @p: target task * @preempt: whether task preemption is allowed or not * * It's the caller's job to ensure that the target task struct * can't go away on us before we can do any checks. * * Returns true if we indeed boosted the target task. */ bool __sched yield_to(struct task_struct *p, bool preempt) { struct task_struct *curr = current; struct rq *rq, *p_rq; unsigned long flags; bool yielded = 0; local_irq_save(flags); rq = this_rq(); again: p_rq = task_rq(p); double_rq_lock(rq, p_rq); while (task_rq(p) != p_rq) { double_rq_unlock(rq, p_rq); goto again; } if (!curr->sched_class->yield_to_task) goto out; if (curr->sched_class != p->sched_class) goto out; if (task_running(p_rq, p) || p->state) goto out; yielded = curr->sched_class->yield_to_task(rq, p, preempt); if (yielded) { schedstat_inc(rq, yld_count); /* * Make p's CPU reschedule; pick_next_entity takes care of * fairness. */ if (preempt && rq != p_rq) resched_task(p_rq->curr); } else { /* * We might have set it in task_yield_fair(), but are * not going to schedule(), so don't want to skip * the next update. */ rq->skip_clock_update = 0; } out: double_rq_unlock(rq, p_rq); local_irq_restore(flags); if (yielded) schedule(); return yielded; } EXPORT_SYMBOL_GPL(yield_to); /* * This task is about to go to sleep on IO. Increment rq->nr_iowait so * that process accounting knows that this is a task in IO wait state. */ void __sched io_schedule(void) { struct rq *rq = raw_rq(); delayacct_blkio_start(); atomic_inc(&rq->nr_iowait); blk_flush_plug(current); current->in_iowait = 1; schedule(); current->in_iowait = 0; atomic_dec(&rq->nr_iowait); delayacct_blkio_end(); } EXPORT_SYMBOL(io_schedule); long __sched io_schedule_timeout(long timeout) { struct rq *rq = raw_rq(); long ret; delayacct_blkio_start(); atomic_inc(&rq->nr_iowait); blk_flush_plug(current); current->in_iowait = 1; ret = schedule_timeout(timeout); current->in_iowait = 0; atomic_dec(&rq->nr_iowait); delayacct_blkio_end(); return ret; } EXPORT_SYMBOL(io_schedule_timeout); /** * sys_sched_get_priority_max - return maximum RT priority. * @policy: scheduling class. * * this syscall returns the maximum rt_priority that can be used * by a given scheduling class. */ SYSCALL_DEFINE1(sched_get_priority_max, int, policy) { int ret = -EINVAL; switch (policy) { case SCHED_FIFO: case SCHED_RR: ret = MAX_USER_RT_PRIO-1; break; case SCHED_NORMAL: case SCHED_BATCH: case SCHED_IDLE: ret = 0; break; } return ret; } /** * sys_sched_get_priority_min - return minimum RT priority. * @policy: scheduling class. * * this syscall returns the minimum rt_priority that can be used * by a given scheduling class. */ SYSCALL_DEFINE1(sched_get_priority_min, int, policy) { int ret = -EINVAL; switch (policy) { case SCHED_FIFO: case SCHED_RR: ret = 1; break; case SCHED_NORMAL: case SCHED_BATCH: case SCHED_IDLE: ret = 0; } return ret; } /** * sys_sched_rr_get_interval - return the default timeslice of a process. * @pid: pid of the process. * @interval: userspace pointer to the timeslice value. * * this syscall writes the default timeslice value of a given process * into the user-space timespec buffer. A value of '0' means infinity. */ SYSCALL_DEFINE2(sched_rr_get_interval, pid_t, pid, struct timespec __user *, interval) { struct task_struct *p; unsigned int time_slice; unsigned long flags; struct rq *rq; int retval; struct timespec t; if (pid < 0) return -EINVAL; retval = -ESRCH; rcu_read_lock(); p = find_process_by_pid(pid); if (!p) goto out_unlock; retval = security_task_getscheduler(p); if (retval) goto out_unlock; rq = task_rq_lock(p, &flags); time_slice = p->sched_class->get_rr_interval(rq, p); task_rq_unlock(rq, p, &flags); rcu_read_unlock(); jiffies_to_timespec(time_slice, &t); retval = copy_to_user(interval, &t, sizeof(t)) ? -EFAULT : 0; return retval; out_unlock: rcu_read_unlock(); return retval; } static const char stat_nam[] = TASK_STATE_TO_CHAR_STR; void sched_show_task(struct task_struct *p) { unsigned long free = 0; unsigned state; state = p->state ? __ffs(p->state) + 1 : 0; printk(KERN_INFO "%-15.15s %c", p->comm, state < sizeof(stat_nam) - 1 ? stat_nam[state] : '?'); #if BITS_PER_LONG == 32 if (state == TASK_RUNNING) printk(KERN_CONT " running "); else printk(KERN_CONT " %08lx ", thread_saved_pc(p)); #else if (state == TASK_RUNNING) printk(KERN_CONT " running task "); else printk(KERN_CONT " %016lx ", thread_saved_pc(p)); #endif #ifdef CONFIG_DEBUG_STACK_USAGE free = stack_not_used(p); #endif printk(KERN_CONT "%5lu %5d %6d 0x%08lx\n", free, task_pid_nr(p), task_pid_nr(rcu_dereference(p->real_parent)), (unsigned long)task_thread_info(p)->flags); show_stack(p, NULL); } void show_state_filter(unsigned long state_filter) { struct task_struct *g, *p; #if BITS_PER_LONG == 32 printk(KERN_INFO " task PC stack pid father\n"); #else printk(KERN_INFO " task PC stack pid father\n"); #endif rcu_read_lock(); do_each_thread(g, p) { /* * reset the NMI-timeout, listing all files on a slow * console might take a lot of time: */ touch_nmi_watchdog(); if (!state_filter || (p->state & state_filter)) sched_show_task(p); } while_each_thread(g, p); touch_all_softlockup_watchdogs(); #ifdef CONFIG_SYSRQ_SCHED_DEBUG sysrq_sched_debug_show(); #endif rcu_read_unlock(); /* * Only show locks if all tasks are dumped: */ if (!state_filter) debug_show_all_locks(); } void __cpuinit init_idle_bootup_task(struct task_struct *idle) { idle->sched_class = &idle_sched_class; } /** * init_idle - set up an idle thread for a given CPU * @idle: task in question * @cpu: cpu the idle task belongs to * * NOTE: this function does not set the idle thread's NEED_RESCHED * flag, to make booting more robust. */ void __cpuinit init_idle(struct task_struct *idle, int cpu) { struct rq *rq = cpu_rq(cpu); unsigned long flags; raw_spin_lock_irqsave(&rq->lock, flags); __sched_fork(idle); idle->state = TASK_RUNNING; idle->se.exec_start = sched_clock(); do_set_cpus_allowed(idle, cpumask_of(cpu)); /* * We're having a chicken and egg problem, even though we are * holding rq->lock, the cpu isn't yet set to this cpu so the * lockdep check in task_group() will fail. * * Similar case to sched_fork(). / Alternatively we could * use task_rq_lock() here and obtain the other rq->lock. * * Silence PROVE_RCU */ rcu_read_lock(); __set_task_cpu(idle, cpu); rcu_read_unlock(); rq->curr = rq->idle = idle; #if defined(CONFIG_SMP) idle->on_cpu = 1; #endif raw_spin_unlock_irqrestore(&rq->lock, flags); /* Set the preempt count _outside_ the spinlocks! */ task_thread_info(idle)->preempt_count = 0; /* * The idle tasks have their own, simple scheduling class: */ idle->sched_class = &idle_sched_class; ftrace_graph_init_idle_task(idle, cpu); #if defined(CONFIG_SMP) sprintf(idle->comm, "%s/%d", INIT_TASK_COMM, cpu); #endif } #ifdef CONFIG_SMP void do_set_cpus_allowed(struct task_struct *p, const struct cpumask *new_mask) { if (p->sched_class && p->sched_class->set_cpus_allowed) p->sched_class->set_cpus_allowed(p, new_mask); cpumask_copy(&p->cpus_allowed, new_mask); p->rt.nr_cpus_allowed = cpumask_weight(new_mask); } /* * This is how migration works: * * 1) we invoke migration_cpu_stop() on the target CPU using * stop_one_cpu(). * 2) stopper starts to run (implicitly forcing the migrated thread * off the CPU) * 3) it checks whether the migrated task is still in the wrong runqueue. * 4) if it's in the wrong runqueue then the migration thread removes * it and puts it into the right queue. * 5) stopper completes and stop_one_cpu() returns and the migration * is done. */ /* * Change a given task's CPU affinity. Migrate the thread to a * proper CPU and schedule it away if the CPU it's executing on * is removed from the allowed bitmask. * * NOTE: the caller must have a valid reference to the task, the * task must not exit() & deallocate itself prematurely. The * call is not atomic; no spinlocks may be held. */ int set_cpus_allowed_ptr(struct task_struct *p, const struct cpumask *new_mask) { unsigned long flags; struct rq *rq; unsigned int dest_cpu; int ret = 0; rq = task_rq_lock(p, &flags); if (cpumask_equal(&p->cpus_allowed, new_mask)) goto out; if (!cpumask_intersects(new_mask, cpu_active_mask)) { ret = -EINVAL; goto out; } if (unlikely((p->flags & PF_THREAD_BOUND) && p != current)) { ret = -EINVAL; goto out; } do_set_cpus_allowed(p, new_mask); /* Can the task run on the task's current CPU? If so, we're done */ if (cpumask_test_cpu(task_cpu(p), new_mask)) goto out; dest_cpu = cpumask_any_and(cpu_active_mask, new_mask); if (p->on_rq) { struct migration_arg arg = { p, dest_cpu }; /* Need help from migration thread: drop lock and wait. */ task_rq_unlock(rq, p, &flags); stop_one_cpu(cpu_of(rq), migration_cpu_stop, &arg); tlb_migrate_finish(p->mm); return 0; } out: task_rq_unlock(rq, p, &flags); return ret; } EXPORT_SYMBOL_GPL(set_cpus_allowed_ptr); /* * Move (not current) task off this cpu, onto dest cpu. We're doing * this because either it can't run here any more (set_cpus_allowed() * away from this CPU, or CPU going down), or because we're * attempting to rebalance this task on exec (sched_exec). * * So we race with normal scheduler movements, but that's OK, as long * as the task is no longer on this CPU. * * Returns non-zero if task was successfully migrated. */ static int __migrate_task(struct task_struct *p, int src_cpu, int dest_cpu) { struct rq *rq_dest, *rq_src; bool moved = false; int ret = 0; if (unlikely(!cpu_active(dest_cpu))) return ret; rq_src = cpu_rq(src_cpu); rq_dest = cpu_rq(dest_cpu); raw_spin_lock(&p->pi_lock); double_rq_lock(rq_src, rq_dest); /* Already moved. */ if (task_cpu(p) != src_cpu) goto done; /* Affinity changed (again). */ if (!cpumask_test_cpu(dest_cpu, tsk_cpus_allowed(p))) goto fail; /* * If we're not on a rq, the next wake-up will ensure we're * placed properly. */ if (p->on_rq) { dequeue_task(rq_src, p, 0); set_task_cpu(p, dest_cpu); enqueue_task(rq_dest, p, 0); check_preempt_curr(rq_dest, p, 0); moved = true; } done: ret = 1; fail: double_rq_unlock(rq_src, rq_dest); raw_spin_unlock(&p->pi_lock); if (moved && task_notify_on_migrate(p)) atomic_notifier_call_chain(&migration_notifier_head, dest_cpu, (void *)src_cpu); return ret; } /* * migration_cpu_stop - this will be executed by a highprio stopper thread * and performs thread migration by bumping thread off CPU then * 'pushing' onto another runqueue. */ static int migration_cpu_stop(void *data) { struct migration_arg *arg = data; /* * The original target cpu might have gone down and we might * be on another cpu but it doesn't matter. */ local_irq_disable(); __migrate_task(arg->task, raw_smp_processor_id(), arg->dest_cpu); local_irq_enable(); return 0; } #ifdef CONFIG_HOTPLUG_CPU /* * Ensures that the idle task is using init_mm right before its cpu goes * offline. */ void idle_task_exit(void) { struct mm_struct *mm = current->active_mm; BUG_ON(cpu_online(smp_processor_id())); if (mm != &init_mm) switch_mm(mm, &init_mm, current); mmdrop(mm); } /* * While a dead CPU has no uninterruptible tasks queued at this point, * it might still have a nonzero ->nr_uninterruptible counter, because * for performance reasons the counter is not stricly tracking tasks to * their home CPUs. So we just add the counter to another CPU's counter, * to keep the global sum constant after CPU-down: */ static void migrate_nr_uninterruptible(struct rq *rq_src) { struct rq *rq_dest = cpu_rq(cpumask_any(cpu_active_mask)); rq_dest->nr_uninterruptible += rq_src->nr_uninterruptible; rq_src->nr_uninterruptible = 0; } /* * remove the tasks which were accounted by rq from calc_load_tasks. */ static void calc_global_load_remove(struct rq *rq) { atomic_long_sub(rq->calc_load_active, &calc_load_tasks); rq->calc_load_active = 0; } /* * Migrate all tasks from the rq, sleeping tasks will be migrated by * try_to_wake_up()->select_task_rq(). * * Called with rq->lock held even though we'er in stop_machine() and * there's no concurrency possible, we hold the required locks anyway * because of lock validation efforts. */ static void migrate_tasks(unsigned int dead_cpu) { struct rq *rq = cpu_rq(dead_cpu); struct task_struct *next, *stop = rq->stop; int dest_cpu; /* * Fudge the rq selection such that the below task selection loop * doesn't get stuck on the currently eligible stop task. * * We're currently inside stop_machine() and the rq is either stuck * in the stop_machine_cpu_stop() loop, or we're executing this code, * either way we should never end up calling schedule() until we're * done here. */ rq->stop = NULL; for ( ; ; ) { /* * There's this thread running, bail when that's the only * remaining thread. */ if (rq->nr_running == 1) break; next = pick_next_task(rq); BUG_ON(!next); next->sched_class->put_prev_task(rq, next); /* Find suitable destination for @next, with force if needed. */ dest_cpu = select_fallback_rq(dead_cpu, next); raw_spin_unlock(&rq->lock); __migrate_task(next, dead_cpu, dest_cpu); raw_spin_lock(&rq->lock); } rq->stop = stop; } #endif /* CONFIG_HOTPLUG_CPU */ #if defined(CONFIG_SCHED_DEBUG) && defined(CONFIG_SYSCTL) static struct ctl_table sd_ctl_dir[] = { { .procname = "sched_domain", .mode = 0555, }, {} }; static struct ctl_table sd_ctl_root[] = { { .procname = "kernel", .mode = 0555, .child = sd_ctl_dir, }, {} }; static struct ctl_table *sd_alloc_ctl_entry(int n) { struct ctl_table *entry = kcalloc(n, sizeof(struct ctl_table), GFP_KERNEL); return entry; } static void sd_free_ctl_entry(struct ctl_table **tablep) { struct ctl_table *entry; /* * In the intermediate directories, both the child directory and * procname are dynamically allocated and could fail but the mode * will always be set. In the lowest directory the names are * static strings and all have proc handlers. */ for (entry = *tablep; entry->mode; entry++) { if (entry->child) sd_free_ctl_entry(&entry->child); if (entry->proc_handler == NULL) kfree(entry->procname); } kfree(*tablep); *tablep = NULL; } static int min_load_idx = 0; static int max_load_idx = CPU_LOAD_IDX_MAX-1; static void set_table_entry(struct ctl_table *entry, const char *procname, void *data, int maxlen, umode_t mode, proc_handler *proc_handler, bool load_idx) { entry->procname = procname; entry->data = data; entry->maxlen = maxlen; entry->mode = mode; entry->proc_handler = proc_handler; if (load_idx) { entry->extra1 = &min_load_idx; entry->extra2 = &max_load_idx; } } static struct ctl_table * sd_alloc_ctl_domain_table(struct sched_domain *sd) { struct ctl_table *table = sd_alloc_ctl_entry(13); if (table == NULL) return NULL; set_table_entry(&table[0], "min_interval", &sd->min_interval, sizeof(long), 0644, proc_doulongvec_minmax, false); set_table_entry(&table[1], "max_interval", &sd->max_interval, sizeof(long), 0644, proc_doulongvec_minmax, false); set_table_entry(&table[2], "busy_idx", &sd->busy_idx, sizeof(int), 0644, proc_dointvec_minmax, true); set_table_entry(&table[3], "idle_idx", &sd->idle_idx, sizeof(int), 0644, proc_dointvec_minmax, true); set_table_entry(&table[4], "newidle_idx", &sd->newidle_idx, sizeof(int), 0644, proc_dointvec_minmax, true); set_table_entry(&table[5], "wake_idx", &sd->wake_idx, sizeof(int), 0644, proc_dointvec_minmax, true); set_table_entry(&table[6], "forkexec_idx", &sd->forkexec_idx, sizeof(int), 0644, proc_dointvec_minmax, true); set_table_entry(&table[7], "busy_factor", &sd->busy_factor, sizeof(int), 0644, proc_dointvec_minmax, false); set_table_entry(&table[8], "imbalance_pct", &sd->imbalance_pct, sizeof(int), 0644, proc_dointvec_minmax, false); set_table_entry(&table[9], "cache_nice_tries", &sd->cache_nice_tries, sizeof(int), 0644, proc_dointvec_minmax, false); set_table_entry(&table[10], "flags", &sd->flags, sizeof(int), 0644, proc_dointvec_minmax, false); set_table_entry(&table[11], "name", sd->name, CORENAME_MAX_SIZE, 0444, proc_dostring, false); /* &table[12] is terminator */ return table; } static ctl_table *sd_alloc_ctl_cpu_table(int cpu) { struct ctl_table *entry, *table; struct sched_domain *sd; int domain_num = 0, i; char buf[32]; for_each_domain(cpu, sd) domain_num++; entry = table = sd_alloc_ctl_entry(domain_num + 1); if (table == NULL) return NULL; i = 0; for_each_domain(cpu, sd) { snprintf(buf, 32, "domain%d", i); entry->procname = kstrdup(buf, GFP_KERNEL); entry->mode = 0555; entry->child = sd_alloc_ctl_domain_table(sd); entry++; i++; } return table; } static struct ctl_table_header *sd_sysctl_header; static void register_sched_domain_sysctl(void) { int i, cpu_num = num_possible_cpus(); struct ctl_table *entry = sd_alloc_ctl_entry(cpu_num + 1); char buf[32]; WARN_ON(sd_ctl_dir[0].child); sd_ctl_dir[0].child = entry; if (entry == NULL) return; for_each_possible_cpu(i) { snprintf(buf, 32, "cpu%d", i); entry->procname = kstrdup(buf, GFP_KERNEL); entry->mode = 0555; entry->child = sd_alloc_ctl_cpu_table(i); entry++; } WARN_ON(sd_sysctl_header); sd_sysctl_header = register_sysctl_table(sd_ctl_root); } /* may be called multiple times per register */ static void unregister_sched_domain_sysctl(void) { if (sd_sysctl_header) unregister_sysctl_table(sd_sysctl_header); sd_sysctl_header = NULL; if (sd_ctl_dir[0].child) sd_free_ctl_entry(&sd_ctl_dir[0].child); } #else static void register_sched_domain_sysctl(void) { } static void unregister_sched_domain_sysctl(void) { } #endif static void set_rq_online(struct rq *rq) { if (!rq->online) { const struct sched_class *class; cpumask_set_cpu(rq->cpu, rq->rd->online); rq->online = 1; for_each_class(class) { if (class->rq_online) class->rq_online(rq); } } } static void set_rq_offline(struct rq *rq) { if (rq->online) { const struct sched_class *class; for_each_class(class) { if (class->rq_offline) class->rq_offline(rq); } cpumask_clear_cpu(rq->cpu, rq->rd->online); rq->online = 0; } } /* * migration_call - callback that gets triggered when a CPU is added. * Here we can start up the necessary migration thread for the new CPU. */ static int __cpuinit migration_call(struct notifier_block *nfb, unsigned long action, void *hcpu) { int cpu = (long)hcpu; unsigned long flags; struct rq *rq = cpu_rq(cpu); switch (action & ~CPU_TASKS_FROZEN) { case CPU_UP_PREPARE: rq->calc_load_update = calc_load_update; break; case CPU_ONLINE: /* Update our root-domain */ raw_spin_lock_irqsave(&rq->lock, flags); if (rq->rd) { BUG_ON(!cpumask_test_cpu(cpu, rq->rd->span)); set_rq_online(rq); } raw_spin_unlock_irqrestore(&rq->lock, flags); break; #ifdef CONFIG_HOTPLUG_CPU case CPU_DYING: sched_ttwu_pending(); /* Update our root-domain */ raw_spin_lock_irqsave(&rq->lock, flags); if (rq->rd) { BUG_ON(!cpumask_test_cpu(cpu, rq->rd->span)); set_rq_offline(rq); } migrate_tasks(cpu); BUG_ON(rq->nr_running != 1); /* the migration thread */ raw_spin_unlock_irqrestore(&rq->lock, flags); migrate_nr_uninterruptible(rq); calc_global_load_remove(rq); break; #endif } update_max_interval(); return NOTIFY_OK; } /* * Register at high priority so that task migration (migrate_all_tasks) * happens before everything else. This has to be lower priority than * the notifier in the perf_event subsystem, though. */ static struct notifier_block __cpuinitdata migration_notifier = { .notifier_call = migration_call, .priority = CPU_PRI_MIGRATION, }; static int __cpuinit sched_cpu_active(struct notifier_block *nfb, unsigned long action, void *hcpu) { switch (action & ~CPU_TASKS_FROZEN) { case CPU_DOWN_FAILED: set_cpu_active((long)hcpu, true); return NOTIFY_OK; default: return NOTIFY_DONE; } } static int __cpuinit sched_cpu_inactive(struct notifier_block *nfb, unsigned long action, void *hcpu) { switch (action & ~CPU_TASKS_FROZEN) { case CPU_DOWN_PREPARE: set_cpu_active((long)hcpu, false); return NOTIFY_OK; default: return NOTIFY_DONE; } } static int __init migration_init(void) { void *cpu = (void *)(long)smp_processor_id(); int err; /* Initialize migration for the boot CPU */ err = migration_call(&migration_notifier, CPU_UP_PREPARE, cpu); BUG_ON(err == NOTIFY_BAD); migration_call(&migration_notifier, CPU_ONLINE, cpu); register_cpu_notifier(&migration_notifier); /* Register cpu active notifiers */ cpu_notifier(sched_cpu_active, CPU_PRI_SCHED_ACTIVE); cpu_notifier(sched_cpu_inactive, CPU_PRI_SCHED_INACTIVE); return 0; } early_initcall(migration_init); #endif #ifdef CONFIG_SMP static cpumask_var_t sched_domains_tmpmask; /* sched_domains_mutex */ #ifdef CONFIG_SCHED_DEBUG static __read_mostly int sched_domain_debug_enabled; static int __init sched_domain_debug_setup(char *str) { sched_domain_debug_enabled = 1; return 0; } early_param("sched_debug", sched_domain_debug_setup); static int sched_domain_debug_one(struct sched_domain *sd, int cpu, int level, struct cpumask *groupmask) { struct sched_group *group = sd->groups; char str[256]; cpulist_scnprintf(str, sizeof(str), sched_domain_span(sd)); cpumask_clear(groupmask); printk(KERN_DEBUG "%*s domain %d: ", level, "", level); if (!(sd->flags & SD_LOAD_BALANCE)) { printk("does not load-balance\n"); if (sd->parent) printk(KERN_ERR "ERROR: !SD_LOAD_BALANCE domain" " has parent"); return -1; } printk(KERN_CONT "span %s level %s\n", str, sd->name); if (!cpumask_test_cpu(cpu, sched_domain_span(sd))) { printk(KERN_ERR "ERROR: domain->span does not contain " "CPU%d\n", cpu); } if (!cpumask_test_cpu(cpu, sched_group_cpus(group))) { printk(KERN_ERR "ERROR: domain->groups does not contain" " CPU%d\n", cpu); } printk(KERN_DEBUG "%*s groups:", level + 1, ""); do { if (!group) { printk("\n"); printk(KERN_ERR "ERROR: group is NULL\n"); break; } if (!group->sgp->power) { printk(KERN_CONT "\n"); printk(KERN_ERR "ERROR: domain->cpu_power not " "set\n"); break; } if (!cpumask_weight(sched_group_cpus(group))) { printk(KERN_CONT "\n"); printk(KERN_ERR "ERROR: empty group\n"); break; } if (cpumask_intersects(groupmask, sched_group_cpus(group))) { printk(KERN_CONT "\n"); printk(KERN_ERR "ERROR: repeated CPUs\n"); break; } cpumask_or(groupmask, groupmask, sched_group_cpus(group)); cpulist_scnprintf(str, sizeof(str), sched_group_cpus(group)); printk(KERN_CONT " %s", str); if (group->sgp->power != SCHED_POWER_SCALE) { printk(KERN_CONT " (cpu_power = %d)", group->sgp->power); } group = group->next; } while (group != sd->groups); printk(KERN_CONT "\n"); if (!cpumask_equal(sched_domain_span(sd), groupmask)) printk(KERN_ERR "ERROR: groups don't span domain->span\n"); if (sd->parent && !cpumask_subset(groupmask, sched_domain_span(sd->parent))) printk(KERN_ERR "ERROR: parent span is not a superset " "of domain->span\n"); return 0; } static void sched_domain_debug(struct sched_domain *sd, int cpu) { int level = 0; if (!sched_domain_debug_enabled) return; if (!sd) { printk(KERN_DEBUG "CPU%d attaching NULL sched-domain.\n", cpu); return; } printk(KERN_DEBUG "CPU%d attaching sched-domain:\n", cpu); for (;;) { if (sched_domain_debug_one(sd, cpu, level, sched_domains_tmpmask)) break; level++; sd = sd->parent; if (!sd) break; } } #else /* !CONFIG_SCHED_DEBUG */ # define sched_domain_debug(sd, cpu) do { } while (0) #endif /* CONFIG_SCHED_DEBUG */ static int sd_degenerate(struct sched_domain *sd) { if (cpumask_weight(sched_domain_span(sd)) == 1) return 1; /* Following flags need at least 2 groups */ if (sd->flags & (SD_LOAD_BALANCE | SD_BALANCE_NEWIDLE | SD_BALANCE_FORK | SD_BALANCE_EXEC | SD_SHARE_CPUPOWER | SD_SHARE_PKG_RESOURCES)) { if (sd->groups != sd->groups->next) return 0; } /* Following flags don't use groups */ if (sd->flags & (SD_WAKE_AFFINE)) return 0; return 1; } static int sd_parent_degenerate(struct sched_domain *sd, struct sched_domain *parent) { unsigned long cflags = sd->flags, pflags = parent->flags; if (sd_degenerate(parent)) return 1; if (!cpumask_equal(sched_domain_span(sd), sched_domain_span(parent))) return 0; /* Flags needing groups don't count if only 1 group in parent */ if (parent->groups == parent->groups->next) { pflags &= ~(SD_LOAD_BALANCE | SD_BALANCE_NEWIDLE | SD_BALANCE_FORK | SD_BALANCE_EXEC | SD_SHARE_CPUPOWER | SD_SHARE_PKG_RESOURCES); if (nr_node_ids == 1) pflags &= ~SD_SERIALIZE; } if (~cflags & pflags) return 0; return 1; } static void free_rootdomain(struct rcu_head *rcu) { struct root_domain *rd = container_of(rcu, struct root_domain, rcu); cpupri_cleanup(&rd->cpupri); free_cpumask_var(rd->rto_mask); free_cpumask_var(rd->online); free_cpumask_var(rd->span); kfree(rd); } static void rq_attach_root(struct rq *rq, struct root_domain *rd) { struct root_domain *old_rd = NULL; unsigned long flags; raw_spin_lock_irqsave(&rq->lock, flags); if (rq->rd) { old_rd = rq->rd; if (cpumask_test_cpu(rq->cpu, old_rd->online)) set_rq_offline(rq); cpumask_clear_cpu(rq->cpu, old_rd->span); /* * If we dont want to free the old_rt yet then * set old_rd to NULL to skip the freeing later * in this function: */ if (!atomic_dec_and_test(&old_rd->refcount)) old_rd = NULL; } atomic_inc(&rd->refcount); rq->rd = rd; cpumask_set_cpu(rq->cpu, rd->span); if (cpumask_test_cpu(rq->cpu, cpu_active_mask)) set_rq_online(rq); raw_spin_unlock_irqrestore(&rq->lock, flags); if (old_rd) call_rcu_sched(&old_rd->rcu, free_rootdomain); } static int init_rootdomain(struct root_domain *rd) { memset(rd, 0, sizeof(*rd)); if (!alloc_cpumask_var(&rd->span, GFP_KERNEL)) goto out; if (!alloc_cpumask_var(&rd->online, GFP_KERNEL)) goto free_span; if (!alloc_cpumask_var(&rd->rto_mask, GFP_KERNEL)) goto free_online; if (cpupri_init(&rd->cpupri) != 0) goto free_rto_mask; return 0; free_rto_mask: free_cpumask_var(rd->rto_mask); free_online: free_cpumask_var(rd->online); free_span: free_cpumask_var(rd->span); out: return -ENOMEM; } /* * By default the system creates a single root-domain with all cpus as * members (mimicking the global state we have today). */ struct root_domain def_root_domain; static void init_defrootdomain(void) { init_rootdomain(&def_root_domain); atomic_set(&def_root_domain.refcount, 1); } static struct root_domain *alloc_rootdomain(void) { struct root_domain *rd; rd = kmalloc(sizeof(*rd), GFP_KERNEL); if (!rd) return NULL; if (init_rootdomain(rd) != 0) { kfree(rd); return NULL; } return rd; } static void free_sched_groups(struct sched_group *sg, int free_sgp) { struct sched_group *tmp, *first; if (!sg) return; first = sg; do { tmp = sg->next; if (free_sgp && atomic_dec_and_test(&sg->sgp->ref)) kfree(sg->sgp); kfree(sg); sg = tmp; } while (sg != first); } static void free_sched_domain(struct rcu_head *rcu) { struct sched_domain *sd = container_of(rcu, struct sched_domain, rcu); /* * If its an overlapping domain it has private groups, iterate and * nuke them all. */ if (sd->flags & SD_OVERLAP) { free_sched_groups(sd->groups, 1); } else if (atomic_dec_and_test(&sd->groups->ref)) { kfree(sd->groups->sgp); kfree(sd->groups); } kfree(sd); } static void destroy_sched_domain(struct sched_domain *sd, int cpu) { call_rcu(&sd->rcu, free_sched_domain); } static void destroy_sched_domains(struct sched_domain *sd, int cpu) { for (; sd; sd = sd->parent) destroy_sched_domain(sd, cpu); } /* * Keep a special pointer to the highest sched_domain that has * SD_SHARE_PKG_RESOURCE set (Last Level Cache Domain) for this * allows us to avoid some pointer chasing select_idle_sibling(). * * Also keep a unique ID per domain (we use the first cpu number in * the cpumask of the domain), this allows us to quickly tell if * two cpus are in the same cache domain, see cpus_share_cache(). */ DEFINE_PER_CPU(struct sched_domain *, sd_llc); DEFINE_PER_CPU(int, sd_llc_id); static void update_top_cache_domain(int cpu) { struct sched_domain *sd; int id = cpu; sd = highest_flag_domain(cpu, SD_SHARE_PKG_RESOURCES); if (sd) id = cpumask_first(sched_domain_span(sd)); rcu_assign_pointer(per_cpu(sd_llc, cpu), sd); per_cpu(sd_llc_id, cpu) = id; } /* * Attach the domain 'sd' to 'cpu' as its base domain. Callers must * hold the hotplug lock. */ static void cpu_attach_domain(struct sched_domain *sd, struct root_domain *rd, int cpu) { struct rq *rq = cpu_rq(cpu); struct sched_domain *tmp; unsigned long next_balance = rq->next_balance; /* Remove the sched domains which do not contribute to scheduling. */ for (tmp = sd; tmp; ) { struct sched_domain *parent = tmp->parent; if (!parent) break; if (sd_parent_degenerate(tmp, parent)) { tmp->parent = parent->parent; if (parent->parent) parent->parent->child = tmp; destroy_sched_domain(parent, cpu); } else tmp = tmp->parent; } if (sd && sd_degenerate(sd)) { tmp = sd; sd = sd->parent; destroy_sched_domain(tmp, cpu); if (sd) sd->child = NULL; } for (tmp = sd; tmp; ) { unsigned long interval; interval = msecs_to_jiffies(tmp->balance_interval); if (time_after(next_balance, tmp->last_balance + interval)) next_balance = tmp->last_balance + interval; tmp = tmp->parent; } rq->next_balance = next_balance; sched_domain_debug(sd, cpu); rq_attach_root(rq, rd); tmp = rq->sd; rcu_assign_pointer(rq->sd, sd); destroy_sched_domains(tmp, cpu); update_top_cache_domain(cpu); } /* cpus with isolated domains */ static cpumask_var_t cpu_isolated_map; /* Setup the mask of cpus configured for isolated domains */ static int __init isolated_cpu_setup(char *str) { alloc_bootmem_cpumask_var(&cpu_isolated_map); cpulist_parse(str, cpu_isolated_map); return 1; } __setup("isolcpus=", isolated_cpu_setup); #ifdef CONFIG_NUMA /** * find_next_best_node - find the next node to include in a sched_domain * @node: node whose sched_domain we're building * @used_nodes: nodes already in the sched_domain * * Find the next node to include in a given scheduling domain. Simply * finds the closest node not already in the @used_nodes map. * * Should use nodemask_t. */ static int find_next_best_node(int node, nodemask_t *used_nodes) { int i, n, val, min_val, best_node = -1; min_val = INT_MAX; for (i = 0; i < nr_node_ids; i++) { /* Start at @node */ n = (node + i) % nr_node_ids; if (!nr_cpus_node(n)) continue; /* Skip already used nodes */ if (node_isset(n, *used_nodes)) continue; /* Simple min distance search */ val = node_distance(node, n); if (val < min_val) { min_val = val; best_node = n; } } if (best_node != -1) node_set(best_node, *used_nodes); return best_node; } /** * sched_domain_node_span - get a cpumask for a node's sched_domain * @node: node whose cpumask we're constructing * @span: resulting cpumask * * Given a node, construct a good cpumask for its sched_domain to span. It * should be one that prevents unnecessary balancing, but also spreads tasks * out optimally. */ static void sched_domain_node_span(int node, struct cpumask *span) { nodemask_t used_nodes; int i; cpumask_clear(span); nodes_clear(used_nodes); cpumask_or(span, span, cpumask_of_node(node)); node_set(node, used_nodes); for (i = 1; i < SD_NODES_PER_DOMAIN; i++) { int next_node = find_next_best_node(node, &used_nodes); if (next_node < 0) break; cpumask_or(span, span, cpumask_of_node(next_node)); } } static const struct cpumask *cpu_node_mask(int cpu) { lockdep_assert_held(&sched_domains_mutex); sched_domain_node_span(cpu_to_node(cpu), sched_domains_tmpmask); return sched_domains_tmpmask; } static const struct cpumask *cpu_allnodes_mask(int cpu) { return cpu_possible_mask; } #endif /* CONFIG_NUMA */ static const struct cpumask *cpu_cpu_mask(int cpu) { return cpumask_of_node(cpu_to_node(cpu)); } int sched_smt_power_savings = 0, sched_mc_power_savings = 0; struct sd_data { struct sched_domain **__percpu sd; struct sched_group **__percpu sg; struct sched_group_power **__percpu sgp; }; struct s_data { struct sched_domain ** __percpu sd; struct root_domain *rd; }; enum s_alloc { sa_rootdomain, sa_sd, sa_sd_storage, sa_none, }; struct sched_domain_topology_level; typedef struct sched_domain *(*sched_domain_init_f)(struct sched_domain_topology_level *tl, int cpu); typedef const struct cpumask *(*sched_domain_mask_f)(int cpu); #define SDTL_OVERLAP 0x01 struct sched_domain_topology_level { sched_domain_init_f init; sched_domain_mask_f mask; int flags; struct sd_data data; }; static int build_overlap_sched_groups(struct sched_domain *sd, int cpu) { struct sched_group *first = NULL, *last = NULL, *groups = NULL, *sg; const struct cpumask *span = sched_domain_span(sd); struct cpumask *covered = sched_domains_tmpmask; struct sd_data *sdd = sd->private; struct sched_domain *child; int i; cpumask_clear(covered); for_each_cpu(i, span) { struct cpumask *sg_span; if (cpumask_test_cpu(i, covered)) continue; sg = kzalloc_node(sizeof(struct sched_group) + cpumask_size(), GFP_KERNEL, cpu_to_node(cpu)); if (!sg) goto fail; sg_span = sched_group_cpus(sg); child = *per_cpu_ptr(sdd->sd, i); if (child->child) { child = child->child; cpumask_copy(sg_span, sched_domain_span(child)); } else cpumask_set_cpu(i, sg_span); cpumask_or(covered, covered, sg_span); sg->sgp = *per_cpu_ptr(sdd->sgp, cpumask_first(sg_span)); atomic_inc(&sg->sgp->ref); if (cpumask_test_cpu(cpu, sg_span)) groups = sg; if (!first) first = sg; if (last) last->next = sg; last = sg; last->next = first; } sd->groups = groups; return 0; fail: free_sched_groups(first, 0); return -ENOMEM; } static int get_group(int cpu, struct sd_data *sdd, struct sched_group **sg) { struct sched_domain *sd = *per_cpu_ptr(sdd->sd, cpu); struct sched_domain *child = sd->child; if (child) cpu = cpumask_first(sched_domain_span(child)); if (sg) { *sg = *per_cpu_ptr(sdd->sg, cpu); (*sg)->sgp = *per_cpu_ptr(sdd->sgp, cpu); atomic_set(&(*sg)->sgp->ref, 1); /* for claim_allocations */ } return cpu; } /* * build_sched_groups will build a circular linked list of the groups * covered by the given span, and will set each group's ->cpumask correctly, * and ->cpu_power to 0. * * Assumes the sched_domain tree is fully constructed */ static int build_sched_groups(struct sched_domain *sd, int cpu) { struct sched_group *first = NULL, *last = NULL; struct sd_data *sdd = sd->private; const struct cpumask *span = sched_domain_span(sd); struct cpumask *covered; int i; get_group(cpu, sdd, &sd->groups); atomic_inc(&sd->groups->ref); if (cpu != cpumask_first(sched_domain_span(sd))) return 0; lockdep_assert_held(&sched_domains_mutex); covered = sched_domains_tmpmask; cpumask_clear(covered); for_each_cpu(i, span) { struct sched_group *sg; int group = get_group(i, sdd, &sg); int j; if (cpumask_test_cpu(i, covered)) continue; cpumask_clear(sched_group_cpus(sg)); sg->sgp->power = 0; for_each_cpu(j, span) { if (get_group(j, sdd, NULL) != group) continue; cpumask_set_cpu(j, covered); cpumask_set_cpu(j, sched_group_cpus(sg)); } if (!first) first = sg; if (last) last->next = sg; last = sg; } last->next = first; return 0; } /* * Initialize sched groups cpu_power. * * cpu_power indicates the capacity of sched group, which is used while * distributing the load between different sched groups in a sched domain. * Typically cpu_power for all the groups in a sched domain will be same unless * there are asymmetries in the topology. If there are asymmetries, group * having more cpu_power will pickup more load compared to the group having * less cpu_power. */ static void init_sched_groups_power(int cpu, struct sched_domain *sd) { struct sched_group *sg = sd->groups; WARN_ON(!sd || !sg); do { sg->group_weight = cpumask_weight(sched_group_cpus(sg)); sg = sg->next; } while (sg != sd->groups); if (cpu != group_first_cpu(sg)) return; update_group_power(sd, cpu); atomic_set(&sg->sgp->nr_busy_cpus, sg->group_weight); } int __weak arch_sd_sibling_asym_packing(void) { return 0*SD_ASYM_PACKING; } /* * Initializers for schedule domains * Non-inlined to reduce accumulated stack pressure in build_sched_domains() */ #ifdef CONFIG_SCHED_DEBUG # define SD_INIT_NAME(sd, type) sd->name = #type #else # define SD_INIT_NAME(sd, type) do { } while (0) #endif #define SD_INIT_FUNC(type) \ static noinline struct sched_domain * \ sd_init_##type(struct sched_domain_topology_level *tl, int cpu) \ { \ struct sched_domain *sd = *per_cpu_ptr(tl->data.sd, cpu); \ *sd = SD_##type##_INIT; \ SD_INIT_NAME(sd, type); \ sd->private = &tl->data; \ return sd; \ } SD_INIT_FUNC(CPU) #ifdef CONFIG_NUMA SD_INIT_FUNC(ALLNODES) SD_INIT_FUNC(NODE) #endif #ifdef CONFIG_SCHED_SMT SD_INIT_FUNC(SIBLING) #endif #ifdef CONFIG_SCHED_MC SD_INIT_FUNC(MC) #endif #ifdef CONFIG_SCHED_BOOK SD_INIT_FUNC(BOOK) #endif static int default_relax_domain_level = -1; int sched_domain_level_max; static int __init setup_relax_domain_level(char *str) { if (kstrtoint(str, 0, &default_relax_domain_level)) pr_warn("Unable to set relax_domain_level\n"); return 1; } __setup("relax_domain_level=", setup_relax_domain_level); static void set_domain_attribute(struct sched_domain *sd, struct sched_domain_attr *attr) { int request; if (!attr || attr->relax_domain_level < 0) { if (default_relax_domain_level < 0) return; else request = default_relax_domain_level; } else request = attr->relax_domain_level; if (request < sd->level) { /* turn off idle balance on this domain */ sd->flags &= ~(SD_BALANCE_WAKE|SD_BALANCE_NEWIDLE); } else { /* turn on idle balance on this domain */ sd->flags |= (SD_BALANCE_WAKE|SD_BALANCE_NEWIDLE); } } static void __sdt_free(const struct cpumask *cpu_map); static int __sdt_alloc(const struct cpumask *cpu_map); static void __free_domain_allocs(struct s_data *d, enum s_alloc what, const struct cpumask *cpu_map) { switch (what) { case sa_rootdomain: if (!atomic_read(&d->rd->refcount)) free_rootdomain(&d->rd->rcu); /* fall through */ case sa_sd: free_percpu(d->sd); /* fall through */ case sa_sd_storage: __sdt_free(cpu_map); /* fall through */ case sa_none: break; } } static enum s_alloc __visit_domain_allocation_hell(struct s_data *d, const struct cpumask *cpu_map) { memset(d, 0, sizeof(*d)); if (__sdt_alloc(cpu_map)) return sa_sd_storage; d->sd = alloc_percpu(struct sched_domain *); if (!d->sd) return sa_sd_storage; d->rd = alloc_rootdomain(); if (!d->rd) return sa_sd; return sa_rootdomain; } /* * NULL the sd_data elements we've used to build the sched_domain and * sched_group structure so that the subsequent __free_domain_allocs() * will not free the data we're using. */ static void claim_allocations(int cpu, struct sched_domain *sd) { struct sd_data *sdd = sd->private; WARN_ON_ONCE(*per_cpu_ptr(sdd->sd, cpu) != sd); *per_cpu_ptr(sdd->sd, cpu) = NULL; if (atomic_read(&(*per_cpu_ptr(sdd->sg, cpu))->ref)) *per_cpu_ptr(sdd->sg, cpu) = NULL; if (atomic_read(&(*per_cpu_ptr(sdd->sgp, cpu))->ref)) *per_cpu_ptr(sdd->sgp, cpu) = NULL; } #ifdef CONFIG_SCHED_SMT static const struct cpumask *cpu_smt_mask(int cpu) { return topology_thread_cpumask(cpu); } #endif /* * Topology list, bottom-up. */ static struct sched_domain_topology_level default_topology[] = { #ifdef CONFIG_SCHED_SMT { sd_init_SIBLING, cpu_smt_mask, }, #endif #ifdef CONFIG_SCHED_MC { sd_init_MC, cpu_coregroup_mask, }, #endif #ifdef CONFIG_SCHED_BOOK { sd_init_BOOK, cpu_book_mask, }, #endif { sd_init_CPU, cpu_cpu_mask, }, #ifdef CONFIG_NUMA { sd_init_NODE, cpu_node_mask, SDTL_OVERLAP, }, { sd_init_ALLNODES, cpu_allnodes_mask, }, #endif { NULL, }, }; static struct sched_domain_topology_level *sched_domain_topology = default_topology; static int __sdt_alloc(const struct cpumask *cpu_map) { struct sched_domain_topology_level *tl; int j; for (tl = sched_domain_topology; tl->init; tl++) { struct sd_data *sdd = &tl->data; sdd->sd = alloc_percpu(struct sched_domain *); if (!sdd->sd) return -ENOMEM; sdd->sg = alloc_percpu(struct sched_group *); if (!sdd->sg) return -ENOMEM; sdd->sgp = alloc_percpu(struct sched_group_power *); if (!sdd->sgp) return -ENOMEM; for_each_cpu(j, cpu_map) { struct sched_domain *sd; struct sched_group *sg; struct sched_group_power *sgp; sd = kzalloc_node(sizeof(struct sched_domain) + cpumask_size(), GFP_KERNEL, cpu_to_node(j)); if (!sd) return -ENOMEM; *per_cpu_ptr(sdd->sd, j) = sd; sg = kzalloc_node(sizeof(struct sched_group) + cpumask_size(), GFP_KERNEL, cpu_to_node(j)); if (!sg) return -ENOMEM; sg->next = sg; *per_cpu_ptr(sdd->sg, j) = sg; sgp = kzalloc_node(sizeof(struct sched_group_power), GFP_KERNEL, cpu_to_node(j)); if (!sgp) return -ENOMEM; *per_cpu_ptr(sdd->sgp, j) = sgp; } } return 0; } static void __sdt_free(const struct cpumask *cpu_map) { struct sched_domain_topology_level *tl; int j; for (tl = sched_domain_topology; tl->init; tl++) { struct sd_data *sdd = &tl->data; for_each_cpu(j, cpu_map) { struct sched_domain *sd; if (sdd->sd) { sd = *per_cpu_ptr(sdd->sd, j); if (sd && (sd->flags & SD_OVERLAP)) free_sched_groups(sd->groups, 0); kfree(*per_cpu_ptr(sdd->sd, j)); } if (sdd->sg) kfree(*per_cpu_ptr(sdd->sg, j)); if (sdd->sgp) kfree(*per_cpu_ptr(sdd->sgp, j)); } free_percpu(sdd->sd); sdd->sd = NULL; free_percpu(sdd->sg); sdd->sg = NULL; free_percpu(sdd->sgp); sdd->sgp = NULL; } } struct sched_domain *build_sched_domain(struct sched_domain_topology_level *tl, struct s_data *d, const struct cpumask *cpu_map, struct sched_domain_attr *attr, struct sched_domain *child, int cpu) { struct sched_domain *sd = tl->init(tl, cpu); if (!sd) return child; cpumask_and(sched_domain_span(sd), cpu_map, tl->mask(cpu)); if (child) { sd->level = child->level + 1; sched_domain_level_max = max(sched_domain_level_max, sd->level); child->parent = sd; } sd->child = child; set_domain_attribute(sd, attr); return sd; } /* * Build sched domains for a given set of cpus and attach the sched domains * to the individual cpus */ static int build_sched_domains(const struct cpumask *cpu_map, struct sched_domain_attr *attr) { enum s_alloc alloc_state = sa_none; struct sched_domain *sd; struct s_data d; int i, ret = -ENOMEM; alloc_state = __visit_domain_allocation_hell(&d, cpu_map); if (alloc_state != sa_rootdomain) goto error; /* Set up domains for cpus specified by the cpu_map. */ for_each_cpu(i, cpu_map) { struct sched_domain_topology_level *tl; sd = NULL; for (tl = sched_domain_topology; tl->init; tl++) { sd = build_sched_domain(tl, &d, cpu_map, attr, sd, i); if (tl->flags & SDTL_OVERLAP || sched_feat(FORCE_SD_OVERLAP)) sd->flags |= SD_OVERLAP; if (cpumask_equal(cpu_map, sched_domain_span(sd))) break; } while (sd->child) sd = sd->child; *per_cpu_ptr(d.sd, i) = sd; } /* Build the groups for the domains */ for_each_cpu(i, cpu_map) { for (sd = *per_cpu_ptr(d.sd, i); sd; sd = sd->parent) { sd->span_weight = cpumask_weight(sched_domain_span(sd)); if (sd->flags & SD_OVERLAP) { if (build_overlap_sched_groups(sd, i)) goto error; } else { if (build_sched_groups(sd, i)) goto error; } } } /* Calculate CPU power for physical packages and nodes */ for (i = nr_cpumask_bits-1; i >= 0; i--) { if (!cpumask_test_cpu(i, cpu_map)) continue; for (sd = *per_cpu_ptr(d.sd, i); sd; sd = sd->parent) { claim_allocations(i, sd); init_sched_groups_power(i, sd); } } /* Attach the domains */ rcu_read_lock(); for_each_cpu(i, cpu_map) { sd = *per_cpu_ptr(d.sd, i); cpu_attach_domain(sd, d.rd, i); } rcu_read_unlock(); ret = 0; error: __free_domain_allocs(&d, alloc_state, cpu_map); return ret; } static cpumask_var_t *doms_cur; /* current sched domains */ static int ndoms_cur; /* number of sched domains in 'doms_cur' */ static struct sched_domain_attr *dattr_cur; /* attribues of custom domains in 'doms_cur' */ /* * Special case: If a kmalloc of a doms_cur partition (array of * cpumask) fails, then fallback to a single sched domain, * as determined by the single cpumask fallback_doms. */ static cpumask_var_t fallback_doms; /* * arch_update_cpu_topology lets virtualized architectures update the * cpu core maps. It is supposed to return 1 if the topology changed * or 0 if it stayed the same. */ int __attribute__((weak)) arch_update_cpu_topology(void) { return 0; } cpumask_var_t *alloc_sched_domains(unsigned int ndoms) { int i; cpumask_var_t *doms; doms = kmalloc(sizeof(*doms) * ndoms, GFP_KERNEL); if (!doms) return NULL; for (i = 0; i < ndoms; i++) { if (!alloc_cpumask_var(&doms[i], GFP_KERNEL)) { free_sched_domains(doms, i); return NULL; } } return doms; } void free_sched_domains(cpumask_var_t doms[], unsigned int ndoms) { unsigned int i; for (i = 0; i < ndoms; i++) free_cpumask_var(doms[i]); kfree(doms); } /* * Set up scheduler domains and groups. Callers must hold the hotplug lock. * For now this just excludes isolated cpus, but could be used to * exclude other special cases in the future. */ static int init_sched_domains(const struct cpumask *cpu_map) { int err; arch_update_cpu_topology(); ndoms_cur = 1; doms_cur = alloc_sched_domains(ndoms_cur); if (!doms_cur) doms_cur = &fallback_doms; cpumask_andnot(doms_cur[0], cpu_map, cpu_isolated_map); dattr_cur = NULL; err = build_sched_domains(doms_cur[0], NULL); register_sched_domain_sysctl(); return err; } /* * Detach sched domains from a group of cpus specified in cpu_map * These cpus will now be attached to the NULL domain */ static void detach_destroy_domains(const struct cpumask *cpu_map) { int i; rcu_read_lock(); for_each_cpu(i, cpu_map) cpu_attach_domain(NULL, &def_root_domain, i); rcu_read_unlock(); } /* handle null as "default" */ static int dattrs_equal(struct sched_domain_attr *cur, int idx_cur, struct sched_domain_attr *new, int idx_new) { struct sched_domain_attr tmp; /* fast path */ if (!new && !cur) return 1; tmp = SD_ATTR_INIT; return !memcmp(cur ? (cur + idx_cur) : &tmp, new ? (new + idx_new) : &tmp, sizeof(struct sched_domain_attr)); } /* * Partition sched domains as specified by the 'ndoms_new' * cpumasks in the array doms_new[] of cpumasks. This compares * doms_new[] to the current sched domain partitioning, doms_cur[]. * It destroys each deleted domain and builds each new domain. * * 'doms_new' is an array of cpumask_var_t's of length 'ndoms_new'. * The masks don't intersect (don't overlap.) We should setup one * sched domain for each mask. CPUs not in any of the cpumasks will * not be load balanced. If the same cpumask appears both in the * current 'doms_cur' domains and in the new 'doms_new', we can leave * it as it is. * * The passed in 'doms_new' should be allocated using * alloc_sched_domains. This routine takes ownership of it and will * free_sched_domains it when done with it. If the caller failed the * alloc call, then it can pass in doms_new == NULL && ndoms_new == 1, * and partition_sched_domains() will fallback to the single partition * 'fallback_doms', it also forces the domains to be rebuilt. * * If doms_new == NULL it will be replaced with cpu_online_mask. * ndoms_new == 0 is a special case for destroying existing domains, * and it will not create the default domain. * * Call with hotplug lock held */ void partition_sched_domains(int ndoms_new, cpumask_var_t doms_new[], struct sched_domain_attr *dattr_new) { int i, j, n; int new_topology; mutex_lock(&sched_domains_mutex); /* always unregister in case we don't destroy any domains */ unregister_sched_domain_sysctl(); /* Let architecture update cpu core mappings. */ new_topology = arch_update_cpu_topology(); n = doms_new ? ndoms_new : 0; /* Destroy deleted domains */ for (i = 0; i < ndoms_cur; i++) { for (j = 0; j < n && !new_topology; j++) { if (cpumask_equal(doms_cur[i], doms_new[j]) && dattrs_equal(dattr_cur, i, dattr_new, j)) goto match1; } /* no match - a current sched domain not in new doms_new[] */ detach_destroy_domains(doms_cur[i]); match1: ; } if (doms_new == NULL) { ndoms_cur = 0; doms_new = &fallback_doms; cpumask_andnot(doms_new[0], cpu_active_mask, cpu_isolated_map); WARN_ON_ONCE(dattr_new); } /* Build new domains */ for (i = 0; i < ndoms_new; i++) { for (j = 0; j < ndoms_cur && !new_topology; j++) { if (cpumask_equal(doms_new[i], doms_cur[j]) && dattrs_equal(dattr_new, i, dattr_cur, j)) goto match2; } /* no match - add a new doms_new */ build_sched_domains(doms_new[i], dattr_new ? dattr_new + i : NULL); match2: ; } /* Remember the new sched domains */ if (doms_cur != &fallback_doms) free_sched_domains(doms_cur, ndoms_cur); kfree(dattr_cur); /* kfree(NULL) is safe */ doms_cur = doms_new; dattr_cur = dattr_new; ndoms_cur = ndoms_new; register_sched_domain_sysctl(); mutex_unlock(&sched_domains_mutex); } #if defined(CONFIG_SCHED_MC) || defined(CONFIG_SCHED_SMT) static void reinit_sched_domains(void) { get_online_cpus(); /* Destroy domains first to force the rebuild */ partition_sched_domains(0, NULL, NULL); rebuild_sched_domains(); put_online_cpus(); } static ssize_t sched_power_savings_store(const char *buf, size_t count, int smt) { unsigned int level = 0; if (sscanf(buf, "%u", &level) != 1) return -EINVAL; /* * level is always be positive so don't check for * level < POWERSAVINGS_BALANCE_NONE which is 0 * What happens on 0 or 1 byte write, * need to check for count as well? */ if (level >= MAX_POWERSAVINGS_BALANCE_LEVELS) return -EINVAL; if (smt) sched_smt_power_savings = level; else sched_mc_power_savings = level; reinit_sched_domains(); return count; } #ifdef CONFIG_SCHED_MC static ssize_t sched_mc_power_savings_show(struct device *dev, struct device_attribute *attr, char *buf) { return sprintf(buf, "%u\n", sched_mc_power_savings); } static ssize_t sched_mc_power_savings_store(struct device *dev, struct device_attribute *attr, const char *buf, size_t count) { return sched_power_savings_store(buf, count, 0); } static DEVICE_ATTR(sched_mc_power_savings, 0644, sched_mc_power_savings_show, sched_mc_power_savings_store); #endif #ifdef CONFIG_SCHED_SMT static ssize_t sched_smt_power_savings_show(struct device *dev, struct device_attribute *attr, char *buf) { return sprintf(buf, "%u\n", sched_smt_power_savings); } static ssize_t sched_smt_power_savings_store(struct device *dev, struct device_attribute *attr, const char *buf, size_t count) { return sched_power_savings_store(buf, count, 1); } static DEVICE_ATTR(sched_smt_power_savings, 0644, sched_smt_power_savings_show, sched_smt_power_savings_store); #endif int __init sched_create_sysfs_power_savings_entries(struct device *dev) { int err = 0; #ifdef CONFIG_SCHED_SMT if (smt_capable()) err = device_create_file(dev, &dev_attr_sched_smt_power_savings); #endif #ifdef CONFIG_SCHED_MC if (!err && mc_capable()) err = device_create_file(dev, &dev_attr_sched_mc_power_savings); #endif return err; } #endif /* CONFIG_SCHED_MC || CONFIG_SCHED_SMT */ static int num_cpus_frozen; /* used to mark begin/end of suspend/resume */ /* * Update cpusets according to cpu_active mask. If cpusets are * disabled, cpuset_update_active_cpus() becomes a simple wrapper * around partition_sched_domains(). * * If we come here as part of a suspend/resume, don't touch cpusets because we * want to restore it back to its original state upon resume anyway. */ static int cpuset_cpu_active(struct notifier_block *nfb, unsigned long action, void *hcpu) { switch (action) { case CPU_ONLINE_FROZEN: case CPU_DOWN_FAILED_FROZEN: /* * num_cpus_frozen tracks how many CPUs are involved in suspend * resume sequence. As long as this is not the last online * operation in the resume sequence, just build a single sched * domain, ignoring cpusets. */ num_cpus_frozen--; if (likely(num_cpus_frozen)) { partition_sched_domains(1, NULL, NULL); break; } /* * This is the last CPU online operation. So fall through and * restore the original sched domains by considering the * cpuset configurations. */ case CPU_ONLINE: case CPU_DOWN_FAILED: cpuset_update_active_cpus(); break; default: return NOTIFY_DONE; } return NOTIFY_OK; } static int cpuset_cpu_inactive(struct notifier_block *nfb, unsigned long action, void *hcpu) { switch (action) { case CPU_DOWN_PREPARE: cpuset_update_active_cpus(); break; case CPU_DOWN_PREPARE_FROZEN: num_cpus_frozen++; partition_sched_domains(1, NULL, NULL); break; default: return NOTIFY_DONE; } return NOTIFY_OK; } void __init sched_init_smp(void) { cpumask_var_t non_isolated_cpus; alloc_cpumask_var(&non_isolated_cpus, GFP_KERNEL); alloc_cpumask_var(&fallback_doms, GFP_KERNEL); get_online_cpus(); mutex_lock(&sched_domains_mutex); init_sched_domains(cpu_active_mask); cpumask_andnot(non_isolated_cpus, cpu_possible_mask, cpu_isolated_map); if (cpumask_empty(non_isolated_cpus)) cpumask_set_cpu(smp_processor_id(), non_isolated_cpus); mutex_unlock(&sched_domains_mutex); put_online_cpus(); hotcpu_notifier(cpuset_cpu_active, CPU_PRI_CPUSET_ACTIVE); hotcpu_notifier(cpuset_cpu_inactive, CPU_PRI_CPUSET_INACTIVE); init_hrtick(); /* Move init over to a non-isolated CPU */ if (set_cpus_allowed_ptr(current, non_isolated_cpus) < 0) BUG(); sched_init_granularity(); free_cpumask_var(non_isolated_cpus); init_sched_rt_class(); } #else void __init sched_init_smp(void) { sched_init_granularity(); } #endif /* CONFIG_SMP */ const_debug unsigned int sysctl_timer_migration = 1; int in_sched_functions(unsigned long addr) { return in_lock_functions(addr) || (addr >= (unsigned long)__sched_text_start && addr < (unsigned long)__sched_text_end); } #ifdef CONFIG_CGROUP_SCHED struct task_group root_task_group; LIST_HEAD(task_groups); #endif DECLARE_PER_CPU(cpumask_var_t, load_balance_tmpmask); void __init sched_init(void) { int i, j; unsigned long alloc_size = 0, ptr; #ifdef CONFIG_FAIR_GROUP_SCHED alloc_size += 2 * nr_cpu_ids * sizeof(void **); #endif #ifdef CONFIG_RT_GROUP_SCHED alloc_size += 2 * nr_cpu_ids * sizeof(void **); #endif #ifdef CONFIG_CPUMASK_OFFSTACK alloc_size += num_possible_cpus() * cpumask_size(); #endif if (alloc_size) { ptr = (unsigned long)kzalloc(alloc_size, GFP_NOWAIT); #ifdef CONFIG_FAIR_GROUP_SCHED root_task_group.se = (struct sched_entity **)ptr; ptr += nr_cpu_ids * sizeof(void **); root_task_group.cfs_rq = (struct cfs_rq **)ptr; ptr += nr_cpu_ids * sizeof(void **); #endif /* CONFIG_FAIR_GROUP_SCHED */ #ifdef CONFIG_RT_GROUP_SCHED root_task_group.rt_se = (struct sched_rt_entity **)ptr; ptr += nr_cpu_ids * sizeof(void **); root_task_group.rt_rq = (struct rt_rq **)ptr; ptr += nr_cpu_ids * sizeof(void **); #endif /* CONFIG_RT_GROUP_SCHED */ #ifdef CONFIG_CPUMASK_OFFSTACK for_each_possible_cpu(i) { per_cpu(load_balance_tmpmask, i) = (void *)ptr; ptr += cpumask_size(); } #endif /* CONFIG_CPUMASK_OFFSTACK */ } #ifdef CONFIG_SMP init_defrootdomain(); #endif init_rt_bandwidth(&def_rt_bandwidth, global_rt_period(), global_rt_runtime()); #ifdef CONFIG_RT_GROUP_SCHED init_rt_bandwidth(&root_task_group.rt_bandwidth, global_rt_period(), global_rt_runtime()); #endif /* CONFIG_RT_GROUP_SCHED */ #ifdef CONFIG_CGROUP_SCHED list_add(&root_task_group.list, &task_groups); INIT_LIST_HEAD(&root_task_group.children); INIT_LIST_HEAD(&root_task_group.siblings); autogroup_init(&init_task); #endif /* CONFIG_CGROUP_SCHED */ #ifdef CONFIG_CGROUP_CPUACCT root_cpuacct.cpustat = &kernel_cpustat; root_cpuacct.cpuusage = alloc_percpu(u64); /* Too early, not expected to fail */ BUG_ON(!root_cpuacct.cpuusage); #endif for_each_possible_cpu(i) { struct rq *rq; rq = cpu_rq(i); raw_spin_lock_init(&rq->lock); rq->nr_running = 0; rq->calc_load_active = 0; rq->calc_load_update = jiffies + LOAD_FREQ; init_cfs_rq(&rq->cfs); init_rt_rq(&rq->rt, rq); #ifdef CONFIG_FAIR_GROUP_SCHED root_task_group.shares = ROOT_TASK_GROUP_LOAD; INIT_LIST_HEAD(&rq->leaf_cfs_rq_list); /* * How much cpu bandwidth does root_task_group get? * * In case of task-groups formed thr' the cgroup filesystem, it * gets 100% of the cpu resources in the system. This overall * system cpu resource is divided among the tasks of * root_task_group and its child task-groups in a fair manner, * based on each entity's (task or task-group's) weight * (se->load.weight). * * In other words, if root_task_group has 10 tasks of weight * 1024) and two child groups A0 and A1 (of weight 1024 each), * then A0's share of the cpu resource is: * * A0's bandwidth = 1024 / (10*1024 + 1024 + 1024) = 8.33% * * We achieve this by letting root_task_group's tasks sit * directly in rq->cfs (i.e root_task_group->se[] = NULL). */ init_cfs_bandwidth(&root_task_group.cfs_bandwidth); init_tg_cfs_entry(&root_task_group, &rq->cfs, NULL, i, NULL); #endif /* CONFIG_FAIR_GROUP_SCHED */ rq->rt.rt_runtime = def_rt_bandwidth.rt_runtime; #ifdef CONFIG_RT_GROUP_SCHED INIT_LIST_HEAD(&rq->leaf_rt_rq_list); init_tg_rt_entry(&root_task_group, &rq->rt, NULL, i, NULL); #endif for (j = 0; j < CPU_LOAD_IDX_MAX; j++) rq->cpu_load[j] = 0; rq->last_load_update_tick = jiffies; #ifdef CONFIG_SMP rq->sd = NULL; rq->rd = NULL; rq->cpu_power = SCHED_POWER_SCALE; rq->post_schedule = 0; rq->active_balance = 0; rq->next_balance = jiffies; rq->push_cpu = 0; rq->cpu = i; rq->online = 0; rq->idle_stamp = 0; rq->avg_idle = 2*sysctl_sched_migration_cost; INIT_LIST_HEAD(&rq->cfs_tasks); rq_attach_root(rq, &def_root_domain); #ifdef CONFIG_NO_HZ rq->nohz_flags = 0; #endif #endif init_rq_hrtick(rq); atomic_set(&rq->nr_iowait, 0); } set_load_weight(&init_task); #ifdef CONFIG_PREEMPT_NOTIFIERS INIT_HLIST_HEAD(&init_task.preempt_notifiers); #endif #ifdef CONFIG_RT_MUTEXES plist_head_init(&init_task.pi_waiters); #endif /* * The boot idle thread does lazy MMU switching as well: */ atomic_inc(&init_mm.mm_count); enter_lazy_tlb(&init_mm, current); /* * Make us the idle thread. Technically, schedule() should not be * called from this thread, however somewhere below it might be, * but because we are the idle thread, we just pick up running again * when this runqueue becomes "idle". */ init_idle(current, smp_processor_id()); calc_load_update = jiffies + LOAD_FREQ; /* * During early bootup we pretend to be a normal task: */ current->sched_class = &fair_sched_class; #ifdef CONFIG_SMP zalloc_cpumask_var(&sched_domains_tmpmask, GFP_NOWAIT); /* May be allocated at isolcpus cmdline parse time */ if (cpu_isolated_map == NULL) zalloc_cpumask_var(&cpu_isolated_map, GFP_NOWAIT); idle_thread_set_boot_cpu(); #endif init_sched_fair_class(); scheduler_running = 1; } #ifdef CONFIG_DEBUG_ATOMIC_SLEEP static inline int preempt_count_equals(int preempt_offset) { int nested = (preempt_count() & ~PREEMPT_ACTIVE) + rcu_preempt_depth(); return (nested == preempt_offset); } static int __might_sleep_init_called; int __init __might_sleep_init(void) { __might_sleep_init_called = 1; return 0; } early_initcall(__might_sleep_init); void __might_sleep(const char *file, int line, int preempt_offset) { static unsigned long prev_jiffy; /* ratelimiting */ rcu_sleep_check(); /* WARN_ON_ONCE() by default, no rate limit reqd. */ if ((preempt_count_equals(preempt_offset) && !irqs_disabled()) || oops_in_progress) return; if (system_state != SYSTEM_RUNNING && (!__might_sleep_init_called || system_state != SYSTEM_BOOTING)) return; if (time_before(jiffies, prev_jiffy + HZ) && prev_jiffy) return; prev_jiffy = jiffies; printk(KERN_ERR "BUG: sleeping function called from invalid context at %s:%d\n", file, line); printk(KERN_ERR "in_atomic(): %d, irqs_disabled(): %d, pid: %d, name: %s\n", in_atomic(), irqs_disabled(), current->pid, current->comm); debug_show_held_locks(current); if (irqs_disabled()) print_irqtrace_events(current); dump_stack(); } EXPORT_SYMBOL(__might_sleep); #endif #ifdef CONFIG_MAGIC_SYSRQ static void normalize_task(struct rq *rq, struct task_struct *p) { const struct sched_class *prev_class = p->sched_class; int old_prio = p->prio; int on_rq; on_rq = p->on_rq; if (on_rq) dequeue_task(rq, p, 0); __setscheduler(rq, p, SCHED_NORMAL, 0); if (on_rq) { enqueue_task(rq, p, 0); resched_task(rq->curr); } check_class_changed(rq, p, prev_class, old_prio); } void normalize_rt_tasks(void) { struct task_struct *g, *p; unsigned long flags; struct rq *rq; read_lock_irqsave(&tasklist_lock, flags); do_each_thread(g, p) { /* * Only normalize user tasks: */ if (!p->mm) continue; p->se.exec_start = 0; #ifdef CONFIG_SCHEDSTATS p->se.statistics.wait_start = 0; p->se.statistics.sleep_start = 0; p->se.statistics.block_start = 0; #endif if (!rt_task(p)) { /* * Renice negative nice level userspace * tasks back to 0: */ if (TASK_NICE(p) < 0 && p->mm) set_user_nice(p, 0); continue; } raw_spin_lock(&p->pi_lock); rq = __task_rq_lock(p); normalize_task(rq, p); __task_rq_unlock(rq); raw_spin_unlock(&p->pi_lock); } while_each_thread(g, p); read_unlock_irqrestore(&tasklist_lock, flags); } #endif /* CONFIG_MAGIC_SYSRQ */ #if defined(CONFIG_IA64) || defined(CONFIG_KGDB_KDB) /* * These functions are only useful for the IA64 MCA handling, or kdb. * * They can only be called when the whole system has been * stopped - every CPU needs to be quiescent, and no scheduling * activity can take place. Using them for anything else would * be a serious bug, and as a result, they aren't even visible * under any other configuration. */ /** * curr_task - return the current task for a given cpu. * @cpu: the processor in question. * * ONLY VALID WHEN THE WHOLE SYSTEM IS STOPPED! */ struct task_struct *curr_task(int cpu) { return cpu_curr(cpu); } #endif /* defined(CONFIG_IA64) || defined(CONFIG_KGDB_KDB) */ #ifdef CONFIG_IA64 /** * set_curr_task - set the current task for a given cpu. * @cpu: the processor in question. * @p: the task pointer to set. * * Description: This function must only be used when non-maskable interrupts * are serviced on a separate stack. It allows the architecture to switch the * notion of the current task on a cpu in a non-blocking manner. This function * must be called with all CPU's synchronized, and interrupts disabled, the * and caller must save the original value of the current task (see * curr_task() above) and restore that value before reenabling interrupts and * re-starting the system. * * ONLY VALID WHEN THE WHOLE SYSTEM IS STOPPED! */ void set_curr_task(int cpu, struct task_struct *p) { cpu_curr(cpu) = p; } #endif #ifdef CONFIG_CGROUP_SCHED /* task_group_lock serializes the addition/removal of task groups */ static DEFINE_SPINLOCK(task_group_lock); static void free_sched_group(struct task_group *tg) { free_fair_sched_group(tg); free_rt_sched_group(tg); autogroup_free(tg); kfree(tg); } /* allocate runqueue etc for a new task group */ struct task_group *sched_create_group(struct task_group *parent) { struct task_group *tg; unsigned long flags; tg = kzalloc(sizeof(*tg), GFP_KERNEL); if (!tg) return ERR_PTR(-ENOMEM); if (!alloc_fair_sched_group(tg, parent)) goto err; if (!alloc_rt_sched_group(tg, parent)) goto err; spin_lock_irqsave(&task_group_lock, flags); list_add_rcu(&tg->list, &task_groups); WARN_ON(!parent); /* root should already exist */ tg->parent = parent; INIT_LIST_HEAD(&tg->children); list_add_rcu(&tg->siblings, &parent->children); spin_unlock_irqrestore(&task_group_lock, flags); return tg; err: free_sched_group(tg); return ERR_PTR(-ENOMEM); } /* rcu callback to free various structures associated with a task group */ static void free_sched_group_rcu(struct rcu_head *rhp) { /* now it should be safe to free those cfs_rqs */ free_sched_group(container_of(rhp, struct task_group, rcu)); } /* Destroy runqueue etc associated with a task group */ void sched_destroy_group(struct task_group *tg) { unsigned long flags; int i; /* end participation in shares distribution */ for_each_possible_cpu(i) unregister_fair_sched_group(tg, i); spin_lock_irqsave(&task_group_lock, flags); list_del_rcu(&tg->list); list_del_rcu(&tg->siblings); spin_unlock_irqrestore(&task_group_lock, flags); /* wait for possible concurrent references to cfs_rqs complete */ call_rcu(&tg->rcu, free_sched_group_rcu); } /* change task's runqueue when it moves between groups. * The caller of this function should have put the task in its new group * by now. This function just updates tsk->se.cfs_rq and tsk->se.parent to * reflect its new group. */ void sched_move_task(struct task_struct *tsk) { struct task_group *tg; int on_rq, running; unsigned long flags; struct rq *rq; rq = task_rq_lock(tsk, &flags); running = task_current(rq, tsk); on_rq = tsk->on_rq; if (on_rq) dequeue_task(rq, tsk, 0); if (unlikely(running)) tsk->sched_class->put_prev_task(rq, tsk); tg = container_of(task_subsys_state_check(tsk, cpu_cgroup_subsys_id, lockdep_is_held(&tsk->sighand->siglock)), struct task_group, css); tg = autogroup_task_group(tsk, tg); tsk->sched_task_group = tg; #ifdef CONFIG_FAIR_GROUP_SCHED if (tsk->sched_class->task_move_group) tsk->sched_class->task_move_group(tsk, on_rq); else #endif set_task_rq(tsk, task_cpu(tsk)); if (unlikely(running)) tsk->sched_class->set_curr_task(rq); if (on_rq) enqueue_task(rq, tsk, 0); task_rq_unlock(rq, tsk, &flags); } #endif /* CONFIG_CGROUP_SCHED */ #if defined(CONFIG_RT_GROUP_SCHED) || defined(CONFIG_CFS_BANDWIDTH) static unsigned long to_ratio(u64 period, u64 runtime) { if (runtime == RUNTIME_INF) return 1ULL << 20; return div64_u64(runtime << 20, period); } #endif #ifdef CONFIG_RT_GROUP_SCHED /* * Ensure that the real time constraints are schedulable. */ static DEFINE_MUTEX(rt_constraints_mutex); /* Must be called with tasklist_lock held */ static inline int tg_has_rt_tasks(struct task_group *tg) { struct task_struct *g, *p; do_each_thread(g, p) { if (rt_task(p) && task_rq(p)->rt.tg == tg) return 1; } while_each_thread(g, p); return 0; } struct rt_schedulable_data { struct task_group *tg; u64 rt_period; u64 rt_runtime; }; static int tg_rt_schedulable(struct task_group *tg, void *data) { struct rt_schedulable_data *d = data; struct task_group *child; unsigned long total, sum = 0; u64 period, runtime; period = ktime_to_ns(tg->rt_bandwidth.rt_period); runtime = tg->rt_bandwidth.rt_runtime; if (tg == d->tg) { period = d->rt_period; runtime = d->rt_runtime; } /* * Cannot have more runtime than the period. */ if (runtime > period && runtime != RUNTIME_INF) return -EINVAL; /* * Ensure we don't starve existing RT tasks. */ if (rt_bandwidth_enabled() && !runtime && tg_has_rt_tasks(tg)) return -EBUSY; total = to_ratio(period, runtime); /* * Nobody can have more than the global setting allows. */ if (total > to_ratio(global_rt_period(), global_rt_runtime())) return -EINVAL; /* * The sum of our children's runtime should not exceed our own. */ list_for_each_entry_rcu(child, &tg->children, siblings) { period = ktime_to_ns(child->rt_bandwidth.rt_period); runtime = child->rt_bandwidth.rt_runtime; if (child == d->tg) { period = d->rt_period; runtime = d->rt_runtime; } sum += to_ratio(period, runtime); } if (sum > total) return -EINVAL; return 0; } static int __rt_schedulable(struct task_group *tg, u64 period, u64 runtime) { int ret; struct rt_schedulable_data data = { .tg = tg, .rt_period = period, .rt_runtime = runtime, }; rcu_read_lock(); ret = walk_tg_tree(tg_rt_schedulable, tg_nop, &data); rcu_read_unlock(); return ret; } static int tg_set_rt_bandwidth(struct task_group *tg, u64 rt_period, u64 rt_runtime) { int i, err = 0; mutex_lock(&rt_constraints_mutex); read_lock(&tasklist_lock); err = __rt_schedulable(tg, rt_period, rt_runtime); if (err) goto unlock; raw_spin_lock_irq(&tg->rt_bandwidth.rt_runtime_lock); tg->rt_bandwidth.rt_period = ns_to_ktime(rt_period); tg->rt_bandwidth.rt_runtime = rt_runtime; for_each_possible_cpu(i) { struct rt_rq *rt_rq = tg->rt_rq[i]; raw_spin_lock(&rt_rq->rt_runtime_lock); rt_rq->rt_runtime = rt_runtime; raw_spin_unlock(&rt_rq->rt_runtime_lock); } raw_spin_unlock_irq(&tg->rt_bandwidth.rt_runtime_lock); unlock: read_unlock(&tasklist_lock); mutex_unlock(&rt_constraints_mutex); return err; } int sched_group_set_rt_runtime(struct task_group *tg, long rt_runtime_us) { u64 rt_runtime, rt_period; rt_period = ktime_to_ns(tg->rt_bandwidth.rt_period); rt_runtime = (u64)rt_runtime_us * NSEC_PER_USEC; if (rt_runtime_us < 0) rt_runtime = RUNTIME_INF; return tg_set_rt_bandwidth(tg, rt_period, rt_runtime); } long sched_group_rt_runtime(struct task_group *tg) { u64 rt_runtime_us; if (tg->rt_bandwidth.rt_runtime == RUNTIME_INF) return -1; rt_runtime_us = tg->rt_bandwidth.rt_runtime; do_div(rt_runtime_us, NSEC_PER_USEC); return rt_runtime_us; } int sched_group_set_rt_period(struct task_group *tg, long rt_period_us) { u64 rt_runtime, rt_period; rt_period = (u64)rt_period_us * NSEC_PER_USEC; rt_runtime = tg->rt_bandwidth.rt_runtime; if (rt_period == 0) return -EINVAL; return tg_set_rt_bandwidth(tg, rt_period, rt_runtime); } long sched_group_rt_period(struct task_group *tg) { u64 rt_period_us; rt_period_us = ktime_to_ns(tg->rt_bandwidth.rt_period); do_div(rt_period_us, NSEC_PER_USEC); return rt_period_us; } static int sched_rt_global_constraints(void) { u64 runtime, period; int ret = 0; if (sysctl_sched_rt_period <= 0) return -EINVAL; runtime = global_rt_runtime(); period = global_rt_period(); /* * Sanity check on the sysctl variables. */ if (runtime > period && runtime != RUNTIME_INF) return -EINVAL; mutex_lock(&rt_constraints_mutex); read_lock(&tasklist_lock); ret = __rt_schedulable(NULL, 0, 0); read_unlock(&tasklist_lock); mutex_unlock(&rt_constraints_mutex); return ret; } int sched_rt_can_attach(struct task_group *tg, struct task_struct *tsk) { /* Don't accept realtime tasks when there is no way for them to run */ if (rt_task(tsk) && tg->rt_bandwidth.rt_runtime == 0) return 0; return 1; } #else /* !CONFIG_RT_GROUP_SCHED */ static int sched_rt_global_constraints(void) { unsigned long flags; int i; if (sysctl_sched_rt_period <= 0) return -EINVAL; /* * There's always some RT tasks in the root group * -- migration, kstopmachine etc.. */ if (sysctl_sched_rt_runtime == 0) return -EBUSY; raw_spin_lock_irqsave(&def_rt_bandwidth.rt_runtime_lock, flags); for_each_possible_cpu(i) { struct rt_rq *rt_rq = &cpu_rq(i)->rt; raw_spin_lock(&rt_rq->rt_runtime_lock); rt_rq->rt_runtime = global_rt_runtime(); raw_spin_unlock(&rt_rq->rt_runtime_lock); } raw_spin_unlock_irqrestore(&def_rt_bandwidth.rt_runtime_lock, flags); return 0; } #endif /* CONFIG_RT_GROUP_SCHED */ int sched_rt_handler(struct ctl_table *table, int write, void __user *buffer, size_t *lenp, loff_t *ppos) { int ret; int old_period, old_runtime; static DEFINE_MUTEX(mutex); mutex_lock(&mutex); old_period = sysctl_sched_rt_period; old_runtime = sysctl_sched_rt_runtime; ret = proc_dointvec(table, write, buffer, lenp, ppos); if (!ret && write) { ret = sched_rt_global_constraints(); if (ret) { sysctl_sched_rt_period = old_period; sysctl_sched_rt_runtime = old_runtime; } else { def_rt_bandwidth.rt_runtime = global_rt_runtime(); def_rt_bandwidth.rt_period = ns_to_ktime(global_rt_period()); } } mutex_unlock(&mutex); return ret; } #ifdef CONFIG_CGROUP_SCHED /* return corresponding task_group object of a cgroup */ static inline struct task_group *cgroup_tg(struct cgroup *cgrp) { return container_of(cgroup_subsys_state(cgrp, cpu_cgroup_subsys_id), struct task_group, css); } static struct cgroup_subsys_state *cpu_cgroup_create(struct cgroup *cgrp) { struct task_group *tg, *parent; if (!cgrp->parent) { /* This is early initialization for the top cgroup */ return &root_task_group.css; } parent = cgroup_tg(cgrp->parent); tg = sched_create_group(parent); if (IS_ERR(tg)) return ERR_PTR(-ENOMEM); return &tg->css; } static void cpu_cgroup_destroy(struct cgroup *cgrp) { struct task_group *tg = cgroup_tg(cgrp); sched_destroy_group(tg); } static int cpu_cgroup_allow_attach(struct cgroup *cgrp, struct cgroup_taskset *tset) { const struct cred *cred = current_cred(), *tcred; struct task_struct *task; cgroup_taskset_for_each(task, cgrp, tset) { tcred = __task_cred(task); if ((current != task) && !capable(CAP_SYS_NICE) && cred->euid != tcred->uid && cred->euid != tcred->suid) return -EACCES; } return 0; } static int cpu_cgroup_can_attach(struct cgroup *cgrp, struct cgroup_taskset *tset) { struct task_struct *task; cgroup_taskset_for_each(task, cgrp, tset) { #ifdef CONFIG_RT_GROUP_SCHED if (!sched_rt_can_attach(cgroup_tg(cgrp), task)) return -EINVAL; #else /* We don't support RT-tasks being in separate groups */ if (task->sched_class != &fair_sched_class) return -EINVAL; #endif } return 0; } static void cpu_cgroup_attach(struct cgroup *cgrp, struct cgroup_taskset *tset) { struct task_struct *task; cgroup_taskset_for_each(task, cgrp, tset) sched_move_task(task); } static void cpu_cgroup_exit(struct cgroup *cgrp, struct cgroup *old_cgrp, struct task_struct *task) { /* * cgroup_exit() is called in the copy_process() failure path. * Ignore this case since the task hasn't ran yet, this avoids * trying to poke a half freed task state from generic code. */ if (!(task->flags & PF_EXITING)) return; sched_move_task(task); } static u64 cpu_notify_on_migrate_read_u64(struct cgroup *cgrp, struct cftype *cft) { struct task_group *tg = cgroup_tg(cgrp); return tg->notify_on_migrate; } static int cpu_notify_on_migrate_write_u64(struct cgroup *cgrp, struct cftype *cft, u64 notify) { struct task_group *tg = cgroup_tg(cgrp); tg->notify_on_migrate = (notify > 0); return 0; } #ifdef CONFIG_FAIR_GROUP_SCHED static int cpu_shares_write_u64(struct cgroup *cgrp, struct cftype *cftype, u64 shareval) { return sched_group_set_shares(cgroup_tg(cgrp), scale_load(shareval)); } static u64 cpu_shares_read_u64(struct cgroup *cgrp, struct cftype *cft) { struct task_group *tg = cgroup_tg(cgrp); return (u64) scale_load_down(tg->shares); } #ifdef CONFIG_CFS_BANDWIDTH static DEFINE_MUTEX(cfs_constraints_mutex); const u64 max_cfs_quota_period = 1 * NSEC_PER_SEC; /* 1s */ const u64 min_cfs_quota_period = 1 * NSEC_PER_MSEC; /* 1ms */ static int __cfs_schedulable(struct task_group *tg, u64 period, u64 runtime); static int tg_set_cfs_bandwidth(struct task_group *tg, u64 period, u64 quota) { int i, ret = 0, runtime_enabled, runtime_was_enabled; struct cfs_bandwidth *cfs_b = &tg->cfs_bandwidth; if (tg == &root_task_group) return -EINVAL; /* * Ensure we have at some amount of bandwidth every period. This is * to prevent reaching a state of large arrears when throttled via * entity_tick() resulting in prolonged exit starvation. */ if (quota < min_cfs_quota_period || period < min_cfs_quota_period) return -EINVAL; /* * Likewise, bound things on the otherside by preventing insane quota * periods. This also allows us to normalize in computing quota * feasibility. */ if (period > max_cfs_quota_period) return -EINVAL; mutex_lock(&cfs_constraints_mutex); ret = __cfs_schedulable(tg, period, quota); if (ret) goto out_unlock; runtime_enabled = quota != RUNTIME_INF; runtime_was_enabled = cfs_b->quota != RUNTIME_INF; /* * If we need to toggle cfs_bandwidth_used, off->on must occur * before making related changes, and on->off must occur afterwards */ if (runtime_enabled && !runtime_was_enabled) cfs_bandwidth_usage_inc(); raw_spin_lock_irq(&cfs_b->lock); cfs_b->period = ns_to_ktime(period); cfs_b->quota = quota; __refill_cfs_bandwidth_runtime(cfs_b); /* restart the period timer (if active) to handle new period expiry */ if (runtime_enabled && cfs_b->timer_active) { /* force a reprogram */ cfs_b->timer_active = 0; __start_cfs_bandwidth(cfs_b); } raw_spin_unlock_irq(&cfs_b->lock); for_each_possible_cpu(i) { struct cfs_rq *cfs_rq = tg->cfs_rq[i]; struct rq *rq = cfs_rq->rq; raw_spin_lock_irq(&rq->lock); cfs_rq->runtime_enabled = runtime_enabled; cfs_rq->runtime_remaining = 0; if (cfs_rq->throttled) unthrottle_cfs_rq(cfs_rq); raw_spin_unlock_irq(&rq->lock); } if (runtime_was_enabled && !runtime_enabled) cfs_bandwidth_usage_dec(); out_unlock: mutex_unlock(&cfs_constraints_mutex); return ret; } int tg_set_cfs_quota(struct task_group *tg, long cfs_quota_us) { u64 quota, period; period = ktime_to_ns(tg->cfs_bandwidth.period); if (cfs_quota_us < 0) quota = RUNTIME_INF; else quota = (u64)cfs_quota_us * NSEC_PER_USEC; return tg_set_cfs_bandwidth(tg, period, quota); } long tg_get_cfs_quota(struct task_group *tg) { u64 quota_us; if (tg->cfs_bandwidth.quota == RUNTIME_INF) return -1; quota_us = tg->cfs_bandwidth.quota; do_div(quota_us, NSEC_PER_USEC); return quota_us; } int tg_set_cfs_period(struct task_group *tg, long cfs_period_us) { u64 quota, period; period = (u64)cfs_period_us * NSEC_PER_USEC; quota = tg->cfs_bandwidth.quota; return tg_set_cfs_bandwidth(tg, period, quota); } long tg_get_cfs_period(struct task_group *tg) { u64 cfs_period_us; cfs_period_us = ktime_to_ns(tg->cfs_bandwidth.period); do_div(cfs_period_us, NSEC_PER_USEC); return cfs_period_us; } static s64 cpu_cfs_quota_read_s64(struct cgroup *cgrp, struct cftype *cft) { return tg_get_cfs_quota(cgroup_tg(cgrp)); } static int cpu_cfs_quota_write_s64(struct cgroup *cgrp, struct cftype *cftype, s64 cfs_quota_us) { return tg_set_cfs_quota(cgroup_tg(cgrp), cfs_quota_us); } static u64 cpu_cfs_period_read_u64(struct cgroup *cgrp, struct cftype *cft) { return tg_get_cfs_period(cgroup_tg(cgrp)); } static int cpu_cfs_period_write_u64(struct cgroup *cgrp, struct cftype *cftype, u64 cfs_period_us) { return tg_set_cfs_period(cgroup_tg(cgrp), cfs_period_us); } struct cfs_schedulable_data { struct task_group *tg; u64 period, quota; }; /* * normalize group quota/period to be quota/max_period * note: units are usecs */ static u64 normalize_cfs_quota(struct task_group *tg, struct cfs_schedulable_data *d) { u64 quota, period; if (tg == d->tg) { period = d->period; quota = d->quota; } else { period = tg_get_cfs_period(tg); quota = tg_get_cfs_quota(tg); } /* note: these should typically be equivalent */ if (quota == RUNTIME_INF || quota == -1) return RUNTIME_INF; return to_ratio(period, quota); } static int tg_cfs_schedulable_down(struct task_group *tg, void *data) { struct cfs_schedulable_data *d = data; struct cfs_bandwidth *cfs_b = &tg->cfs_bandwidth; s64 quota = 0, parent_quota = -1; if (!tg->parent) { quota = RUNTIME_INF; } else { struct cfs_bandwidth *parent_b = &tg->parent->cfs_bandwidth; quota = normalize_cfs_quota(tg, d); parent_quota = parent_b->hierarchal_quota; /* * ensure max(child_quota) <= parent_quota, inherit when no * limit is set */ if (quota == RUNTIME_INF) quota = parent_quota; else if (parent_quota != RUNTIME_INF && quota > parent_quota) return -EINVAL; } cfs_b->hierarchal_quota = quota; return 0; } static int __cfs_schedulable(struct task_group *tg, u64 period, u64 quota) { int ret; struct cfs_schedulable_data data = { .tg = tg, .period = period, .quota = quota, }; if (quota != RUNTIME_INF) { do_div(data.period, NSEC_PER_USEC); do_div(data.quota, NSEC_PER_USEC); } rcu_read_lock(); ret = walk_tg_tree(tg_cfs_schedulable_down, tg_nop, &data); rcu_read_unlock(); return ret; } static int cpu_stats_show(struct cgroup *cgrp, struct cftype *cft, struct cgroup_map_cb *cb) { struct task_group *tg = cgroup_tg(cgrp); struct cfs_bandwidth *cfs_b = &tg->cfs_bandwidth; cb->fill(cb, "nr_periods", cfs_b->nr_periods); cb->fill(cb, "nr_throttled", cfs_b->nr_throttled); cb->fill(cb, "throttled_time", cfs_b->throttled_time); return 0; } #endif /* CONFIG_CFS_BANDWIDTH */ #endif /* CONFIG_FAIR_GROUP_SCHED */ #ifdef CONFIG_RT_GROUP_SCHED static int cpu_rt_runtime_write(struct cgroup *cgrp, struct cftype *cft, s64 val) { return sched_group_set_rt_runtime(cgroup_tg(cgrp), val); } static s64 cpu_rt_runtime_read(struct cgroup *cgrp, struct cftype *cft) { return sched_group_rt_runtime(cgroup_tg(cgrp)); } static int cpu_rt_period_write_uint(struct cgroup *cgrp, struct cftype *cftype, u64 rt_period_us) { return sched_group_set_rt_period(cgroup_tg(cgrp), rt_period_us); } static u64 cpu_rt_period_read_uint(struct cgroup *cgrp, struct cftype *cft) { return sched_group_rt_period(cgroup_tg(cgrp)); } #endif /* CONFIG_RT_GROUP_SCHED */ static struct cftype cpu_files[] = { { .name = "notify_on_migrate", .read_u64 = cpu_notify_on_migrate_read_u64, .write_u64 = cpu_notify_on_migrate_write_u64, }, #ifdef CONFIG_FAIR_GROUP_SCHED { .name = "shares", .read_u64 = cpu_shares_read_u64, .write_u64 = cpu_shares_write_u64, }, #endif #ifdef CONFIG_CFS_BANDWIDTH { .name = "cfs_quota_us", .read_s64 = cpu_cfs_quota_read_s64, .write_s64 = cpu_cfs_quota_write_s64, }, { .name = "cfs_period_us", .read_u64 = cpu_cfs_period_read_u64, .write_u64 = cpu_cfs_period_write_u64, }, { .name = "stat", .read_map = cpu_stats_show, }, #endif #ifdef CONFIG_RT_GROUP_SCHED { .name = "rt_runtime_us", .read_s64 = cpu_rt_runtime_read, .write_s64 = cpu_rt_runtime_write, }, { .name = "rt_period_us", .read_u64 = cpu_rt_period_read_uint, .write_u64 = cpu_rt_period_write_uint, }, #endif }; static int cpu_cgroup_populate(struct cgroup_subsys *ss, struct cgroup *cont) { return cgroup_add_files(cont, ss, cpu_files, ARRAY_SIZE(cpu_files)); } struct cgroup_subsys cpu_cgroup_subsys = { .name = "cpu", .create = cpu_cgroup_create, .destroy = cpu_cgroup_destroy, .can_attach = cpu_cgroup_can_attach, .attach = cpu_cgroup_attach, .allow_attach = cpu_cgroup_allow_attach, .exit = cpu_cgroup_exit, .populate = cpu_cgroup_populate, .subsys_id = cpu_cgroup_subsys_id, .early_init = 1, }; #endif /* CONFIG_CGROUP_SCHED */ #ifdef CONFIG_CGROUP_CPUACCT /* * CPU accounting code for task groups. * * Based on the work by Paul Menage (menage@google.com) and Balbir Singh * (balbir@in.ibm.com). */ /* create a new cpu accounting group */ static struct cgroup_subsys_state *cpuacct_create(struct cgroup *cgrp) { struct cpuacct *ca; if (!cgrp->parent) return &root_cpuacct.css; ca = kzalloc(sizeof(*ca), GFP_KERNEL); if (!ca) goto out; ca->cpuusage = alloc_percpu(u64); if (!ca->cpuusage) goto out_free_ca; ca->cpustat = alloc_percpu(struct kernel_cpustat); if (!ca->cpustat) goto out_free_cpuusage; return &ca->css; out_free_cpuusage: free_percpu(ca->cpuusage); out_free_ca: kfree(ca); out: return ERR_PTR(-ENOMEM); } /* destroy an existing cpu accounting group */ static void cpuacct_destroy(struct cgroup *cgrp) { struct cpuacct *ca = cgroup_ca(cgrp); free_percpu(ca->cpustat); free_percpu(ca->cpuusage); kfree(ca); } static u64 cpuacct_cpuusage_read(struct cpuacct *ca, int cpu) { u64 *cpuusage = per_cpu_ptr(ca->cpuusage, cpu); u64 data; #ifndef CONFIG_64BIT /* * Take rq->lock to make 64-bit read safe on 32-bit platforms. */ raw_spin_lock_irq(&cpu_rq(cpu)->lock); data = *cpuusage; raw_spin_unlock_irq(&cpu_rq(cpu)->lock); #else data = *cpuusage; #endif return data; } static void cpuacct_cpuusage_write(struct cpuacct *ca, int cpu, u64 val) { u64 *cpuusage = per_cpu_ptr(ca->cpuusage, cpu); #ifndef CONFIG_64BIT /* * Take rq->lock to make 64-bit write safe on 32-bit platforms. */ raw_spin_lock_irq(&cpu_rq(cpu)->lock); *cpuusage = val; raw_spin_unlock_irq(&cpu_rq(cpu)->lock); #else *cpuusage = val; #endif } /* return total cpu usage (in nanoseconds) of a group */ static u64 cpuusage_read(struct cgroup *cgrp, struct cftype *cft) { struct cpuacct *ca = cgroup_ca(cgrp); u64 totalcpuusage = 0; int i; for_each_present_cpu(i) totalcpuusage += cpuacct_cpuusage_read(ca, i); return totalcpuusage; } static int cpuusage_write(struct cgroup *cgrp, struct cftype *cftype, u64 reset) { struct cpuacct *ca = cgroup_ca(cgrp); int err = 0; int i; if (reset) { err = -EINVAL; goto out; } for_each_present_cpu(i) cpuacct_cpuusage_write(ca, i, 0); out: return err; } static int cpuacct_percpu_seq_read(struct cgroup *cgroup, struct cftype *cft, struct seq_file *m) { struct cpuacct *ca = cgroup_ca(cgroup); u64 percpu; int i; for_each_present_cpu(i) { percpu = cpuacct_cpuusage_read(ca, i); seq_printf(m, "%llu ", (unsigned long long) percpu); } seq_printf(m, "\n"); return 0; } static const char *cpuacct_stat_desc[] = { [CPUACCT_STAT_USER] = "user", [CPUACCT_STAT_SYSTEM] = "system", }; static int cpuacct_stats_show(struct cgroup *cgrp, struct cftype *cft, struct cgroup_map_cb *cb) { struct cpuacct *ca = cgroup_ca(cgrp); int cpu; s64 val = 0; for_each_online_cpu(cpu) { struct kernel_cpustat *kcpustat = per_cpu_ptr(ca->cpustat, cpu); val += kcpustat->cpustat[CPUTIME_USER]; val += kcpustat->cpustat[CPUTIME_NICE]; } val = cputime64_to_clock_t(val); cb->fill(cb, cpuacct_stat_desc[CPUACCT_STAT_USER], val); val = 0; for_each_online_cpu(cpu) { struct kernel_cpustat *kcpustat = per_cpu_ptr(ca->cpustat, cpu); val += kcpustat->cpustat[CPUTIME_SYSTEM]; val += kcpustat->cpustat[CPUTIME_IRQ]; val += kcpustat->cpustat[CPUTIME_SOFTIRQ]; } val = cputime64_to_clock_t(val); cb->fill(cb, cpuacct_stat_desc[CPUACCT_STAT_SYSTEM], val); return 0; } static struct cftype files[] = { { .name = "usage", .read_u64 = cpuusage_read, .write_u64 = cpuusage_write, }, { .name = "usage_percpu", .read_seq_string = cpuacct_percpu_seq_read, }, { .name = "stat", .read_map = cpuacct_stats_show, }, }; static int cpuacct_populate(struct cgroup_subsys *ss, struct cgroup *cgrp) { return cgroup_add_files(cgrp, ss, files, ARRAY_SIZE(files)); } /* * charge this task's execution time to its accounting group. * * called with rq->lock held. */ void cpuacct_charge(struct task_struct *tsk, u64 cputime) { struct cpuacct *ca; int cpu; if (unlikely(!cpuacct_subsys.active)) return; cpu = task_cpu(tsk); rcu_read_lock(); ca = task_ca(tsk); for (; ca; ca = parent_ca(ca)) { u64 *cpuusage = per_cpu_ptr(ca->cpuusage, cpu); *cpuusage += cputime; } rcu_read_unlock(); } struct cgroup_subsys cpuacct_subsys = { .name = "cpuacct", .create = cpuacct_create, .destroy = cpuacct_destroy, .populate = cpuacct_populate, .subsys_id = cpuacct_subsys_id, }; #endif /* CONFIG_CGROUP_CPUACCT */
SlimSaber/kernel_sony_msm8974
kernel/sched/core.c
C
gpl-2.0
211,543
import os from unipath import Path try: # expect at ~/source/tshilo-dikotla/etc/default.cnf # etc folder is not in the git repo PATH = Path(os.path.dirname(os.path.realpath(__file__))).ancestor( 1).child('etc') if not os.path.exists(PATH): raise TypeError( 'Path to database credentials at \'{}\' does not exist'.format(PATH)) with open(os.path.join(PATH, 'secret_key.txt')) as f: PRODUCTION_SECRET_KEY = f.read().strip() PRODUCTION_POSTGRES = { 'default': { 'ENGINE': 'django.db.backends.mysql', 'OPTIONS': { 'read_default_file': os.path.join(PATH, 'default.cnf'), }, 'HOST': '', 'PORT': '', 'ATOMIC_REQUESTS': True, }, # 'lab_api': { # 'ENGINE': 'django.db.backends.mysql', # 'OPTIONS': { # 'read_default_file': os.path.join(PATH, 'lab_api.cnf'), # }, # 'HOST': '', # 'PORT': '', # 'ATOMIC_REQUESTS': True, # }, } except TypeError: PRODUCTION_POSTGRES = None PRODUCTION_SECRET_KEY = None print('Path to production database credentials does not exist') TRAVIS_POSTGRES = { 'default': { 'ENGINE': 'django.db.backends.mysql', 'NAME': 'td', 'USER': 'travis', 'HOST': '', 'PORT': '', 'ATOMIC_REQUESTS': True, }, 'lab_api': { 'ENGINE': 'django.db.backends.mysql', 'NAME': 'td_lab', 'USER': 'travis', 'HOST': '', 'PORT': '', 'ATOMIC_REQUESTS': True, }, 'test_server': { 'ENGINE': 'django.db.backends.mysql', 'NAME': 'td_test', 'USER': 'travis', 'HOST': '', 'PORT': '', 'ATOMIC_REQUESTS': True, }, } TEST_HOSTS_POSTGRES = { 'default': { 'ENGINE': 'django.db.backends.postgresql_psycopg2', 'NAME': 'td', 'USER': 'django', 'PASSWORD': 'django', 'HOST': '', 'PORT': '', 'ATOMIC_REQUESTS': True, }, 'lab_api': { 'ENGINE': 'django.db.backends.postgresql_psycopg2', 'NAME': 'td_lab', 'USER': 'django', 'PASSWORD': 'django', 'HOST': '', 'PORT': '', 'ATOMIC_REQUESTS': True, }, }
botswana-harvard/tshilo-dikotla
tshilo_dikotla/databases.py
Python
gpl-2.0
2,422
/** * @file * File with JS to initialize jQuery plugins on fields. */ (function($){ Drupal.behaviors.field_timer = { attach: function() { var settings = drupalSettings.field_timer; if ($.countdown != undefined) { $.countdown.setDefaults($.countdown.regionalOptions['']); } for (var key in settings) { var options = settings[key].settings; var $item = $('#' + key); var timestamp = $item.data('timestamp'); switch (settings[key].plugin) { case 'county': $item.once('field-timer').each(function() { $(this).county($.extend({endDateTime: new Date(timestamp * 1000)}, options)); }); break; case 'jquery.countdown': $item.once('field-timer').each(function() { $(this).countdown($.extend( options, { until: (options.until ? new Date(timestamp * 1000) : null), since: (options.since ? new Date(timestamp * 1000) : null) }, $.countdown.regionalOptions[options.regional] )); }); break; case 'jquery.countdown.led': $item.once('field-timer').each(function() { $(this).countdown({ until: (options.until ? new Date(timestamp * 1000) : null), since: (options.since ? new Date(timestamp * 1000) : null), layout: $item.html() }); }); break; } } } } })(jQuery);
blakefrederick/sas-backend
modules/field_timer/js/field_timer.js
JavaScript
gpl-2.0
1,598
/* * (C) 2007-2010 Alibaba Group Holding Limited. * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License version 2 as * published by the Free Software Foundation. * * * Version: $Id: test_batch_read.cpp 44 2010-11-12 07:43:00Z chuyu@taobao.com $ * * Authors: * qushan <qushan@taobao.com> * - initial release * */ #include "util.h" #include "thread.h" #include "common/func.h" #include "client/tfs_client_api.h" #include <vector> #include <algorithm> #include <functional> using namespace KFS; using namespace tfs::client; using namespace tfs::common; static int32_t m_stop = 0; void sign_handler(int32_t sig) { switch (sig) { case SIGINT: m_stop = 1; break; } } #define FILE_NAME_LEN 18 void* read_worker(void* arg) { ThreadParam param = *(ThreadParam*) (arg); char file_list_name[100]; sprintf(file_list_name, "wf_%d", param.index_); FILE* input_fd = fopen(file_list_name, "rb"); if (NULL == input_fd) { printf("index(%d) open read file failed, exit\n", param.index_); return NULL; } /* param.locker_->lock(); TfsSession session; session.init((char*) param.conf_.c_str()); param.locker_->unlock(); TfsFile tfs_file; tfs_file.set_session(&session); */ printf("init connection to nameserver:%s\n", param.ns_ip_port_.c_str()); TfsClient tfsclient; int iret = tfsclient.initialize(param.ns_ip_port_); if (iret == TFS_ERROR) { return NULL; } Timer timer; Stater stater("read"); const int32_t BUFLEN = 32; char name_buf[BUFLEN]; int32_t failed_count = 0; int32_t zoomed_count = 0; int32_t total_count = 0; int64_t time_start = Func::curr_time(); int64_t time_consumed = 0, min_time_consumed = 0, max_time_consumed = 0, accumlate_time_consumed = 0; // 1M file number, each 18 bit, total 18M vector < std::string > write_file_list; while (fgets(name_buf, BUFLEN, input_fd)) { ssize_t endpos = strlen(name_buf) - 1; while (name_buf[endpos] == '\n') { name_buf[endpos] = 0; --endpos; } write_file_list.push_back(name_buf); } fclose(input_fd); //random read if (param.random_) { vector<std::string>::iterator start = write_file_list.begin(); vector<std::string>::iterator end = write_file_list.end(); random_shuffle(start, end); } bool read_image = false; bool image_scale_random = false; if ((param.max_size_ != 0) && (param.min_size_ != 0)) { read_image = true; } if (param.max_size_ != param.min_size_) { image_scale_random = true; } vector<std::string>::iterator vit = write_file_list.begin(); for (; vit != write_file_list.end(); vit++) { if (m_stop) { break; } if ((param.file_count_ > 0) && (total_count >= param.file_count_)) { break; } timer.start(); int32_t ret = 0; bool zoomed = true; if (read_image) { if (image_scale_random) { srand(time(NULL) + rand() + pthread_self()); int32_t min_width = (param.max_size_ / 6); int32_t min_height = (param.min_size_ / 6); int32_t scale_width = rand() % (param.max_size_ - min_width) + min_width; int32_t scale_height = rand() % (param.min_size_ - min_height) + min_height; ret = copy_file_v3(tfsclient, (char *) (*vit).c_str(), scale_width, scale_height, -1, zoomed); if (zoomed) { ++zoomed_count; } } } else { ret = copy_file_v2(tfsclient, (char *) (*vit).c_str(), -1); } if (ret != TFS_SUCCESS) { printf("read file fail %s ret : %d\n", (*vit).c_str(), ret); ++failed_count; } else { time_consumed = timer.consume(); stater.stat_time_count(time_consumed); if (total_count == 0) { min_time_consumed = time_consumed; } if (time_consumed < min_time_consumed) { min_time_consumed = time_consumed; } if (time_consumed > max_time_consumed) { max_time_consumed = time_consumed; } accumlate_time_consumed += time_consumed; } if (param.profile_) { printf("read file (%s), (%s)\n", (*vit).c_str(), ret == TFS_SUCCESS ? "success" : "failed"); print_rate(ret, time_consumed); } ++total_count; } uint32_t total_succ_count = total_count - failed_count; ((ThreadParam*) arg)->file_count_ = total_succ_count; int64_t time_stop = Func::curr_time(); time_consumed = time_stop - time_start; double iops = static_cast<double> (total_succ_count) / (static_cast<double> (time_consumed) / 1000000); double rate = static_cast<double> (time_consumed) / total_succ_count; double aiops = static_cast<double> (total_succ_count) / (static_cast<double> (accumlate_time_consumed) / 1000000); double arate = static_cast<double> (accumlate_time_consumed) / total_succ_count; printf("thread index:%5d count:%5d failed:%5d, zoomed:%5d, filesize:%6d iops:%10.3f rate:%10.3f ," " min:%" PRI64_PREFIX "d, max:%" PRI64_PREFIX "d,avg:%" PRI64_PREFIX "d aiops:%10.3f, arate:%10.3f \n", param.index_, total_count, failed_count, zoomed_count, param.file_size_, iops, rate, min_time_consumed, max_time_consumed, accumlate_time_consumed / total_succ_count, aiops, arate); stater.dump_time_stat(); return NULL; } int main(int argc, char* argv[]) { int32_t thread_count = 1; ThreadParam input_param; int32_t ret = fetch_input_opt(argc, argv, input_param, thread_count); if (ret != TFS_SUCCESS || input_param.ns_ip_port_.empty() || thread_count > THREAD_SIZE) { printf("usage: -d -t \n"); exit(-1); } //if (thread_count > 0) ClientPoolCollect::setClientPoolCollectParam(thread_count,0,0); signal(SIGINT, sign_handler); MetaThread threads[THREAD_SIZE]; ThreadParam param[THREAD_SIZE]; tbsys::CThreadMutex glocker; int64_t time_start = Func::curr_time(); for (int32_t i = 0; i < thread_count; ++i) { param[i].index_ = i; param[i].conf_ = input_param.conf_; param[i].file_count_ = input_param.file_count_; param[i].file_size_ = input_param.file_size_; param[i].min_size_ = input_param.min_size_; param[i].max_size_ = input_param.max_size_; param[i].profile_ = input_param.profile_; param[i].random_ = input_param.random_; param[i].locker_ = &glocker; param[i].ns_ip_port_ = input_param.ns_ip_port_; threads[i].start(read_worker, (void*) &param[i]); } for (int32_t i = 0; i < thread_count; ++i) { threads[i].join(); } int32_t total_count = 0; for (int32_t i = 0; i < thread_count; ++i) { total_count += param[i].file_count_; } int64_t time_stop = Func::curr_time(); int64_t time_consumed = time_stop - time_start; double iops = static_cast<double>(total_count) / (static_cast<double>(time_consumed) / 1000000); double rate = static_cast<double>(time_consumed) / total_count; printf("read_thread count filesize iops rate\n"); printf("%10d %5d %9d %8.3f %12.3f \n", thread_count, total_count, input_param.file_size_, iops, rate); }
qqiangwu/annotated-tfs
tests/batch/test_batch_read.cpp
C++
gpl-2.0
7,158
/* X-Chat * Copyright (C) 1998 Peter Zelezny. * * 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 */ #include <stdio.h> #include <stdlib.h> #include <sys/types.h> #include <sys/stat.h> #include <unistd.h> #include <string.h> #include <fcntl.h> #include <ctype.h> #include "fe-gtk.h" #include <gtk/gtklabel.h> #include <gtk/gtkeditable.h> #include <gtk/gtkmenu.h> #include <gtk/gtkmenuitem.h> #include <gtk/gtkoptionmenu.h> #include <gtk/gtkvbox.h> #include <gtk/gtkhbox.h> #include <gtk/gtkclist.h> #include <gtk/gtknotebook.h> #include <gtk/gtkcheckbutton.h> #include <gtk/gtkentry.h> #include <gtk/gtkvscrollbar.h> #include "../common/xchat.h" #include "../common/xchatc.h" #include "../common/cfgfiles.h" #include "../common/fe.h" #include "../common/userlist.h" #include "../common/outbound.h" #include "../common/util.h" #include "../common/text.h" #include "../common/plugin.h" #include <gdk/gdkkeysyms.h> #include "gtkutil.h" #include "menu.h" #include "xtext.h" #include "palette.h" #include "maingui.h" #include "textgui.h" #include "fkeys.h" #ifdef USE_GTKSPELL #include <gtk/gtktextview.h> #endif static void replace_handle (GtkWidget * wid); void key_action_tab_clean (void); /***************** Key Binding Code ******************/ /* NOTES: To add a new action: 1) inc KEY_MAX_ACTIONS 2) write the function at the bottom of this file (with all the others) FIXME: Write about calling and returning 3) Add it to key_actions --AGL */ /* Remember that the *number* of actions is this *plus* 1 --AGL */ #define KEY_MAX_ACTIONS 14 /* These are cp'ed from history.c --AGL */ #define STATE_SHIFT GDK_SHIFT_MASK #define STATE_ALT GDK_MOD1_MASK #define STATE_CTRL GDK_CONTROL_MASK struct key_binding { int keyval; /* GDK keynumber */ char *keyname; /* String with the name of the function */ int action; /* Index into key_actions */ int mod; /* Flags of STATE_* above */ char *data1, *data2; /* Pointers to strings, these must be freed */ struct key_binding *next; }; struct key_action { int (*handler) (GtkWidget * wid, GdkEventKey * evt, char *d1, char *d2, struct session * sess); char *name; char *help; }; struct gcomp_data { char data[CHANLEN]; int elen; }; static int key_load_kbs (char *); static void key_load_defaults (); static void key_save_kbs (char *); static int key_action_handle_command (GtkWidget * wid, GdkEventKey * evt, char *d1, char *d2, struct session *sess); static int key_action_page_switch (GtkWidget * wid, GdkEventKey * evt, char *d1, char *d2, struct session *sess); int key_action_insert (GtkWidget * wid, GdkEventKey * evt, char *d1, char *d2, struct session *sess); static int key_action_scroll_page (GtkWidget * wid, GdkEventKey * evt, char *d1, char *d2, struct session *sess); static int key_action_set_buffer (GtkWidget * wid, GdkEventKey * evt, char *d1, char *d2, struct session *sess); static int key_action_history_up (GtkWidget * wid, GdkEventKey * evt, char *d1, char *d2, struct session *sess); static int key_action_history_down (GtkWidget * wid, GdkEventKey * evt, char *d1, char *d2, struct session *sess); static int key_action_tab_comp (GtkWidget * wid, GdkEventKey * evt, char *d1, char *d2, struct session *sess); static int key_action_comp_chng (GtkWidget * wid, GdkEventKey * evt, char *d1, char *d2, struct session *sess); static int key_action_replace (GtkWidget * wid, GdkEventKey * evt, char *d1, char *d2, struct session *sess); static int key_action_move_tab_left (GtkWidget * wid, GdkEventKey * evt, char *d1, char *d2, struct session *sess); static int key_action_move_tab_right (GtkWidget * wid, GdkEventKey * evt, char *d1, char *d2, struct session *sess); static int key_action_move_tab_family_left (GtkWidget * wid, GdkEventKey * evt, char *d1, char *d2, struct session *sess); static int key_action_move_tab_family_right (GtkWidget * wid, GdkEventKey * evt, char *d1, char *d2, struct session *sess); static int key_action_put_history (GtkWidget * wid, GdkEventKey * evt, char *d1, char *d2, struct session *sess); static GtkWidget *key_dialog; static struct key_binding *keys_root = NULL; static const struct key_action key_actions[KEY_MAX_ACTIONS + 1] = { {key_action_handle_command, "Run Command", N_("The \002Run Command\002 action runs the data in Data 1 as if it has been typed into the entry box where you pressed the key sequence. Thus it can contain text (which will be sent to the channel/person), commands or user commands. When run all \002\\n\002 characters in Data 1 are used to deliminate seperate commands so it is possible to run more than one command. If you want a \002\\\002 in the actual text run then enter \002\\\\\002")}, {key_action_page_switch, "Change Page", N_("The \002Change Page\002 command switches between pages in the notebook. Set Data 1 to the page you want to switch to. If Data 2 is set to anything then the switch will be relative to the current position")}, {key_action_insert, "Insert in Buffer", N_("The \002Insert in Buffer\002 command will insert the contents of Data 1 into the entry where the key sequence was pressed at the current cursor position")}, {key_action_scroll_page, "Scroll Page", N_("The \002Scroll Page\002 command scrolls the text widget up or down one page or one line. Set Data 1 to either Up, Down, +1 or -1.")}, {key_action_set_buffer, "Set Buffer", N_("The \002Set Buffer\002 command sets the entry where the key sequence was entered to the contents of Data 1")}, {key_action_history_up, "Last Command", N_("The \002Last Command\002 command sets the entry to contain the last command entered - the same as pressing up in a shell")}, {key_action_history_down, "Next Command", N_("The \002Next Command\002 command sets the entry to contain the next command entered - the same as pressing down in a shell")}, {key_action_tab_comp, "Complete nick/command", N_("This command changes the text in the entry to finish an incomplete nickname or command. If Data 1 is set then double-tabbing in a string will select the last nick, not the next")}, {key_action_comp_chng, "Change Selected Nick", N_("This command scrolls up and down through the list of nicks. If Data 1 is set to anything it will scroll up, else it scrolls down")}, {key_action_replace, "Check For Replace", N_("This command checks the last word entered in the entry against the replace list and replaces it if it finds a match")}, {key_action_move_tab_left, "Move front tab left", N_("This command moves the front tab left by one")}, {key_action_move_tab_right, "Move front tab right", N_("This command moves the front tab right by one")}, {key_action_move_tab_family_left, "Move tab family left", N_("This command moves the current tab family to the left")}, {key_action_move_tab_family_right, "Move tab family right", N_("This command moves the current tab family to the right")}, {key_action_put_history, "Push input line into history", N_("Push input line into history but doesn't send to server")}, }; void key_init () { keys_root = NULL; if (key_load_kbs (NULL) == 1) { key_load_defaults (); if (key_load_kbs (NULL) == 1) fe_message (_("There was an error loading key" " bindings configuration"), FE_MSG_ERROR); } } static char * key_get_key_name (int keyval) { return gdk_keyval_name (gdk_keyval_to_lower (keyval)); } /* Ok, here are the NOTES key_handle_key_press now handles all the key presses and history_keypress is now defunct. It goes thru the linked list keys_root and finds a matching key. It runs the action func and switches on these values: 0) Return 1) Find next 2) stop signal and return * history_keypress is now dead (and gone) * key_handle_key_press now takes its role * All the possible actions are in a struct called key_actions (in fkeys.c) * it is made of {function, name, desc} * key bindings can pass 2 *text* strings to the handler. If more options are nee ded a format can be put on one of these options * key actions are passed { the entry widget the Gdk event data 1 data 2 session struct } * key bindings are stored in a linked list of key_binding structs * which looks like { int keyval; GDK keynumber char *keyname; String with the name of the function int action; Index into key_actions int mod; Flags of STATE_* above char *data1, *data2; Pointers to strings, these must be freed struct key_binding *next; } * remember that is (data1 || data2) != NULL then they need to be free()'ed --AGL */ gboolean key_handle_key_press (GtkWidget *wid, GdkEventKey *evt, session *sess) { struct key_binding *kb, *last = NULL; int keyval = evt->keyval; int mod, n; GSList *list; /* where did this event come from? */ list = sess_list; while (list) { sess = list->data; if (sess->gui->input_box == wid) { if (sess->gui->is_tab) sess = current_tab; break; } list = list->next; } if (!list) return FALSE; current_sess = sess; if (plugin_emit_keypress (sess, evt->state, evt->keyval, evt->length, evt->string)) return 1; /* maybe the plugin closed this tab? */ if (!is_session (sess)) return 1; mod = evt->state & (STATE_CTRL | STATE_ALT | STATE_SHIFT); kb = keys_root; while (kb) { if (kb->keyval == keyval && kb->mod == mod) { if (kb->action < 0 || kb->action > KEY_MAX_ACTIONS) return 0; /* Bump this binding to the top of the list */ if (last != NULL) { last->next = kb->next; kb->next = keys_root; keys_root = kb; } /* Run the function */ n = key_actions[kb->action].handler (wid, evt, kb->data1, kb->data2, sess); switch (n) { case 0: return 1; case 2: g_signal_stop_emission_by_name (G_OBJECT (wid), "key_press_event"); return 1; } } last = kb; kb = kb->next; } switch (keyval) { case GDK_space: key_action_tab_clean (); break; #if defined(USE_GTKSPELL) /* gtktextview has no 'activate' event, so we trap ENTER here */ case GDK_Return: case GDK_KP_Enter: if (!(evt->state & GDK_CONTROL_MASK)) { g_signal_stop_emission_by_name (G_OBJECT (wid), "key_press_event"); mg_inputbox_cb (wid, sess->gui); } #endif } return 0; } /* Walks keys_root and free()'s everything */ /*static void key_free_all () { struct key_binding *cur, *next; cur = keys_root; while (cur) { next = cur->next; if (cur->data1) free (cur->data1); if (cur->data2) free (cur->data2); free (cur); cur = next; } keys_root = NULL; }*/ /* Turns mod flags into a C-A-S string */ static char * key_make_mod_str (int mod, char *buf) { int i = 0; if (mod & STATE_CTRL) { if (i) buf[i++] = '-'; buf[i++] = 'C'; } if (mod & STATE_ALT) { if (i) buf[i++] = '-'; buf[i++] = 'A'; } if (mod & STATE_SHIFT) { if (i) buf[i++] = '-'; buf[i++] = 'S'; } buf[i] = 0; return buf; } /* ***** GUI code here ******************* */ /* NOTE: The key_dialog defin is above --AGL */ static GtkWidget *key_dialog_act_menu, *key_dialog_kb_clist; static GtkWidget *key_dialog_tog_c, *key_dialog_tog_s, *key_dialog_tog_a; static GtkWidget *key_dialog_ent_key, *key_dialog_ent_d1, *key_dialog_ent_d2; static GtkWidget *key_dialog_text; static void key_load_defaults () { /* This is the default config */ #define defcfg \ "C\nPrior\nChange Page\nD1:-1\nD2:Relative\n\n"\ "C\nNext\nChange Page\nD1:1\nD2:Relative\n\n"\ "A\n9\nChange Page\nD1:9\nD2!\n\n"\ "A\n8\nChange Page\nD1:8\nD2!\n\n"\ "A\n7\nChange Page\nD1:7\nD2!\n\n"\ "A\n6\nChange Page\nD1:6\nD2!\n\n"\ "A\n5\nChange Page\nD1:5\nD2!\n\n"\ "A\n4\nChange Page\nD1:4\nD2!\n\n"\ "A\n3\nChange Page\nD1:3\nD2!\n\n"\ "A\n2\nChange Page\nD1:2\nD2!\n\n"\ "A\n1\nChange Page\nD1:1\nD2!\n\n"\ "C\no\nInsert in Buffer\nD1:\nD2!\n\n"\ "C\nb\nInsert in Buffer\nD1:\nD2!\n\n"\ "C\nk\nInsert in Buffer\nD1:\nD2!\n\n"\ "S\nNext\nChange Selected Nick\nD1!\nD2!\n\n"\ "S\nPrior\nChange Selected Nick\nD1:Up\nD2!\n\n"\ "None\nNext\nScroll Page\nD1:Down\nD2!\n\n"\ "None\nPrior\nScroll Page\nD1:Up\nD2!\n\n"\ "S\nDown\nScroll Page\nD1:+1\nD2!\n\n"\ "S\nUp\nScroll Page\nD1:-1\nD2!\n\n"\ "None\nDown\nNext Command\nD1!\nD2!\n\n"\ "None\nUp\nLast Command\nD1!\nD2!\n\n"\ "None\nTab\nComplete nick/command\nD1!\nD2!\n\n"\ "None\nspace\nCheck For Replace\nD1!\nD2!\n\n"\ "None\nReturn\nCheck For Replace\nD1!\nD2!\n\n"\ "None\nKP_Enter\nCheck For Replace\nD1!\nD2!\n\n"\ "C\nTab\nComplete nick/command\nD1:Up\nD2!\n\n"\ "A\nLeft\nMove front tab left\nD1!\nD2!\n\n"\ "A\nRight\nMove front tab right\nD1!\nD2!\n\n"\ "CS\nPrior\nMove tab family left\nD1!\nD2!\n\n"\ "CS\nNext\nMove tab family right\nD1!\nD2!\n\n"\ "None\nF9\nRun Command\nD1:/GUI MENU TOGGLE\nD2!\n\n" int fd; fd = xchat_open_file ("keybindings.conf", O_CREAT | O_TRUNC | O_WRONLY, 0x180, XOF_DOMODE); if (fd < 0) /* ???!!! */ return; write (fd, defcfg, strlen (defcfg)); close (fd); } static void key_dialog_close () { key_dialog = NULL; key_save_kbs (NULL); } static void key_dialog_add_new (GtkWidget * button, GtkCList * list) { gchar *strs[] = { "", NULL, NULL, NULL, NULL }; struct key_binding *kb; strs[1] = _("<none>"); strs[2] = _("<none>"); strs[3] = _("<none>"); strs[4] = _("<none>"); kb = malloc (sizeof (struct key_binding)); kb->keyval = 0; kb->keyname = NULL; kb->action = -1; kb->mod = 0; kb->data1 = kb->data2 = NULL; kb->next = keys_root; keys_root = kb; gtk_clist_set_row_data (GTK_CLIST (list), gtk_clist_append (GTK_CLIST (list), strs), kb); } static void key_dialog_delete (GtkWidget * button, GtkCList * list) { struct key_binding *kb, *cur, *last; int row = gtkutil_clist_selection ((GtkWidget *) list); if (row != -1) { kb = gtk_clist_get_row_data (list, row); cur = keys_root; last = NULL; while (cur) { if (cur == kb) { if (last) last->next = kb->next; else keys_root = kb->next; if (kb->data1) free (kb->data1); if (kb->data2) free (kb->data2); free (kb); gtk_clist_remove (list, row); return; } last = cur; cur = cur->next; } printf ("*** key_dialog_delete: couldn't find kb in list!\n"); /*if (getenv ("XCHAT_DEBUG")) abort ();*/ } } static void key_print_text (GtkXText *xtext, char *text) { unsigned int old = prefs.timestamp; prefs.timestamp = 0; /* temporarily disable stamps */ gtk_xtext_clear (GTK_XTEXT (xtext)->buffer, 0); PrintTextRaw (GTK_XTEXT (xtext)->buffer, text, 0, 0); prefs.timestamp = old; } static void key_dialog_sel_act (GtkWidget * un, int num) { int row = gtkutil_clist_selection (key_dialog_kb_clist); struct key_binding *kb; if (row != -1) { kb = gtk_clist_get_row_data (GTK_CLIST (key_dialog_kb_clist), row); kb->action = num; gtk_clist_set_text (GTK_CLIST (key_dialog_kb_clist), row, 2, _(key_actions[num].name)); if (key_actions[num].help) { key_print_text (GTK_XTEXT (key_dialog_text), _(key_actions[num].help)); } } } static void key_dialog_sel_row (GtkWidget * clist, gint row, gint column, GdkEventButton * evt, gpointer data) { struct key_binding *kb = gtk_clist_get_row_data (GTK_CLIST (clist), row); if (kb == NULL) { printf ("*** key_dialog_sel_row: kb == NULL\n"); abort (); } if (kb->action > -1 && kb->action <= KEY_MAX_ACTIONS) { gtk_option_menu_set_history (GTK_OPTION_MENU (key_dialog_act_menu), kb->action); if (key_actions[kb->action].help) { key_print_text (GTK_XTEXT (key_dialog_text), _(key_actions[kb->action].help)); } } gtk_toggle_button_set_active (GTK_TOGGLE_BUTTON (key_dialog_tog_c), (kb->mod & STATE_CTRL) == STATE_CTRL); gtk_toggle_button_set_active (GTK_TOGGLE_BUTTON (key_dialog_tog_s), (kb->mod & STATE_SHIFT) == STATE_SHIFT); gtk_toggle_button_set_active (GTK_TOGGLE_BUTTON (key_dialog_tog_a), (kb->mod & STATE_ALT) == STATE_ALT); if (kb->data1) gtk_entry_set_text (GTK_ENTRY (key_dialog_ent_d1), kb->data1); else gtk_entry_set_text (GTK_ENTRY (key_dialog_ent_d1), ""); if (kb->data2) gtk_entry_set_text (GTK_ENTRY (key_dialog_ent_d2), kb->data2); else gtk_entry_set_text (GTK_ENTRY (key_dialog_ent_d2), ""); if (kb->keyname) gtk_entry_set_text (GTK_ENTRY (key_dialog_ent_key), kb->keyname); else gtk_entry_set_text (GTK_ENTRY (key_dialog_ent_key), ""); } static void key_dialog_tog_key (GtkWidget * tog, int kstate) { int state = GTK_TOGGLE_BUTTON (tog)->active; int row = gtkutil_clist_selection (key_dialog_kb_clist); struct key_binding *kb; char buf[32]; if (row == -1) return; kb = gtk_clist_get_row_data (GTK_CLIST (key_dialog_kb_clist), row); if (state) kb->mod |= kstate; else kb->mod &= ~kstate; gtk_clist_set_text (GTK_CLIST (key_dialog_kb_clist), row, 0, key_make_mod_str (kb->mod, buf)); } static GtkWidget * key_dialog_make_toggle (char *label, void *callback, void *option, GtkWidget * box) { GtkWidget *wid; wid = gtk_check_button_new_with_label (label); gtk_toggle_button_set_active (GTK_TOGGLE_BUTTON (wid), 0); gtk_signal_connect (GTK_OBJECT (wid), "toggled", GTK_SIGNAL_FUNC (callback), option); gtk_box_pack_end (GTK_BOX (box), wid, 0, 0, 0); gtk_widget_show (wid); return wid; } static GtkWidget * key_dialog_make_entry (char *label, char *act, void *callback, void *option, GtkWidget * box) { GtkWidget *wid, *hbox;; hbox = gtk_hbox_new (0, 2); if (label) { wid = gtk_label_new (label); gtk_widget_show (wid); gtk_box_pack_start (GTK_BOX (hbox), wid, 0, 0, 0); } wid = gtk_entry_new (); if (act) { gtk_signal_connect (GTK_OBJECT (wid), act, GTK_SIGNAL_FUNC (callback), option); } gtk_box_pack_start (GTK_BOX (hbox), wid, 0, 0, 0); gtk_widget_show (wid); gtk_widget_show (hbox); gtk_box_pack_start (GTK_BOX (box), hbox, 0, 0, 0); return wid; } static void key_dialog_set_key (GtkWidget * entry, GdkEventKey * evt, void *none) { int row = gtkutil_clist_selection (key_dialog_kb_clist); struct key_binding *kb; gtk_entry_set_text (GTK_ENTRY (entry), ""); if (row == -1) return; kb = gtk_clist_get_row_data (GTK_CLIST (key_dialog_kb_clist), row); kb->keyval = evt->keyval; kb->keyname = key_get_key_name (kb->keyval); gtk_clist_set_text (GTK_CLIST (key_dialog_kb_clist), row, 1, kb->keyname); gtk_entry_set_text (GTK_ENTRY (entry), kb->keyname); g_signal_stop_emission_by_name (G_OBJECT (entry), "key_press_event"); } static void key_dialog_set_data (GtkWidget * entry, int d) { const char *text = gtk_entry_get_text (GTK_ENTRY (entry)); int row = gtkutil_clist_selection (key_dialog_kb_clist); struct key_binding *kb; char *buf; int len = strlen (text); len++; if (row == -1) return; kb = gtk_clist_get_row_data (GTK_CLIST (key_dialog_kb_clist), row); if (d == 0) { /* using data1 */ if (kb->data1) free (kb->data1); buf = (char *) malloc (len); memcpy (buf, text, len); kb->data1 = buf; gtk_clist_set_text (GTK_CLIST (key_dialog_kb_clist), row, 3, text); } else { if (kb->data2) free (kb->data2); buf = (char *) malloc (len); memcpy (buf, text, len); kb->data2 = buf; gtk_clist_set_text (GTK_CLIST (key_dialog_kb_clist), row, 4, text); } } void key_dialog_show () { GtkWidget *vbox, *hbox, *list, *vbox2, *wid, *wid2, *wid3, *hbox2; struct key_binding *kb; gchar *titles[] = { NULL, NULL, NULL, "1", "2" }; char temp[32]; int i; titles[0] = _("Mod"); titles[1] = _("Key"); titles[2] = _("Action"); if (key_dialog) { mg_bring_tofront (key_dialog); return; } key_dialog = mg_create_generic_tab ("editkeys", _("XChat: Keyboard Shortcuts"), TRUE, FALSE, key_dialog_close, NULL, 560, 330, &vbox, 0); hbox = gtk_hbox_new (0, 2); gtk_box_pack_start (GTK_BOX (vbox), hbox, 1, 1, 0); list = gtkutil_clist_new (5, titles, hbox, 0, key_dialog_sel_row, 0, NULL, 0, GTK_SELECTION_SINGLE); gtk_widget_set_usize (list, 400, 0); key_dialog_kb_clist = list; gtk_widget_show (hbox); kb = keys_root; gtk_clist_set_column_width (GTK_CLIST (list), 1, 50); gtk_clist_set_column_width (GTK_CLIST (list), 2, 120); gtk_clist_set_column_width (GTK_CLIST (list), 3, 50); gtk_clist_set_column_width (GTK_CLIST (list), 4, 50); while (kb) { titles[0] = key_make_mod_str (kb->mod, temp); titles[1] = kb->keyname; if (kb->action < 0 || kb->action > KEY_MAX_ACTIONS) titles[2] = _("<none>"); else titles[2] = key_actions[kb->action].name; if (kb->data1) titles[3] = kb->data1; else titles[3] = _("<none>"); if (kb->data2) titles[4] = kb->data2; else titles[4] = _("<none>"); gtk_clist_set_row_data (GTK_CLIST (list), gtk_clist_append (GTK_CLIST (list), titles), kb); kb = kb->next; } vbox2 = gtk_vbox_new (0, 2); gtk_box_pack_end (GTK_BOX (hbox), vbox2, 1, 1, 0); wid = gtk_button_new_with_label (_("Add New")); gtk_box_pack_start (GTK_BOX (vbox2), wid, 0, 0, 0); gtk_signal_connect (GTK_OBJECT (wid), "clicked", GTK_SIGNAL_FUNC (key_dialog_add_new), list); gtk_widget_show (wid); wid = gtk_button_new_with_label (_("Delete")); gtk_box_pack_start (GTK_BOX (vbox2), wid, 0, 0, 0); gtk_signal_connect (GTK_OBJECT (wid), "clicked", GTK_SIGNAL_FUNC (key_dialog_delete), list); gtk_widget_show (wid); gtk_widget_show (vbox2); wid = gtk_option_menu_new (); wid2 = gtk_menu_new (); for (i = 0; i <= KEY_MAX_ACTIONS; i++) { wid3 = gtk_menu_item_new_with_label (_(key_actions[i].name)); gtk_widget_show (wid3); gtk_menu_shell_append (GTK_MENU_SHELL (wid2), wid3); gtk_signal_connect (GTK_OBJECT (wid3), "activate", GTK_SIGNAL_FUNC (key_dialog_sel_act), GINT_TO_POINTER (i)); } gtk_option_menu_set_menu (GTK_OPTION_MENU (wid), wid2); gtk_option_menu_set_history (GTK_OPTION_MENU (wid), 0); gtk_box_pack_end (GTK_BOX (vbox2), wid, 0, 0, 0); gtk_widget_show (wid); key_dialog_act_menu = wid; key_dialog_tog_s = key_dialog_make_toggle (_("Shift"), key_dialog_tog_key, (void *) STATE_SHIFT, vbox2); key_dialog_tog_a = key_dialog_make_toggle (_("Alt"), key_dialog_tog_key, (void *) STATE_ALT, vbox2); key_dialog_tog_c = key_dialog_make_toggle (_("Ctrl"), key_dialog_tog_key, (void *) STATE_CTRL, vbox2); key_dialog_ent_key = key_dialog_make_entry (_("Key"), "key_press_event", key_dialog_set_key, NULL, vbox2); key_dialog_ent_d1 = key_dialog_make_entry (_("Data 1"), "activate", key_dialog_set_data, NULL, vbox2); key_dialog_ent_d2 = key_dialog_make_entry (_("Data 2"), "activate", key_dialog_set_data, (void *) 1, vbox2); hbox2 = gtk_hbox_new (0, 2); gtk_box_pack_end (GTK_BOX (vbox), hbox2, 0, 0, 1); wid = gtk_xtext_new (colors, 0); gtk_xtext_set_tint (GTK_XTEXT (wid), prefs.tint_red, prefs.tint_green, prefs.tint_blue); gtk_xtext_set_background (GTK_XTEXT (wid), channelwin_pix, prefs.transparent); gtk_widget_set_usize (wid, 0, 75); gtk_box_pack_start (GTK_BOX (hbox2), wid, 1, 1, 1); gtk_xtext_set_font (GTK_XTEXT (wid), prefs.font_normal); gtk_widget_show (wid); wid2 = gtk_vscrollbar_new (GTK_XTEXT (wid)->adj); gtk_box_pack_start (GTK_BOX (hbox2), wid2, 0, 0, 0); gtk_widget_show (wid2); gtk_widget_show (hbox2); key_dialog_text = wid; gtk_widget_show_all (key_dialog); } static void key_save_kbs (char *fn) { int fd, i; char buf[512]; struct key_binding *kb; if (!fn) fd = xchat_open_file ("keybindings.conf", O_CREAT | O_TRUNC | O_WRONLY, 0x180, XOF_DOMODE); else fd = xchat_open_file (fn, O_CREAT | O_TRUNC | O_WRONLY, 0x180, XOF_DOMODE | XOF_FULLPATH); if (fd < 0) { fe_message (_("Error opening keys config file\n"), FE_MSG_ERROR); return; } write (fd, buf, snprintf (buf, 510, "# XChat key bindings config file\n\n")); kb = keys_root; i = 0; while (kb) { if (kb->keyval == -1 || kb->keyname == NULL || kb->action < 0) { kb = kb->next; continue; } i = 0; if (kb->mod & STATE_CTRL) { i++; write (fd, "C", 1); } if (kb->mod & STATE_ALT) { i++; write (fd, "A", 1); } if (kb->mod & STATE_SHIFT) { i++; write (fd, "S", 1); } if (i == 0) write (fd, "None\n", 5); else write (fd, "\n", 1); write (fd, buf, snprintf (buf, 510, "%s\n%s\n", kb->keyname, key_actions[kb->action].name)); if (kb->data1 && kb->data1[0]) write (fd, buf, snprintf (buf, 510, "D1:%s\n", kb->data1)); else write (fd, "D1!\n", 4); if (kb->data2 && kb->data2[0]) write (fd, buf, snprintf (buf, 510, "D2:%s\n", kb->data2)); else write (fd, "D2!\n", 4); write (fd, "\n", 1); kb = kb->next; } close (fd); } /* I just know this is going to be a nasty parse, if you think it's bugged it almost certainly is so contact the XChat dev team --AGL */ static inline int key_load_kbs_helper_mod (char *in, int *out) { int n, len, mod = 0; /* First strip off the fluff */ while (in[0] == ' ' || in[0] == '\t') in++; len = strlen (in); while (in[len] == ' ' || in[len] == '\t') { in[len] = 0; len--; } if (strcmp (in, "None") == 0) { *out = 0; return 0; } for (n = 0; n < len; n++) { switch (in[n]) { case 'C': mod |= STATE_CTRL; break; case 'A': mod |= STATE_ALT; break; case 'S': mod |= STATE_SHIFT; break; default: return 1; } } *out = mod; return 0; } /* These are just local defines to keep me sane --AGL */ #define KBSTATE_MOD 0 #define KBSTATE_KEY 1 #define KBSTATE_ACT 2 #define KBSTATE_DT1 3 #define KBSTATE_DT2 4 /* *** Warning, Warning! - massive function ahead! --AGL */ static int key_load_kbs (char *filename) { char *buf, *ibuf; struct stat st; struct key_binding *kb = NULL, *last = NULL; int fd, len, pnt = 0, state = 0, n; if (filename == NULL) fd = xchat_open_file ("keybindings.conf", O_RDONLY, 0, 0); else fd = xchat_open_file (filename, O_RDONLY, 0, XOF_FULLPATH); if (fd < 0) return 1; if (fstat (fd, &st) != 0) return 1; ibuf = malloc (st.st_size); read (fd, ibuf, st.st_size); close (fd); while (buf_get_line (ibuf, &buf, &pnt, st.st_size)) { if (buf[0] == '#') continue; if (strlen (buf) == 0) continue; switch (state) { case KBSTATE_MOD: kb = (struct key_binding *) malloc (sizeof (struct key_binding)); if (key_load_kbs_helper_mod (buf, &kb->mod)) goto corrupt_file; state = KBSTATE_KEY; continue; case KBSTATE_KEY: /* First strip off the fluff */ while (buf[0] == ' ' || buf[0] == '\t') buf++; len = strlen (buf); while (buf[len] == ' ' || buf[len] == '\t') { buf[len] = 0; len--; } n = gdk_keyval_from_name (buf); if (n == 0) { /* Unknown keyname, abort */ if (last) last->next = NULL; free (ibuf); ibuf = malloc (1024); snprintf (ibuf, 1024, _("Unknown keyname %s in key bindings config file\nLoad aborted, please fix %s/keybindings.conf\n"), buf, get_xdir_utf8 ()); fe_message (ibuf, FE_MSG_ERROR); free (ibuf); return 2; } kb->keyname = gdk_keyval_name (n); kb->keyval = n; state = KBSTATE_ACT; continue; case KBSTATE_ACT: /* First strip off the fluff */ while (buf[0] == ' ' || buf[0] == '\t') buf++; len = strlen (buf); while (buf[len] == ' ' || buf[len] == '\t') { buf[len] = 0; len--; } for (n = 0; n < KEY_MAX_ACTIONS + 1; n++) { if (strcmp (key_actions[n].name, buf) == 0) { kb->action = n; break; } } if (n == KEY_MAX_ACTIONS + 1) { if (last) last->next = NULL; free (ibuf); ibuf = malloc (1024); snprintf (ibuf, 1024, _("Unknown action %s in key bindings config file\nLoad aborted, Please fix %s/keybindings\n"), buf, get_xdir_utf8 ()); fe_message (ibuf, FE_MSG_ERROR); free (ibuf); return 3; } state = KBSTATE_DT1; continue; case KBSTATE_DT1: case KBSTATE_DT2: if (state == KBSTATE_DT1) kb->data1 = kb->data2 = NULL; while (buf[0] == ' ' || buf[0] == '\t') buf++; if (buf[0] != 'D') { free (ibuf); ibuf = malloc (1024); snprintf (ibuf, 1024, _("Expecting Data line (beginning Dx{:|!}) but got:\n%s\n\nLoad aborted, Please fix %s/keybindings\n"), buf, get_xdir_utf8 ()); fe_message (ibuf, FE_MSG_ERROR); free (ibuf); return 4; } switch (buf[1]) { case '1': if (state != KBSTATE_DT1) goto corrupt_file; break; case '2': if (state != KBSTATE_DT2) goto corrupt_file; break; default: goto corrupt_file; } if (buf[2] == ':') { len = strlen (buf); /* Add one for the NULL, subtract 3 for the "Dx:" */ len++; len -= 3; if (state == KBSTATE_DT1) { kb->data1 = malloc (len); memcpy (kb->data1, &buf[3], len); } else { kb->data2 = malloc (len); memcpy (kb->data2, &buf[3], len); } } else if (buf[2] == '!') { if (state == KBSTATE_DT1) kb->data1 = NULL; else kb->data2 = NULL; } if (state == KBSTATE_DT1) { state = KBSTATE_DT2; continue; } else { if (last) last->next = kb; else keys_root = kb; last = kb; state = KBSTATE_MOD; } continue; } } if (last) last->next = NULL; free (ibuf); return 0; corrupt_file: /*if (getenv ("XCHAT_DEBUG")) abort ();*/ snprintf (ibuf, 1024, _("Key bindings config file is corrupt, load aborted\n" "Please fix %s/keybindings.conf\n"), get_xdir_utf8 ()); fe_message (ibuf, FE_MSG_ERROR); free (ibuf); return 5; } /* ***** Key actions start here *********** */ /* See the NOTES above --AGL */ /* "Run command" */ static int key_action_handle_command (GtkWidget * wid, GdkEventKey * evt, char *d1, char *d2, struct session *sess) { int ii, oi, len; char out[2048], d = 0; if (!d1) return 0; len = strlen (d1); /* Replace each "\n" substring with '\n' */ for (ii = oi = 0; ii < len; ii++) { d = d1[ii]; if (d == '\\') { ii++; d = d1[ii]; if (d == 'n') out[oi++] = '\n'; else if (d == '\\') out[oi++] = '\\'; else { out[oi++] = '\\'; out[oi++] = d; } continue; } out[oi++] = d; } out[oi] = 0; handle_multiline (sess, out, 0, 0); return 0; } static int key_action_page_switch (GtkWidget * wid, GdkEventKey * evt, char *d1, char *d2, struct session *sess) { int len, i, num; if (!d1) return 1; len = strlen (d1); if (!len) return 1; for (i = 0; i < len; i++) { if (d1[i] < '0' || d1[i] > '9') { if (i == 0 && (d1[i] == '+' || d1[i] == '-')) continue; else return 1; } } num = atoi (d1); if (!d2) num--; if (!d2 || d2[0] == 0) mg_switch_page (FALSE, num); else mg_switch_page (TRUE, num); return 0; } int key_action_insert (GtkWidget * wid, GdkEventKey * evt, char *d1, char *d2, struct session *sess) { int tmp_pos; if (!d1) return 1; tmp_pos = SPELL_ENTRY_GET_POS (wid); SPELL_ENTRY_INSERT (wid, d1, strlen (d1), &tmp_pos); SPELL_ENTRY_SET_POS (wid, tmp_pos); return 2; } /* handles PageUp/Down keys */ static int key_action_scroll_page (GtkWidget * wid, GdkEventKey * evt, char *d1, char *d2, struct session *sess) { int value, end; GtkAdjustment *adj; enum scroll_type { PAGE_UP, PAGE_DOWN, LINE_UP, LINE_DOWN }; int type = PAGE_DOWN; if (d1) { if (!strcasecmp (d1, "up")) type = PAGE_UP; else if (!strcasecmp (d1, "+1")) type = LINE_DOWN; else if (!strcasecmp (d1, "-1")) type = LINE_UP; } if (!sess) return 0; adj = GTK_RANGE (sess->gui->vscrollbar)->adjustment; end = adj->upper - adj->lower - adj->page_size; switch (type) { case LINE_UP: value = adj->value - 1.0; break; case LINE_DOWN: value = adj->value + 1.0; break; case PAGE_UP: value = adj->value - (adj->page_size - 1); break; default: /* PAGE_DOWN */ value = adj->value + (adj->page_size - 1); break; } if (value < 0) value = 0; if (value > end) value = end; gtk_adjustment_set_value (adj, value); return 0; } static int key_action_set_buffer (GtkWidget * wid, GdkEventKey * evt, char *d1, char *d2, struct session *sess) { if (!d1) return 1; if (d1[0] == 0) return 1; SPELL_ENTRY_SET_TEXT (wid, d1); SPELL_ENTRY_SET_POS (wid, -1); return 2; } static int key_action_history_up (GtkWidget * wid, GdkEventKey * ent, char *d1, char *d2, struct session *sess) { char *new_line; new_line = history_up (&sess->history, SPELL_ENTRY_GET_TEXT (wid)); if (new_line) { SPELL_ENTRY_SET_TEXT (wid, new_line); SPELL_ENTRY_SET_POS (wid, -1); } return 2; } static int key_action_history_down (GtkWidget * wid, GdkEventKey * ent, char *d1, char *d2, struct session *sess) { char *new_line; new_line = history_down (&sess->history); if (new_line) { SPELL_ENTRY_SET_TEXT (wid, new_line); SPELL_ENTRY_SET_POS (wid, -1); } return 2; } /* old data that we reuse */ static struct gcomp_data old_gcomp; /* work on the data, ie return only channels */ static int double_chan_cb (session *lsess, GList **list) { if (lsess->type == SESS_CHANNEL) *list = g_list_prepend(*list, lsess->channel); return TRUE; } /* convert a slist -> list. */ static GList * chanlist_double_list (GSList *inlist) { GList *list = NULL; g_slist_foreach(inlist, (GFunc)double_chan_cb, &list); return list; } /* handle commands */ static int double_cmd_cb (struct popup *pop, GList **list) { *list = g_list_prepend(*list, pop->name); return TRUE; } /* convert a slist -> list. */ static GList * cmdlist_double_list (GSList *inlist) { GList *list = NULL; g_slist_foreach (inlist, (GFunc)double_cmd_cb, &list); return list; } static char * gcomp_nick_func (char *data) { if (data) return ((struct User *)data)->nick; return ""; } void key_action_tab_clean(void) { if (old_gcomp.elen) { old_gcomp.data[0] = 0; old_gcomp.elen = 0; } } /* Used in the followig completers */ #define COMP_BUF 2048 /* For use in sorting the user list for completion */ static int talked_recent_cmp (struct User *a, struct User *b) { if (a->lasttalk < b->lasttalk) return -1; if (a->lasttalk > b->lasttalk) return 1; return 0; } static int key_action_tab_comp (GtkWidget *t, GdkEventKey *entry, char *d1, char *d2, struct session *sess) { int len = 0, elen = 0, i = 0, cursor_pos, ent_start = 0, comp = 0, found = 0, prefix_len, skip_len = 0, is_nick, is_cmd = 0; char buf[COMP_BUF], ent[CHANLEN], *postfix = NULL, *result, *ch; GList *list = NULL, *tmp_list = NULL; const char *text; GCompletion *gcomp = NULL; /* force the IM Context to reset */ SPELL_ENTRY_SET_EDITABLE (t, FALSE); SPELL_ENTRY_SET_EDITABLE (t, TRUE); text = SPELL_ENTRY_GET_TEXT (t); if (text[0] == 0) return 1; len = g_utf8_strlen (text, -1); /* must be null terminated */ cursor_pos = SPELL_ENTRY_GET_POS (t); buf[0] = 0; /* make sure we don't get garbage in the buffer */ /* handle "nick: " or "nick " or "#channel "*/ ch = g_utf8_find_prev_char(text, g_utf8_offset_to_pointer(text,cursor_pos)); if (ch && ch[0] == ' ') { skip_len++; ch = g_utf8_find_prev_char(text, ch); if (!ch) return 2; cursor_pos = g_utf8_pointer_to_offset(text, ch); if (cursor_pos && (g_utf8_get_char_validated(ch, -1) == ':' || g_utf8_get_char_validated(ch, -1) == ',' || g_utf8_get_char_validated(ch, -1) == prefs.nick_suffix[0])) { skip_len++; } else cursor_pos = g_utf8_pointer_to_offset(text, g_utf8_offset_to_pointer(ch, 1)); } comp = skip_len; /* store the text following the cursor for reinsertion later */ if ((cursor_pos + skip_len) < len) postfix = g_utf8_offset_to_pointer(text, cursor_pos + skip_len); for (ent_start = cursor_pos; ; --ent_start) { if (ent_start == 0) break; ch = g_utf8_offset_to_pointer(text, ent_start - 1); if (ch && ch[0] == ' ') break; } if (ent_start == 0 && text[0] == prefs.cmdchar[0]) { ent_start++; is_cmd = 1; } prefix_len = ent_start; elen = cursor_pos - ent_start; g_utf8_strncpy (ent, g_utf8_offset_to_pointer (text, prefix_len), elen); is_nick = (ent[0] == '#' || ent[0] == '&' || is_cmd) ? 0 : 1; if (sess->type == SESS_DIALOG && is_nick) { /* tab in a dialog completes the other person's name */ if (rfc_ncasecmp (sess->channel, ent, elen) == 0) { result = sess->channel; is_nick = 0; } else return 2; } else { if (is_nick) { gcomp = g_completion_new((GCompletionFunc)gcomp_nick_func); tmp_list = userlist_double_list(sess); /* create a temp list so we can free the memory */ if (prefs.completion_sort == 1) /* sort in last-talk order? */ tmp_list = g_list_sort (tmp_list, (void *)talked_recent_cmp); } else { gcomp = g_completion_new (NULL); if (is_cmd) { tmp_list = cmdlist_double_list (command_list); for(i = 0; xc_cmds[i].name != NULL ; i++) { tmp_list = g_list_prepend (tmp_list, xc_cmds[i].name); } tmp_list = plugin_command_list(tmp_list); } else tmp_list = chanlist_double_list (sess_list); } tmp_list = g_list_reverse(tmp_list); /* make the comp entries turn up in the right order */ g_completion_set_compare (gcomp, (GCompletionStrncmpFunc)rfc_ncasecmp); if (tmp_list) { g_completion_add_items (gcomp, tmp_list); g_list_free (tmp_list); } if (comp && !(rfc_ncasecmp(old_gcomp.data, ent, old_gcomp.elen) == 0)) { key_action_tab_clean (); comp = 0; } list = g_completion_complete_utf8 (gcomp, comp ? old_gcomp.data : ent, &result); if (result == NULL) /* No matches found */ { g_completion_free(gcomp); return 2; } if (comp) /* existing completion */ { while(list) /* find the current entry */ { if(rfc_ncasecmp(list->data, ent, elen) == 0) { found = 1; break; } list = list->next; } if (found) { if (!(d1 && d1[0])) /* not holding down shift */ { if (g_list_next(list) == NULL) list = g_list_first(list); else list = g_list_next(list); } else { if (g_list_previous(list) == NULL) list = g_list_last(list); else list = g_list_previous(list); } g_free(result); result = (char*)list->data; } else { g_free(result); g_completion_free(gcomp); return 2; } } else { strcpy(old_gcomp.data, ent); old_gcomp.elen = elen; /* Get the first nick and put out the data for future nickcompletes */ if (prefs.completion_amount && g_list_length (list) <= prefs.completion_amount) { g_free(result); result = (char*)list->data; } else { /* bash style completion */ if (g_list_next(list) != NULL) { if (strlen (result) > elen) /* the largest common prefix is larger than nick, change the data */ { if (prefix_len) g_utf8_strncpy (buf, text, prefix_len); strncat (buf, result, COMP_BUF - prefix_len); cursor_pos = strlen (buf); g_free(result); #if !GLIB_CHECK_VERSION(2,4,0) g_utf8_validate (buf, -1, (const gchar **)&result); (*result) = 0; #endif if (postfix) { strcat (buf, " "); strncat (buf, postfix, COMP_BUF - cursor_pos -1); } SPELL_ENTRY_SET_TEXT (t, buf); SPELL_ENTRY_SET_POS (t, g_utf8_pointer_to_offset(buf, buf + cursor_pos)); buf[0] = 0; } else g_free(result); while (list) { len = strlen (buf); /* current buffer */ elen = strlen (list->data); /* next item to add */ if (len + elen + 2 >= COMP_BUF) /* +2 is space + null */ { PrintText (sess, buf); buf[0] = 0; len = 0; } strcpy (buf + len, (char *) list->data); strcpy (buf + len + elen, " "); list = list->next; } PrintText (sess, buf); g_completion_free(gcomp); return 2; } /* Only one matching entry */ g_free(result); result = list->data; } } } if(result) { if (prefix_len) g_utf8_strncpy(buf, text, prefix_len); strncat (buf, result, COMP_BUF - (prefix_len + 3)); /* make sure nicksuffix and space fits */ if(!prefix_len && is_nick) strcat (buf, &prefs.nick_suffix[0]); strcat (buf, " "); cursor_pos = strlen (buf); if (postfix) strncat (buf, postfix, COMP_BUF - cursor_pos - 2); SPELL_ENTRY_SET_TEXT (t, buf); SPELL_ENTRY_SET_POS (t, g_utf8_pointer_to_offset(buf, buf + cursor_pos)); } if (gcomp) g_completion_free(gcomp); return 2; } #undef COMP_BUF static int key_action_comp_chng (GtkWidget * wid, GdkEventKey * ent, char *d1, char *d2, struct session *sess) { key_action_tab_comp(wid, ent, d1, d2, sess); return 2; } static int key_action_replace (GtkWidget * wid, GdkEventKey * ent, char *d1, char *d2, struct session *sess) { replace_handle (wid); return 1; } static int key_action_move_tab_left (GtkWidget * wid, GdkEventKey * ent, char *d1, char *d2, struct session *sess) { mg_move_tab (sess, +1); return 2; /* don't allow default action */ } static int key_action_move_tab_right (GtkWidget * wid, GdkEventKey * ent, char *d1, char *d2, struct session *sess) { mg_move_tab (sess, -1); return 2; /* -''- */ } static int key_action_move_tab_family_left (GtkWidget * wid, GdkEventKey * ent, char *d1, char *d2, struct session *sess) { mg_move_tab_family (sess, +1); return 2; /* don't allow default action */ } static int key_action_move_tab_family_right (GtkWidget * wid, GdkEventKey * ent, char *d1, char *d2, struct session *sess) { mg_move_tab_family (sess, -1); return 2; /* -''- */ } static int key_action_put_history (GtkWidget * wid, GdkEventKey * ent, char *d1, char *d2, struct session *sess) { history_add (&sess->history, SPELL_ENTRY_GET_TEXT (wid)); SPELL_ENTRY_SET_TEXT (wid, ""); return 2; /* -''- */ } /* -------- */ #define STATE_SHIFT GDK_SHIFT_MASK #define STATE_ALT GDK_MOD1_MASK #define STATE_CTRL GDK_CONTROL_MASK static void replace_handle (GtkWidget *t) { const char *text, *postfix_pnt; struct popup *pop; GSList *list = replace_list; char word[256]; char postfix[256]; char outbuf[4096]; int c, len, xlen; text = SPELL_ENTRY_GET_TEXT (t); len = strlen (text); if (len < 1) return; for (c = len - 1; c > 0; c--) { if (text[c] == ' ') break; } if (text[c] == ' ') c++; xlen = c; if (len - c >= (sizeof (word) - 12)) return; if (len - c < 1) return; memcpy (word, &text[c], len - c); word[len - c] = 0; len = strlen (word); if (word[0] == '\'' && word[len] == '\'') return; postfix_pnt = NULL; for (c = 0; c < len; c++) { if (word[c] == '\'') { postfix_pnt = &word[c + 1]; word[c] = 0; break; } } if (postfix_pnt != NULL) { if (strlen (postfix_pnt) > sizeof (postfix) - 12) return; strcpy (postfix, postfix_pnt); } while (list) { pop = (struct popup *) list->data; if (strcmp (pop->name, word) == 0) { memcpy (outbuf, text, xlen); outbuf[xlen] = 0; if (postfix_pnt == NULL) snprintf (word, sizeof (word), "%s", pop->cmd); else snprintf (word, sizeof (word), "%s%s", pop->cmd, postfix); strcat (outbuf, word); SPELL_ENTRY_SET_TEXT (t, outbuf); SPELL_ENTRY_SET_POS (t, -1); return; } list = list->next; } }
rofl0r/ixchat
src/fe-gtk/fkeys.c
C
gpl-2.0
44,561
namespace PowerPointLabs.ELearningLab.AudioGenerator { public class AzureAccount { private static AzureAccount instance; private string key; private string endpoint; public static AzureAccount GetInstance() { if (instance == null) { instance = new AzureAccount(); } return instance; } private AzureAccount() { key = null; endpoint = null; } public void SetUserKeyAndRegion(string key, string endpoint) { this.key = key; this.endpoint = endpoint; } public string GetKey() { return key; } public string GetRegion() { return endpoint; } public string GetUri() { if (!string.IsNullOrEmpty(endpoint)) { return EndpointToUriConverter.azureEndpointToUriMapping[endpoint]; } return null; } public bool IsEmpty() { return key == null || endpoint == null; } public void Clear() { key = null; endpoint = null; } } }
PowerPointLabs/PowerPointLabs
PowerPointLabs/PowerPointLabs/ELearningLab/AudioGenerator/AzureVoiceGenerator/Model/AzureAccount.cs
C#
gpl-2.0
1,280
# # $Id: Makefile 9433 2012-02-10 15:25:49Z lculik $ # ROOT = ../../../ C_SOURCES=\ adler32.c \ compress.c \ crc32.c \ deflate.c \ gzlib.c \ gzwrite.c \ gzread.c \ gzclose.c \ infback.c \ inffast.c \ inflate.c \ inftrees.c \ trees.c \ uncompr.c \ zutil.c \ LIBNAME=zlib # The list of all valid GT drivers is defined in config/<arch>/global.cf. include $(TOP)$(ROOT)config/lib.cf include $(TOP)$(ROOT)config/dir.cf ifneq ($(HB_GT_DEFAULT),) CFLAGS += -DHB_GT_DEFAULT=$(HB_GT_DEFAULT:gt%=%) endif ifneq ($(HB_GT_LIB),) CFLAGS += -DHB_GT_LIB=$(HB_GT_LIB:gt%=%) endif CFLAGS += -I../..
xharbour/core
source/rtl/zlib/Makefile
Makefile
gpl-2.0
612
<?php namespace App\Http\Controllers; use Illuminate\Http\Request; use Hash; use App\Models\Link; use App\Models\User; use App\Helpers\UserHelper; class AdminController extends Controller { /** * Show the admin panel, and process admin AJAX requests. * * @return Response */ public function displayAdminPage(Request $request) { if (!$this->isLoggedIn()) { return abort(404); } $username = session('username'); $role = session('role'); $admin_users = null; $admin_links = null; if ($this->currIsAdmin()) { $admin_users = User::paginate(15); $admin_links = Link::paginate(15); } $user = UserHelper::getUserByUsername($username); if (!$user) { return redirect(route('index'))->with('error', 'Invalid or disabled account.'); } $user_links = Link::where('creator', $username) ->paginate(15); return view('admin', [ 'role' => $role, 'admin_users' => $admin_users, 'admin_links' => $admin_links, 'user_links' => $user_links, 'api_key' => $user->api_key, 'api_active' => $user->api_active, 'api_quota' => $user->api_quota, 'user_id' => $user->id ]); } public function changePassword(Request $request) { if (!$this->isLoggedIn()) { return abort(404); } $username = session('username'); $old_password = $request->input('current_password'); $new_password = $request->input('new_password'); if (UserHelper::checkCredentials($username, $old_password) == false) { // Invalid credentials return redirect('admin')->with('error', 'Current password invalid. Try again.'); } else { // Credentials are correct $user = UserHelper::getUserByUsername($username); $user->password = Hash::make($new_password); $user->save(); $request->session()->flash('success', "Password changed successfully."); return redirect(route('admin')); } } }
goeroe/polr
app/Http/Controllers/AdminController.php
PHP
gpl-2.0
2,212
namespace CommandPattern.Properties { [global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()] [global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.VisualStudio.Editors.SettingsDesigner.SettingsSingleFileGenerator", "10.0.0.0")] internal sealed partial class Settings : global::System.Configuration.ApplicationSettingsBase { private static Settings defaultInstance = ((Settings)(global::System.Configuration.ApplicationSettingsBase.Synchronized(new Settings()))); public static Settings Default { get { return defaultInstance; } } } }
logicalforhad/designpattern
GofPattern/CommandPattern/Properties/Settings.Designer.cs
C#
gpl-2.0
669
package teammates.client.scripts; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.File; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; import java.lang.reflect.Method; import java.lang.reflect.Type; import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Set; import teammates.common.datatransfer.DataBundle; import teammates.common.datatransfer.attributes.CourseAttributes; import teammates.common.datatransfer.attributes.InstructorAttributes; import teammates.common.datatransfer.attributes.StudentAttributes; import teammates.common.util.JsonUtils; import teammates.test.driver.BackDoor; import teammates.test.driver.FileHelper; import teammates.test.driver.TestProperties; import teammates.test.pageobjects.Browser; import teammates.test.pageobjects.BrowserPool; /** * Annotations for Performance tests with * <ul> * <li>Name: name of the test</li> * <li>CustomTimer: (default is false) if true, the function will return the duration need to recorded itself. * If false, the function return the status of the test and expected the function * which called it to record the duration.</li> * </ul> */ @Target(ElementType.METHOD) @Retention(RetentionPolicy.RUNTIME) @interface PerformanceTest { String name() default ""; boolean customTimer() default false; } /** * Usage: This script is to profile performance of the app with id in test.properties. To run multiple instance * of this script in parallel, use ParallelProfiler.Java. * * <p>Notes: * <ul> * <li>Edit name of the report file, the result will be written to a file in src/test/resources/data folder</li> * <li>Make sure that the data in PerformanceProfilerImportData.json is imported (by using ImportData.java)</li> * </ul> */ public class PerformanceProfiler extends Thread { private static final String defaultReportPath = TestProperties.TEST_DATA_FOLDER + "/" + "nameOfTheReportFile.txt"; private static final int NUM_OF_RUNS = 2; private static final int WAIT_TIME_TEST = 1000; //waiting time between tests, in ms private static final int WAIT_TIME_RUN = 5000; //waiting time between runs, in ms private static final String runningDataSourceFile = "PerformanceProfilerRunningData.json"; private String reportFilePath; private DataBundle data; private Map<String, ArrayList<Float>> results = new HashMap<>(); protected PerformanceProfiler(String path) { reportFilePath = path; } @Override public void run() { //Data used for profiling String jsonString = ""; try { jsonString = FileHelper.readFile(TestProperties.TEST_DATA_FOLDER + "/" + runningDataSourceFile); } catch (IOException e) { e.printStackTrace(); } data = JsonUtils.fromJson(jsonString, DataBundle.class); //Import previous results try { results = importReportFile(reportFilePath); } catch (IOException e) { e.printStackTrace(); } Browser browser; for (int i = 0; i < NUM_OF_RUNS; i++) { browser = BrowserPool.getBrowser(); //overcome initial loading time with the below line //getInstructorAsJson(); //get all methods with annotation and record time Method[] methods = PerformanceProfiler.class.getMethods(); for (Method method : methods) { performMethod(method); } // Wait between runs BrowserPool.release(browser); try { Thread.sleep(WAIT_TIME_RUN); } catch (InterruptedException e) { e.printStackTrace(); } } // Write the results back to file try { printResult(reportFilePath); } catch (IOException e) { e.printStackTrace(); } System.out.print("\n Finished!"); } /** * This function perform the method and print the return value for debugging. */ private void performMethod(Method method) { if (method.isAnnotationPresent(PerformanceTest.class)) { PerformanceTest test = method.getAnnotation(PerformanceTest.class); String name = test.name(); boolean customTimer = test.customTimer(); Type type = method.getReturnType(); if (!results.containsKey(name)) { results.put(name, new ArrayList<Float>()); } try { float duration = 0; if (type.equals(String.class) && !customTimer) { long startTime = System.nanoTime(); Object retVal = method.invoke(this); long endTime = System.nanoTime(); duration = (float) ((endTime - startTime) / 1000000.0); //in miliSecond System.out.print("Name: " + name + "\tTime: " + duration + "\tVal: " + retVal.toString() + "\n"); } else if (type.equals(Long.class) && customTimer) { duration = (float) ((Long) method.invoke(this) / 1000000.0); System.out.print("Name: " + name + "\tTime: " + duration + "\n"); } // Add new duration to the arrayList of the test. ArrayList<Float> countList = results.get(name); countList.add(duration); } catch (Exception e) { System.out.print(e.toString()); } // reduce chance of data not being persisted try { Thread.sleep(WAIT_TIME_TEST); } catch (InterruptedException e) { e.printStackTrace(); } } } /** * Run this script as an single-thread Java application (for simple, non-parallel profiling). * For parallel profiling, please use ParallelProfiler.java. */ public static void main(String[] args) { // Run this script as an single-thread Java application (for simple, non-parallel profiling) // For parallel profiling, please use ParallelProfiler.java new PerformanceProfiler(defaultReportPath).start(); } /** * The results from file stored in filePath. * @return {@code HashMap<nameOfTest, durations>} of the report stored in filePath */ private static HashMap<String, ArrayList<Float>> importReportFile(String filePath) throws IOException { HashMap<String, ArrayList<Float>> results = new HashMap<>(); File reportFile = new File(filePath); // Create the report file if not existed if (!reportFile.exists()) { try { reportFile.createNewFile(); } catch (IOException e) { e.printStackTrace(); } return results; } //Import old data to the HashMap BufferedReader br = new BufferedReader(new FileReader(filePath)); String strLine; while ((strLine = br.readLine()) != null) { System.out.println(strLine); String[] strs = strLine.split("\\|"); String testName = strs[0]; String[] durations = strs[2].split("\\,"); ArrayList<Float> arr = new ArrayList<>(); for (String str : durations) { Float f = Float.parseFloat(str); arr.add(f); } results.put(testName, arr); } br.close(); return results; } /** * Writes the results to the file with path filePath. */ private void printResult(String filePath) throws IOException { List<String> list = new ArrayList<>(); for (String str : results.keySet()) { list.add(str); } Collections.sort(list); FileWriter fstream = new FileWriter(filePath); BufferedWriter out = new BufferedWriter(fstream); for (String str : list) { StringBuilder lineStrBuilder = new StringBuilder(); ArrayList<Float> arr = results.get(str); Float total = 0.0f; for (Float f : arr) { total += f; lineStrBuilder.append(f).append(" , "); } String lineStr = lineStrBuilder.substring(0, lineStrBuilder.length() - 3); //remove last comma Float average = total / arr.size(); out.write(str + "| " + average + " | " + lineStr + "\n"); } out.close(); } // TODO: this class needs to be tweaked to work with the new Browser class // Performance Tests , the order of these tests is also the order they will run /* @PerformanceTest(name = "Instructor login",customTimer = true) public Long instructorLogin() { browser.goToUrl(TestProperties.TEAMMATES_URL); browser.click(browser.instructorLoginButton); long startTime = System.nanoTime(); browser.login("testingforteammates@gmail.com", "testingforteammates", false); return System.nanoTime()-startTime; } @PerformanceTest(name = "Instructor home page") String instructorHomePage() { browser.goToUrl(TestProperties.TEAMMATES_URL + "/page/instructorHome"); return ""; } @PerformanceTest(name = "Instructor eval page") public String instructorEval() { browser.goToUrl(TestProperties.TEAMMATES_URL + "/page/instructorEval"); return ""; } @PerformanceTest(name = "Instructor add eval",customTimer = true) public Long instructorAddEval() { Calendar cal = Calendar.getInstance(TimeZone.getTimeZone("UTC")); cal.add(Calendar.DATE, +1); Date date1 = cal.getTime(); cal.add(Calendar.DATE, +2); Date date2 = cal.getTime(); long startTime = System.nanoTime(); browser.addEvaluation("idOf_Z2_Cou0_of_Coo0", "test", date1, date2, true, "This is the instructions, please follow", 5); browser.waitForStatusMessage(Common.STATUS_EVALUATION_ADDED); return System.nanoTime() - startTime; } @PerformanceTest(name = "Instructor eval page") public String instructorEval2() { browser.goToUrl(TestProperties.TEAMMATES_URL + "/page/instructorEval"); return ""; } @PerformanceTest(name = "Instructor delete eval*",customTimer = true) public Long instructorDeleteEval() { int evalRowID = browser.getEvaluationRowID("idOf_Z2_Cou0_of_Coo0", "test"); By deleteLinkLocator = browser.getInstructorEvaluationDeleteLinkLocator(evalRowID); long startTime =System.nanoTime(); browser.clickAndConfirm(deleteLinkLocator); return System.nanoTime() - startTime; } @PerformanceTest(name = "Instructor course page") public String instructorCourse() { browser.goToUrl(TestProperties.TEAMMATES_URL + "/page/instructorCourse"); return ""; } @PerformanceTest(name = "Instructor add course",customTimer = true) public Long instructorAddCourse() { long startTime = System.nanoTime(); browser.addCourse("testcourse", "testcourse"); browser.waitForStatusMessage(Common.STATUS_COURSE_ADDED); return System.nanoTime() - startTime; } @PerformanceTest(name = "Instructor course page") public String instructorCourse2() { browser.goToUrl(TestProperties.TEAMMATES_URL + "/page/instructorCourse"); return ""; } @PerformanceTest(name = "Instructor delete course*",customTimer = true) public Long instructorDeleteCourse() throws Exception { String courseId = "testcourse"; int courseRowId = browser.getCourseRowID(courseId); By deleteLinkLocator = browser.getInstructorCourseDeleteLinkLocator(courseRowId); long startTime = System.nanoTime(); browser.clickAndConfirm(deleteLinkLocator); return System.nanoTime() - startTime; } @PerformanceTest(name = "Instructor course student detail page") public String instructorCourseStudentDetails() { browser.goToUrl(TestProperties.TEAMMATES_URL + "/page/instructorCourseStudentDetails?courseid=idOf_Z2_Cou0_of_Coo0" + "&studentemail=testingforteammates%40gmail.com"); return ""; } @PerformanceTest(name = "Instructor course enroll page") public String instructorCourseEnroll() { browser.goToUrl(TestProperties.TEAMMATES_URL + "/page/instructorCourseEnroll?courseid=idOf_Z2_Cou0_of_Coo0"); return ""; } @PerformanceTest(name = "Instructor course enroll student*",customTimer = true) public Long instructorCourseEnrollStudent() { String enrollString = "Team 1 | teststudent | alice.b.tmms@gmail.com | This comment has been changed\n"; browser.fillString(By.id("enrollstudents"), enrollString); long startTime = System.nanoTime(); browser.click(By.id("button_enroll")); return System.nanoTime() - startTime; } @PerformanceTest(name = "Instructor course enroll page") public String instructorCourseDetails() { browser.goToUrl(TestProperties.TEAMMATES_URL + "/page/instructorCourseDetails?courseid=idOf_Z2_Cou0_of_Coo0"); return ""; } @PerformanceTest(name = "Instructor course delete student *",customTimer = true) public Long instructorCourseDeleteStudent() { int studentRowId = browser.getStudentRowId("teststudent"); long startTime = System.nanoTime(); browser.clickInstructorCourseDetailStudentDeleteAndConfirm(studentRowId); return System.nanoTime() - startTime; } @PerformanceTest(name = "Instructor eval results") public String instructorEvalResults() { browser.goToUrl(TestProperties.TEAMMATES_URL + "/page/instructorEvalResults?courseid=idOf_Z2_Cou0_of_Coo0" + "&evaluationname=Z2_Eval0_in_Cou0_of_Coo0"); return ""; } @PerformanceTest(name = "Instructor view student eval ") public String instructorViewStuEval() { browser.goToUrl(TestProperties.TEAMMATES_URL + "/page/instructorEvalSubmissionView?courseid=idOf_Z2_Cou0_of_Coo0" + "&evaluationname=Z2_Eval0_in_Cou0_of_Coo0&studentemail=Z2_Stu59Email%40gmail.com"); return ""; } @PerformanceTest(name = "Instructor help page ") public String instructorHelp() { browser.goToUrl(TestProperties.TEAMMATES_URL + "/instructorHelp.jsp"); return ""; } @PerformanceTest(name = "Instructor log out") public String instructorLogout() { browser.logout(); return ""; } @PerformanceTest(name = "Student login") public String stuLogin() { browser.loginStudent("testingforteammates@gmail.com","testingforteammates"); return ""; } @PerformanceTest(name = "Student homepage") public String stuHomepage() { browser.goToUrl(TestProperties.TEAMMATES_URL + "/page/studentHome"); return ""; } @PerformanceTest(name = "Student course detail page") public String stuCoursepage() { browser.goToUrl(TestProperties.TEAMMATES_URL + "/page/studentCourseDetails?courseid=idOf_Z2_Cou0_of_Coo0"); return ""; } @PerformanceTest(name = "Student edit submission page") public String stuEditSubmissionPage() { browser.goToUrl(TestProperties.TEAMMATES_URL + "/page/studentEvalEdit?courseid=idOf_Z2_Cou0_of_Coo0" + "&evaluationname=Z2_Eval0_in_Cou0_of_Coo0"); return ""; } @PerformanceTest(name = "Student edit submission ") public String stuEditSubmission() { browser.goToUrl(TestProperties.TEAMMATES_URL + "/page/studentCourseDetails?courseid=idOf_Z2_Cou0_of_Coo0"); return ""; } @PerformanceTest(name = "Student eval result ") public String stuEvalResultPage() { browser.goToUrl(TestProperties.TEAMMATES_URL + "/page/studentEvalResults?courseid=idOf_Z2_Cou0_of_Coo0" + "&evaluationname=Z2_Eval0_in_Cou0_of_Coo0"); return ""; } @PerformanceTest(name = "Student log out") public String stuLogout() { browser.logout(); return ""; } @PerformanceTest(name = "BD create instructor") public String createInstructor() { String status = ""; Set<String> set = data.instructors.keySet(); for (String instructorKey : set) { InstructorAttributes instructor = data.instructors.get(instructorKey); status += BackDoor.createInstructor(instructor); } return status; } @PerformanceTest(name = "BD get instructor") public String getInstructorAsJson() { String status = ""; Set<String> set = data.instructors.keySet(); for (String instructorKey : set) { InstructorAttributes instructor = data.instructors.get(instructorKey); status += BackDoor.getInstructorAsJson(instructor.googleId, instructor.courseId); } return status; } @PerformanceTest(name = "BD get courses by instructor") public String getCoursesByInstructor() { String status = ""; Set<String> set = data.instructors.keySet(); for (String instructorKey : set) { InstructorAttributes instructor = data.instructors.get(instructorKey); String[] courses = BackDoor.getCoursesByInstructorId(instructor.googleId); for (String courseName : courses) { status += " " + courseName; } } return status; } @PerformanceTest(name = "BD create course") public String createCourse() { String status = ""; Set<String> set = data.courses.keySet(); for (String courseKey : set) { CourseAttributes course = data.courses.get(courseKey); status += " " + BackDoor.createCourse(course); } return status; } @PerformanceTest(name = "BD get course") public String getCourseAsJson() { String status = ""; Set<String> set = data.courses.keySet(); for (String courseKey : set) { CourseAttributes course = data.courses.get(courseKey); status += " " + BackDoor.getCourseAsJson(course.id); } return status; } @PerformanceTest(name = "BD create student") public String createStudent() { String status = ""; Set<String> set = data.students.keySet(); for (String studentKey : set) { StudentAttributes student = data.students.get(studentKey); status += " " + BackDoor.createStudent(student); } return status; } // The method createSubmission is not implemented in BackDoor yet. @PerformanceTest(name = "BD create submission") static public String createSubmissions() { String status = ""; Set<String> set = data.submissions.keySet(); for (String submissionKey : set) { SubmissionData submission = data.submissions.get(submissionKey); status += " " + BackDoor.createSubmission(submission); } return status; } */ @PerformanceTest(name = "BD get student") public String getStudent() { StringBuilder status = new StringBuilder(); Set<String> set = data.getStudents().keySet(); for (String studentKey : set) { StudentAttributes student = data.getStudents().get(studentKey); status.append(' ').append(JsonUtils.toJson(BackDoor.getStudent(student.course, student.email))); } return status.toString(); } @PerformanceTest(name = "BD get key for student") public String getKeyForStudent() { StringBuilder status = new StringBuilder(); Set<String> set = data.getStudents().keySet(); for (String studentKey : set) { StudentAttributes student = data.getStudents().get(studentKey); status.append(' ').append(BackDoor.getEncryptedKeyForStudent(student.course, student.email)); } return status.toString(); } @PerformanceTest(name = "BD edit student") public String editStudent() { StringBuilder status = new StringBuilder(); Set<String> set = data.getStudents().keySet(); for (String studentKey : set) { StudentAttributes student = data.getStudents().get(studentKey); status.append(' ').append(BackDoor.editStudent(student.email, student)); } return status.toString(); } @PerformanceTest(name = "BD delete student") public String deleteStudent() { StringBuilder status = new StringBuilder(); Set<String> set = data.getStudents().keySet(); for (String studentKey : set) { StudentAttributes student = data.getStudents().get(studentKey); status.append(' ').append(BackDoor.deleteStudent(student.course, student.email)); } return status.toString(); } @PerformanceTest(name = "BD Delete Course") public String deleteCourse() { StringBuilder status = new StringBuilder(); Set<String> set = data.getCourses().keySet(); for (String courseKey : set) { CourseAttributes course = data.getCourses().get(courseKey); status.append(' ').append(BackDoor.deleteCourse(course.getId())); } return status.toString(); } @PerformanceTest(name = "BD Delete Instructor") public String deleteInstructor() { StringBuilder status = new StringBuilder(); Set<String> set = data.getInstructors().keySet(); for (String instructorKey : set) { InstructorAttributes instructor = data.getInstructors().get(instructorKey); status.append(BackDoor.deleteInstructor(instructor.email, instructor.courseId)); } return status.toString(); } }
Gorgony/teammates
src/client/java/teammates/client/scripts/PerformanceProfiler.java
Java
gpl-2.0
22,398
#!/bin/sh ./scripts/generator.py > Good-songs-to-play.ad sudo docker run --privileged=true -v $PWD:/documents asciidoctor/docker-asciidoctor asciidoctor -v -a stylesheet=stylesheets/minimal.css Good-songs-to-play.ad -o index.html sudo docker run --privileged=true -v $PWD:/documents asciidoctor/docker-asciidoctor asciidoctor -r asciidoctor-pdf -b pdf Good-songs-to-play.ad -o index.pdf sudo docker run --privileged=true -v $PWD:/documents asciidoctor/docker-asciidoctor asciidoctor -v -a stylesheet=stylesheets/minimal.css SetList.ad -o setlist.html
TheVasin/good-songs-to-play
scripts/publish_with_docker.sh
Shell
gpl-2.0
551
/** * @file gnome-cmd-chown-dialog.h * @copyright (C) 2001-2006 Marcus Bjurman\n * @copyright (C) 2007-2012 Piotr Eljasiak\n * @copyright (C) 2013-2022 Uwe Scholz\n * * @copyright 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. * * @copyright 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. * * @copyright 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., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA. */ #pragma once #define GNOME_CMD_TYPE_CHOWN_DIALOG (gnome_cmd_chown_dialog_get_type ()) #define GNOME_CMD_CHOWN_DIALOG(obj) (G_TYPE_CHECK_INSTANCE_CAST((obj), GNOME_CMD_TYPE_CHOWN_DIALOG, GnomeCmdChownDialog)) #define GNOME_CMD_CHOWN_DIALOG_CLASS(klass) (G_TYPE_CHECK_CLASS_CAST((klass), GNOME_CMD_TYPE_CHOWN_DIALOG, GnomeCmdChownDialogClass)) #define GNOME_CMD_IS_CHOWN_DIALOG(obj) (G_TYPE_CHECK_INSTANCE_TYPE((obj), GNOME_CMD_TYPE_CHOWN_DIALOG)) #define GNOME_CMD_IS_CHOWN_DIALOG_CLASS(klass) (G_TYPE_CHECK_CLASS_TYPE ((klass), GNOME_CMD_TYPE_CHOWN_DIALOG)) #define GNOME_CMD_CHOWN_DIALOG_GET_CLASS(obj) (G_TYPE_INSTANCE_GET_CLASS((obj), GNOME_CMD_TYPE_CHOWN_DIALOG, GnomeCmdChownDialogClass)) GType gnome_cmd_chown_dialog_get_type (); struct GnomeCmdChownDialogPrivate; struct GnomeCmdChownDialog { GnomeCmdDialog parent; GnomeCmdChownDialogPrivate *priv; }; struct GnomeCmdChownDialogClass { GnomeCmdDialogClass parent_class; }; GtkWidget *gnome_cmd_chown_dialog_new (GList *files);
GNOME/gnome-commander
src/dialogs/gnome-cmd-chown-dialog.h
C
gpl-2.0
1,979
/* * Copyright (C) 2013-2014 Stefan Ascher <sa14@stievie.mooo.com> * * This file is part of Giddo. * * Giddo 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. * Giddo 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 Giddo. If not, see <http://www.gnu.org/licenses/>. */ function dayDiff(first, second) { return Math.round((second - first) / (1000 * 60 * 60 * 24)); } $(document).ready(function() { var now = new Date(); var nowUtc = new Date(now.getUTCFullYear(), now.getUTCMonth(), now.getUTCDate(), now.getUTCHours(), now.getUTCMinutes(), now.getUTCSeconds()); $.each($(".date-time"), function() { var val = $(this).text(); var dt = val.split(" "); var date = dt[0].split("-"); var then = new Date(Date.UTC(parseInt(date[0]), parseInt(date[1]) - 1, parseInt(date[2]))); var daysSince = dayDiff(then, nowUtc); var time = dt[1].split(":"); var years = now.getFullYear() - parseInt(date[0]); if (years !== 0) return; $(this).attr("title", val); var months = (now.getMonth() + 1) - parseInt(date[1]); if (daysSince > 29) { if (months > 1) { $(this).text(months + " months ago"); return; } if (months === 1) { $(this).text(months + " month ago"); return; } } if (daysSince > 1) { $(this).text(daysSince + " days ago"); return; } if (daysSince === 1) { $(this).text(daysSince + " day ago"); return; } var hours = now.getHours() - parseInt(time[0]); if (hours > 1) { $(this).text(hours + " hours ago"); return; } if (hours === 1) { $(this).text(hours + " hour ago"); return; } var mins = now.getMinutes() - parseInt(time[1]); if (mins > 1) { $(this).text(mins + " minutes ago"); return; } if (mins === 1) { $(this).text(mins + " minute ago"); return; } var secs = now.getSeconds() - parseInt(time[2]); if (secs > 1) { $(this).text(secs + " seconds ago"); return; } if (secs === 1) { $(this).text(secs + " second ago"); return; } $(this).text("right now"); }); $.each($(".time"), function() { var val = $(this).text(); var dt = val.split(" "); $(this).attr("title", val); $(this).text(dt[1]); }); });
stievie/Giddo
js/datetime.js
JavaScript
gpl-2.0
2,848
/* * Copyright (c) 1998-2015 Caucho Technology -- all rights reserved * * This file is part of Baratine(TM)(TM) * * Each copy or derived work must preserve the copyright notice and this * notice unmodified. * * Baratine 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. * * Baratine 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, or any warranty * of NON-INFRINGEMENT. See the GNU General Public License for more * details. * * You should have received a copy of the GNU General Public License * along with Baratine; if not, write to the * * Free Software Foundation, Inc. * 59 Temple Place, Suite 330 * Boston, MA 02111-1307 USA * * @author Scott Ferguson */ package io.baratine.pipe; import java.util.Map; /** * General message type for pipes. * * This Message API is designed to improve interoperability by providing a * useful default API. While pipes can use any message type, general messages * drivers like an AMQP broker or a mail sender need to choose one of * their own. * * Applications may be better served by using application-specific messages. * * @param <T> type of the encapsulated value */ public interface Message<T> { /** * Method value returns encapsulated message value. * * @return encapsulated value */ T value(); /** * Method headers returns optional header passed with the message * * @return map of headers */ Map<String,Object> headers(); /** * Method header returns value of a header matching a key * * @param key header key * @return header value */ Object header(String key); /** * Create an instance of a MessageBuilder using passed value as an encapsulated * Message value. * * @param value value to encapsulate in a message * @param <X> type of the value * @return an instance of MessageBuilder */ static <X> MessageBuilder<X> newMessage(X value) { return new MessageImpl<>(value); } /** * MessageBuilder interface allows setting properties for a Message, such as * headers. * * @param <T> type of a value encapsulated in a Message */ interface MessageBuilder<T> extends Message<T> { MessageBuilder<T> header(String key, Object value); } }
baratine/baratine
api/src/main/java/io/baratine/pipe/Message.java
Java
gpl-2.0
2,551
/* * Copyright (C) 2006-2010 Alex Lasnier <alex@fepg.org> * * This file is part of ATSC EPG * * 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, see <http://www.gnu.org/licenses/>. */ #ifndef __ATSC_SCANNER_H #define __ATSC_SCANNER_H #include <list> #include <vdr/device.h> #include <vdr/filter.h> #include <vdr/osdbase.h> ////////////////////////////////////////////////////////////////////////////// class cATSCScanner : public cOsdMenu, public cThread, public cFilter { public: cATSCScanner(void); virtual ~cATSCScanner(); virtual eOSState ProcessKey(eKeys Key); protected: virtual void Action(void); virtual void Process(u_short Pid, u_char Tid, const u_char *Data, int Length); private: void AddLine(const char* Text, ...); void UpdateLastLine(const char* Text); int Number(uint16_t major, uint16_t minor); void SetTransponderData(cChannel* c); void ProcessVCT(u_char Tid, const u_char* Data, int Length); void ProcessPAT(const u_char* Data, int Length); bool ProcessPMT(const u_char* Data, int Length); cCondWait condWait; bool gotPAT; bool gotVCT; bool gotPMT; int tsid; std::list<uint16_t> pmtSIDs; bool devSelection; int currentFrequency; const char* dir; char* numberCmd; FILE* file; int deviceNum; int modulation; int ignoreEncrypted; const char* deviceNames[MAXDEVICES]; }; ////////////////////////////////////////////////////////////////////////////// #endif //__ATSC_SCANNER_H
garbear/atscepg
scanner.h
C
gpl-2.0
2,037
package org.caliog.myRPG.Mobs; import org.bukkit.entity.Entity; import org.caliog.myRPG.Manager; import org.caliog.myRPG.Entities.PlayerManager; import org.caliog.myRPG.Entities.myClass; import org.caliog.myRPG.Utils.EntityUtils; public class PetController { public static void controll() { for (final myClass player : PlayerManager.getPlayers()) { if (player.getPets().isEmpty()) continue; for (final Pet pet : player.getPets()) { Entity entity = EntityUtils.getEntity(pet.getId(), player.getPlayer().getWorld()); if (entity == null) continue; if (entity.getLocation().distanceSquared(player.getPlayer().getLocation()) > 512) { Manager.scheduleTask(new Runnable() { @Override public void run() { pet.die(player); } }); } } } } }
caliog/myRPG
src/org/caliog/myRPG/Mobs/PetController.java
Java
gpl-2.0
811
/* Elysian Fields is a 2D game programmed in C# with the framework MonoGame Copyright (C) 2015 Erik Iwarson If you have any questions, don't hesitate to send me an e-mail at erikiwarson@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 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. */ using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace Elysian_Fields { class DamageObject { public Creature creature; public int ID; public int damageDealt; public int EndTime; public int StartTime; public const int Steps = 30; public const int DamageDuration = 1000; public const int Text_Damage = 1; public const int Text_Healing = 2; public const int Text_Experience = 3; public int StepDuration { get { return DamageDuration / Steps; } set { } } public int CurrentStep = 0; public int Text_Type = 0; //public bool Healing; //public int OffsetX public Coordinates Position = new Coordinates(); //public int StartOffsetX; public double StartOffsetY = 15; //public int EndOffsetX; //public int EndOffsetY = 0; public DamageObject() { ID = -1; } public DamageObject(Creature monster, int Damage, int _text_type, int _StartTime, int _EndTime, int id = 0, Coordinates pos = null) { creature = monster; damageDealt = Damage; ID = id; EndTime = _EndTime; StartTime = _StartTime; Position = pos; Text_Type = _text_type; } public double OffsetY(int CurrentTime) { double CurrentStepEndTime = StartTime + DamageDuration - ((Steps - CurrentStep) * StepDuration); if (CurrentTime >= CurrentStepEndTime) { if(CurrentStep < Steps) CurrentStep++; } return StartOffsetY - (CurrentStep * (StartOffsetY / Steps)); } } }
Szune/Elysian-Fields
Elysian Fields/Elysian Fields/DamageObject.cs
C#
gpl-2.0
2,733
/* Configuration defines for installed libtiff. This file maintained for backward compatibility. Do not use definitions from this file in your programs. */ #ifndef _TIFFCONF_ #define _TIFFCONF_ /* Signed 16-bit type */ #define TIFF_INT16_T signed short /* Signed 32-bit type */ #define TIFF_INT32_T signed int /* Signed 64-bit type */ #define TIFF_INT64_T signed long long /* Signed 8-bit type */ #define TIFF_INT8_T signed char /* Unsigned 16-bit type */ #define TIFF_UINT16_T unsigned short /* Unsigned 32-bit type */ #define TIFF_UINT32_T unsigned int /* Unsigned 64-bit type */ #define TIFF_UINT64_T unsigned long long /* Unsigned 8-bit type */ #define TIFF_UINT8_T unsigned char /* Unsigned size type */ #define TIFF_SIZE_T unsigned long /* Signed size type */ #define TIFF_SSIZE_T signed long long /* Pointer difference type */ #define TIFF_PTRDIFF_T ptrdiff_t /* Define to 1 if the system has the type `int16'. */ /* #undef HAVE_INT16 */ /* Define to 1 if the system has the type `int32'. */ /* #undef HAVE_INT32 */ /* Define to 1 if the system has the type `int8'. */ /* #undef HAVE_INT8 */ /* Compatibility stuff. */ /* Define as 0 or 1 according to the floating point format suported by the machine */ #define HAVE_IEEEFP 1 /* Set the native cpu bit order (FILLORDER_LSB2MSB or FILLORDER_MSB2LSB) */ #define HOST_FILLORDER FILLORDER_MSB2LSB /* Native cpu byte order: 1 if big-endian (Motorola) or 0 if little-endian (Intel) */ #define HOST_BIGENDIAN 0 /* Support CCITT Group 3 & 4 algorithms */ #define CCITT_SUPPORT 1 /* Support JPEG compression (requires IJG JPEG library) */ /* #undef JPEG_SUPPORT */ /* Support JBIG compression (requires JBIG-KIT library) */ /* #undef JBIG_SUPPORT */ /* Support LogLuv high dynamic range encoding */ #define LOGLUV_SUPPORT 1 /* Support LZW algorithm */ #define LZW_SUPPORT 1 /* Support NeXT 2-bit RLE algorithm */ #define NEXT_SUPPORT 1 /* Support Old JPEG compresson (read contrib/ojpeg/README first! Compilation fails with unpatched IJG JPEG library) */ /* #undef OJPEG_SUPPORT */ /* Support Macintosh PackBits algorithm */ #define PACKBITS_SUPPORT 1 /* Support Pixar log-format algorithm (requires Zlib) */ /* #undef PIXARLOG_SUPPORT */ /* Support ThunderScan 4-bit RLE algorithm */ #define THUNDER_SUPPORT 1 /* Support Deflate compression */ /* #undef ZIP_SUPPORT */ /* Support strip chopping (whether or not to convert single-strip uncompressed images to mutiple strips of ~8Kb to reduce memory usage) */ #define STRIPCHOP_DEFAULT 1 /* Enable SubIFD tag (330) support */ #define SUBIFD_SUPPORT 1 /* Treat extra sample as alpha (default enabled). The RGBA interface will treat a fourth sample with no EXTRASAMPLE_ value as being ASSOCALPHA. Many packages produce RGBA files but don't mark the alpha properly. */ #define DEFAULT_EXTRASAMPLE_AS_ALPHA 1 /* Pick up YCbCr subsampling info from the JPEG data stream to support files lacking the tag (default enabled). */ #define CHECK_JPEG_YCBCR_SUBSAMPLING 1 /* Support MS MDI magic number files as TIFF */ #define MDI_SUPPORT 1 /* * Feature support definitions. * XXX: These macros are obsoleted. Don't use them in your apps! * Macros stays here for backward compatibility and should be always defined. */ #define COLORIMETRY_SUPPORT #define YCBCR_SUPPORT #define CMYK_SUPPORT #define ICC_SUPPORT #define PHOTOSHOP_SUPPORT #define IPTC_SUPPORT #endif /* _TIFFCONF_ */
sumedhghaisas/gyp-libtiff
config/win/x64/tiffconf.h
C
gpl-2.0
3,435
/* * Copyright 2001-2004 The Apache Software Foundation. * * 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.apache.xerces.impl.xs; import java.util.Vector; import org.apache.xerces.impl.Constants; import org.apache.xerces.impl.dv.SchemaDVFactory; import org.apache.xerces.impl.dv.ValidatedInfo; import org.apache.xerces.impl.dv.XSSimpleType; import org.apache.xerces.impl.xs.identity.IdentityConstraint; import org.apache.xerces.impl.xs.util.SimpleLocator; import org.apache.xerces.impl.xs.util.StringListImpl; import org.apache.xerces.impl.xs.util.XSNamedMap4Types; import org.apache.xerces.impl.xs.util.XSNamedMapImpl; import org.apache.xerces.impl.xs.util.XSObjectListImpl; import org.apache.xerces.parsers.DOMParser; import org.apache.xerces.parsers.IntegratedParserConfiguration; import org.apache.xerces.parsers.SAXParser; import org.apache.xerces.util.SymbolHash; import org.apache.xerces.util.SymbolTable; import org.apache.xerces.xni.NamespaceContext; import org.apache.xerces.xni.grammars.XMLGrammarDescription; import org.apache.xerces.xni.grammars.XSGrammar; import org.apache.xerces.xs.StringList; import org.apache.xerces.xs.XSAnnotation; import org.apache.xerces.xs.XSAttributeDeclaration; import org.apache.xerces.xs.XSAttributeGroupDefinition; import org.apache.xerces.xs.XSConstants; import org.apache.xerces.xs.XSElementDeclaration; import org.apache.xerces.xs.XSModel; import org.apache.xerces.xs.XSModelGroupDefinition; import org.apache.xerces.xs.XSNamedMap; import org.apache.xerces.xs.XSNamespaceItem; import org.apache.xerces.xs.XSNotationDeclaration; import org.apache.xerces.xs.XSObjectList; import org.apache.xerces.xs.XSParticle; import org.apache.xerces.xs.XSTypeDefinition; import org.apache.xerces.xs.XSWildcard; /** * This class is to hold all schema component declaration that are declared * within one namespace. * * The Grammar class this class extends contains what little * commonality there is between XML Schema and DTD grammars. It's * useful to distinguish grammar objects from other kinds of object * when they exist in pools or caches. * * @xerces.internal * * @author Sandy Gao, IBM * @author Elena Litani, IBM * * @version $Id: SchemaGrammar.java,v 1.42 2004/12/15 23:48:48 mrglavas Exp $ */ public class SchemaGrammar implements XSGrammar, XSNamespaceItem { // the target namespace of grammar String fTargetNamespace; // global decls: map from decl name to decl object SymbolHash fGlobalAttrDecls; SymbolHash fGlobalAttrGrpDecls; SymbolHash fGlobalElemDecls; SymbolHash fGlobalGroupDecls; SymbolHash fGlobalNotationDecls; SymbolHash fGlobalIDConstraintDecls; SymbolHash fGlobalTypeDecls; // the XMLGrammarDescription member XSDDescription fGrammarDescription = null; // annotations associated with the "root" schema of this targetNamespace XSAnnotationImpl [] fAnnotations = null; // number of annotations declared int fNumAnnotations; // symbol table for constructing parsers (annotation support) private SymbolTable fSymbolTable = null; // parsers for annotation support private SAXParser fSAXParser = null; private DOMParser fDOMParser = null; // // Constructors // // needed to make BuiltinSchemaGrammar work. protected SchemaGrammar() {} /** * Default constructor. * * @param targetNamespace * @param grammarDesc the XMLGrammarDescription corresponding to this objec * at the least a systemId should always be known. * @param symbolTable needed for annotation support */ public SchemaGrammar(String targetNamespace, XSDDescription grammarDesc, SymbolTable symbolTable) { fTargetNamespace = targetNamespace; fGrammarDescription = grammarDesc; fSymbolTable = symbolTable; // REVISIT: do we know the numbers of the following global decls // when creating this grammar? If so, we can pass the numbers in, // and use that number to initialize the following hashtables. fGlobalAttrDecls = new SymbolHash(); fGlobalAttrGrpDecls = new SymbolHash(); fGlobalElemDecls = new SymbolHash(); fGlobalGroupDecls = new SymbolHash(); fGlobalNotationDecls = new SymbolHash(); fGlobalIDConstraintDecls = new SymbolHash(); // if we are parsing S4S, put built-in types in first // they might get overwritten by the types from S4S, but that's // considered what the application wants to do. if (fTargetNamespace == SchemaSymbols.URI_SCHEMAFORSCHEMA) fGlobalTypeDecls = SG_SchemaNS.fGlobalTypeDecls.makeClone(); else fGlobalTypeDecls = new SymbolHash(); } // <init>(String, XSDDescription) // number of built-in XSTypes we need to create for base and full // datatype set private static final int BASICSET_COUNT = 29; private static final int FULLSET_COUNT = 46; private static final int GRAMMAR_XS = 1; private static final int GRAMMAR_XSI = 2; // this class makes sure the static, built-in schema grammars // are immutable. public static class BuiltinSchemaGrammar extends SchemaGrammar { /** * Special constructor to create the grammars for the schema namespaces * * @param grammar */ public BuiltinSchemaGrammar(int grammar) { SchemaDVFactory schemaFactory = SchemaDVFactory.getInstance(); if (grammar == GRAMMAR_XS) { // target namespace fTargetNamespace = SchemaSymbols.URI_SCHEMAFORSCHEMA; // grammar description fGrammarDescription = new XSDDescription(); fGrammarDescription.fContextType = XSDDescription.CONTEXT_PREPARSE; fGrammarDescription.setNamespace(SchemaSymbols.URI_SCHEMAFORSCHEMA); // no global decls other than types fGlobalAttrDecls = new SymbolHash(1); fGlobalAttrGrpDecls = new SymbolHash(1); fGlobalElemDecls = new SymbolHash(1); fGlobalGroupDecls = new SymbolHash(1); fGlobalNotationDecls = new SymbolHash(1); fGlobalIDConstraintDecls = new SymbolHash(1); // get all built-in types fGlobalTypeDecls = schemaFactory.getBuiltInTypes(); // add anyType fGlobalTypeDecls.put(fAnyType.getName(), fAnyType); } else if (grammar == GRAMMAR_XSI) { // target namespace fTargetNamespace = SchemaSymbols.URI_XSI; // grammar description fGrammarDescription = new XSDDescription(); fGrammarDescription.fContextType = XSDDescription.CONTEXT_PREPARSE; fGrammarDescription.setNamespace(SchemaSymbols.URI_XSI); // no global decls other than attributes fGlobalAttrGrpDecls = new SymbolHash(1); fGlobalElemDecls = new SymbolHash(1); fGlobalGroupDecls = new SymbolHash(1); fGlobalNotationDecls = new SymbolHash(1); fGlobalIDConstraintDecls = new SymbolHash(1); fGlobalTypeDecls = new SymbolHash(1); // 4 attributes, so initialize the size as 4*2 = 8 fGlobalAttrDecls = new SymbolHash(8); String name = null; String tns = null; XSSimpleType type = null; short scope = XSConstants.SCOPE_GLOBAL; // xsi:type name = SchemaSymbols.XSI_TYPE; tns = SchemaSymbols.URI_XSI; type = schemaFactory.getBuiltInType(SchemaSymbols.ATTVAL_QNAME); fGlobalAttrDecls.put(name, new BuiltinAttrDecl(name, tns, type, scope)); // xsi:nil name = SchemaSymbols.XSI_NIL; tns = SchemaSymbols.URI_XSI; type = schemaFactory.getBuiltInType(SchemaSymbols.ATTVAL_BOOLEAN); fGlobalAttrDecls.put(name, new BuiltinAttrDecl(name, tns, type, scope)); XSSimpleType anyURI = schemaFactory.getBuiltInType(SchemaSymbols.ATTVAL_ANYURI); // xsi:schemaLocation name = SchemaSymbols.XSI_SCHEMALOCATION; tns = SchemaSymbols.URI_XSI; type = schemaFactory.createTypeList(null, SchemaSymbols.URI_XSI, (short)0, anyURI, null); fGlobalAttrDecls.put(name, new BuiltinAttrDecl(name, tns, type, scope)); // xsi:noNamespaceSchemaLocation name = SchemaSymbols.XSI_NONAMESPACESCHEMALOCATION; tns = SchemaSymbols.URI_XSI; type = anyURI; fGlobalAttrDecls.put(name, new BuiltinAttrDecl(name, tns, type, scope)); } } // <init>(int) // return the XMLGrammarDescription corresponding to this // object public XMLGrammarDescription getGrammarDescription() { return fGrammarDescription.makeClone(); } // getGrammarDescription(): XMLGrammarDescription // override these methods solely so that these // objects cannot be modified once they're created. public void setImportedGrammars(Vector importedGrammars) { // ignore } public void addGlobalAttributeDecl(XSAttributeDecl decl) { // ignore } public void addGlobalAttributeGroupDecl(XSAttributeGroupDecl decl) { // ignore } public void addGlobalElementDecl(XSElementDecl decl) { // ignore } public void addGlobalGroupDecl(XSGroupDecl decl) { // ignore } public void addGlobalNotationDecl(XSNotationDecl decl) { // ignore } public void addGlobalTypeDecl(XSTypeDefinition decl) { // ignore } public void addComplexTypeDecl(XSComplexTypeDecl decl, SimpleLocator locator) { // ignore } public void addRedefinedGroupDecl(XSGroupDecl derived, XSGroupDecl base, SimpleLocator locator) { // ignore } public synchronized void addDocument(Object document, String location) { // ignore } // annotation support synchronized DOMParser getDOMParser() { return null; } synchronized SAXParser getSAXParser() { return null; } } /** * <p>A partial schema for schemas for validating annotations.</p> * * @xerces.internal * * @author Michael Glavassevich, IBM */ public static final class Schema4Annotations extends SchemaGrammar { /** * Special constructor to create a schema * capable of validating annotations. */ public Schema4Annotations() { // target namespace fTargetNamespace = SchemaSymbols.URI_SCHEMAFORSCHEMA; // grammar description fGrammarDescription = new XSDDescription(); fGrammarDescription.fContextType = XSDDescription.CONTEXT_PREPARSE; fGrammarDescription.setNamespace(SchemaSymbols.URI_SCHEMAFORSCHEMA); // no global decls other than types and // element declarations for <annotation>, <documentation> and <appinfo>. fGlobalAttrDecls = new SymbolHash(1); fGlobalAttrGrpDecls = new SymbolHash(1); fGlobalElemDecls = new SymbolHash(6); fGlobalGroupDecls = new SymbolHash(1); fGlobalNotationDecls = new SymbolHash(1); fGlobalIDConstraintDecls = new SymbolHash(1); // get all built-in types fGlobalTypeDecls = SG_SchemaNS.fGlobalTypeDecls; // create element declarations for <annotation>, <documentation> and <appinfo> XSElementDecl annotationDecl = createAnnotationElementDecl(SchemaSymbols.ELT_ANNOTATION); XSElementDecl documentationDecl = createAnnotationElementDecl(SchemaSymbols.ELT_DOCUMENTATION); XSElementDecl appinfoDecl = createAnnotationElementDecl(SchemaSymbols.ELT_APPINFO); // add global element declarations fGlobalElemDecls.put(annotationDecl.fName, annotationDecl); fGlobalElemDecls.put(documentationDecl.fName, documentationDecl); fGlobalElemDecls.put(appinfoDecl.fName, appinfoDecl); // create complex type declarations for <annotation>, <documentation> and <appinfo> XSComplexTypeDecl annotationType = new XSComplexTypeDecl(); XSComplexTypeDecl documentationType = new XSComplexTypeDecl(); XSComplexTypeDecl appinfoType = new XSComplexTypeDecl(); // set the types on their element declarations annotationDecl.fType = annotationType; documentationDecl.fType = documentationType; appinfoDecl.fType = appinfoType; // create attribute groups for <annotation>, <documentation> and <appinfo> XSAttributeGroupDecl annotationAttrs = new XSAttributeGroupDecl(); XSAttributeGroupDecl documentationAttrs = new XSAttributeGroupDecl(); XSAttributeGroupDecl appinfoAttrs = new XSAttributeGroupDecl(); // fill in attribute groups { // create and fill attribute uses for <annotation>, <documentation> and <appinfo> XSAttributeUseImpl annotationIDAttr = new XSAttributeUseImpl(); annotationIDAttr.fAttrDecl = new XSAttributeDecl(); annotationIDAttr.fAttrDecl.setValues(SchemaSymbols.ATT_ID, null, (XSSimpleType) fGlobalTypeDecls.get(SchemaSymbols.ATTVAL_ID), XSConstants.VC_NONE, XSConstants.SCOPE_LOCAL, null, annotationType, null); annotationIDAttr.fUse = SchemaSymbols.USE_OPTIONAL; annotationIDAttr.fConstraintType = XSConstants.VC_NONE; XSAttributeUseImpl documentationSourceAttr = new XSAttributeUseImpl(); documentationSourceAttr.fAttrDecl = new XSAttributeDecl(); documentationSourceAttr.fAttrDecl.setValues(SchemaSymbols.ATT_SOURCE, null, (XSSimpleType) fGlobalTypeDecls.get(SchemaSymbols.ATTVAL_ANYURI), XSConstants.VC_NONE, XSConstants.SCOPE_LOCAL, null, documentationType, null); documentationSourceAttr.fUse = SchemaSymbols.USE_OPTIONAL; documentationSourceAttr.fConstraintType = XSConstants.VC_NONE; XSAttributeUseImpl documentationLangAttr = new XSAttributeUseImpl(); documentationLangAttr.fAttrDecl = new XSAttributeDecl(); documentationLangAttr.fAttrDecl.setValues("lang".intern(), NamespaceContext.XML_URI, (XSSimpleType) fGlobalTypeDecls.get(SchemaSymbols.ATTVAL_LANGUAGE), XSConstants.VC_NONE, XSConstants.SCOPE_LOCAL, null, documentationType, null); documentationLangAttr.fUse = SchemaSymbols.USE_OPTIONAL; documentationLangAttr.fConstraintType = XSConstants.VC_NONE; XSAttributeUseImpl appinfoSourceAttr = new XSAttributeUseImpl(); appinfoSourceAttr.fAttrDecl = new XSAttributeDecl(); appinfoSourceAttr.fAttrDecl.setValues(SchemaSymbols.ATT_SOURCE, null, (XSSimpleType) fGlobalTypeDecls.get(SchemaSymbols.ATTVAL_ANYURI), XSConstants.VC_NONE, XSConstants.SCOPE_LOCAL, null, appinfoType, null); appinfoSourceAttr.fUse = SchemaSymbols.USE_OPTIONAL; appinfoSourceAttr.fConstraintType = XSConstants.VC_NONE; // create lax attribute wildcard for <annotation>, <documentation> and <appinfo> XSWildcardDecl otherAttrs = new XSWildcardDecl(); otherAttrs.fNamespaceList = new String [] {fTargetNamespace, null}; otherAttrs.fType = XSWildcard.NSCONSTRAINT_NOT; otherAttrs.fProcessContents = XSWildcard.PC_LAX; // add attribute uses and wildcards to attribute groups for <annotation>, <documentation> and <appinfo> annotationAttrs.addAttributeUse(annotationIDAttr); annotationAttrs.fAttributeWC = otherAttrs; documentationAttrs.addAttributeUse(documentationSourceAttr); documentationAttrs.addAttributeUse(documentationLangAttr); documentationAttrs.fAttributeWC = otherAttrs; appinfoAttrs.addAttributeUse(appinfoSourceAttr); appinfoAttrs.fAttributeWC = otherAttrs; } // create particles for <annotation> XSParticleDecl annotationParticle = createUnboundedModelGroupParticle(); { XSModelGroupImpl annotationChoice = new XSModelGroupImpl(); annotationChoice.fCompositor = XSModelGroupImpl.MODELGROUP_CHOICE; annotationChoice.fParticleCount = 2; annotationChoice.fParticles = new XSParticleDecl[2]; annotationChoice.fParticles[0] = createChoiceElementParticle(appinfoDecl); annotationChoice.fParticles[1] = createChoiceElementParticle(documentationDecl); annotationParticle.fValue = annotationChoice; } // create wildcard particle for <documentation> and <appinfo> XSParticleDecl anyWCSequenceParticle = createUnboundedAnyWildcardSequenceParticle(); // fill complex types annotationType.setValues("#AnonType_" + SchemaSymbols.ELT_ANNOTATION, fTargetNamespace, SchemaGrammar.fAnyType, XSConstants.DERIVATION_RESTRICTION, XSConstants.DERIVATION_NONE, (short) (XSConstants.DERIVATION_EXTENSION | XSConstants.DERIVATION_RESTRICTION), XSComplexTypeDecl.CONTENTTYPE_ELEMENT, false, annotationAttrs, null, annotationParticle, new XSObjectListImpl(null, 0)); annotationType.setName("#AnonType_" + SchemaSymbols.ELT_ANNOTATION); annotationType.setIsAnonymous(); documentationType.setValues("#AnonType_" + SchemaSymbols.ELT_DOCUMENTATION, fTargetNamespace, SchemaGrammar.fAnyType, XSConstants.DERIVATION_RESTRICTION, XSConstants.DERIVATION_NONE, (short) (XSConstants.DERIVATION_EXTENSION | XSConstants.DERIVATION_RESTRICTION), XSComplexTypeDecl.CONTENTTYPE_MIXED, false, documentationAttrs, null, anyWCSequenceParticle, new XSObjectListImpl(null, 0)); documentationType.setName("#AnonType_" + SchemaSymbols.ELT_DOCUMENTATION); documentationType.setIsAnonymous(); appinfoType.setValues("#AnonType_" + SchemaSymbols.ELT_APPINFO, fTargetNamespace, SchemaGrammar.fAnyType, XSConstants.DERIVATION_RESTRICTION, XSConstants.DERIVATION_NONE, (short) (XSConstants.DERIVATION_EXTENSION | XSConstants.DERIVATION_RESTRICTION), XSComplexTypeDecl.CONTENTTYPE_MIXED, false, appinfoAttrs, null, anyWCSequenceParticle, new XSObjectListImpl(null, 0)); appinfoType.setName("#AnonType_" + SchemaSymbols.ELT_APPINFO); appinfoType.setIsAnonymous(); } // <init>(int) // return the XMLGrammarDescription corresponding to this // object public XMLGrammarDescription getGrammarDescription() { return fGrammarDescription.makeClone(); } // getGrammarDescription(): XMLGrammarDescription // override these methods solely so that these // objects cannot be modified once they're created. public void setImportedGrammars(Vector importedGrammars) { // ignore } public void addGlobalAttributeDecl(XSAttributeDecl decl) { // ignore } public void addGlobalAttributeGroupDecl(XSAttributeGroupDecl decl) { // ignore } public void addGlobalElementDecl(XSElementDecl decl) { // ignore } public void addGlobalGroupDecl(XSGroupDecl decl) { // ignore } public void addGlobalNotationDecl(XSNotationDecl decl) { // ignore } public void addGlobalTypeDecl(XSTypeDefinition decl) { // ignore } public void addComplexTypeDecl(XSComplexTypeDecl decl, SimpleLocator locator) { // ignore } public void addRedefinedGroupDecl(XSGroupDecl derived, XSGroupDecl base, SimpleLocator locator) { // ignore } public synchronized void addDocument(Object document, String location) { // ignore } // annotation support synchronized DOMParser getDOMParser() { return null; } synchronized SAXParser getSAXParser() { return null; } // // private helper methods // private XSElementDecl createAnnotationElementDecl(String localName) { XSElementDecl eDecl = new XSElementDecl(); eDecl.fName = localName; eDecl.fTargetNamespace = fTargetNamespace; eDecl.setIsGlobal(); eDecl.fBlock = (XSConstants.DERIVATION_EXTENSION | XSConstants.DERIVATION_RESTRICTION | XSConstants.DERIVATION_SUBSTITUTION); eDecl.setConstraintType(XSConstants.VC_NONE); return eDecl; } private XSParticleDecl createUnboundedModelGroupParticle() { XSParticleDecl particle = new XSParticleDecl(); particle.fMinOccurs = 0; particle.fMaxOccurs = SchemaSymbols.OCCURRENCE_UNBOUNDED; particle.fType = XSParticleDecl.PARTICLE_MODELGROUP; return particle; } private XSParticleDecl createChoiceElementParticle(XSElementDecl ref) { XSParticleDecl particle = new XSParticleDecl(); particle.fMinOccurs = 1; particle.fMaxOccurs = 1; particle.fType = XSParticleDecl.PARTICLE_ELEMENT; particle.fValue = ref; return particle; } private XSParticleDecl createUnboundedAnyWildcardSequenceParticle() { XSParticleDecl particle = createUnboundedModelGroupParticle(); XSModelGroupImpl sequence = new XSModelGroupImpl(); sequence.fCompositor = XSModelGroupImpl.MODELGROUP_SEQUENCE; sequence.fParticleCount = 1; sequence.fParticles = new XSParticleDecl[1]; sequence.fParticles[0] = createAnyLaxWildcardParticle(); particle.fValue = sequence; return particle; } private XSParticleDecl createAnyLaxWildcardParticle() { XSParticleDecl particle = new XSParticleDecl(); particle.fMinOccurs = 1; particle.fMaxOccurs = 1; particle.fType = XSParticleDecl.PARTICLE_WILDCARD; XSWildcardDecl anyWC = new XSWildcardDecl(); anyWC.fNamespaceList = null; anyWC.fType = XSWildcard.NSCONSTRAINT_ANY; anyWC.fProcessContents = XSWildcard.PC_LAX; particle.fValue = anyWC; return particle; } } // Grammar methods // return the XMLGrammarDescription corresponding to this // object public XMLGrammarDescription getGrammarDescription() { return fGrammarDescription; } // getGrammarDescription(): XMLGrammarDescription // DTDGrammar methods public boolean isNamespaceAware () { return true; } // isNamespaceAware():boolean Vector fImported = null; public void setImportedGrammars(Vector importedGrammars) { fImported = importedGrammars; } public Vector getImportedGrammars() { return fImported; } /** * Returns this grammar's target namespace. */ public final String getTargetNamespace() { return fTargetNamespace; } // getTargetNamespace():String /** * register one global attribute */ public void addGlobalAttributeDecl(XSAttributeDecl decl) { fGlobalAttrDecls.put(decl.fName, decl); } /** * register one global attribute group */ public void addGlobalAttributeGroupDecl(XSAttributeGroupDecl decl) { fGlobalAttrGrpDecls.put(decl.fName, decl); } /** * register one global element */ public void addGlobalElementDecl(XSElementDecl decl) { fGlobalElemDecls.put(decl.fName, decl); // if there is a substitution group affiliation, store in an array, // for further constraint checking: UPA, PD, EDC if (decl.fSubGroup != null) { if (fSubGroupCount == fSubGroups.length) fSubGroups = resize(fSubGroups, fSubGroupCount+INC_SIZE); fSubGroups[fSubGroupCount++] = decl; } } /** * register one global group */ public void addGlobalGroupDecl(XSGroupDecl decl) { fGlobalGroupDecls.put(decl.fName, decl); } /** * register one global notation */ public void addGlobalNotationDecl(XSNotationDecl decl) { fGlobalNotationDecls.put(decl.fName, decl); } /** * register one global type */ public void addGlobalTypeDecl(XSTypeDefinition decl) { fGlobalTypeDecls.put(decl.getName(), decl); } /** * register one identity constraint */ public final void addIDConstraintDecl(XSElementDecl elmDecl, IdentityConstraint decl) { elmDecl.addIDConstraint(decl); fGlobalIDConstraintDecls.put(decl.getIdentityConstraintName(), decl); } /** * get one global attribute */ public final XSAttributeDecl getGlobalAttributeDecl(String declName) { return(XSAttributeDecl)fGlobalAttrDecls.get(declName); } /** * get one global attribute group */ public final XSAttributeGroupDecl getGlobalAttributeGroupDecl(String declName) { return(XSAttributeGroupDecl)fGlobalAttrGrpDecls.get(declName); } /** * get one global element */ public final XSElementDecl getGlobalElementDecl(String declName) { return(XSElementDecl)fGlobalElemDecls.get(declName); } /** * get one global group */ public final XSGroupDecl getGlobalGroupDecl(String declName) { return(XSGroupDecl)fGlobalGroupDecls.get(declName); } /** * get one global notation */ public final XSNotationDecl getGlobalNotationDecl(String declName) { return(XSNotationDecl)fGlobalNotationDecls.get(declName); } /** * get one global type */ public final XSTypeDefinition getGlobalTypeDecl(String declName) { return(XSTypeDefinition)fGlobalTypeDecls.get(declName); } /** * get one identity constraint */ public final IdentityConstraint getIDConstraintDecl(String declName) { return(IdentityConstraint)fGlobalIDConstraintDecls.get(declName); } /** * get one identity constraint */ public final boolean hasIDConstraints() { return fGlobalIDConstraintDecls.getLength() > 0; } // array to store complex type decls private static final int INITIAL_SIZE = 16; private static final int INC_SIZE = 16; private int fCTCount = 0; private XSComplexTypeDecl[] fComplexTypeDecls = new XSComplexTypeDecl[INITIAL_SIZE]; private SimpleLocator[] fCTLocators = new SimpleLocator[INITIAL_SIZE]; // an array to store groups being redefined by restriction // even-numbered elements are the derived groups, odd-numbered ones their bases private static final int REDEFINED_GROUP_INIT_SIZE = 2; private int fRGCount = 0; private XSGroupDecl[] fRedefinedGroupDecls = new XSGroupDecl[REDEFINED_GROUP_INIT_SIZE]; private SimpleLocator[] fRGLocators = new SimpleLocator[REDEFINED_GROUP_INIT_SIZE/2]; // a flag to indicate whether we have checked the 3 constraints on this // grammar. boolean fFullChecked = false; /** * add one complex type decl: for later constraint checking */ public void addComplexTypeDecl(XSComplexTypeDecl decl, SimpleLocator locator) { if (fCTCount == fComplexTypeDecls.length) { fComplexTypeDecls = resize(fComplexTypeDecls, fCTCount+INC_SIZE); fCTLocators = resize(fCTLocators, fCTCount+INC_SIZE); } fCTLocators[fCTCount] = locator; fComplexTypeDecls[fCTCount++] = decl; } /** * add a group redefined by restriction: for later constraint checking */ public void addRedefinedGroupDecl(XSGroupDecl derived, XSGroupDecl base, SimpleLocator locator) { if (fRGCount == fRedefinedGroupDecls.length) { // double array size each time. fRedefinedGroupDecls = resize(fRedefinedGroupDecls, fRGCount << 1); fRGLocators = resize(fRGLocators, fRGCount); } fRGLocators[fRGCount/2] = locator; fRedefinedGroupDecls[fRGCount++] = derived; fRedefinedGroupDecls[fRGCount++] = base; } /** * get all complex type decls: for later constraint checking */ final XSComplexTypeDecl[] getUncheckedComplexTypeDecls() { if (fCTCount < fComplexTypeDecls.length) { fComplexTypeDecls = resize(fComplexTypeDecls, fCTCount); fCTLocators = resize(fCTLocators, fCTCount); } return fComplexTypeDecls; } /** * get the error locator of all complex type decls */ final SimpleLocator[] getUncheckedCTLocators() { if (fCTCount < fCTLocators.length) { fComplexTypeDecls = resize(fComplexTypeDecls, fCTCount); fCTLocators = resize(fCTLocators, fCTCount); } return fCTLocators; } /** * get all redefined groups: for later constraint checking */ final XSGroupDecl[] getRedefinedGroupDecls() { if (fRGCount < fRedefinedGroupDecls.length) { fRedefinedGroupDecls = resize(fRedefinedGroupDecls, fRGCount); fRGLocators = resize(fRGLocators, fRGCount/2); } return fRedefinedGroupDecls; } /** * get the error locator of all redefined groups */ final SimpleLocator[] getRGLocators() { if (fRGCount < fRedefinedGroupDecls.length) { fRedefinedGroupDecls = resize(fRedefinedGroupDecls, fRGCount); fRGLocators = resize(fRGLocators, fRGCount/2); } return fRGLocators; } /** * after the first-round checking, some types don't need to be checked * against UPA again. here we trim the array to the proper size. */ final void setUncheckedTypeNum(int newSize) { fCTCount = newSize; fComplexTypeDecls = resize(fComplexTypeDecls, fCTCount); fCTLocators = resize(fCTLocators, fCTCount); } // used to store all substitution group information declared in // this namespace private int fSubGroupCount = 0; private XSElementDecl[] fSubGroups = new XSElementDecl[INITIAL_SIZE]; /** * get all substitution group information: for the 3 constraint checking */ final XSElementDecl[] getSubstitutionGroups() { if (fSubGroupCount < fSubGroups.length) fSubGroups = resize(fSubGroups, fSubGroupCount); return fSubGroups; } // anyType and anySimpleType: because there are so many places where // we need direct access to these two types public final static XSComplexTypeDecl fAnyType = new XSAnyType(); private static class XSAnyType extends XSComplexTypeDecl { public XSAnyType () { fName = SchemaSymbols.ATTVAL_ANYTYPE; super.fTargetNamespace = SchemaSymbols.URI_SCHEMAFORSCHEMA; fBaseType = this; fDerivedBy = XSConstants.DERIVATION_RESTRICTION; fContentType = XSComplexTypeDecl.CONTENTTYPE_MIXED; fParticle = null; fAttrGrp = null; } // overridden methods public void setValues(String name, String targetNamespace, XSTypeDefinition baseType, short derivedBy, short schemaFinal, short block, short contentType, boolean isAbstract, XSAttributeGroupDecl attrGrp, XSSimpleType simpleType, XSParticleDecl particle) { // don't allow this. } public void setName(String name){ // don't allow this. } public void setIsAbstractType() { // null implementation } public void setContainsTypeID() { // null implementation } public void setIsAnonymous() { // null implementation } public void reset() { // null implementation } public XSObjectList getAttributeUses() { return new XSObjectListImpl(null, 0); } public XSAttributeGroupDecl getAttrGrp() { XSWildcardDecl wildcard = new XSWildcardDecl(); wildcard.fProcessContents = XSWildcardDecl.PC_LAX; XSAttributeGroupDecl attrGrp = new XSAttributeGroupDecl(); attrGrp.fAttributeWC = wildcard; return attrGrp; } public XSWildcard getAttributeWildcard() { XSWildcardDecl wildcard = new XSWildcardDecl(); wildcard.fProcessContents = XSWildcardDecl.PC_LAX; return wildcard; } public XSParticle getParticle() { // the wildcard used in anyType (content and attribute) // the spec will change strict to skip for anyType XSWildcardDecl wildcard = new XSWildcardDecl(); wildcard.fProcessContents = XSWildcardDecl.PC_LAX; // the particle for the content wildcard XSParticleDecl particleW = new XSParticleDecl(); particleW.fMinOccurs = 0; particleW.fMaxOccurs = SchemaSymbols.OCCURRENCE_UNBOUNDED; particleW.fType = XSParticleDecl.PARTICLE_WILDCARD; particleW.fValue = wildcard; // the model group of a sequence of the above particle XSModelGroupImpl group = new XSModelGroupImpl(); group.fCompositor = XSModelGroupImpl.MODELGROUP_SEQUENCE; group.fParticleCount = 1; group.fParticles = new XSParticleDecl[1]; group.fParticles[0] = particleW; // the content of anyType: particle of the above model group XSParticleDecl particleG = new XSParticleDecl(); particleG.fType = XSParticleDecl.PARTICLE_MODELGROUP; particleG.fValue = group; return particleG; } public XSObjectList getAnnotations() { return null; } } private static class BuiltinAttrDecl extends XSAttributeDecl { public BuiltinAttrDecl(String name, String tns, XSSimpleType type, short scope) { fName = name; super.fTargetNamespace = tns; fType = type; fScope = scope; } public void setValues(String name, String targetNamespace, XSSimpleType simpleType, short constraintType, short scope, ValidatedInfo valInfo, XSComplexTypeDecl enclosingCT) { // ignore this call. } public void reset () { // also ignore this call. } public XSAnnotation getAnnotation() { return null; } } // class BuiltinAttrDecl // the grammars to hold components of the schema namespace public final static BuiltinSchemaGrammar SG_SchemaNS = new BuiltinSchemaGrammar(GRAMMAR_XS); public final static Schema4Annotations SG_Schema4Annotations = new Schema4Annotations(); public final static XSSimpleType fAnySimpleType = (XSSimpleType)SG_SchemaNS.getGlobalTypeDecl(SchemaSymbols.ATTVAL_ANYSIMPLETYPE); // the grammars to hold components of the schema-instance namespace public final static BuiltinSchemaGrammar SG_XSI = new BuiltinSchemaGrammar(GRAMMAR_XSI); static final XSComplexTypeDecl[] resize(XSComplexTypeDecl[] oldArray, int newSize) { XSComplexTypeDecl[] newArray = new XSComplexTypeDecl[newSize]; System.arraycopy(oldArray, 0, newArray, 0, Math.min(oldArray.length, newSize)); return newArray; } static final XSGroupDecl[] resize(XSGroupDecl[] oldArray, int newSize) { XSGroupDecl[] newArray = new XSGroupDecl[newSize]; System.arraycopy(oldArray, 0, newArray, 0, Math.min(oldArray.length, newSize)); return newArray; } static final XSElementDecl[] resize(XSElementDecl[] oldArray, int newSize) { XSElementDecl[] newArray = new XSElementDecl[newSize]; System.arraycopy(oldArray, 0, newArray, 0, Math.min(oldArray.length, newSize)); return newArray; } static final SimpleLocator[] resize(SimpleLocator[] oldArray, int newSize) { SimpleLocator[] newArray = new SimpleLocator[newSize]; System.arraycopy(oldArray, 0, newArray, 0, Math.min(oldArray.length, newSize)); return newArray; } // XSNamespaceItem methods // the max index / the max value of XSObject type private static final short MAX_COMP_IDX = XSTypeDefinition.SIMPLE_TYPE; private static final boolean[] GLOBAL_COMP = {false, // null true, // attribute true, // element true, // type false, // attribute use true, // attribute group true, // group false, // model group false, // particle false, // wildcard false, // idc true, // notation false, // annotation false, // facet false, // multi value facet true, // complex type true // simple type }; // store a certain kind of components from all namespaces private XSNamedMap[] fComponents = null; // store the documents and their locations contributing to this namespace // REVISIT: use StringList and XSObjectList for there fields. private Vector fDocuments = null; private Vector fLocations = null; public synchronized void addDocument(Object document, String location) { if (fDocuments == null) { fDocuments = new Vector(); fLocations = new Vector(); } fDocuments.addElement(document); fLocations.addElement(location); } /** * [schema namespace] * @see <a href="http://www.w3.org/TR/xmlschema-1/#nsi-schema_namespace">[schema namespace]</a> * @return The target namespace of this item. */ public String getSchemaNamespace() { return fTargetNamespace; } // annotation support synchronized DOMParser getDOMParser() { if (fDOMParser != null) return fDOMParser; // REVISIT: when schema handles XML 1.1, will need to // revisit this (and the practice of not prepending an XML decl to the annotation string IntegratedParserConfiguration config = new IntegratedParserConfiguration(fSymbolTable); // note that this should never produce errors or require // entity resolution, so just a barebones configuration with // a couple of feature set will do fine config.setFeature(Constants.SAX_FEATURE_PREFIX + Constants.NAMESPACES_FEATURE, true); config.setFeature(Constants.SAX_FEATURE_PREFIX + Constants.VALIDATION_FEATURE, false); fDOMParser = new DOMParser(config); return fDOMParser; } synchronized SAXParser getSAXParser() { if (fSAXParser != null) return fSAXParser; // REVISIT: when schema handles XML 1.1, will need to // revisit this (and the practice of not prepending an XML decl to the annotation string IntegratedParserConfiguration config = new IntegratedParserConfiguration(fSymbolTable); // note that this should never produce errors or require // entity resolution, so just a barebones configuration with // a couple of feature set will do fine config.setFeature(Constants.SAX_FEATURE_PREFIX + Constants.NAMESPACES_FEATURE, true); config.setFeature(Constants.SAX_FEATURE_PREFIX + Constants.VALIDATION_FEATURE, false); fSAXParser = new SAXParser(config); return fSAXParser; } /** * [schema components]: a list of top-level components, i.e. element * declarations, attribute declarations, etc. * @param objectType The type of the declaration, i.e. * <code>ELEMENT_DECLARATION</code>. Note that * <code>XSTypeDefinition.SIMPLE_TYPE</code> and * <code>XSTypeDefinition.COMPLEX_TYPE</code> can also be used as the * <code>objectType</code> to retrieve only complex types or simple * types, instead of all types. * @return A list of top-level definition of the specified type in * <code>objectType</code> or an empty <code>XSNamedMap</code> if no * such definitions exist. */ public synchronized XSNamedMap getComponents(short objectType) { if (objectType <= 0 || objectType > MAX_COMP_IDX || !GLOBAL_COMP[objectType]) { return XSNamedMapImpl.EMPTY_MAP; } if (fComponents == null) fComponents = new XSNamedMap[MAX_COMP_IDX+1]; // get the hashtable for this type of components if (fComponents[objectType] == null) { SymbolHash table = null; switch (objectType) { case XSConstants.TYPE_DEFINITION: case XSTypeDefinition.COMPLEX_TYPE: case XSTypeDefinition.SIMPLE_TYPE: table = fGlobalTypeDecls; break; case XSConstants.ATTRIBUTE_DECLARATION: table = fGlobalAttrDecls; break; case XSConstants.ELEMENT_DECLARATION: table = fGlobalElemDecls; break; case XSConstants.ATTRIBUTE_GROUP: table = fGlobalAttrGrpDecls; break; case XSConstants.MODEL_GROUP_DEFINITION: table = fGlobalGroupDecls; break; case XSConstants.NOTATION_DECLARATION: table = fGlobalNotationDecls; break; } // for complex/simple types, create a special implementation, // which take specific types out of the hash table if (objectType == XSTypeDefinition.COMPLEX_TYPE || objectType == XSTypeDefinition.SIMPLE_TYPE) { fComponents[objectType] = new XSNamedMap4Types(fTargetNamespace, table, objectType); } else { fComponents[objectType] = new XSNamedMapImpl(fTargetNamespace, table); } } return fComponents[objectType]; } /** * Convenience method. Returns a top-level simple or complex type * definition. * @param name The name of the definition. * @return An <code>XSTypeDefinition</code> or null if such definition * does not exist. */ public XSTypeDefinition getTypeDefinition(String name) { return getGlobalTypeDecl(name); } /** * Convenience method. Returns a top-level attribute declaration. * @param name The name of the declaration. * @return A top-level attribute declaration or null if such declaration * does not exist. */ public XSAttributeDeclaration getAttributeDeclaration(String name) { return getGlobalAttributeDecl(name); } /** * Convenience method. Returns a top-level element declaration. * @param name The name of the declaration. * @return A top-level element declaration or null if such declaration * does not exist. */ public XSElementDeclaration getElementDeclaration(String name) { return getGlobalElementDecl(name); } /** * Convenience method. Returns a top-level attribute group definition. * @param name The name of the definition. * @return A top-level attribute group definition or null if such * definition does not exist. */ public XSAttributeGroupDefinition getAttributeGroup(String name) { return getGlobalAttributeGroupDecl(name); } /** * Convenience method. Returns a top-level model group definition. * * @param name The name of the definition. * @return A top-level model group definition definition or null if such * definition does not exist. */ public XSModelGroupDefinition getModelGroupDefinition(String name) { return getGlobalGroupDecl(name); } /** * Convenience method. Returns a top-level notation declaration. * * @param name The name of the declaration. * @return A top-level notation declaration or null if such declaration * does not exist. */ public XSNotationDeclaration getNotationDeclaration(String name) { return getGlobalNotationDecl(name); } /** * [document location] * @see <a href="http://www.w3.org/TR/xmlschema-1/#sd-document_location">[document location]</a> * @return a list of document information item */ public StringList getDocumentLocations() { return new StringListImpl(fLocations); } /** * Return an <code>XSModel</code> that represents components in this schema * grammar. * * @return an <code>XSModel</code> representing this schema grammar */ public XSModel toXSModel() { return new XSModelImpl(new SchemaGrammar[]{this}); } public XSModel toXSModel(XSGrammar[] grammars) { if (grammars == null || grammars.length == 0) return toXSModel(); int len = grammars.length; boolean hasSelf = false; for (int i = 0; i < len; i++) { if (grammars[i] == this) { hasSelf = true; break; } } SchemaGrammar[] gs = new SchemaGrammar[hasSelf ? len : len+1]; for (int i = 0; i < len; i++) gs[i] = (SchemaGrammar)grammars[i]; if (!hasSelf) gs[len] = this; return new XSModelImpl(gs); } /** * @see org.apache.xerces.xs.XSNamespaceItem#getAnnotations() */ public XSObjectList getAnnotations() { return new XSObjectListImpl(fAnnotations, fNumAnnotations); } public void addAnnotation(XSAnnotationImpl annotation) { if(annotation == null) return; if(fAnnotations == null) { fAnnotations = new XSAnnotationImpl[2]; } else if(fNumAnnotations == fAnnotations.length) { XSAnnotationImpl[] newArray = new XSAnnotationImpl[fNumAnnotations << 1]; System.arraycopy(fAnnotations, 0, newArray, 0, fNumAnnotations); fAnnotations = newArray; } fAnnotations[fNumAnnotations++] = annotation; } } // class SchemaGrammar
BIORIMP/biorimp
BIO-RIMP/test_data/code/xerces/src/org/apache/xerces/impl/xs/SchemaGrammar.java
Java
gpl-2.0
49,139
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <!-- NewPage --> <html lang="en"> <head> <!-- Generated by javadoc (version 1.7.0_65) on Thu Oct 23 20:37:10 CEST 2014 --> <meta http-equiv="Content-Type" content="text/html" charset="UTF-8"> <title>Uses of Package org.richfaces.annotation (RichFaces Distribution Assembler 4.5.0.Final API)</title> <meta name="date" content="2014-10-23"> <link rel="stylesheet" type="text/css" href="../../../stylesheet.css" title="Style"> </head> <body> <script type="text/javascript"><!-- if (location.href.indexOf('is-external=true') == -1) { parent.document.title="Uses of Package org.richfaces.annotation (RichFaces Distribution Assembler 4.5.0.Final API)"; } //--> </script> <noscript> <div>JavaScript is disabled on your browser.</div> </noscript> <!-- ========= START OF TOP NAVBAR ======= --> <div class="topNav"><a name="navbar_top"> <!-- --> </a><a href="#skip-navbar_top" title="Skip navigation links"></a><a name="navbar_top_firstrow"> <!-- --> </a> <ul class="navList" title="Navigation"> <li><a href="../../../overview-summary.html">Overview</a></li> <li><a href="package-summary.html">Package</a></li> <li>Class</li> <li class="navBarCell1Rev">Use</li> <li><a href="package-tree.html">Tree</a></li> <li><a href="../../../deprecated-list.html">Deprecated</a></li> <li><a href="../../../index-all.html">Index</a></li> <li><a href="../../../help-doc.html">Help</a></li> </ul> <div class="aboutLanguage"><em><b>RichFaces Distribution Assembler 4.5.0.Final</b></em></div> </div> <div class="subNav"> <ul class="navList"> <li>Prev</li> <li>Next</li> </ul> <ul class="navList"> <li><a href="../../../index.html?org/richfaces/annotation/package-use.html" target="_top">Frames</a></li> <li><a href="package-use.html" target="_top">No Frames</a></li> </ul> <ul class="navList" id="allclasses_navbar_top"> <li><a href="../../../allclasses-noframe.html">All Classes</a></li> </ul> <div> <script type="text/javascript"><!-- allClassesLink = document.getElementById("allclasses_navbar_top"); if(window==top) { allClassesLink.style.display = "block"; } else { allClassesLink.style.display = "none"; } //--> </script> </div> <a name="skip-navbar_top"> <!-- --> </a></div> <!-- ========= END OF TOP NAVBAR ========= --> <div class="header"> <h1 title="Uses of Package org.richfaces.annotation" class="title">Uses of Package<br>org.richfaces.annotation</h1> </div> <div class="contentContainer">No usage of org.richfaces.annotation</div> <!-- ======= START OF BOTTOM NAVBAR ====== --> <div class="bottomNav"><a name="navbar_bottom"> <!-- --> </a><a href="#skip-navbar_bottom" title="Skip navigation links"></a><a name="navbar_bottom_firstrow"> <!-- --> </a> <ul class="navList" title="Navigation"> <li><a href="../../../overview-summary.html">Overview</a></li> <li><a href="package-summary.html">Package</a></li> <li>Class</li> <li class="navBarCell1Rev">Use</li> <li><a href="package-tree.html">Tree</a></li> <li><a href="../../../deprecated-list.html">Deprecated</a></li> <li><a href="../../../index-all.html">Index</a></li> <li><a href="../../../help-doc.html">Help</a></li> </ul> <div class="aboutLanguage"><em><b>RichFaces Distribution Assembler 4.5.0.Final</b></em></div> </div> <div class="subNav"> <ul class="navList"> <li>Prev</li> <li>Next</li> </ul> <ul class="navList"> <li><a href="../../../index.html?org/richfaces/annotation/package-use.html" target="_top">Frames</a></li> <li><a href="package-use.html" target="_top">No Frames</a></li> </ul> <ul class="navList" id="allclasses_navbar_bottom"> <li><a href="../../../allclasses-noframe.html">All Classes</a></li> </ul> <div> <script type="text/javascript"><!-- allClassesLink = document.getElementById("allclasses_navbar_bottom"); if(window==top) { allClassesLink.style.display = "block"; } else { allClassesLink.style.display = "none"; } //--> </script> </div> <a name="skip-navbar_bottom"> <!-- --> </a></div> <!-- ======== END OF BOTTOM NAVBAR ======= --> <p class="legalCopy"><small>Copyright &#169; 2014 <a href="http://www.jboss.org">JBoss by Red Hat</a>. All Rights Reserved.</small></p> </body> </html>
Jacksson/mywmsnb
lib/richfaces/doc/javadoc/org/richfaces/annotation/package-use.html
HTML
gpl-2.0
4,228
/* vegas_net_thread.c * * Routine to read packets from network and put them * into shared memory blocks. */ #define _GNU_SOURCE 1 #include <stdio.h> #include <stdlib.h> #include <math.h> #include <unistd.h> #include <string.h> #include <pthread.h> #include <signal.h> #include <sched.h> #include <sys/time.h> #include <sys/resource.h> #include <sys/types.h> #include "fitshead.h" #include "vegas_params.h" #include "vegas_error.h" #include "vegas_status.h" #include "vegas_databuf.h" #include "vegas_udp.h" #include "vegas_time.h" #define STATUS_KEY "NETSTAT" /* Define before vegas_threads.h */ #include "vegas_threads.h" #include "vegas_defines.h" /* This file will only compile if the FITS_TYPE is set to SDFITS */ #if FITS_TYPE != SDFITS #error "FITS_TYPE not set to SDFITS." #endif #include "sdfits.h" #include "spead_heap.h" #define DEBUG_NET #undef TEST_DROP_PKTS #ifdef TEST_DROP_PKTS int ___test_have_tossed = 0; int ___test_toss_packets = 0; void test_loose_packets(char *howmany) { ___test_have_tossed = 0; ___test_toss_packets = (int)strtol(howmany, 0, 0); } #endif /// Read a status buffer all of the key observation paramters extern void vegas_read_obs_params(char *buf, struct vegas_params *g, struct sdfits *p); /** Structs/functions to more easily deal with multiple * active blocks being filled */ struct datablock_stats { struct vegas_databuf *db; // Pointer to overall shared mem databuf int block_idx; // Block index number in databuf unsigned int heap_idx; // Index of first heap in block size_t heap_size; // Size of each heap size_t spead_hdr_size; // Size of each SPEAD header int heaps_per_block; // Total number of heaps to go in the block int nheaps; // Number of heaps filled so far int pkts_dropped; // Number of dropped packets so far unsigned int last_heap; // Last heap counter written to block }; /** Touch all memory pages in a databuffer (non-destructive) */ void touch_all_pages(struct vegas_databuf *db) { size_t pagesize = 4096; volatile char *ptr; int i, page; for (i=0; i<db->n_block; ++i) { ptr = vegas_databuf_data(db, i); for (page=0; page<db->block_size/pagesize; ++page) { volatile char dummy; dummy = *ptr; *ptr = dummy; ptr += pagesize; } } } /** Reset all packet loss counters */ void reset_stats(struct datablock_stats *d) { d->nheaps=0; d->pkts_dropped=0; d->last_heap=0; } /** Reset block params */ void reset_block(struct datablock_stats *d) { d->block_idx = -1; d->heap_idx = 0; reset_stats(d); } /** Initialize block struct */ void init_block(struct datablock_stats *d, struct vegas_databuf *db, size_t heap_size, size_t spead_hdr_size, int heaps_per_block) { d->db = db; d->heap_size = heap_size; d->spead_hdr_size = spead_hdr_size; d->heaps_per_block = heaps_per_block; reset_block(d); } /** Update block header info, set filled status */ void finalize_block(struct datablock_stats *d) { char *header = vegas_databuf_header(d->db, d->block_idx); hputi4(header, "HEAPIDX", d->heap_idx); hputi4(header, "HEAPSIZE", d->heap_size); hputi4(header, "NHEAPS", d->nheaps); hputi4(header, "NDROP", d->pkts_dropped); struct databuf_index* index = (struct databuf_index*) vegas_databuf_index(d->db, d->block_idx); index->num_heaps = d->nheaps; index->heap_size = d->heap_size; vegas_databuf_set_filled(d->db, d->block_idx); } /** Push all blocks down a level, losing the first one */ void block_stack_push(struct datablock_stats *d, int nblock) { int i; for (i=1; i<nblock; i++) memcpy(&d[i-1], &d[i], sizeof(struct datablock_stats)); } /** Go to next block in set */ void increment_block(struct datablock_stats *d, unsigned int next_heap_cntr) { d->block_idx = (d->block_idx + 1) % d->db->n_block; d->heap_idx = next_heap_cntr; reset_stats(d); } /** Check whether a certain heap counter belongs in the data block */ int block_heap_check(struct datablock_stats *d, unsigned int heap_cntr) { if (heap_cntr < d->heap_idx) return(-1); else if (heap_cntr >= d->heap_idx + d->heaps_per_block) return(1); else return(0); } /** * Write a SPEAD packet into the datablock. Also zeroes out any dropped packets. */ static unsigned int prev_heap_cntr; static unsigned int prev_heap_offset; static char pkts_dropped_in_heap; void write_spead_packet_to_block(struct datablock_stats *d, struct vegas_udp_packet *p, unsigned int heap_cntr, unsigned int heap_offset, unsigned int pkts_per_heap, char bw_mode[]) { int block_heap_idx; char *spead_header_addr, *spead_payload_addr; double mjd; /*Determine packet's address within block */ block_heap_idx = heap_cntr - d->heap_idx; spead_header_addr = vegas_databuf_data(d->db, d->block_idx) + block_heap_idx * d->spead_hdr_size; spead_payload_addr = vegas_databuf_data(d->db, d->block_idx) + MAX_HEAPS_PER_BLK * d->spead_hdr_size + block_heap_idx * (d->heap_size - d->spead_hdr_size) + heap_offset; /* Copy packet to address, while reversing the byte ordering */ vegas_spead_packet_copy(p, spead_header_addr, spead_payload_addr, bw_mode); /*Update block statistics */ d->nheaps = block_heap_idx + 1; d->last_heap = heap_cntr; //Determine if we dropped any packets while in same heap if( vegas_spead_packet_seq_num(heap_cntr, heap_offset, pkts_per_heap) - vegas_spead_packet_seq_num(prev_heap_cntr, prev_heap_offset, pkts_per_heap) > 1 && prev_heap_cntr == heap_cntr) { pkts_dropped_in_heap = 1; } struct databuf_index* index = (struct databuf_index*) vegas_databuf_index(d->db, d->block_idx); //If start of new heap, write it to index if(heap_cntr != prev_heap_cntr) { index->cpu_gpu_buf[block_heap_idx].heap_cntr = heap_cntr; index->cpu_gpu_buf[block_heap_idx].heap_valid = 0; if(heap_offset == 0) pkts_dropped_in_heap = 0; else pkts_dropped_in_heap = 1; } //If this is the last packet of the heap, write valid bit and MJD to index // JJB what is 6*8 here? if(heap_offset + PAYLOAD_SIZE + 6*8 >= d->heap_size) { index->cpu_gpu_buf[block_heap_idx].heap_valid = 1 - pkts_dropped_in_heap; get_current_mjd_double(&mjd); index->cpu_gpu_buf[block_heap_idx].heap_rcvd_mjd = mjd; } prev_heap_cntr = heap_cntr; prev_heap_offset = heap_offset; } /** This thread is passed a single arg, pointer * to the vegas_udp_params struct. This thread should * be cancelled and restarted if any hardware params * change, as this potentially affects packet size, etc. */ void *vegas_net_thread(void *_args) { /* Get arguments */ struct vegas_thread_args *args = (struct vegas_thread_args *)_args; int rv; /* Set cpu affinity */ rv = sched_setaffinity(0, sizeof(cpu_set_t), &args->cpuset); if (rv<0) { vegas_error("vegas_net_thread", "Error setting cpu affinity."); perror("sched_setaffinity"); } /* Set priority */ rv=0; if (args->priority != 0) { struct sched_param priority_param; priority_param.sched_priority = args->priority; rv = pthread_setschedparam(pthread_self(), SCHED_FIFO, &priority_param); } if (rv<0) { vegas_error("vegas_net_thread", "Error setting priority level."); perror("set_priority"); } /* Attach to status shared mem area */ struct vegas_status st; rv = vegas_status_attach(&st); if (rv!=VEGAS_OK) { vegas_error("vegas_net_thread", "Error attaching to status shared memory."); pthread_exit(NULL); } pthread_cleanup_push((void *)vegas_status_detach, &st); pthread_cleanup_push((void *)set_exit_status, &st); /* Init status, read info */ vegas_status_lock_safe(&st); hputs(st.buf, STATUS_KEY, "init"); vegas_status_unlock_safe(&st); /* Read in general parameters */ struct vegas_params gp; struct sdfits pf; char status_buf[VEGAS_STATUS_SIZE]; vegas_status_lock_safe(&st); memcpy(status_buf, st.buf, VEGAS_STATUS_SIZE); vegas_status_unlock_safe(&st); vegas_read_obs_params(status_buf, &gp, &pf); pthread_cleanup_push((void *)vegas_free_sdfits, &pf); /* Read network params */ struct vegas_udp_params up; vegas_read_net_params(status_buf, &up); up.observation_started = 0; /* Attach to databuf shared mem */ struct vegas_databuf *db; db = vegas_databuf_attach(args->output_buffer); if (db==NULL) { vegas_error("vegas_net_thread", "Error attaching to databuf shared memory."); pthread_exit(NULL); } pthread_cleanup_push((void *)vegas_databuf_detach, db); // Only the net thread seems to need this. This // call causes the data portion of net buffer to be // paged in by 'touching' each 4k memory page. This fixes dropped packets // at the beginning of scan issue. touch_all_pages(db); /* Time parameters */ double meas_stt_mjd=0.0; double meas_stt_offs=0.0; /* See which packet format to use */ int nchan=0, npol=0; nchan = pf.hdr.nchan; npol = pf.hdr.npol; /* Figure out size of data in each packet, number of packets * per block, etc. Changing packet size during an obs is not * recommended. */ int block_size; struct vegas_udp_packet p; size_t heap_size = 0, spead_hdr_size = 0; unsigned int heaps_per_block, packets_per_heap = 0; char bw_mode[16]; if (hgets(status_buf, "BW_MODE", 16, bw_mode)) { if(strncasecmp(bw_mode, "high", 4) == 0) { heap_size = sizeof(struct freq_spead_heap) + nchan*4*sizeof(int); spead_hdr_size = sizeof(struct freq_spead_heap); packets_per_heap = nchan*4*sizeof(int) / PAYLOAD_SIZE; up.is_hbw = 1; } else if(strncasecmp(bw_mode, "low", 3) == 0) { heap_size = sizeof(struct time_spead_heap) + PAYLOAD_SIZE; spead_hdr_size = sizeof(struct time_spead_heap); packets_per_heap = 1; up.is_hbw = 0; } else { // Since the mode is unknown, the calculations below may fail. // give up and exit. vegas_error("vegas_net_thread", "Unsupported bandwidth mode"); pthread_exit(NULL); } } else vegas_error("vegas_net_thread", "BW_MODE not set"); if (hgeti4(status_buf, "BLOCSIZE", &block_size)==0) { block_size = db->block_size; hputi4(status_buf, "BLOCSIZE", block_size); } else { if (block_size > db->block_size) { vegas_error("vegas_net_thread", "BLOCSIZE > databuf block_size"); block_size = db->block_size; hputi4(status_buf, "BLOCSIZE", block_size); } } heaps_per_block = (block_size - MAX_HEAPS_PER_BLK*spead_hdr_size) / (heap_size - spead_hdr_size); /* make general --> */ int nsubband = pf.hdr.nsubband; int iDataSize = heaps_per_block * (heap_size - spead_hdr_size); int iWholeSpectra = iDataSize / (nsubband * nchan * 4); /* 4 is the number of bytes in a sample */ heaps_per_block = (iWholeSpectra * (nsubband * nchan * 4)) / (heap_size - spead_hdr_size); if (heaps_per_block > MAX_HEAPS_PER_BLK) /* sanity check, shouldn't happen */ { vegas_error("vegas_net_thread", "heaps_per_block > MAX_HEAPS_PER_BLK"); pthread_exit(NULL); } /* <-- make general */ /* List of databuf blocks currently in use */ unsigned i; const int nblock = 2; struct datablock_stats blocks[nblock]; for (i=0; i<nblock; i++) init_block(&blocks[i], db, heap_size, spead_hdr_size, heaps_per_block); /* Convenience names for first/last blocks in set */ struct datablock_stats *fblock, *lblock; fblock = &blocks[0]; lblock = &blocks[nblock-1]; /* Misc counters, etc */ char *curdata=NULL, *curheader=NULL, *curindex=NULL; unsigned int heap_cntr=0, last_heap_cntr=2048, nextblock_heap_cntr=0; unsigned int heap_offset; unsigned int seq_num=0, last_seq_num=1050; int heap_cntr_diff, seq_num_diff; unsigned int obs_started = 0; unsigned long long npacket_total = 0, npacket_this_block=0, ndropped_total = 0; double drop_frac_avg=0.0; const double drop_lpf = 0.25; prev_heap_cntr = 0; prev_heap_offset = 0; char msg[256]; /* Give all the threads a chance to start before opening network socket */ sleep(1); /* Set up UDP socket */ rv = vegas_udp_init(&up); if (rv!=VEGAS_OK) { vegas_error("vegas_net_thread", "Error opening UDP socket."); pthread_exit(NULL); } pthread_cleanup_push((void *)vegas_udp_close, &up); /* Main loop */ unsigned force_new_block=0, waiting=-1; signal(SIGINT,cc); while (run) { /* Wait for data */ rv = vegas_udp_wait(&up); if (rv!=VEGAS_OK) { if (rv==VEGAS_TIMEOUT) { /* Set "waiting" flag */ if (waiting!=1) { vegas_status_lock_safe(&st); hputs(st.buf, STATUS_KEY, "waiting"); vegas_status_unlock_safe(&st); waiting=1; } continue; } else { vegas_error("vegas_net_thread", "vegas_udp_wait returned error"); perror("vegas_udp_wait"); pthread_exit(NULL); } } /* Read packet */ rv = vegas_udp_recv(&up, &p, bw_mode); #ifdef TEST_DROP_PKTS if (___test_toss_packets) { ___test_toss_packets--; ___test_have_tossed++; if (!___test_toss_packets) printf("Tossed %d packets\n", ___test_have_tossed); continue; } #endif if (rv!=VEGAS_OK) { if (rv==VEGAS_ERR_PACKET) { #ifdef DEBUG_NET vegas_warn("vegas_net_thread", "Incorrect pkt size"); #endif continue; } else { vegas_error("vegas_net_thread", "vegas_udp_recv returned error"); perror("vegas_udp_recv"); pthread_exit(NULL); } } /* Update status if needed */ if (waiting!=0) { vegas_status_lock_safe(&st); hputs(st.buf, STATUS_KEY, "receiving"); vegas_status_unlock_safe(&st); waiting=0; } /* Check seq num diff */ heap_cntr = vegas_spead_packet_heap_cntr(&p); heap_offset = vegas_spead_packet_heap_offset(&p); seq_num = vegas_spead_packet_seq_num(heap_cntr, heap_offset, packets_per_heap); heap_cntr_diff = heap_cntr - last_heap_cntr; seq_num_diff = (int)(seq_num - last_seq_num); last_seq_num = seq_num; last_heap_cntr = heap_cntr; if (seq_num_diff<=0) { if (seq_num_diff<-1024) { force_new_block=1; obs_started = 1; up.observation_started = 1; #ifdef DEBUG_NET printf("Debug: observation started\n"); #endif } else if (seq_num_diff==0) { sprintf(msg, "Received duplicate packet (seq_num=%d)", seq_num); vegas_warn("vegas_net_thread", msg); } else { #ifdef DEBUG_NET sprintf(msg, "out of order packet. Diff = %d", seq_num_diff); vegas_warn("vegas_net_thread", msg); #endif continue; /* No going backwards */ } } else { force_new_block=0; npacket_total += seq_num_diff; ndropped_total += seq_num_diff - 1; npacket_this_block += seq_num_diff; fblock->pkts_dropped += seq_num_diff - 1; #ifdef DEBUG_NET if(seq_num_diff > 1) { sprintf(msg, "Missing packet. seq_num_diff = %d", seq_num_diff); vegas_warn("vegas_net_thread", msg); } #endif } /* If obs has not started, ignore this packet */ if(!obs_started) { fblock->pkts_dropped = 0; npacket_total = 0; ndropped_total = 0; npacket_this_block = 0; // insert synthetic blanking and the SCAN_NOT_STARTED bits in status field // [performed in the vegas_udp_recv() call above] and keep going. // This allows data to begin flowing through the data buffers without // being accumulated/recorded. // continue; } /* Determine if we go to next block */ if (heap_cntr>=nextblock_heap_cntr || force_new_block) { /* Update drop stats */ if (npacket_this_block > 0) drop_frac_avg = (1.0-drop_lpf)*drop_frac_avg + drop_lpf * (double)fblock->pkts_dropped / (double)npacket_this_block; vegas_status_lock_safe(&st); hputi8(st.buf, "NPKT", npacket_total); hputi8(st.buf, "NDROP", ndropped_total); hputr8(st.buf, "DROPAVG", drop_frac_avg); hputr8(st.buf, "DROPTOT", npacket_total ? (double)ndropped_total/(double)npacket_total : 0.0); hputi4(st.buf, "NETBLKOU", fblock->block_idx); vegas_status_unlock_safe(&st); /* Finalize first block, and push it off the list. * Then grab next available block. */ if (fblock->block_idx>=0) finalize_block(fblock); block_stack_push(blocks, nblock); increment_block(lblock, heap_cntr); curdata = vegas_databuf_data(db, lblock->block_idx); curheader = vegas_databuf_header(db, lblock->block_idx); curindex = vegas_databuf_index(db, lblock->block_idx); nextblock_heap_cntr = lblock->heap_idx + heaps_per_block; npacket_this_block = 0; /* If new obs started, reset total counters, get start * time. Start time is rounded to nearest integer * second, with warning if we're off that by more * than 100ms. Any current blocks on the stack * are also finalized/reset */ if (force_new_block) { /* Reset stats */ npacket_total=0; ndropped_total=0; npacket_this_block = 0; /* Get obs start time */ get_current_mjd_double(&meas_stt_mjd); printf("vegas_net_thread: got start packet at MJD %f", meas_stt_mjd); meas_stt_offs = meas_stt_mjd*24*60*60 - floor(meas_stt_mjd*24*60*60); if(meas_stt_offs > 0.1 && meas_stt_offs < 0.9) { char msg[256]; sprintf(msg, "Second fraction = %3.1f ms > +/-100 ms", meas_stt_offs*1e3); vegas_warn("vegas_net_thread", msg); } vegas_status_lock_safe(&st); hputnr8(st.buf, "M_STTMJD", 8, meas_stt_mjd); hputr8(st.buf, "M_STTOFF", meas_stt_offs); vegas_status_unlock_safe(&st); /* Warn if 1st packet number is not zero */ if (seq_num!=0) { char msg[256]; sprintf(msg, "First packet number is not 0 (seq_num=%d)", seq_num); vegas_warn("vegas_net_thread", msg); } } /* Read current status shared mem */ vegas_status_lock_safe(&st); memcpy(status_buf, st.buf, VEGAS_STATUS_SIZE); vegas_status_unlock_safe(&st); /* Wait for new block to be free, then clear it * if necessary and fill its header with new values. */ while ((rv=vegas_databuf_wait_free(db, lblock->block_idx)) != VEGAS_OK) { if (rv==VEGAS_TIMEOUT) { waiting=1; vegas_warn("vegas_net_thread", "timeout while waiting for output block\n"); vegas_status_lock_safe(&st); hputs(st.buf, STATUS_KEY, "blocked"); vegas_status_unlock_safe(&st); continue; } else { vegas_error("vegas_net_thread", "error waiting for free databuf"); run=0; pthread_exit(NULL); break; } } memcpy(curheader, status_buf, VEGAS_STATUS_SIZE); memset(curdata, 0, block_size); memset(curindex, 0, db->index_size); } /* Copy packet into any blocks where it belongs. * The "write packets" functions also update drop stats * for blocks, etc. */ int nblocks = 0; for (i=0; i<nblock; i++) { if ((blocks[i].block_idx>=0) && (block_heap_check(&blocks[i],heap_cntr)==0)) { if (nblocks > 0) { printf("vegas_net_thread: Warning! Adding packet to more than one block! heap_cntr= %d, block = %d",heap_cntr,i); } nblocks++; write_spead_packet_to_block(&blocks[i], &p, heap_cntr, heap_offset, packets_per_heap, bw_mode); } } /* Will exit if thread has been cancelled */ pthread_testcancel(); } pthread_exit(NULL); /* Have to close all push's */ pthread_cleanup_pop(0); /* Closes push(vegas_udp_close) */ pthread_cleanup_pop(0); /* Closes set_exit_status */ pthread_cleanup_pop(0); /* Closes vegas_free_psrfits */ pthread_cleanup_pop(0); /* Closes vegas_status_detach */ pthread_cleanup_pop(0); /* Closes vegas_databuf_detach */ }
nrao/FLAG-Beamformer-Devel
src/vegas_hpc/src/vegas_net_thread.c
C
gpl-2.0
22,982
// ********************************************************************** // // Copyright (c) 2003-2013 ZeroC, Inc. All rights reserved. // // This copy of Ice is licensed to you under the terms described in the // ICE_LICENSE file included in this distribution. // // ********************************************************************** using Test; using System; using System.Diagnostics; using System.Reflection; [assembly: CLSCompliant(true)] [assembly: AssemblyTitle("IceTest")] [assembly: AssemblyDescription("Ice test")] [assembly: AssemblyCompany("ZeroC, Inc.")] public class Collocated { internal class App : Ice.Application { public override int run(string[] args) { communicator().getProperties().setProperty("TestAdapter.Endpoints", "default -p 12010"); communicator().getProperties().setProperty("Ice.Warn.Dispatch", "0"); Ice.ObjectAdapter adapter = communicator().createObjectAdapter("TestAdapter"); adapter.addServantLocator(new ServantLocatorI("category"), "category"); adapter.addServantLocator(new ServantLocatorI(""), ""); adapter.add(new TestI(), communicator().stringToIdentity("asm")); adapter.add(new TestActivationI(), communicator().stringToIdentity("test/activation")); AllTests.allTests(communicator(), true); return 0; } } public static int Main(string[] args) { App app = new App(); return app.main(args); } }
sbesson/zeroc-ice
cs/test/Ice/servantLocator/Collocated.cs
C#
gpl-2.0
1,521
// 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. // Based upon // CDialogMinTrayBtn template class // MFC CDialog with minimize to systemtray button (0.04a) // Supports WinXP styles (thanks to David Yuheng Zhao for CVisualStylesXP - yuheng_zhao@yahoo.com) // // ------------------------------------------------------------ // DialogMinTrayBtn.hpp // zegzav - 2002,2003 - eMule project (http://www.emule-project.net) // ------------------------------------------------------------ // // Modified by Tim Kosse (mailto:tim.kosse@gmx.de) for use within FileZilla #include "StdAfx.h"; #include "MinTrayBtn.h" #include "VisualStylesXP.h" IMPLEMENT_DYNCREATE(CMinTrayBtn, CHookWnd); // ------------------------------ // constants // ------------------------------ #define CAPTION_BUTTONSPACE (2) #define CAPTION_MINHEIGHT (8) #define TIMERMINTRAYBTN_ID 0x76617a67 #define TIMERMINTRAYBTN_PERIOD 200 // ms #define WP_TRAYBUTTON WP_MINBUTTON BEGIN_TM_PART_STATES(TRAYBUTTON) TM_STATE(1, TRAYBS, NORMAL) TM_STATE(2, TRAYBS, HOT) TM_STATE(3, TRAYBS, PUSHED) TM_STATE(4, TRAYBS, DISABLED) // Inactive TM_STATE(5, TRAYBS, INORMAL) TM_STATE(6, TRAYBS, IHOT) TM_STATE(7, TRAYBS, IPUSHED) TM_STATE(8, TRAYBS, IDISABLED) END_TM_PART_STATES() #define BMP_TRAYBTN_WIDTH (21) #define BMP_TRAYBTN_HEIGHT (21) #define BMP_TRAYBTN_BLUE _T("IDB_LUNA_BLUE") #define BMP_TRAYBTN_METALLIC _T("IDB_LUNA_METALLIC") #define BMP_TRAYBTN_HOMESTEAD _T("IDB_LUNA_HOMESTEAD") #define BMP_TRAYBTN_TRANSCOLOR (RGB(255,0,255)) LPCTSTR CMinTrayBtn::m_pszMinTrayBtnBmpName[] = { BMP_TRAYBTN_BLUE, BMP_TRAYBTN_METALLIC, BMP_TRAYBTN_HOMESTEAD }; #define VISUALSTYLESXP_DEFAULTFILE L"LUNA.MSSTYLES" #define VISUALSTYLESXP_BLUE 0 #define VISUALSTYLESXP_METALLIC 1 #define VISUALSTYLESXP_HOMESTEAD 2 #define VISUALSTYLESXP_NAMEBLUE L"NORMALCOLOR" #define VISUALSTYLESXP_NAMEMETALLIC L"METALLIC" #define VISUALSTYLESXP_NAMEHOMESTEAD L"HOMESTEAD" // _WIN32_WINNT >= 0x0501 (XP only) #define _WM_THEMECHANGED 0x031A #define _ON_WM_THEMECHANGED() \ { _WM_THEMECHANGED, 0, 0, 0, AfxSig_l, \ (AFX_PMSG)(AFX_PMSGW) \ (static_cast< LRESULT (AFX_MSG_CALL CWnd::*)(void) > (_OnThemeChanged)) \ }, // _WIN32_WINDOWS >= 0x0410 (95 not supported) BOOL (WINAPI *CMinTrayBtn::_TransparentBlt)(HDC, int, int, int, int, HDC, int, int, int, int, UINT)= NULL; // ------------------------------ // contructor/init // ------------------------------ CMinTrayBtn::CMinTrayBtn(CWnd* pParentWnd) : CHookWnd(FALSE), m_MinTrayBtnPos(0,0), m_MinTrayBtnSize(0,0), m_bMinTrayBtnEnabled(TRUE), m_bMinTrayBtnVisible(TRUE), m_bMinTrayBtnUp(TRUE), m_bMinTrayBtnCapture(FALSE), m_bMinTrayBtnActive(FALSE), m_bMinTrayBtnHitTest(FALSE) { ASSERT(pParentWnd); m_pOwner = pParentWnd; m_hDLL = NULL; MinTrayBtnInit(); } CMinTrayBtn::~CMinTrayBtn() { if (m_hDLL) FreeLibrary(m_hDLL); } void CMinTrayBtn::MinTrayBtnInit() { m_nMinTrayBtnTimerId = 0; MinTrayBtnInitBitmap(); if (!_TransparentBlt) { m_hDLL = LoadLibrary(_T("MSIMG32.DLL")); if (m_hDLL) { (FARPROC &)_TransparentBlt = GetProcAddress(m_hDLL, "TransparentBlt"); if (!_TransparentBlt) { FreeLibrary(m_hDLL); m_hDLL = NULL; } } } } // ------------------------------ // messages // ------------------------------ void CMinTrayBtn::OnNcPaint() { MinTrayBtnUpdatePosAndSize(); MinTrayBtnDraw(); } BOOL CMinTrayBtn::OnNcActivate(BOOL bActive) { MinTrayBtnUpdatePosAndSize(); m_bMinTrayBtnActive = bActive; MinTrayBtnDraw(); return TRUE; } UINT CMinTrayBtn::OnNcHitTest(CPoint point) { BOOL bPreviousHitTest= m_bMinTrayBtnHitTest; m_bMinTrayBtnHitTest= MinTrayBtnHitTest(point); if ((!IsWindowsClassicStyle()) && (m_bMinTrayBtnHitTest != bPreviousHitTest)) MinTrayBtnDraw(); // Windows XP Style (hot button) if (m_bMinTrayBtnHitTest) return HTMINTRAYBUTTON; return HTERROR; } BOOL CMinTrayBtn::OnNcLButtonDown(UINT nHitTest, CPoint point) { if ((m_pOwner->GetStyle() & WS_DISABLED) || (!MinTrayBtnIsEnabled()) || (!MinTrayBtnIsVisible()) || (!MinTrayBtnHitTest(point))) { return FALSE; } m_pOwner->SetCapture(); m_bMinTrayBtnCapture = TRUE; MinTrayBtnSetDown(); return TRUE; } BOOL CMinTrayBtn::OnMouseMove(UINT nFlags, CPoint point) { if ((m_pOwner->GetStyle() & WS_DISABLED) || (!m_bMinTrayBtnCapture)) return FALSE; m_pOwner->ClientToScreen(&point); m_bMinTrayBtnHitTest= MinTrayBtnHitTest(point); if (m_bMinTrayBtnHitTest) { if (m_bMinTrayBtnUp) MinTrayBtnSetDown(); } else { if (!m_bMinTrayBtnUp) MinTrayBtnSetUp(); } return TRUE; } BOOL CMinTrayBtn::OnLButtonUp(UINT nFlags, CPoint point) { if ((m_pOwner->GetStyle() & WS_DISABLED) || (!m_bMinTrayBtnCapture)) return FALSE; ReleaseCapture(); m_bMinTrayBtnCapture = FALSE; MinTrayBtnSetUp(); m_pOwner->ClientToScreen(&point); if (MinTrayBtnHitTest(point)) m_pOwner->SendMessage(WM_SYSCOMMAND, SC_MINIMIZETRAY, MAKELONG(point.x, point.y)); return TRUE; } void CMinTrayBtn::OnThemeChanged() { MinTrayBtnInitBitmap(); } // ------------------------------ // methods // ------------------------------ void CMinTrayBtn::MinTrayBtnUpdatePosAndSize() { DWORD dwStyle = m_pOwner->GetStyle(); DWORD dwExStyle = m_pOwner->GetExStyle(); INT caption= ((dwExStyle & WS_EX_TOOLWINDOW) == 0) ? GetSystemMetrics(SM_CYCAPTION) - 1 : GetSystemMetrics(SM_CYSMCAPTION) - 1; if (caption < CAPTION_MINHEIGHT) caption= CAPTION_MINHEIGHT; CSize borderfixed(-GetSystemMetrics(SM_CXFIXEDFRAME), GetSystemMetrics(SM_CYFIXEDFRAME)); CSize bordersize(-GetSystemMetrics(SM_CXSIZEFRAME), GetSystemMetrics(SM_CYSIZEFRAME)); CRect window; m_pOwner->GetWindowRect(&window); CSize button; button.cy= caption - (CAPTION_BUTTONSPACE * 2); button.cx= button.cy; if (IsWindowsClassicStyle()) button.cx+= 2; m_MinTrayBtnSize = button; m_MinTrayBtnPos.x = window.Width() - ((CAPTION_BUTTONSPACE + button.cx) * 2); m_MinTrayBtnPos.y = CAPTION_BUTTONSPACE; if ((dwStyle & WS_THICKFRAME) != 0) { // resizable window m_MinTrayBtnPos+= bordersize; } else { // fixed window m_MinTrayBtnPos+= borderfixed; } if ( ((dwExStyle & WS_EX_TOOLWINDOW) == 0) && (((dwStyle & WS_MINIMIZEBOX) != 0) || ((dwStyle & WS_MAXIMIZEBOX) != 0)) ) { if (IsWindowsClassicStyle()) m_MinTrayBtnPos.x-= (button.cx * 2) + CAPTION_BUTTONSPACE; else m_MinTrayBtnPos.x-= (button.cx + CAPTION_BUTTONSPACE) * 2; } } void CMinTrayBtn::MinTrayBtnShow() { if (MinTrayBtnIsVisible()) return; m_bMinTrayBtnVisible = TRUE; if (m_pOwner->IsWindowVisible()) { m_pOwner->RedrawWindow(NULL, NULL, RDW_FRAME | RDW_INVALIDATE | RDW_UPDATENOW); } } void CMinTrayBtn::MinTrayBtnHide() { if (!MinTrayBtnIsVisible()) return; m_bMinTrayBtnVisible= FALSE; if (m_pOwner->IsWindowVisible()) { m_pOwner->RedrawWindow(NULL, NULL, RDW_FRAME | RDW_INVALIDATE | RDW_UPDATENOW); } } void CMinTrayBtn::MinTrayBtnEnable() { if (MinTrayBtnIsEnabled()) return; m_bMinTrayBtnEnabled= TRUE; MinTrayBtnSetUp(); } void CMinTrayBtn::MinTrayBtnDisable() { if (!MinTrayBtnIsEnabled()) return; m_bMinTrayBtnEnabled= FALSE; if (m_bMinTrayBtnCapture) { ReleaseCapture(); m_bMinTrayBtnCapture= FALSE; } MinTrayBtnSetUp(); } void CMinTrayBtn::MinTrayBtnDraw() { if (!MinTrayBtnIsVisible()) return; CDC *pDC = m_pOwner->GetWindowDC(); if (!pDC) return; // panic! if (IsWindowsClassicStyle()) { CBrush black(GetSysColor(COLOR_BTNTEXT)); CBrush gray(GetSysColor(COLOR_GRAYTEXT)); CBrush gray2(GetSysColor(COLOR_BTNHILIGHT)); // button if (m_bMinTrayBtnUp) pDC->DrawFrameControl(MinTrayBtnGetRect(), DFC_BUTTON, DFCS_BUTTONPUSH); else pDC->DrawFrameControl(MinTrayBtnGetRect(), DFC_BUTTON, DFCS_BUTTONPUSH | DFCS_PUSHED); // dot CRect btn= MinTrayBtnGetRect(); btn.DeflateRect(2,2); UINT caption= MinTrayBtnGetSize().cy + (CAPTION_BUTTONSPACE * 2); UINT pixratio= (caption >= 14) ? ((caption >= 20) ? 2 + ((caption - 20) / 8) : 2) : 1; UINT pixratio2= (caption >= 12) ? 1 + (caption - 12) / 8: 0; UINT dotwidth= (1 + pixratio * 3) >> 1; UINT dotheight= pixratio; CRect dot(CPoint(0,0), CPoint(dotwidth, dotheight)); CSize spc((1 + pixratio2 * 3) >> 1, pixratio2); dot-= dot.Size(); dot+= btn.BottomRight(); dot-= spc; if (!m_bMinTrayBtnUp) dot+= CPoint(1,1); if (m_bMinTrayBtnEnabled) { pDC->FillRect(dot, &black); } else { pDC->FillRect(dot + CPoint(1,1), &gray2); pDC->FillRect(dot, &gray); } } else { // VisualStylesXP CRect btn = MinTrayBtnGetRect(); int iState; if (!m_bMinTrayBtnEnabled) iState= TRAYBS_DISABLED; else if (m_pOwner->GetStyle() & WS_DISABLED) iState= MINBS_NORMAL; else if (m_bMinTrayBtnHitTest) iState= (m_bMinTrayBtnCapture) ? MINBS_PUSHED : MINBS_HOT; else iState= MINBS_NORMAL; // inactive if (!m_bMinTrayBtnActive) iState+= 4; // inactive state TRAYBS_Ixxx if ((m_bmMinTrayBtnBitmap.m_hObject) && (_TransparentBlt)) { // known theme (bitmap) CBitmap *pBmpOld; CDC dcMem; if ((dcMem.CreateCompatibleDC(pDC)) && ((pBmpOld= dcMem.SelectObject(&m_bmMinTrayBtnBitmap)) != NULL)) { _TransparentBlt(pDC->m_hDC, btn.left, btn.top, btn.Width(), btn.Height(), dcMem.m_hDC, 0, BMP_TRAYBTN_HEIGHT * (iState - 1), BMP_TRAYBTN_WIDTH, BMP_TRAYBTN_HEIGHT, BMP_TRAYBTN_TRANSCOLOR); dcMem.SelectObject(pBmpOld); } } else { // unknown theme (ThemeData) HTHEME hTheme= g_xpStyle.OpenThemeData(m_pOwner->GetSafeHwnd(), L"Window"); if (hTheme) { btn.top+= btn.Height() / 8; g_xpStyle.DrawThemeBackground(hTheme, pDC->m_hDC, WP_TRAYBUTTON, iState, &btn, NULL); g_xpStyle.CloseThemeData(hTheme); } } } m_pOwner->ReleaseDC(pDC); } BOOL CMinTrayBtn::MinTrayBtnHitTest(CPoint point) const { CRect rWnd; m_pOwner->GetWindowRect(&rWnd); point.Offset(-rWnd.TopLeft()); CRect rBtn= MinTrayBtnGetRect(); rBtn.InflateRect(0, CAPTION_BUTTONSPACE); return (rBtn.PtInRect(point)); } void CMinTrayBtn::MinTrayBtnSetUp() { m_bMinTrayBtnUp= TRUE; MinTrayBtnDraw(); } void CMinTrayBtn::MinTrayBtnSetDown() { m_bMinTrayBtnUp = FALSE; MinTrayBtnDraw(); } BOOL CMinTrayBtn::IsWindowsClassicStyle() const { return (!((g_xpStyle.IsThemeActive()) && (g_xpStyle.IsAppThemed()))); } INT CMinTrayBtn::GetVisualStylesXPColor() const { if (IsWindowsClassicStyle()) return -1; WCHAR szwThemeFile[MAX_PATH]; WCHAR szwThemeColor[256]; if (g_xpStyle.GetCurrentThemeName(szwThemeFile, MAX_PATH, szwThemeColor, 256, NULL, 0) != S_OK) return -1; WCHAR *p; if ((p= wcsrchr(szwThemeFile, '\\')) == NULL) return -1; p++; if (_wcsicmp(p, VISUALSTYLESXP_DEFAULTFILE) != 0) return -1; if (_wcsicmp(szwThemeColor, VISUALSTYLESXP_NAMEBLUE) == 0) return VISUALSTYLESXP_BLUE; if (_wcsicmp(szwThemeColor, VISUALSTYLESXP_NAMEMETALLIC) == 0) return VISUALSTYLESXP_METALLIC; if (_wcsicmp(szwThemeColor, VISUALSTYLESXP_NAMEHOMESTEAD) == 0) return VISUALSTYLESXP_HOMESTEAD; return -1; } BOOL CMinTrayBtn::MinTrayBtnInitBitmap() { INT nColor; m_bmMinTrayBtnBitmap.DeleteObject(); if ((nColor= GetVisualStylesXPColor()) == -1) return FALSE; const TCHAR *pszBmpName= m_pszMinTrayBtnBmpName[nColor]; BOOL res = m_bmMinTrayBtnBitmap.Attach(::LoadBitmap(AfxGetInstanceHandle(), pszBmpName)); return res; } #define WM_THEMECHANGED 0x031A BOOL CMinTrayBtn::ProcessWindowMessage(HWND hWnd, UINT nMsg, WPARAM wParam, LPARAM lParam, LRESULT& lResult) { switch (nMsg) { case WM_NCPAINT: lResult = DefWindowProc(nMsg, wParam, lParam); OnNcPaint(); return TRUE; case WM_SETTEXT: lResult = DefWindowProc(nMsg, wParam, lParam); MinTrayBtnDraw(); return TRUE; case WM_NCACTIVATE: lResult = DefWindowProc(nMsg, wParam, lParam); OnNcActivate(wParam); return TRUE; case WM_NCHITTEST: { lResult = (INT)OnNcHitTest(CPoint(lParam)); if (lResult == HTERROR) lResult = DefWindowProc(nMsg, wParam, lParam); } return TRUE; case WM_NCLBUTTONDOWN: if (!OnNcLButtonDown(wParam, CPoint(lParam))) lResult = DefWindowProc(nMsg, wParam, lParam); else lResult = 0; return TRUE; case WM_THEMECHANGED: OnThemeChanged(); break; case WM_MOUSEMOVE: OnMouseMove(wParam, CPoint(lParam)); break; case WM_LBUTTONUP: if (OnLButtonUp(wParam, CPoint(lParam))) lResult = 0; else lResult = DefWindowProc(nMsg, wParam, lParam); return TRUE; } return FALSE; }
ChadSki/FeatherweightVirtualMachine
FVM_UI/fvmshell/misc/MinTrayBtn.cpp
C++
gpl-2.0
13,862
# Camdram ![Build status](https://github.com/camdram/camdram/workflows/CI/badge.svg?branch=master&event=push) ![Deployment status](https://github.com/camdram/camdram/actions/workflows/deploy-release.yml/badge.svg) [![Code Coverage](https://codecov.io/gh/camdram/camdram/branch/master/graphs/badge.svg?branch=master)](http://codecov.io/github/camdram/camdram?branch=master) [![Join the chat at https://gitter.im/camdram/development](https://badges.gitter.im/Join%20Chat.svg)](https://gitter.im/camdram/development) Camdram is an [open source](http://opensource.org/docs/osd) project developed by a team of volunteers for the benefit of the Cambridge student theatre community. We use this repository to host the code that runs Camdram and to co-ordinate our work, however we welcome anyone to contribute bugs and suggest new features. The steps required to set up a development checkout of Camdram are detailed below. For the sake of brevity, these instructions assume that the reader is familiar with a number of technologies, such as developing on a Linux based platform, using Git and GitHub. New releases are made on the `master` branch every so often using the GitHub interface. This automatically generates a changelog and pushes the new release into production at https://www.camdram.net/. The latest changes can be seen at https://development.camdram.net/ which always reflects the `HEAD` state of this repository. If you encounter any problems with the instructions below, please [create a GitHub issue]( https://github.com/camdram/camdram/issues/new) or send an e-mail to support@camdram.net. We also have a [live chat hosted on Gitter](https://gitter.im/camdram/development) which you can use to quickly and informally get in touch with the development team. ## Docker Installation [Docker](https://www.docker.com/get-started) is a virtualization service that acts as a platform for running containerised application. It's a great way to get a development environment setup with minimal hassle and should work cross-platform on Windows, macOS and Linux. First you will need to install Docker using the link above, then clone the Camdram repository and build the necessary Docker images: 1. `git clone git@github.com:camdram/camdram.git && cd camdram` 2. `docker-compose build` 3. `docker-compose up` This will automatically create and configure the full Camdram stack and start the server locally on port 8000. ## Native Installation The native installation is a lot more complicated than the Docker installation procedure and so we've broken it down into several steps. ### 1) Install programs You will need to install the necessary package dependencies required to run Camdram. **PHP version 7.3 or greater is required**. #### Debian/Ubuntu and Derivatives The command below can be run on recent Debian-based distros (including Ubuntu and the [Windows Subsystem for Linux](https://docs.microsoft.com/en-us/windows/wsl/install-win10)). ``` sudo apt-get install git-core php php-cli composer php-curl php-intl php-sqlite3 php-gd php-json php-mbstring php-xml php-zip ``` #### macOS You will need to have [Homebrew](https://brew.sh/) installed. The following command _appears_ (from minimal testing) to install everything required on recent versions of macOS. ``` brew install git php composer ``` Installation methods on other distros and operating systems will vary. ### 2) Create a local version of Camdram The steps below assume that the Composer PHP package manager is installed globally on your system. If it is not available in your distro's repositories, alternate installation methods can be found at https://getcomposer.org/download/. **Note**: some of the SQL database operations performed by the `composer` commands below are memory-intensive. Default installations of PHP tend to set the memory limit of a PHP script to a value which will undoubtedly cause fatal errors. To prevent this, find your `php.ini` file (location varies by system) and change the `memory_limit` setting, to something like `memory_limit = 1G` (a gigabyte is definitely sufficient - you may be able to get away with a lot less if you prefer). Alternatively you can call the PHP interpreter like so: ``` php -d memory_limit=1G $(which composer) etc....... ``` The command below will download and set up a Camdram checkout in a new folder called `camdram`: ``` composer create-project camdram/camdram camdram dev-master --no-interaction --keep-vcs ``` After obtaining a copy of the code, change into the newly created directory and start a local web server: ``` cd camdram php app/console server:run ``` You should then be able to visit [http://127.0.0.1:8000/](http://127.0.0.1:8000/) in your web browser to see your personal version of Camdram's homepage. You'll need to create an administrator account in order to get access to most of the site's features. To make this happen automatically whenever you reset the database, open `app/config/parameters.yml` and replace the line setting `default_admin_idents` with: ```yaml default_admin_idents: "[ { \"name\": \"Your Name\", \"email\": \"yourcrsid@cam.ac.uk\" } ]" ``` then run ``` php app/console doctrine:fixtures:load --no-interaction ``` You should then be able to log in with Raven and have full administrator access. ### 3) Run test suite Camdram has a limited but growing [automated test suite](https://github.com/camdram/camdram/wiki/Running-and-creating-tests), which can be used to ensure your checkout is working and check for certain regressions after making changes. It can be executed by running: ``` ./runtests ``` ### 4) Create a fork Camdram's development model follows the standard idioms used by FOSS projects hosted on GitHub. If you are just interested in experimenting with the codebase, no further steps are necessary, but if you'd like to contribute then you will need to [create a fork](https://help.github.com/articles/fork-a-repo). After creating a personal fork, you can repoint your checkout using the commands below. ``` git remote rename origin upstream git remote add origin git@github.com:your-github-username/camdram.git ``` We run Camdram as a meritocracy: anyone who has a reasonable number of pull requests accepted will be given access rights to commit straight to the Camdram repository ### 5) Write some code It is a good idea to create a "feature branch" before starting development, so that the pull request will be named appropriately: ``` git checkout -b my-cool-feature ``` Some useful tips: * The site uses the Symfony PHP framework - [read the documentation](http://symfony.com/doc/3.4/index.html). * Use the GitHub issue tracker to discover and discuss issues to work on. If you think you know how to do something, write the code, commit it, and submit a pull request. * If you want to discuss how to implement a new feature or how to fix a bug, get in touch with one of the developers. It would probably be wise to get in touch before starting on any significant projects to avoid wasted effort! * Visit http://try.github.io/ if you're not familiar with Git. * Code should ideally conform to the style guide here: http://www.php-fig.org/psr/psr-2/. If this is far too daunting, a poorly styled but functional improvement is better than no improvement. You can use http://cs.sensiolabs.org/ to (mostly) clean your code up after writing it. Depending on the type of change, ensure it works as a logged-in and/or non-logged in visitor. You can grant administration rights to your user account (which allows you to create and modify any Camdram content) by running ``` php app/console camdram:admins --grant=youremail@domain.com ``` ### 6) Submit your changes * Run `git add file1.php file2.php` for each file you wish to include in the commit * Run `git commit` and enter a message describing the changes you have made * Run `git push` to send your changes to GitHub It is good practice to include the relevant issue number (prefixed with a hash #) at the end of the commit message - this will cause your commit to be linked to the issue page on GitHub. Once your changes are pushed to your Camdram fork on GitHub, you can [submit a pull request](https://help.github.com/articles/creating-a-pull-request/) to have it included in Camdram. **Please note:** we automatically display the names of some contributors on our [development page](https://www.camdram.net/development/) as a way of saying thanks! By submitting your changes you are acknowledging that you are happy for this to happen. ### 7) Pull in other people's changes At a later date, once your local repository has become out of sync with Github (because other people have make changes), you can run the following commands to pull in other people's changes and update your checkout: ``` git fetch upstream git merge upstream/master ``` The following commands may need to be run after the above, if the dependencies, database schema or JS/CSS assets have changed. ``` composer install php app/console camdram:database:refresh php app/console camdram:assets:download ``` ### 8) Read the Wiki [The Wiki](http://github.com/camdram/camdram/wiki) has various pieces of information about both the current and in-development versions of Camdram. Reading through those pages can give insight into the more esoteric parts of the system. You can suggest ideas for new articles using the contact details above. The following wiki pages detail how to create a server set-up that's more similar to the version of Camdram at https://www.camdram.net/: * [Setting up for JS/CSS development](https://github.com/camdram/camdram/wiki/Webpack-setup-guide) * [Setting up a MySQL database](https://github.com/camdram/camdram/wiki/Setting-up-a-MySQL-database) * [External API registration](https://github.com/camdram/camdram/wiki/API-registration) * [Setting up an Apache virtual host](https://github.com/camdram/camdram/wiki/Setting-up-an-Apache-virtual-host) --- ### Copyright Camdram is released under version two of the [GNU General Public License](https://www.gnu.org/licenses/old-licenses/gpl-2.0.en.html#SEC1). Copyright (C) 2014–2021 Members of the Camdram Web Team and other contributors.
camdram/camdram
README.md
Markdown
gpl-2.0
10,213
biopackplus =========== Biopack plus
complancecenter/biopackplus
README.md
Markdown
gpl-2.0
38
<?xml version="1.0" encoding="utf-8"?> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en"> <head> <meta http-equiv="content-type" content="text/html; charset=UTF-8" /> <title>Liquidsoap dev :: Audio Stream Generation</title> <link href="../../css/new.css" type="text/css" rel="stylesheet" /> <script type="text/javascript" src="//www.google.com/jsapi"></script> <link rel="shortcut icon" href="../favicon.ico" /> <script> google.load("jquery", "1.6.1"); google.load("jqueryui", "1.8.14"); </script> <script type="text/javascript" src="../../js/jQuery.syntax/jquery.syntax.min.js"></script> <script type="text/javascript" src="../../js/liq-jquery.js"></script> </head> <body> <div class="menu"> <ul> <li id="menu-developers"> <a href="https://github.com/savonet/liquidsoap/issues" target="_blank">developpers</a> </li> <li id="menu-doc-api-www"> <a href="../reference.html">API</a> </li> <li id="menu-support"> <a href="documentation.html">documentation</a> </li> <li id="menu-download"> <a href="../../download.html">download</a> </li> <li id="menu-about"> <a href="../../index.html">about</a> </li> </ul> </div> <div class="section" id="main"> <h1>get_json_metadata.liq</h1> <div class="content"> <pre class="syntax">meta = ref [] # s = some source # Update current metadata # converted in UTF8 def update_meta(m) = m = metadata.export(m) recode = string.recode(out_enc="UTF-8") def f(x) = (recode(fst(x)),recode(snd(x))) end meta := list.map(f,m) end # Apply update_metadata # every time we see a new # metadata s = on_metadata(update_meta,s) # Return the json content # of meta def get_meta(~protocol,~data,~headers,uri) = m = !meta http_response( protocol=protocol, code=200, headers=[("Content-Type","application/json; charset=utf-8")], data=json_of(m) ) end # Register get_meta at port 700 harbor.http.register(port=7000,method="GET","/getmeta",get_meta) </pre> <a href="get_json_metadata.liq"> <img class="grab" src="../../images/grab.png" alt="Grab the code!" title="Grab the code!"> </a> </div> <div id="footer"> 2003-2017 Savonet team</div> </div> <script type="text/javascript" src="//www.google.com/cse/brand?form=cse-search-box&amp;lang=en"></script> <script type="text/javascript" src="../../js/search.js"></script> <script type="text/javascript"> var _gaq = _gaq || []; _gaq.push(['_setAccount', 'UA-927362-1']); _gaq.push(['_trackPageview']); (function() { var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true; ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js'; var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s); })(); </script> </body> </html>
savonet/liquidsoap-full
website/orig/legacy/doc-dev/scripts/get_json_metadata.html
HTML
gpl-2.0
3,062
package com.pcab.marvel.model; /** * Summary type used for creators. */ public class RoleSummary extends Summary { /** * The role in the parent entity. */ private String role; public String getRole() { return role; } public void setRole(String role) { this.role = role; } }
pablocabrera85/marvel-api-client
src/main/java/com/pcab/marvel/model/RoleSummary.java
Java
gpl-2.0
330
/* ***** BEGIN LICENSE BLOCK ***** * Source last modified: $Id: test_velocity_caps.cpp,v 1.2 2005/03/14 19:36:42 bobclark Exp $ * * Portions Copyright (c) 1995-2004 RealNetworks, Inc. All Rights Reserved. * * The contents of this file, and the files included with this file, * are subject to the current version of the RealNetworks Public * Source License (the "RPSL") available at * http://www.helixcommunity.org/content/rpsl unless you have licensed * the file under the current version of the RealNetworks Community * Source License (the "RCSL") available at * http://www.helixcommunity.org/content/rcsl, in which case the RCSL * will apply. You may also obtain the license terms directly from * RealNetworks. You may not use this file except in compliance with * the RPSL or, if you have a valid RCSL with RealNetworks applicable * to this file, the RCSL. Please see the applicable RPSL or RCSL for * the rights, obligations and limitations governing use of the * contents of the file. * * Alternatively, the contents of this file may be used under the * terms of the GNU General Public License Version 2 or later (the * "GPL") in which case the provisions of the GPL are applicable * instead of those above. If you wish to allow use of your version of * this file only under the terms of the GPL, and not to allow others * to use your version of this file under the terms of either the RPSL * or RCSL, indicate your decision by deleting the provisions above * and replace them with the notice and other provisions required by * the GPL. If you do not delete the provisions above, a recipient may * use your version of this file under the terms of any one of the * RPSL, the RCSL or the GPL. * * This file is part of the Helix DNA Technology. RealNetworks is the * developer of the Original Code and owns the copyrights in the * portions it created. * * This file, and the files included with this file, is distributed * and made available on an 'AS IS' basis, WITHOUT WARRANTY OF ANY * KIND, EITHER EXPRESS OR IMPLIED, AND REALNETWORKS HEREBY DISCLAIMS * ALL SUCH WARRANTIES, INCLUDING WITHOUT LIMITATION, ANY WARRANTIES * OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, QUIET * ENJOYMENT OR NON-INFRINGEMENT. * * Technology Compatibility Kit Test Suite(s) Location: * http://www.helixcommunity.org/content/tck * * Contributor(s): * * ***** END LICENSE BLOCK ***** */ #include "hxtypes.h" #include "hxcom.h" #include "hxplayvelocity.h" #include "test_velocity_caps.h" CHXPlaybackVelocityCapsTest::CHXPlaybackVelocityCapsTest() { m_ppCaps[0] = new CHXPlaybackVelocityCaps(); m_ppCaps[1] = new CHXPlaybackVelocityCaps(); } CHXPlaybackVelocityCapsTest::~CHXPlaybackVelocityCapsTest() { HX_DELETE(m_ppCaps[0]); HX_DELETE(m_ppCaps[1]); } void CHXPlaybackVelocityCapsTest::GetCommandInfo(UTVector<HLXUnitTestCmdInfo*>& cmds) { cmds.Resize(6); cmds[0] = new HLXUnitTestCmdInfoDisp<CHXPlaybackVelocityCapsTest>(this, "CHXPlaybackVelocityCaps()", &CHXPlaybackVelocityCapsTest::HandleConstructorCmd, 2); cmds[1] = new HLXUnitTestCmdInfoDisp<CHXPlaybackVelocityCapsTest>(this, "GetNumRanges", &CHXPlaybackVelocityCapsTest::HandleGetNumRangesCmd, 3); cmds[2] = new HLXUnitTestCmdInfoDisp<CHXPlaybackVelocityCapsTest>(this, "GetRange", &CHXPlaybackVelocityCapsTest::HandleGetRangeCmd, 5); cmds[3] = new HLXUnitTestCmdInfoDisp<CHXPlaybackVelocityCapsTest>(this, "AddRange", &CHXPlaybackVelocityCapsTest::HandleAddRangeCmd, 5); cmds[4] = new HLXUnitTestCmdInfoDisp<CHXPlaybackVelocityCapsTest>(this, "CombineCapsLogicalAnd", &CHXPlaybackVelocityCapsTest::HandleCombineCapsLogicalAndCmd, 2); cmds[5] = new HLXUnitTestCmdInfoDisp<CHXPlaybackVelocityCapsTest>(this, "IsCapable", &CHXPlaybackVelocityCapsTest::HandleIsCapableCmd, 4); } const char* CHXPlaybackVelocityCapsTest::DefaultCommandLine() const { return "test_velocity_caps test_velocity_caps.in -a"; } HLXCmdBasedTest* CHXPlaybackVelocityCapsTest::Clone() const { return new CHXPlaybackVelocityCapsTest(); } bool CHXPlaybackVelocityCapsTest::HandleConstructorCmd(const UTVector<UTString>& params) { bool bRet = false; UINT32 ulIndex = strtoul(params[1], NULL, 10); if (ulIndex < 2) { HX_DELETE(m_ppCaps[ulIndex]); m_ppCaps[ulIndex] = new CHXPlaybackVelocityCaps(); if (m_ppCaps[ulIndex]) { bRet = true; } } return bRet; } bool CHXPlaybackVelocityCapsTest::HandleGetNumRangesCmd(const UTVector<UTString>& params) { bool bRet = false; UINT32 ulIndex = strtoul(params[1], NULL, 10); if (ulIndex < 2 && m_ppCaps[ulIndex]) { UINT32 ulExpectedNum = strtoul(params[2], NULL, 10); UINT32 ulActualNum = m_ppCaps[ulIndex]->GetNumRanges(); if (ulExpectedNum == ulActualNum) { bRet = true; } } return bRet; } bool CHXPlaybackVelocityCapsTest::HandleGetRangeCmd(const UTVector<UTString>& params) { bool bRet = false; UINT32 ulIndex = strtoul(params[1], NULL, 10); if (ulIndex < 2 && m_ppCaps[ulIndex]) { UINT32 ulRangeIndex = strtoul(params[2], NULL, 10); INT32 lExpectedMin = (INT32) strtol(params[3], NULL, 10); INT32 lExpectedMax = (INT32) strtol(params[4], NULL, 10); INT32 lActualMin = 0; INT32 lActualMax = 0; HX_RESULT retVal = m_ppCaps[ulIndex]->GetRange(ulRangeIndex, lActualMin, lActualMax); if (SUCCEEDED(retVal) && lExpectedMin == lActualMin && lExpectedMax == lActualMax) { bRet = true; } } return bRet; } bool CHXPlaybackVelocityCapsTest::HandleAddRangeCmd(const UTVector<UTString>& params) { bool bRet = false; UINT32 ulIndex = strtoul(params[1], NULL, 10); if (ulIndex < 2 && m_ppCaps[ulIndex]) { INT32 lMinToAdd = strtol(params[2], NULL, 10); INT32 lMaxToAdd = strtol(params[3], NULL, 10); UINT32 ulExpRet = strtoul(params[4], NULL, 10); HX_RESULT retVal = m_ppCaps[ulIndex]->AddRange(lMinToAdd, lMaxToAdd); if ((ulExpRet && SUCCEEDED(retVal)) || (!ulExpRet && FAILED(retVal))) { bRet = true; } } return bRet; } bool CHXPlaybackVelocityCapsTest::HandleCombineCapsLogicalAndCmd(const UTVector<UTString>& params) { bool bRet = false; UINT32 ulIndex = strtoul(params[1], NULL, 10); if (ulIndex < 2 && m_ppCaps[0] && m_ppCaps[1]) { UINT32 ulOtherIndex = (ulIndex == 0 ? 1 : 0); HX_RESULT retVal = m_ppCaps[ulIndex]->CombineCapsLogicalAnd(m_ppCaps[ulOtherIndex]); if (SUCCEEDED(retVal)) { bRet = true; } } return bRet; } bool CHXPlaybackVelocityCapsTest::HandleIsCapableCmd(const UTVector<UTString>& params) { bool bRet = false; UINT32 ulIndex = strtoul(params[1], NULL, 10); if (ulIndex < 2 && m_ppCaps[ulIndex]) { INT32 lVelToCheck = strtol(params[2], NULL, 10); UINT32 ulExpRet = strtoul(params[3], NULL, 10); HXBOOL bExpRet = (ulExpRet ? TRUE : FALSE); HXBOOL bActRet = m_ppCaps[ulIndex]->IsCapable(lVelToCheck); if (bActRet == bExpRet) { bRet = true; } } return bRet; }
muromec/qtopia-ezx
src/3rdparty/libraries/helix/src/common/util/test/test_velocity_caps.cpp
C++
gpl-2.0
8,664
<div class="wikidoc"> <h1>Installing</h1> Installing is too easy. Run setup program and follow it. <br> <b>Remember:</b> When you install any add-on to Outlook need quit this program. <h1>Using</h1> After install and start Outlook, the system add new tab in Ribbon with name &quot;<b>Add-Ins</b>&quot;. There is new section &quot;<b>Google Contact</b>&quot;. There are three buttons: Configuration, Synchronize and About. <br> <img title="Add-Ins Ribbon" alt="Add-Ins Ribbon" src="http://i3.codeplex.com/Download?ProjectName=pzcgsync&DownloadId=266042"> <h2>Configuration</h2> Before first using you must configure Google account and synchronization way. Group &quot;<b>First synchronize</b>&quot; is for new synchronization or for re-connect synchronization between systems. After first synchronization ends the checkbox “Is First synchronize “ uncheck and in every next synchronization is use settings from &quot;<b>Standard synchronize setup</b>&quot;.<br> There is possible set logging level and logging directory.<br> &nbsp;<a href="http://download.codeplex.com/Download?ProjectName=pzcgsync&DownloadId=390361"><img title="image" border="0" alt="image" src="http://download.codeplex.com/Download?ProjectName=pzcgsync&DownloadId=390362" width="444" height="286" style="border-right-width:0px; padding-left:0px; padding-right:0px; display:inline; border-top-width:0px; border-bottom-width:0px; border-left-width:0px; padding-top:0px"></a> <p>In Advanced settings is possible set more options. First one is configuration for Cache system. This mean use local cache for contacts and its images. There are two buttons witch delete cached data for Outlook or Google.</p> <p>Parameter Time To Live mean – how many days are cache data valid from last synchronization. After this time are all data read from source.</p> <p><a href="http://download.codeplex.com/Download?ProjectName=pzcgsync&DownloadId=390363"><img title="image" border="0" alt="image" src="http://download.codeplex.com/Download?ProjectName=pzcgsync&DownloadId=390364" width="454" height="298" style="border-right-width:0px; padding-left:0px; padding-right:0px; display:inline; border-top-width:0px; border-bottom-width:0px; border-left-width:0px; padding-top:0px"></a></p> <p>Next available options on Advanced Configuration is Clear synchronization keys in source systems.</p> <p><a href="http://download.codeplex.com/Download?ProjectName=pzcgsync&DownloadId=390365"><img title="image" border="0" alt="image" src="http://download.codeplex.com/Download?ProjectName=pzcgsync&DownloadId=390366" width="450" height="296" style="border-right-width:0px; padding-left:0px; padding-right:0px; display:inline; border-top-width:0px; border-bottom-width:0px; border-left-width:0px; padding-top:0px"></a></p> <h2>Synchronization</h2> <p>System synchronizes your Outlook contacts with Google Contacts by your request. After synchronization is show window with information about changes in both systems.</p> <p>In fist time and after more than one hour inactivity need authorize application for Google Contact API. Program open default internet browser and request your credentials. This is no more write to&nbsp; application.</p> <p><a href="http://download.codeplex.com/Download?ProjectName=pzcgsync&DownloadId=390367"><img title="image" border="0" alt="image" src="http://download.codeplex.com/Download?ProjectName=pzcgsync&DownloadId=390368" width="690" height="445" style="border-bottom:0px; border-left:0px; padding-left:0px; padding-right:0px; display:inline; border-top:0px; border-right:0px; padding-top:0px"></a></p> <p>After login to Google account (if you don’t login automatically), you must approve application permissions.</p> <p><a href="http://download.codeplex.com/Download?ProjectName=pzcgsync&DownloadId=390369"><img title="image" border="0" alt="image" src="http://download.codeplex.com/Download?ProjectName=pzcgsync&DownloadId=390370" width="677" height="265" style="border-bottom:0px; border-left:0px; padding-left:0px; padding-right:0px; display:inline; border-top:0px; border-right:0px; padding-top:0px"></a></p> <p>When press “<strong>Allow access</strong>” system generate access code for application. This code is valid only short time. You copy this code and insert to application window.</p> <p><a href="http://download.codeplex.com/Download?ProjectName=pzcgsync&DownloadId=390371"><img title="image" border="0" alt="image" src="http://download.codeplex.com/Download?ProjectName=pzcgsync&DownloadId=390372" width="522" height="105" style="border-bottom:0px; border-left:0px; padding-left:0px; padding-right:0px; display:inline; border-top:0px; border-right:0px; padding-top:0px"></a></p> <p>Insert code to this windows and after press OK system start synchronize contact.</p> <p><a href="http://download.codeplex.com/Download?ProjectName=pzcgsync&DownloadId=390373"><img title="image" border="0" alt="image" src="http://download.codeplex.com/Download?ProjectName=pzcgsync&DownloadId=390374" width="446" height="159" style="border-bottom:0px; border-left:0px; padding-left:0px; padding-right:0px; display:inline; border-top:0px; border-right:0px; padding-top:0px"></a></p> <p>Synchronization process has five parts, reading from Outlook, reading from Google, </p> <p><br> <img title="Information when program run" alt="Information when program run" src="http://i3.codeplex.com/Download?ProjectName=pzcgsync&DownloadId=266045"> <img title="Final information about last synchronization" alt="Final information about last synchronization" src="http://i3.codeplex.com/Download?ProjectName=pzcgsync&DownloadId=266044"></p> </div><div class="ClearBoth"></div>
ZdPo/ContactSync
docs/Installation.html
HTML
gpl-2.0
5,678
/*************************************************************************** kgpanel.cpp - description ------------------- copyright : (C) 2003 by Csaba Karai copyright : (C) 2010 by Jan Lepper e-mail : krusader@users.sourceforge.net web site : http://krusader.sourceforge.net --------------------------------------------------------------------------- Description *************************************************************************** A db dD d8888b. db db .d8888. .d8b. d8888b. d88888b d8888b. 88 ,8P' 88 `8D 88 88 88' YP d8' `8b 88 `8D 88' 88 `8D 88,8P 88oobY' 88 88 `8bo. 88ooo88 88 88 88ooooo 88oobY' 88`8b 88`8b 88 88 `Y8b. 88~~~88 88 88 88~~~~~ 88`8b 88 `88. 88 `88. 88b d88 db 8D 88 88 88 .8D 88. 88 `88. YP YD 88 YD ~Y8888P' `8888Y' YP YP Y8888D' Y88888P 88 YD S o u r c e F i l e *************************************************************************** * * * 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. * * * ***************************************************************************/ #include "kgpanel.h" #include "../defaults.h" #include "../Dialogs/krdialogs.h" #include <QtGui/QTabWidget> #include <QFrame> #include <QGridLayout> #include <QLabel> #include <QVBoxLayout> #include <klocale.h> #include <QtGui/QValidator> #include <kmessagebox.h> #include <kfiledialog.h> #include <kglobal.h> #include <kstandarddirs.h> #include "viewtype.h" #include "viewfactory.h" #include "module.h" #include "viewconfigui.h" #include "../krusaderapp.h" #include "../Panel/krlayoutfactory.h" enum { PAGE_MISC = 0, PAGE_VIEW, PAGE_PANELTOOLBAR, PAGE_MOUSE, PAGE_MEDIA_MENU, PAGE_LAYOUT }; KgPanel::KgPanel(bool first, QWidget* parent) : KonfiguratorPage(first, parent) { tabWidget = new QTabWidget(this); setWidget(tabWidget); setWidgetResizable(true); setupMiscTab(); setupPanelTab(); setupButtonsTab(); setupMouseModeTab(); setupMediaMenuTab(); setupLayoutTab(); } ViewConfigUI *KgPanel::viewConfigUI() { ViewConfigUI *viewCfg = qobject_cast<ViewConfigUI*>(KrusaderApp::self()->module("View")); Q_ASSERT(viewCfg); return viewCfg; } // --------------------------------------------------------------------------------------- // ---------------------------- Misc TAB ------------------------------------------------ // --------------------------------------------------------------------------------------- void KgPanel::setupMiscTab() { QScrollArea *scrollArea = new QScrollArea(tabWidget); QWidget *tab = new QWidget(scrollArea); scrollArea->setFrameStyle(QFrame::NoFrame); scrollArea->setWidget(tab); scrollArea->setWidgetResizable(true); tabWidget->addTab(scrollArea, i18n("General")); QVBoxLayout *miscLayout = new QVBoxLayout(tab); miscLayout->setSpacing(6); miscLayout->setContentsMargins(11, 11, 11, 11); // --------------------------------------------------------------------------------------- // ------------------------------- Address Bar ------------------------------------------- // --------------------------------------------------------------------------------------- QGroupBox *miscGrp = createFrame(i18n("Address bar"), tab); QGridLayout *miscGrid = createGridLayout(miscGrp); KONFIGURATOR_CHECKBOX_PARAM general_settings[] = { // cfg_class, cfg_name, default, text, restart, tooltip {"Look&Feel", "FlatOriginBar", _FlatOriginBar, i18n("Flat address bar"), true, 0 }, {"Look&Feel", "ShortenHomePath", _ShortenHomePath, i18n("Shorten home path"), true, i18n("Display home path as \"~\"") }, }; KonfiguratorCheckBoxGroup *cbs = createCheckBoxGroup(2, 0, general_settings, 2 /*count*/, miscGrp, PAGE_MISC); cbs->find("FlatOriginBar")->addDep(cbs->find("ShortenHomePath")); miscGrid->addWidget(cbs, 0, 0); miscLayout->addWidget(miscGrp); // --------------------------------------------------------------------------------------- // ------------------------------- Operation --------------------------------------------- // --------------------------------------------------------------------------------------- miscGrp = createFrame(i18n("Operation"), tab); miscGrid = createGridLayout(miscGrp); KONFIGURATOR_CHECKBOX_PARAM operation_settings[] = { // cfg_class, cfg_name, default, text, restart, tooltip {"Look&Feel", "Mark Dirs", _MarkDirs, i18n("Autoselect directories"), false, i18n("When matching the select criteria, not only files will be selected, but also directories.") }, {"Look&Feel", "Rename Selects Extension", true, i18n("Rename selects extension"), false, i18n("When renaming a file, the whole text is selected. If you want Total-Commander like renaming of just the name, without extension, uncheck this option.") }, {"Look&Feel", "UnselectBeforeOperation", _UnselectBeforeOperation, i18n("Unselect files before copy/move"), false, i18n("Unselect files, which are to be copied/moved, before the operation starts.") }, {"Look&Feel", "FilterDialogRemembersSettings", _FilterDialogRemembersSettings, i18n("Filter dialog remembers settings"), false, i18n("The filter dialog is opened with the last filter settings that where applied to the panel.") }, }; cbs = createCheckBoxGroup(2, 0, operation_settings, 4 /*count*/, miscGrp, PAGE_MISC); miscGrid->addWidget(cbs, 0, 0); miscLayout->addWidget(miscGrp); // --------------------------------------------------------------------------------------- // ------------------------------ Tabs --------------------------------------------------- // --------------------------------------------------------------------------------------- miscGrp = createFrame(i18n("Tabs"), tab); miscGrid = createGridLayout(miscGrp); KONFIGURATOR_CHECKBOX_PARAM tabbar_settings[] = { // cfg_class cfg_name default text restart tooltip {"Look&Feel", "Fullpath Tab Names", _FullPathTabNames, i18n("Use full path tab names"), true , i18n("Display the full path in the folder tabs. By default only the last part of the path is displayed.") }, {"Look&Feel", "Show Tab Buttons", true, i18n("Show new/close tab buttons"), true , i18n("Show the new/close tab buttons") }, }; cbs = createCheckBoxGroup(2, 0, tabbar_settings, 2 /*count*/, miscGrp, PAGE_MISC); miscGrid->addWidget(cbs, 0, 0); // ----------------- Tab Bar position ---------------------------------- QHBoxLayout *hbox = new QHBoxLayout(); hbox->addWidget(new QLabel(i18n("Tab Bar position:"), miscGrp)); KONFIGURATOR_NAME_VALUE_PAIR positions[] = {{ i18n("Top"), "top" }, { i18n("Bottom"), "bottom" } }; KonfiguratorComboBox *cmb = createComboBox("Look&Feel", "Tab Bar Position", "bottom", positions, 2, miscGrp, true, false, PAGE_MISC); hbox->addWidget(cmb); hbox->addWidget(createSpacer(miscGrp)); miscGrid->addLayout(hbox, 1, 0); miscLayout->addWidget(miscGrp); // --------------------------------------------------------------------------------------- // ----------------------------- Quicksearch ------------------------------------------- // --------------------------------------------------------------------------------------- miscGrp = createFrame(i18n("Quicksearch/Quickfilter"), tab); miscGrid = createGridLayout(miscGrp); KONFIGURATOR_CHECKBOX_PARAM quicksearch[] = { // cfg_class cfg_name default text restart tooltip {"Look&Feel", "New Style Quicksearch", _NewStyleQuicksearch, i18n("New style Quicksearch"), false, i18n("Opens a quick search dialog box.") }, {"Look&Feel", "Case Sensitive Quicksearch", _CaseSensitiveQuicksearch, i18n("Case sensitive Quicksearch/QuickFilter"), false, i18n("All files beginning with capital letters appear before files beginning with non-capital letters (UNIX default).") }, {"Look&Feel", "Up/Down Cancels Quicksearch", false, i18n("Up/Down cancels Quicksearch"), false, i18n("Pressing the Up/Down buttons cancels Quicksearch.") }, }; quicksearchCheckboxes = createCheckBoxGroup(2, 0, quicksearch, 3 /*count*/, miscGrp, PAGE_MISC); miscGrid->addWidget(quicksearchCheckboxes, 0, 0); connect(quicksearchCheckboxes->find("New Style Quicksearch"), SIGNAL(stateChanged(int)), this, SLOT(slotDisable())); slotDisable(); // -------------- Quicksearch position ----------------------- hbox = new QHBoxLayout(); hbox->addWidget(new QLabel(i18n("Position:"), miscGrp)); cmb = createComboBox("Look&Feel", "Quicksearch Position", "bottom", positions, 2, miscGrp, true, false, PAGE_MISC); hbox->addWidget(cmb); hbox->addWidget(createSpacer(miscGrp)); miscGrid->addLayout(hbox, 1, 0); miscLayout->addWidget(miscGrp); // -------------------------------------------------------------------------------------------- // ------------------------------- Status/Totalsbar settings ---------------------------------- // -------------------------------------------------------------------------------------------- miscGrp = createFrame(i18n("Status/Totalsbar"), tab); miscGrid = createGridLayout(miscGrp); KONFIGURATOR_CHECKBOX_PARAM barSettings[] = { {"Look&Feel", "Show Size In Bytes", true, i18n("Show size in bytes too"), true, i18n("Show size in bytes too") }, {"Look&Feel", "ShowSpaceInformation", true, i18n("Show space information"), true, i18n("Show free/total space on the device") }, }; KonfiguratorCheckBoxGroup *barSett = createCheckBoxGroup(2, 0, barSettings, 2 /*count*/, miscGrp, PAGE_MISC); miscGrid->addWidget(barSett, 1, 0, 1, 2); miscLayout->addWidget(miscGrp); } // -------------------------------------------------------------------------------------------- // ------------------------------------ Layout Tab -------------------------------------------- // -------------------------------------------------------------------------------------------- void KgPanel::setupLayoutTab() { QScrollArea *scrollArea = new QScrollArea(tabWidget); QWidget *tab = new QWidget(scrollArea); scrollArea->setFrameStyle(QFrame::NoFrame); scrollArea->setWidget(tab); scrollArea->setWidgetResizable(true); tabWidget->addTab(scrollArea, i18n("Layout")); QGridLayout *grid = createGridLayout(tab); QStringList layoutNames = KrLayoutFactory::layoutNames(); int numLayouts = layoutNames.count(); grid->addWidget(createSpacer(tab), 0, 2); QLabel *l = new QLabel(i18n("Layout:"), tab); l->setAlignment(Qt::AlignRight | Qt::AlignVCenter); grid->addWidget(l, 0, 0); KONFIGURATOR_NAME_VALUE_PAIR *layouts = new KONFIGURATOR_NAME_VALUE_PAIR[numLayouts]; for (int i = 0; i != numLayouts; i++) { layouts[ i ].text = KrLayoutFactory::layoutDescription(layoutNames[i]); layouts[ i ].value = layoutNames[i]; } KonfiguratorComboBox *cmb = createComboBox("PanelLayout", "Layout", "default", layouts, numLayouts, tab, true, false, PAGE_LAYOUT); grid->addWidget(cmb, 0, 1); delete [] layouts; l = new QLabel(i18n("Frame Color:"), tab); l->setAlignment(Qt::AlignRight | Qt::AlignVCenter); grid->addWidget(l, 1, 0); KONFIGURATOR_NAME_VALUE_PAIR frameColor[] = { { i18nc("Frame color", "Defined by Layout"), "default" }, { i18nc("Frame color", "None"), "none" }, { i18nc("Frame color", "Statusbar"), "Statusbar" } }; cmb = createComboBox("PanelLayout", "FrameColor", "default", frameColor, 3, tab, true, false, PAGE_LAYOUT); grid->addWidget(cmb, 1, 1); l = new QLabel(i18n("Frame Shape:"), tab); l->setAlignment(Qt::AlignRight | Qt::AlignVCenter); grid->addWidget(l, 2, 0); KONFIGURATOR_NAME_VALUE_PAIR frameShape[] = { { i18nc("Frame shape", "Defined by Layout"), "default" }, { i18nc("Frame shape", "None"), "NoFrame" }, { i18nc("Frame shape", "Box"), "Box" }, { i18nc("Frame shape", "Panel"), "Panel" }, }; cmb = createComboBox("PanelLayout", "FrameShape", "default", frameShape, 4, tab, true, false, PAGE_LAYOUT); grid->addWidget(cmb, 2, 1); l = new QLabel(i18n("Frame Shadow:"), tab); l->setAlignment(Qt::AlignRight | Qt::AlignVCenter); grid->addWidget(l, 3, 0); KONFIGURATOR_NAME_VALUE_PAIR frameShadow[] = { { i18nc("Frame shadow", "Defined by Layout"), "default" }, { i18nc("Frame shadow", "None"), "Plain" }, { i18nc("Frame shadow", "Raised"), "Raised" }, { i18nc("Frame shadow", "Sunken"), "Sunken" }, }; cmb = createComboBox("PanelLayout", "FrameShadow", "default", frameShadow, 4, tab, true, false, PAGE_LAYOUT); grid->addWidget(cmb, 3, 1); } // ---------------------------------------------------------------------------------- // ---------------------------- VIEW TAB ------------------------------------------- // ---------------------------------------------------------------------------------- void KgPanel::setupPanelTab() { QScrollArea *scrollArea = new QScrollArea(tabWidget); scrollArea->setFrameStyle(QFrame::NoFrame); scrollArea->setWidgetResizable(true); QWidget *tab_panel = viewConfigUI()->createViewCfgTab(scrollArea, this, PAGE_VIEW); scrollArea->setWidget(tab_panel); tabWidget->addTab(scrollArea, i18n("View")); } // ----------------------------------------------------------------------------------- // -------------------------- Panel Toolbar TAB ---------------------------------- // ----------------------------------------------------------------------------------- void KgPanel::setupButtonsTab() { QScrollArea *scrollArea = new QScrollArea(tabWidget); QWidget *tab = new QWidget(scrollArea); scrollArea->setFrameStyle(QFrame::NoFrame); scrollArea->setWidget(tab); scrollArea->setWidgetResizable(true); tabWidget->addTab(scrollArea, i18n("Buttons")); QBoxLayout * tabLayout = new QVBoxLayout(tab); tabLayout->setSpacing(6); tabLayout->setContentsMargins(11, 11, 11, 11); KONFIGURATOR_CHECKBOX_PARAM buttonsParams[] = // cfg_class cfg_name default text restart tooltip { {"ListPanelButtons", "Icons", false, i18n("Toolbar buttons have icons"), true, "" }, {"Look&Feel", "Media Button Visible", true, i18n("Show Media Button"), true , i18n("The media button will be visible.") }, {"Look&Feel", "Back Button Visible", false, i18n("Show Back Button"), true , "Goes back in history." }, {"Look&Feel", "Forward Button Visible", false, i18n("Show Forward Button"), true , "Goes forward in history." }, {"Look&Feel", "History Button Visible", true, i18n("Show History Button"), true , i18n("The history button will be visible.") }, {"Look&Feel", "Bookmarks Button Visible", true, i18n("Show Bookmarks Button"), true , i18n("The bookmarks button will be visible.") }, {"Look&Feel", "Panel Toolbar visible", _PanelToolBar, i18n("Show Panel Toolbar"), true, i18n("The panel toolbar will be visible.") }, }; buttonsCheckboxes = createCheckBoxGroup(1, 0, buttonsParams, 7/*count*/, tab, PAGE_PANELTOOLBAR); connect(buttonsCheckboxes->find("Panel Toolbar visible"), SIGNAL(stateChanged(int)), this, SLOT(slotEnablePanelToolbar())); tabLayout->addWidget(buttonsCheckboxes, 0, 0); QGroupBox * panelToolbarGrp = createFrame(i18n("Visible Panel Toolbar buttons"), tab); QGridLayout * panelToolbarGrid = createGridLayout(panelToolbarGrp); KONFIGURATOR_CHECKBOX_PARAM panelToolbarButtonsParams[] = { // cfg_class cfg_name default text restart tooltip {"Look&Feel", "Open Button Visible", _Open, i18n("Open button"), true , i18n("Opens the directory browser.") }, {"Look&Feel", "Equal Button Visible", _cdOther, i18n("Equal button (=)"), true , i18n("Changes the panel directory to the other panel directory.") }, {"Look&Feel", "Up Button Visible", _cdUp, i18n("Up button (..)"), true , i18n("Changes the panel directory to the parent directory.") }, {"Look&Feel", "Home Button Visible", _cdHome, i18n("Home button (~)"), true , i18n("Changes the panel directory to the home directory.") }, {"Look&Feel", "Root Button Visible", _cdRoot, i18n("Root button (/)"), true , i18n("Changes the panel directory to the root directory.") }, {"Look&Feel", "SyncBrowse Button Visible", _syncBrowseButton, i18n("Toggle-button for sync-browsing"), true , i18n("Each directory change in the panel is also performed in the other panel.") }, }; panelToolbarButtonsCheckboxes = createCheckBoxGroup(1, 0, panelToolbarButtonsParams, sizeof(panelToolbarButtonsParams) / sizeof(*panelToolbarButtonsParams), panelToolbarGrp, PAGE_PANELTOOLBAR); panelToolbarGrid->addWidget(panelToolbarButtonsCheckboxes, 0, 0); tabLayout->addWidget(panelToolbarGrp, 1, 0); // Enable panel toolbar checkboxes slotEnablePanelToolbar(); } // --------------------------------------------------------------------------- // -------------------------- Mouse TAB ---------------------------------- // --------------------------------------------------------------------------- void KgPanel::setupMouseModeTab() { QScrollArea *scrollArea = new QScrollArea(tabWidget); scrollArea->setFrameStyle(QFrame::NoFrame); scrollArea->setWidgetResizable(true); QWidget *tab_mouse = viewConfigUI()->createSelectionModeCfgTab(scrollArea, this, PAGE_MOUSE); scrollArea->setWidget(tab_mouse); tabWidget->addTab(scrollArea, i18n("Selection Mode")); } // --------------------------------------------------------------------------- // -------------------------- Media Menu TAB ---------------------------------- // --------------------------------------------------------------------------- void KgPanel::setupMediaMenuTab() { QScrollArea *scrollArea = new QScrollArea(tabWidget); QWidget *tab = new QWidget(scrollArea); scrollArea->setFrameStyle(QFrame::NoFrame); scrollArea->setWidget(tab); scrollArea->setWidgetResizable(true); tabWidget->addTab(scrollArea, i18n("Media Menu")); QBoxLayout * tabLayout = new QVBoxLayout(tab); tabLayout->setSpacing(6); tabLayout->setContentsMargins(11, 11, 11, 11); KONFIGURATOR_CHECKBOX_PARAM mediaMenuParams[] = { // cfg_class cfg_name default text restart tooltip {"MediaMenu", "ShowPath", true, i18n("Show Mount Path"), false, 0 }, {"MediaMenu", "ShowFSType", true, i18n("Show File System Type"), false, 0 }, }; KonfiguratorCheckBoxGroup *mediaMenuCheckBoxes = createCheckBoxGroup(1, 0, mediaMenuParams, sizeof(mediaMenuParams) / sizeof(*mediaMenuParams), tab, PAGE_MEDIA_MENU); tabLayout->addWidget(mediaMenuCheckBoxes, 0, 0); QHBoxLayout *showSizeHBox = new QHBoxLayout(); showSizeHBox->addWidget(new QLabel(i18n("Show Size:"), tab)); KONFIGURATOR_NAME_VALUE_PAIR showSizeValues[] = { { i18nc("setting 'show size'", "Always"), "Always" }, { i18nc("setting 'show size'", "When Device has no Label"), "WhenNoLabel" }, { i18nc("setting 'show size'", "Never"), "Never" }, }; KonfiguratorComboBox *showSizeCmb = createComboBox("MediaMenu", "ShowSize", "Always", showSizeValues, sizeof(showSizeValues) / sizeof(*showSizeValues), tab, false, false, PAGE_MEDIA_MENU); showSizeHBox->addWidget(showSizeCmb); showSizeHBox->addStretch(); tabLayout->addLayout(showSizeHBox); tabLayout->addStretch(); } void KgPanel::slotDisable() { bool isNewStyleQuickSearch = quicksearchCheckboxes->find("New Style Quicksearch")->isChecked(); quicksearchCheckboxes->find("Case Sensitive Quicksearch")->setEnabled(isNewStyleQuickSearch); } void KgPanel::slotEnablePanelToolbar() { bool enableTB = buttonsCheckboxes->find("Panel Toolbar visible")->isChecked(); panelToolbarButtonsCheckboxes->find("Root Button Visible")->setEnabled(enableTB); panelToolbarButtonsCheckboxes->find("Home Button Visible")->setEnabled(enableTB); panelToolbarButtonsCheckboxes->find("Up Button Visible")->setEnabled(enableTB); panelToolbarButtonsCheckboxes->find("Equal Button Visible")->setEnabled(enableTB); panelToolbarButtonsCheckboxes->find("Open Button Visible")->setEnabled(enableTB); panelToolbarButtonsCheckboxes->find("SyncBrowse Button Visible")->setEnabled(enableTB); } int KgPanel::activeSubPage() { return tabWidget->currentIndex(); }
amatveyakin/skuire
krusader/Konfigurator/kgpanel.cpp
C++
gpl-2.0
21,856
#!/usr/bin/perl package OpenSRS::EmailDefense_errors; use strict; use Exporter; use vars qw( @ISA @EXPORT ); @ISA = qw(Exporter); @EXPORT = ( 'ERROR_M001', 'ERROR_M002', 'ERROR_M003', 'ERROR_M004', 'ERROR_M005', 'ERROR_M006', 'ERROR_M007', 'ERROR_M008', 'ERROR_M110', 'ERROR_M120', 'ERROR_M140', 'ERROR_M150', 'ERROR_M100', 'ERROR_M170', 'ERROR_M200', 'ERROR_M210', ); use constant ERROR_M001 => 'Empty domain name.'; use constant ERROR_M002 => 'Empty username.'; use constant ERROR_M003 => 'Empty password.'; use constant ERROR_M004 => 'User does not own queried domain.'; use constant ERROR_M005 => 'Empty confirm password.'; use constant ERROR_M006 => 'Passwords must be a minimum of 6 characters.'; use constant ERROR_M007 => 'Empty users.'; use constant ERROR_M008 => 'Duplicate users.'; use constant ERROR_M110 => 'Email Defense Service for this domain cannot be purchased or managed through this interface. Please contact your current provider for assistance.'; use constant ERROR_M100 => 'Error retrieving information.'; use constant ERROR_M140 => 'Passwords do not match.'; use constant ERROR_M150 => 'Username is already taken. Please enter another username.'; use constant ERROR_M170 => 'User does not exist.'; use constant ERROR_M200 => 'Username and/or password not found.'; use constant ERROR_M210 => 'The maximum number of Email Defense Users you can enter is '; 1;
milhomem/controller
backend/src/sistema/include/mods/OpenSRS/EmailDefense_errors.pm
Perl
gpl-2.0
1,532
var v = "题库题数:1546(2015.05.09更新)"; alert("脚本加载完成。\n如果您为使用此脚本支付了任何费用,那么恭喜您,您被坑了。\n\n按确定开始执行。"); var allQ = []; $(".examLi").each(function(){ allQ.push($(this).text()); }); var counter = 0; for(var i = 1; i <= 20; i++){ var thisQ = allQ[i].split(" "); var q = thisQ[64].substring(0, thisQ[64].length - 1); //问题 //答案 var a = []; for(var ii = 112; ii <= 172; ii += 20){ a.push(thisQ[ii].substring(1, thisQ[ii].length - 1)); } var rightA = getAns(q); //获取正确答案 if(a.indexOf(rightA) > -1){ $(".examLi").eq(i) //找到正确的题 .find("li").eq(a.indexOf(rightA)) //找到正确的选项 .addClass("currSolution"); //选择选项 }else{ counter += 1; if(rightA !== undefined){ //题库错误处理 alert("题库错误!\n问题:\"" + q + "\"\n返回的答案:\"" + rightA + "\"\n捕获的答案列表:" + a); } } } alert("答题完成,有" + counter +"道题没填写(题库中没有或返回的答案无效)。") //题库函数 function getAns (q){ // 79 = 79 switch(q){ case "以下哪一位数学家不是法国人?": return ".黎曼"; case "当PCl5 = PCl3 +Cl2的化学平衡常数Kc=1.8M时,在0.5L的容器中加入0.15molPCl5,求平衡后Cl2的浓度": return ".0.26M"; case "以下哪种颜色不属于色光三原色?": return ".黄"; case "iphone 4之后苹果推出的手机是": return ".iphone 4S"; case "c++的int类型通常占用几个字节?": return "4(byte)"; case "冥王星的公转周期?": return ".248地球年"; case "世界上用图像显示的第一个电子游戏是什么?": return ".Core War"; case "AIDS的全称是什么?": return ".获得性免疫缺陷综合征"; case "计算机编程中常见的if语句是?": return ".判断语句"; case "风靡一时的游戏主机“红白机”全名为?": return ".Family Computer"; case "当天空出现了鱼鳞云(透光高积云),下列哪种天气现象会发生?": return ".降雨"; case "一直被拿去做实验从未被超越的动物是": return ".小白鼠"; case "以下作品中哪一个完全没有使用3D技术": return ".LOVELIVE TV版"; case "以下哪款耳机采用了特斯拉技术": return ".拜亚T1"; case "美国历史上第一位黑人总统是": return ".Barack Hussein Obama II"; case "以下哪种功率放大器效率最低?": return ".甲类"; case "RGBA中的A是指?": return ".Alpha"; case "“不学礼,无以立”。出于何处?": return ".《论语》"; case "静电场的高斯定理和环路定理说明静电场是个什么场?": return ".有源有旋场"; case "新生物性状产生的根本原因在于?": return ".基因重组"; case "一个农田的全部生物属于?": return ".群落"; case "北回归线没有从下列哪个省中穿过?": return ".福建"; case "什么是“DTS”": return ".数字家庭影院系统"; case "被誉为生命科学“登月”计划的是": return ".人类基因组计划"; case "下列有关电子显微镜的说法正确的是": return ".常用的有透射电镜和扫描电子镜"; case "天文学上,红移是指": return ".天体离我们远去"; case "传说中从天而降砸到牛顿的是": return ".苹果"; case "拿破仑在从厄尔巴岛逃回法国,到兵败滑铁卢再次流放,一共重返帝位多少天?": return ".101"; case "剧毒NaCN(氰化钠)的水解产物HCN是什么味道": return ".苦杏仁味"; case "金鱼的卵什么颜色的才能孵化": return ".淡青色"; default: return undefined; }} //结束switch和题库函数 } //结束运行确认
mobaobaoss/mobaobaoss.github.io
timu1.js
JavaScript
gpl-2.0
3,742
/* * This file is part of the coreboot project. * * Copyright (C) 2008 coresystems GmbH * * 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; version 2 of * the License. * * 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. */ typedef struct { u16 osys; u8 smif; u8 prm0; u8 prm1; u8 scif; u8 prm2; u8 prm3; u8 lckf; u8 prm4; u8 prm5; u32 p80d; u8 lids; u8 pwrs; u8 dbgs; u8 linxs; u8 rsvd; u8 actt; u8 psvt; u8 tc1v; u8 tc2v; u8 tspv; u8 crtt; u8 dtse; u8 dts1; u8 dts2; u8 rsvd2; u8 bnum; u8 b0sc, b1sc, b2sc; u8 b0ss, b1ss, b2ss; u8 rsvd3[3]; u8 apic; u8 mpen; u8 bten; u8 ppcm; u8 pcp0; u8 pcp1; u8 rsvd4[4]; u8 natp; u8 cmap; u8 cmbp; u8 lptp; u8 fdcp; u8 rfdv; u8 hotk; u8 rtcf; u8 util; u8 acin; u8 igds; u8 tlst; u8 cadl; u8 padl; u16 cste; u16 pste; u16 nste; u16 sste; u8 ndid; u32 did1; u32 did2; u32 did3; u32 did4; u32 did5; u8 rsvd5[0xb]; u8 brtl; u8 odds; u8 alse; u8 alaf; u8 llow; u8 lhih; u8 rsvd6; u8 emae; u16 emap; u16 emal; u8 rsvd7; u8 mefe; u8 igps; u8 rsvd8[2]; u8 tpmp; u8 tpme; u8 rsvd9[8]; u8 gtf0[7]; u8 gtf2[7]; u8 idem; u8 idet; u8 dock; } global_nvs_t;
rockchip-linux/coreboot
src/northbridge/intel/sch/nvs.h
C
gpl-2.0
1,496
#! /usr/bin/make # WARNING: # only add extensions here that are either present in the kernel, or whose # header files are present in the include/linux directory of this iptables # package (HW) # #BRCM begin #PF_EXT_SLIB:=ah connlimit connmark conntrack dscp ecn esp helper icmp iprange length limit mac mark multiport owner physdev pkttype realm rpc sctp standard state tcp tcpmss tos ttl udp unclean CLASSIFY CONNMARK DNAT DSCP ECN LOG MARK MASQUERADE MIRROR NETMAP NOTRACK REDIRECT REJECT SAME SNAT TARPIT TCPMSS TOS TRACE TTL ULOG PF_EXT_SLIB:=TCPMSS ifneq ($(strip $(BRCM_KERNEL_NF_FIREWALL)),) PF_EXT_SLIB+=icmp limit standard state tcp udp LOG endif ifneq ($(strip $(BRCM_KERNEL_NF_NAT)),) PF_EXT_SLIB+=DNAT MASQUERADE REDIRECT SNAT endif ifneq ($(strip $(BRCM_KERNEL_NF_MANGLE)),) PF_EXT_SLIB+=mark MARK FTOS endif #PF6_EXT_SLIB:=eui64 hl icmpv6 length limit mac mark multiport owner standard tcp udp HL LOG MARK TRACE # Optionals #PF_EXT_SLIB_OPTS:=$(foreach T,$(wildcard extensions/.*-test),$(shell KERNEL_DIR=$(KERNEL_DIR) $(T))) #PF6_EXT_SLIB_OPTS:=$(foreach T,$(wildcard extensions/.*-test6),$(shell KERNEL_DIR=$(KERNEL_DIR) $(T))) # BRCM end PF_EXT_ALL_SLIB:=$(patsubst extensions/libipt_%.c, %, $(wildcard extensions/libipt_*.c)) PF6_EXT_ALL_SLIB:=$(patsubst extensions/libip6t_%.c, %, $(wildcard extensions/libip6t_*.c)) PF_EXT_MAN_ALL_MATCHES:=$(foreach T,$(PF_EXT_ALL_SLIB),$(shell test -f extensions/libipt_$(T).man && grep -q register_match extensions/libipt_$(T).c && echo $(T))) PF_EXT_MAN_ALL_TARGETS:=$(foreach T,$(PF_EXT_ALL_SLIB),$(shell test -f extensions/libipt_$(T).man && grep -q register_target extensions/libipt_$(T).c && echo $(T))) PF6_EXT_MAN_ALL_MATCHES:=$(foreach T,$(PF6_EXT_ALL_SLIB),$(shell test -f extensions/libip6t_$(T).man && grep -q register_match6 extensions/libip6t_$(T).c && echo $(T))) PF6_EXT_MAN_ALL_TARGETS:=$(foreach T,$(PF6_EXT_ALL_SLIB),$(shell test -f extensions/libip6t_$(T).man && grep -q register_target6 extensions/libip6t_$(T).c && echo $(T))) PF_EXT_MAN_MATCHES:=$(filter $(PF_EXT_ALL_SLIB), $(PF_EXT_MAN_ALL_MATCHES)) PF_EXT_MAN_TARGETS:=$(filter $(PF_EXT_ALL_SLIB), $(PF_EXT_MAN_ALL_TARGETS)) PF_EXT_MAN_EXTRA_MATCHES:=$(filter-out $(PF_EXT_MAN_MATCHES), $(PF_EXT_MAN_ALL_MATCHES)) PF_EXT_MAN_EXTRA_TARGETS:=$(filter-out $(PF_EXT_MAN_TARGETS), $(PF_EXT_MAN_ALL_TARGETS)) PF6_EXT_MAN_MATCHES:=$(filter $(PF6_EXT_ALL_SLIB), $(PF6_EXT_MAN_ALL_MATCHES)) PF6_EXT_MAN_TARGETS:=$(filter $(PF6_EXT_ALL_SLIB), $(PF6_EXT_MAN_ALL_TARGETS)) PF6_EXT_MAN_EXTRA_MATCHES:=$(filter-out $(PF6_EXT_MAN_MATCHES), $(PF6_EXT_MAN_ALL_MATCHES)) PF6_EXT_MAN_EXTRA_TARGETS:=$(filter-out $(PF6_EXT_MAN_TARGETS), $(PF6_EXT_MAN_ALL_TARGETS)) allman: @echo ALL_SLIB: $(PF_EXT_ALL_SLIB) @echo ALL_MATCH: $(PF_EXT_MAN_ALL_MATCHES) @echo ALL_TARGET: $(PF_EXT_MAN_ALL_TARGETS) PF_EXT_SLIB+=$(PF_EXT_SLIB_OPTS) PF6_EXT_SLIB+=$(PF6_EXT_SLIB_OPTS) OPTIONALS+=$(patsubst %,IPv4:%,$(PF_EXT_SLIB_OPTS)) OPTIONALS+=$(patsubst %,IPv6:%,$(PF6_EXT_SLIB_OPTS)) ifndef NO_SHARED_LIBS SHARED_LIBS+=$(foreach T,$(PF_EXT_SLIB),extensions/libipt_$(T).so) EXTRA_INSTALLS+=$(foreach T, $(PF_EXT_SLIB), $(DESTDIR)$(LIBDIR)/iptables/libipt_$(T).so) ifeq ($(DO_IPV6), 1) SHARED_LIBS+=$(foreach T,$(PF6_EXT_SLIB),extensions/libip6t_$(T).so) EXTRA_INSTALLS+=$(foreach T, $(PF6_EXT_SLIB), $(DESTDIR)$(LIBDIR)/iptables/libip6t_$(T).so) endif else # NO_SHARED_LIBS EXT_OBJS+=$(foreach T,$(PF_EXT_SLIB),extensions/libipt_$(T).o) EXT_FUNC+=$(foreach T,$(PF_EXT_SLIB),ipt_$(T)) EXT_OBJS+= extensions/initext.o ifeq ($(DO_IPV6), 1) EXT6_OBJS+=$(foreach T,$(PF6_EXT_SLIB),extensions/libip6t_$(T).o) EXT6_FUNC+=$(foreach T,$(PF6_EXT_SLIB),ip6t_$(T)) EXT6_OBJS+= extensions/initext6.o endif # DO_IPV6 endif # NO_SHARED_LIBS ifndef TOPLEVEL_INCLUDED local: cd .. && $(MAKE) $(SHARED_LIBS) endif ifdef NO_SHARED_LIBS # BRCM begin extensions/libext.a: $(EXT_OBJS) # rm -f $@; ar crv $@ $(EXT_OBJS) rm -f $@; $(AR) crv $@ $(EXT_OBJS) extensions/libext6.a: $(EXT6_OBJS) # rm -f $@; ar crv $@ $(EXT6_OBJS) rm -f $@; $(AR) crv $@ $(EXT6_OBJS) # BRCM end extensions/initext.o: extensions/initext.c extensions/initext6.o: extensions/initext6.c extensions/initext.c: extensions/Makefile echo "" > $@ for i in $(EXT_FUNC); do \ echo "extern void $${i}_init(void);" >> $@; \ done echo "void init_extensions(void) {" >> $@ for i in $(EXT_FUNC); do \ echo " $${i}_init();" >> $@; \ done echo "}" >> $@ extensions/initext6.c: extensions/Makefile echo "" > $@ for i in $(EXT6_FUNC); do \ echo "extern void $${i}_init(void);" >> $@; \ done echo "void init_extensions(void) {" >> $@ for i in $(EXT6_FUNC); do \ echo " $${i}_init();" >> $@; \ done echo "}" >> $@ extensions/lib%.o: extensions/lib%.c $(CC) $(CFLAGS) -D_INIT=$*_init -c -o $@ $< endif EXTRAS += extensions/libipt_targets.man extensions/libipt_targets.man: $(patsubst %,extensions/libipt_%.man,$(PF_EXT_MAN_ALL_TARGETS)) @for ext in $(PF_EXT_MAN_TARGETS); do \ echo ".SS $$ext" ;\ cat extensions/libipt_$$ext.man ;\ done >extensions/libipt_targets.man @if [ -n "$(PF_EXT_MAN_EXTRA_TARGETS)" ]; then \ extra=$(PF_EXT_MAN_EXTRA_TARGETS) ;\ for ext in $${extra:-""}; do \ echo ".SS $$ext (not supported, see Patch-O-Matic)" ;\ cat extensions/libipt_$$ext.man ;\ done ;\ fi >>extensions/libipt_targets.man EXTRAS += extensions/libipt_matches.man extensions/libipt_matches.man: $(patsubst %,extensions/libipt_%.man,$(PF_EXT_MAN_ALL_MATCHES)) @for ext in $(PF_EXT_MAN_MATCHES); do \ echo ".SS $$ext" ;\ cat extensions/libipt_$$ext.man ;\ done >extensions/libipt_matches.man @if [ -n "$(PF_EXT_MAN_EXTRA_MATCHES)" ]; then \ extra=$(PF_EXT_MAN_EXTRA_MATCHES) ;\ for ext in $${extra:-""}; do \ echo ".SS $$ext (not supported, see Patch-O-Matic)" ;\ cat extensions/libipt_$$ext.man ;\ done ;\ fi >>extensions/libipt_matches.man EXTRAS += extensions/libip6t_targets.man extensions/libip6t_targets.man: $(patsubst %, extensions/libip6t_%.man, $(PF6_EXT_MAN_ALL_TARGETS)) @for ext in $(PF6_EXT_MAN_TARGETS); do \ echo ".SS $$ext" ;\ cat extensions/libip6t_$$ext.man ;\ done >extensions/libip6t_targets.man @if [ -n "$(PF6_EXT_MAN_EXTRA_TARGETS)" ]; then \ extra=$(PF6_EXT_MAN_EXTRA_TARGETS) ;\ for ext in $${extra:-""}; do \ echo ".SS $$ext (not supported, see Patch-O-Matic)" ;\ cat extensions/libip6t_$$ext.man ;\ done ;\ fi >>extensions/libip6t_targets.man EXTRAS += extensions/libip6t_matches.man extensions/libip6t_matches.man: $(patsubst %, extensions/libip6t_%.man, $(PF6_EXT_MAN_ALL_MATCHES)) @for ext in $(PF6_EXT_MAN_MATCHES); do \ echo ".SS $$ext" ;\ cat extensions/libip6t_$$ext.man ;\ done >extensions/libip6t_matches.man @if [ -n "$(PF6_EXT_MAN_EXTRA_MATCHES)" ]; then \ extra=$(PF6_EXT_MAN_EXTRA_MATCHES) ;\ for ext in $${extra:-""}; do \ echo ".SS $$ext (not supported, see Patch-O-Matic)" ;\ cat extensions/libip6t_$$ext.man ;\ done ;\ fi >>extensions/libip6t_matches.man $(DESTDIR)$(LIBDIR)/iptables/libipt_%.so: extensions/libipt_%.so @[ -d $(DESTDIR)$(LIBDIR)/iptables ] || mkdir -p $(DESTDIR)$(LIBDIR)/iptables cp $< $@ $(DESTDIR)$(LIBDIR)/iptables/libip6t_%.so: extensions/libip6t_%.so @[ -d $(DESTDIR)$(LIBDIR)/iptables ] || mkdir -p $(DESTDIR)$(LIBDIR)/iptables cp $< $@
z3bu/AH4222
userapps/opensource/iptables/extensions/Makefile
Makefile
gpl-2.0
7,350
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" lang="en-US" xml:lang="en-US"> <head> <title>HVDR Wild-type 2x2</title> <link rel="stylesheet" type="text/css" href="/res/hvdr.css"/> <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1"/> <style type="text/css"> .hidden { visibility: hidden; } .unhidden { visibility: visible; } td { text-align : left; } td.shade1 { background: lightblue; } td.shade2 { background: #ffff99; } td.shade3 { background: pink; } fieldset { width: 50%; } input.aminoacid1 { text-align:center; background:lightblue; color:darkslategrey; font-weight:bold; } input.aminoacid2 { text-align:center; background:#ffff99; color:darkslategrey; font-weight:bold; } input.nucleotide { text-align:center; } div.instructions { font-family:monospace; } a:focus { outline: 0; } em.i { font-style:oblique; font-weight:normal; text-decoration:none; } em.b{ font-style:normal; font-weight:bold; text-decoration:none; } legend { font-weight:bold; padding:0.2em 0.5em; border:1px solid green; color:green; font-size:120%; font-family:monospace; background:lightgreen; } <!-- http://www.pixy.cz/blogg/clanky/css-fieldsetandlabels.html --> </style> <noscript> <div class="dotted_red" style="border-width:1.5px; color:darkred; font-size:12px; font-family:monospace;" align="center"> This site works better with JavaScript enabled. It is strongly recommended that you enable JavaScript and <a href="">reload</a> the page. </div> </noscript> </head> <body onload="updateTable();"> <h1>HVDR Online Tools</h1> <div class="note">Hepatitis Virus Diversity Research <a href="http://www.wits.ac.za/health/hvdrp">Programme</a>, University of the Witwatersrand</div> <h2><img src="/res/wt2x2.png" style="vertical-align:middle"> Wild-type 2x2</h2> <form method="post" action="/cgi-bin/wt2x2.cgi" enctype="multipart/form-data" onSubmit="return checkForm();" name="theform"> <br> <fieldset> <legend>Specify input FASTA file and threshold</legend> <table> <tr> <td>Input file</td> <td><input type="file" name="infile"></td> </tr> </table> <br> <div class="instructions">The input file should contain (aligned) nucleotide or amino acid sequence data in FASTA format.</div> </fieldset> <br> <fieldset> <legend>Specify parameters</legend> <table> <tr><td>Threshold</td><td><input type="text" size="4" maxlength="4" value="0.05" id="thresh" name="thresh"></td><td></td></tr> <tr><td>Offset</td><td><input type="text" size="6" maxlength="6" value="0" id="offset" name="offset" title="Starting position"></td><td></td></tr> <tr><td>Group 1</td><td><input type="text" size="16" maxlength="16" value="Name 1" id="name1" name="name1"></td><td><input type="text" size="48" maxlength="255" value="" id="g1" name="g1"></td></tr> <tr><td>Group 2</td><td><input type="text" size="16" maxlength="16" value="Name 2" id="name2" name="name2"></td><td><input type="text" size="48" maxlength="255" value="" id="g2" name="g2"></td></tr> </table> <br> <div class="instructions">A group may be omitted if it contains all elements not in the specified group.</div> </fieldset> <br> <input type="submit" value="Submit!"> </form> </html>
DrTrevorBell/SmallGenomeTools
wt2x2/index.html
HTML
gpl-2.0
3,250
package net.kolls.railworld.play; /* * Copyright (C) 2010 Steve Kollmansberger * * 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., * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. */ import java.awt.GridLayout; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.util.ArrayList; import java.util.HashMap; import java.util.Iterator; import java.util.Map; import java.util.Random; import java.util.Vector; import javax.swing.Box; import javax.swing.BoxLayout; import javax.swing.Icon; import javax.swing.ImageIcon; import javax.swing.JButton; import javax.swing.JComboBox; import javax.swing.JFrame; import javax.swing.JLabel; import javax.swing.JPanel; import javax.swing.JTabbedPane; import javax.swing.WindowConstants; import net.kolls.railworld.Car; import net.kolls.railworld.Factories; import net.kolls.railworld.Images; import net.kolls.railworld.RailSegment; import net.kolls.railworld.Train; import net.kolls.railworld.car.Caboose; import net.kolls.railworld.car.Engine; import net.kolls.railworld.play.script.ScriptManager; import net.kolls.railworld.segment.EESegment; import net.kolls.railworld.segment.LUSegment; import net.kolls.railworld.tuic.TrainPainter; /** * Provides a window allowing the user to create a train to enter the map. * * @author Steve Kollmansberger * */ public class TrainCreator extends JFrame { private JPanel loaded, unloaded, nonload; private MultiLineTrainPanel ctrain; private Vector<EESegment> ees; private PlayFrame pf; private JComboBox enters, speeds; private final int incr = Train.MAX_SPEED_MPH / Train.MAX_THROTTLE; private Map<String,Car> sc; /** * Generate a series of engines, cargo cars, and possibly a caboose * based on possible cargo cars. * * @param r Random number source * @param engine The template car for the engine, e.g. to allow derived engine types * @param sources Array of allowable cargo cars * @return Train cars */ public static Car[] generate(Random r, Car engine, Car[] sources) { int leng = r.nextInt(20)+2; int occurs; int i, j; ArrayList<Car> results = new ArrayList<Car>(); int l2 = leng; while (l2 > 1 && results.size() < 3) { results.add( (Car)engine.newInstance()); l2 /= r.nextInt(5)+1; } if (sources.length == 0) return results.toArray(new Car[0]); while (results.size() < leng) { occurs = r.nextInt(4)+1; i = r.nextInt(sources.length); for (j = 0; j < occurs; j++) { try { Car c2 = (Car)sources[i].newInstance(); if (sources[i].loaded()) c2.load(); else c2.unload(); results.add(c2); } catch (Exception ex) { ex.printStackTrace(); } } } if ((double)leng / 20 > r.nextDouble()) results.add(new Caboose()); return results.toArray(new Car[0]); } private void generate() { Random r = new Random(); Car[] cars = sc.values().toArray(new Car[0]); Car[] resultCars = generate(r, new Engine(), cars); for (Car c : resultCars) ctrain.myVC.add(c); } private JButton carButton(final Car c) { String d = c.show(); Icon i = new ImageIcon(TrainPainter.image(c, this)); JButton j = new JButton(d,i); j.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { // because of the way the cars are added to the train // we have to have separate instances for each car // because a referencer is just copied // so it's actually many of the same car otherwise // this does create a problem for selected cars try { Car c2 = (Car)c.newInstance(); if (c.loaded()) c2.load(); else c2.unload(); ctrain.myVC.add(c2); } catch (Exception ex) { ex.printStackTrace(); } ctrain.revalidate(); ctrain.repaint(); } }); return j; } private void addLUButton(Car c) { c.load(); loaded.add(carButton(c)); // in order to have a loaded and unloaded car // separately, we need to have two instances try { Car c2 = (Car)c.newInstance(); c2.unload(); unloaded.add(carButton(c2)); } catch (Exception e) { e.printStackTrace(); } } private void addWidgets() { getContentPane().setLayout(new BoxLayout(getContentPane(), BoxLayout.Y_AXIS)); JTabbedPane tabbedPane = new JTabbedPane(); nonload = new JPanel(); loaded = new JPanel(); unloaded = new JPanel(); nonload.setLayout(new GridLayout(0,2)); loaded.setLayout(new GridLayout(0,2)); unloaded.setLayout(new GridLayout(0,2)); ArrayList<Car> at = Factories.cars.allTypes(); for (int i = 0; i < at.size(); i++) { Car c = at.get(i); if (c.canUserCreate() == false) continue; if (c.isLoadable()) { addLUButton(c); } else { nonload.add(carButton(c)); } } tabbedPane.add("Special", nonload); tabbedPane.add("Loaded", loaded); tabbedPane.add("Unloaded", unloaded); getContentPane().add(tabbedPane); ctrain = new MultiLineTrainPanel(); getContentPane().add(ctrain); // create the combo boxes // for selecting entrance and speed JPanel hp = new JPanel(); hp.setLayout(new BoxLayout(hp, BoxLayout.X_AXIS)); hp.add(new JLabel("Entering At")); hp.add(Box.createHorizontalGlue()); enters = new JComboBox(); Iterator<EESegment> ei = ees.iterator(); while (ei.hasNext()) { EESegment ee = ei.next(); enters.addItem(ee.label); } hp.add(enters); getContentPane().add(hp); hp = new JPanel(); hp.setLayout(new BoxLayout(hp, BoxLayout.X_AXIS)); hp.add(new JLabel("Speed")); hp.add(Box.createHorizontalGlue()); speeds = new JComboBox(); int i; for (i = 1; i <= Train.MAX_THROTTLE; i++) { speeds.addItem(Integer.toString(i*incr) + " MPH"); } speeds.setSelectedIndex(i-2); // due to starting at 1 hp.add(speeds); getContentPane().add(hp); hp = new JPanel(); hp.setLayout(new BoxLayout(hp, BoxLayout.X_AXIS)); JButton b; b = new JButton("OK"); b.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { if (ctrain.myVC.isEmpty()) { // cancel, no cars dispose(); return; } Car[] cr = (ctrain.myVC.toArray(new Car[0])); Train t = new Train(cr); if (t.hasEngine()) t.setThrottle(speeds.getSelectedIndex()+1); t.setVel(incr*(speeds.getSelectedIndex()+1)); // avoid acceleration wait // also if there are no engines, the train // would ever be stuck on the border EESegment ee = ees.get(enters.getSelectedIndex()); t.pos.r = ee; t.pos.orig = ee.HES; t.followMeOnce = true; t.getController().setTrainActionScriptNotify(sm); pf.addTrain(t, true); dispose(); // close window when done } }); hp.add(Box.createHorizontalGlue()); hp.add(b); hp.add(Box.createHorizontalGlue()); b = new JButton("Clear"); b.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { ctrain.myVC.clear(); ctrain.revalidate(); getContentPane().repaint(); } }); hp.add(b); hp.add(Box.createHorizontalGlue()); b = new JButton("Generate"); b.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { ctrain.myVC.clear(); generate(); ctrain.revalidate(); getContentPane().repaint(); } }); hp.add(b); hp.add(Box.createHorizontalGlue()); b = new JButton("Cancel"); b.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { dispose(); } }); hp.add(b); hp.add(Box.createHorizontalGlue()); getContentPane().add(hp); setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE); pack(); } private ScriptManager sm; /** * Shows the train creator window. * The rail segments are needed for the generator to know what load/unload cars are supported. * When created, the train will be added to the given trains collection automatically. * * @param lines An array of {@link RailSegment}s used for the train generator. * @param pf PlayFrame by which the {@link PlayFrame#addTrain(Train, boolean)} method will be called. * @param trainNotify The script manager to attach to the traincontroller for notification. */ public TrainCreator(RailSegment[] lines, PlayFrame pf, ScriptManager trainNotify) { super("New Train"); setIconImage(Images.frameIcon); // need to find all EE segments // and lu segments for generator ees = new Vector<EESegment>(); sc = new HashMap<String,Car>(); for (int i = 0; i < lines.length; i++) { if (lines[i] instanceof EESegment) ees.add((EESegment)lines[i]); if (lines[i] instanceof LUSegment) { Car[] cl = ((LUSegment)lines[i]).lu(); for (int j = 0; j < cl.length; j++) sc.put(cl[j].show() + (cl[j].loaded() ? "/L" : "/U"), cl[j]); } } this.pf = pf; sm = trainNotify; addWidgets(); } }
Neschur/railworld
src/net/kolls/railworld/play/TrainCreator.java
Java
gpl-2.0
9,483
<?php /** * @version CVS: 1.0.0 * @package Com_Propertycontact * @author azharuddin <azharuddin.shaikh53@gmail.com> * @copyright 2017 azharuddin * @license GNU General Public License version 2 or later; see LICENSE.txt */ defined('_JEXEC') or die; // Include dependancies jimport('joomla.application.component.controller'); JLoader::registerPrefix('Propertycontact', JPATH_COMPONENT); JLoader::register('PropertycontactController', JPATH_COMPONENT . '/controller.php'); // Execute the task. $controller = JControllerLegacy::getInstance('Propertycontact'); $controller->execute(JFactory::getApplication()->input->get('task')); $controller->redirect();
azharu53/kuwithome
components/com_propertycontact/propertycontact.php
PHP
gpl-2.0
676
/* -*- Mode: java; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 4 -*- * * The contents of this file are subject to the Netscape Public License * Version 1.0 (the "NPL"); you may not use this file except in * compliance with the NPL. You may obtain a copy of the NPL at * http://www.mozilla.org/NPL/ * * Software distributed under the NPL is distributed on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the NPL * for the specific language governing rights and limitations under the * NPL. * * The Initial Developer of this code under the NPL is Netscape * Communications Corporation. Portions created by Netscape are * Copyright (C) 1997-1999 Netscape Communications Corporation. All Rights * Reserved. * * This file was originally distributed with Rhino. I have copied it * into SmallJava to avoid enforcing a dependency on Rhino being * installed (and to avoid conflicting with installed versions of * Rhino) -- all hail Java's extraordinarily bad package system! */ package com.svincent.smalljava.rhino; public class Label { private static final int FIXUPTABLE_SIZE = 8; private static final boolean DEBUG = true; public Label() { itsPC = -1; } public short getPC() { return itsPC; } public void fixGotos(byte theCodeBuffer[]) { if (DEBUG) { if ((itsPC == -1) && (itsFixupTable != null)) throw new RuntimeException("Unlocated label"); } if (itsFixupTable != null) { for (int i = 0; i < itsFixupTableTop; i++) { int fixupSite = itsFixupTable[i]; // -1 to get delta from instruction start short offset = (short)(itsPC - (fixupSite - 1)); theCodeBuffer[fixupSite++] = (byte)(offset >> 8); theCodeBuffer[fixupSite] = (byte)offset; } } itsFixupTable = null; } public void setPC(short thePC) { if (DEBUG) { if ((itsPC != -1) && (itsPC != thePC)) throw new RuntimeException("Duplicate label"); } itsPC = thePC; } public void addFixup(int fixupSite) { if (itsFixupTable == null) { itsFixupTableTop = 1; itsFixupTable = new int[FIXUPTABLE_SIZE]; itsFixupTable[0] = fixupSite; } else { if (itsFixupTableTop == itsFixupTable.length) { int oldLength = itsFixupTable.length; int newTable[] = new int[oldLength + FIXUPTABLE_SIZE]; System.arraycopy(itsFixupTable, 0, newTable, 0, oldLength); itsFixupTable = newTable; } itsFixupTable[itsFixupTableTop++] = fixupSite; } } private short itsPC; private int itsFixupTable[]; private int itsFixupTableTop; }
shawn-vincent/moksa
src/com/svincent/smalljava/rhino/Label.java
Java
gpl-2.0
3,032
/* * common functions for Indeo Video Interactive codecs (Indeo4 and Indeo5) * * Copyright (c) 2009 Maxim Poliakovski * * This file is part of FFmpeg. * * FFmpeg is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * FFmpeg 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 * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with FFmpeg; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ /** * @file libavcodec/ivi_common.c * This file contains functions and data shared by both Indeo4 and * Indeo5 decoders. */ #define ALT_BITSTREAM_READER_LE #include "avcodec.h" #include "get_bits.h" #include "ivi_common.h" #include "libavutil/common.h" #include "ivi_dsp.h" extern const IVIHuffDesc ff_ivi_mb_huff_desc[8]; ///< static macroblock huffman tables extern const IVIHuffDesc ff_ivi_blk_huff_desc[8]; ///< static block huffman tables VLC ff_ivi_mb_vlc_tabs [8]; VLC ff_ivi_blk_vlc_tabs[8]; /** * Reverses "nbits" bits of the value "val" and returns the result * in the least significant bits. */ static uint16_t inv_bits(uint16_t val, int nbits) { uint16_t res; if (nbits <= 8) { res = av_reverse[val] >> (8-nbits); } else res = ((av_reverse[val & 0xFF] << 8) + (av_reverse[val >> 8])) >> (16-nbits); return res; } int ff_ivi_create_huff_from_desc(const IVIHuffDesc *cb, VLC *vlc, int flag) { int pos, i, j, codes_per_row, prefix, not_last_row; uint16_t codewords[256]; /* FIXME: move this temporal storage out? */ uint8_t bits[256]; pos = 0; /* current position = 0 */ for (i = 0; i < cb->num_rows; i++) { codes_per_row = 1 << cb->xbits[i]; not_last_row = (i != cb->num_rows - 1); prefix = ((1 << i) - 1) << (cb->xbits[i] + not_last_row); for (j = 0; j < codes_per_row; j++) { if (pos >= 256) /* Some Indeo5 codebooks can have more than 256 */ break; /* elements, but only 256 codes are allowed! */ bits[pos] = i + cb->xbits[i] + not_last_row; if (bits[pos] > IVI_VLC_BITS) return -1; /* invalid descriptor */ codewords[pos] = inv_bits((prefix | j), bits[pos]); if (!bits[pos]) bits[pos] = 1; pos++; }//for j }//for i /* number of codewords = pos */ return init_vlc(vlc, IVI_VLC_BITS, pos, bits, 1, 1, codewords, 2, 2, (flag ? INIT_VLC_USE_NEW_STATIC : 0) | INIT_VLC_LE); } void ff_ivi_init_static_vlc(void) { int i; static VLC_TYPE table_data[8192 * 16][2]; static int initialized_vlcs = 0; if (initialized_vlcs) return; for (i = 0; i < 8; i++) { ff_ivi_mb_vlc_tabs[i].table = table_data + i * 2 * 8192; ff_ivi_mb_vlc_tabs[i].table_allocated = 8192; ff_ivi_create_huff_from_desc(&ff_ivi_mb_huff_desc[i], &ff_ivi_mb_vlc_tabs[i], 1); ff_ivi_blk_vlc_tabs[i].table = table_data + (i * 2 + 1) * 8192; ff_ivi_blk_vlc_tabs[i].table_allocated = 8192; ff_ivi_create_huff_from_desc(&ff_ivi_blk_huff_desc[i], &ff_ivi_blk_vlc_tabs[i], 1); } initialized_vlcs = 1; } int ff_ivi_dec_huff_desc(GetBitContext *gb, int desc_coded, int which_tab, IVIHuffTab *huff_tab, AVCodecContext *avctx) { int i, result; IVIHuffDesc new_huff; if (!desc_coded) { /* select default table */ huff_tab->tab = (which_tab) ? &ff_ivi_blk_vlc_tabs[7] : &ff_ivi_mb_vlc_tabs [7]; } else { huff_tab->tab_sel = get_bits(gb, 3); if (huff_tab->tab_sel == 7) { /* custom huffman table (explicitly encoded) */ new_huff.num_rows = get_bits(gb, 4); for (i = 0; i < new_huff.num_rows; i++) new_huff.xbits[i] = get_bits(gb, 4); /* Have we got the same custom table? Rebuild if not. */ if (ff_ivi_huff_desc_cmp(&new_huff, &huff_tab->cust_desc)) { ff_ivi_huff_desc_copy(&huff_tab->cust_desc, &new_huff); if (huff_tab->cust_tab.table) free_vlc(&huff_tab->cust_tab); result = ff_ivi_create_huff_from_desc(&huff_tab->cust_desc, &huff_tab->cust_tab, 0); if (result) { av_log(avctx, AV_LOG_ERROR, "Error while initializing custom vlc table!\n"); return -1; } } huff_tab->tab = &huff_tab->cust_tab; } else { /* select one of predefined tables */ huff_tab->tab = (which_tab) ? &ff_ivi_blk_vlc_tabs[huff_tab->tab_sel] : &ff_ivi_mb_vlc_tabs [huff_tab->tab_sel]; } } return 0; } int ff_ivi_huff_desc_cmp(const IVIHuffDesc *desc1, const IVIHuffDesc *desc2) { return desc1->num_rows != desc2->num_rows || memcmp(desc1->xbits, desc2->xbits, desc1->num_rows); } void ff_ivi_huff_desc_copy(IVIHuffDesc *dst, const IVIHuffDesc *src) { dst->num_rows = src->num_rows; memcpy(dst->xbits, src->xbits, src->num_rows); } int av_cold ff_ivi_init_planes(IVIPlaneDesc *planes, const IVIPicConfig *cfg) { int p, b; uint32_t b_width, b_height, align_fac, width_aligned, height_aligned, buf_size; IVIBandDesc *band; ff_ivi_free_buffers(planes); /* fill in the descriptor of the luminance plane */ planes[0].width = cfg->pic_width; planes[0].height = cfg->pic_height; planes[0].num_bands = cfg->luma_bands; /* fill in the descriptors of the chrominance planes */ planes[1].width = planes[2].width = (cfg->pic_width + 3) >> 2; planes[1].height = planes[2].height = (cfg->pic_height + 3) >> 2; planes[1].num_bands = planes[2].num_bands = cfg->chroma_bands; for (p = 0; p < 3; p++) { planes[p].bands = av_mallocz(planes[p].num_bands * sizeof(IVIBandDesc)); if (!planes[p].bands) return AVERROR(ENOMEM); /* select band dimensions: if there is only one band then it * has the full size, if there are several bands each of them * has only half size */ b_width = planes[p].num_bands == 1 ? planes[p].width : (planes[p].width + 1) >> 1; b_height = planes[p].num_bands == 1 ? planes[p].height : (planes[p].height + 1) >> 1; /* luma band buffers will be aligned on 16x16 (max macroblock size) */ /* chroma band buffers will be aligned on 8x8 (max macroblock size) */ align_fac = p ? 8 : 16; width_aligned = FFALIGN(b_width , align_fac); height_aligned = FFALIGN(b_height, align_fac); buf_size = width_aligned * height_aligned * sizeof(int16_t); for (b = 0; b < planes[p].num_bands; b++) { band = &planes[p].bands[b]; /* select appropriate plane/band */ band->plane = p; band->band_num = b; band->width = b_width; band->height = b_height; band->pitch = width_aligned; band->bufs[0] = av_malloc(buf_size); band->bufs[1] = av_malloc(buf_size); if (!band->bufs[0] || !band->bufs[1]) return AVERROR(ENOMEM); /* allocate the 3rd band buffer for scalability mode */ if (cfg->luma_bands > 1) { band->bufs[2] = av_malloc(buf_size); if (!band->bufs[2]) return AVERROR(ENOMEM); } planes[p].bands[0].blk_vlc.cust_desc.num_rows = 0; /* reset custom vlc */ } } return 0; } void av_cold ff_ivi_free_buffers(IVIPlaneDesc *planes) { int p, b, t; for (p = 0; p < 3; p++) { for (b = 0; b < planes[p].num_bands; b++) { av_freep(&planes[p].bands[b].bufs[0]); av_freep(&planes[p].bands[b].bufs[1]); av_freep(&planes[p].bands[b].bufs[2]); if (planes[p].bands[b].blk_vlc.cust_tab.table) free_vlc(&planes[p].bands[b].blk_vlc.cust_tab); for (t = 0; t < planes[p].bands[b].num_tiles; t++) av_freep(&planes[p].bands[b].tiles[t].mbs); av_freep(&planes[p].bands[b].tiles); } av_freep(&planes[p].bands); } } int av_cold ff_ivi_init_tiles(IVIPlaneDesc *planes, int tile_width, int tile_height) { int p, b, x, y, x_tiles, y_tiles, t_width, t_height; IVIBandDesc *band; IVITile *tile, *ref_tile; for (p = 0; p < 3; p++) { t_width = !p ? tile_width : (tile_width + 3) >> 2; t_height = !p ? tile_height : (tile_height + 3) >> 2; if (!p && planes[0].num_bands == 4) { t_width >>= 1; t_height >>= 1; } for (b = 0; b < planes[p].num_bands; b++) { band = &planes[p].bands[b]; x_tiles = IVI_NUM_TILES(band->width, t_width); y_tiles = IVI_NUM_TILES(band->height, t_height); band->num_tiles = x_tiles * y_tiles; av_freep(&band->tiles); band->tiles = av_mallocz(band->num_tiles * sizeof(IVITile)); if (!band->tiles) return AVERROR(ENOMEM); tile = band->tiles; /* use the first luma band as reference for motion vectors * and quant */ ref_tile = planes[0].bands[0].tiles; for (y = 0; y < band->height; y += t_height) { for (x = 0; x < band->width; x += t_width) { tile->xpos = x; tile->ypos = y; tile->width = FFMIN(band->width - x, t_width); tile->height = FFMIN(band->height - y, t_height); tile->is_empty = tile->data_size = 0; /* calculate number of macroblocks */ tile->num_MBs = IVI_MBs_PER_TILE(tile->width, tile->height, band->mb_size); av_freep(&tile->mbs); tile->mbs = av_malloc(tile->num_MBs * sizeof(IVIMbInfo)); if (!tile->mbs) return AVERROR(ENOMEM); tile->ref_mbs = 0; if (p || b) { tile->ref_mbs = ref_tile->mbs; ref_tile++; } tile++; } } }// for b }// for p return 0; } int ff_ivi_dec_tile_data_size(GetBitContext *gb) { int len; len = 0; if (get_bits1(gb)) { len = get_bits(gb, 8); if (len == 255) len = get_bits_long(gb, 24); } /* align the bitstream reader on the byte boundary */ align_get_bits(gb); return len; } int ff_ivi_decode_blocks(GetBitContext *gb, IVIBandDesc *band, IVITile *tile) { int mbn, blk, num_blocks, num_coeffs, blk_size, scan_pos, run, val, pos, is_intra, mc_type, mv_x, mv_y, col_mask; uint8_t col_flags[8]; int32_t prev_dc, trvec[64]; uint32_t cbp, sym, lo, hi, quant, buf_offs, q; IVIMbInfo *mb; RVMapDesc *rvmap = band->rv_map; void (*mc_with_delta_func)(int16_t *buf, const int16_t *ref_buf, uint32_t pitch, int mc_type); void (*mc_no_delta_func) (int16_t *buf, const int16_t *ref_buf, uint32_t pitch, int mc_type); const uint8_t *base_tab, *scale_tab; prev_dc = 0; /* init intra prediction for the DC coefficient */ blk_size = band->blk_size; col_mask = blk_size - 1; /* column mask for tracking non-zero coeffs */ num_blocks = (band->mb_size != blk_size) ? 4 : 1; /* number of blocks per mb */ num_coeffs = blk_size * blk_size; if (blk_size == 8) { mc_with_delta_func = ff_ivi_mc_8x8_delta; mc_no_delta_func = ff_ivi_mc_8x8_no_delta; } else { mc_with_delta_func = ff_ivi_mc_4x4_delta; mc_no_delta_func = ff_ivi_mc_4x4_no_delta; } for (mbn = 0, mb = tile->mbs; mbn < tile->num_MBs; mb++, mbn++) { is_intra = !mb->type; cbp = mb->cbp; buf_offs = mb->buf_offs; quant = av_clip(band->glob_quant + mb->q_delta, 0, 23); base_tab = is_intra ? band->intra_base : band->inter_base; scale_tab = is_intra ? band->intra_scale : band->inter_scale; if (!is_intra) { mv_x = mb->mv_x; mv_y = mb->mv_y; if (!band->is_halfpel) { mc_type = 0; /* we have only fullpel vectors */ } else { mc_type = ((mv_y & 1) << 1) | (mv_x & 1); mv_x >>= 1; mv_y >>= 1; /* convert halfpel vectors into fullpel ones */ } } for (blk = 0; blk < num_blocks; blk++) { /* adjust block position in the buffer according to its number */ if (blk & 1) { buf_offs += blk_size; } else if (blk == 2) { buf_offs -= blk_size; buf_offs += blk_size * band->pitch; } if (cbp & 1) { /* block coded ? */ scan_pos = -1; memset(trvec, 0, num_coeffs*sizeof(trvec[0])); /* zero transform vector */ memset(col_flags, 0, sizeof(col_flags)); /* zero column flags */ while (scan_pos <= num_coeffs) { sym = get_vlc2(gb, band->blk_vlc.tab->table, IVI_VLC_BITS, 1); if (sym == rvmap->eob_sym) break; /* End of block */ if (sym == rvmap->esc_sym) { /* Escape - run/val explicitly coded using 3 vlc codes */ run = get_vlc2(gb, band->blk_vlc.tab->table, IVI_VLC_BITS, 1) + 1; lo = get_vlc2(gb, band->blk_vlc.tab->table, IVI_VLC_BITS, 1); hi = get_vlc2(gb, band->blk_vlc.tab->table, IVI_VLC_BITS, 1); val = IVI_TOSIGNED((hi << 6) | lo); /* merge them and convert into signed val */ } else { run = rvmap->runtab[sym]; val = rvmap->valtab[sym]; } /* de-zigzag and dequantize */ scan_pos += run; if (scan_pos >= num_coeffs) break; pos = band->scan[scan_pos]; if (IVI_DEBUG && !val) av_log(NULL, AV_LOG_ERROR, "Val = 0 encountered!\n"); q = (base_tab[pos] * scale_tab[quant]) >> 8; if (q > 1) val = val * q + FFSIGN(val) * ((q >> 1) - (q & 1)); trvec[pos] = val; col_flags[pos & col_mask] |= !!val; /* track columns containing non-zero coeffs */ }// while if (scan_pos >= num_coeffs && sym != rvmap->eob_sym) return -1; /* corrupt block data */ /* undoing DC coeff prediction for intra-blocks */ if (is_intra && band->is_2d_trans) { prev_dc += trvec[0]; trvec[0] = prev_dc; col_flags[0] |= !!prev_dc; } /* apply inverse transform */ band->inv_transform(trvec, band->buf + buf_offs, band->pitch, col_flags); /* apply motion compensation */ if (!is_intra) mc_with_delta_func(band->buf + buf_offs, band->ref_buf + buf_offs + mv_y * band->pitch + mv_x, band->pitch, mc_type); } else { /* block not coded */ /* for intra blocks apply the dc slant transform */ /* for inter - perform the motion compensation without delta */ if (is_intra && band->dc_transform) { band->dc_transform(&prev_dc, band->buf + buf_offs, band->pitch, blk_size); } else mc_no_delta_func(band->buf + buf_offs, band->ref_buf + buf_offs + mv_y * band->pitch + mv_x, band->pitch, mc_type); } cbp >>= 1; }// for blk }// for mbn align_get_bits(gb); return 0; } void ff_ivi_process_empty_tile(AVCodecContext *avctx, IVIBandDesc *band, IVITile *tile, int32_t mv_scale) { int x, y, need_mc, mbn, blk, num_blocks, mv_x, mv_y, mc_type; int offs, mb_offset, row_offset; IVIMbInfo *mb, *ref_mb; const int16_t *src; int16_t *dst; void (*mc_no_delta_func)(int16_t *buf, const int16_t *ref_buf, uint32_t pitch, int mc_type); offs = tile->ypos * band->pitch + tile->xpos; mb = tile->mbs; ref_mb = tile->ref_mbs; row_offset = band->mb_size * band->pitch; need_mc = 0; /* reset the mc tracking flag */ for (y = tile->ypos; y < (tile->ypos + tile->height); y += band->mb_size) { mb_offset = offs; for (x = tile->xpos; x < (tile->xpos + tile->width); x += band->mb_size) { mb->xpos = x; mb->ypos = y; mb->buf_offs = mb_offset; mb->type = 1; /* set the macroblocks type = INTER */ mb->cbp = 0; /* all blocks are empty */ if (!band->qdelta_present && !band->plane && !band->band_num) { mb->q_delta = band->glob_quant; mb->mv_x = 0; mb->mv_y = 0; } if (band->inherit_qdelta && ref_mb) mb->q_delta = ref_mb->q_delta; if (band->inherit_mv) { /* motion vector inheritance */ if (mv_scale) { mb->mv_x = ivi_scale_mv(ref_mb->mv_x, mv_scale); mb->mv_y = ivi_scale_mv(ref_mb->mv_y, mv_scale); } else { mb->mv_x = ref_mb->mv_x; mb->mv_y = ref_mb->mv_y; } need_mc |= mb->mv_x || mb->mv_y; /* tracking non-zero motion vectors */ } mb++; if (ref_mb) ref_mb++; mb_offset += band->mb_size; } // for x offs += row_offset; } // for y if (band->inherit_mv && need_mc) { /* apply motion compensation if there is at least one non-zero motion vector */ num_blocks = (band->mb_size != band->blk_size) ? 4 : 1; /* number of blocks per mb */ mc_no_delta_func = (band->blk_size == 8) ? ff_ivi_mc_8x8_no_delta : ff_ivi_mc_4x4_no_delta; for (mbn = 0, mb = tile->mbs; mbn < tile->num_MBs; mb++, mbn++) { mv_x = mb->mv_x; mv_y = mb->mv_y; if (!band->is_halfpel) { mc_type = 0; /* we have only fullpel vectors */ } else { mc_type = ((mv_y & 1) << 1) | (mv_x & 1); mv_x >>= 1; mv_y >>= 1; /* convert halfpel vectors into fullpel ones */ } for (blk = 0; blk < num_blocks; blk++) { /* adjust block position in the buffer according with its number */ offs = mb->buf_offs + band->blk_size * ((blk & 1) + !!(blk & 2) * band->pitch); mc_no_delta_func(band->buf + offs, band->ref_buf + offs + mv_y * band->pitch + mv_x, band->pitch, mc_type); } } } else { /* copy data from the reference tile into the current one */ src = band->ref_buf + tile->ypos * band->pitch + tile->xpos; dst = band->buf + tile->ypos * band->pitch + tile->xpos; for (y = 0; y < tile->height; y++) { memcpy(dst, src, tile->width*sizeof(band->buf[0])); src += band->pitch; dst += band->pitch; } } } #if IVI_DEBUG uint16_t ivi_calc_band_checksum (IVIBandDesc *band) { int x, y; int16_t *src, checksum; src = band->buf; checksum = 0; for (y = 0; y < band->height; src += band->pitch, y++) for (x = 0; x < band->width; x++) checksum += src[x]; return checksum; } int ivi_check_band (IVIBandDesc *band, const uint8_t *ref, int pitch) { int x, y, result; uint8_t t1, t2; int16_t *src; src = band->buf; result = 0; for (y = 0; y < band->height; src += band->pitch, y++) { for (x = 0; x < band->width; x++) { t1 = av_clip(src[x] + 128, 0, 255); t2 = ref[x]; if (t1 != t2) { av_log(NULL, AV_LOG_ERROR, "Data mismatch: row %d, column %d\n", y / band->blk_size, x / band->blk_size); result = -1; } } ref += pitch; } return result; } #endif void ff_ivi_output_plane(IVIPlaneDesc *plane, uint8_t *dst, int dst_pitch) { int x, y; const int16_t *src = plane->bands[0].buf; uint32_t pitch = plane->bands[0].pitch; for (y = 0; y < plane->height; y++) { for (x = 0; x < plane->width; x++) dst[x] = av_clip_uint8(src[x] + 128); src += pitch; dst += dst_pitch; } } /** * These are 2x8 predefined Huffman codebooks for coding macroblock/block * signals. They are specified using "huffman descriptors" in order to * avoid huge static tables. The decoding tables will be generated at * startup from these descriptors. */ const IVIHuffDesc ff_ivi_mb_huff_desc[8] = { {8, {0, 4, 5, 4, 4, 4, 6, 6}}, {12, {0, 2, 2, 3, 3, 3, 3, 5, 3, 2, 2, 2}}, {12, {0, 2, 3, 4, 3, 3, 3, 3, 4, 3, 2, 2}}, {12, {0, 3, 4, 4, 3, 3, 3, 3, 3, 2, 2, 2}}, {13, {0, 4, 4, 3, 3, 3, 3, 2, 3, 3, 2, 1, 1}}, {9, {0, 4, 4, 4, 4, 3, 3, 3, 2}}, {10, {0, 4, 4, 4, 4, 3, 3, 2, 2, 2}}, {12, {0, 4, 4, 4, 3, 3, 2, 3, 2, 2, 2, 2}} }; const IVIHuffDesc ff_ivi_blk_huff_desc[8] = { {10, {1, 2, 3, 4, 4, 7, 5, 5, 4, 1}}, {11, {2, 3, 4, 4, 4, 7, 5, 4, 3, 3, 2}}, {12, {2, 4, 5, 5, 5, 5, 6, 4, 4, 3, 1, 1}}, {13, {3, 3, 4, 4, 5, 6, 6, 4, 4, 3, 2, 1, 1}}, {11, {3, 4, 4, 5, 5, 5, 6, 5, 4, 2, 2}}, {13, {3, 4, 5, 5, 5, 5, 6, 4, 3, 3, 2, 1, 1}}, {13, {3, 4, 5, 5, 5, 6, 5, 4, 3, 3, 2, 1, 1}}, {9, {3, 4, 4, 5, 5, 5, 6, 5, 5}} }; /** * Run-value (RLE) tables. */ const RVMapDesc ff_ivi_rvmap_tabs[9] = { { /* MapTab0 */ 5, /* eob_sym */ 2, /* esc_sym */ /* run table */ {1, 1, 0, 1, 1, 0, 1, 1, 2, 2, 1, 1, 1, 1, 3, 3, 1, 1, 2, 2, 1, 1, 4, 4, 1, 1, 1, 1, 2, 2, 5, 5, 1, 1, 3, 3, 1, 1, 6, 6, 1, 2, 1, 2, 7, 7, 1, 1, 8, 8, 1, 1, 4, 2, 1, 4, 2, 1, 3, 3, 1, 1, 1, 9, 9, 1, 2, 1, 2, 1, 5, 5, 1, 1, 10, 10, 1, 1, 3, 3, 2, 2, 1, 1, 11, 11, 6, 4, 4, 1, 6, 1, 2, 1, 2, 12, 8, 1, 12, 7, 8, 7, 1, 16, 1, 16, 1, 3, 3, 13, 1, 13, 2, 2, 1, 15, 1, 5, 14, 15, 1, 5, 14, 1, 17, 8, 17, 8, 1, 4, 4, 2, 2, 1, 25, 25, 24, 24, 1, 3, 1, 3, 1, 8, 6, 7, 6, 1, 18, 8, 18, 1, 7, 23, 2, 2, 23, 1, 1, 21, 22, 9, 9, 22, 19, 1, 21, 5, 19, 5, 1, 33, 20, 33, 20, 8, 4, 4, 1, 32, 2, 2, 8, 3, 32, 26, 3, 1, 7, 7, 26, 6, 1, 6, 1, 1, 16, 1, 10, 1, 10, 2, 16, 29, 28, 2, 29, 28, 1, 27, 5, 8, 5, 27, 1, 8, 3, 7, 3, 31, 41, 31, 1, 41, 6, 1, 6, 7, 4, 4, 1, 1, 2, 1, 2, 11, 34, 30, 11, 1, 30, 15, 15, 34, 36, 40, 36, 40, 35, 35, 37, 37, 39, 39, 38, 38}, /* value table */ { 1, -1, 0, 2, -2, 0, 3, -3, 1, -1, 4, -4, 5, -5, 1, -1, 6, -6, 2, -2, 7, -7, 1, -1, 8, -8, 9, -9, 3, -3, 1, -1, 10, -10, 2, -2, 11, -11, 1, -1, 12, 4, -12, -4, 1, -1, 13, -13, 1, -1, 14, -14, 2, 5, 15, -2, -5, -15, -3, 3, 16, -16, 17, 1, -1, -17, 6, 18, -6, -18, 2, -2, 19, -19, 1, -1, 20, -20, 4, -4, 7, -7, 21, -21, 1, -1, 2, 3, -3, 22, -2, -22, 8, 23, -8, 1, 2, -23, -1, 2, -2, -2, 24, 1, -24, -1, 25, 5, -5, 1, -25, -1, 9, -9, 26, 1, -26, 3, 1, -1, 27, -3, -1, -27, 1, 3, -1, -3, 28, -4, 4, 10, -10, -28, 1, -1, 1, -1, 29, 6, -29, -6, 30, -4, 3, 3, -3, -30, 1, 4, -1, 31, -3, 1, 11, -11, -1, -31, 32, -1, -1, 2, -2, 1, 1, -32, 1, 4, -1, -4, 33, -1, 1, 1, -1, 5, 5, -5, -33, -1, -12, 12, -5, -7, 1, 1, 7, 34, 4, -4, -1, 4, -34, -4, 35, 36, -2, -35, -2, -36, 2, 13, 2, -1, 1, -13, 1, -1, 37, 1, -5, 6, 5, -1, 38, -6, -8, 5, 8, -1, 1, 1, -37, -1, 5, 39, -5, -5, 6, -6, -38, -39, -14, 40, 14, 2, 1, 1, -2, -40, -1, -2, 2, -1, -1, -1, 1, 1, 1, -1, 1, -1, 1, -1, 1, -1} },{ /* MapTab1 */ 0, /* eob_sym */ 38, /* esc_sym */ /* run table */ {0, 1, 1, 2, 2, 3, 3, 4, 4, 5, 5, 6, 8, 6, 8, 7, 7, 9, 9, 10, 10, 11, 11, 1, 12, 1, 12, 13, 13, 16, 14, 16, 14, 15, 15, 17, 17, 18, 0, 18, 19, 20, 21, 19, 22, 21, 20, 22, 25, 24, 2, 25, 24, 23, 23, 2, 26, 28, 26, 28, 29, 27, 29, 27, 33, 33, 1, 32, 1, 3, 32, 30, 36, 3, 36, 30, 31, 31, 35, 34, 37, 41, 34, 35, 37, 4, 41, 4, 49, 8, 8, 49, 40, 38, 5, 38, 40, 39, 5, 39, 42, 43, 42, 7, 57, 6, 43, 44, 6, 50, 7, 44, 57, 48, 50, 48, 45, 45, 46, 47, 51, 46, 47, 58, 1, 51, 58, 1, 52, 59, 53, 9, 52, 55, 55, 59, 53, 56, 54, 56, 54, 9, 64, 64, 60, 63, 60, 63, 61, 62, 61, 62, 2, 10, 2, 10, 11, 1, 11, 13, 12, 1, 12, 13, 16, 16, 8, 8, 14, 3, 3, 15, 14, 15, 4, 4, 1, 17, 17, 5, 1, 7, 7, 5, 6, 1, 2, 2, 6, 22, 1, 25, 21, 22, 8, 24, 1, 21, 25, 24, 8, 18, 18, 23, 9, 20, 23, 33, 29, 33, 20, 1, 19, 1, 29, 36, 9, 36, 19, 41, 28, 57, 32, 3, 28, 3, 1, 27, 49, 49, 1, 32, 26, 26, 2, 4, 4, 7, 57, 41, 2, 7, 10, 5, 37, 16, 10, 27, 8, 8, 13, 16, 37, 13, 1, 5}, /* value table */ {0, 1, -1, 1, -1, 1, -1, 1, -1, 1, -1, 1, 1, -1, -1, 1, -1, 1, -1, 1, -1, 1, -1, 2, 1, -2, -1, 1, -1, 1, 1, -1, -1, 1, -1, 1, -1, 1, 0, -1, 1, 1, 1, -1, 1, -1, -1, -1, 1, 1, 2, -1, -1, 1, -1, -2, 1, 1, -1, -1, 1, 1, -1, -1, 1, -1, 3, 1, -3, 2, -1, 1, 1, -2, -1, -1, -1, 1, 1, 1, 1, 1, -1, -1, -1, 2, -1, -2, 1, 2, -2, -1, 1, 1, 2, -1, -1, 1, -2, -1, 1, 1, -1, 2, 1, 2, -1, 1, -2, -1, -2, -1, -1, 1, 1, -1, 1, -1, 1, 1, 1, -1, -1, 1, 4, -1, -1, -4, 1, 1, 1, 2, -1, -1, 1, -1, -1, 1, -1, -1, 1, -2, 1, -1, 1, 1, -1, -1, 1, 1, -1, -1, 3, 2, -3, -2, 2, 5, -2, 2, 2, -5, -2, -2, -2, 2, -3, 3, 2, 3, -3, 2, -2, -2, 3, -3, 6, 2, -2, 3, -6, 3, -3, -3, 3, 7, -4, 4, -3, 2, -7, 2, 2, -2, -4, 2, 8, -2, -2, -2, 4, 2, -2, 2, 3, 2, -2, -2, 2, 2, -2, -8, -2, 9, -2, 2, -3, -2, 2, -2, 2, 2, 2, 4, -2, -4, 10, 2, 2, -2, -9, -2, 2, -2, 5, 4, -4, 4, -2, 2, -5, -4, -3, 4, 2, -3, 3, -2, -5, 5, 3, 3, -2, -3, -10, -4} },{ /* MapTab2 */ 2, /* eob_sym */ 11, /* esc_sym */ /* run table */ {1, 1, 0, 2, 2, 1, 1, 3, 3, 4, 4, 0, 1, 1, 5, 5, 2, 2, 6, 6, 7, 7, 1, 8, 1, 8, 3, 3, 9, 9, 1, 2, 2, 1, 4, 10, 4, 10, 11, 11, 1, 5, 12, 12, 1, 5, 13, 13, 3, 3, 6, 6, 2, 2, 14, 14, 16, 16, 15, 7, 15, 8, 8, 7, 1, 1, 17, 17, 4, 4, 1, 1, 18, 18, 2, 2, 5, 5, 25, 3, 9, 3, 25, 9, 19, 24, 19, 24, 1, 21, 20, 1, 21, 22, 20, 22, 23, 23, 8, 6, 33, 6, 8, 33, 7, 7, 26, 26, 1, 32, 1, 32, 28, 4, 28, 10, 29, 27, 27, 10, 41, 4, 29, 2, 2, 41, 36, 31, 49, 31, 34, 30, 34, 36, 30, 35, 1, 49, 11, 5, 35, 11, 1, 3, 3, 5, 37, 37, 8, 40, 8, 40, 12, 12, 42, 42, 1, 38, 16, 57, 1, 6, 16, 39, 38, 6, 7, 7, 13, 13, 39, 43, 2, 43, 57, 2, 50, 9, 44, 9, 50, 4, 15, 48, 44, 4, 1, 15, 48, 14, 14, 1, 45, 45, 8, 3, 5, 8, 51, 47, 3, 46, 46, 47, 5, 51, 1, 17, 17, 58, 1, 58, 2, 52, 52, 2, 53, 7, 59, 6, 6, 56, 53, 55, 7, 55, 1, 54, 59, 56, 54, 10, 1, 10, 4, 60, 1, 60, 8, 4, 8, 64, 64, 61, 1, 63, 3, 63, 62, 61, 5, 11, 5, 3, 11, 62}, /* value table */ { 1, -1, 0, 1, -1, 2, -2, 1, -1, 1, -1, 0, 3, -3, 1, -1, 2, -2, 1, -1, 1, -1, 4, 1, -4, -1, 2, -2, 1, -1, 5, 3, -3, -5, 2, 1, -2, -1, 1, -1, 6, 2, 1, -1, -6, -2, 1, -1, 3, -3, 2, -2, 4, -4, 1, -1, 1, -1, 1, 2, -1, 2, -2, -2, 7, -7, 1, -1, 3, -3, 8, -8, 1, -1, 5, -5, 3, -3, 1, 4, 2, -4, -1, -2, 1, 1, -1, -1, 9, 1, 1, -9, -1, 1, -1, -1, 1, -1, 3, -3, 1, 3, -3, -1, 3, -3, 1, -1, 10, 1, -10, -1, 1, 4, -1, 2, 1, -1, 1, -2, 1, -4, -1, 6, -6, -1, 1, 1, 1, -1, 1, 1, -1, -1, -1, 1, 11, -1, -2, 4, -1, 2, -11, 5, -5, -4, -1, 1, 4, 1, -4, -1, -2, 2, 1, -1, 12, 1, -2, 1, -12, 4, 2, 1, -1, -4, 4, -4, 2, -2, -1, 1, 7, -1, -1, -7, -1, -3, 1, 3, 1, 5, 2, 1, -1, -5, 13, -2, -1, 2, -2, -13, 1, -1, 5, 6, 5, -5, 1, 1, -6, 1, -1, -1, -5, -1, 14, 2, -2, 1, -14, -1, 8, 1, -1, -8, 1, 5, 1, 5, -5, 1, -1, 1, -5, -1, 15, 1, -1, -1, -1, 3, -15, -3, 6, 1, 16, -1, 6, -6, -6, 1, -1, 1, -16, 1, 7, -1, 1, -1, -6, -3, 6, -7, 3, -1} },{ /* MapTab3 */ 0, /* eob_sym */ 35, /* esc_sym */ /* run table */ {0, 1, 1, 2, 2, 3, 3, 4, 4, 1, 1, 5, 5, 6, 6, 7, 7, 8, 8, 9, 9, 2, 2, 10, 10, 1, 1, 11, 11, 12, 12, 3, 3, 13, 13, 0, 14, 14, 16, 15, 16, 15, 4, 4, 17, 1, 17, 1, 5, 5, 18, 18, 2, 2, 6, 6, 8, 19, 7, 8, 7, 19, 20, 20, 21, 21, 22, 24, 22, 24, 23, 23, 1, 1, 25, 25, 3, 3, 26, 26, 9, 9, 27, 27, 28, 28, 33, 29, 4, 33, 29, 1, 4, 1, 32, 32, 2, 2, 31, 10, 30, 10, 30, 31, 34, 34, 5, 5, 36, 36, 35, 41, 35, 11, 41, 11, 37, 1, 8, 8, 37, 6, 1, 6, 40, 7, 7, 40, 12, 38, 12, 39, 39, 38, 49, 13, 49, 13, 3, 42, 3, 42, 16, 16, 43, 43, 14, 14, 1, 1, 44, 15, 44, 15, 2, 2, 57, 48, 50, 48, 57, 50, 4, 45, 45, 4, 46, 47, 47, 46, 1, 51, 1, 17, 17, 51, 8, 9, 9, 5, 58, 8, 58, 5, 52, 52, 55, 56, 53, 56, 55, 59, 59, 53, 54, 1, 6, 54, 7, 7, 6, 1, 2, 3, 2, 3, 64, 60, 60, 10, 10, 64, 61, 62, 61, 63, 1, 63, 62, 1, 18, 24, 18, 4, 25, 4, 8, 21, 21, 1, 24, 22, 25, 22, 8, 11, 19, 11, 23, 1, 20, 23, 19, 20, 5, 12, 5, 1, 16, 2, 12, 13, 2, 13, 1, 16}, /* value table */ { 0, 1, -1, 1, -1, 1, -1, 1, -1, 2, -2, 1, -1, 1, -1, 1, -1, 1, -1, 1, -1, 2, -2, 1, -1, 3, -3, 1, -1, 1, -1, 2, -2, 1, -1, 0, 1, -1, 1, 1, -1, -1, 2, -2, 1, 4, -1, -4, 2, -2, 1, -1, -3, 3, 2, -2, 2, 1, 2, -2, -2, -1, 1, -1, 1, -1, 1, 1, -1, -1, 1, -1, 5, -5, 1, -1, 3, -3, 1, -1, 2, -2, 1, -1, 1, -1, 1, 1, 3, -1, -1, 6, -3, -6, -1, 1, 4, -4, 1, 2, 1, -2, -1, -1, 1, -1, 3, -3, 1, -1, 1, 1, -1, 2, -1, -2, 1, 7, -3, 3, -1, 3, -7, -3, 1, -3, 3, -1, 2, 1, -2, 1, -1, -1, 1, 2, -1, -2, -4, -1, 4, 1, 2, -2, 1, -1, -2, 2, 8, -8, -1, 2, 1, -2, -5, 5, 1, -1, -1, 1, -1, 1, 4, -1, 1, -4, -1, -1, 1, 1, 9, 1, -9, 2, -2, -1, -4, 3, -3, -4, -1, 4, 1, 4, 1, -1, 1, -1, 1, 1, -1, 1, -1, -1, -1, 10, 4, 1, 4, -4, -4, -10, 6, 5, -6, -5, 1, -1, 1, 3, -3, -1, 1, -1, -1, -1, 11, 1, 1, -11, -2, -2, 2, 5, -2, -5, -5, 2, -2, 12, 2, -2, 2, 2, 5, -3, -2, 3, -2, -12, -2, 2, 2, 2, -5, 3, 5, 13, -3, 7, -3, -3, -7, 3, -13, 3} },{ /* MapTab4 */ 0, /* eob_sym */ 34, /* esc_sym */ /* run table */ {0, 1, 1, 1, 2, 2, 1, 3, 3, 1, 1, 1, 4, 4, 1, 5, 2, 1, 5, 2, 1, 1, 6, 6, 1, 1, 1, 1, 1, 7, 3, 1, 2, 3, 0, 1, 2, 7, 1, 1, 1, 8, 1, 1, 8, 1, 1, 1, 9, 1, 9, 1, 2, 1, 1, 2, 1, 1, 10, 4, 1, 10, 1, 4, 1, 1, 1, 1, 1, 3, 1, 1, 1, 3, 2, 1, 5, 1, 1, 1, 2, 5, 1, 11, 1, 11, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 2, 1, 6, 1, 6, 1, 1, 2, 1, 1, 1, 1, 1, 1, 1, 12, 3, 1, 12, 1, 1, 1, 2, 1, 1, 3, 1, 1, 1, 1, 1, 1, 4, 1, 1, 1, 2, 1, 1, 4, 1, 1, 1, 1, 1, 1, 2, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 3, 1, 2, 1, 1, 5, 1, 1, 1, 1, 1, 7, 1, 7, 1, 1, 2, 3, 1, 1, 1, 1, 5, 1, 1, 1, 1, 1, 1, 2, 13, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 13, 2, 1, 1, 4, 1, 1, 1, 3, 1, 6, 1, 1, 1, 14, 1, 1, 1, 1, 1, 14, 6, 1, 1, 1, 1, 15, 2, 4, 1, 2, 3, 15, 1, 1, 1, 8, 1, 1, 8, 1, 1, 1, 1, 1, 1, 1, 1, 2, 1, 1, 1, 1, 1, 1, 1}, /* value table */ { 0, 1, -1, 2, 1, -1, -2, 1, -1, 3, -3, 4, 1, -1, -4, 1, 2, 5, -1, -2, -5, 6, 1, -1, -6, 7, -7, 8, -8, 1, 2, 9, 3, -2, 0, -9, -3, -1, 10, -10, 11, 1, -11, 12, -1, -12, 13, -13, 1, 14, -1, -14, 4, 15, -15, -4, 16, -16, 1, 2, 17, -1, -17, -2, 18, -18, 19, -19, 20, 3, -20, 21, -21, -3, 5, 22, 2, -22, -23, 23, -5, -2, 24, 1, -24, -1, 25, -25, 26, -26, -27, 27, 28, 29, -28, -29, 6, 30, 2, -31, -2, -30, 31, -6, -32, 32, 33, -33, 34, -35, -34, 1, 4, -36, -1, 35, 37, 36, 7, -37, 38, -4, -38, 39, 41, 40, -40, -39, 3, 42, -43, -41, -7, -42, 43, -3, 44, -44, 45, -45, 46, 47, 8, -47, -48, -46, 50, -50, 48, 49, 51, -49, 52, -52, 5, -51, -8, -53, 53, 3, -56, 56, 55, 54, -54, 2, 60, -2, -55, 58, 9, -5, 59, 57, -57, -63, -3, -58, -60, -61, 61, -59, -62, -9, 1, 64, 62, 69, -64, 63, 65, -67, -68, 66, -65, 68, -66, -69, 67, -70, -1, 10, 71, -71, 4, 73, 72, 70, 6, -76, -3, 74, -78, -74, 1, 78, 80, -72, -75, 76, -1, 3, -73, 79, 75, 77, 1, 11, -4, -79, -10, -6, -1, -77, -83, -80, 2, 81, -84, -2, 83, -81, 82, -82, 84, -87, -86, 85, -11, -85, 86, -89, 87, -88, 88, 89} },{ /* MapTab5 */ 2, /* eob_sym */ 33, /* esc_sym */ /* run table */ {1, 1, 0, 2, 1, 2, 1, 3, 3, 1, 1, 4, 4, 2, 2, 1, 1, 5, 5, 6, 1, 6, 1, 7, 7, 3, 3, 2, 8, 2, 8, 1, 1, 0, 9, 9, 1, 1, 10, 4, 10, 4, 11, 11, 2, 1, 2, 1, 12, 12, 3, 3, 1, 1, 13, 5, 5, 13, 14, 1, 1, 14, 2, 2, 6, 6, 15, 1, 1, 15, 16, 4, 7, 16, 4, 7, 1, 1, 3, 3, 8, 8, 2, 2, 1, 1, 17, 17, 1, 1, 18, 18, 5, 5, 2, 2, 1, 1, 9, 19, 9, 19, 20, 3, 3, 20, 1, 10, 21, 1, 10, 4, 4, 21, 22, 6, 6, 22, 1, 1, 23, 24, 2, 2, 23, 24, 11, 1, 1, 11, 7, 25, 7, 1, 1, 25, 8, 8, 3, 26, 3, 1, 12, 2, 2, 26, 1, 12, 5, 5, 27, 4, 1, 4, 1, 27, 28, 1, 28, 13, 1, 13, 2, 29, 2, 1, 32, 6, 1, 30, 14, 29, 14, 6, 3, 31, 3, 1, 30, 1, 32, 31, 33, 9, 33, 1, 1, 7, 9, 7, 2, 2, 1, 1, 4, 36, 34, 4, 5, 10, 10, 5, 34, 1, 1, 35, 8, 8, 36, 3, 35, 1, 15, 3, 2, 1, 16, 15, 16, 2, 37, 1, 37, 1, 1, 1, 6, 6, 38, 1, 38, 11, 1, 39, 39, 40, 11, 2, 41, 4, 40, 1, 2, 4, 1, 1, 1, 41, 3, 1, 3, 1, 5, 7, 5, 7}, /* value table */ { 1, -1, 0, 1, 2, -1, -2, 1, -1, 3, -3, 1, -1, 2, -2, 4, -4, 1, -1, 1, 5, -1, -5, 1, -1, 2, -2, 3, 1, -3, -1, 6, -6, 0, 1, -1, 7, -7, 1, 2, -1, -2, 1, -1, 4, 8, -4, -8, 1, -1, 3, -3, 9, -9, 1, 2, -2, -1, 1, 10, -10, -1, 5, -5, 2, -2, 1, 11, -11, -1, 1, 3, 2, -1, -3, -2, 12, -12, 4, -4, 2, -2, -6, 6, 13, -13, 1, -1, 14, -14, 1, -1, 3, -3, 7, -7, 15, -15, 2, 1, -2, -1, 1, 5, -5, -1, -16, 2, 1, 16, -2, 4, -4, -1, 1, 3, -3, -1, 17, -17, 1, 1, -8, 8, -1, -1, 2, 18, -18, -2, 3, 1, -3, 19, -19, -1, 3, -3, 6, 1, -6, 20, 2, 9, -9, -1, -20, -2, 4, -4, 1, -5, 21, 5, -21, -1, 1, -22, -1, 2, 22, -2, 10, 1, -10, 23, 1, 4, -23, 1, 2, -1, -2, -4, -7, 1, 7, -24, -1, 24, -1, -1, 1, 3, -1, -25, 25, 4, -3, -4, 11, -11, 26, -26, 6, 1, 1, -6, -5, -3, 3, 5, -1, -27, 27, 1, 4, -4, -1, -8, -1, 28, 2, 8, -12, -28, -2, -2, 2, 12, -1, 29, 1, -29, 30, -30, 5, -5, 1, -31, -1, 3, 31, -1, 1, 1, -3, -13, 1, -7, -1, -32, 13, 7, 32, 33, -33, -1, -9, -34, 9, 34, -6, 5, 6, -5} },{ /* MapTab6 */ 2, /* eob_sym */ 13, /* esc_sym */ /* run table */ {1, 1, 0, 1, 1, 2, 2, 1, 1, 3, 3, 1, 1, 0, 2, 2, 4, 1, 4, 1, 1, 1, 5, 5, 1, 1, 6, 6, 2, 2, 1, 1, 3, 3, 7, 7, 1, 1, 8, 8, 1, 1, 2, 2, 1, 9, 1, 9, 4, 4, 10, 1, 1, 10, 1, 1, 11, 11, 3, 3, 1, 2, 1, 2, 1, 1, 12, 12, 5, 5, 1, 1, 13, 1, 1, 13, 2, 2, 1, 1, 6, 6, 1, 1, 4, 14, 4, 14, 3, 1, 3, 1, 1, 1, 15, 7, 15, 2, 2, 7, 1, 1, 1, 8, 1, 8, 16, 16, 1, 1, 1, 1, 2, 1, 1, 2, 1, 1, 3, 5, 5, 3, 4, 1, 1, 4, 1, 1, 17, 17, 9, 1, 1, 9, 2, 2, 1, 1, 10, 10, 1, 6, 1, 1, 6, 18, 1, 1, 18, 1, 1, 1, 2, 2, 3, 1, 3, 1, 1, 1, 4, 1, 19, 1, 19, 7, 1, 1, 20, 1, 4, 20, 1, 7, 11, 2, 1, 11, 21, 2, 8, 5, 1, 8, 1, 5, 21, 1, 1, 1, 22, 1, 1, 22, 1, 1, 3, 3, 1, 23, 2, 12, 24, 1, 1, 2, 1, 1, 12, 23, 1, 1, 24, 1, 1, 1, 4, 1, 1, 1, 2, 1, 6, 6, 4, 2, 1, 1, 1, 1, 1, 1, 1, 14, 13, 3, 1, 25, 9, 25, 14, 1, 9, 3, 13, 1, 1, 1, 1, 1, 10, 1, 1, 2, 10, 2}, /* value table */ {-20, -1, 0, 2, -2, 1, -1, 3, -3, 1, -1, 4, -4, 0, 2, -2, 1, 5, -1, -5, 6, -6, 1, -1, 7, -7, 1, -1, 3, -3, 8, -8, 2, -2, 1, -1, 9, -9, 1, -1, 10, -10, 4, -4, 11, 1, -11, -1, 2, -2, 1, 12, -12, -1, 13, -13, 1, -1, 3, -3, 14, 5, -14, -5, -15, 15, -1, 1, 2, -2, 16, -16, 1, 17, -17, -1, 6, -6, 18, -18, 2, -2, -19, 19, -3, 1, 3, -1, 4, 20, -4, 1, -21, 21, 1, 2, -1, -7, 7, -2, 22, -22, 23, 2, -23, -2, 1, -1, -24, 24, -25, 25, -8, -26, 26, 8, -27, 27, 5, 3, -3, -5, -4, 28, -28, 4, 29, -29, 1, -1, -2, -30, 30, 2, 9, -9, -31, 31, 2, -2, -32, 3, 32, -33, -3, 1, 33, -34, -1, 34, -35, 35, -10, 10, -6, 36, 6, -36, 37, -37, -5, 38, 1, -38, -1, 3, 39, -39, -1, 40, 5, 1, -40, -3, 2, -11, -41, -2, 1, 11, -3, -4, 41, 3, 42, 4, -1, -43, -42, 43, 1, -44, 45, -1, 44, -45, -7, 7, -46, 1, -12, 2, 1, -47, 46, 12, 47, 48, -2, -1, -48, 49, -1, -50, -49, 50, -6, -51, 51, 52, -13, 53, -4, 4, 6, 13, -53, -52, -54, 55, 54, -55, -56, -2, 2, -8, 56, 1, -3, -1, 2, 58, 3, 8, -2, 57, -58, -60, -59, -57, -3, 60, 59, -14, 3, 14} },{ /* MapTab7 */ 2, /* eob_sym */ 38, /* esc_sym */ /* run table */ {1, 1, 0, 2, 2, 1, 1, 3, 3, 4, 4, 5, 5, 1, 1, 6, 6, 2, 2, 7, 7, 8, 8, 1, 1, 3, 3, 9, 9, 10, 10, 1, 1, 2, 2, 4, 4, 11, 0, 11, 12, 12, 13, 13, 1, 1, 5, 5, 14, 14, 15, 16, 15, 16, 3, 3, 1, 6, 1, 6, 2, 2, 7, 7, 8, 8, 17, 17, 1, 1, 4, 4, 18, 18, 2, 2, 1, 19, 1, 20, 19, 20, 21, 21, 3, 3, 22, 22, 5, 5, 24, 1, 1, 23, 9, 23, 24, 9, 2, 2, 10, 1, 1, 10, 6, 6, 25, 4, 4, 25, 7, 7, 26, 8, 1, 8, 3, 1, 26, 3, 11, 11, 27, 27, 2, 28, 1, 2, 28, 1, 12, 12, 5, 5, 29, 13, 13, 29, 32, 1, 1, 33, 31, 30, 32, 4, 30, 33, 4, 31, 3, 14, 1, 1, 3, 34, 34, 2, 2, 14, 6, 6, 35, 36, 35, 36, 1, 15, 1, 16, 16, 15, 7, 9, 7, 9, 37, 8, 8, 37, 1, 1, 39, 2, 38, 39, 2, 40, 5, 38, 40, 5, 3, 3, 4, 4, 10, 10, 1, 1, 1, 1, 41, 2, 41, 2, 6, 6, 1, 1, 11, 42, 11, 43, 3, 42, 3, 17, 4, 43, 1, 17, 7, 1, 8, 44, 4, 7, 44, 5, 8, 2, 5, 1, 2, 48, 45, 1, 12, 45, 12, 48, 13, 13, 1, 9, 9, 46, 1, 46, 47, 47, 49, 18, 18, 49}, /* value table */ { 1, -1, 0, 1, -1, 2, -2, 1, -1, 1, -1, 1, -1, 3, -3, 1, -1, -2, 2, 1, -1, 1, -1, 4, -4, -2, 2, 1, -1, 1, -1, 5, -5, -3, 3, 2, -2, 1, 0, -1, 1, -1, 1, -1, 6, -6, 2, -2, 1, -1, 1, 1, -1, -1, -3, 3, 7, 2, -7, -2, -4, 4, 2, -2, 2, -2, 1, -1, 8, -8, 3, -3, 1, -1, -5, 5, 9, 1, -9, 1, -1, -1, 1, -1, -4, 4, 1, -1, 3, -3, 1, -10, 10, 1, 2, -1, -1, -2, 6, -6, 2, 11, -11, -2, 3, -3, 1, -4, 4, -1, 3, -3, 1, 3, 12, -3, -5, -12, -1, 5, 2, -2, 1, -1, -7, 1, 13, 7, -1, -13, 2, -2, 4, -4, 1, 2, -2, -1, 1, 14, -14, 1, 1, 1, -1, -5, -1, -1, 5, -1, -6, 2, -15, 15, 6, 1, -1, -8, 8, -2, -4, 4, 1, 1, -1, -1, 16, 2, -16, -2, 2, -2, 4, 3, -4, -3, -1, -4, 4, 1, -17, 17, -1, -9, 1, 1, 9, 1, -5, -1, -1, 5, -7, 7, 6, -6, 3, -3, 18, -18, 19, -19, 1, -10, -1, 10, -5, 5, 20, -20, -3, 1, 3, 1, 8, -1, -8, 2, 7, -1, -21, -2, 5, 21, 5, -1, -7, -5, 1, -6, -5, -11, 6, 22, 11, 1, 1, -22, -3, -1, 3, -1, 3, -3, -23, 4, -4, 1, 23, -1, 1, -1, 1, -2, 2, -1} },{ /* MapTab8 */ 4, /* eob_sym */ 11, /* esc_sym */ /* run table */ {1, 1, 1, 1, 0, 2, 2, 1, 1, 3, 3, 0, 1, 1, 2, 2, 4, 4, 1, 1, 5, 5, 1, 1, 2, 2, 3, 3, 6, 6, 1, 1, 7, 7, 8, 1, 8, 2, 2, 1, 4, 4, 1, 3, 1, 3, 9, 9, 2, 2, 1, 5, 1, 5, 10, 10, 1, 1, 11, 11, 3, 6, 3, 4, 4, 6, 2, 2, 1, 12, 1, 12, 7, 13, 7, 13, 1, 1, 8, 8, 2, 2, 14, 14, 16, 15, 16, 5, 5, 1, 3, 15, 1, 3, 4, 4, 1, 1, 17, 17, 2, 2, 6, 6, 1, 18, 1, 18, 22, 21, 22, 21, 25, 24, 25, 19, 9, 20, 9, 23, 19, 24, 20, 3, 23, 7, 3, 1, 1, 7, 28, 26, 29, 5, 28, 26, 5, 8, 29, 4, 8, 27, 2, 2, 4, 27, 1, 1, 10, 36, 10, 33, 33, 36, 30, 1, 32, 32, 1, 30, 6, 31, 31, 35, 3, 6, 11, 11, 3, 2, 35, 2, 34, 1, 34, 1, 37, 37, 12, 7, 12, 5, 41, 5, 4, 7, 1, 8, 13, 4, 1, 41, 13, 38, 8, 38, 9, 1, 40, 40, 9, 1, 39, 2, 2, 49, 39, 42, 3, 3, 14, 16, 49, 14, 16, 42, 43, 43, 6, 6, 15, 1, 1, 15, 44, 44, 1, 1, 50, 48, 4, 5, 4, 7, 5, 2, 10, 10, 48, 7, 50, 45, 2, 1, 45, 8, 8, 1, 46, 46, 3, 47, 47, 3, 1, 1}, /* value table */ { 1, -1, 2, -2, 0, 1, -1, 3, -3, 1, -1, 0, 4, -4, 2, -2, 1, -1, 5, -5, 1, -1, 6, -6, 3, -3, 2, -2, 1, -1, 7, -7, 1, -1, 1, 8, -1, 4, -4, -8, 2, -2, 9, 3, -9, -3, 1, -1, 5, -5, 10, 2, -10, -2, 1, -1, 11, -11, 1, -1, -4, 2, 4, 3, -3, -2, 6, -6, 12, 1, -12, -1, 2, 1, -2, -1, 13, -13, 2, -2, 7, -7, 1, -1, 1, 1, -1, 3, -3, 14, 5, -1, -14, -5, 4, -4, 15, -15, 1, -1, 8, -8, -3, 3, 16, 1, -16, -1, 1, 1, -1, -1, 1, 1, -1, 1, 2, 1, -2, 1, -1, -1, -1, 6, -1, 3, -6, 17, -17, -3, 1, 1, 1, 4, -1, -1, -4, 3, -1, 5, -3, -1, -9, 9, -5, 1, 18, -18, 2, 1, -2, 1, -1, -1, 1, 19, -1, 1, -19, -1, 4, 1, -1, 1, 7, -4, -2, 2, -7, 10, -1, -10, 1, 20, -1, -20, 1, -1, 2, 4, -2, 5, 1, -5, 6, -4, 21, 4, 2, -6, -21, -1, -2, 1, -4, -1, -3, 22, -1, 1, 3, -22, -1, 11, -11, 1, 1, 1, 8, -8, 2, 2, -1, -2, -2, -1, 1, -1, -5, 5, 2, 23, -23, -2, 1, -1, 24, -24, -1, -1, 7, 6, -7, 5, -6, 12, -3, 3, 1, -5, 1, 1, -12, 25, -1, -5, 5, -25, -1, 1, 9, 1, -1, -9, 26, -26} } };
dreamerc/mplayer
libavcodec/ivi_common.c
C
gpl-2.0
46,143
/* ============================================================================== This file is part of the JUCE library. Copyright (c) 2017 - ROLI Ltd. JUCE is an open source library subject to commercial or open-source licensing. The code included in this file is provided under the terms of the ISC license http://www.isc.org/downloads/software-support-policy/isc-license. Permission To use, copy, modify, and/or distribute this software for any purpose with or without fee is hereby granted provided that the above copyright notice and this permission notice appear in all copies. JUCE IS PROVIDED "AS IS" WITHOUT ANY WARRANTY, AND ALL WARRANTIES, WHETHER EXPRESSED OR IMPLIED, INCLUDING MERCHANTABILITY AND FITNESS FOR PURPOSE, ARE DISCLAIMED. ============================================================================== */ namespace juce { //============================================================================== /** A simple class to generate hash functions for some primitive types, intended for use with the HashMap class. @see HashMap */ struct DefaultHashFunctions { /** Generates a simple hash from an unsigned int. */ static int generateHash (uint32 key, int upperLimit) noexcept { return (int) (key % (uint32) upperLimit); } /** Generates a simple hash from an integer. */ static int generateHash (int32 key, int upperLimit) noexcept { return generateHash ((uint32) key, upperLimit); } /** Generates a simple hash from a uint64. */ static int generateHash (uint64 key, int upperLimit) noexcept { return (int) (key % (uint64) upperLimit); } /** Generates a simple hash from an int64. */ static int generateHash (int64 key, int upperLimit) noexcept { return generateHash ((uint64) key, upperLimit); } /** Generates a simple hash from a string. */ static int generateHash (const String& key, int upperLimit) noexcept { return generateHash ((uint32) key.hashCode(), upperLimit); } /** Generates a simple hash from a variant. */ static int generateHash (const var& key, int upperLimit) noexcept { return generateHash (key.toString(), upperLimit); } /** Generates a simple hash from a void ptr. */ static int generateHash (const void* key, int upperLimit) noexcept { return generateHash ((pointer_sized_uint) key, upperLimit); } }; //============================================================================== /** Holds a set of mappings between some key/value pairs. The types of the key and value objects are set as template parameters. You can also specify a class to supply a hash function that converts a key value into an hashed integer. This class must have the form: @code struct MyHashGenerator { int generateHash (MyKeyType key, int upperLimit) const { // The function must return a value 0 <= x < upperLimit return someFunctionOfMyKeyType (key) % upperLimit; } }; @endcode Like the Array class, the key and value types are expected to be copy-by-value types, so if you define them to be pointer types, this class won't delete the objects that they point to. If you don't supply a class for the HashFunctionType template parameter, the default one provides some simple mappings for strings and ints. @code HashMap<int, String> hash; hash.set (1, "item1"); hash.set (2, "item2"); DBG (hash [1]); // prints "item1" DBG (hash [2]); // prints "item2" // This iterates the map, printing all of its key -> value pairs.. for (HashMap<int, String>::Iterator i (hash); i.next();) DBG (i.getKey() << " -> " << i.getValue()); @endcode @tparam HashFunctionType The class of hash function, which must be copy-constructible. @see CriticalSection, DefaultHashFunctions, NamedValueSet, SortedSet */ template <typename KeyType, typename ValueType, class HashFunctionType = DefaultHashFunctions, class TypeOfCriticalSectionToUse = DummyCriticalSection> class HashMap { private: typedef typename TypeHelpers::ParameterType<KeyType>::type KeyTypeParameter; typedef typename TypeHelpers::ParameterType<ValueType>::type ValueTypeParameter; public: //============================================================================== /** Creates an empty hash-map. @param numberOfSlots Specifies the number of hash entries the map will use. This will be the "upperLimit" parameter that is passed to your generateHash() function. The number of hash slots will grow automatically if necessary, or it can be remapped manually using remapTable(). @param hashFunction An instance of HashFunctionType, which will be copied and stored to use with the HashMap. This parameter can be omitted if HashFunctionType has a default constructor. */ explicit HashMap (int numberOfSlots = defaultHashTableSize, HashFunctionType hashFunction = HashFunctionType()) : hashFunctionToUse (hashFunction), totalNumItems (0) { hashSlots.insertMultiple (0, nullptr, numberOfSlots); } /** Destructor. */ ~HashMap() { clear(); } //============================================================================== /** Removes all values from the map. Note that this will clear the content, but won't affect the number of slots (see remapTable and getNumSlots). */ void clear() { const ScopedLockType sl (getLock()); for (auto i = hashSlots.size(); --i >= 0;) { auto* h = hashSlots.getUnchecked(i); while (h != nullptr) { const ScopedPointer<HashEntry> deleter (h); h = h->nextEntry; } hashSlots.set (i, nullptr); } totalNumItems = 0; } //============================================================================== /** Returns the current number of items in the map. */ inline int size() const noexcept { return totalNumItems; } /** Returns the value corresponding to a given key. If the map doesn't contain the key, a default instance of the value type is returned. @param keyToLookFor the key of the item being requested */ inline ValueType operator[] (KeyTypeParameter keyToLookFor) const { const ScopedLockType sl (getLock()); if (auto* entry = getEntry (getSlot (keyToLookFor), keyToLookFor)) return entry->value; return ValueType(); } /** Returns a reference to the value corresponding to a given key. If the map doesn't contain the key, a default instance of the value type is added to the map and a reference to this is returned. @param keyToLookFor the key of the item being requested */ inline ValueType& getReference (KeyTypeParameter keyToLookFor) { const ScopedLockType sl (getLock()); auto hashIndex = generateHashFor (keyToLookFor, getNumSlots()); auto* firstEntry = hashSlots.getUnchecked (hashIndex); if (auto* entry = getEntry (firstEntry, keyToLookFor)) return entry->value; auto* entry = new HashEntry (keyToLookFor, ValueType(), firstEntry); hashSlots.set (hashIndex, entry); ++totalNumItems; if (totalNumItems > (getNumSlots() * 3) / 2) remapTable (getNumSlots() * 2); return entry->value; } //============================================================================== /** Returns true if the map contains an item with the specied key. */ bool contains (KeyTypeParameter keyToLookFor) const { const ScopedLockType sl (getLock()); return (getEntry (getSlot (keyToLookFor), keyToLookFor) != nullptr); } /** Returns true if the hash contains at least one occurrence of a given value. */ bool containsValue (ValueTypeParameter valueToLookFor) const { const ScopedLockType sl (getLock()); for (auto i = getNumSlots(); --i >= 0;) for (auto* entry = hashSlots.getUnchecked(i); entry != nullptr; entry = entry->nextEntry) if (entry->value == valueToLookFor) return true; return false; } //============================================================================== /** Adds or replaces an element in the hash-map. If there's already an item with the given key, this will replace its value. Otherwise, a new item will be added to the map. */ void set (KeyTypeParameter newKey, ValueTypeParameter newValue) { getReference (newKey) = newValue; } /** Removes an item with the given key. */ void remove (KeyTypeParameter keyToRemove) { const ScopedLockType sl (getLock()); auto hashIndex = generateHashFor (keyToRemove, getNumSlots()); auto* entry = hashSlots.getUnchecked (hashIndex); HashEntry* previous = nullptr; while (entry != nullptr) { if (entry->key == keyToRemove) { const ScopedPointer<HashEntry> deleter (entry); entry = entry->nextEntry; if (previous != nullptr) previous->nextEntry = entry; else hashSlots.set (hashIndex, entry); --totalNumItems; } else { previous = entry; entry = entry->nextEntry; } } } /** Removes all items with the given value. */ void removeValue (ValueTypeParameter valueToRemove) { const ScopedLockType sl (getLock()); for (auto i = getNumSlots(); --i >= 0;) { auto* entry = hashSlots.getUnchecked(i); HashEntry* previous = nullptr; while (entry != nullptr) { if (entry->value == valueToRemove) { const ScopedPointer<HashEntry> deleter (entry); entry = entry->nextEntry; if (previous != nullptr) previous->nextEntry = entry; else hashSlots.set (i, entry); --totalNumItems; } else { previous = entry; entry = entry->nextEntry; } } } } /** Remaps the hash-map to use a different number of slots for its hash function. Each slot corresponds to a single hash-code, and each one can contain multiple items. @see getNumSlots() */ void remapTable (int newNumberOfSlots) { const ScopedLockType sl (getLock()); Array<HashEntry*> newSlots; newSlots.insertMultiple (0, nullptr, newNumberOfSlots); for (auto i = getNumSlots(); --i >= 0;) { HashEntry* nextEntry = nullptr; for (auto* entry = hashSlots.getUnchecked(i); entry != nullptr; entry = nextEntry) { auto hashIndex = generateHashFor (entry->key, newNumberOfSlots); nextEntry = entry->nextEntry; entry->nextEntry = newSlots.getUnchecked (hashIndex); newSlots.set (hashIndex, entry); } } hashSlots.swapWith (newSlots); } /** Returns the number of slots which are available for hashing. Each slot corresponds to a single hash-code, and each one can contain multiple items. @see getNumSlots() */ inline int getNumSlots() const noexcept { return hashSlots.size(); } //============================================================================== /** Efficiently swaps the contents of two hash-maps. */ template <class OtherHashMapType> void swapWith (OtherHashMapType& otherHashMap) noexcept { const ScopedLockType lock1 (getLock()); const typename OtherHashMapType::ScopedLockType lock2 (otherHashMap.getLock()); hashSlots.swapWith (otherHashMap.hashSlots); std::swap (totalNumItems, otherHashMap.totalNumItems); } //============================================================================== /** Returns the CriticalSection that locks this structure. To lock, you can call getLock().enter() and getLock().exit(), or preferably use an object of ScopedLockType as an RAII lock for it. */ inline const TypeOfCriticalSectionToUse& getLock() const noexcept { return lock; } /** Returns the type of scoped lock to use for locking this array */ typedef typename TypeOfCriticalSectionToUse::ScopedLockType ScopedLockType; private: //============================================================================== class HashEntry { public: HashEntry (KeyTypeParameter k, ValueTypeParameter val, HashEntry* const next) : key (k), value (val), nextEntry (next) {} const KeyType key; ValueType value; HashEntry* nextEntry; JUCE_DECLARE_NON_COPYABLE (HashEntry) }; public: //============================================================================== /** Iterates over the items in a HashMap. To use it, repeatedly call next() until it returns false, e.g. @code HashMap <String, String> myMap; HashMap<String, String>::Iterator i (myMap); while (i.next()) { DBG (i.getKey() << " -> " << i.getValue()); } @endcode The order in which items are iterated bears no resemblence to the order in which they were originally added! Obviously as soon as you call any non-const methods on the original hash-map, any iterators that were created beforehand will cease to be valid, and should not be used. @see HashMap */ struct Iterator { Iterator (const HashMap& hashMapToIterate) noexcept : hashMap (hashMapToIterate), entry (nullptr), index (0) {} Iterator (const Iterator& other) noexcept : hashMap (other.hashMap), entry (other.entry), index (other.index) {} /** Moves to the next item, if one is available. When this returns true, you can get the item's key and value using getKey() and getValue(). If it returns false, the iteration has finished and you should stop. */ bool next() noexcept { if (entry != nullptr) entry = entry->nextEntry; while (entry == nullptr) { if (index >= hashMap.getNumSlots()) return false; entry = hashMap.hashSlots.getUnchecked (index++); } return true; } /** Returns the current item's key. This should only be called when a call to next() has just returned true. */ KeyType getKey() const { return entry != nullptr ? entry->key : KeyType(); } /** Returns the current item's value. This should only be called when a call to next() has just returned true. */ ValueType getValue() const { return entry != nullptr ? entry->value : ValueType(); } /** Resets the iterator to its starting position. */ void reset() noexcept { entry = nullptr; index = 0; } Iterator& operator++() noexcept { next(); return *this; } ValueType operator*() const { return getValue(); } bool operator!= (const Iterator& other) const noexcept { return entry != other.entry || index != other.index; } void resetToEnd() noexcept { index = hashMap.getNumSlots(); } private: //============================================================================== const HashMap& hashMap; HashEntry* entry; int index; // using the copy constructor is ok, but you cannot assign iterators Iterator& operator= (const Iterator&) = delete; JUCE_LEAK_DETECTOR (Iterator) }; /** Returns a start iterator for the values in this tree. */ Iterator begin() const noexcept { Iterator i (*this); i.next(); return i; } /** Returns an end iterator for the values in this tree. */ Iterator end() const noexcept { Iterator i (*this); i.resetToEnd(); return i; } private: //============================================================================== enum { defaultHashTableSize = 101 }; friend struct Iterator; HashFunctionType hashFunctionToUse; Array<HashEntry*> hashSlots; int totalNumItems; TypeOfCriticalSectionToUse lock; int generateHashFor (KeyTypeParameter key, int numSlots) const { const int hash = hashFunctionToUse.generateHash (key, numSlots); jassert (isPositiveAndBelow (hash, numSlots)); // your hash function is generating out-of-range numbers! return hash; } static inline HashEntry* getEntry (HashEntry* firstEntry, KeyType keyToLookFor) noexcept { for (auto* entry = firstEntry; entry != nullptr; entry = entry->nextEntry) if (entry->key == keyToLookFor) return entry; return nullptr; } inline HashEntry* getSlot (KeyType key) const noexcept { return hashSlots.getUnchecked (generateHashFor (key, getNumSlots())); } JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (HashMap) }; } // namespace juce
pingdynasty/FirmwareSender
JuceLibraryCode/modules/juce_core/containers/juce_HashMap.h
C
gpl-2.0
18,558
// Copyright 2013 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. #ifndef COMPONENTS_NACL_LOADER_NACL_HELPER_WIN_64_H_ #define COMPONENTS_NACL_LOADER_NACL_HELPER_WIN_64_H_ namespace nacl { int NaClWin64Main(); } #endif
qtekfun/htcDesire820Kernel
external/chromium_org/components/nacl/loader/nacl_helper_win_64.h
C
gpl-2.0
326
// Copyright 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. #ifndef WEBKIT_RENDERER_COMPOSITOR_BINDINGS_WEB_ANIMATION_IMPL_H_ #define WEBKIT_RENDERER_COMPOSITOR_BINDINGS_WEB_ANIMATION_IMPL_H_ #include "base/memory/scoped_ptr.h" #include "third_party/WebKit/public/platform/WebAnimation.h" #include "webkit/renderer/compositor_bindings/webkit_compositor_bindings_export.h" namespace cc { class Animation; } namespace blink { class WebAnimationCurve; } namespace webkit { class WebAnimationImpl : public blink::WebAnimation { public: WEBKIT_COMPOSITOR_BINDINGS_EXPORT WebAnimationImpl( const blink::WebAnimationCurve& curve, TargetProperty target, int animation_id, int group_id); virtual ~WebAnimationImpl(); virtual int id(); virtual TargetProperty targetProperty() const; virtual int iterations() const; virtual void setIterations(int iterations); virtual double startTime() const; virtual void setStartTime(double monotonic_time); virtual double timeOffset() const; virtual void setTimeOffset(double monotonic_time); virtual bool alternatesDirection() const; virtual void setAlternatesDirection(bool alternates); scoped_ptr<cc::Animation> PassAnimation(); private: scoped_ptr<cc::Animation> animation_; DISALLOW_COPY_AND_ASSIGN(WebAnimationImpl); }; } #endif
qtekfun/htcDesire820Kernel
external/chromium_org/webkit/renderer/compositor_bindings/web_animation_impl.h
C
gpl-2.0
1,441
#php常用函数 [TOC] ##写入文件 1. 打开资源(文件)fopen($filename,$mode) 2. 写文件fwrite($handle,$str) 3. 关闭文件fclose($handle) 4. 一步写入file_put_contents($filename,$str,$mode) FILE_APPEND LOCK_EX } ##读文件 1. 读文件fread($handle,字节数) 2. 读一行fgets($handle); 3. 读一个字符fgetc($handle) 4. 读成一个数组中file($filename) 5. 一步读取file_get_contents($filename) ##目录操作 1. 建目录mkdir($dirname) 2. 删除目录rmdir($dirname) 3. 打开目录句柄opendir($dirname) 4. 读取目录条数readdir($handle) 5. 关闭目录资源closedir($handle) 6. 重置目录资源rewinddir($dirname); ##目录和文件操作 1. 检查文件或目录是否存在file_exists($filename) 2. 文件或者目录重命名rename($file) ##文件操作 1. 拷贝文件copy('原文件','目标文件') 2. 删除文件unlink($filename) 3. 获取文件大小filesize($filename) 4. 取得文件的创建时间filectime($filename) 5. 取得文件的访问时间fileatime($filename) 6. 取得文件的修改时间filemtime($filename) ##路径操作 1. 获取路径dirname($path) 2. 获取文件名basename($path) 3. 获取路径信息pathinfo($path) ##数组函数(极其重要) 1. 在数组的开头插入一个元素array_unshift($arr,$v) 2. 在数组的尾部添加数组元素array_push($arr,$v,$v1...) 3. 将数组的第一个元素移出,并返回此元素array_shift($arr) 4. 在数组的尾部删除元素array_pop($arr) 5. 将数组用$separator连接成一个字符串implode($a,$arr) 6. 检测变量是否是数组is_array($arr) 7. 获得数组的键名array_keys($arr) 8. 获得数组的值array_values($arr) 9. 检索$value是否在$arr中,返回布尔值in_array($v,$arr) 10. 检索数组$arr中,是否有$key这个键名array_key_exists($k,$arr) 11. 检索$value是否在$arr中,若存在返回键名Array_search($value, $arr) 12. 将一个数组逆向排序,如果第二个参数为true,则保持键名Array_reverse($arr, true) 13. 交换数组的键和值 Array_flip($arr) 14. 统计数组元素的个数 Count($arr) 15. 统计数组中所有值的出现次数 Array_count_values($arr) 16. 移除数组中的重复值 Array_unique($arr) 17. 值由小到大排序 Sort($arr) 18. 值由大到小排序 Rsort($arr) 19. 键由小到大排序 ksort($arr) 20. 键由大到小排序 krsort($arr) 21. 随机从数组中取得$num个元素 Array_rand($arr, $num) 22. 对数组的所有元素求和Array_sum($arr) 23. 合并数组 array_merge($arr,$arr) ##字符串函数(极其重要) 1. 输出字符串 echo($str) echo 2. 原样输出(区分单引号和双引号) print($str) 3. 输出字符串,结束脚本执行 Die($str):die($str) die; 4. 输出字符串,结束脚本执行 exit($str) exit; 5. 输出格式化字符串 printf($str,$p1,...) 6. 不直接输出格式化的字符串,返回格式化的字符串,保存到变量中 sprintf($str,$p1,...) 7. 打印变量的相关信息 var_dump($p) 8. 字符串转换为小写 strtolower($str) 9. 字符串转换为大写 strtoupper($str) 10. 将字符串的第一个字符转换为大写 ucfirst($str) 11. 将字符串中每个单词转换为大写 ucwords($str) 12. 去除字符串两端的空白字符。 Trim($str,' ,') 13. 去除字符串左边空白字符。 Ltrim($str) 14. 去除字符串右边空白字符。Rtrim($str) 空白字符:"","\t","\n","\r",”\0” 15. 取得字符串长度 strlen($str) 16. 统计包含的字符串个数 substr_count($str,’子串’) 17. 返回字符串$string中由$start开始,长度为$length的子字符串 Substr($string ,$start[,$length]) 18. 返回字符串$string中,$search第一次出现到字符串结束的子字符串。 Strstr($string,$search) 19. 查找$search在$str中第一次位的置,从$offset开始。 Strpos($str,$search[,int $offset]) 20. 查找$search在$str中最后一次的位置,从$offset开始 Strrpos($str,$search[,int $offset]) 21. 替换$str中的全部$search为 $replace。 Str_replace($search,$replace,$str) 22. 重复输出指定的字符串 Str_repeat() 23. 加密字符串 Md5() 24. 字符串翻转 Strrev() 25. 使用一个字符串分割另一个字符串,形成一个数组//把字符串变成数组 Explode(“分隔符”,$str);
huadian18/my_note
note/text.md
Markdown
gpl-2.0
4,266
<?php /* * @version $Id: HEADER 15930 2011-10-30 15:47:55Z tsmr $ ------------------------------------------------------------------------- ocsinventoryng plugin for GLPI Copyright (C) 2015-2022 by the ocsinventoryng Development Team. https://github.com/pluginsGLPI/ocsinventoryng ------------------------------------------------------------------------- LICENSE This file is part of ocsinventoryng. ocsinventoryng 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. ocsinventoryng 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 ocsinventoryng. If not, see <http://www.gnu.org/licenses/>. -------------------------------------------------------------------------- */ if (!defined('GLPI_ROOT')) { die("Sorry. You can't access directly to this file"); } /** * Class PluginOcsinventoryngRuleImportEntity */ class PluginOcsinventoryngRuleImportEntity extends CommonDBTM { static $rightname = "plugin_ocsinventoryng"; const NO_RULE = 0; /** * @param int $nb * * @return translated */ static function getTypeName($nb = 0) { return __('Elements not match with the rule', 'ocsinventoryng'); } /** * @param $name * * @return array */ static function cronInfo($name) { switch ($name) { case "CheckRuleImportEntity" : return ['description' => __('OCSNG', 'ocsinventoryng') . " - " . __('Alerts on computers that no longer respond the rules for assigning an item to an entity', 'ocsinventoryng')]; } } /** * Checking machines that no longer respond the assignment rules * * @param $task * * @return int */ static function cronCheckRuleImportEntity($task) { global $DB, $CFG_GLPI; ini_set("memory_limit", "-1"); ini_set("max_execution_time", "0"); if (!$CFG_GLPI["notifications_mailing"]) { return 0; } $CronTask = new CronTask(); if ($CronTask->getFromDBbyName("PluginOcsinventoryngRuleImportEntity", "CheckRuleImportEntity")) { if ($CronTask->fields["state"] == CronTask::STATE_DISABLE) { return 0; } } else { return 0; } $cron_status = 0; $plugin_ocsinventoryng_ocsservers_id = 0; foreach ($DB->request("glpi_plugin_ocsinventoryng_ocsservers", "`is_active` = 1 AND `use_checkruleimportentity` = 1") as $config) { $plugin_ocsinventoryng_ocsservers_id = $config["id"]; $plugin_ocsinventoryng_ocsservers_name = $config["name"]; if ($plugin_ocsinventoryng_ocsservers_id > 0) { $computers = self::checkRuleImportEntity($plugin_ocsinventoryng_ocsservers_id); foreach ($computers as $entities_id => $items) { $message = $plugin_ocsinventoryng_ocsservers_name . ": <br />" . sprintf(__('Items that do not meet the allocation rules for the entity %s: %s', 'ocsinventoryng'), Dropdown::getDropdownName("glpi_entities", $entities_id), count($items)) . "<br />"; if (NotificationEvent::raiseEvent("CheckRuleImportEntity", new PluginOcsinventoryngRuleImportEntity(), ['entities_id' => $entities_id, 'items' => $items])) { $cron_status = 1; if ($task) { $task->addVolume(1); $task->log($message); } else { Session::addMessageAfterRedirect($message); } } else { if ($task) { $task->addVolume(count($items)); $task->log($message . "\n"); } else { Session::addMessageAfterRedirect($message); } } } } } return $cron_status; } /** * Checks the assignment rules for the server computers * * @param $plugin_ocsinventoryng_ocsservers_id * * @return array */ static function checkRuleImportEntity($plugin_ocsinventoryng_ocsservers_id) { $data = []; $computers = self::getComputerOcsLink($plugin_ocsinventoryng_ocsservers_id); $ruleCollection = new RuleImportEntityCollection(); $ruleAsset = new RuleAssetCollection(); foreach ($computers as $computer) { $fields = $ruleCollection->processAllRules($computer, [], ['ocsid' => $computer['ocsid']]); //case pc matched with a rule if (isset($fields['_ruleid'])) { $entities_id = $computer['entities_id']; //Verification of the entity and location if (isset($fields['entities_id']) && $fields['entities_id'] != $entities_id) { if (!isset($data[$entities_id])) { $data[$entities_id] = []; } $data[$entities_id][$computer['id']] = $computer; $data[$entities_id][$computer['id']]['ruleid'] = $fields['_ruleid']; $rule = new Rule(); $rule->getFromDB($fields['_ruleid']); $data[$entities_id][$computer['id']]['rule_name'] = $rule->fields['name']; if (isset($fields['entities_id']) && $fields['entities_id'] != $entities_id) { if (!isset($data[$fields['entities_id']])) { $data[$fields['entities_id']] = []; } $data[$entities_id][$computer['id']]['error'][] = 'Entity'; $data[$entities_id][$computer['id']]['dataerror'][] = $fields['entities_id']; $data[$fields['entities_id']][$computer['id']] = $data[$entities_id][$computer['id']]; } } $output = ['locations_id' => $computer['locations_id']]; $fields = $ruleAsset->processAllRules($computer, $output, ['ocsid' => $computer['ocsid']]); if (isset($fields['locations_id']) && $fields['locations_id'] != $computer['locations_id'] || !isset($fields['locations_id']) && $computer['locations_id'] != 0) { if(!isset($data[$entities_id][$computer['id']])) { $data[$entities_id][$computer['id']] = $computer; } $data[$entities_id][$computer['id']]['error'][] = 'Location'; $data[$entities_id][$computer['id']]['dataerror'][] = $fields['locations_id']; } } else { //No rules match $entities_id = $computer['entities_id']; if (!isset($data[$entities_id])) { $data[$entities_id] = []; } $data[$entities_id][$computer['id']] = $computer; $data[$entities_id][$computer['id']]['error'][] = self::NO_RULE; } } return $data; } /** * @param $plugin_ocsinventoryng_ocsservers_id * * @return array */ static function getComputerOcsLink($plugin_ocsinventoryng_ocsservers_id) { $ocslink = new PluginOcsinventoryngOcslink(); $ocslinks = $ocslink->find(["plugin_ocsinventoryng_ocsservers_id" => $plugin_ocsinventoryng_ocsservers_id], ["entities_id"]); $computers = []; foreach ($ocslinks as $ocs) { $computer = new Computer(); if ($computer->getFromDB($ocs['computers_id'])) { $computer_id = $computer->fields['id']; $computers[$computer_id] = $computer->fields; $computers[$computer_id]['ocsservers_id'] = $ocs['plugin_ocsinventoryng_ocsservers_id']; $computers[$computer_id]['ocsid'] = $ocs['ocsid']; $computers[$computer_id]['_source'] = 'ocsinventoryng'; $computers[$computer_id]['_auto'] = true; } } return $computers; } }
pluginsGLPI/ocsinventoryng
inc/ruleimportentity.class.php
PHP
gpl-2.0
8,763
package ika.geo.grid; import ika.geo.GeoGrid; import ika.geo.GeoObject; import ika.geoexport.ESRIASCIIGridExporter; import ika.geoimport.EsriASCIIGridReader; import java.io.IOException; import java.util.logging.Level; import java.util.logging.Logger; /** * Multiply the cell values of two grids. * @author Bernhard Jenny, Institute of Cartography, ETH Zurich. */ public class GridMultiplyOperator implements GridOperator{ public static void main(String[] args) { try { String f1 = ika.utils.FileUtils.askFile(null, "Grid 1 (ESRI ASCII format)", true); if (f1 == null) { System.exit(0); } String f2 = ika.utils.FileUtils.askFile(null, "Grid 2 (ESRI ASCII format)", true); if (f2 == null) { System.exit(0); } GeoGrid grid1 = EsriASCIIGridReader.read(f1); GeoGrid grid2 = EsriASCIIGridReader.read(f2); GeoGrid res = new GridMultiplyOperator().operate(grid1, grid2); String resFilePath = ika.utils.FileUtils.askFile(null, "Result Grid (ESRI ASCII format)", false); if (resFilePath != null) { ESRIASCIIGridExporter.export(res, resFilePath); } System.exit(0); } catch (IOException ex) { Logger.getLogger(GridMultiplyOperator.class.getName()).log(Level.SEVERE, null, ex); } } public String getName() { return "Multiply"; } public GeoObject operate(GeoGrid geoGrid) { throw new UnsupportedOperationException("Not supported yet."); } public GeoGrid operate(GeoGrid grid1, GeoGrid grid2) { if (!grid1.hasSameExtensionAndResolution(grid2)) { throw new IllegalArgumentException("grids of different size"); } final int nrows = grid1.getRows(); final int ncols = grid1.getCols(); GeoGrid newGrid = new GeoGrid(ncols, nrows, grid1.getCellSize()); newGrid.setWest(grid1.getWest()); newGrid.setNorth(grid1.getNorth()); float[][] src1 = grid1.getGrid(); float[][] src2 = grid2.getGrid(); float[][] dstGrid = newGrid.getGrid(); for (int row = 0; row < nrows; ++row) { float[] srcRow1 = src1[row]; float[] srcRow2 = src2[row]; float[] dstRow = dstGrid[row]; for (int col = 0; col < ncols; ++col) { dstRow[col] = srcRow1[col] * srcRow2[col]; } } return newGrid; } }
OSUCartography/FlexProjector
src/ika/geo/grid/GridMultiplyOperator.java
Java
gpl-2.0
2,585
/* * Asterisk -- An open source telephony toolkit. * * Copyright (C) 1999 - 2005, Digium, Inc. * * Mark Spencer <markster@digium.com> * * See http://www.asterisk.org for more information about * the Asterisk project. Please do not directly contact * any of the maintainers of this project for assistance; * the project provides a web site, mailing lists and IRC * channels for your use. * * This program is free software, distributed under the terms of * the GNU General Public License Version 2. See the LICENSE file * at the top of the source tree. */ /*! \file * * \brief GTK Console monitor -- very kludgy right now * */ /* * I know this might seem somewhat pointless in its current phase, but one * of the most important parts of this module is demonstrate that modules * can require other external libraries and still be loaded (in this * case, a host of libraries involving gtk), so long as they are properly * linked (see the Makefile) */ #include <sys/types.h> #include <stdlib.h> #include <fcntl.h> #include <unistd.h> #include <stdio.h> #include <string.h> #include <stdarg.h> #include <signal.h> #include <sys/time.h> #include <gtk/gtk.h> #include <glib.h> #include "asterisk.h" ASTERISK_FILE_VERSION(__FILE__, "$Revision: 43269 $") #include "asterisk/pbx.h" #include "asterisk/config.h" #include "asterisk/module.h" #include "asterisk/logger.h" #include "asterisk/options.h" #include "asterisk/cli.h" #include "asterisk/utils.h" AST_MUTEX_DEFINE_STATIC(verb_lock); static pthread_t console_thread; static int inuse=0; static int clipipe[2]; static int cleanupid = -1; static char *dtext = "Asterisk PBX Console (GTK Version)"; static GtkWidget *window; static GtkWidget *quit; static GtkWidget *closew; static GtkWidget *verb; static GtkWidget *modules; static GtkWidget *statusbar; static GtkWidget *cli; static struct timeval last; static void update_statusbar(char *msg) { gtk_statusbar_pop(GTK_STATUSBAR(statusbar), 1); gtk_statusbar_push(GTK_STATUSBAR(statusbar), 1, msg); } int unload_module(void) { if (inuse) { /* Kill off the main thread */ pthread_cancel(console_thread); gdk_threads_enter(); gtk_widget_destroy(window); gdk_threads_leave(); close(clipipe[0]); close(clipipe[1]); } return 0; } static int cleanup(void *useless) { gdk_threads_enter(); gtk_clist_thaw(GTK_CLIST(verb)); gtk_widget_queue_resize(verb->parent); gtk_clist_moveto(GTK_CLIST(verb), GTK_CLIST(verb)->rows - 1, 0, 0, 0); cleanupid = -1; gdk_threads_leave(); return 0; } static void __verboser(const char *stuff, int opos, int replacelast, int complete) { char *s2[2]; struct timeval tv; int ms; s2[0] = (char *)stuff; s2[1] = NULL; gtk_clist_freeze(GTK_CLIST(verb)); if (replacelast) gtk_clist_remove(GTK_CLIST(verb), GTK_CLIST(verb)->rows - 1); gtk_clist_append(GTK_CLIST(verb), s2); if (!ast_tvzero(last)) { gdk_threads_leave(); gettimeofday(&tv, NULL); if (cleanupid > -1) gtk_timeout_remove(cleanupid); ms = ast_tvdiff_ms(tv, last); if (ms < 100) { /* We just got a message within 100ms, so just schedule an update in the near future */ cleanupid = gtk_timeout_add(200, cleanup, NULL); } else { cleanup(&cleanupid); } last = tv; } else { gettimeofday(&last, NULL); } } static void verboser(const char *stuff, int opos, int replacelast, int complete) { ast_mutex_lock(&verb_lock); /* Lock appropriately if we're really being called in verbose mode */ __verboser(stuff, opos, replacelast, complete); ast_mutex_unlock(&verb_lock); } static void cliinput(void *data, int source, GdkInputCondition ic) { static char buf[256]; static int offset = 0; int res; char *c; char *l; char n; /* Read as much stuff is there */ res = read(source, buf + offset, sizeof(buf) - 1 - offset); if (res > -1) buf[res + offset] = '\0'; /* make sure we've null terminated whatever we have so far */ c = buf; l = buf; while(*c) { if (*c == '\n') { /* Keep the trailing \n */ c++; n = *c; *c = '\0'; __verboser(l, 0, 0, 1); *(c - 1) = '\0'; *c = n; l = c; } else c++; } if (strlen(l)) { /* We have some left over */ memmove(buf, l, strlen(l) + 1); offset = strlen(buf); } else { offset = 0; } } static void remove_module(void) { int res; char *module; char buf[256]; if (GTK_CLIST(modules)->selection) { module= (char *)gtk_clist_get_row_data(GTK_CLIST(modules), (int) GTK_CLIST(modules)->selection->data); gdk_threads_leave(); res = ast_unload_resource(module, 0); gdk_threads_enter(); if (res) { snprintf(buf, sizeof(buf), "Module '%s' is in use", module); update_statusbar(buf); } else { snprintf(buf, sizeof(buf), "Module '%s' removed", module); update_statusbar(buf); } } } static void reload_module(void) { int res, x; char *module; char buf[256]; if (GTK_CLIST(modules)->selection) { module= (char *)gtk_clist_get_row_data(GTK_CLIST(modules), (int) GTK_CLIST(modules)->selection->data); module = strdup(module); if (module) { gdk_threads_leave(); res = ast_unload_resource(module, 0); gdk_threads_enter(); if (res) { snprintf(buf, sizeof(buf), "Module '%s' is in use", module); update_statusbar(buf); } else { gdk_threads_leave(); res = ast_load_resource(module); gdk_threads_enter(); if (res) { snprintf(buf, sizeof(buf), "Error reloading module '%s'", module); } else { snprintf(buf, sizeof(buf), "Module '%s' reloaded", module); } for (x=0; x < GTK_CLIST(modules)->rows; x++) { if (!strcmp((char *)gtk_clist_get_row_data(GTK_CLIST(modules), x), module)) { gtk_clist_select_row(GTK_CLIST(modules), x, -1); break; } } update_statusbar(buf); } free(module); } } } static void file_ok_sel(GtkWidget *w, GtkFileSelection *fs) { char tmp[AST_CONFIG_MAX_PATH]; char *module = gtk_file_selection_get_filename(fs); char buf[256]; snprintf(tmp, sizeof(tmp), "%s/", ast_config_AST_MODULE_DIR); if (!strncmp(module, (char *)tmp, strlen(tmp))) module += strlen(tmp); gdk_threads_leave(); if (ast_load_resource(module)) { snprintf(buf, sizeof(buf), "Error loading module '%s'.", module); update_statusbar(buf); } else { snprintf(buf, sizeof(buf), "Module '%s' loaded", module); update_statusbar(buf); } gdk_threads_enter(); gtk_widget_destroy(GTK_WIDGET(fs)); } static void add_module(void) { char tmp[AST_CONFIG_MAX_PATH]; GtkWidget *filew; snprintf(tmp, sizeof(tmp), "%s/*.so", ast_config_AST_MODULE_DIR); filew = gtk_file_selection_new("Load Module"); gtk_signal_connect(GTK_OBJECT (GTK_FILE_SELECTION(filew)->ok_button), "clicked", GTK_SIGNAL_FUNC(file_ok_sel), filew); gtk_signal_connect_object(GTK_OBJECT (GTK_FILE_SELECTION(filew)->cancel_button), "clicked", GTK_SIGNAL_FUNC(gtk_widget_destroy), GTK_OBJECT(filew)); gtk_file_selection_set_filename(GTK_FILE_SELECTION(filew), (char *)tmp); gtk_widget_show(filew); } static int add_mod(const char *module, const char *description, int usecount, const char *like) { char use[10]; char *pass[4]; int row; snprintf(use, sizeof(use), "%d", usecount); pass[0] = module; pass[1] = description; pass[2] = use; pass[3] = NULL; row = gtk_clist_append(GTK_CLIST(modules), pass); gtk_clist_set_row_data(GTK_CLIST(modules), row, module); return 0; } static int mod_update(void) { char *module= NULL; /* Update the mod stuff */ if (GTK_CLIST(modules)->selection) { module= (char *)gtk_clist_get_row_data(GTK_CLIST(modules), (int) GTK_CLIST(modules)->selection->data); } gtk_clist_freeze(GTK_CLIST(modules)); gtk_clist_clear(GTK_CLIST(modules)); ast_update_module_list(add_mod, NULL); if (module) gtk_clist_select_row(GTK_CLIST(modules), gtk_clist_find_row_from_data(GTK_CLIST(modules), module), -1); gtk_clist_thaw(GTK_CLIST(modules)); return 1; } static void exit_now(GtkWidget *widget, gpointer data) { ast_loader_unregister(mod_update); gtk_main_quit(); inuse--; ast_update_use_count(); ast_unregister_verbose(verboser); ast_unload_resource("pbx_gtkconsole", 0); if (option_verbose > 1) ast_verbose(VERBOSE_PREFIX_2 "GTK Console Monitor Exiting\n"); /* XXX Trying to quit after calling this makes asterisk segfault XXX */ } static void exit_completely(GtkWidget *widget, gpointer data) { #if 0 /* Clever... */ ast_cli_command(clipipe[1], "quit"); #else kill(getpid(), SIGTERM); #endif } static void exit_nicely(GtkWidget *widget, gpointer data) { fflush(stdout); gtk_widget_destroy(window); } static void *consolethread(void *data) { gtk_widget_show(window); gdk_threads_enter(); gtk_main(); gdk_threads_leave(); return NULL; } static int cli_activate(void) { char buf[256] = ""; strncpy(buf, gtk_entry_get_text(GTK_ENTRY(cli)), sizeof(buf) - 1); gtk_entry_set_text(GTK_ENTRY(cli), ""); if (strlen(buf)) { ast_cli_command(clipipe[1], buf); } return TRUE; } static int show_console(void) { GtkWidget *hbox; GtkWidget *wbox; GtkWidget *notebook; GtkWidget *sw; GtkWidget *bbox, *hbbox, *add, *removew, *reloadw; char *modtitles[3] = { "Module", "Description", "Use Count" }; window = gtk_window_new(GTK_WINDOW_TOPLEVEL); statusbar = gtk_statusbar_new(); gtk_widget_show(statusbar); gtk_signal_connect(GTK_OBJECT(window), "delete_event", GTK_SIGNAL_FUNC (exit_nicely), window); gtk_signal_connect(GTK_OBJECT(window), "destroy", GTK_SIGNAL_FUNC (exit_now), window); gtk_container_set_border_width(GTK_CONTAINER(window), 10); quit = gtk_button_new_with_label("Quit Asterisk"); gtk_signal_connect(GTK_OBJECT(quit), "clicked", GTK_SIGNAL_FUNC (exit_completely), window); gtk_widget_show(quit); closew = gtk_button_new_with_label("Close Window"); gtk_signal_connect(GTK_OBJECT(closew), "clicked", GTK_SIGNAL_FUNC (exit_nicely), window); gtk_widget_show(closew); notebook = gtk_notebook_new(); verb = gtk_clist_new(1); gtk_clist_columns_autosize(GTK_CLIST(verb)); sw = gtk_scrolled_window_new(NULL, NULL); gtk_scrolled_window_set_policy(GTK_SCROLLED_WINDOW(sw), GTK_POLICY_AUTOMATIC, GTK_POLICY_ALWAYS); gtk_container_add(GTK_CONTAINER(sw), verb); gtk_widget_show(verb); gtk_widget_show(sw); gtk_widget_set_usize(verb, 640, 400); gtk_notebook_append_page(GTK_NOTEBOOK(notebook), sw, gtk_label_new("Verbose Status")); modules = gtk_clist_new_with_titles(3, modtitles); gtk_clist_columns_autosize(GTK_CLIST(modules)); gtk_clist_set_column_auto_resize(GTK_CLIST(modules), 0, TRUE); gtk_clist_set_column_auto_resize(GTK_CLIST(modules), 1, TRUE); gtk_clist_set_column_auto_resize(GTK_CLIST(modules), 2, TRUE); gtk_clist_set_sort_column(GTK_CLIST(modules), 0); gtk_clist_set_auto_sort(GTK_CLIST(modules), TRUE); gtk_clist_column_titles_passive(GTK_CLIST(modules)); sw = gtk_scrolled_window_new(NULL, NULL); gtk_scrolled_window_set_policy(GTK_SCROLLED_WINDOW(sw), GTK_POLICY_AUTOMATIC, GTK_POLICY_ALWAYS); gtk_container_add(GTK_CONTAINER(sw), modules); gtk_clist_set_selection_mode(GTK_CLIST(modules), GTK_SELECTION_BROWSE); gtk_widget_show(modules); gtk_widget_show(sw); add = gtk_button_new_with_label("Load..."); gtk_widget_show(add); removew = gtk_button_new_with_label("Unload"); gtk_widget_show(removew); reloadw = gtk_button_new_with_label("Reload"); gtk_widget_show(reloadw); gtk_signal_connect(GTK_OBJECT(removew), "clicked", GTK_SIGNAL_FUNC (remove_module), window); gtk_signal_connect(GTK_OBJECT(add), "clicked", GTK_SIGNAL_FUNC (add_module), window); gtk_signal_connect(GTK_OBJECT(reloadw), "clicked", GTK_SIGNAL_FUNC (reload_module), window); bbox = gtk_vbox_new(FALSE, 5); gtk_widget_show(bbox); gtk_widget_set_usize(bbox, 100, -1); gtk_box_pack_start(GTK_BOX(bbox), add, FALSE, FALSE, 5); gtk_box_pack_start(GTK_BOX(bbox), removew, FALSE, FALSE, 5); gtk_box_pack_start(GTK_BOX(bbox), reloadw, FALSE, FALSE, 5); hbbox = gtk_hbox_new(FALSE, 5); gtk_widget_show(hbbox); gtk_box_pack_start(GTK_BOX(hbbox), sw, TRUE, TRUE, 5); gtk_box_pack_start(GTK_BOX(hbbox), bbox, FALSE, FALSE, 5); gtk_notebook_append_page(GTK_NOTEBOOK(notebook), hbbox, gtk_label_new("Module Information")); gtk_widget_show(notebook); wbox = gtk_hbox_new(FALSE, 5); gtk_widget_show(wbox); gtk_box_pack_end(GTK_BOX(wbox), quit, FALSE, FALSE, 5); gtk_box_pack_end(GTK_BOX(wbox), closew, FALSE, FALSE, 5); hbox = gtk_vbox_new(FALSE, 0); gtk_widget_show(hbox); /* Command line */ cli = gtk_entry_new(); gtk_widget_show(cli); gtk_signal_connect(GTK_OBJECT(cli), "activate", GTK_SIGNAL_FUNC (cli_activate), NULL); gtk_box_pack_start(GTK_BOX(hbox), notebook, TRUE, TRUE, 5); gtk_box_pack_start(GTK_BOX(hbox), wbox, FALSE, FALSE, 5); gtk_box_pack_start(GTK_BOX(hbox), cli, FALSE, FALSE, 0); gtk_box_pack_start(GTK_BOX(hbox), statusbar, FALSE, FALSE, 0); gtk_container_add(GTK_CONTAINER(window), hbox); gtk_window_set_title(GTK_WINDOW(window), "Asterisk Console"); gtk_widget_grab_focus(cli); ast_pthread_create(&console_thread, NULL, consolethread, NULL); /* XXX Okay, seriously fix me! XXX */ usleep(100000); ast_register_verbose(verboser); gtk_clist_freeze(GTK_CLIST(verb)); ast_loader_register(mod_update); gtk_clist_thaw(GTK_CLIST(verb)); gdk_input_add(clipipe[0], GDK_INPUT_READ, cliinput, NULL); mod_update(); update_statusbar("Asterisk Console Ready"); return 0; } int load_module(void) { if (pipe(clipipe)) { ast_log(LOG_WARNING, "Unable to create CLI pipe\n"); return -1; } g_thread_init(NULL); if (gtk_init_check(NULL, NULL)) { if (!show_console()) { inuse++; ast_update_use_count(); if (option_verbose > 1) ast_verbose( VERBOSE_PREFIX_2 "Launched GTK Console monitor\n"); } else ast_log(LOG_WARNING, "Unable to start GTK console\n"); } else { if (option_debug) ast_log(LOG_DEBUG, "Unable to start GTK console monitor -- ignoring\n"); if (option_verbose > 1) ast_verbose( VERBOSE_PREFIX_2 "GTK is not available -- skipping monitor\n"); } return 0; } int usecount(void) { return inuse; } char *description(void) { return dtext; } char *key(void) { return ASTERISK_GPL_KEY; }
tpenguin/solarisvoip-asterisk
pbx/pbx_gtkconsole.c
C
gpl-2.0
14,089
#include <stdlib.h> #include <stdio.h> #include <string.h> #include <errno.h> #include "memFun.h" #include "HtLog.h" #include "SrvDef.h" #include "MsqOpr.h" #include "ErrCode.h" #include "DbsDef.h" #include "DbsTbl.h" #include "SrvParam.h" int MemInstSrvMapCreate() { int iRet, nMemDbIndex, nMemTblId; iRet = memdbGetIPCKey(&nMemDbIndex, "tbl_inst_srv_map"); if (iRet) { top_errno = ERR_CODE_MEM_NOTFOUND; snprintf(top_errstr, sizeof(top_errstr), "memdbLink tbl_inst_srv_map error"); return -1; } nMemTblId = gMemdbInfoList.tMemDbInfo[nMemDbIndex].nTblId; memset(&gMemDb[nMemTblId], 0, sizeof(MEMDATABASE)); iRet = CreateMemDB(&gMemDb[nMemTblId], "tbl_inst_srv_map", gMemdbInfoList.tMemDbInfo[nMemTblId].nMemDbKey, gMemdbInfoList.tMemDbInfo[nMemTblId].nMaxRecordNum, sizeof(Tbl_inst_srv_map_Def), 1); if (iRet != T_SUCCESS) { snprintf(top_errstr, sizeof(top_errstr), "CreateMemDB error: [%d], Key: [%d]\n", iRet, gMemdbInfoList.tMemDbInfo[nMemTblId].nMemDbKey); top_errno = ERR_CODE_MEM_CREATE; return -1; } /* Set MemDb Index */ SetKeyMemDB(&gMemDb[nMemTblId], Tbl_inst_srv_map_Def, inst_id, FIELD_CHAR, FIELD_ASC); SetKeyMemDB(&gMemDb[nMemTblId], Tbl_inst_srv_map_Def, srv_id, FIELD_CHAR, FIELD_ASC); return 0; } int MemInstSrvMapLoad(int nMemDbIndex) { int iRet, rownum; Tbl_inst_srv_map_Def tTblInstSrvMap; DbsINSTSRVMAP(DBS_CURSOR, &tTblInstSrvMap); iRet = DbsINSTSRVMAP(DBS_OPEN, &tTblInstSrvMap); if (iRet) { top_errno = ERR_CODE_DBS_CUR_OPEN; snprintf(top_errstr, sizeof(top_errstr), "DbsINSTSRVMAP DBS_OPEN error"); return -1; } rownum = 0; while (1) { memset(&tTblInstSrvMap, 0, sizeof(tTblInstSrvMap)); iRet = DbsINSTSRVMAP(DBS_FETCH, &tTblInstSrvMap); if (iRet == DBS_NOTFOUND) break; if (iRet) { top_errno = ERR_CODE_DBS_CUR_FETCH; snprintf(top_errstr, sizeof(top_errstr), "DbsINSTSRVMAP DBS_FETCH error"); return -1; } MEMTRIM(tTblInstSrvMap.inst_id, 0); MEMTRIM(tTblInstSrvMap.srv_id, 0); iRet = InsertMemDB(&gMemDb[nMemDbIndex], (char*)&tTblInstSrvMap); if (iRet && iRet != T_MDB_DUPKEY) { top_errno = ERR_CODE_MEM_LOAD; snprintf(top_errstr, sizeof(top_errstr), "InsertMemDB tbl_inst_srv_map [%s] [%s] error", tTblInstSrvMap.inst_id, tTblInstSrvMap.srv_id); return -1; } rownum++; } return 0; }
longzl1991/online
src/Mem/MemInstSrvMap.c
C
gpl-2.0
2,712
#include <stdint.h> #include <inttypes.h> #include <util/circlebuf.h> #include <obs-module.h> #ifdef LIBSPEEXDSP_ENABLED #include <speex/speex_preprocess.h> #endif #ifdef LIBRNNOISE_ENABLED #ifdef _MSC_VER #define ssize_t intptr_t #endif #include <rnnoise.h> #include <media-io/audio-resampler.h> #endif bool nvafx_loaded = false; #ifdef LIBNVAFX_ENABLED #include "nvafx-load.h" #include <pthread.h> #endif /* -------------------------------------------------------- */ #define do_log(level, format, ...) \ blog(level, "[noise suppress: '%s'] " format, \ obs_source_get_name(ng->context), ##__VA_ARGS__) #define warn(format, ...) do_log(LOG_WARNING, format, ##__VA_ARGS__) #define info(format, ...) do_log(LOG_INFO, format, ##__VA_ARGS__) #ifdef _DEBUG #define debug(format, ...) do_log(LOG_DEBUG, format, ##__VA_ARGS__) #else #define debug(format, ...) #endif /* -------------------------------------------------------- */ #define S_SUPPRESS_LEVEL "suppress_level" #define S_NVAFX_INTENSITY "intensity" #define S_METHOD "method" #define S_METHOD_SPEEX "speex" #define S_METHOD_RNN "rnnoise" #define S_METHOD_NVAFX "nvafx" #define MT_ obs_module_text #define TEXT_SUPPRESS_LEVEL MT_("NoiseSuppress.SuppressLevel") #define TEXT_NVAFX_INTENSITY MT_("NoiseSuppress.Intensity") #define TEXT_METHOD MT_("NoiseSuppress.Method") #define TEXT_METHOD_SPEEX MT_("NoiseSuppress.Method.Speex") #define TEXT_METHOD_RNN MT_("NoiseSuppress.Method.RNNoise") #define TEXT_METHOD_NVAFX MT_("NoiseSuppress.Method.nvafx") #define MAX_PREPROC_CHANNELS 16 /* RNNoise constants, these can't be changed */ #define RNNOISE_SAMPLE_RATE 48000 #define RNNOISE_FRAME_SIZE 480 /* nvafx constants, these can't be changed */ #define NVAFX_SAMPLE_RATE 48000 #define NVAFX_FRAME_SIZE \ 480 /* the sdk does not explicitly set this as a constant though it relies on it*/ /* If the following constant changes, RNNoise breaks */ #define BUFFER_SIZE_MSEC 10 /* -------------------------------------------------------- */ struct noise_suppress_data { obs_source_t *context; int suppress_level; uint64_t last_timestamp; uint64_t latency; size_t frames; size_t channels; struct circlebuf info_buffer; struct circlebuf input_buffers[MAX_PREPROC_CHANNELS]; struct circlebuf output_buffers[MAX_PREPROC_CHANNELS]; bool use_rnnoise; bool use_nvafx; bool nvafx_enabled; #ifdef LIBSPEEXDSP_ENABLED /* Speex preprocessor state */ SpeexPreprocessState *spx_states[MAX_PREPROC_CHANNELS]; #endif #ifdef LIBRNNOISE_ENABLED /* RNNoise state */ DenoiseState *rnn_states[MAX_PREPROC_CHANNELS]; /* Resampler */ audio_resampler_t *rnn_resampler; audio_resampler_t *rnn_resampler_back; #endif #ifdef LIBNVAFX_ENABLED /* NVAFX handle, one per audio channel */ NvAFX_Handle handle[MAX_PREPROC_CHANNELS]; uint32_t sample_rate; float intensity_ratio; unsigned int num_samples_per_frame, num_channels; char *model; bool nvafx_initialized; /* Resampler */ audio_resampler_t *nvafx_resampler; audio_resampler_t *nvafx_resampler_back; /* Initialization */ bool nvafx_loading; pthread_t nvafx_thread; pthread_mutex_t nvafx_mutex; #endif /* PCM buffers */ float *copy_buffers[MAX_PREPROC_CHANNELS]; #ifdef LIBSPEEXDSP_ENABLED spx_int16_t *spx_segment_buffers[MAX_PREPROC_CHANNELS]; #endif #ifdef LIBRNNOISE_ENABLED float *rnn_segment_buffers[MAX_PREPROC_CHANNELS]; #endif #ifdef LIBNVAFX_ENABLED float *nvafx_segment_buffers[MAX_PREPROC_CHANNELS]; #endif /* output data */ struct obs_audio_data output_audio; DARRAY(float) output_data; }; #ifdef LIBNVAFX_ENABLED /* global mutex for nvafx load functions since they aren't thread-safe */ pthread_mutex_t nvafx_initializer_mutex; #endif /* -------------------------------------------------------- */ #define SUP_MIN -60 #define SUP_MAX 0 static const float c_32_to_16 = (float)INT16_MAX; static const float c_16_to_32 = ((float)INT16_MAX + 1.0f); /* -------------------------------------------------------- */ static const char *noise_suppress_name(void *unused) { UNUSED_PARAMETER(unused); return obs_module_text("NoiseSuppress"); } static void noise_suppress_destroy(void *data) { struct noise_suppress_data *ng = data; #ifdef LIBNVAFX_ENABLED if (ng->nvafx_enabled) pthread_mutex_lock(&ng->nvafx_mutex); #endif for (size_t i = 0; i < ng->channels; i++) { #ifdef LIBSPEEXDSP_ENABLED speex_preprocess_state_destroy(ng->spx_states[i]); #endif #ifdef LIBRNNOISE_ENABLED rnnoise_destroy(ng->rnn_states[i]); #endif #ifdef LIBNVAFX_ENABLED if (ng->handle[0]) { if (NvAFX_DestroyEffect(ng->handle[i]) != NVAFX_STATUS_SUCCESS) { do_log(LOG_ERROR, "NvAFX_Release() failed"); } } #endif circlebuf_free(&ng->input_buffers[i]); circlebuf_free(&ng->output_buffers[i]); } #ifdef LIBSPEEXDSP_ENABLED bfree(ng->spx_segment_buffers[0]); #endif #ifdef LIBRNNOISE_ENABLED bfree(ng->rnn_segment_buffers[0]); if (ng->rnn_resampler) { audio_resampler_destroy(ng->rnn_resampler); audio_resampler_destroy(ng->rnn_resampler_back); } #endif #ifdef LIBNVAFX_ENABLED bfree(ng->nvafx_segment_buffers[0]); if (ng->nvafx_resampler) { audio_resampler_destroy(ng->nvafx_resampler); audio_resampler_destroy(ng->nvafx_resampler_back); } bfree(ng->model); if (ng->nvafx_enabled) { if (ng->use_nvafx) pthread_join(ng->nvafx_thread, NULL); pthread_mutex_unlock(&ng->nvafx_mutex); pthread_mutex_destroy(&ng->nvafx_mutex); } #endif bfree(ng->copy_buffers[0]); circlebuf_free(&ng->info_buffer); da_free(ng->output_data); bfree(ng); } static void *nvafx_initialize(void *data) { #ifdef LIBNVAFX_ENABLED struct noise_suppress_data *ng = data; int err; if (!ng->use_nvafx || !nvafx_loaded) return NULL; pthread_mutex_lock(&ng->nvafx_mutex); pthread_mutex_lock(&nvafx_initializer_mutex); if (!ng->handle[0]) { ng->sample_rate = NVAFX_SAMPLE_RATE; for (int i = 0; i < ng->channels; i++) { err = NvAFX_CreateEffect(NVAFX_EFFECT_DENOISER, &ng->handle[i]); if (err != NVAFX_STATUS_SUCCESS) { do_log(LOG_ERROR, "NvAFX_CreateEffect() failed, error %i", err); goto failure; } err = NvAFX_SetU32(ng->handle[i], NVAFX_PARAM_DENOISER_SAMPLE_RATE, ng->sample_rate); if (err != NVAFX_STATUS_SUCCESS) { do_log(LOG_ERROR, "NvAFX_SetU32(Sample Rate: %f) failed, error %i", ng->sample_rate, err); goto failure; } // initial setting of intensity to 1.0f err = NvAFX_SetFloat( ng->handle[i], NVAFX_PARAM_DENOISER_INTENSITY_RATIO, ng->intensity_ratio); if (err != NVAFX_STATUS_SUCCESS) { do_log(LOG_ERROR, "NvAFX_SetFloat(Intensity Ratio: %f) failed, error %i", 1.0f, err); goto failure; } err = NvAFX_SetString(ng->handle[i], NVAFX_PARAM_DENOISER_MODEL_PATH, ng->model); if (err != NVAFX_STATUS_SUCCESS) { do_log(LOG_ERROR, "NvAFX_SetString() failed, error %i", err); goto failure; } err = NvAFX_Load(ng->handle[i]); if (err != NVAFX_STATUS_SUCCESS) { do_log(LOG_ERROR, "NvAFX_Load() failed with error %i", err); goto failure; } } if (ng->use_nvafx) { err = NvAFX_GetU32(ng->handle[0], NVAFX_PARAM_DENOISER_NUM_CHANNELS, &ng->num_channels); if (err != NVAFX_STATUS_SUCCESS) { do_log(LOG_ERROR, "NvAFX_GetU32() failed to get the number of channels, error %i", err); goto failure; } if (ng->num_channels != 1) { do_log(LOG_ERROR, "The number of channels is not 1 in the sdk any more ==> update code"); goto failure; } NvAFX_Status err = NvAFX_GetU32( ng->handle[0], NVAFX_PARAM_DENOISER_NUM_SAMPLES_PER_FRAME, &ng->num_samples_per_frame); if (err != NVAFX_STATUS_SUCCESS) { do_log(LOG_ERROR, "NvAFX_GetU32() failed to get the number of samples per frame, error %i", err); goto failure; } if (ng->num_samples_per_frame != NVAFX_FRAME_SIZE) { do_log(LOG_ERROR, "The number of samples per frame has changed from 480 (= 10 ms) ==> update code"); goto failure; } } } ng->nvafx_initialized = true; pthread_mutex_unlock(&nvafx_initializer_mutex); pthread_mutex_unlock(&ng->nvafx_mutex); return NULL; failure: ng->use_nvafx = false; pthread_mutex_unlock(&nvafx_initializer_mutex); pthread_mutex_unlock(&ng->nvafx_mutex); return NULL; #else UNUSED_PARAMETER(data); return NULL; #endif } static inline void alloc_channel(struct noise_suppress_data *ng, uint32_t sample_rate, size_t channel, size_t frames) { #ifdef LIBSPEEXDSP_ENABLED ng->spx_states[channel] = speex_preprocess_state_init((int)frames, sample_rate); #endif #ifdef LIBRNNOISE_ENABLED ng->rnn_states[channel] = rnnoise_create(NULL); #endif circlebuf_reserve(&ng->input_buffers[channel], frames * sizeof(float)); circlebuf_reserve(&ng->output_buffers[channel], frames * sizeof(float)); } static inline enum speaker_layout convert_speaker_layout(uint8_t channels) { switch (channels) { case 0: return SPEAKERS_UNKNOWN; case 1: return SPEAKERS_MONO; case 2: return SPEAKERS_STEREO; case 3: return SPEAKERS_2POINT1; case 4: return SPEAKERS_4POINT0; case 5: return SPEAKERS_4POINT1; case 6: return SPEAKERS_5POINT1; case 8: return SPEAKERS_7POINT1; default: return SPEAKERS_UNKNOWN; } } static void noise_suppress_update(void *data, obs_data_t *s) { struct noise_suppress_data *ng = data; uint32_t sample_rate = audio_output_get_sample_rate(obs_get_audio()); size_t channels = audio_output_get_channels(obs_get_audio()); size_t frames = (size_t)sample_rate / (1000 / BUFFER_SIZE_MSEC); const char *method = obs_data_get_string(s, S_METHOD); ng->suppress_level = (int)obs_data_get_int(s, S_SUPPRESS_LEVEL); ng->latency = 1000000000LL / (1000 / BUFFER_SIZE_MSEC); ng->use_rnnoise = strcmp(method, S_METHOD_RNN) == 0; ng->use_nvafx = ng->nvafx_enabled && strcmp(method, S_METHOD_NVAFX) == 0; /* Process 10 millisecond segments to keep latency low */ /* Also RNNoise only supports buffers of this exact size. */ /* At 48kHz, NVAFX processes 480 samples which corresponds to 10 ms.*/ ng->frames = frames; ng->channels = channels; #ifdef LIBNVAFX_ENABLED ng->intensity_ratio = (float)obs_data_get_double(s, S_NVAFX_INTENSITY); if (ng->use_nvafx) { pthread_mutex_lock(&ng->nvafx_mutex); if (ng->nvafx_initialized) { int err; for (int i = 0; i < ng->channels; i++) { err = NvAFX_SetFloat( ng->handle[i], NVAFX_PARAM_DENOISER_INTENSITY_RATIO, ng->intensity_ratio); if (err != NVAFX_STATUS_SUCCESS) { do_log(LOG_ERROR, "NvAFX_SetFloat(Intensity Ratio: %f) failed, error %i", ng->intensity_ratio, err); ng->use_nvafx = false; } } } pthread_mutex_unlock(&ng->nvafx_mutex); } #endif /* Ignore if already allocated */ #if defined(LIBSPEEXDSP_ENABLED) if (!ng->use_rnnoise && !ng->use_nvafx && ng->spx_states[0]) return; #endif #ifdef LIBNVAFX_ENABLED if (ng->use_nvafx && (ng->nvafx_initialized || ng->nvafx_loading)) return; #endif #ifdef LIBRNNOISE_ENABLED if (ng->use_rnnoise && ng->rnn_states[0]) return; #endif /* One speex/rnnoise state for each channel (limit 2) */ ng->copy_buffers[0] = bmalloc(frames * channels * sizeof(float)); #ifdef LIBSPEEXDSP_ENABLED ng->spx_segment_buffers[0] = bmalloc(frames * channels * sizeof(spx_int16_t)); #endif #ifdef LIBRNNOISE_ENABLED ng->rnn_segment_buffers[0] = bmalloc(RNNOISE_FRAME_SIZE * channels * sizeof(float)); #endif #ifdef LIBNVAFX_ENABLED ng->nvafx_segment_buffers[0] = bmalloc(NVAFX_FRAME_SIZE * channels * sizeof(float)); #endif for (size_t c = 1; c < channels; ++c) { ng->copy_buffers[c] = ng->copy_buffers[c - 1] + frames; #ifdef LIBSPEEXDSP_ENABLED ng->spx_segment_buffers[c] = ng->spx_segment_buffers[c - 1] + frames; #endif #ifdef LIBRNNOISE_ENABLED ng->rnn_segment_buffers[c] = ng->rnn_segment_buffers[c - 1] + RNNOISE_FRAME_SIZE; #endif #ifdef LIBNVAFX_ENABLED ng->nvafx_segment_buffers[c] = ng->nvafx_segment_buffers[c - 1] + NVAFX_FRAME_SIZE; #endif } #ifdef LIBNVAFX_ENABLED if (!ng->nvafx_initialized && ng->use_nvafx && !ng->nvafx_loading) { ng->nvafx_loading = true; pthread_create(&ng->nvafx_thread, NULL, nvafx_initialize, ng); } #endif for (size_t i = 0; i < channels; i++) alloc_channel(ng, sample_rate, i, frames); #ifdef LIBRNNOISE_ENABLED if (sample_rate == RNNOISE_SAMPLE_RATE) { ng->rnn_resampler = NULL; ng->rnn_resampler_back = NULL; } else { struct resample_info src, dst; src.samples_per_sec = sample_rate; src.format = AUDIO_FORMAT_FLOAT_PLANAR; src.speakers = convert_speaker_layout((uint8_t)channels); dst.samples_per_sec = RNNOISE_SAMPLE_RATE; dst.format = AUDIO_FORMAT_FLOAT_PLANAR; dst.speakers = convert_speaker_layout((uint8_t)channels); ng->rnn_resampler = audio_resampler_create(&dst, &src); ng->rnn_resampler_back = audio_resampler_create(&src, &dst); } #endif #ifdef LIBNVAFX_ENABLED if (sample_rate == NVAFX_SAMPLE_RATE) { ng->nvafx_resampler = NULL; ng->nvafx_resampler_back = NULL; } else { struct resample_info src, dst; src.samples_per_sec = sample_rate; src.format = AUDIO_FORMAT_FLOAT_PLANAR; src.speakers = convert_speaker_layout((uint8_t)channels); dst.samples_per_sec = NVAFX_SAMPLE_RATE; dst.format = AUDIO_FORMAT_FLOAT_PLANAR; dst.speakers = convert_speaker_layout((uint8_t)channels); ng->nvafx_resampler = audio_resampler_create(&dst, &src); ng->nvafx_resampler_back = audio_resampler_create(&src, &dst); } #endif } #ifdef _MSC_VER #pragma warning(push) #pragma warning(disable : 4706) #endif bool load_nvafx(void) { #ifdef LIBNVAFX_ENABLED if (!load_lib()) { blog(LOG_INFO, "[noise suppress: Nvidia RTX denoiser disabled, redistributable not found]"); return false; } pthread_mutex_init(&nvafx_initializer_mutex, PTHREAD_MUTEX_DEFAULT); #define LOAD_SYM_FROM_LIB(sym, lib, dll) \ if (!(sym = (sym##_t)GetProcAddress(lib, #sym))) { \ DWORD err = GetLastError(); \ printf("[noise suppress: Couldn't load " #sym " from " dll \ ": %lu (0x%lx)]", \ err, err); \ goto unload_everything; \ } #define LOAD_SYM(sym) LOAD_SYM_FROM_LIB(sym, nv_audiofx, "NVAudioEffects.dll") LOAD_SYM(NvAFX_GetEffectList); LOAD_SYM(NvAFX_CreateEffect); LOAD_SYM(NvAFX_DestroyEffect); LOAD_SYM(NvAFX_SetU32); LOAD_SYM(NvAFX_SetString); LOAD_SYM(NvAFX_SetFloat); LOAD_SYM(NvAFX_GetU32); LOAD_SYM(NvAFX_GetString); LOAD_SYM(NvAFX_GetFloat); LOAD_SYM(NvAFX_Load); LOAD_SYM(NvAFX_Run); #undef LOAD_SYM int err; NvAFX_Handle h = NULL; err = NvAFX_CreateEffect(NVAFX_EFFECT_DENOISER, &h); if (err != NVAFX_STATUS_SUCCESS) { if (err == NVAFX_STATUS_GPU_UNSUPPORTED) { blog(LOG_INFO, "[noise suppress: Nvidia RTX denoiser disabled: unsupported GPU]"); } else { blog(LOG_ERROR, "[noise suppress: Nvidia RTX denoiser disabled: error %i", err); } goto unload_everything; } err = NvAFX_DestroyEffect(h); if (err != NVAFX_STATUS_SUCCESS) { blog(LOG_ERROR, "NvAFX_DestroyEffect() failed, error %i", err); goto unload_everything; } nvafx_loaded = true; blog(LOG_INFO, "[noise suppress: Nvidia RTX denoiser enabled]"); return true; unload_everything: release_lib(); #endif return false; } #ifdef _MSC_VER #pragma warning(pop) #endif static void *noise_suppress_create(obs_data_t *settings, obs_source_t *filter) { struct noise_suppress_data *ng = bzalloc(sizeof(struct noise_suppress_data)); ng->context = filter; #ifdef LIBNVAFX_ENABLED char sdk_path[MAX_PATH]; if (!nvafx_get_sdk_path(sdk_path, sizeof(sdk_path))) { ng->nvafx_enabled = false; do_log(LOG_ERROR, "NVAFX redist is not installed."); } else { const char *file = "\\models\\denoiser_48k.trtpkg"; size_t size = strlen(sdk_path) + strlen(file) + 1; char *buffer = (char *)bmalloc(size); strcpy(buffer, sdk_path); strcat(buffer, file); ng->model = buffer; ng->nvafx_enabled = true; ng->nvafx_initialized = false; ng->nvafx_loading = false; pthread_mutex_init(&ng->nvafx_mutex, PTHREAD_MUTEX_DEFAULT); info("NVAFX SDK redist path was found here %s", sdk_path); } #endif noise_suppress_update(ng, settings); return ng; } static inline void process_speexdsp(struct noise_suppress_data *ng) { #ifdef LIBSPEEXDSP_ENABLED /* Set args */ for (size_t i = 0; i < ng->channels; i++) speex_preprocess_ctl(ng->spx_states[i], SPEEX_PREPROCESS_SET_NOISE_SUPPRESS, &ng->suppress_level); /* Convert to 16bit */ for (size_t i = 0; i < ng->channels; i++) for (size_t j = 0; j < ng->frames; j++) { float s = ng->copy_buffers[i][j]; if (s > 1.0f) s = 1.0f; else if (s < -1.0f) s = -1.0f; ng->spx_segment_buffers[i][j] = (spx_int16_t)(s * c_32_to_16); } /* Execute */ for (size_t i = 0; i < ng->channels; i++) speex_preprocess_run(ng->spx_states[i], ng->spx_segment_buffers[i]); /* Convert back to 32bit */ for (size_t i = 0; i < ng->channels; i++) for (size_t j = 0; j < ng->frames; j++) ng->copy_buffers[i][j] = (float)ng->spx_segment_buffers[i][j] / c_16_to_32; #endif } static inline void process_rnnoise(struct noise_suppress_data *ng) { #ifdef LIBRNNOISE_ENABLED /* Adjust signal level to what RNNoise expects, resample if necessary */ if (ng->rnn_resampler) { float *output[MAX_PREPROC_CHANNELS]; uint32_t out_frames; uint64_t ts_offset; audio_resampler_resample(ng->rnn_resampler, (uint8_t **)output, &out_frames, &ts_offset, (const uint8_t **)ng->copy_buffers, (uint32_t)ng->frames); for (size_t i = 0; i < ng->channels; i++) { for (ssize_t j = 0, k = (ssize_t)out_frames - RNNOISE_FRAME_SIZE; j < RNNOISE_FRAME_SIZE; ++j, ++k) { if (k >= 0) { ng->rnn_segment_buffers[i][j] = output[i][k] * 32768.0f; } else { ng->rnn_segment_buffers[i][j] = 0; } } } } else { for (size_t i = 0; i < ng->channels; i++) { for (size_t j = 0; j < RNNOISE_FRAME_SIZE; ++j) { ng->rnn_segment_buffers[i][j] = ng->copy_buffers[i][j] * 32768.0f; } } } /* Execute */ for (size_t i = 0; i < ng->channels; i++) { rnnoise_process_frame(ng->rnn_states[i], ng->rnn_segment_buffers[i], ng->rnn_segment_buffers[i]); } /* Revert signal level adjustment, resample back if necessary */ if (ng->rnn_resampler) { float *output[MAX_PREPROC_CHANNELS]; uint32_t out_frames; uint64_t ts_offset; audio_resampler_resample( ng->rnn_resampler_back, (uint8_t **)output, &out_frames, &ts_offset, (const uint8_t **)ng->rnn_segment_buffers, RNNOISE_FRAME_SIZE); for (size_t i = 0; i < ng->channels; i++) { for (ssize_t j = 0, k = (ssize_t)out_frames - ng->frames; j < (ssize_t)ng->frames; ++j, ++k) { if (k >= 0) { ng->copy_buffers[i][j] = output[i][k] / 32768.0f; } else { ng->copy_buffers[i][j] = 0; } } } } else { for (size_t i = 0; i < ng->channels; i++) { for (size_t j = 0; j < RNNOISE_FRAME_SIZE; ++j) { ng->copy_buffers[i][j] = ng->rnn_segment_buffers[i][j] / 32768.0f; } } } #else UNUSED_PARAMETER(ng); #endif } static inline void process_nvafx(struct noise_suppress_data *ng) { #ifdef LIBNVAFX_ENABLED if (nvafx_loaded && ng->use_nvafx && ng->nvafx_initialized) { /* Resample if necessary */ if (ng->nvafx_resampler) { float *output[MAX_PREPROC_CHANNELS]; uint32_t out_frames; uint64_t ts_offset; audio_resampler_resample( ng->nvafx_resampler, (uint8_t **)output, &out_frames, &ts_offset, (const uint8_t **)ng->copy_buffers, (uint32_t)ng->frames); for (size_t i = 0; i < ng->channels; i++) { for (ssize_t j = 0, k = (ssize_t)out_frames - NVAFX_FRAME_SIZE; j < NVAFX_FRAME_SIZE; ++j, ++k) { if (k >= 0) { ng->nvafx_segment_buffers[i][j] = output[i][k]; } else { ng->nvafx_segment_buffers[i][j] = 0; } } } } else { for (size_t i = 0; i < ng->channels; i++) { for (size_t j = 0; j < NVAFX_FRAME_SIZE; ++j) { ng->nvafx_segment_buffers[i][j] = ng->copy_buffers[i][j]; } } } /* Execute */ for (size_t i = 0; i < ng->channels; i++) { NvAFX_Status err = NvAFX_Run( ng->handle[i], &ng->nvafx_segment_buffers[i], &ng->nvafx_segment_buffers[i], ng->num_samples_per_frame, ng->num_channels); if (err != NVAFX_STATUS_SUCCESS) do_log(LOG_ERROR, "NvAFX_Run() failed, error %i", err); } /* Revert signal level adjustment, resample back if necessary */ if (ng->nvafx_resampler) { float *output[MAX_PREPROC_CHANNELS]; uint32_t out_frames; uint64_t ts_offset; audio_resampler_resample( ng->nvafx_resampler_back, (uint8_t **)output, &out_frames, &ts_offset, (const uint8_t **)ng->nvafx_segment_buffers, NVAFX_FRAME_SIZE); for (size_t i = 0; i < ng->channels; i++) { for (ssize_t j = 0, k = (ssize_t)out_frames - ng->frames; j < (ssize_t)ng->frames; ++j, ++k) { if (k >= 0) { ng->copy_buffers[i][j] = output[i][k]; } else { ng->copy_buffers[i][j] = 0; } } } } else { for (size_t i = 0; i < ng->channels; i++) { for (size_t j = 0; j < NVAFX_FRAME_SIZE; ++j) { ng->copy_buffers[i][j] = ng->nvafx_segment_buffers[i][j]; } } } } #else UNUSED_PARAMETER(ng); #endif } static inline void process(struct noise_suppress_data *ng) { /* Pop from input circlebuf */ for (size_t i = 0; i < ng->channels; i++) circlebuf_pop_front(&ng->input_buffers[i], ng->copy_buffers[i], ng->frames * sizeof(float)); if (ng->use_rnnoise) { process_rnnoise(ng); } else if (ng->use_nvafx) { if (nvafx_loaded) { process_nvafx(ng); } } else { process_speexdsp(ng); } /* Push to output circlebuf */ for (size_t i = 0; i < ng->channels; i++) circlebuf_push_back(&ng->output_buffers[i], ng->copy_buffers[i], ng->frames * sizeof(float)); } struct ng_audio_info { uint32_t frames; uint64_t timestamp; }; static inline void clear_circlebuf(struct circlebuf *buf) { circlebuf_pop_front(buf, NULL, buf->size); } static void reset_data(struct noise_suppress_data *ng) { for (size_t i = 0; i < ng->channels; i++) { clear_circlebuf(&ng->input_buffers[i]); clear_circlebuf(&ng->output_buffers[i]); } clear_circlebuf(&ng->info_buffer); } static struct obs_audio_data * noise_suppress_filter_audio(void *data, struct obs_audio_data *audio) { struct noise_suppress_data *ng = data; struct ng_audio_info info; size_t segment_size = ng->frames * sizeof(float); size_t out_size; #ifdef LIBSPEEXDSP_ENABLED if (!ng->spx_states[0]) return audio; #endif #ifdef LIBRNNOISE_ENABLED if (!ng->rnn_states[0]) return audio; #endif /* ----------------------------------------------- * if timestamp has dramatically changed, consider it a new stream of * audio data. clear all circular buffers to prevent old audio data * from being processed as part of the new data. */ if (ng->last_timestamp) { int64_t diff = llabs((int64_t)ng->last_timestamp - (int64_t)audio->timestamp); if (diff > 1000000000LL) reset_data(ng); } ng->last_timestamp = audio->timestamp; /* ----------------------------------------------- * push audio packet info (timestamp/frame count) to info circlebuf */ info.frames = audio->frames; info.timestamp = audio->timestamp; circlebuf_push_back(&ng->info_buffer, &info, sizeof(info)); /* ----------------------------------------------- * push back current audio data to input circlebuf */ for (size_t i = 0; i < ng->channels; i++) circlebuf_push_back(&ng->input_buffers[i], audio->data[i], audio->frames * sizeof(float)); /* ----------------------------------------------- * pop/process each 10ms segments, push back to output circlebuf */ while (ng->input_buffers[0].size >= segment_size) process(ng); /* ----------------------------------------------- * peek front of info circlebuf, check to see if we have enough to * pop the expected packet size, if not, return null */ memset(&info, 0, sizeof(info)); circlebuf_peek_front(&ng->info_buffer, &info, sizeof(info)); out_size = info.frames * sizeof(float); if (ng->output_buffers[0].size < out_size) return NULL; /* ----------------------------------------------- * if there's enough audio data buffered in the output circlebuf, * pop and return a packet */ circlebuf_pop_front(&ng->info_buffer, NULL, sizeof(info)); da_resize(ng->output_data, out_size * ng->channels); for (size_t i = 0; i < ng->channels; i++) { ng->output_audio.data[i] = (uint8_t *)&ng->output_data.array[i * out_size]; circlebuf_pop_front(&ng->output_buffers[i], ng->output_audio.data[i], out_size); } ng->output_audio.frames = info.frames; ng->output_audio.timestamp = info.timestamp - ng->latency; return &ng->output_audio; } static bool noise_suppress_method_modified(obs_properties_t *props, obs_property_t *property, obs_data_t *settings) { obs_property_t *p_suppress_level = obs_properties_get(props, S_SUPPRESS_LEVEL); obs_property_t *p_navfx_intensity = obs_properties_get(props, S_NVAFX_INTENSITY); const char *method = obs_data_get_string(settings, S_METHOD); bool enable_level = strcmp(method, S_METHOD_SPEEX) == 0; bool enable_intensity = strcmp(method, S_METHOD_NVAFX) == 0; obs_property_set_visible(p_suppress_level, enable_level); obs_property_set_visible(p_navfx_intensity, enable_intensity); UNUSED_PARAMETER(property); return true; } static void noise_suppress_defaults_v1(obs_data_t *s) { obs_data_set_default_int(s, S_SUPPRESS_LEVEL, -30); #if defined(LIBRNNOISE_ENABLED) && !defined(LIBSPEEXDSP_ENABLED) obs_data_set_default_string(s, S_METHOD, S_METHOD_RNN); #else obs_data_set_default_string(s, S_METHOD, S_METHOD_SPEEX); #endif #if defined(LIBNVAFX_ENABLED) obs_data_set_default_double(s, S_NVAFX_INTENSITY, 1.0); #endif } static void noise_suppress_defaults_v2(obs_data_t *s) { obs_data_set_default_int(s, S_SUPPRESS_LEVEL, -30); #if defined(LIBRNNOISE_ENABLED) obs_data_set_default_string(s, S_METHOD, S_METHOD_RNN); #else obs_data_set_default_string(s, S_METHOD, S_METHOD_SPEEX); #endif #if defined(LIBNVAFX_ENABLED) obs_data_set_default_double(s, S_NVAFX_INTENSITY, 1.0); #endif } static obs_properties_t *noise_suppress_properties(void *data) { obs_properties_t *ppts = obs_properties_create(); #ifdef LIBNVAFX_ENABLED struct noise_suppress_data *ng = (struct noise_suppress_data *)data; #else UNUSED_PARAMETER(data); #endif #if defined(LIBRNNOISE_ENABLED) && defined(LIBSPEEXDSP_ENABLED) obs_property_t *method = obs_properties_add_list( ppts, S_METHOD, TEXT_METHOD, OBS_COMBO_TYPE_LIST, OBS_COMBO_FORMAT_STRING); obs_property_list_add_string(method, TEXT_METHOD_SPEEX, S_METHOD_SPEEX); obs_property_list_add_string(method, TEXT_METHOD_RNN, S_METHOD_RNN); #ifdef LIBNVAFX_ENABLED if (ng->nvafx_enabled) obs_property_list_add_string(method, TEXT_METHOD_NVAFX, S_METHOD_NVAFX); #endif obs_property_set_modified_callback(method, noise_suppress_method_modified); #endif #ifdef LIBSPEEXDSP_ENABLED obs_property_t *speex_slider = obs_properties_add_int_slider( ppts, S_SUPPRESS_LEVEL, TEXT_SUPPRESS_LEVEL, SUP_MIN, SUP_MAX, 1); obs_property_int_set_suffix(speex_slider, " dB"); #endif #ifdef LIBNVAFX_ENABLED obs_property_t *nvafx_slider = obs_properties_add_float_slider( ppts, S_NVAFX_INTENSITY, TEXT_NVAFX_INTENSITY, 0.0f, 1.0f, 0.01f); if (!nvafx_loaded) { obs_property_list_item_disable(method, 2, true); } #endif return ppts; } struct obs_source_info noise_suppress_filter = { .id = "noise_suppress_filter", .type = OBS_SOURCE_TYPE_FILTER, .output_flags = OBS_SOURCE_AUDIO | OBS_SOURCE_CAP_OBSOLETE, .get_name = noise_suppress_name, .create = noise_suppress_create, .destroy = noise_suppress_destroy, .update = noise_suppress_update, .filter_audio = noise_suppress_filter_audio, .get_defaults = noise_suppress_defaults_v1, .get_properties = noise_suppress_properties, }; struct obs_source_info noise_suppress_filter_v2 = { .id = "noise_suppress_filter", .version = 2, .type = OBS_SOURCE_TYPE_FILTER, .output_flags = OBS_SOURCE_AUDIO, .get_name = noise_suppress_name, .create = noise_suppress_create, .destroy = noise_suppress_destroy, .update = noise_suppress_update, .filter_audio = noise_suppress_filter_audio, .get_defaults = noise_suppress_defaults_v2, .get_properties = noise_suppress_properties, };
pkviet/obs-studio
plugins/obs-filters/noise-suppress-filter.c
C
gpl-2.0
28,855
/*************************************************************************** Model Racing Dribbling hardware ***************************************************************************/ #include "driver.h" #include "dribling.h" /************************************* * * Convert the palette PROM into * a real palette * *************************************/ PALETTE_INIT( dribling ) { const UINT8 *prom = memory_region(REGION_PROMS) + 0x400; int i; for (i = 0; i < 256; i++) { int r = (~prom[i] >> 0) & 1; /* 220 */ int g = (~prom[i] >> 1) & 3; /* 820 + 560 (332 max) */ int b = (~prom[i] >> 3) & 1; /* 220 */ r *= 0xff; g *= 0x55; b *= 0xff; palette_set_color(i,r,g,b); } } /************************************* * * Color control writes * *************************************/ WRITE8_HANDLER( dribling_colorram_w ) { /* it is very important that we mask off the two bits here */ colorram[offset & 0x1f9f] = data; } /************************************* * * Video update routine * *************************************/ VIDEO_UPDATE( dribling ) { UINT8 *prombase = memory_region(REGION_PROMS); UINT8 *gfxbase = memory_region(REGION_GFX1); int x, y; /* loop over rows */ for (y = cliprect->min_y; y <= cliprect->max_y; y++) { UINT16 *dst = bitmap->line[y]; /* loop over columns */ for (x = cliprect->min_x; x <= cliprect->max_x; x++) { int b7 = prombase[(x >> 3) | ((y >> 3) << 5)] & 1; int b6 = dribling_abca; int b5 = (x >> 3) & 1; int b4 = (gfxbase[(x >> 3) | (y << 5)] >> (x & 7)) & 1; int b3 = (videoram[(x >> 3) | (y << 5)] >> (x & 7)) & 1; int b2_0 = colorram[(x >> 3) | ((y >> 2) << 7)] & 7; /* assemble the various bits into a palette PROM index */ dst[x] = (b7 << 7) | (b6 << 6) | (b5 << 5) | (b4 << 4) | (b3 << 3) | b2_0; } } }
scs/uclinux
user/games/xmame/xmame-0.106/src/vidhrdw/dribling.c
C
gpl-2.0
1,845
--[[ Title: GridView Author(s): LiPeng Date: 2017/10/3 Desc: use the lib: ------------------------------------------------------------ NPL.load("(gl)script/ide/System/Windows/Controls/GridView.lua"); local GridView = commonlib.gettable("System.Windows.Controls.GridView"); ------------------------------------------------------------ ]] NPL.load("(gl)script/ide/System/Windows/UIElement.lua"); local GridView = commonlib.inherit(commonlib.gettable("System.Windows.UIElement"), commonlib.gettable("System.Windows.Controls.GridView")); GridView:Property("Name", "GridView"); -- the client area X, Y position in pixels relative to the logical tree view container. GridView:Property({"ClientX", 0, auto = "true"}); GridView:Property({"ClientY", 0, auto = "true"}); -- this is automatically set according to whether a scroll bar is available. GridView:Property({"ClientWidth", 10, auto = "true"}); GridView:Property({"ClientHeight", 10, auto = "true"}); -- default indentation GridView:Property({"DefaultIndentation", 5, auto = "true"}); -- whether to show icon on the left of each line. GridView:Property({"ShowIcon", true, auto = "true"}); -- how many items to display per row for the root node. GridView:Property({"ItemsPerRow", nil, auto = "true"}); -- Default height of Tree Node GridView:Property({"DefaultNodeHeight", 24, auto = "true"}); -- Default width of Tree Node, this is not used unless we are displaying the treenode in a grid view style. GridView:Property({"DefaultNodeWidth", nil, auto = "true"}); -- Default padding of tree nodes. this is not used unless we are displaying the treenode in a grid view style. GridView:Property({"DefaultNodePadding", 0, auto = "true"}); -- how many pixels to scroll each time GridView:Property({"VerticalScrollBarStep", 24, auto = "true"}); -- how many pixels to scroll when user hit the empty space of the scroll bar. this is usually same as DefaultNodeHeight GridView:Property({"VerticalScrollBarPageSize", 24, auto = "true"}); GridView:Property({"ItemOpenBG", "Texture/3DMapSystem/common/itemopen.png", auto=true}) GridView:Property({"ItemCloseBG", "Texture/3DMapSystem/common/itemclosed.png", auto=true}) GridView:Property({"MouseOverBG", nil, auto=true}) GridView:Property({"NormalBG", nil, auto=true}) GridView:Property({"ItemToggleSize", nil, auto=true}) GridView:Property({"DefaultIconSize", nil, auto=true}) GridView:Property({"VerticalScrollBarOffsetX", nil, auto=true}) GridView:Property({"DefaultIconSize", nil, auto=true}) function GridView:ctor() end
NPLPackages/main
script/ide/System/Windows/Controls/GridView.lua
Lua
gpl-2.0
2,524
/* * Copyright © 2011 Keith Packard <keithp@keithp.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; version 2 of the License. * * 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. */ #include "ao.h" /* * AltOS always cranks the clock to the max frequency */ void ao_clock_init(void) { /* disable RC clock */ CLKSEL0 &= ~(1 << RCE); /* Disable PLL */ PLLCSR &= ~(1 << PLLE); /* Enable external clock */ CLKSEL0 |= (1 << EXTE); /* wait for external clock to be ready */ while ((CLKSTA & (1 << EXTON)) == 0) ; /* select external clock */ CLKSEL0 |= (1 << CLKS); /* Disable the clock prescaler */ cli(); CLKPR = (1 << CLKPCE); /* Always run the system clock at 8MHz */ #if AVR_CLOCK > 12000000UL CLKPR = 1; #else CLKPR = 0; #endif sei(); /* Set up the PLL to use the crystal */ /* Use primary system clock as PLL source */ PLLFRQ = ((0 << PINMUX) | /* Use primary clock */ (0 << PLLUSB) | /* No divide by 2 for USB */ (0 << PLLTM0) | /* Disable high speed timer */ (0x4 << PDIV0)); /* 48MHz PLL clock */ /* Set the frequency of the crystal */ #if AVR_CLOCK > 12000000UL PLLCSR |= (1 << PINDIV); /* For 16MHz crystal on Teensy board */ #else PLLCSR &= ~(1 << PINDIV); /* For 8MHz crystal on TeleScience board */ #endif /* Enable the PLL */ PLLCSR |= (1 << PLLE); while (!(PLLCSR & (1 << PLOCK))) ; set_sleep_mode(SLEEP_MODE_IDLE); sleep_enable(); }
ajtowns/altos
src/avr/ao_clock.c
C
gpl-2.0
1,949
""" This is script doc string. """ g = 1 # block 1 at level 0 # this is a comment that starts a line after indent # this comment starts in column 1 h=2 # another inline comment # see if this comment is preceded by whitespace def f(a,b,c): # function with multiple returns """ This is multi-line function doc string. """ if a > b: # block 2 at level 1 if b > c: # block 3 at level 2 a = c # block 4 at level 3 else: # block 3 at level 2 return # block 4 at level 3 - explicit return print a # block 2 at level 1 # implicit return f(1,2,3) # block 1 at level 0 [f(i,3,5) for i in range(5)] def g(a,b): a += 1 if a > 'c': print "a is larger" def h(b): return b*b return h(b) g(3,2) v = 123 # this function definition shows that parameter names are not # defined until after the parameter list is completed. That is, # it is invalid to define: def h(a,b=a): ... def h(a, b=v,c=(v,),d={'a':(2,4,6)},e=[3,5,7]): print "b: a=%s b=%s" % (a,b) def k( a , b ) : c = a d = b if c > d: return d def kk( c ): return c*c return kk(c+d) class C: """ This is class doc string.""" def __init__( self ): """ This is a member function doc string""" if 1: return elif 0: return class D (object): def dd( self, *args, **kwds ): return args, kwds def main(): "This is single line doc string" h(3) c = C() g(3,2) f(7,5,3) # next, test if whitespace affects token sequences h ( 'a' , 'z' ) [ 1 : ] # next, test tokenization for statement that crosses lines h ( 'b' , 'y' ) [ 1 : ] if __name__ == "__main__": main()
ipmb/PyMetrics
PyMetrics/examples/sample.py
Python
gpl-2.0
1,928
package sampler; import org.junit.Rule; import org.junit.Test; import org.junit.rules.ExpectedException; import java.io.File; import java.io.IOException; import java.io.Reader; import java.io.StringReader; import java.io.StringWriter; import java.io.Writer; import java.util.List; import java.util.Vector; import static org.mockito.Mockito.*; public class SamplerTest { @Rule public ExpectedException thrown = ExpectedException.none(); @Test public void partitionsCreatedFromInputAndWrittenToOutput() { SequenceReader sequenceReader = mock(SequenceReader.class); SubSequenceCollector subSequenceCollector = mock(SubSequenceCollector.class); PeriodicSampler periodicSampler = mock(PeriodicSampler.class); ListWriter listWriter = mock(ListWriter.class); Sampler sampler = new Sampler(sequenceReader, subSequenceCollector, periodicSampler, listWriter); Reader inputReader = new StringReader("abcdefghi"); Writer outputWriter = new StringWriter(); int numPartitions = 5; Sequence inputSequence = new Sequence("abcdefghi"); List<Sequence> sequenceList = new Vector<>(); sequenceList.add(new Sequence("abc")); sequenceList.add(new Sequence("def")); sequenceList.add(new Sequence("ghi")); List<Sequence> partitions = new Vector<>(); partitions.add(new Sequence("abc")); partitions.add(new Sequence("ghi")); when(sequenceReader.read(inputReader)).thenReturn(inputSequence); when(subSequenceCollector.collect(inputSequence)).thenReturn(sequenceList); when(periodicSampler.sample(sequenceList, numPartitions - 1)).thenReturn(partitions); sampler.createPartitions(inputReader, outputWriter, numPartitions); verify(listWriter).write(partitions, outputWriter); } @Test public void validateFailsIfLessThanTwoParametersPassed() { thrown.expect(SamplerException.class); Sampler.validateInputs(new String[] {}); } @Test public void validateFailsIfMoreThanTwoParametersPassed() { thrown.expect(SamplerException.class); Sampler.validateInputs(new String[] {"", "", ""}); } @Test public void firstArgumentMustBeFile() { thrown.expect(SamplerException.class); Sampler.validateInputs(new String[] {"does not exist", "1"}); } @Test public void secondArgumentMustBeInteger() throws IOException { File file = File.createTempFile("sampler-unit-test", ".tmp"); thrown.expect(SamplerException.class); Sampler.validateInputs(new String[] {file.getAbsolutePath(), "abc"}); } }
dennislloydjr/genome-indexing
src/test/java/sampler/SamplerTest.java
Java
gpl-2.0
2,670
package com.dovydasvenckus.timetracker.entry; import com.dovydasvenckus.timetracker.core.date.clock.DateTimeService; import com.dovydasvenckus.timetracker.core.pagination.PageSizeResolver; import com.dovydasvenckus.timetracker.core.security.ClientDetails; import com.dovydasvenckus.timetracker.project.Project; import com.dovydasvenckus.timetracker.project.ProjectRepository; import org.springframework.data.domain.Page; import org.springframework.data.domain.PageRequest; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import java.util.Optional; @Service public class TimeEntryService { private final DateTimeService dateTimeService; private final TimeEntryRepository timeEntryRepository; private final ProjectRepository projectRepository; private final PageSizeResolver pageSizeResolver; public TimeEntryService(DateTimeService dateTimeService, TimeEntryRepository timeEntryRepository, ProjectRepository projectRepository, PageSizeResolver pageSizeResolver) { this.dateTimeService = dateTimeService; this.timeEntryRepository = timeEntryRepository; this.projectRepository = projectRepository; this.pageSizeResolver = pageSizeResolver; } @Transactional(readOnly = true) Page<TimeEntryDTO> findAll(int page, int pageSize, ClientDetails clientDetails) { return timeEntryRepository .findAllByDeleted( clientDetails.getId(), false, PageRequest.of(page, pageSizeResolver.resolvePageSize(pageSize)) ) .map(TimeEntryDTO::new); } @Transactional(readOnly = true) public Page<TimeEntryDTO> findAllByProject(long projectId, int page, int pageSize, ClientDetails clientDetails) { return timeEntryRepository .findAllByProject( projectId, clientDetails.getId(), PageRequest.of(page, pageSizeResolver.resolvePageSize(pageSize)) ) .map(TimeEntryDTO::new); } @Transactional public TimeEntry create(TimeEntryDTO timeEntryDTO, ClientDetails clientDetails) { timeEntryDTO.setId(null); TimeEntry timeEntry; timeEntry = new TimeEntry(timeEntryDTO, clientDetails.getId()); Optional<Project> project = projectRepository.findByIdAndCreatedBy( timeEntryDTO.getProject().getId(), clientDetails.getId() ); project.ifPresent(timeEntry::setProject); timeEntryRepository.save(timeEntry); return timeEntry; } @Transactional public void stop(TimeEntryDTO timeEntryDTO, ClientDetails clientDetails) { timeEntryRepository.findByIdAndCreatedBy(timeEntryDTO.getId(), clientDetails.getId()) .ifPresent(entry -> entry.setEndDate(dateTimeService.now())); } @Transactional public void delete(Long id, ClientDetails clientDetails) { timeEntryRepository.findByIdAndCreatedBy(id, clientDetails.getId()) .ifPresent(timeEntry -> timeEntry.setDeleted(true)); } Optional<TimeEntryDTO> findCurrentlyActive(ClientDetails clientDetails) { return timeEntryRepository.findCurrentlyActive(clientDetails.getId()) .map(TimeEntryDTO::new); } @Transactional public TimeEntry startTracking(Long projectId, String description, ClientDetails clientDetails) { Optional<Project> project = projectRepository.findByIdAndCreatedBy(projectId, clientDetails.getId()); if (project.isPresent()) { TimeEntry timeEntry = new TimeEntry(); timeEntry.setStartDate(dateTimeService.now()); timeEntry.setDescription(description); timeEntry.setProject(project.get()); timeEntry.setCreatedBy(clientDetails.getId()); timeEntryRepository.save(timeEntry); return timeEntry; } return null; } }
dovydasvenckus/time-tracker
src/main/java/com/dovydasvenckus/timetracker/entry/TimeEntryService.java
Java
gpl-2.0
4,153
<?php //Yii::import('application.extensions.EUploadedImage'); class MarketController extends Controller { /** * @var string the default layout for the views. Defaults to '//layouts/column2', meaning * using two-column layout. See 'protected/views/layouts/column2.php'. */ public $layout = '//layouts/column2'; /** * @return array action filters */ public function filters() { return array( 'accessControl', // perform access control for CRUD operations ); } /** * Specifies the access control rules. * This method is used by the 'accessControl' filter. * @return array access control rules */ public function accessRules() { return array( array('allow', // allow all users to perform 'index' and 'view' actions 'actions' => array('index', 'view', 'rss'), 'users' => array('*'), ), array('allow', // allow authenticated user to perform 'create' and 'update' actions 'actions' => array('create', 'update', 'join', 'panel', 'panelView', 'list', 'delete', 'expire'), 'users' => array('@'), ), array('allow', // allow admin user to perform 'admin' and 'delete' actions 'actions' => array('admin'), 'users' => array('admin'), ), array('deny', // deny all users 'users' => array('*'), ), ); } /** * Displays a particular model. * @param integer $id the ID of the model to be displayed */ public function actionView($id) { if(!is_numeric($id)){ throw new CHttpException(404, 'Access denied.'); } $entity_id = Yii::app()->user->getId(); $model = MarketAd::model()->with( array( 'entities' => array('on' => ($entity_id ? 'entities.id=' . $entity_id : null)), 'joined' => array('on' => ($entity_id ? 'joined.entity_id=' . $entity_id : null)) ))->findByPk($id); $this->render('view', array( 'model' => $model, )); } /** * Displays a particular model. * @param integer $id the ID of the model to be displayed */ public function actionPanel($id) { if(!is_numeric($id)){ throw new CHttpException(404, 'Access denied.'); } $model = $this->loadModel($id); //MarketAd::model()->with('users')->findByPk($id); if (isset(Yii::app()->user->roles[$model->created_by])) { $criteria = new CDbCriteria; $criteria->with = array( 'marketAds' => array( 'together' => true, 'condition' => 'marketAds.id=' . $id, ), 'marketJoined' => array( 'together' => true, 'condition' => 'marketJoined.ad_id=' . $id, ), ); $criteria->compare('marketAds.id', $id); $dataProvider = new CActiveDataProvider('Entity', array( 'criteria' => $criteria, )); Notification::shown($model->created_by, Sid::getSID($model)); $this->render('panel', array( 'model' => $model, 'dataProvider' => $dataProvider, )); } else { Yii::app()->user->setFlash('error', Yii::t('market', 'You can not access to this advertisement control panel')); $this->redirect(array('view', 'id' => $id)); } } public function actionPanelView($ad_id, $entity_id) { if(!is_numeric($ad_id) || !is_numeric($entity_id)){ throw new CHttpException(404, 'Access denied.'); } $ad = $this->loadModel($ad_id); if (!isset(Yii::app()->user->roles[$model->created_by])) { $entity = Entity::model()->findByPk($entity_id); $joined = MarketJoined::model()->with('entity')->findByPk(array('ad_id' => $ad_id, 'entity_id' => $entity_id)); $joined->setScenario('panel'); if (isset($_POST['MarketJoined'])) { $joined->attributes = $_POST['MarketJoined']; if ($joined->save()) { /* if($joined->form_comment != '') { $headers = 'MIME-Version: 1.0' . "\r\n"; $headers .= 'Content-type: text/html; charset=utf-8' . "\r\n"; $headers .= "From: noreply@instauremoslademocracia.net\r\n"; if (mail($user->email,Yii::t('market','[Comment from DEMOS Market]').' '.$ad->title, $this->renderPartial('_joinMail', array('title' => $ad->title, 'message' => $joined->form_comment, 'ad_id' => $ad_id, 'user_id' => $user_id, ), true),$headers)) Yii::app()->user->setFlash('success',Yii::t('market','Thank you for contacting')); else Yii::app()->user->setFlash('error',Yii::t('market','E-mail not sent')); } */ $this->redirect(array('panel', 'id' => $ad_id)); } } Notification::shown($ad->created_by, Sid::getSID($joined)); $this->render('panelView', array( 'entity' => $entity, 'joined' => $joined, 'ad' => $ad, ) ); } else { Yii::app()->user->setFlash('error', Yii::t('market', 'You can not access to this advertisement control panel')); $this->redirect(array('view', 'id' => $ad_id)); } } /** * Creates a new model. * If creation is successful, the browser will be redirected to the 'view' page. */ public function actionCreate($id = null) { $model = new MarketAd; // Uncomment the following line if AJAX validation is needed // $this->performAjaxValidation($model); $entity = Entity::model()->findByPk(Yii::app()->user->logged); $user = $entity->getObject(); if ($id != null) { if (isset(Yii::app()->user->roles[$id])) { $model->created_by = $id; } else { throw new CHttpException(404, 'Access denied.'); } } if (isset($_POST['MarketAd'])) { $model->attributes = $_POST['MarketAd']; if ($model->save()) { if ($user->blocked) { ActivityLog::add(Yii::app()->user->logged, ActivityLog::BLOCKED_MARKET_AD, Sid::getSID($model)); } $this->redirect(array('view', 'id' => $model->id)); } } $model->expiration = date('Y-m-d', time() + MarketAd::MAX_EXPIRATION); $this->render('create', array( 'model' => $model, )); } /** * Updates a particular model. * If update is successful, the browser will be redirected to the 'view' page. * @param integer $id the ID of the model to be updated */ public function actionUpdate($id) { if(!is_numeric($id)){ throw new CHttpException(404, 'Access denied.'); } $model = $this->loadModel($id); if (!isset(Yii::app()->user->roles[$model->created_by])) { Yii::app()->user->setFlash('error', Yii::t('market', 'You can not update this advertisement')); $this->redirect(array('view', 'id' => $id)); return; } // Uncomment the following line if AJAX validation is needed // $this->performAjaxValidation($model); if (isset($_POST['MarketAd'])) { $model->attributes = $_POST['MarketAd']; if ($model->save()) $this->redirect(array('view', 'id' => $model->id)); } $this->render('update', array( 'model' => $model, )); } /** * Deletes a particular model. * If deletion is successful, the browser will be redirected to the 'admin' page. * @param integer $id the ID of the model to be deleted */ public function actionExpire($id) { if(!is_numeric($id)){ throw new CHttpException(404, 'Access denied.'); } $model = $this->loadModel($id); if (!isset(Yii::app()->user->roles[$model->created_by])) { Yii::app()->user->setFlash('error', Yii::t('market', 'You can not update this advertisement')); $this->redirect(array('view', 'id' => $id)); return; } // we only allow deletion via POST request $model->expiration = '0000-00-00'; $model->save(); // if AJAX request (triggered by deletion via admin grid view), we should not redirect the browser if (!isset($_GET['ajax'])) $this->redirect(isset($_POST['returnUrl']) ? $_POST['returnUrl'] : array('index')); } /** * Deletes a particular model. * If deletion is successful, the browser will be redirected to the 'admin' page. * @param integer $id the ID of the model to be deleted */ public function actionDelete($id) { if(!is_numeric($id)){ throw new CHttpException(404, 'Access denied.'); } $model = $this->loadModel($id); if (!isset(Yii::app()->user->roles[$model->created_by])) { Yii::app()->user->setFlash('error', Yii::t('market', 'You can not delete this advertisement')); $this->redirect(array('view', 'id' => $id)); return; } $model->visible = 0; $model->save(); Yii::app()->user->setFlash('notice', Yii::t('app', 'The advertisement have been moved away')); // if AJAX request (triggered by deletion via admin grid view), we should not redirect the browser if (!isset($_GET['ajax'])) $this->redirect(isset($_POST['returnUrl']) ? $_POST['returnUrl'] : array('index')); // else // throw new CHttpException(400,'Invalid request. Please do not repeat this request again.'); } /** * Join to a Market Ad a new model. * If creation is successful, the browser will be redirected to the 'view' page. */ public function actionJoin($id) { if(!is_numeric($id)){ throw new CHttpException(404, 'Access denied.'); } $ad = $this->loadModel($id); $entity_id = Yii::app()->user->getId(); $model = MarketJoined::model()->findByPk(array('ad_id' => $id, 'entity_id' => $entity_id)); if ($model == null) { $model = new MarketJoined; $model->ad_id = $id; $already_joined = false; } else { $already_joined = true; Yii::app()->user->setFlash('success', Yii::t('market', 'You are already joined, update anything you need.')); } $model->setScenario('join'); // uncomment the following code to enable ajax-based validation /* if(isset($_POST['ajax']) && $_POST['ajax']==='market-joined-join-form') { echo CActiveForm::validate($model); Yii::app()->end(); } */ if (isset($_POST['MarketJoined'])) { $model->attributes = $_POST['MarketJoined']; if ($model->validate()) { // form inputs are valid, do something here if ($model->save()) { Yii::app()->user->setFlash('success', Yii::t('market', 'You have successfully joined')); $this->redirect(array('view', 'id' => $ad->id)); } } } Notification::shown($entity_id, Sid::getSID($model)); $this->render('join', array('model' => $model, 'ad' => $ad)); } /** * Lists all models. */ public function actionList($mode = null, $tribe_id=null) { if((!!$mode && !is_numeric($mode)) || (!!$tribe_id && !is_numeric($tribe_id))){ throw new CHttpException(404, 'Access denied.'); } $this->actionIndex($mode,$tribe_id); } /** * Lists all models. */ public function actionIndex($mode = null, $tribe_id=null) { if((!!$mode && !is_numeric($mode)) || (!!$tribe_id && !is_numeric($tribe_id))){ throw new CHttpException(404, 'Access denied.'); } $entity_id = Yii::app()->user->getId(); $model = new MarketAd('search'); $model->unsetAttributes(); // clear any default values $tribe= null; if ($tribe_id && is_numeric($tribe_id)){ $tribe = Tribe::model()->findByPk($tribe_id); } if (isset($_GET['MarketAd'])) $model->attributes = $_GET['MarketAd']; $dataProvider = MarketAd::getAds($model, $mode, $entity_id,$tribe_id); $this->render('index', array( 'dataProvider' => $dataProvider, 'model' => $model, 'tribe' => $tribe )); } /** * Manages all models. */ public function actionAdmin() { $model = new MarketAd('search'); $model->unsetAttributes(); // clear any default values if (isset($_GET['MarketAd'])) $model->attributes = $_GET['MarketAd']; $this->render('admin', array( 'model' => $model, )); } /** * Manages all models. */ public function actionRss() { $entity_id = Yii::app()->user->getId(); $dataProvider = MarketAd::getAds(null, 3, $entity_id); $dataProvider->setPagination(false); $this->renderPartial('rss', array( 'dataProvider' => $dataProvider, )); } /** * Returns the data model based on the primary key given in the GET variable. * If the data model is not found, an HTTP exception will be raised. * @param integer the ID of the model to be loaded */ public function loadModel($id) { if(!is_numeric($id)){ throw new CHttpException(404, 'Access denied.'); } $model = MarketAd::model()->findByPk($id); if ($model === null) throw new CHttpException(404, 'The requested page does not exist.'); return $model; } /** * Performs the AJAX validation. * @param CModel the model to be validated */ protected function performAjaxValidation($model) { if (isset($_POST['ajax']) && $_POST['ajax'] === 'market-ad-form') { echo CActiveForm::validate($model); Yii::app()->end(); } } }
mianfiga/monedademos
protected/controllers/MarketController.php
PHP
gpl-2.0
14,834
# Tabbed profile view extension ## Install 1. Download the latest release. 2. Unzip the downloaded release, and change the name of the folder to `tabbedprofileview`. 3. In the `ext` directory of your phpBB board, create a new directory named `zyleta` (if it does not already exist). 4. Copy the `tabbedprofileview` folder to `/ext/zyleta/` (if done correctly, you'll have the main extension class at (your forum root)/ext/zyleta/tabbedprofileview/composer.json). 5. Navigate in the ACP to `Customise -> Manage extensions`. 6. Look for `Tabbed profile view` under the Disabled Extensions list, and click its `Enable` link. ## Uninstall 1. Navigate in the ACP to `Customise -> Extension Management -> Extensions`. 2. Look for `Tabbed profile view` under the Enabled Extensions list, and click its `Disable` link. 3. To permanently uninstall, click `Delete Data` and then delete the `/ext/zyleta/tabbedprofileview` folder. ## Add tabs If You wanna add another element on tab, use event called `tabbed_profile_view_tablist_prepend` (if You wanna add a tab on first from right position) or `tabbed_profile_view_tablist_append` (first from left position). To add corectly new tab do it like this: ```html <li id="{NAME_OF_YOUR_TAB}-tab" class="tab"> <a href="#tabs" data-subpanel="{NAME_OF_YOUR_TAB}" role="tab" aria-controls="{NAME_OF_YOUR_TAB}">{L_NAME_OF_YOUR_TAB}</a> </li> ``` and replace `{NAME_OF_YOUR_TAB}` with a name You would call this tab. `{L_NAME_OF_YOUR_TAB}` is a displayed name on tab. It can be direct name, or can be from language file. That's all what You did here. Now take a look at "Add content". ## Add content If You added tab, You can add a content for it. Place it on event called `memberlist_view_contact_after` or `memberlist_view_contact_before`. The code should looks like this: ```html <fieldset id="{NAME_OF_YOUR_TAB}" class="fields2" role="tabpanel"> <div class="panel bg2 tabstats"> <div class="inner"> {YOUR_CODE} </div> </div> </fieldset> ``` `{NAME_OF_YOUR_TAB}` have to be the same as on adding a tab. Class `bg2` is just for better styling - same colour as others contents. Class `tabstats` is just declared and coded, so it makes easiest to style Your code. Class `inner` isn't coded, but it is default on phpBB, and makes a nicer look. You can place Your code on place where `{YOUR_CODE}` is placed, it can be whatever You like, but You have to style it by Your own. ## License [GNU General Public License v2](http://opensource.org/licenses/GPL-2.0)
Zyleta/phpbb-3.1-tabbedprofileview
README.md
Markdown
gpl-2.0
2,569
/* * This source file is part of CaesarJ * For the latest info, see http://caesarj.org/ * * Copyright © 2003-2005 * Darmstadt University of Technology, Software Technology Group * Also see acknowledgements in readme.txt * * 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 * * $Id: OpcodeNames.java,v 1.2 2005-01-24 16:52:57 aracic Exp $ */ package org.caesarj.classfile; /** * The human-readable name of this opcodes */ public class OpcodeNames { /** * Returns the name for this opcode */ public static String getName(int opcode) { return opcodeNames[opcode]; } // -------------------------------------------------------------------- // DATA MEMBERS // -------------------------------------------------------------------- private static String[] opcodeNames = { "nop", "aconst_null", "iconst_m1", "iconst_0", "iconst_1", "iconst_2", "iconst_3", "iconst_4", "iconst_5", "lconst_0", "lconst_1", "fconst_0", "fconst_1", "fconst_2", "dconst_0", "dconst_1", "bipush", "sipush", "ldc", "ldc_w", "ldc2_w", "iload", "lload", "fload", "dload", "aload", "iload_0", "iload_1", "iload_2", "iload_3", "lload_0", "lload_1", "lload_2", "lload_3", "fload_0", "fload_1", "fload_2", "fload_3", "dload_0", "dload_1", "dload_2", "dload_3", "aload_0", "aload_1", "aload_2", "aload_3", "iaload", "laload", "faload", "daload", "aaload", "baload", "caload", "saload", "istore", "lstore", "fstore", "dstore", "astore", "istore_0", "istore_1", "istore_2", "istore_3", "lstore_0", "lstore_1", "lstore_2", "lstore_3", "fstore_0", "fstore_1", "fstore_2", "fstore_3", "dstore_0", "dstore_1", "dstore_2", "dstore_3", "astore_0", "astore_1", "astore_2", "astore_3", "iastore", "lastore", "fastore", "dastore", "aastore", "bastore", "castore", "sastore", "pop", "pop2", "dup", "dup_x1", "dup_x2", "dup2", "dup2_x1", "dup2_x2", "swap", "iadd", "ladd", "fadd", "dadd", "isub", "lsub", "fsub", "dsub", "imul", "lmul", "fmul", "dmul", "idiv", "ldiv", "fdiv", "ddiv", "irem", "lrem", "frem", "drem", "ineg", "lneg", "fneg", "dneg", "ishl", "lshl", "ishr", "lshr", "iushr", "lushr", "iand", "land", "ior", "lor", "ixor", "lxor", "iinc", "i2l", "i2f", "i2d", "l2i", "l2f", "l2d", "f2i", "f2l", "f2d", "d2i", "d2l", "d2f", "i2b", "i2c", "i2s", "lcmp", "fcmpl", "fcmpg", "dcmpl", "dcmpg", "ifeq", "ifne", "iflt", "ifge", "ifgt", "ifle", "if_icmpeq", "if_icmpne", "if_icmplt", "if_icmpge", "if_icmpgt", "if_icmple", "if_acmpeq", "if_acmpne", "goto", "jsr", "ret", "tableswitch", "lookupswitch", "ireturn", "lreturn", "freturn", "dreturn", "areturn", "return", "getstatic", "putstatic", "getfield", "putfield", "invokevirtual", "invokespecial", "invokestatic", "invokeinterface", "xxxunusedxxx", "new", "newarray", "anewarray", "arraylength", "athrow", "checkcast", "instanceof", "monitorenter", "monitorexit", "wide", "multianewarray", "ifnull", "ifnonnull", "goto_w", "jsr_w" }; }
tud-stg-lang/caesar-compiler
src/org/caesarj/classfile/OpcodeNames.java
Java
gpl-2.0
4,355
<?php /** * @copyright Copyright (C) eZ Systems AS. All rights reserved. * @license For full copyright and license information view LICENSE file distributed with this source code. */ declare(strict_types=1); namespace eZ\Publish\API\Repository\Values\Content\Search\Facet; use eZ\Publish\API\Repository\Values\Content\Search\Facet; /** * This class represents a field range facet. * * @deprecated since eZ Platform 3.2.0, to be removed in eZ Platform 4.0.0. */ class FieldRangeFacet extends Facet { /** * Number of documents not containing any terms in the queried fields. * * @var int */ public $missingCount; /** * The number of terms which are not in the queried top list. * * @var int */ public $otherCount; /** * The total count of terms found. * * @var int */ public $totalCount; /** * For each interval there is an entry with statistical data. * * @var \eZ\Publish\API\Repository\Values\Content\Search\Facet\RangeFacetEntry[] */ public $entries; }
gggeek/ezpublish-kernel
eZ/Publish/API/Repository/Values/Content/Search/Facet/FieldRangeFacet.php
PHP
gpl-2.0
1,081
#ifndef LIMIT_MODULE_H #define LIMIT_MODULE_H #include <Arduino.h> #include "./base.hpp" #include "../../vehiclecontrol.h" class Limit_module : public Modulebase { private: protected: Vehiclecontrol mInputControl; Vehiclecontrol mOutputControl; Limit_module(byte id, int module) : Modulebase(id, module, Roles::LIMIT_MODULE) { mInputControl.setName("Input_limit-INPUT"); mOutputControl.setName("Input_limit-OUTPUT"); } public: const Vehiclecontrol getOutputControl() const { return mOutputControl; } }; #endif
faraday-motion/pacer
src/modules/base/limit_module.h
C
gpl-2.0
540
! ! Copyright (C) 2002-2008 Quantum ESPRESS0 groups ! This file is distributed under the terms of the ! GNU General Public License. See the file `License' ! in the root directory of the present distribution, ! or http://www.gnu.org/copyleft/gpl.txt . ! subroutine dforceb(c0, i, betae, ipol, bec0, ctabin, gqq, gqqm, qmat, dq2, df) ! this subroutine computes the force for electrons ! in case of Berry,s phase like perturbation ! it gives the force for the i-th state ! c0 input: Psi^0_i ! c1 input: Psi^1_i ! i input: ot computes the force for the i-th state ! v0 input: the local zeroth order potential ! v1 input: the local first order potential ! betae input: the functions beta_iR ! ipol input:the polarization of nabla_k ! bec0 input: the factors <beta_iR|Psi^0_v> ! bec1 input: the factors <beta_iR|Psi^1_v> ! ctabin input: the inverse-correspondence array g'+(-)1=g ! gqq input: the factors int dr Beta_Rj*Beta_Ri exp(iGr) ! gqqm input: the factors int dr Beta_Rj*Beta_Ri exp(iGr) ! qmat input: ! dq2 input: factors d^2hxc_ijR ! df output: force for the i-th state use kinds, only : DP use gvecs use gvecw, only: ngw use parameters use electrons_base, only: nx => nbspx, n => nbsp, nspin, f use constants, only : use ions_base, only : nat, nax, na, nsp use cell_base, only: at, alat use uspp_param, only: nh, nhm, nvb, ish use uspp, only : nhsa=> nkb use efield_module, ONLY : ctabin_missing_1,ctabin_missing_2,n_g_missing_m,& & ctabin_missing_rev_1,ctabin_missing_rev_2 use mp_global, only: intra_bgrp_comm, nproc_bgrp use mp, only: mp_alltoall use parallel_include implicit none complex(DP) c0(ngw, n), betae(ngw,nhsa), df(ngw),& & gqq(nhm,nhm,nax,nsp),gqqm(nhm,nhm,nax,nsp),& & qmat(nx,nx) real(DP) bec0(nhsa,n), dq2(nat,nhm,nhm,nspin), gmes real(DP), EXTERNAL :: g_mes integer i, ipol, ctabin(ngw,2) ! local variables integer j,k,ig,iv,jv,ix,jx,is,ia, isa,iss,iss1,mism integer ir,ism,itemp,itempa,jnl,inl complex(DP) ci ,fi, fp, fm real(DP) afr(nhsa), dd complex(DP) afrc(nhsa) complex(DP), allocatable:: dtemp(:) complex(DP), allocatable :: sndbuf(:,:,:),rcvbuf(:,:,:) integer :: ierr, ip allocate( dtemp(ngw)) ci=(0.d0,1.d0) ! now the interaction term ! first the norm-conserving part do ig=1,ngw dtemp(ig)=(0.d0,0.d0) enddo do j=1,n do ig=1,ngw if(ctabin(ig,2) .ne. (ngw+1)) then if(ctabin(ig,2).ge.0) then dtemp(ig)=dtemp(ig)+c0(ctabin(ig,2),j)*qmat(j,i) else dtemp(ig)=dtemp(ig)+CONJG(c0(-ctabin(ig,2),j))*qmat(j,i) endif endif enddo do ig=1,ngw if(ctabin(ig,1) .ne. (ngw+1)) then if(ctabin(ig,1).ge.0) then dtemp(ig)=dtemp(ig)-c0(ctabin(ig,1),j)*CONJG(qmat(j,i)) else dtemp(ig)=dtemp(ig)-CONJG(c0(-ctabin(ig,1),j))*conjg(qmat(j,i)) endif endif enddo #if defined(__MPI) if(ipol/=3) then !allocate arrays allocate(sndbuf(n_g_missing_m(ipol),2,nproc_bgrp)) sndbuf(:,:,:)=(0.d0,0.d0) allocate(rcvbuf(n_g_missing_m(ipol),2,nproc_bgrp)) !copy arrays to snd buf do ip=1,nproc_bgrp do ig=1,n_g_missing_m(ipol) if(ipol==1) then if(ctabin_missing_rev_1(ig,1,ip)>0) then sndbuf(ig,1,ip)=-c0(ctabin_missing_rev_1(ig,1,ip),j)*CONJG(qmat(j,i)) elseif(ctabin_missing_rev_1(ig,1,ip)<0) then sndbuf(ig,1,ip)=-conjg(c0(-ctabin_missing_rev_1(ig,1,ip),j))*CONJG(qmat(j,i)) endif else if(ctabin_missing_rev_2(ig,1,ip)>0) then sndbuf(ig,1,ip)=-c0(ctabin_missing_rev_2(ig,1,ip),j)*CONJG(qmat(j,i)) elseif(ctabin_missing_rev_2(ig,1,ip)<0) then sndbuf(ig,1,ip)=-conjg(c0(-ctabin_missing_rev_2(ig,1,ip),j))*CONJG(qmat(j,i)) endif endif enddo do ig=1,n_g_missing_m(ipol) if(ipol==1) then if(ctabin_missing_rev_1(ig,2,ip)>0) then sndbuf(ig,2,ip)=c0(ctabin_missing_rev_1(ig,2,ip),j)*qmat(j,i) elseif(ctabin_missing_rev_1(ig,2,ip)<0) then sndbuf(ig,2,ip)=conjg(c0(-ctabin_missing_rev_1(ig,2,ip),j))*qmat(j,i) endif else if(ctabin_missing_rev_2(ig,2,ip)>0) then sndbuf(ig,2,ip)=c0(ctabin_missing_rev_2(ig,2,ip),j)*qmat(j,i) elseif(ctabin_missing_rev_2(ig,2,ip)<0) then sndbuf(ig,2,ip)=conjg(c0(-ctabin_missing_rev_2(ig,2,ip),j))*qmat(j,i) endif endif enddo enddo CALL mp_alltoall( sndbuf, rcvbuf, intra_bgrp_comm ) !update sca do ip=1,nproc_bgrp do ig=1,n_g_missing_m(ipol) if(ipol==1) then if(ctabin_missing_1(ig,1,ip)/=0) then dtemp(ctabin_missing_1(ig,1,ip))=dtemp(ctabin_missing_1(ig,1,ip))+rcvbuf(ig,1,ip) endif if(ctabin_missing_1(ig,2,ip)/=0) then dtemp(ctabin_missing_1(ig,2,ip))=dtemp(ctabin_missing_1(ig,2,ip))+rcvbuf(ig,2,ip) endif else if(ctabin_missing_2(ig,1,ip)/=0) then dtemp(ctabin_missing_2(ig,1,ip))=dtemp(ctabin_missing_2(ig,1,ip))+rcvbuf(ig,1,ip) endif if(ctabin_missing_2(ig,2,ip)/=0) then dtemp(ctabin_missing_2(ig,2,ip))=dtemp(ctabin_missing_2(ig,2,ip))+rcvbuf(ig,2,ip) endif endif enddo enddo !deallocate arrays deallocate(rcvbuf,sndbuf) endif #endif enddo gmes = g_mes ( ipol, at, alat ) fi=f(i)*ci/(2.d0*gmes) do ig=1,ngw df(ig)= fi*dtemp(ig) end do ! now the interacting Vanderbilt term ! the term (-ie/|G|)(-beta_i'R>gqq(i',j')bec0_jRj'Q^-1_ji+ ! +beta_i'R>gqqm(i',j')bec0jRj'Q^-1_ij* if(nhsa.gt.0) then do inl=1,nhsa afrc(inl)=(0.d0,0.d0) end do do is=1,nvb!loop on species do iv=1,nh(is) !loop on projectors do jv=1,nh(is) !loop on projectors do ia=1,na(is) inl=ish(is)+(iv-1)*na(is)+ia jnl=ish(is)+(jv-1)*na(is)+ia do j=1,n !loop on states afrc(inl)=afrc(inl)+gqq(iv,jv,ia,is)*bec0(jnl,j)*qmat(j,i)& & -CONJG(gqq(jv,iv,ia,is))*bec0(jnl,j)*conjg(qmat(i,j)) end do end do end do end do enddo do ig=1,ngw dtemp(ig)=(0.d0,0.d0) end do do inl=1,nhsa do ig=1,ngw dtemp(ig)=dtemp(ig)+afrc(inl)*betae(ig,inl) enddo enddo ! call MXMA ! & (betae,1,2*ngw,afr,1,nhsax,dtemp,1,2*ngw,2*ngw,nhsa,1) do ig=1,ngw df(ig)=df(ig)+fi*dtemp(ig) end do endif deallocate( dtemp) return end subroutine dforceb function enberry( detq, ipol ) use constants, only : use kinds, only: dp use cell_base, only: alat, at USE electrons_base, ONLY : nspin implicit none complex(dp), intent (in) :: detq real(dp) :: enberry integer ipol real(dp) gmes real(dp), external :: g_mes gmes = g_mes ( ipol, at, alat ) enberry = 2.d0/REAL(nspin,DP)*AIMAG(log(detq))/gmes ! take care of sign return end function enberry ! ! Copyright (C) 2011 Quantum ESPRESSO group ! This file is distributed under the terms of the ! GNU General Public License. See the file `License' ! in the root directory of the present distribution, ! or http://www.gnu.org/copyleft/gpl.txt . ! FUNCTION g_mes ( ipol, at, alat ) USE kinds, ONLY : dp USE constants, ONLY : pi IMPLICIT NONE INTEGER, INTENT(IN) :: ipol REAL(dp), INTENT(IN) :: at(3,3), alat REAL(dp) :: g_mes IF ( ipol < 1 .OR. ipol > 3) CALL errore ( 'gmes','incorrect ipol', 1) g_mes = 2.0_dp*pi/alat/SQRT(at(1,ipol)**2+at(2,ipol)**2+at(3,ipol)**2) END FUNCTION g_mes
dceresoli/ce-espresso
CPV/src/dforceb.f90
FORTRAN
gpl-2.0
8,675
package de.tum.bgu.msm.syntheticPopulationGenerator.properties; import de.tum.bgu.msm.common.datafile.TableDataSet; import de.tum.bgu.msm.properties.PropertiesUtil; import de.tum.bgu.msm.utils.SiloUtil; import org.apache.commons.math.distribution.GammaDistributionImpl; import java.util.ResourceBundle; public class GermanyPropertiesSynPop extends AbstractPropertiesSynPop { public GermanyPropertiesSynPop(ResourceBundle bundle) { PropertiesUtil.newPropertySubmodule("SP: main properties"); state = PropertiesUtil.getStringProperty(bundle, "state.synPop", "01"); states = PropertiesUtil.getStringPropertyArray(bundle, "states.synPop.splitting", new String[]{"01","10"}); numberOfSubpopulations = PropertiesUtil.getIntProperty(bundle, "micro.data.subpopulations", 1); populationSplitting = PropertiesUtil.getBooleanProperty(bundle, "micro.data.splitting", false); runBySubpopulation = PropertiesUtil.getBooleanProperty(bundle,"run.by.subpopulation",false); readMergeAndSplit = PropertiesUtil.getBooleanProperty(bundle, "micro.data.read.splitting", false); runSyntheticPopulation = PropertiesUtil.getBooleanProperty(bundle, "run.synth.pop.generator", false); runIPU = PropertiesUtil.getBooleanProperty(bundle, "run.ipu.synthetic.pop", false); runAllocation = PropertiesUtil.getBooleanProperty(bundle, "run.population.allocation", false); //runJobAllocation = PropertiesUtil.getBooleanProperty(bundle, "run.job.de.tum.bgu.msm.syntheticPopulationGenerator.germany.disability ", true); // was there initially. was true - than can not find Agri runJobAllocation = PropertiesUtil.getBooleanProperty(bundle, "run.job.allocation", true); twoGeographicalAreasIPU = PropertiesUtil.getBooleanProperty(bundle, "run.ipu.city.and.county", false); boroughIPU = PropertiesUtil.getBooleanProperty(bundle,"run.three.areas",false); runDisability = PropertiesUtil.getBooleanProperty(bundle, "run.disability", false); runMicrolocation = PropertiesUtil.getBooleanProperty(bundle, "run.sp.microlocation", false); microDataFile = PropertiesUtil.getStringProperty(bundle, "micro.data", "C:/Users/Wei/Documents/germanyModel/topSecretData/suf2010v1.dat"); // todo this table is not a property but a data container, "ID_city" might be a property? (if this is applciable to other implementations) marginalsMunicipality = SiloUtil.readCSVfile(PropertiesUtil.getStringProperty(bundle,"marginals.municipality","input/syntheticPopulation/" + state + "/marginalsMunicipality.csv")); marginalsMunicipality.buildIndex(marginalsMunicipality.getColumnPosition("ID_city")); jobsByTaz = SiloUtil.readCSVfile(PropertiesUtil.getStringProperty(bundle,"jobs.by.taz","input/syntheticPopulation" + "/jobsByTaz.csv")); jobsByTaz.buildIndex(jobsByTaz.getColumnPosition("taz")); //todo same as municipalities marginalsCounty = SiloUtil.readCSVfile(PropertiesUtil.getStringProperty(bundle,"marginals.county","input/syntheticPopulation/" + state + "/marginalsCounty.csv")); marginalsCounty.buildIndex(marginalsCounty.getColumnPosition("ID_county")); selectedMunicipalities = SiloUtil.readCSVfile(PropertiesUtil.getStringProperty(bundle,"municipalities.list","input/syntheticPopulation/" + state + "/municipalitiesList.csv")); selectedMunicipalities.buildIndex(selectedMunicipalities.getColumnPosition("ID_city")); cellsMatrix = SiloUtil.readCSVfile(PropertiesUtil.getStringProperty(bundle,"taz.definition","input/syntheticPopulation/" + state + "/zoneAttributeswithTAZ.csv")); cellsMatrix.buildIndex(cellsMatrix.getColumnPosition("ID_cell")); zoneSystemFileName = PropertiesUtil.getStringProperty(bundle,"taz.definition ","input/syntheticPopulation/" + state + "/zoneAttributeswithTAZ.csv"); //todo this cannot be the final name of the matrix omxFileName = PropertiesUtil.getStringProperty(bundle, "distanceODmatrix", "input/syntheticPopulation/tdTest_distance.omx"); attributesMunicipality = PropertiesUtil.getStringPropertyArray(bundle, "attributes.municipality", new String[]{"Agr", "Ind", "Srv"}); attributesCounty = PropertiesUtil.getStringPropertyArray(bundle, "attributes.county", new String[]{"Agr", "Ind", "Srv"}); ageBracketsPerson = PropertiesUtil.getIntPropertyArray(bundle, "age.brackets", new int[]{9, 14, 19, 24, 29, 34, 39, 44, 49, 54, 59, 64, 69, 74, 79, 84, 120}); ageBracketsPersonQuarter = null; jobStringType = PropertiesUtil.getStringPropertyArray(bundle, "employment.types", new String[]{"Agr", "Ind", "Srv"}); alphaJob = PropertiesUtil.getDoubleProperty(bundle, "employment.choice.alpha", 50); gammaJob = PropertiesUtil.getDoubleProperty(bundle, "employment.choice.gamma", -0.003); tripLengthDistributionFileName = PropertiesUtil.getStringProperty(bundle, "trip.length.distribution", "input/syntheticPopulation/tripLengthDistribution.csv"); schoolTypes = PropertiesUtil.getIntPropertyArray(bundle, "school.types", new int[]{1, 2, 3}); alphaUniversity = PropertiesUtil.getDoubleProperty(bundle, "university.choice.alpha", 50); gammaUniversity = PropertiesUtil.getDoubleProperty(bundle, "university.choice.gamma", -0.003); householdSizes = PropertiesUtil.getIntPropertyArray(bundle, "household.size.brackets", new int[]{1, 2, 3, 4, 5}); maxIterations = PropertiesUtil.getIntProperty(bundle, "max.iterations.ipu", 1000); maxError = PropertiesUtil.getDoubleProperty(bundle, "max.error.ipu", 0.0001); improvementError = PropertiesUtil.getDoubleProperty(bundle, "min.improvement.error.ipu", 0.001); iterationError = PropertiesUtil.getDoubleProperty(bundle, "iterations.improvement.ipu", 2); increaseError = PropertiesUtil.getDoubleProperty(bundle, "increase.error.ipu", 1.05); initialError = PropertiesUtil.getDoubleProperty(bundle, "ini.error.ipu", 1000); double incomeShape = PropertiesUtil.getDoubleProperty(bundle, "income.gamma.shape", 1.0737036186); double incomeRate = PropertiesUtil.getDoubleProperty(bundle, "income.gamma.rate", 0.0006869439); //todo consider to read it from another source e.g. a JS calculator or CSV file //this is not a property but a variable? incomeGammaDistribution = new GammaDistributionImpl(incomeShape, 1 / incomeRate); //todo this properties will be doubled with silo model run properties weightsFileName = PropertiesUtil.getStringProperty(bundle, "weights.matrix", "microData/" + state + "/interimFiles/weigthsMatrix.csv"); errorsMunicipalityFileName = PropertiesUtil.getStringProperty(bundle, "errors.IPU.municipality.matrix", "microData/" + state + "/interimFiles/errorsIPUmunicipality.csv"); errorsCountyFileName = PropertiesUtil.getStringProperty(bundle, "errors.IPU.county.matrix", "microData/" + state + "/interimFiles/errorsIPUcounty.csv"); errorsSummaryFileName = PropertiesUtil.getStringProperty(bundle, "errors.IPU.summary.matrix", "microData/" + state + "/interimFiles/errorsIPUsummary.csv"); frequencyMatrixFileName = PropertiesUtil.getStringProperty(bundle,"frequency.matrix.file","microData/" + state + "/interimFiles/quencyMatrix.csv"); buildingLocationlist = null; jobLocationlist = null; schoolLocationlist = SiloUtil.readCSVfile(PropertiesUtil.getStringProperty(bundle,"school.location", "input/syntheticPopulation/08_schoolLocation.csv")); firstVacantJob = PropertiesUtil.getIntProperty(bundle,"first.vacant.job.id", 45000000); /*cellsMicrolocations = SiloUtil.readCSVfile2("C:/models/silo/germany/input/syntheticPopulation/all_raster_100_updated.csv"); cellsMicrolocations.buildStringIndex(cellsMicrolocations.getColumnPosition("id"));*/ microPersonsFileName = PropertiesUtil.getStringProperty(bundle, "micro.persons", "microData/" + state + "/interimFiles/microPersons.csv"); microHouseholdsFileName = PropertiesUtil.getStringProperty(bundle, "micro.households", "microData/" + state + "/interimFiles/microHouseholds.csv"); zonalDataIPU = null; householdsFileName = PropertiesUtil.getStringProperty(bundle, "household.file.ascii", "microData/hh"); personsFileName = PropertiesUtil.getStringProperty(bundle, "person.file.ascii", "microData/pp"); dwellingsFileName = PropertiesUtil.getStringProperty(bundle, "dwelling.file.ascii", "microData/dd"); jobsFileName = PropertiesUtil.getStringProperty(bundle, "job.file.ascii", "microData/jj"); pathSyntheticPopulationFiles = PropertiesUtil.getStringProperty(bundle, "path.synthetic.ascii", "microData/"); householdsStateFileName = PropertiesUtil.getStringProperty(bundle, "household.file.ascii.sp", "microData/" + state + "/hh"); personsStateFileName = PropertiesUtil.getStringProperty(bundle, "person.file.ascii.sp", "microData/" + state + "/pp"); dwellingsStateFileName = PropertiesUtil.getStringProperty(bundle, "dwelling.file.ascii.sp", "microData/" + state + "/dd"); jobsStateFileName = PropertiesUtil.getStringProperty(bundle, "job.file.ascii.sp", "microData/" + state + "/jj"); counters = SiloUtil.readCSVfile(PropertiesUtil.getStringProperty(bundle,"counters.synthetic.population","microData/subPopulations/countersByState.csv")); counters.buildStringIndex(counters.getColumnPosition("state")); vacantJobPercentage = PropertiesUtil.getIntProperty(bundle,"jobs.vacant.percentage", 25); if (boroughIPU) { attributesBorough = PropertiesUtil.getStringPropertyArray(bundle, "attributes.borough", new String[]{"Agr", "Ind", "Srv"}); marginalsBorough = SiloUtil.readCSVfile(PropertiesUtil.getStringProperty(bundle, "marginals.borough", "input/syntheticPopulation/" + state + "/marginalsBorough.csv")); marginalsBorough.buildIndex(marginalsBorough.getColumnPosition("ID_borough")); selectedBoroughs = SiloUtil.readCSVfile(PropertiesUtil.getStringProperty(bundle,"municipalities.list.borough","input/syntheticPopulation/" + state + "/municipalitiesListBorough.csv")); selectedBoroughs.buildIndex(selectedBoroughs.getColumnPosition("ID_borough")); cellsMatrixBoroughs = SiloUtil.readCSVfile(PropertiesUtil.getStringProperty(bundle,"taz.definition","input/syntheticPopulation/" + state + "/zoneAttributesBoroughwithTAZ.csv")); cellsMatrixBoroughs.buildIndex(cellsMatrixBoroughs.getColumnPosition("ID_cell")); } } }
msmobility/silo
synthetic-population/src/main/java/de/tum/bgu/msm/syntheticPopulationGenerator/properties/GermanyPropertiesSynPop.java
Java
gpl-2.0
10,681