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
# THIS FILE IS PART OF THE CYLC WORKFLOW ENGINE. # Copyright (C) NIWA & British Crown (Met Office) & Contributors. # # 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/>. """General utilities for the integration test infrastructure. These utilities are not intended for direct use by tests (hence the underscore function names). Use the fixtures provided in the conftest instead. """ import asyncio def _rm_if_empty(path): """Convenience wrapper for removing empty directories.""" try: path.rmdir() except OSError: return False return True
oliver-sanders/cylc
tests/integration/utils/__init__.py
Python
gpl-3.0
1,157
package com.gmail.mrphpfan; import com.gmail.mrphpfan.mccombatlevel.calculator.JavaScriptCalculator; import com.gmail.mrphpfan.mccombatlevel.calculator.LevelCalculator; import com.gmail.nossr50.config.Config; import com.gmail.nossr50.datatypes.player.PlayerProfile; import com.gmail.nossr50.datatypes.skills.PrimarySkillType; import javax.script.ScriptEngineManager; import org.junit.Before; import org.junit.Ignore; import org.junit.Test; import org.junit.runner.RunWith; import org.powermock.core.classloader.annotations.PrepareForTest; import org.powermock.modules.junit4.PowerMockRunner; import static org.hamcrest.CoreMatchers.is; import static org.hamcrest.CoreMatchers.notNullValue; import static org.hamcrest.MatcherAssert.assertThat; import static org.junit.Assume.assumeThat; import static org.mockito.Matchers.any; import static org.powermock.api.mockito.PowerMockito.mock; import static org.powermock.api.mockito.PowerMockito.mockStatic; import static org.powermock.api.mockito.PowerMockito.when; @PrepareForTest({PrimarySkillType.class, Config.class}) @RunWith(PowerMockRunner.class) public class CalculationTest { @Before public void before() { //ignore test in Java 10 in combination with PowerMock, because of bugs assumeThat(new ScriptEngineManager().getEngineByName("JavaScript"), notNullValue()); mockStatic(Config.class); Config fakeConfig = mock(Config.class); when(Config.getInstance()).thenReturn(fakeConfig); when(fakeConfig.getLocale()).thenReturn("en_US"); } @Test @Ignore public void testScript() { String formula = "Math.round((unarmed + swords + axes + archery + .25 * acrobatics + .25 * taming) / 45)"; LevelCalculator levelCalculator = new JavaScriptCalculator(formula); PlayerProfile playerProfile = mock(PlayerProfile.class); when(playerProfile.getSkillLevel(any(PrimarySkillType.class))).thenReturn(100); assertThat(10, is(levelCalculator.calculateLevel(playerProfile))); } }
games647/McCombatLevel
src/test/java/com/gmail/mrphpfan/CalculationTest.java
Java
gpl-3.0
2,019
# cy0
tranter1991/cy0
README.md
Markdown
gpl-3.0
6
/* * stringtools.h * * Created on: 6 mai 2010 * Author: pierre Blavy * GPL 3.0 */ #ifndef STRINGTOOLS_H_ #define STRINGTOOLS_H_ #include <string> #include <algorithm> #include <sstream> #include <deque> namespace bconfig{ namespace str{ //--- begins end with --- inline bool beginWith(std::string const &source, std::string const &end) { if(source.length() < end.length()){return false;} return source.substr(0, end.length() ) == end; } inline bool endWith(std::string const &source, std::string const &end) { if(source.length() < end.length()){return false;} return source.substr(source.length() - end.length()) == end; } //--- remove fist, last --- inline void removeLast(std::string &s,char c){ if(s[s.length()-1] == c){ s=s.substr(0,s.length()-1); } } inline void removeFirst(std::string &s,char c){ if(s.length()<1){return;} if(s[0] == c){ s=s.substr(1); } } //---Trim--- inline void trim_right(std::string &source, const std::string &t= " ") { source.erase(source.find_last_not_of(t)+1); } inline void trim_left(std::string &source, const std::string &t = " ") { source.erase(0, source.find_first_not_of(t)); } inline void trim(std::string &source, const std::string &t = " ") { trim_right(source,t); trim_left(source,t); } //--- casse --- inline void toUpper(std::string &s){ std::transform(s.begin(), s.end(), s.begin(), ::toupper); } inline void toLower(std::string &s){ std::transform(s.begin(), s.end(), s.begin(), ::tolower); } //--- replace --- inline void replace(std::string &s, char oldone, char newone) { for(size_t i=0;i<s.length();++i){ if(s[i]==oldone){s[i] = newone;} } } //Source : http://stackoverflow.com/questions/1452501/string-replace-in-c inline void replace(std::string& value, std::string const& search,std::string const& replace){ using namespace std; std::string::size_type next; for(next = value.find(search); // Try and find the first match next != std::string::npos; // next is npos if nothing was found next = value.find(search,next) // search for the next match starting after // the last match that was found. ) { // Inside the loop. So we found a match. value.replace(next,search.length(),replace); // Do the replacement. next += replace.length(); // Move to just after the replace // This is the point were we start // the next search from. } } ///--- tokenize --- inline std::deque<std::string> tokenize(const std::string &s ,char sep){ std::string token; std::deque<std::string> R; std::istringstream iss(s); while ( getline(iss, token, sep) ) { R.push_back(token); } return R; } inline std::deque<std::string> tokenize(const std::string &s ,const std::string & sep){ std::deque<std::string> R; if(sep==""){R.push_back(s); return R;} std::string token; for(size_t i=0; i< s.length() - sep.size() +1 ;++i){ char c = s[i]; if(s.substr(i,sep.size()) == sep ){ R.push_back(token); token=""; } token+=c; } if(token !="") R.push_back(token); return R; } inline std::deque<std::string> tokenizeMultipleSep(std::string const & s, std::string const & seps){ using namespace std; deque<string> R; string token; for(size_t i = 0; i<s.length();++i){ char c=s[i]; if(seps.find(c)!=string::npos){//separator if(token!=""){ R.push_back(token);} token=""; continue; } token+=c; } if(token!=""){ R.push_back(token);} return R; } //--- find all --- inline std::deque<size_t> findAll(const std::string &s,const std::string &toFind){ using namespace std; std::deque<size_t> R; size_t pos= s.find(toFind); while (pos != string::npos ){ R.push_back(pos); pos = s.find(toFind,pos+1); } return R; } //--- delChar --- inline void delChar(std::string &s ,char sep){ //TODO make a more efficient code without tokenize dependency std::deque<std::string> d = tokenize(s,sep); s=""; for(size_t i=0;i<d.size();++i){ s+=d[i]; } } //--- getBetween --- inline std::string getBetween(std::string const &s, size_t begin, size_t end){ return s.substr(begin+1, end-begin); } //--- comments --- inline void cutComment(std::string&s, char c = '#'){s=tokenize(s,c)[0];trim(s);} }}//end namespace BConfig::str #endif /* STRINGTOOLS_H_ */
pierreblavy2/cpp-BConfig
src/helpers/str_tools.h
C
gpl-3.0
4,480
/* Copyright 2013 Oliver Katz * * This file is part of LibIncandescence. * * LibIncandescence 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. * * LibIncandescene 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 LibIncandescence. If not, see <http://www.gnu.org/licenses/>. */ /*! \file Util.h * \brief Basic utilities for all of LibIncandescence. * Util.h contains console message formatting, macros to display debug messages, * warnings, non-fatal errors and fatal errors. It also contains the testing system, * which is very primitive, but hey. Lastly, it contains file IO for the basic loading * of configuration/script files. */ /*! \def INCD_MESSAGE_STREAM * \brief The IO stream to output console messages to. * This can easily be changed to cerr, if stdout conflicts with other messages. */ /*! \def INCD_MESSAGE_PREFIX * \brief The prefix to use for all console messages. * Contains the file and line number location that the message originated from. */ /*! \def INCD_MESSAGE_PREFIX_ERROR * \brief The prefix to use for all errors. */ /*! \def INCD_MESSAGE_PREFIX_WARNING * \brief The prefix to use for all warnings. */ /*! \def INCD_MESSAGE_PREFIX_DEBUG * \brief The prefix to use for all debug messages. */ /*! \def INCD_MESSAGE_PREFIX_TEST * \brief The prefix to use for all test message. */ /*! \def INCD_MESSAGE_DISPLAY(msg) * \brief Displays text in \a msg to console. * Displays text with no prefix to stream defined in INCD_MESSAGE_STREAM. */ /*! \def INCD_FATAL(msg) * \brief Displays fatal error to console, then halts program. * After it displays the fatal error, it will throw a std::runtime_error * exception, so that the source of the fatal error may be backtraced * with a debugger. */ /*! \def INCD_ERROR(msg) * \brief Displays error to console, but doesn't halt program. * Fun fact: the output to the console is identical to that of INCD_FATAL. */ /*! \def INCD_WARNING(msg) * \brief Displays a warning to console. */ /*! \def INCD_DEBUG(msg) * \brief Displays a debug message to console. */ /*! \def INCD_TEST_HEADER(name) * \brief Denotes the beginning of a test. * When you are testing something in a test file, use this at the beginning of a test * to tell the user that a new test is starting. * * For example: * \include TestUtil.cpp */ /*! \def INCD_TEST_ASSERT(expected, recieved) * \brief Displays the result of a test. * Displays the value of \a expected and \a recieved, as well as the code for \a recieved * so that the user can see what the test was for. */ #ifndef __LIB_INCANDESCENCE_UTIL_H #define __LIB_INCANDESCENCE_UTIL_H #include <iostream> #include <string> #include <fstream> #include <vector> #include <map> #include <sstream> #define INCD_MESSAGE_STREAM cout #define INCD_MESSAGE_PREFIX "[Incandescence "<<__FILE__<<":"<<__LINE__<<"] " #define INCD_MESSAGE_PREFIX_ERROR INCD_MESSAGE_PREFIX<<"error: " #define INCD_MESSAGE_PREFIX_WARNING INCD_MESSAGE_PREFIX<<"warning: " #define INCD_MESSAGE_PREFIX_DEBUG INCD_MESSAGE_PREFIX<<"debug: " #define INCD_MESSAGE_PREFIX_TEST INCD_MESSAGE_PREFIX<<"test: " #define INCD_MESSAGE_DISPLAY(msg) {INCD_MESSAGE_STREAM<<msg<<"\n";} #define INCD_FATAL(msg) {INCD_MESSAGE_DISPLAY(INCD_MESSAGE_PREFIX_ERROR<<msg);throw std::runtime_error("internal incandescence error");} #define INCD_ERROR(msg) {INCD_MESSAGE_DISPLAY(INCD_MESSAGE_PREFIX_ERROR<<msg);} #define INCD_WARNING(msg) {INCD_MESSAGE_DISPLAY(INCD_MESSAGE_PREFIX_WARNING<<msg);} #define INCD_DEBUG(msg) {INCD_MESSAGE_DISPLAY(INCD_MESSAGE_PREFIX_WARNING<<msg);} #define INCD_TEST_HEADER(name) {INCD_MESSAGE_DISPLAY(INCD_MESSAGE_PREFIX_TEST<<"running '"<<name<<"'");} #define INCD_TEST_ASSERT(expected, recieved) { \ std::stringstream _ssExpected; \ _ssExpected << expected; \ std::stringstream _ssRecieved; \ _ssRecieved << recieved; \ if (_ssExpected.str().compare(_ssRecieved.str()) == 0) \ { \ INCD_MESSAGE_DISPLAY(INCD_MESSAGE_PREFIX_TEST << " '" << #expected << "' succeeded ('" << _ssExpected.str() << "' == '" << _ssRecieved.str() << "')."); \ } \ else \ { \ INCD_MESSAGE_DISPLAY(INCD_MESSAGE_PREFIX_TEST << " '" << #expected << "' failed ('" << _ssExpected.str() << "' != '" << _ssRecieved.str() << "')."); \ } \ } /*! Namespace for all LibIncandescence classes/methods/global variables. */ namespace incandescence { using namespace std; /*! Tests to see if a file exists. * \param path The path of the file. */ bool fileExists(string path); /*! Reads the contents of a text file into memory and returns it as a string. * \param path The path of the file. */ string loadFile(string path); } #endif
olivettikatz/libincandescence
util/Util.h
C
gpl-3.0
5,130
<?php define("LOG_LEVEL", -1); /* quality assurance */ define("DEBUG_MSG", false); //define("REQUEST_URI", $_SERVER["REQUEST_URI"]); # root directory //define("REQUEST_URI", substr($_SERVER["REQUEST_URI"], LENGTH)); # replace LENGTH with (path-length) to avoid useless function call define("REQUEST_URI", ($_SERVER["SCRIPT_NAME"] == "/index.php") ? $_SERVER["REQUEST_URI"] : substr($_SERVER["REQUEST_URI"], strlen(dirname($_SERVER["SCRIPT_NAME"])))); # portable alternative. cost: 1 eval + 3 function call. //define("EPR", "/var/opt"); define("EPR", strtr(dirname(__FILE__), "\\", "/")); # portable alternative. define("FWK", EPR); # only if not in public folder require_once FWK."/classes/FrontController.php"; require_once FWK."/classes/CGI.php"; ?>
wilaheng/wila
index.php
PHP
gpl-3.0
755
namespace MQCloud.Transport.Implementation { internal class ThematicOperationResponse<T> : ThematicMessage<T> { public int CallbackId { get; set; } } }
mqcloud/csharp
Transport/TransportAPI/Implementation/ThematicOperationResponse.cs
C#
gpl-3.0
167
CC = g++ LIBRARY =Newmat10D/libnewmat.a cluster-1.49/src/libcluster.a -L./boost/lib LIBRARY_STATIC=Newmat10D/libnewmat.a cluster-1.49/src/libcluster.a boost/lib/libboost_regex.a -static-libstdc++ -static-libgcc INCLUDE =-I./Newmat10D -I./Subset_library/ -I./boost/include default: all all: tar -zxvf Newmat10D.tar.gz cd Newmat10D && tar -zxvf newmat10D.tar.gz cp Newmat10D/nm_gnu.mak Newmat10D/Makefile make -C Newmat10D tar -zxvf cluster-1.49.tar.gz cd ./cluster-1.49 && perl Makefile.PL make -C cluster-1.49 tar -jxvf boost_1_64_0a.tar.bz2 tar -jxvf boost_1_64_0b.tar.bz2 tar -jxvf boost_1_64_0c.tar.bz2 tar -jxvf boost_1_64_0d.tar.bz2 cd boost_1_64_0 && ./bootstrap.sh --prefix=../boost --with-libraries=regex cd boost_1_64_0 && ./bjam install cd boost_1_64_0/libs/regex/build && make -fgcc.mak cd boost_1_64_0/libs/regex/build/gcc && ln -s libboost_regex-gcc-1_64.a libboost_regex.a $(CC) -c -g Subset_library/subset.C -o Subset_library/subset.o $(CC) -c S3det_v2.4.cpp $(INCLUDE) $(CC) -o S3det_v2.4.exe S3det_v2.4.o ./Subset_library/subset.o -lm $(LIBRARY_STATIC) $(CC) -c MCdet_scores_v2.1.cpp $(INCLUDE) $(CC) -o MCdet_v2.1.exe MCdet_scores_v2.1.o -lm $(LIBRARY_STATIC) clean: make clean -C cluster-1.49 make clean -C boost_1_64_0 cd Newmat10D && rm *.o && rm libnewmat.a rm Subset_library/subset.o rm S3det_v2.4.exe rm MCdet_v2.1.exe
david-juan/ChromDet
S3Det_modified/Makefile
Makefile
gpl-3.0
1,384
var inherit = function(){ $('*[inherit="source"]').change(function(){ $.get('/admin/libio/variety/hierarchy/' + $(this).val(), function(data){ $('*[inherit="target"]').each(function(key, input){ var id = $(input).prop('id'); var fieldName = id.substring(id.indexOf('_') + 1); $(input).val(data[fieldName]); if( $(input).prop('tagName') == 'SELECT' ) $(input).trigger('change'); }); }); }); }; $(document).ready(inherit); $(document).on('sonata-admin-setup-list-modal sonata-admin-append-form-element', inherit);
libre-informatique/SymfonyLibrinfoVarietiesBundle
src/Resources/public/js/inherit.js
JavaScript
gpl-3.0
651
using System.Collections; using System.Collections.Generic; using BaiRong.Core; using SiteServer.CMS.Core; using SiteServer.CMS.Model; namespace SiteServer.CMS.ImportExport { public class SiteTemplateManager { private readonly string _rootPath; private SiteTemplateManager(string rootPath) { _rootPath = rootPath; DirectoryUtils.CreateDirectoryIfNotExists(_rootPath); } public static SiteTemplateManager GetInstance(string rootPath) { return new SiteTemplateManager(rootPath); } public static SiteTemplateManager Instance => new SiteTemplateManager(PathUtility.GetSiteTemplatesPath(string.Empty)); public void DeleteSiteTemplate(string siteTemplateDir) { var directoryPath = PathUtils.Combine(_rootPath, siteTemplateDir); DirectoryUtils.DeleteDirectoryIfExists(directoryPath); var filePath = PathUtils.Combine(_rootPath, siteTemplateDir + ".zip"); FileUtils.DeleteFileIfExists(filePath); } public bool IsSiteTemplateDirectoryExists(string siteTemplateDir) { var siteTemplatePath = PathUtils.Combine(_rootPath, siteTemplateDir); return DirectoryUtils.IsDirectoryExists(siteTemplatePath); } public int GetSiteTemplateCount() { var directorys = DirectoryUtils.GetDirectoryPaths(_rootPath); return directorys.Length; } public List<string> GetDirectoryNameLowerList() { var directorys = DirectoryUtils.GetDirectoryNames(_rootPath); var list = new List<string>(); foreach (var directoryName in directorys) { list.Add(directoryName.ToLower().Trim()); } return list; } public SortedList GetSiteTemplateSortedList() { var sortedlist = new SortedList(); var directoryPaths = DirectoryUtils.GetDirectoryPaths(_rootPath); foreach (var siteTemplatePath in directoryPaths) { var metadataXmlFilePath = PathUtility.GetSiteTemplateMetadataPath(siteTemplatePath, DirectoryUtils.SiteTemplates.FileMetadata); if (FileUtils.IsFileExists(metadataXmlFilePath)) { var siteTemplateInfo = Serializer.ConvertFileToObject(metadataXmlFilePath, typeof(SiteTemplateInfo)) as SiteTemplateInfo; if (siteTemplateInfo != null) { var directoryName = PathUtils.GetDirectoryName(siteTemplatePath); sortedlist.Add(directoryName, siteTemplateInfo); } } } return sortedlist; } public void ImportSiteTemplateToEmptyPublishmentSystem(int publishmentSystemId, string siteTemplateDir, bool isUseTables, bool isImportContents, bool isImportTableStyles, string administratorName) { var siteTemplatePath = PathUtility.GetSiteTemplatesPath(siteTemplateDir); if (DirectoryUtils.IsDirectoryExists(siteTemplatePath)) { var publishmentSystemInfo = PublishmentSystemManager.GetPublishmentSystemInfo(publishmentSystemId); var templateFilePath = PathUtility.GetSiteTemplateMetadataPath(siteTemplatePath, DirectoryUtils.SiteTemplates.FileTemplate); var tableDirectoryPath = PathUtility.GetSiteTemplateMetadataPath(siteTemplatePath, DirectoryUtils.SiteTemplates.Table); var menuDisplayFilePath = PathUtility.GetSiteTemplateMetadataPath(siteTemplatePath, DirectoryUtils.SiteTemplates.FileMenuDisplay); var tagStyleFilePath = PathUtility.GetSiteTemplateMetadataPath(siteTemplatePath, DirectoryUtils.SiteTemplates.FileTagStyle); var adFilePath = PathUtility.GetSiteTemplateMetadataPath(siteTemplatePath, DirectoryUtils.SiteTemplates.FileAd); var seoFilePath = PathUtility.GetSiteTemplateMetadataPath(siteTemplatePath, DirectoryUtils.SiteTemplates.FileSeo); var stlTagPath = PathUtility.GetSiteTemplateMetadataPath(siteTemplatePath, DirectoryUtils.SiteTemplates.FileStlTag); var gatherRuleFilePath = PathUtility.GetSiteTemplateMetadataPath(siteTemplatePath, DirectoryUtils.SiteTemplates.FileGatherRule); var inputDirectoryPath = PathUtility.GetSiteTemplateMetadataPath(siteTemplatePath, DirectoryUtils.SiteTemplates.Input); var configurationFilePath = PathUtility.GetSiteTemplateMetadataPath(siteTemplatePath, DirectoryUtils.SiteTemplates.FileConfiguration); var siteContentDirectoryPath = PathUtility.GetSiteTemplateMetadataPath(siteTemplatePath, DirectoryUtils.SiteTemplates.SiteContent); var contentModelPath = PathUtility.GetSiteTemplateMetadataPath(siteTemplatePath,DirectoryUtils.SiteTemplates.FileContentModel); var importObject = new ImportObject(publishmentSystemId); importObject.ImportFiles(siteTemplatePath, true); importObject.ImportTemplates(templateFilePath, true, administratorName); importObject.ImportAuxiliaryTables(tableDirectoryPath, isUseTables); importObject.ImportMenuDisplay(menuDisplayFilePath, true); importObject.ImportTagStyle(tagStyleFilePath, true); importObject.ImportAd(adFilePath, true); importObject.ImportSeo(seoFilePath, true); importObject.ImportStlTag(stlTagPath, true); importObject.ImportGatherRule(gatherRuleFilePath, true); importObject.ImportInput(inputDirectoryPath, true); importObject.ImportConfiguration(configurationFilePath); importObject.ImportContentModel(contentModelPath, true); var filePathArrayList = ImportObject.GetSiteContentFilePathArrayList(siteContentDirectoryPath); foreach (string filePath in filePathArrayList) { importObject.ImportSiteContent(siteContentDirectoryPath, filePath, isImportContents); } DataProvider.NodeDao.UpdateContentNum(publishmentSystemInfo); if (isImportTableStyles) { importObject.ImportTableStyles(tableDirectoryPath); } importObject.RemoveDbCache(); } } public static void ExportPublishmentSystemToSiteTemplate(PublishmentSystemInfo publishmentSystemInfo, string siteTemplateDir) { var exportObject = new ExportObject(publishmentSystemInfo.PublishmentSystemId); var siteTemplatePath = PathUtility.GetSiteTemplatesPath(siteTemplateDir); //导出模板 var templateFilePath = PathUtility.GetSiteTemplateMetadataPath(siteTemplatePath, DirectoryUtils.SiteTemplates.FileTemplate); exportObject.ExportTemplates(templateFilePath); //导出辅助表及样式 var tableDirectoryPath = PathUtility.GetSiteTemplateMetadataPath(siteTemplatePath, DirectoryUtils.SiteTemplates.Table); exportObject.ExportTablesAndStyles(tableDirectoryPath); //导出下拉菜单 var menuDisplayFilePath = PathUtility.GetSiteTemplateMetadataPath(siteTemplatePath, DirectoryUtils.SiteTemplates.FileMenuDisplay); exportObject.ExportMenuDisplay(menuDisplayFilePath); //导出模板标签样式 var tagStyleFilePath = PathUtility.GetSiteTemplateMetadataPath(siteTemplatePath, DirectoryUtils.SiteTemplates.FileTagStyle); exportObject.ExportTagStyle(tagStyleFilePath); //导出广告 var adFilePath = PathUtility.GetSiteTemplateMetadataPath(siteTemplatePath, DirectoryUtils.SiteTemplates.FileAd); exportObject.ExportAd(adFilePath); //导出采集规则 var gatherRuleFilePath = PathUtility.GetSiteTemplateMetadataPath(siteTemplatePath, DirectoryUtils.SiteTemplates.FileGatherRule); exportObject.ExportGatherRule(gatherRuleFilePath); //导出提交表单 var inputDirectoryPath = PathUtility.GetSiteTemplateMetadataPath(siteTemplatePath, DirectoryUtils.SiteTemplates.Input); exportObject.ExportInput(inputDirectoryPath); //导出站点属性以及站点属性表单 var configurationFilePath = PathUtility.GetSiteTemplateMetadataPath(siteTemplatePath, DirectoryUtils.SiteTemplates.FileConfiguration); exportObject.ExportConfiguration(configurationFilePath); //导出SEO var seoFilePath = PathUtility.GetSiteTemplateMetadataPath(siteTemplatePath, DirectoryUtils.SiteTemplates.FileSeo); exportObject.ExportSeo(seoFilePath); //导出自定义模板语言 var stlTagFilePath = PathUtility.GetSiteTemplateMetadataPath(siteTemplatePath, DirectoryUtils.SiteTemplates.FileStlTag); exportObject.ExportStlTag(stlTagFilePath); //导出关联字段 var relatedFieldDirectoryPath = PathUtility.GetSiteTemplateMetadataPath(siteTemplatePath, DirectoryUtils.SiteTemplates.RelatedField); exportObject.ExportRelatedField(relatedFieldDirectoryPath); //导出内容模型(自定义添加的) var contentModelDirectoryPath = PathUtility.GetSiteTemplateMetadataPath(siteTemplatePath, DirectoryUtils.SiteTemplates.FileContentModel); exportObject.ExportContentModel(contentModelDirectoryPath); } } }
kk141242/siteserver
source/SiteServer.CMS/ImportExport/SiteTemplateManager.cs
C#
gpl-3.0
9,736
<head> <meta charset="UTF-8"> <meta name="robots" content="noindex"> <meta http-equiv="content-type" content="text/html; charset=UTF-8"> <meta content='width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=0' name='viewport' /> <meta name="HandheldFriendly" content="true" /> <meta name="apple-mobile-web-app-capable" content="YES" /> <link href="nv.d3.min.css" rel="stylesheet"> <script src="nv.d3.min.js"></script> <script src="/lib/stream_layers.js"></script> <title>the school system</title> </head>
givinalis/sms
index.html
HTML
gpl-3.0
535
///////////////////////////////////////////////////////////////////////////////// // // Copyright (C) 2018- Equinor ASA // // ResInsight 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. // // ResInsight 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 at <http://www.gnu.org/licenses/gpl.html> // for more details. // ///////////////////////////////////////////////////////////////////////////////// #pragma once #include "RimLegendConfig.h" #include "cafPdmChildField.h" #include "cafPdmField.h" #include "cafPdmObject.h" #include "RigFemResultPosEnum.h" #include "RimFemResultObserver.h" #include <QList> #include <vector> class RigFemResultAddress; class RimRegularLegendConfig; //================================================================================================== /// /// //================================================================================================== class RimTensorResults : public RimFemResultObserver, public caf::PdmObject { CAF_PDM_HEADER_INIT; public: enum TensorColors { WHITE_GRAY_BLACK, ORANGE_BLUE_WHITE, MAGENTA_BROWN_GRAY, RESULT_COLORS }; enum ScaleMethod { RESULT, CONSTANT }; public: RimTensorResults(); ~RimTensorResults() override; RigFemResultAddress selectedTensorResult() const; void setShowTensors( bool enableTensors ); bool showTensors() const; bool showPrincipal1() const; bool showPrincipal2() const; bool showPrincipal3() const; float threshold() const; float sizeScale() const; TensorColors vectorColors() const; ScaleMethod scaleMethod() const; void mappingRange( double* min, double* max ) const; std::vector<RigFemResultAddress> observedResults() const override; static RigFemResultPosEnum resultPositionType(); QString resultFieldName() const; static QString uiFieldName( const QString& fieldName ); caf::PdmChildField<RimRegularLegendConfig*> arrowColorLegendConfig; private: std::vector<std::string> getResultMetaDataForUIFieldSetting(); void fieldChangedByUi( const caf::PdmFieldHandle* changedField, const QVariant& oldValue, const QVariant& newValue ) override; caf::PdmFieldHandle* objectToggleField() override; QList<caf::PdmOptionItemInfo> calculateValueOptions( const caf::PdmFieldHandle* fieldNeedingOptions, bool* useOptionsOnly ) override; void defineUiOrdering( QString uiConfigName, caf::PdmUiOrdering& uiOrdering ) override; void initAfterRead() override; void defineEditorAttribute( const caf::PdmFieldHandle* field, QString uiConfigName, caf::PdmUiEditorAttribute* attribute ) override; void defineUiTreeOrdering( caf::PdmUiTreeOrdering& uiTreeOrdering, QString uiConfigName = "" ) override; static QString fieldNameFromUi( const QString& uiFieldName ); private: caf::PdmField<bool> m_showTensors; caf::PdmField<QString> m_resultFieldName; caf::PdmField<QString> m_resultFieldNameUiField; caf::PdmField<bool> m_principal1; caf::PdmField<bool> m_principal2; caf::PdmField<bool> m_principal3; caf::PdmField<float> m_threshold; caf::PdmField<caf::AppEnum<TensorColors>> m_vectorColor; caf::PdmField<caf::AppEnum<ScaleMethod>> m_scaleMethod; caf::PdmField<float> m_sizeScale; caf::PdmField<RimLegendConfig::RangeModeEnum> m_rangeMode; };
OPM/ResInsight
ApplicationLibCode/ProjectDataModel/RimTensorResults.h
C
gpl-3.0
4,263
<?php function smarty_function_chart_date_range($params, &$smarty) { global $L; $name_id = $params["name_id"]; $default = $params["default"]; $lines = array(); $lines[] = "<select name=\"$name_id\" id=\"$name_id\">"; $lines[] = "<option value=\"everything\" " . (($default == "everything") ? "selected" : "") . ">{$L["phrase_all_time"]}</option>"; $lines[] = "<optgroup label=\"{$L["phrase_days_or_weeks"]}\">"; $lines[] = "<option value=\"last_7_days\" " . (($default == "last_7_days") ? "selected" : "") . ">{$L["phrase_last_7_days"]}</option>"; $lines[] = "<option value=\"last_10_days\" " . (($default == "last_10_days") ? "selected" : "") . ">{$L["phrase_last_10_days"]}</option>"; $lines[] = "<option value=\"last_14_days\" " . (($default == "last_14_days") ? "selected" : "") . ">{$L["phrase_last_2_weeks"]}</option>"; $lines[] = "<option value=\"last_21_days\" " . (($default == "last_21_days") ? "selected" : "") . ">{$L["phrase_last_3_weeks"]}</option>"; $lines[] = "<option value=\"last_30_days\" " . (($default == "last_30_days") ? "selected" : "") . ">{$L["phrase_last_30_days"]}</option>"; $lines[] = "</optgroup>"; $lines[] = "<optgroup label=\"{$L["word_months"]}\">"; $lines[] = "<option value=\"year_to_date\" " . (($default == "year_to_date") ? "selected" : "") . ">{$L["phrase_year_to_date"]}</option>"; $lines[] = "<option value=\"month_to_date\" " . (($default == "month_to_date") ? "selected" : "") . ">{$L["phrase_month_to_date"]}</option>"; $lines[] = "<option value=\"last_2_months\" " . (($default == "last_2_months") ? "selected" : "") . ">{$L["phrase_last_2_months"]}</option>"; $lines[] = "<option value=\"last_3_months\" " . (($default == "last_3_months") ? "selected" : "") . ">{$L["phrase_last_3_months"]}</option>"; $lines[] = "<option value=\"last_4_months\" " . (($default == "last_4_months") ? "selected" : "") . ">{$L["phrase_last_4_months"]}</option>"; $lines[] = "<option value=\"last_5_months\" " . (($default == "last_5_months") ? "selected" : "") . ">{$L["phrase_last_5_months"]}</option>"; $lines[] = "<option value=\"last_6_months\" " . (($default == "last_6_months") ? "selected" : "") . ">{$L["phrase_last_6_months"]}</option>"; $lines[] = "</optgroup>"; $lines[] = "<optgroup label=\"{$L["word_years"]}\">"; $lines[] = "<option value=\"last_12_months\" " . (($default == "last_12_months") ? "selected" : "") . ">{$L["phrase_last_12_months"]}</option>"; $lines[] = "<option value=\"last_2_years\" " . (($default == "last_2_years") ? "selected" : "") . ">{$L["phrase_last_2_years"]}</option>"; $lines[] = "<option value=\"last_3_years\" " . (($default == "last_3_years") ? "selected" : "") . ">{$L["phrase_last_3_years"]}</option>"; $lines[] = "<option value=\"last_4_years\" " . (($default == "last_4_years") ? "selected" : "") . ">{$L["phrase_last_4_years"]}</option>"; $lines[] = "<option value=\"last_5_years\" " . (($default == "last_5_years") ? "selected" : "") . ">{$L["phrase_last_5_years"]}</option>"; $lines[] = "</optgroup>"; $lines[] = "</select>"; echo implode("\n", $lines); }
formtools/module-data_visualization
smarty_plugins/function.chart_date_range.php
PHP
gpl-3.0
3,073
# Qt library # # Notes: # There's no performance penalty for importing all Qt modules into whichever modules # need access to at least some Qt modules, so for simplicity's sake that's what we'll do. from util import RequiredImportError from constants import PYSIDE, PYQT4 import qt_helper _qtLib = qt_helper.qtLib def QtLib(): """Returns PYSIDE or PYQT4, whichever is being used by the program.""" return _qtLib if _qtLib == PYSIDE: from PySide import QtGui, QtCore, QtSql from PySide.QtGui import * from PySide.QtCore import * from PySide.QtSql import * from PySide.phonon import Phonon elif _qtLib == PYQT4: import sip sip.setapi('QString', 2) # Prevent QString from being returned by PyQt4 functions. sip.setapi('QVariant', 2) # Prevent QVariant from being returned by PyQt4 functions. from PyQt4 import QtGui, QtCore, QtSql from PyQt4.QtGui import * from PyQt4.QtCore import * from PyQt4.QtSql import * from PyQt4.phonon import Phonon else: raise RequiredImportError('No Qt library found.')
pylonsoflight/kea
qt.py
Python
gpl-3.0
1,023
<!DOCTYPE html> <!--[if lt IE 7]><html class="no-js lt-ie10 lt-ie9 lt-ie8 lt-ie7 "> <![endif]--> <!--[if IE 7]><html class="no-js lt-ie10 lt-ie9 lt-ie8"> <![endif]--> <!--[if IE 8]><html class="no-js lt-ie10 lt-ie9"> <![endif]--> <!--[if IE 9]><html class="no-js lt-ie10"> <![endif]--> <!--[if gt IE 8]><!--> <html class="no-js"> <!--<![endif]--> <head> <!-- Basic Page Needs --> <meta charset="utf-8"> <title>Be</title> <meta name="description" content="" > <meta name="author" content=""> <!-- Mobile Specific Metas --> <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1"> <!-- Favicons --> <link rel="shortcut icon" href="images/favicon.ico"> <!-- FONTS --> <link rel='stylesheet' id='Roboto-css' href='http://fonts.googleapis.com/css?family=Roboto:100,300,400,400italic,700'> <link rel='stylesheet' id='Lato-css' href='http://fonts.googleapis.com/css?family=Lato:300'> <link rel='stylesheet' id='Patua+One-css' href='http://fonts.googleapis.com/css?family=Patua+One:100,300,400,400italic,700'> <!-- CSS --> <link rel='stylesheet' id='global-css' href='../../css/global.css'> <link rel='stylesheet' id='structure-css' href='css/structure.css'> <link rel='stylesheet' id='local-css' href='css/shop.css'> <link rel='stylesheet' id='custom-css' href='css/custom.css'> </head> <!-- body --> <body class="archive tax-product_cat term-outdoor-shoes term-52 woocommerce woocommerce-page with_aside aside_left layout-full-width header-modern sticky-header sticky-white subheader-both-center"> <!-- #Wrapper --> <!-- Main Theme Wrapper --> <div id="Wrapper"> <!-- #Header_bg --> <!-- Header Wrapper --> <div id="Header_wrapper" class="bg-parallax" data-stellar-background-ratio="0.5"> <!-- #Header --> <!-- Header --> <header id="Header"> <!-- Header Top - Info Area --> <div id="Action_bar"> <div class="container"> <div class="column one"> <!-- Header - contact info area--> <ul class="contact_details"> <li class="slogan"> Have any questions? </li> <li class="phone"> <i class="icon-phone"></i><a href="tel:+61383766284">+61 383 766 284</a> </li> <li class="mail"> <i class="icon-mail-line"></i><a href="mailto:noreply@envato.com">noreply@envato.com</a> </li> </ul> <!--Social info area--> <ul class="social"> <li class="skype"> <a href="#" title="Skype"><i class="icon-skype"></i></a> </li> <li class="facebook"> <a href="#" title="Facebook"><i class="icon-facebook"></i></a> </li> <li class="googleplus"> <a href="#" title="Google+"><i class="icon-gplus"></i></a> </li> <li class="twitter"> <a href="#" title="Twitter"><i class="icon-twitter"></i></a> </li> <li class="vimeo"> <a href="#" title="Vimeo"><i class="icon-vimeo"></i></a> </li> <li class="youtube"> <a href="#" title="YouTube"><i class="icon-play"></i></a> </li> <li class="flickr"> <a href="#" title="Flickr"><i class="icon-flickr"></i></a> </li> <li class="linkedin"> <a href="#" title="LinkedIn"><i class="icon-linkedin"></i></a> </li> </ul> </div> </div> </div> <!-- .header_placeholder 4sticky --> <!-- Header - Logo and Menu area --> <div id="Top_bar"> <div class="container"> <div class="column one"> <div class="top_bar_left clearfix"> <!-- .logo --> <!-- Logo--> <div class="logo"> <a id="logo" href="#" title="BeShop - BeTheme"><img class="logo-main scale-with-grid" src="images/shop.png" alt="BeShop - BeTheme" /><img class="logo-sticky scale-with-grid" src="images/shop.png" alt="" /></a> </div> <!-- Main menu--> <div class="menu_wrapper"> <nav id="menu"> <ul id="menu-main-menu" class="menu"> <li> <a href="../../index-shop.html"><span>Home</span></a> </li> <li class="menu-item-type-taxonomy menu-item-object-product_cat "> <a href="for-her.html"><span>For her</span></a> <ul class="sub-menu mfn-megamenu mfn-megamenu-3"> <li class="menu-item-type-taxonomy menu-item-object-product_cat mfn-megamenu-cols-3"> <a class="mfn-megamenu-title" href="for-her-clothing-for-her.html"><span>Clothing</span></a> <ul class="sub-menu mfn-megamenu mfn-megamenu-3"> <li class="menu-item-type-taxonomy menu-item-object-product_cat"> <a href="for-her-dresses.html"><span>Dresses</span></a> </li> <li class="menu-item-type-taxonomy menu-item-object-product_cat"> <a href="for-her-jackets.html"><span>Jackets</span></a> </li> <li class="menu-item-type-taxonomy menu-item-object-product_cat"> <a href="for-her-jeans.html"><span>Jeans</span></a> </li> <li class="menu-item-type-taxonomy menu-item-object-product_cat"> <a href="for-her-shorts.html"><span>Shorts</span></a> </li> <li class="menu-item-type-taxonomy menu-item-object-product_cat"> <a href="for-her-tops.html"><span>Tops</span></a> </li> </ul> </li> <li class="menu-item-type-taxonomy menu-item-object-product_cat mfn-megamenu-cols-3"> <a class="mfn-megamenu-title" href="shoes-for-her.html"><span>Shoes</span></a> <ul class="sub-menu mfn-megamenu mfn-megamenu-3"> <li class="menu-item-type-taxonomy menu-item-object-product_cat"> <a href="for-her-ankle-boots.html"><span>Ankle boots</span></a> </li> <li class="menu-item-type-taxonomy menu-item-object-product_cat"> <a href="for-her-ballet-pumps.html"><span>Ballet pumps</span></a> </li> <li class="menu-item-type-taxonomy menu-item-object-product_cat"> <a href="for-her-heals.html"><span>Heels</span></a> </li> <li class="menu-item-type-taxonomy menu-item-object-product_cat"> <a href="for-her-sandals.html"><span>Sandals</span></a> </li> <li class="menu-item-type-taxonomy menu-item-object-product_cat"> <a href="for-her-slippers.html"><span>Slippers</span></a> </li> </ul> </li> <li class="menu-item-type-taxonomy menu-item-object-product_cat mfn-megamenu-cols-3"> <a class="mfn-megamenu-title" href="for-her-accessories.html"><span>Accessories</span></a> <ul class="sub-menu mfn-megamenu mfn-megamenu-3"> <li class="menu-item-type-taxonomy menu-item-object-product_cat"> <a href="for-her-bags-accessories.html"><span>Bags</span></a> </li> <li class="menu-item-type-taxonomy menu-item-object-product_cat"> <a href="for-her-belts.html"><span>Belts</span></a> </li> <li class="menu-item-type-taxonomy menu-item-object-product_cat"> <a href="for-her-hats-caps-accessories.html"><span>Hats &#038; Caps</span></a> </li> <li class="menu-item-type-taxonomy menu-item-object-product_cat"> <a href="for-her-rucksacks-accessories.html"><span>Rucksacks</span></a> </li> <li class="menu-item-type-taxonomy menu-item-object-product_cat"> <a href="for-her-sunglasses.html"><span>Sunglasses</span></a> </li> </ul> </li> </ul> </li> <li class="menu-item-type-taxonomy menu-item-object-product_cat "> <a href="for-him.html"><span>For him</span></a> <ul class="sub-menu mfn-megamenu mfn-megamenu-3"> <li class="menu-item-type-taxonomy menu-item-object-product_cat mfn-megamenu-cols-3"> <a class="mfn-megamenu-title" href="clothing-for-her-for-him.html"><span>Clothing</span></a> <ul class="sub-menu mfn-megamenu mfn-megamenu-3"> <li class="menu-item-type-taxonomy menu-item-object-product_cat"> <a href="for-him-hoodies.html"><span>Hoodies</span></a> </li> <li class="menu-item-type-taxonomy menu-item-object-product_cat"> <a href="jackets-clothing-for-her-for-him.html"><span>Jackets</span></a> </li> <li class="menu-item-type-taxonomy menu-item-object-product_cat"> <a href="jeans-clothing-for-her-for-him.html"><span>Jeans</span></a> </li> <li class="menu-item-type-taxonomy menu-item-object-product_cat"> <a href="for-him-t-shirts.html"><span>T-shirts</span></a> </li> <li class="menu-item-type-taxonomy menu-item-object-product_cat"> <a href="for-him-trousers.html"><span>Trousers</span></a> </li> </ul> </li> <li class="menu-item-type-taxonomy menu-item-object-product_cat mfn-megamenu-cols-3"> <a class="mfn-megamenu-title" href="for-him-shoes.html"><span>Shoes</span></a> <ul class="sub-menu mfn-megamenu mfn-megamenu-3"> <li class="menu-item-type-taxonomy menu-item-object-product_cat"> <a href="for-him-business-shoes.html"><span>Business Shoes</span></a> </li> <li class="menu-item-type-taxonomy menu-item-object-product_cat"> <a href="for-him-moccasins.html"><span>Moccasins</span></a> </li> <li class="menu-item-type-taxonomy menu-item-object-product_cat"> <a href="for-him-outdoor-shoes.html"><span>Outdoor Shoes</span></a> </li> <li class="menu-item-type-taxonomy menu-item-object-product_cat"> <a href="for-him-sandals-shoes.html"><span>Sandals</span></a> </li> <li class="menu-item-type-taxonomy menu-item-object-product_cat"> <a href="for-him-trainers.html"><span>Trainers</span></a> </li> </ul> </li> <li class="menu-item-type-taxonomy menu-item-object-product_cat mfn-megamenu-cols-3"> <a class="mfn-megamenu-title" href="accessories-for-him.html"><span>Accessories</span></a> <ul class="sub-menu mfn-megamenu mfn-megamenu-3"> <li class="menu-item-type-taxonomy menu-item-object-product_cat"> <a href="for-him-bags.html"><span>Bags</span></a> </li> <li class="menu-item-type-taxonomy menu-item-object-product_cat"> <a href="belts-accessories-for-him.html"><span>Belts</span></a> </li> <li class="menu-item-type-taxonomy menu-item-object-product_cat"> <a href="for-him-hats-caps.html"><span>Hats &#038; Caps</span></a> </li> <li class="menu-item-type-taxonomy menu-item-object-product_cat"> <a href="for-him-rucksacks.html"><span>Rucksacks</span></a> </li> <li class="menu-item-type-taxonomy menu-item-object-product_cat"> <a href="sunglasses-accessories-for-him.html"><span>Sunglasses</span></a> </li> </ul> </li> </ul> </li> <li> <a href="about-us.html"><span>About us</span></a> </li> <li> <a href="faq.html"><span>FAQ</span></a> </li> <li> <a href="contact-us.html"><span>Contact us</span></a> </li> </ul> </nav><a class="responsive-menu-toggle " href="#"><i class="icon-menu"></i></a> </div> <!-- Secondary menu area - only for certain pages --> <div class="secondary_menu_wrapper"> <!-- #secondary-menu --> </div> <!-- Banner area - only for certain pages--> <div class="banner_wrapper"></div> <!-- Header Searchform area--> <div class="search_wrapper"> <!-- #searchform --> <form method="get" id="searchform" action="#"> <i class="icon_search icon-search"></i> <a href="#" class="icon_close"><i class="icon-cancel"></i></a> <input type="text" class="field" name="s" id="s" placeholder="Enter your search" /> <input type="submit" class="submit flv_disp_none" value="" /> </form> </div> </div> <div class="top_bar_right"> <div class="top_bar_right_wrapper"> <!-- Shopping cart icon--> <a id="header_cart" href="#"><i class="icon-basket"></i><span>0</span></a><a id="search_button" href="#"><i class="icon-search"></i></a> </div> </div> </div> </div> </div> </header> <!--Subheader area - only for certain pages --> <div id="Subheader"> <div class="container"> <div class="column one"> <h1 class="title">Outdoor Shoes</h1> </div> </div> </div> </div> <!-- #Content --> <!-- Main Content --> <div id="Content"> <div class="content_wrapper clearfix"> <!-- .sections_group --> <div class="sections_group"> <div class="section"> <div class="section_wrapper clearfix"> <div class="items_group clearfix"> <!-- One full width row--> <div class="column one woocommerce-content"> <div class="shop-filters"> <p class="woocommerce-result-count"> Showing all 2 results </p> <form class="woocommerce-ordering" method="get"> <select name="orderby" class="orderby"> <option value="menu_order" selected='selected'>Default sorting</option> <option value="popularity" >Sort by popularity</option> <option value="rating" >Sort by average rating</option> <option value="date" >Sort by newness</option> <option value="price" >Sort by price: low to high</option> <option value="price-desc" >Sort by price: high to low</option> </select> </form> </div> <div class="products_wrapper isotope_wrapper"> <ul class="products grid"> <li class="isotope-item post-31 product type-product status-publish has-post-thumbnail product_cat-business-shoes product_cat-moccasins product_cat-outdoor-shoes product_cat-sandals-shoes product_cat-slippers product_cat-trainers shipping-taxable purchasable product-type-simple product-cat-business-shoes product-cat-moccasins product-cat-outdoor-shoes product-cat-sandals-shoes product-cat-slippers product-cat-trainers instock"> <div class="image_frame scale-with-grid product-loop-thumb" > <div class="image_wrapper"> <a href="product-ninja-silhouette.html"><div class="mask"></div><img width="300" height="300" src="images/home_store_product15-300x300.jpg" class="scale-with-grid wp-post-image" alt="home_store_product15" /></a> <div class="image_links"> <a href="#" rel="nofollow" data-product_id="31" class="add_to_cart_button product_type_simple"><i class="icon-basket"></i></a><a class="link" href="product-ninja-silhouette.html"><i class="icon-link"></i></a> </div> </div><a href="product-ninja-silhouette.html"><span class="product-loading-icon added-cart"></span></a> </div> <div class="desc"> <h4><a href="product-ninja-silhouette.html">Ninja Silhouette</a></h4> <div class="star-rating" title="Rated 5.00 out of 5"> <span style="width:100%"><strong class="rating">5.00</strong> out of 5</span> </div> <span class="price"><span class="amount">&pound;20.00</span></span> </div> </li> <li class="isotope-item post-19 product type-product status-publish has-post-thumbnail product_cat-bags product_cat-ballet-pumps product_cat-belts product_cat-business-shoes product_cat-dresses product_cat-hats-caps product_cat-jackets-clothing-for-her-for-him product_cat-jeans product_cat-outdoor-shoes product_cat-rucksacks-accessories product_cat-sandals product_cat-sunglasses-accessories-for-him product_cat-t-shirts product_cat-tops product_cat-trainers shipping-taxable purchasable product-type-simple product-cat-bags product-cat-ballet-pumps product-cat-belts product-cat-business-shoes product-cat-dresses product-cat-hats-caps product-cat-jackets-clothing-for-her-for-him product-cat-jeans product-cat-outdoor-shoes product-cat-rucksacks-accessories product-cat-sandals product-cat-sunglasses-accessories-for-him product-cat-t-shirts product-cat-tops product-cat-trainers instock"> <div class="image_frame scale-with-grid product-loop-thumb" > <div class="image_wrapper"> <a href="product-premium-quality.html"><div class="mask"></div><img width="300" height="300" src="images/home_store_product17-300x300.jpg" class="scale-with-grid wp-post-image" alt="home_store_product17" /></a> <div class="image_links"> <a href="#" rel="nofollow" data-product_id="19" class="add_to_cart_button product_type_simple"><i class="icon-basket"></i></a><a class="link" href="product-premium-quality.html"><i class="icon-link"></i></a> </div> </div><a href="product-premium-quality.html"><span class="product-loading-icon added-cart"></span></a> </div> <div class="desc"> <h4><a href="product-premium-quality.html">Premium Quality</a></h4> <div class="star-rating" title="Rated 4.50 out of 5"> <span style="width:90%"><strong class="rating">4.50</strong> out of 5</span> </div> <span class="price"><span class="amount">&pound;20.00</span></span> </div> </li> </ul> </div> </div> </div> </div> </div> </div> <!-- .four-columns - sidebar --> <!-- Sidebar area--> <div class="sidebar four columns"> <div class="widget-area clearfix "> <aside id="woocommerce_widget_cart-2" class="widget woocommerce widget_shopping_cart"> <h3>Shopping Cart</h3><div class="widget_shopping_cart_content"></div> </aside> <aside id="woocommerce_product_categories-2" class="widget woocommerce widget_product_categories"> <h3>Product Categories</h3> <ul class="product-categories"> <li class="cat-item cat-item-25"> <a href="for-her.html">For her</a> </li> <li class="cat-item cat-item-26 cat-parent current-cat-parent"> <a href="#">For him</a> <ul class='children'> <li class="cat-item cat-item-32"> <a href="accessories-for-him.html">Accessories</a> </li> <li class="cat-item cat-item-41"> <a href="clothing-for-her-for-him.html">Clothing</a> </li> <li class="cat-item cat-item-27 cat-parent current-cat-parent"> <a href="#">Shoes</a> <ul class='children'> <li class="cat-item cat-item-39"> <a href="for-him-business-shoes.html">Business Shoes</a> </li> <li class="cat-item cat-item-51"> <a href="for-him-moccasins.html">Moccasins</a> </li> <li class="cat-item cat-item-52 current-cat"> <a href="../../index-shop.html">Outdoor Shoes</a> </li> <li class="cat-item cat-item-56"> <a href="for-him-sandals-shoes.html">Sandals</a> </li> <li class="cat-item cat-item-30"> <a href="for-him-trainers.html">Trainers</a> </li> </ul> </li> </ul> </li> </ul> </aside> <aside id="woocommerce_products-2" class="widget woocommerce widget_products"> <h3>Products</h3> <ul class="product_list_widget"> <li> <a href="product-woo-album-1.html" title="Woo Album #1"> <img width="180" height="180" src="images/home_store_product1-180x180.jpg" class="attachment-shop_thumbnail wp-post-image" alt="home_store_product1" /> <span class="product-title">Woo Album #1</span> </a> <span class="amount">&pound;9.00</span> </li> <li> <a href="product-woo-ninja-3.html" title="Woo Logo"> <img width="180" height="180" src="images/home_store_product2-180x180.jpg" class="attachment-shop_thumbnail wp-post-image" alt="home_store_product2" /> <span class="product-title">Woo Logo</span> </a> <span class="amount">&pound;15.00</span> </li> <li> <a href="product-woo-ninja-3.html" title="Woo Ninja"> <img width="180" height="180" src="images/home_store_product3-180x180.jpg" class="attachment-shop_thumbnail wp-post-image" alt="home_store_product3" /> <span class="product-title">Woo Ninja</span> </a> <span class="amount">&pound;15.00</span> </li> </ul> </aside> <aside id="woocommerce_product_search-2" class="widget woocommerce widget_product_search"> <h3>Search Products</h3> <form role="search" method="get" class="woocommerce-product-search" action="#"> <label class="screen-reader-text" for="s">Search for:</label> <input type="search" class="search-field" placeholder="Search Products&hellip;" value="" name="s" title="Search for:" /> <input type="submit" value="Search" /> <input type="hidden" name="post_type" value="product" /> </form> </aside> </div> </div> </div> </div> <!-- #Footer --> <!-- Footer--> <footer id="Footer" class="clearfix"> <div class="widgets_wrapper"> <div class="container"> <!-- One Third (1/3) Column --> <div class="column one-third"> <!-- Text Area --> <aside id="text-3" class="widget widget_text"> <h4>About us</h4> <div class="textwidget"> Curabitur et ligula. Ut molestie a, ultricies porta urna. Vestibulum commodo volutpat a, convallis. Phasellus fermentum in, dolor. Pellentesque facilisis. Nulla imper diet sit amet magna. Vestibulum dapibus, mauris nec malesuada fames ac turpis velit, rhoncus eu luctus et ac, laoreet enim. </div> </aside> </div> <!-- One Third (1/3) Column --> <div class="column one-third"> <!-- Text Area --> <aside id="text-2" class="widget widget_text"> <h4>Our mission</h4> <div class="textwidget"> Proin gravida nibh vel velit auctor aliquet. Aenean sollicitudin, lorem quis bibendum auctor, nisi elit consequat ipsum, nec sagittis sem nibh id elit. Duis sed odio sit amet. Sed ut imperdiet nisi. Proin condimentum fermentum nunc. Etiam pharetra, erat sed fermentum feugiat, velit mauris. </div> </aside> </div> <!-- One Third (1/3) Column --> <div class="column one-third"> <!-- Text Area --> <aside id="text-4" class="widget widget_text"> <h4>Shortcut links</h4> <div class="textwidget"> <ul class="flv_list_ul_46"> <li> <a href="#">Velit mauris</a> </li> <li> <a href="#">Entum feuis</a> </li> <li> <a href="#">Aliquam massa </a> </li> <li> <a href="#">Egestas quam</a> </li> </ul> <ul class="flv_list_ul_46"> <li> <a href="#">Aenean ligula</a> </li> <li> <a href="#">Dapibus at dolor</a> </li> <li> <a href="#">Molestie id</a> </li> <li> <a href="#">Vestibulum</a> </li> </ul> </div> </aside> </div> </div> </div> <!-- Footer copyright--> <div class="footer_copy"> <div class="container"> <div class="column one"> <a id="back_to_top" href="#" class="button button_left button_js"><span class="button_icon"><i class="icon-up-open-big"></i></span></a> <!-- Copyrights --> <div class="copyright"> &copy; 2015 BeShop - BeTheme. All Rights Reserved. <a target="_blank" rel="nofollow" href="http://themeforest.net/user/beantownthemes/portfolio?ref=BeantownThemes">Beantownthemes</a> </div> <!--Social info area--> <ul class="social"> <li class="skype"> <a href="#" title="Skype"><i class="icon-skype"></i></a> </li> <li class="facebook"> <a href="#" title="Facebook"><i class="icon-facebook"></i></a> </li> <li class="googleplus"> <a href="#" title="Google+"><i class="icon-gplus"></i></a> </li> <li class="twitter"> <a href="#" title="Twitter"><i class="icon-twitter"></i></a> </li> <li class="vimeo"> <a href="#" title="Vimeo"><i class="icon-vimeo"></i></a> </li> <li class="youtube"> <a href="#" title="YouTube"><i class="icon-play"></i></a> </li> <li class="flickr"> <a href="#" title="Flickr"><i class="icon-flickr"></i></a> </li> <li class="linkedin"> <a href="#" title="LinkedIn"><i class="icon-linkedin"></i></a> </li> </ul> </div> </div> </div> </footer> </div><!-- #Wrapper --> <!-- JS --> <script type="text/javascript" src="../../js/jquery-2.1.4.min.js"></script> <script type="text/javascript" src="../../js/mfn.menu.js"></script> <script type="text/javascript" src="../../js/jquery.plugins.js"></script> <script type="text/javascript" src="../../js/jquery.jplayer.min.js"></script> <script type="text/javascript" src="../../js/animations/animations.js"></script> <script type="text/javascript" src="../../js/scripts.js"></script> <script> //<![CDATA[ jQuery(window).load(function() { var retina = window.devicePixelRatio > 1 ? true : false; if (retina) { var retinaEl = jQuery("#logo img.logo-main"); var retinaLogoW = retinaEl.width(); var retinaLogoH = retinaEl.height(); retinaEl.attr("src", "images/retina-shop.png").width(retinaLogoW).height(retinaLogoH); var stickyEl = jQuery("#logo img.logo-sticky"); var stickyLogoW = stickyEl.width(); var stickyLogoH = stickyEl.height(); stickyEl.attr("src", "images/retina-shop.png").width(stickyLogoW).height(stickyLogoH); } }); //]]> </script> </body> </html>
blakel12/metavault
content/shop/for-him-outdoor-shoes.html
HTML
gpl-3.0
27,435
/* * This file is part of the L2J Global project. * * 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/>. */ package com.l2jglobal.gameserver.network.clientpackets; import com.l2jglobal.Config; import com.l2jglobal.commons.network.PacketReader; import com.l2jglobal.gameserver.model.actor.instance.L2PcInstance; import com.l2jglobal.gameserver.network.client.L2GameClient; import com.l2jglobal.gameserver.network.serverpackets.NpcHtmlMessage; /** * @author Global */ public class ExPCCafeRequestOpenWindowWithoutNPC implements IClientIncomingPacket { @Override public boolean read(L2GameClient client, PacketReader packet) { return true; } @Override public void run(L2GameClient client) { final L2PcInstance activeChar = client.getActiveChar(); if ((activeChar != null) && Config.PC_CAFE_ENABLED) { final NpcHtmlMessage html = new NpcHtmlMessage(); html.setFile(activeChar.getHtmlPrefix(), "data/html/pccafe.htm"); activeChar.sendPacket(html); } } }
rubenswagner/L2J-Global
java/com/l2jglobal/gameserver/network/clientpackets/ExPCCafeRequestOpenWindowWithoutNPC.java
Java
gpl-3.0
1,579
<?php /** * Copyright (c) 2014 Educ-Action * * This file is part of ADES. * * ADES 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. * * ADES 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 ADES. If not, see <http://www.gnu.org/licenses/>. */ include ("inc/prive.inc.php"); include ("inc/funcdate.inc.php"); include ("inc/fonctions.inc.php"); include ("config/constantes.inc.php"); Normalisation(); ?> <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <meta content="text/html; charset=ISO-8859-1" http-equiv="content-type"> <title><?php echo ECOLE ?></title> <link media="screen" rel="stylesheet" href="config/screen.css" type="text/css"> <link media="print" rel="stylesheet" href="config/print.css" type="text/css"> <link rel="stylesheet" href="config/menu.css" type="text/css" media="screen"> <script type="text/javascript" src="inc/overlib/overlib.js"><!-- overLIB (c) Erik Bosrup --> </script> </head> <body> <div id="overDiv" style="position:absolute; visibility:hidden; z-index:1000;"></div> <?php // autorisations pour la page autoriser (); // tout le monde // menu require ("inc/menu.inc.php"); ?> <div id="texte"> <h2>Sélection du nom de l'élève</h2> <?php $classe=(isset($_REQUEST['classe'])?$_REQUEST['classe']:Null); include ("config/confbd.inc.php"); $lienDB = mysql_connect($sql_serveur, $sql_user, $sql_passwd); mysql_select_db ($sql_bdd); // Recherche des élèves qui figurent dans la classe $classe $sql = "select ideleve, nom, prenom FROM ades_eleves "; $sql .= "WHERE classe = '$classe' ORDER BY nom, prenom"; $listeEleves = @mysql_query($sql); // on passe les élèves en revue echo "<h3>$classe</h3>\n"; $n=1; while ($eleve = mysql_fetch_array($listeEleves)) { foreach ($eleve as $key=>$rubrique) $$key = $rubrique; echo "<a href=\"ficheel.php?mode=voir&amp;ideleve=$ideleve\">"; echo "$n -> $nom $prenom</a><br>\n"; $n++; } echo retourIndex (); mysql_close ($lienDB); ?> </div> <div id="pied"><?php require ("inc/notice.inc.php"); ?></div> </body> </html>
doc212/ades
web/nomeleve.php
PHP
gpl-3.0
2,540
/* Generated By:JJTree: Do not edit this line. ASTSQLOrderByElem.java */ package com.hardcode.gdbms.parser; public class ASTSQLOrderByElem extends SimpleNode { public ASTSQLOrderByElem(int id) { super(id); } public ASTSQLOrderByElem(SQLEngine p, int id) { super(p, id); } /** Accept the visitor. **/ public Object jjtAccept(SQLEngineVisitor visitor, Object data) { return visitor.visit(this, data); } }
iCarto/siga
libGDBMS/src/main/java/com/hardcode/gdbms/parser/ASTSQLOrderByElem.java
Java
gpl-3.0
434
#!/usr/bin/python -tt # An incredibly simple agent. All we do is find the closest enemy tank, drive # towards it, and shoot. Note that if friendly fire is allowed, you will very # often kill your own tanks with this code. ################################################################# # NOTE TO STUDENTS # This is a starting point for you. You will need to greatly # modify this code if you want to do anything useful. But this # should help you to know how to interact with BZRC in order to # get the information you need. # # After starting the bzrflag server, this is one way to start # this code: # python agent0.py [hostname] [port] # # Often this translates to something like the following (with the # port name being printed out by the bzrflag server): # python agent0.py localhost 49857 ################################################################# import sys import math import time from bzrc import BZRC, Command class Agent(object): """Class handles all command and control logic for a teams tanks.""" def __init__(self, bzrc): self.go_straight = True self.bzrc = bzrc self.constants = self.bzrc.get_constants() self.commands = [] def tick(self, time_diff, shoot=False): print 'time_dif', time_diff """Some time has passed; decide what to do next.""" mytanks, othertanks, flags, shots = self.bzrc.get_lots_o_stuff() self.mytanks = mytanks self.othertanks = othertanks self.flags = flags self.shots = shots self.enemies = [tank for tank in othertanks if tank.color != self.constants['team']] self.commands = [] if shoot: print 'shooting' for tank in mytanks: self.tanks_shoot(tank) else: print 'go straight' if self.go_straight else 'turn instead' for tank in mytanks: self.testing_tanks(tank) self.go_straight = not self.go_straight results = self.bzrc.do_commands(self.commands) return self.go_straight def tanks_shoot(self, tank): self.bzrc.shoot(tank.index) def testing_tanks(self, tank): if self.go_straight: command = Command(tank.index, 1, 0, 0) else: command = Command(tank.index, 0, 0.6, 0) self.commands.append(command) def attack_enemies(self, tank): """Find the closest enemy and chase it, shooting as you go.""" best_enemy = None best_dist = 2 * float(self.constants['worldsize']) for enemy in self.enemies: if enemy.status != 'alive': continue dist = math.sqrt((enemy.x - tank.x)**2 + (enemy.y - tank.y)**2) if dist < best_dist: best_dist = dist best_enemy = enemy if best_enemy is None: command = Command(tank.index, 0, 0, False) self.commands.append(command) else: self.move_to_position(tank, best_enemy.x, best_enemy.y) def move_to_position(self, tank, target_x, target_y): """Set command to move to given coordinates.""" target_angle = math.atan2(target_y - tank.y, target_x - tank.x) relative_angle = self.normalize_angle(target_angle - tank.angle) command = Command(tank.index, 1, 2 * relative_angle, True) self.commands.append(command) def normalize_angle(self, angle): """Make any angle be between +/- pi.""" angle -= 2 * math.pi * int (angle / (2 * math.pi)) if angle <= -math.pi: angle += 2 * math.pi elif angle > math.pi: angle -= 2 * math.pi return angle def main(): # Process CLI arguments. try: execname, host, port = sys.argv except ValueError: execname = sys.argv[0] print >>sys.stderr, '%s: incorrect number of arguments' % execname print >>sys.stderr, 'usage: %s hostname port' % sys.argv[0] sys.exit(-1) # Connect. #bzrc = BZRC(host, int(port), debug=True) bzrc = BZRC(host, int(port)) agent = Agent(bzrc) prev_time = time.time() prev_time_shoot = time.time() wait = 8 # Run the agent try: while True: if time.time() > prev_time_shoot + 2: agent.tick(time.time() - prev_time_shoot, True) prev_time_shoot = time.time() if time.time() > prev_time + wait: went_straight = agent.tick(time.time() - prev_time) wait = 3 if went_straight else 8 prev_time = time.time() except KeyboardInterrupt: print "Exiting due to keyboard interrupt." bzrc.close() if __name__ == '__main__': main() # vim: et sw=4 sts=4
sm-github/bzrflag
bzagents/dumb_agent.py
Python
gpl-3.0
4,903
<?php // This file is part of Moodle - http://moodle.org/ // // Moodle is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // // Moodle is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with Moodle. If not, see <http://www.gnu.org/licenses/>. $string['multichoicewiris'] = 'Multiple choice - science'; $string['multichoicewiris_help'] = 'Like the standard Multiple choice, but you can deliver different question text and choices by inserting random numbers, formulas or plots. The feedback can also use the random values.'; $string['editingmultichoicewiris'] = 'Editing a multiple choice - math & science question by WIRIS'; $string['addingmultichoicewiris'] = 'Adding a multiple choice - math & science question by WIRIS'; $string['multichoicewirissummary'] = 'Like the standard Multiple choice, but you can deliver different question text and choices by inserting random numbers, formulas or plots. The feedback can also use the random values.'; $string['multichoicewiris_algorithm'] = 'Algorithm'; $string['multichoicewiris_wiris_variables'] = 'WIRIS variables '; $string['multichoicewiris_cantimportoverride'] = 'The multiple choice - math & science question could not be imported properly from Moodle 1.9 format. The question can be manually fixed following the instructions at <a href="http://www.wiris.com/quizzes/docs/moodle/manual/multiple-choice#frommoodle1">http://www.wiris.com/quizzes/docs/moodle/manual/multiple-choice#frommoodle1</a>.'; // From Moodle 2.3. $string['pluginname'] = 'Multiple choice - science'; $string['pluginname_help'] = 'Like the standard Multiple choice, but you can deliver different question text and choices by inserting random numbers, formulas or plots. The feedback can also use the random values.'; $string['pluginnamesummary'] = 'Like the standard Multiple choice, but you can deliver different question text and choices by inserting random numbers, formulas or plots. The feedback can also use the random values.'; $string['pluginnameadding'] = 'Adding a multiple choice - math & science question by WIRIS'; $string['pluginnameediting'] = 'Editing a multiple choice - math & science question by WIRIS';
nitro2010/moodle
question/type/multichoicewiris/lang/en/qtype_multichoicewiris.php
PHP
gpl-3.0
2,595
package tripbooker.dto.domain.ticket; /** * * @author Pablo Albaladejo Mestre <pablo.albaladejo.mestre@gmail.com> */ public class TicketDOImp implements ITicketDO{ private int ticketID; private String code; private int userID; private int flightID; @Override public int getTicketID() { return ticketID; } @Override public void setTicketID(int ticketID) { this.ticketID = ticketID; } @Override public String getCode() { return code; } @Override public void setCode(String code) { this.code = code; } @Override public int getUserID() { return userID; } @Override public void setUserID(int userID) { this.userID = userID; } @Override public int getFlightID() { return flightID; } @Override public void setFlightID(int flightID) { this.flightID = flightID; } @Override public String toString() { return "TicketDOImp{" + "ticketID=" + ticketID + ", code=" + code + ", userID=" + userID + ", flightID=" + flightID + '}'; } }
pablo-albaladejo/javaee
proyecto/base/tripbooker/src/tripbooker/dto/domain/ticket/TicketDOImp.java
Java
gpl-3.0
1,133
#pragma once #include <ieventstore.h> #include <ieventsubject.h> #include <atomic> namespace reporting { class EventStoreProcessor { public: explicit EventStoreProcessor( const IEventStorePtr& store, const IEventSubjectPtr& subject, int delay = 5) : d_store_sp(store), d_subject_sp(subject), d_delay(delay), d_shutdown(false) {} ~EventStoreProcessor() {} void start(); void shutdown() { d_shutdown = false; } private: void processEvents(); IEventStorePtr d_store_sp; IEventSubjectPtr d_subject_sp; int d_delay; std::atomic_bool d_shutdown; }; }
spaque/reporting-cpp
src/reporting/eventstoreprocessor.h
C
gpl-3.0
642
{$N UI.UI_Panel} .ui.UI_Panel { position: absolute; padding: 0; margin: 0; } .ui.UI_Panel > .inner { position: relative; padding: 0; margin: 0; overflow: auto; width: 100%; height: 100%; } .ui.UI_Panel > .inner > .body { position: relative; padding: 0; margin: 0; overflow: hidden; min-width: 100%; min-height: 100%; width: 100%; height: 100%; }
sfia-andreidaniel/Constraint
css/UI_Panel.css
CSS
gpl-3.0
365
\documentclass[12pt]{article} %**** Page settings ********************* \usepackage[% paper=a4paper,% %landscape, %includeheadfoot,% margin=1cm,% headsep=0cm, footskip=0cm,% dvips,% ]{geometry} %**** Encoding ************************** \usepackage[latin1]{inputenc} %**************************************** \pagestyle{empty} \begin{document} % \noindent abcdefghijklmnopqrstuvwxyz \\[1em] ABCDEFGHIJKLMNOPQRSTUVWXYZ \\[1em] 0123456789 % \begin{itemize} \item apple \item orange \item banana \end{itemize} % Sed ut perspiciatis, unde omnis iste natus error sit voluptatem accusantium doloremque laudantium, totam rem aperiam eaque ipsa, quae ab illo inventore veritatis et quasi architecto beatae vitae dicta sunt, explicabo. Nemo enim ipsam voluptatem, quia voluptas sit, aspernatur aut odit aut fugit, sed quia consequuntur magni dolores eos, qui ratione voluptatem sequi nesciunt, neque porro quisquam est, qui dolorem ipsum, quia dolor sit, amet, consectetur, adipisci velit, sed quia non numquam eius modi tempora incidunt, ut labore et dolore magnam aliquam quaerat voluptatem. Ut enim ad minima veniam, quis nostrum exercitationem ullam corporis suscipit laboriosam, nisi ut aliquid ex ea commodi consequatur? Quis autem vel eum iure reprehenderit, qui in ea voluptate velit esse, quam nihil molestiae consequatur, vel illum, qui dolorem eum fugiat, quo voluptas nulla pariatur? % \end{document} %%% Local Variables: %%% mode: latex %%% TeX-master: t %%% End:
FabriceSalvaire/PyDVI
tex-samples/long-text.cmr.latin1.tex
TeX
gpl-3.0
1,477
.issue-event { width: 100%; margin: 15px; } .page { margin: 0px 40px 0px 0px; } .header { background: var(--primary-color-dark) !important; color: #FFF; margin: 1px 0px 15px; padding: 15px 0px 0px; } .header h1 { color: #FFF; margin-left: 20px; } .status { margin-left: 0px; } .status mwc-icon { } .status-merged { background: purple; color: #FFF; } .status-open { background: green; color: #FFF; } .status-closed { background: red; color: #FFF; } .header-actions { margin: 18px; } .header-actions a:active, .header-actions a:visited, .header-actions a { text-decoration: none; } .issue-event h1, .issue-event h2, .issue-event h3, .issue-event h4, .issue-event h5 { margin: 15px 0px 5px; } .issue-actions { } .issue-event--label mwc-icon { position: relative; top: 4px; } .issue-event--primary { margin: 15px 0px; } .issue-event--date { color: #CCC; } paper-button { background: var(--accent-color); color: var(--accent-text-color); } paper-tabs { --paper-tabs-selection-bar-color: var(--accent-color); } .no-proposed-changes-message { padding: 15px 25px; } .diff { margin-left: 15px; } .diff--arrow { font-size: .9em; }
Tangerine-Community/Tangerine
client/src/app/case/components/issue/issue.component.css
CSS
gpl-3.0
1,197
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Text; using System.Windows.Forms; namespace multiFormList { public partial class FormLogin : Form { const string USERNAME = "admin"; const string PASSWORD = "0000"; public static string username; public FormLogin() { InitializeComponent(); } private void FormLogin_Load(object sender, EventArgs e) { textBox1.Focus(); username = ""; textBox1.Text = ""; textBox2.Text = ""; CenterToScreen(); textBox2.UseSystemPasswordChar = true; } private void button1_Click(object sender, EventArgs e) { if(textBox1.Text == USERNAME && textBox2.Text == PASSWORD) { username = USERNAME; this.Close(); } else { MessageBox.Show("帳號或密碼錯誤!", "錯誤", MessageBoxButtons.OK, MessageBoxIcon.Error); username = ""; } textBox1.Text = ""; textBox2.Text = ""; } private void button2_Click(object sender, EventArgs e) { username = ""; textBox1.Text = ""; textBox2.Text = ""; this.Close(); } } }
aben20807/window_programming
practice/multiFormList/multiFormList/FormLogin.cs
C#
gpl-3.0
1,456
<HTML > <HEAD> <META HTTP-EQUIV="Content-Type" CONTENT="text/html; charset=windows-1252" /> <TITLE>doImport</TITLE> <LINK REL="stylesheet" TYPE="text/css" HREF="../common/ie4.css" /> <LINK REL="stylesheet" TYPE="text/css" HREF="../common/ie5.css" /> <style> BODY { font-family:verdana,arial,helvetica; margin:0; } </style> <SCRIPT LANGUAGE="javascript" SRC="../common/common.js"></SCRIPT> <SCRIPT LANGUAGE="javascript" SRC="../common/browdata.js"></SCRIPT> <SCRIPT LANGUAGE="javascript" SRC="../common/appliesto2.js"></SCRIPT> <SCRIPT LANGUAGE="javascript" SRC="../common/toolbar.js"></SCRIPT> <LINK REL="stylesheet" TYPE="text/css" HREF="../common/ie4.css" /> <LINK REL="stylesheet" TYPE="text/css" HREF="../common/inetsdk.css" /> <LINK REL="stylesheet" TYPE="text/css" HREF="../common/advSDKATIE4.css" /> <LINK REL="stylesheet" TYPE="text/css" HREF="../common/default.css" /> <SCRIPT> var gbDBG = true; </SCRIPT> <SCRIPT LANGUAGE="JavaScript1.2"> var gsHTCPath = "../common/"; var gsGraphicsPath = "../common/"; var gsCodePath = "../common/"; </SCRIPT> <SCRIPT LANGUAGE="JavaScript1.2"> var gsContextMenuPath = gsHTCPath + "contextmenu.htc"; var gsCodeDecoPath = gsHTCPath + "codedeco.htc"; var gsStoreName="workshop"; var gsGraphicsPath = "../common/"; </SCRIPT> <SCRIPT LANGUAGE="JavaScript1.2"> function InitPage() { if (!assert( (typeof(oBD) == 'object' && oBD != null), "browdata object unavailable!") ) { return; } if ("MSIE" == oBD.browser && oBD.majorVer >= 5 && (oBD.platform.toLowerCase()!="x" && oBD.platform!="Mac" && oBD.platform!="PPC" )) { if (typeof(fnATInit) == 'function') fnATInit(); if (typeof(PostGBInit) == 'function') PostGBInit(); if (typeof(PostInit) == 'function') PostInit(); if (typeof(initTabbedMembers) == 'function') initTabbedMembers(); if (typeof(hideExamples) == 'function') hideExamples(); } if (oBD.getsNavBar && oBD.platform!="PPC" ) { if (typeof(SetShowMes) == 'function') SetShowMes(); } } function assert(bCond, sMsg) { if (bCond) { return true; } else { if (gbDBG) { alert(sMsg); } return false; } } window.onload = InitPage; </SCRIPT> <SCRIPT LANGUAGE="JavaScript1.2"> function PreInit() { } </SCRIPT> <SCRIPT LANGUAGE="JavaScript"> </script> </HEAD> <BODY TOPMARGIN="0" LEFTMARGIN="0" MARGINHEIGHT="0" MARGINWIDTH="0" BGCOLOR="#FFFFFF" TEXT="#000000"> <TABLE STYLE="table-layout:fixed" class='clsContainer' CELLPADDING='15' CELLSPACING='0' float='left' WIDTH='100%' BORDER='0'> <TR> <TD VALIGN='top'> <DIV CLASS="clsDocBody"><TABLE WIDTH="97%" CELLPADDING="0" CELLSPACING="0"><TR><TD><H1>doImport Method </H1></TD><TD ALIGN="right"><A HREF="../default.html" TITLE="This index is only for content formerly found in the Web Workshop." TARGET="_top">Internet Development Index</A></TD></TR></TABLE> <HR SIZE="1"></HR><P>Dynamically imports an element behavior.</P><P CLASS="clsRef">Syntax</P><BLOCKQUOTE><PRE CLASS="clsSyntax"><I>namespace</I><B>.doImport(</B><I>sUrl</I><B>)</B></PRE></BLOCKQUOTE><P CLASS="clsRef">Parameters</P><BLOCKQUOTE><TABLE CLASS="clsStd"><TR><TD><I>sUrl</I></TD><TD> Required. <b>String</b> that specifies the URL of the element behavior to import into the namespace.</TD></TR></TABLE></BLOCKQUOTE><P CLASS="clsRef">Return Value</P><BLOCKQUOTE><P>No return value.</P></BLOCKQUOTE><P CLASS="clsRef">Remarks</P><BLOCKQUOTE><P>Once imported into a namespace by this method, an element behavior can be used on the page where the namespace has been declared.</P><P>Using this method alone is not enough to enable a element behavior to function on a Web page; it is also necessary to add a custom element to the body of the primary document, as illustrated in the following code snippet.</P><P><PRE CLASS="clsCode" AUTOHILITE="1">&lt;body&gt; &lt;myns:mycustomtag/&gt; &lt;/body&gt;</PRE></P><P>The preceding sample shows how a custom element makes use of a custom namespace, which is declared on the <A HREF="../properties/xmlns.html">XMLNS</A> attribute of the HTML tag.</P><P>A script or binary behavior can also be used to insert a custom element. See the examples that follow for an illustration of this technique.</P></BLOCKQUOTE><P CLASS="clsRef">Examples</P><BLOCKQUOTE><P> The following example declares a namespace called "TESTNS" and imports the default Microsoft&#174; Internet Explorer behaviors into it.</P><PRE CLASS="clsCode" AUTOHILITE="1">&lt;HTML XMLNS:TESTNS&gt; &lt;HEAD&gt; &lt;SCRIPT LANGUAGE="JScript"&gt; document.namespaces("TESTNS").doImport("#default"); &lt;/SCRIPT&gt; &lt;/HEAD&gt; </PRE><P> The following example shows how the <B>doImport</B> method can be used in conjunction with the <A HREF="../methods/createelement.html">createElement</A> to insert a custom element to which an element behavior is attached.</P><PRE CLASS="clsCode" AUTOHILITE="1">&lt;HTML xmlns:myns&gt; &lt;BODY onload=Load()&gt; &lt;SCRIPT&gt; var ns; // holds the newly created namespace object function Load() { ns = document.namespaces[0]; ns.doImport("redbg.htc"); if(ns.readyState != "complete") { // Wait for the element behaviors to finish downloading ns.attachEvent("onreadystatechange", addTagnamesToBody); } else { addTagnamesToBody(); } return true; } function addTagnamesToBody() { if(ns.readyState != "complete") return; var v = document.createElement("myns:abc"); v.innerText = "ElementBehavior"; document.body.appendChild(v); ns.detachEvent("onreadystatechange", addTagnamesToBody); } &lt;/SCRIPT&gt; &lt;/BODY&gt;&lt;/HTML&gt; </PRE><P> The following code shows the content of the HTML Component (HTC) file, <SPAN CLASS="clsLiteral">redbg.htc</SPAN>, which simply applies a red background when the <A HREF="/workshop/components/htc/reference/events/ondocumentready.html">ondocumentready</A> event fires.</P><PRE CLASS="clsCode" AUTOHILITE="1">&lt;public:component tagName=abc &gt; &lt;public:attach event=ondocumentready onevent=Doc_Ready() /&gt; &lt;/public:component&gt; &lt;script&gt; function Doc_Ready() { element.document.bgColor = "red"; } &lt;/script&gt;</PRE></BLOCKQUOTE><P CLASS="clsRef">Standards Information</P><BLOCKQUOTE><P> There is no public standard that applies to this method. </P></BLOCKQUOTE><P CLASS="clsRef">Applies To</P><BLOCKQUOTE><TABLE ID="oATTable" CLASS="TMAT3D"><TR><TD VALIGN="top" STYLE="border: 1 outset; display: none;"></TD><TD ID="oATData" CLASS="controls"><A PLATINFO="win32=5.5;ce=5.5" HREF="../objects/namespace.html"> namespace</A></TD></TR><TR><TD COLSPAN="2" CLASS="controls"></TD></TR></TABLE></BLOCKQUOTE><P CLASS="clsRef">See Also</P><BLOCKQUOTE><A HREF="../pi/import.html">IMPORT</A>, <A HREF="/workshop/author/behaviors/overview/viewlink_ovw.html">Introduction to Viewlink</A>, <A HREF="/workshop/author/behaviors/overview/elementb_ovw.html">About Element Behaviors</A></BLOCKQUOTE></DIV> </TD> </TR> </TABLE> </BODY> </HTML>
gucong3000/handbook
dhtml/DHTML/DHTMLref/methods/doimport.html
HTML
gpl-3.0
6,763
package br.edu.curso.mockito.exercicio.interacao.game; import static org.mockito.Matchers.any; import static org.mockito.Matchers.anyInt; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.never; import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; import org.junit.Before; import org.junit.Rule; import org.junit.Test; import org.junit.rules.TestName; import br.edu.curso.mockito.exercicio.interacao.game.Dicionario.Tema; // TODO tratar espacos para incluir palavras compostas ou com hífen // TODO quando repetir letra que acertou, mostrar aviso, e se insistir, gameover com frase,: apelou! // TODO randomizar o tipo: fruta, pais public class ForcaTest { private Forca forca; private Dicionario dicionarioMock; private Desenhista desenhistaMock; private Coletor coletorMock; @Rule public TestName name = new TestName(); @Before public void before() { // mocks this.dicionarioMock = mock( Dicionario.class ); this.desenhistaMock = mock( Desenhista.class ); this.coletorMock = mock( Coletor.class ); // real this.forca = this.montarJogo(); System.out.println( "\n\n#" + name.getMethodName() ); } @Test public void acertoDireto() { when( dicionarioMock.eleger(any(Tema.class)) ).thenReturn("leopardo"); when( coletorMock.obter() ).thenReturn( "l" ); forca.jogar( Tema.animais ); verify( desenhistaMock, never() ).desenha( anyInt() ); } @Test public void acerto6Erros() { when( dicionarioMock.eleger(any(Tema.class)) ).thenReturn("leopardo"); when( coletorMock.obter() ).thenReturn( "x", "y", "w" ); forca.jogar( Tema.animais ); verify( desenhistaMock, times(7) ).desenha( anyInt() ); } private Forca montarJogo() { return Forca.builder() .dicionario( this.dicionarioMock ) .desenhista( this.desenhistaMock ) .coletor( coletorMock ) .build(); } }
rafarocha/ceshi
unit/ceshi-mockito/src/test/java/br/edu/curso/mockito/exercicio/interacao/game/ForcaTest.java
Java
gpl-3.0
1,935
/** * Session.java * * This file was auto-generated from WSDL * by the Apache Axis 1.4 Apr 22, 2006 (06:55:48 PDT) WSDL2Java emitter. */ package is.idega.idegaweb.pheidippides.webservice.hlaupastyrkurISB.client; @SuppressWarnings({"rawtypes", "unused"}) public class Session implements java.io.Serializable { private static final long serialVersionUID = -1707510865522412478L; private java.lang.String sessionID; public Session() { } public Session( java.lang.String sessionID) { this.sessionID = sessionID; } /** * Gets the sessionID value for this Session. * * @return sessionID */ public java.lang.String getSessionID() { return sessionID; } /** * Sets the sessionID value for this Session. * * @param sessionID */ public void setSessionID(java.lang.String sessionID) { this.sessionID = sessionID; } private java.lang.Object __equalsCalc = null; @Override public synchronized boolean equals(java.lang.Object obj) { if (!(obj instanceof Session)) return false; Session other = (Session) obj; if (obj == null) return false; if (this == obj) return true; if (__equalsCalc != null) { return (__equalsCalc == obj); } __equalsCalc = obj; boolean _equals; _equals = true && ((this.sessionID==null && other.getSessionID()==null) || (this.sessionID!=null && this.sessionID.equals(other.getSessionID()))); __equalsCalc = null; return _equals; } private boolean __hashCodeCalc = false; @Override public synchronized int hashCode() { if (__hashCodeCalc) { return 0; } __hashCodeCalc = true; int _hashCode = 1; if (getSessionID() != null) { _hashCode += getSessionID().hashCode(); } __hashCodeCalc = false; return _hashCode; } // Type metadata private static org.apache.axis.description.TypeDesc typeDesc = new org.apache.axis.description.TypeDesc(Session.class, true); static { typeDesc.setXmlType(new javax.xml.namespace.QName("http://illuminati.is", "Session")); org.apache.axis.description.ElementDesc elemField = new org.apache.axis.description.ElementDesc(); elemField.setFieldName("sessionID"); elemField.setXmlName(new javax.xml.namespace.QName("http://illuminati.is", "sessionID")); elemField.setXmlType(new javax.xml.namespace.QName("http://www.w3.org/2001/XMLSchema", "string")); elemField.setNillable(true); typeDesc.addFieldDesc(elemField); } /** * Return type metadata object */ public static org.apache.axis.description.TypeDesc getTypeDesc() { return typeDesc; } /** * Get Custom Serializer */ public static org.apache.axis.encoding.Serializer getSerializer( java.lang.String mechType, java.lang.Class _javaType, javax.xml.namespace.QName _xmlType) { return new org.apache.axis.encoding.ser.BeanSerializer( _javaType, _xmlType, typeDesc); } /** * Get Custom Deserializer */ public static org.apache.axis.encoding.Deserializer getDeserializer( java.lang.String mechType, java.lang.Class _javaType, javax.xml.namespace.QName _xmlType) { return new org.apache.axis.encoding.ser.BeanDeserializer( _javaType, _xmlType, typeDesc); } }
bluebottle/is.idega.idegaweb.block.pheidippides
src/java/is/idega/idegaweb/pheidippides/webservice/hlaupastyrkurISB/client/Session.java
Java
gpl-3.0
3,626
package net.ramso.dita.bookmap; import java.util.ArrayList; import java.util.List; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlAttribute; import javax.xml.bind.annotation.XmlElement; import javax.xml.bind.annotation.XmlElements; import javax.xml.bind.annotation.XmlSchemaType; import javax.xml.bind.annotation.XmlSeeAlso; import javax.xml.bind.annotation.XmlType; import javax.xml.bind.annotation.adapters.CollapsedStringAdapter; import javax.xml.bind.annotation.adapters.XmlJavaTypeAdapter; import net.ramso.dita.utils.GenericData; /** * <p>Java class for frontmatter.class complex type. * * <p>The following schema fragment specifies the expected content contained within this class. * * <pre> * &lt;complexType name="frontmatter.class"> * &lt;complexContent> * &lt;restriction base="{http://www.w3.org/2001/XMLSchema}anyType"> * &lt;sequence> * &lt;group ref="{}frontmatter.content"/> * &lt;/sequence> * &lt;attGroup ref="{}frontmatter.attributes"/> * &lt;/restriction> * &lt;/complexContent> * &lt;/complexType> * </pre> * * */ @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "frontmatter.class", propOrder = { "booklistsOrNoticesOrDedication" }) @XmlSeeAlso({ Frontmatter.class }) public class FrontmatterClass extends GenericData { @XmlElements({ @XmlElement(name = "booklists", type = Booklists.class), @XmlElement(name = "notices", type = Notices.class), @XmlElement(name = "dedication", type = Dedication.class), @XmlElement(name = "colophon", type = Colophon.class), @XmlElement(name = "bookabstract", type = Bookabstract.class), @XmlElement(name = "draftintro", type = Draftintro.class), @XmlElement(name = "preface", type = Preface.class), @XmlElement(name = "topicref", type = Topicref.class), @XmlElement(name = "anchorref", type = Anchorref.class), @XmlElement(name = "keydef", type = Keydef.class), @XmlElement(name = "mapref", type = Mapref.class), @XmlElement(name = "topicgroup", type = Topicgroup.class), @XmlElement(name = "topichead", type = Topichead.class), @XmlElement(name = "topicset", type = Topicset.class), @XmlElement(name = "topicsetref", type = Topicsetref.class) }) protected List<java.lang.Object> booklistsOrNoticesOrDedication; @XmlAttribute(name = "keyref") protected String keyref; @XmlAttribute(name = "query") protected String query; @XmlAttribute(name = "outputclass") protected String outputclass; @XmlAttribute(name = "id") @XmlJavaTypeAdapter(CollapsedStringAdapter.class) @XmlSchemaType(name = "NMTOKEN") protected String id; @XmlAttribute(name = "conref") protected String conref; @XmlAttribute(name = "conrefend") protected String conrefend; @XmlAttribute(name = "conaction") protected ConactionAttClass conaction; @XmlAttribute(name = "conkeyref") protected String conkeyref; @XmlAttribute(name = "translate") protected YesnoAttClass translate; @XmlAttribute(name = "lang", namespace = "http://www.w3.org/XML/1998/namespace") protected String lang; @XmlAttribute(name = "dir") protected DirAttsClass dir; @XmlAttribute(name = "base") protected String base; @XmlAttribute(name = "rev") protected String rev; @XmlAttribute(name = "importance") protected ImportanceAttsClass importance; @XmlAttribute(name = "status") protected StatusAttsClass status; @XmlAttribute(name = "props") protected String props; @XmlAttribute(name = "platform") protected String platform; @XmlAttribute(name = "product") protected String product; @XmlAttribute(name = "audience") protected String audienceMod; @XmlAttribute(name = "otherprops") protected String otherprops; @XmlAttribute(name = "collection-type") protected CollectionTypeClass collectionType; @XmlAttribute(name = "type") protected String type; @XmlAttribute(name = "processing-role") protected ProcessingRoleAttClass processingRole; @XmlAttribute(name = "scope") protected ScopeAttClass scope; @XmlAttribute(name = "locktitle") protected YesnoAttClass locktitle; @XmlAttribute(name = "format") protected String format; @XmlAttribute(name = "linking") protected LinkingtypesClass linking; @XmlAttribute(name = "toc") protected YesnoAttClass toc; @XmlAttribute(name = "print") protected PrintAttClass print; @XmlAttribute(name = "search") protected YesnoAttClass search; @XmlAttribute(name = "chunk") protected String chunk; @XmlAttribute(name = "xtrc") protected String xtrc; @XmlAttribute(name = "xtrf") protected String xtrf; /** * Gets the value of the booklistsOrNoticesOrDedication property. * * <p> * This accessor method returns a reference to the live list, * not a snapshot. Therefore any modification you make to the * returned list will be present inside the JAXB object. * This is why there is not a <CODE>set</CODE> method for the booklistsOrNoticesOrDedication property. * * <p> * For example, to add a new item, do as follows: * <pre> * getBooklistsOrNoticesOrDedication().add(newItem); * </pre> * * * <p> * Objects of the following type(s) are allowed in the list * {@link Booklists } * {@link Notices } * {@link Dedication } * {@link Colophon } * {@link Bookabstract } * {@link Draftintro } * {@link Preface } * {@link Topicref } * {@link Anchorref } * {@link Keydef } * {@link Mapref } * {@link Topicgroup } * {@link Topichead } * {@link Topicset } * {@link Topicsetref } * * */ public List<java.lang.Object> getBooklistsOrNoticesOrDedication() { if (booklistsOrNoticesOrDedication == null) { booklistsOrNoticesOrDedication = new ArrayList<java.lang.Object>(); } return this.booklistsOrNoticesOrDedication; } /** * Gets the value of the keyref property. * * @return * possible object is * {@link String } * */ public String getKeyref() { return keyref; } /** * Sets the value of the keyref property. * * @param value * allowed object is * {@link String } * */ public void setKeyref(String value) { this.keyref = value; } /** * Gets the value of the query property. * * @return * possible object is * {@link String } * */ public String getQuery() { return query; } /** * Sets the value of the query property. * * @param value * allowed object is * {@link String } * */ public void setQuery(String value) { this.query = value; } /** * Gets the value of the outputclass property. * * @return * possible object is * {@link String } * */ public String getOutputclass() { return outputclass; } /** * Sets the value of the outputclass property. * * @param value * allowed object is * {@link String } * */ public void setOutputclass(String value) { this.outputclass = value; } /** * Gets the value of the id property. * * @return * possible object is * {@link String } * */ public String getId() { return id; } /** * Sets the value of the id property. * * @param value * allowed object is * {@link String } * */ public void setId(String value) { this.id = value; } /** * Gets the value of the conref property. * * @return * possible object is * {@link String } * */ public String getConref() { return conref; } /** * Sets the value of the conref property. * * @param value * allowed object is * {@link String } * */ public void setConref(String value) { this.conref = value; } /** * Gets the value of the conrefend property. * * @return * possible object is * {@link String } * */ public String getConrefend() { return conrefend; } /** * Sets the value of the conrefend property. * * @param value * allowed object is * {@link String } * */ public void setConrefend(String value) { this.conrefend = value; } /** * Gets the value of the conaction property. * * @return * possible object is * {@link ConactionAttClass } * */ public ConactionAttClass getConaction() { return conaction; } /** * Sets the value of the conaction property. * * @param value * allowed object is * {@link ConactionAttClass } * */ public void setConaction(ConactionAttClass value) { this.conaction = value; } /** * Gets the value of the conkeyref property. * * @return * possible object is * {@link String } * */ public String getConkeyref() { return conkeyref; } /** * Sets the value of the conkeyref property. * * @param value * allowed object is * {@link String } * */ public void setConkeyref(String value) { this.conkeyref = value; } /** * Gets the value of the translate property. * * @return * possible object is * {@link YesnoAttClass } * */ public YesnoAttClass getTranslate() { return translate; } /** * Sets the value of the translate property. * * @param value * allowed object is * {@link YesnoAttClass } * */ public void setTranslate(YesnoAttClass value) { this.translate = value; } /** * Gets the value of the lang property. * * @return * possible object is * {@link String } * */ public String getLang() { return lang; } /** * Sets the value of the lang property. * * @param value * allowed object is * {@link String } * */ public void setLang(String value) { this.lang = value; } /** * Gets the value of the dir property. * * @return * possible object is * {@link DirAttsClass } * */ public DirAttsClass getDir() { return dir; } /** * Sets the value of the dir property. * * @param value * allowed object is * {@link DirAttsClass } * */ public void setDir(DirAttsClass value) { this.dir = value; } /** * Gets the value of the base property. * * @return * possible object is * {@link String } * */ public String getBase() { return base; } /** * Sets the value of the base property. * * @param value * allowed object is * {@link String } * */ public void setBase(String value) { this.base = value; } /** * Gets the value of the rev property. * * @return * possible object is * {@link String } * */ public String getRev() { return rev; } /** * Sets the value of the rev property. * * @param value * allowed object is * {@link String } * */ public void setRev(String value) { this.rev = value; } /** * Gets the value of the importance property. * * @return * possible object is * {@link ImportanceAttsClass } * */ public ImportanceAttsClass getImportance() { return importance; } /** * Sets the value of the importance property. * * @param value * allowed object is * {@link ImportanceAttsClass } * */ public void setImportance(ImportanceAttsClass value) { this.importance = value; } /** * Gets the value of the status property. * * @return * possible object is * {@link StatusAttsClass } * */ public StatusAttsClass getStatus() { return status; } /** * Sets the value of the status property. * * @param value * allowed object is * {@link StatusAttsClass } * */ public void setStatus(StatusAttsClass value) { this.status = value; } /** * Gets the value of the props property. * * @return * possible object is * {@link String } * */ public String getProps() { return props; } /** * Sets the value of the props property. * * @param value * allowed object is * {@link String } * */ public void setProps(String value) { this.props = value; } /** * Gets the value of the platform property. * * @return * possible object is * {@link String } * */ public String getPlatform() { return platform; } /** * Sets the value of the platform property. * * @param value * allowed object is * {@link String } * */ public void setPlatform(String value) { this.platform = value; } /** * Gets the value of the product property. * * @return * possible object is * {@link String } * */ public String getProduct() { return product; } /** * Sets the value of the product property. * * @param value * allowed object is * {@link String } * */ public void setProduct(String value) { this.product = value; } /** * Gets the value of the audienceMod property. * * @return * possible object is * {@link String } * */ public String getAudienceMod() { return audienceMod; } /** * Sets the value of the audienceMod property. * * @param value * allowed object is * {@link String } * */ public void setAudienceMod(String value) { this.audienceMod = value; } /** * Gets the value of the otherprops property. * * @return * possible object is * {@link String } * */ public String getOtherprops() { return otherprops; } /** * Sets the value of the otherprops property. * * @param value * allowed object is * {@link String } * */ public void setOtherprops(String value) { this.otherprops = value; } /** * Gets the value of the collectionType property. * * @return * possible object is * {@link CollectionTypeClass } * */ public CollectionTypeClass getCollectionType() { return collectionType; } /** * Sets the value of the collectionType property. * * @param value * allowed object is * {@link CollectionTypeClass } * */ public void setCollectionType(CollectionTypeClass value) { this.collectionType = value; } /** * Gets the value of the type property. * * @return * possible object is * {@link String } * */ public String getType() { return type; } /** * Sets the value of the type property. * * @param value * allowed object is * {@link String } * */ public void setType(String value) { this.type = value; } /** * Gets the value of the processingRole property. * * @return * possible object is * {@link ProcessingRoleAttClass } * */ public ProcessingRoleAttClass getProcessingRole() { return processingRole; } /** * Sets the value of the processingRole property. * * @param value * allowed object is * {@link ProcessingRoleAttClass } * */ public void setProcessingRole(ProcessingRoleAttClass value) { this.processingRole = value; } /** * Gets the value of the scope property. * * @return * possible object is * {@link ScopeAttClass } * */ public ScopeAttClass getScope() { return scope; } /** * Sets the value of the scope property. * * @param value * allowed object is * {@link ScopeAttClass } * */ public void setScope(ScopeAttClass value) { this.scope = value; } /** * Gets the value of the locktitle property. * * @return * possible object is * {@link YesnoAttClass } * */ public YesnoAttClass getLocktitle() { return locktitle; } /** * Sets the value of the locktitle property. * * @param value * allowed object is * {@link YesnoAttClass } * */ public void setLocktitle(YesnoAttClass value) { this.locktitle = value; } /** * Gets the value of the format property. * * @return * possible object is * {@link String } * */ public String getFormat() { return format; } /** * Sets the value of the format property. * * @param value * allowed object is * {@link String } * */ public void setFormat(String value) { this.format = value; } /** * Gets the value of the linking property. * * @return * possible object is * {@link LinkingtypesClass } * */ public LinkingtypesClass getLinking() { return linking; } /** * Sets the value of the linking property. * * @param value * allowed object is * {@link LinkingtypesClass } * */ public void setLinking(LinkingtypesClass value) { this.linking = value; } /** * Gets the value of the toc property. * * @return * possible object is * {@link YesnoAttClass } * */ public YesnoAttClass getToc() { return toc; } /** * Sets the value of the toc property. * * @param value * allowed object is * {@link YesnoAttClass } * */ public void setToc(YesnoAttClass value) { this.toc = value; } /** * Gets the value of the print property. * * @return * possible object is * {@link PrintAttClass } * */ public PrintAttClass getPrint() { return print; } /** * Sets the value of the print property. * * @param value * allowed object is * {@link PrintAttClass } * */ public void setPrint(PrintAttClass value) { this.print = value; } /** * Gets the value of the search property. * * @return * possible object is * {@link YesnoAttClass } * */ public YesnoAttClass getSearch() { return search; } /** * Sets the value of the search property. * * @param value * allowed object is * {@link YesnoAttClass } * */ public void setSearch(YesnoAttClass value) { this.search = value; } /** * Gets the value of the chunk property. * * @return * possible object is * {@link String } * */ public String getChunk() { return chunk; } /** * Sets the value of the chunk property. * * @param value * allowed object is * {@link String } * */ public void setChunk(String value) { this.chunk = value; } /** * Gets the value of the xtrc property. * * @return * possible object is * {@link String } * */ public String getXtrc() { return xtrc; } /** * Sets the value of the xtrc property. * * @param value * allowed object is * {@link String } * */ public void setXtrc(String value) { this.xtrc = value; } /** * Gets the value of the xtrf property. * * @return * possible object is * {@link String } * */ public String getXtrf() { return xtrf; } /** * Sets the value of the xtrf property. * * @param value * allowed object is * {@link String } * */ public void setXtrf(String value) { this.xtrf = value; } }
ramsodev/DitaManagement
dita/dita.bookmap/src/net/ramso/dita/bookmap/FrontmatterClass.java
Java
gpl-3.0
21,779
"use strict"; var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) { var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d; if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc); else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r; return c > 3 && r && Object.defineProperty(target, key, r), r; }; var __metadata = (this && this.__metadata) || function (k, v) { if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v); }; Object.defineProperty(exports, "__esModule", { value: true }); var core_1 = require("@angular/core"); var user_service_1 = require("../../services/user.service"); var HomeComponent = (function () { function HomeComponent(userService) { this.userService = userService; this.users = []; } HomeComponent.prototype.ngOnInit = function () { var _this = this; // get users from secure api end point this.userService.getUsers() .subscribe(function (users) { _this.users = users; }); }; return HomeComponent; }()); HomeComponent = __decorate([ core_1.Component({ moduleId: module.id, templateUrl: 'home.component.html' }), __metadata("design:paramtypes", [user_service_1.UserService]) ], HomeComponent); exports.HomeComponent = HomeComponent; //# sourceMappingURL=home.component.js.map
umeshsohaliya/AngularSampleA
app/components/home/home.component.js
JavaScript
gpl-3.0
1,660
'use strict'; var BarcodeScan = require('com.tlantic.plugins.device.barcodescan.BarcodeScan'); var barcodeScan; exports.init = function (success, fail, args) { if (!barcodeScan) { barcodeScan = new BarcodeScan(); barcodeScan.onReceive = exports.rcMessage; barcodeScan.init(success, fail); } else { barcodeScan.endReceivingData(function () { barcodeScan.onReceive = exports.rcMessage; barcodeScan.init(success, fail); }); } }; exports.stop = function stop(success, fail, args) { barcodeScan.endReceivingData(success); }; // callback to receive data written on socket inputStream exports.rcMessage = function (scanLabel, scanData, scanType) { window.tlantic.plugins.device.barcodescan.receive(scanLabel, scanData, scanType); }; require('cordova/windows8/commandProxy').add('DeviceBarcodeScan', exports);
Tlantic/cdv-device-barcodescan-plugin
src/windows8/BarcodeScanProxy.js
JavaScript
gpl-3.0
897
# IPython的魔法符号-Magics #### [openthings@163.com](http://my.oschina.net/u/2306127/blog?catalog=2527511) ### 最新的Jupyter Notebook可以混合执行Shell、Python以及Ruby、R等代码! 这一功能将解释型语言的特点发挥到了极致,从而打破了传统语言`"运行时"`的边界。 **IPython是一个非常好用Python控制台,极大地扩展了Python的能力。** 因为它不仅是一种语言的运行环境,而且是一个高效率的分析工具。 * 之前任何语言和IDE都是相互独立的,导致工作时需要在不同的系统间切换和拷贝/粘贴数据。 * Magic操作符可以在HTML页面中输入shell脚本以及Ruby等其它语言并混合执行,极大地提升了传统的“控制台”的生产效率。 * Magics是一个单行的标签式“命令行”系统,指示后续的代码将如何、以及被何种解释器去处理。 * Magisc与传统的shell脚本几乎没有什么区别,但是可以将多种指令混合在一起。 Magics 主要有两种语法: * Line magics: 以 `%` 字符开始,该行后面都为指令代码,参数用空格隔开,不需要加引号。 * Cell magics: 使用两个百分号 (`%%`)开始, 后面的整个单元(Cell)都是指令代码。 注意,`%%`魔法操作符只在Cell的第一行使用,而且不能嵌套、重复(一个Cell只有一个)。极个别的情况,可以堆叠,但是只用于个别情况。 #### 输入 [`%lsmagic`] 可以获得Magic操作符的列表。 如下所示(在Jupyter Notebook环境下,按[`shift+enter`]可以运行。): ```python %lsmagic ``` ** 缺省情况下,`Automagic`开关打开,不需要输入`%`符号,将会自动识别。** 注意,这有可能与其它的操作引起冲突,需要注意避免。如果有混淆情况,加上`%`符号即可。 下面显示运行一段代码所消耗的时间。 ```python time print("hi") ``` hi CPU times: user 0 ns, sys: 0 ns, total: 0 ns Wall time: 47.9 µs ```python %time ``` CPU times: user 0 ns, sys: 0 ns, total: 0 ns Wall time: 4.77 µs #### 执行Shell脚本。 ```python ls -l -h ``` 总用量 340K -rw-rw-r-- 1 supermap supermap 266K 4月 29 09:29 jupyter_magics.ipynb -rw-rw-r-- 1 supermap supermap 58K 4月 27 12:38 pandas_quickstart.ipynb -rw-rw-r-- 1 supermap supermap 12K 4月 27 12:28 pystart_databasic.ipynb ```python !ls -l -h ``` 总用量 340K -rw-rw-r-- 1 supermap supermap 266K 4月 29 09:29 jupyter_magics.ipynb -rw-rw-r-- 1 supermap supermap 58K 4月 27 12:38 pandas_quickstart.ipynb -rw-rw-r-- 1 supermap supermap 12K 4月 27 12:28 pystart_databasic.ipynb ```python files = !ls -l -h files ``` ['总用量 348K', '-rw-rw-r-- 1 supermap supermap 276K 4月 29 09:31 jupyter_magics.ipynb', '-rw-rw-r-- 1 supermap supermap 58K 4月 27 12:38 pandas_quickstart.ipynb', '-rw-rw-r-- 1 supermap supermap 12K 4月 27 12:28 pystart_databasic.ipynb'] #### 执行多行shell脚本。 ```python %%! ls -l pwd who ``` ['总用量 344', '-rw-rw-r-- 1 supermap supermap 274868 4月 29 09:33 jupyter_magics.ipynb', '-rw-rw-r-- 1 supermap supermap 59280 4月 27 12:38 pandas_quickstart.ipynb', '-rw-rw-r-- 1 supermap supermap 11528 4月 27 12:28 pystart_databasic.ipynb', '/home/supermap/GISpark/git_notebook/pystart', 'supermap :0 2016-04-28 20:39 (:0)', 'supermap pts/0 2016-04-28 21:50 (:0)', 'supermap pts/6 2016-04-28 22:22 (:0)'] ### 下面开始体验一下魔法操作符的威力。 载入matplotlib和numpy,后面的数值计算和绘图将会使用。 ```python %matplotlib inline import numpy as np import matplotlib.pyplot as plt ``` ## <!--====--> cell magics的简单例子 #### `%timeit` 魔法,计量代码的执行时间, 适用于单行和cell: ```python %timeit np.linalg.eigvals(np.random.rand(100,100)) ``` The slowest run took 8.96 times longer than the fastest. This could mean that an intermediate result is being cached. 100 loops, best of 3: 5.82 ms per loop ```python %%timeit a = np.random.rand(100, 100) np.linalg.eigvals(a) ``` 100 loops, best of 3: 6.07 ms per loop #### `%%capture` 魔法,用于捕获stdout/err, 可以直接显示,也可以存到变量里备用: ```python %%capture capt from __future__ import print_function import sys print('Hello stdout') print('and stderr', file=sys.stderr) ``` ```python capt.stdout, capt.stderr ``` ('Hello stdout\n', 'and stderr\n') ```python capt.show() ``` Hello stdout and stderr #### `%%writefile` 魔法,将后续的语句写入文件中: ```python %%writefile foo.py print('Hello world') ``` Writing foo.py ```python %run foo ``` Hello world ## <!--====--> Magics 运行其它的解释器。 ##### IPython 有一个 `%%script` 魔法操作符, 可以在一个子进程中运行其它语言的解释器,包括: bash, ruby, perl, zsh, R, 等等. 执行时从stdin取得输入,就像你自己在键入一样。 #### 直接在`%%script` 行后传入指令即可使用。 后续的cell中的内容将按照指示符运行,子进程的信息通过stdout/err捕获和显示。 ```python %%script python import sys print('hello from Python %s' % sys.version) ``` hello from Python 3.5.1 |Anaconda 4.0.0 (64-bit)| (default, Dec 7 2015, 11:16:01) [GCC 4.4.7 20120313 (Red Hat 4.4.7-1)] ```python %%script python3 import sys print('hello from Python: %s' % sys.version) ``` hello from Python: 3.5.1 |Anaconda 4.0.0 (64-bit)| (default, Dec 7 2015, 11:16:01) [GCC 4.4.7 20120313 (Red Hat 4.4.7-1)] IPython对通用的解释器创建了别名,可以直接使用, 譬如:bash, ruby, perl, etc. **等价于这个操作符: `%%script <name>` ** ```python %%ruby puts "Hello from Ruby #{RUBY_VERSION}" ``` Hello from Ruby 2.1.5 ```python %%bash echo "hello from $BASH" ``` hello from /bin/bash ## 高级练习: 写一个自己的脚本文件。 写一个脚本文件,名为 `lnum.py`, 然后执行: ```python %%writefile ./lnum.py print('my first line.') print("my second line.") print("Finished.") ``` Writing ./lnum.py ```python %%script python ./lnum.py # ``` my first line. my second line. Finished. ## 捕获输出。 可以直接从子进程中捕获stdout/err到Python变量中, 替代直接进入stdout/err。 ```python %%bash echo "hi, stdout" echo "hello, stderr" >&2 ``` hi, stdout hello, stderr ```python %%bash --out output --err error echo "hi, stdout" echo "hello, stderr" >&2 ``` 可以直接访问变量名了。 ```python print(error) print(output) ``` hello, stderr hi, stdout ## 后台运行 Scripts 只需添加 **`--bg`** ,即可让脚本在后台运行。 在此情况下, 输出将被丢弃,除非使用 `--out/err` 捕获输出。 ```python %%ruby --bg --out ruby_lines for n in 1...10 sleep 1 puts "line #{n}" STDOUT.flush end ``` Starting job # 2 in a separate thread. #### 当后台线程保存输出时,有一个stdout/err *pipes*, 而不是输出的文本形式。 ```python ruby_lines ``` <_io.BufferedReader name=52> ```python print(ruby_lines.read()) ``` b'line 1\nline 2\nline 3\nline 4\nline 5\nline 6\nline 7\nline 8\nline 9\n' # Cython Magic 函数扩展 ## 载入 extension IPtyhon 包含 `cythonmagic` extension,提供了几个与Cython代码工作的魔法函数。使用 `%load_ext` 载入,如下: ```python %load_ext cythonmagic ``` /home/supermap/anaconda3/envs/GISpark/lib/python3.5/site-packages/IPython/extensions/cythonmagic.py:21: UserWarning: The Cython magic has been moved to the Cython package warnings.warn("""The Cython magic has been moved to the Cython package""") ** `%%cython_pyximport`** magic函数允许你在Cell中使用任意的Cython代码。Cython代码被写入`.pyx` 文件,保存在当前工作目录,然后使用`pyximport` 引用进来。需要指定一个模块的名称,所有的符号将被自动import。 ```python %%cython_pyximport foo def f(x): return 4.0*x ``` ERROR: Cell magic `%%cython_pyximport` not found. ```python f(10) ``` 40.0 ## The %cython magic `%cython` magic类似于 `%%cython_pyximport` magic, 但不需要指定一个模块名称. `%%cython` magic 使用 `~/.cython/magic`目录中的临时文件来管理模块,所有符号会被自动引用。 下面是一个使用Cython的例子,Black-Scholes options pricing algorithm: ```python %%cython cimport cython from libc.math cimport exp, sqrt, pow, log, erf @cython.cdivision(True) cdef double std_norm_cdf(double x) nogil: return 0.5*(1+erf(x/sqrt(2.0))) @cython.cdivision(True) def black_scholes(double s, double k, double t, double v, double rf, double div, double cp): """Price an option using the Black-Scholes model. s : initial stock price k : strike price t : expiration time v : volatility rf : risk-free rate div : dividend cp : +1/-1 for call/put """ cdef double d1, d2, optprice with nogil: d1 = (log(s/k)+(rf-div+0.5*pow(v,2))*t)/(v*sqrt(t)) d2 = d1 - v*sqrt(t) optprice = cp*s*exp(-div*t)*std_norm_cdf(cp*d1) - \ cp*k*exp(-rf*t)*std_norm_cdf(cp*d2) return optprice ``` ERROR: Cell magic `%%cython` not found. ```python black_scholes(100.0, 100.0, 1.0, 0.3, 0.03, 0.0, -1) ``` --------------------------------------------------------------------------- NameError Traceback (most recent call last) <ipython-input-40-ae31cbfa5fba> in <module>() ----> 1 black_scholes(100.0, 100.0, 1.0, 0.3, 0.03, 0.0, -1) NameError: name 'black_scholes' is not defined #### 测量一下运行时间。 ```python #%timeit black_scholes(100.0, 100.0, 1.0, 0.3, 0.03, 0.0, -1) ``` Cython 允许使用额外的库与你的扩展进行链接,采用 `-l` 选项 (或者 `--lib`)。 注意,该选项可以使用多次,libraries, such as `-lm -llib2 --lib lib3`. 这里是使用 system math library的例子: ```python %%cython -lm from libc.math cimport sin print 'sin(1)=', sin(1) ``` sin(1)= 0.841470984808 同样,可以使用 `-I/--include` 来指定包含头文件的目录, 以及使用 `-c/--compile-args` 编译选项,以及 `extra_compile_args` of the distutils `Extension` class. 请参考 [the Cython docs on C library usage](http://docs.cython.org/src/tutorial/clibraries.html) 获得更详细的说明。 # Rmagic 函数扩展 IPython 通过 `rmagic` 扩展来调用R模块,是通过rpy2来实现的(安装:`conda install rpy2`)。 rpy2的文档:http://rpy2.readthedocs.io/en/version_2.7.x/ #### 首先使用 `%load_ext` 载入该模块: **注意:新的rpy2已改动,不能运行**。参考:http://rpy2.readthedocs.io/en/version_2.7.x/interactive.html?highlight=rmagic ```python %reload_ext rmagic ``` /home/supermap/anaconda3/envs/GISpark/lib/python3.5/site-packages/IPython/extensions/rmagic.py:11: UserWarning: The rmagic extension in IPython has moved to `rpy2.ipython`, please see `rpy2` documentation. warnings.warn("The rmagic extension in IPython has moved to " 典型的用法是使用R来计算numpy的Array的统计指标。我们试一下简单线性模型,输出scatterplot。 ```python %matplotlib inline import numpy as np import matplotlib.pyplot as plt ``` ```python X = np.array([0,1,2,3,4]) Y = np.array([3,5,4,6,7]) plt.scatter(X, Y) ``` <matplotlib.collections.PathCollection at 0x7f9760cdd208> ![png](jupyter_magics_files/jupyter_magics_70_1.png) 首先把变量赋给 R, 拟合模型并返回结果。 %Rpush 拷贝 rpy2中的变量. %R 对 rpy2 中的字符串求值,然后返回结果。在这里是线性模型的协方差-coefficients。 ```python %Rpush X Y %R lm(Y~X)$coef ``` ERROR: Line magic function `%Rpush` not found. ERROR: Line magic function `%R` not found. %R可以返回多个值。 ```python %R resid(lm(Y~X)); coef(lm(X~Y)) ``` ERROR: Line magic function `%R` not found. 可以将 %R 结果传回 python objects. 返回值是一个“;”隔开的多行表达式,*coef(lm(X~Y))*. 拉取R的其它变量, 采用 %Rpull 和 %Rget. 在 R code 执行后,在 rpy2 namespace 有变量需要获取。 主要区别是: (%Rget)返回值, 而(%Rpull)从 self.shell.user_ns 拉取。想象一下,我们计算得到变量 "a" 在rpy2's namespace. 使用 %R magic, 我们得到结果并存储到 b。可以从 user_ns 使用 %Rpull得到。返回的是同一个数据。 ```python b = %R a=resid(lm(Y~X)) %Rpull a print(a) assert id(b.data) == id(a.data) %R -o a ``` [-0.2 0.9 -1. 0.1 0.2] ## Plotting and capturing output R的控制台stdout()被ipython捕获。 ```python from __future__ import print_function v1 = %R plot(X,Y); print(summary(lm(Y~X))); vv=mean(X)*mean(Y) print('v1 is:', v1) v2 = %R mean(X)*mean(Y) print('v2 is:', v2) ``` Call: lm(formula = Y ~ X) Residuals: 1 2 3 4 5 -0.2 0.9 -1.0 0.1 0.2 Coefficients: Estimate Std. Error t value Pr(>|t|) (Intercept) 3.2000 0.6164 5.191 0.0139 * X 0.9000 0.2517 3.576 0.0374 * --- Signif. codes: 0 ‘***’ 0.001 ‘**’ 0.01 ‘*’ 0.05 ‘.’ 0.1 ‘ ’ 1 Residual standard error: 0.7958 on 3 degrees of freedom Multiple R-squared: 0.81, Adjusted R-squared: 0.7467 F-statistic: 12.79 on 1 and 3 DF, p-value: 0.03739 ![png](jupyter_magics_files/jupyter_magics_80_1.png) v1 is: [ 10.] v2 is: [ 10.] ## Cell 级别的 magic 我们希望用R在cell级别。而且numpy最好不要转换,参考R: rnumpy ( http://bitbucket.org/njs/rnumpy/wiki/API ) 。 ```python %%R -i X,Y -o XYcoef XYlm = lm(Y~X) XYcoef = coef(XYlm) print(summary(XYlm)) par(mfrow=c(2,2)) plot(XYlm) ``` Call: lm(formula = Y ~ X) Residuals: 1 2 3 4 5 -0.2 0.9 -1.0 0.1 0.2 Coefficients: Estimate Std. Error t value Pr(>|t|) (Intercept) 3.2000 0.6164 5.191 0.0139 * X 0.9000 0.2517 3.576 0.0374 * --- Signif. codes: 0 ‘***’ 0.001 ‘**’ 0.01 ‘*’ 0.05 ‘.’ 0.1 ‘ ’ 1 Residual standard error: 0.7958 on 3 degrees of freedom Multiple R-squared: 0.81, Adjusted R-squared: 0.7467 F-statistic: 12.79 on 1 and 3 DF, p-value: 0.03739 ![png](jupyter_magics_files/jupyter_magics_83_1.png) # octavemagic: Octave inside IPython **`octavemagic`** 提供与Octave交互的能力。依赖 `oct2py` 和 `h5py` 软件包。 载入扩展包: %load_ext octavemagic ## 概览 载入这个扩展包,启用了三个magic functions: `%octave`, `%octave_push`, 和 `%octave_pull`。 第一个执行一行或多行Octave, 后面两个执行 Octave 和 Python 的变量交换。 ```python x = %octave [1 2; 3 4]; x ``` array([[ 1., 2.], [ 3., 4.]]) ```python a = [1, 2, 3] %octave_push a %octave a = a * 2; %octave_pull a a ``` array([[2, 4, 6]]) **`%%octave`** : 多行 Octave 被执行。但与单行不同, 没有值被返回, 我们使用`-i` 和 `-o` 指定输入和输出变量。 ```python %%octave -i x -o y y = x + 3; ``` ```python y ``` array([[ 4., 5.], [ 6., 7.]]) ## Plotting Plot输出自动被捕获和显示,使用 `-f` 参数选择输出的格式 (目前支持 `png` 和 `svg`)。 ```python %%octave -f svg p = [12 -2.5 -8 -0.1 8]; x = 0:0.01:1; polyout(p, 'x') plot(x, polyval(p, x)); ``` 12*x^4 - 2.5*x^3 - 8*x^2 - 0.1*x^1 + 8 ![svg](jupyter_magics_files/jupyter_magics_96_1.svg) 使用 `-s` 参数调整大小: ```python %%octave -s 500,500 # butterworth filter, order 2, cutoff pi/2 radians b = [0.292893218813452 0.585786437626905 0.292893218813452]; a = [1 0 0.171572875253810]; freqz(b, a, 32); ``` ![png](jupyter_magics_files/jupyter_magics_98_0.png) ```python %%octave -s 600,200 -f png subplot(121); [x, y] = meshgrid(0:0.1:3); r = sin(x - 0.5).^2 + cos(y - 0.5).^2; surf(x, y, r); subplot(122); sombrero() ``` ![png](jupyter_magics_files/jupyter_magics_99_0.png)
supergis/git_notebook
doc/jupyter_magics.md
Markdown
gpl-3.0
16,492
<!DOCTYPE html> <html lang="en-us"> <head> <title>Apt Get</title> <style> html body { font-family: Lato, sans-serif; background-color: white; } :root { --accent: #3fb3b2; --border-width: 5px ; } </style> <link rel="stylesheet" href="../../css/main.css"> <link rel="stylesheet" href="../../css/academicons.min.css"> <link rel="stylesheet" href="../../css/font-awesome.min.css"> <link rel="stylesheet" href="../../css/insileco.css"> <link rel="stylesheet" href="../../css/jquery.tocify.css"> <link rel="stylesheet" href="https://cdn.jsdelivr.net/gh/tonsky/FiraCode@1.206/distr/fira_code.css"> <link rel="stylesheet" href="https://ajax.googleapis.com/ajax/libs/jqueryui/1.12.1/themes/smoothness/jquery-ui.css"> <link rel="stylesheet" href="https://fonts.googleapis.com/css?family=Lato"> <link rel="stylesheet" href="//cdnjs.cloudflare.com/ajax/libs/highlight.js/9.12.0/styles/github.min.css"> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous"> <script src="//cdnjs.cloudflare.com/ajax/libs/highlight.js/9.12.0/highlight.min.js"></script> <script>hljs.initHighlightingOnLoad();</script> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script> <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js" integrity="sha384-Tc5IQib027qvyjSMfHjOMaLkfuWVxZxUPnCJA7l2mCWNIpG9mGCD8wGNIcPD7Txa" crossorigin="anonymous"></script> <script src="../../js/jquery-1.8.3.min.js"></script> <script src="../../js/jquery-ui-1.9.1.custom.min.js"></script> <script src="../../js/jquery.tocify.min.js"></script> <meta name="generator" content="Hugo 0.53" /> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <link href="https://insileco.github.io/tags/apt-get/index.xml" rel="alternate" type="application/rss+xml" title="inSileco" /> <link href="https://insileco.github.io/tags/apt-get/index.xml" rel="feed" type="application/rss+xml" title="inSileco" /> <script async src="https://www.googletagmanager.com/gtag/js?id=UA-109508556-1"></script> <script> window.dataLayer = window.dataLayer || []; function gtag(){dataLayer.push(arguments)}; gtag('js', new Date()); gtag('config', 'UA-109508556-1'); </script> </head> <body> <nav class="navbar navbar-default navbar-fixed-top"> <div class="container"> <div class="navbar-header"> <a class="navbar-brand visible-xs" href="#">Apt Get</a> <button class="navbar-toggle" data-target=".navbar-collapse" data-toggle="collapse"> <span class="icon-bar"></span> <span class="icon-bar"></span> <span class="icon-bar"></span> </button> </div> <div class="collapse navbar-collapse"> <ul class="nav navbar-nav"> <li><a href="../../">Home</a></li> <li><a href="../../about/">About</a></li> <li><a href="../../post/">Posts</a></li> <li><a href="../../software/">Software</a></li> <li><a href="../../tips/">Tips</a></li> <li><a href="../../tuto/">Tutorials</a></li> <li><a href="../../wiki/">Wiki</a></li> </ul> <ul class="nav navbar-nav navbar-right"> <li class="navbar-icon"><a href="https://github.com/inSileco/"><i class="fa fa-github"></i></a></li> <li class="navbar-icon"><a href="https://twitter.com/inSileco/"><i class="fa fa-twitter"></i></a></li> </ul> </div> </div> </nav> <main> <h2>Apt Get</h2> <div class="item"> <h1> <a href="../../2018/12/09/ubuntu-windows-7-dual-partition/">Ubuntu &#43; Windows 7 - dual partition</a> <small>December 9, 2018</small> </h1> <p> <i class="fa fa-tags" aria-hidden="true"></i> <a href="../../tags/windows"><kbd class="item-tag">Windows</kbd></a> <a href="../../tags/ubuntu"><kbd class="item-tag">Ubuntu</kbd></a> <a href="../../tags/dual-partition"><kbd class="item-tag">dual partition</kbd></a> <a href="../../tags/chocolatey"><kbd class="item-tag">chocolatey</kbd></a> <a href="../../tags/apt-get"><kbd class="item-tag">apt-get</kbd></a> </p> </div> </main> <footer> <script src="//yihui.name/js/math-code.js"></script> <script async src="//cdn.bootcss.com/mathjax/2.7.1/MathJax.js?config=TeX-MML-AM_CHTML"> </script> <p class="copyright text-muted">&copy; 2018 inSileco | All rights reserved | Powered by <a href="https://bookdown.org/yihui/blogdown/">Blogdown</a>, <a href="https://gohugo.io">Hugo</a> and <a href="https://github.com/calintat/minimal">Minimal</a>.</p> </footer> </body> </html>
letiR/letiR_website
tags/apt-get/index.html
HTML
gpl-3.0
5,892
// // njhseq - A library for analyzing sequence data // Copyright (C) 2012-2018 Nicholas Hathaway <nicholas.hathaway@umassmed.edu>, // // This file is part of njhseq. // // njhseq 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. // // njhseq 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 njhseq. If not, see <http://www.gnu.org/licenses/>. // /* * AlignerPool.cpp * * Created on: Jan 7, 2016 * Author: nick */ #include "AlignerPool.hpp" namespace njhseq { namespace concurrent { AlignerPool::AlignerPool(uint64_t startingMaxLen, const gapScoringParameters & gapInfo, const substituteMatrix & scoring, const size_t size) : startingMaxLen_(startingMaxLen), gapInfo_(gapInfo), scoring_(scoring), size_(size) { for(uint32_t i = 0; i < size_; ++i){ aligners_.emplace_back(aligner(startingMaxLen_, gapInfo_, scoring_)); } } AlignerPool::AlignerPool(const aligner & alignerObj, const size_t size) : startingMaxLen_(alignerObj.parts_.maxSize_), gapInfo_(alignerObj.parts_.gapScores_), scoring_( alignerObj.parts_.scoring_), size_(size) { for (uint32_t i = 0; i < size_; ++i) { aligners_.emplace_back(alignerObj); } } AlignerPool::AlignerPool(const size_t size) : size_(size) { startingMaxLen_ = 400; gapInfo_ = gapScoringParameters(5, 1); scoring_.setWithSimple(2, -2); for(uint32_t i = 0; i < size_; ++i){ aligners_.emplace_back(aligner(startingMaxLen_, gapInfo_, scoring_)); } } AlignerPool::AlignerPool(const AlignerPool& that) : startingMaxLen_(that.startingMaxLen_), gapInfo_(that.gapInfo_), scoring_(that.scoring_), size_( that.size_) { for(uint32_t i = 0; i < size_; ++i){ aligners_.emplace_back(aligner(startingMaxLen_, gapInfo_, scoring_)); } } AlignerPool::~AlignerPool() { std::lock_guard<std::mutex> lock(poolmtx_); // GUARD destoryAlignersNoLock(); } void AlignerPool::initAligners(){ std::lock_guard<std::mutex> lock(poolmtx_); // GUARD // now push them onto the queue for (aligner& alignerObj : aligners_) { alignerObj.processAlnInfoInput(inAlnDir_); pushAligner(alignerObj); } } void AlignerPool::destoryAligners(){ std::lock_guard<std::mutex> lock(poolmtx_); // GUARD destoryAlignersNoLock(); } void AlignerPool::destoryAlignersNoLock(){ closing_ = true; { //merge the alignment of the other aligners into one and then write to avoid duplications PooledAligner first_aligner_ptr; queue_.waitPop(first_aligner_ptr); if(size_ > 1){ for (size_t i = 1; i < size_; ++i) { PooledAligner aligner_ptr; queue_.waitPop(aligner_ptr); if("" != outAlnDir_){ first_aligner_ptr->alnHolder_.mergeOtherHolder(aligner_ptr->alnHolder_); } } } if("" != outAlnDir_){ first_aligner_ptr->processAlnInfoOutput(outAlnDir_, false); } } } void AlignerPool::pushAligner(aligner& alignerObj){ if(!closing_){ AlignerPool* p = this; queue_.push( std::shared_ptr<aligner>(&alignerObj, [p](aligner* alignerObj) { p->pushAligner(*alignerObj); })); } } PooledAligner AlignerPool::popAligner() { PooledAligner aligner_ptr; queue_.waitPop(aligner_ptr); return aligner_ptr; } } // namespace concurrent } // namespace njhseq
bailey-lab/bibseq
src/njhseq/concurrency/pools/AlignerPool.cpp
C++
gpl-3.0
3,615
<?php /* * Copyright (C) 2015 Biospex * biospex@gmail.com * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. */ namespace App\Listeners; use Illuminate\Support\Facades\Cache; /** * Class CacheEventSubscriber * * @package App\Listeners */ class CacheEventSubscriber { /** * Register the listeners for the subscriber. * * @param $events */ public function subscribe($events) { $events->listen( 'cache.flush', 'App\Listeners\CacheEventSubscriber@flush' ); } /** * Flush tag * @param $tag */ public function flush($tag) { Cache::tags((string) $tag)->flush(); } }
iDigBio/Biospex
app/Listeners/CacheEventSubscriber.php
PHP
gpl-3.0
1,285
/* * Copyright (C) 2017 Timo Vesalainen <timo.vesalainen@iki.fi> * * 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/>. */ package org.vesalainen.vfs.attributes; import java.nio.ByteBuffer; import java.nio.file.attribute.AclFileAttributeView; import java.nio.file.attribute.BasicFileAttributeView; import java.nio.file.attribute.DosFileAttributeView; import java.nio.file.attribute.FileAttributeView; import java.nio.file.attribute.FileOwnerAttributeView; import java.nio.file.attribute.FileTime; import java.nio.file.attribute.GroupPrincipal; import java.nio.file.attribute.PosixFileAttributeView; import java.nio.file.attribute.UserDefinedFileAttributeView; import java.nio.file.attribute.UserPrincipal; import java.util.Arrays; import java.util.HashMap; import java.util.HashSet; import java.util.Map; import java.util.Objects; import java.util.Set; import java.util.stream.Collectors; import org.vesalainen.util.Bijection; import org.vesalainen.util.HashBijection; import org.vesalainen.util.HashMapSet; import org.vesalainen.util.CollectionHelp; import org.vesalainen.util.MapSet; import org.vesalainen.vfs.unix.UnixFileAttributeView; /** * * @author Timo Vesalainen <timo.vesalainen@iki.fi> */ public final class FileAttributeName { public static final String BASIC_VIEW = "basic"; public static final String ACL_VIEW = "acl"; public static final String POSIX_VIEW = "posix"; public static final String OWNER_VIEW = "owner"; public static final String DOS_VIEW = "dos"; public static final String USER_VIEW = "user"; public static final String UNIX_VIEW = "org.vesalainen.vfs.unix"; public static final String DIGEST_VIEW = "org.vesalainen.vfs.digest"; // digest public static final String CONTENT = DIGEST_VIEW+":org.vesalainen.vfs.content"; public static final String CPIO_CHECKSUM = DIGEST_VIEW+":org.vesalainen.vfs.cpiochecksum"; public static final String CRC32 = DIGEST_VIEW+":org.vesalainen.vfs.crc32"; public static final String MD5 = DIGEST_VIEW+":org.vesalainen.vfs.md5"; public static final String SHA1 = DIGEST_VIEW+":org.vesalainen.vfs.sha1"; public static final String SHA256 = DIGEST_VIEW+":org.vesalainen.vfs.sha256"; public static final String DEVICE = UNIX_VIEW+":org.vesalainen.vfs.device"; public static final String INODE = UNIX_VIEW+":org.vesalainen.vfs.inode"; public static final String NLINK = UNIX_VIEW+":org.vesalainen.vfs.nlink"; public static final String SETUID = UNIX_VIEW+":org.vesalainen.vfs.setuid"; public static final String SETGID = UNIX_VIEW+":org.vesalainen.vfs.setgid"; public static final String STICKY = UNIX_VIEW+":org.vesalainen.vfs.sticky"; // posix public static final String PERMISSIONS = "posix:permissions"; public static final String GROUP = "posix:group"; // basic public static final String LAST_MODIFIED_TIME = "basic:lastModifiedTime"; public static final String LAST_ACCESS_TIME = "basic:lastAccessTime"; public static final String CREATION_TIME = "basic:creationTime"; public static final String SIZE = "basic:size"; public static final String IS_REGULAR = "basic:isRegularFile"; public static final String IS_DIRECTORY = "basic:isDirectory"; public static final String IS_SYMBOLIC_LINK = "basic:isSymbolicLink"; public static final String IS_OTHER = "basic:isOther"; public static final String FILE_KEY = "basic:fileKey"; public static final String OWNER = "owner:owner"; public static final String ACL = "acl:acl"; public static final String READONLY = "dos:readonly"; public static final String HIDDEN = "dos:hidden"; public static final String SYSTEM = "dos:system"; public static final String ARCHIVE = "dos:archive"; private static final Map<String,Class<?>> types; private static final Bijection<String,Class<? extends FileAttributeView>> nameView; private static final MapSet<String,String> impliesMap = new HashMapSet<>(); private static final Map<String,Name> nameMap = new HashMap<>(); static { addName(DEVICE); addName(INODE); addName(NLINK); addName(SETUID); addName(SETGID); addName(STICKY); // posix addName(PERMISSIONS); addName(GROUP); // basic addName(LAST_MODIFIED_TIME); addName(LAST_ACCESS_TIME); addName(CREATION_TIME); addName(SIZE); addName(IS_REGULAR); addName(IS_DIRECTORY); addName(IS_SYMBOLIC_LINK); addName(IS_OTHER); addName(FILE_KEY); addName(OWNER); addName(ACL); addName(READONLY); addName(HIDDEN); addName(SYSTEM); addName(ARCHIVE); addName(CONTENT); addName(CPIO_CHECKSUM); addName(CRC32); addName(MD5); addName(SHA1); addName(SHA256); types = new HashMap<>(); types.put(DEVICE, Integer.class); types.put(INODE, Integer.class); types.put(NLINK, Integer.class); types.put(SETUID, Boolean.class); types.put(SETGID, Boolean.class); types.put(STICKY, Boolean.class); types.put(PERMISSIONS, Set.class); types.put(GROUP, GroupPrincipal.class); types.put(OWNER, UserPrincipal.class); types.put(LAST_MODIFIED_TIME, FileTime.class); types.put(LAST_ACCESS_TIME, FileTime.class); types.put(CREATION_TIME, FileTime.class); types.put(SIZE, Long.class); types.put(IS_REGULAR, Boolean.class); types.put(IS_DIRECTORY, Boolean.class); types.put(IS_SYMBOLIC_LINK, Boolean.class); types.put(IS_OTHER, Boolean.class); types.put(FILE_KEY, Boolean.class); nameView = new HashBijection<>(); nameView.put(BASIC_VIEW, BasicFileAttributeView.class); nameView.put(ACL_VIEW, AclFileAttributeView.class); nameView.put(DOS_VIEW, DosFileAttributeView.class); nameView.put(OWNER_VIEW, FileOwnerAttributeView.class); nameView.put(POSIX_VIEW, PosixFileAttributeView.class); nameView.put(USER_VIEW, UserDefinedFileAttributeView.class); nameView.put(UNIX_VIEW, UnixFileAttributeView.class); nameView.put(DIGEST_VIEW, DigestFileAttributeView.class); initImplies(BASIC_VIEW); initImplies(ACL_VIEW); initImplies(DOS_VIEW); initImplies(OWNER_VIEW); initImplies(POSIX_VIEW); initImplies(USER_VIEW); initImplies(UNIX_VIEW); initImplies(DIGEST_VIEW); } private static void initImplies(String view) { Class<? extends FileAttributeView> viewClass = nameView.getSecond(view); initImplies(view, viewClass); } private static void initImplies(String view, Class<? extends FileAttributeView> viewClass) { String name = nameView.getFirst(viewClass); if (name != null) { impliesMap.add(view, name); } for (Class<?> itf : viewClass.getInterfaces()) { if (FileAttributeView.class.isAssignableFrom(itf)) { initImplies(view, (Class<? extends FileAttributeView>) itf); } } } /** * Returns a set that contains given views as well as all implied views. * @param views * @return */ public static final Set<String> impliedSet(String... views) { Set<String> set = new HashSet<>(); for (String view : views) { set.addAll(impliesMap.get(view)); } return set; } public static final Set<String> topViews(Set<String> views) { return topViews(CollectionHelp.toArray(views, String.class)); } public static final Set<String> topViews(String... views) { Set<String> set = Arrays.stream(views).collect(Collectors.toSet()); int len = views.length; for (int ii=0;ii<len;ii++) { String view = views[ii]; for (int jj=0;jj<len;jj++) { if (ii != jj) { Set<String> is = impliesMap.get(views[jj]); if (is.contains(view)) { set.remove(view); } } } } return set; } public static final Class<?> type(Name name) { return types.get(name.toString()); } public static final void check(Name name, Object value) { Objects.requireNonNull(value, "value can't be null"); if (DIGEST_VIEW.equals(name.view)) { if (!value.getClass().equals(byte[].class) && !(value instanceof ByteBuffer)) { throw new ClassCastException(value+" not expected type byte[]/ByteBuffer"); } } else { if (USER_VIEW.equals(name.view)) { if (!value.getClass().equals(byte[].class) && !(value instanceof ByteBuffer)) { throw new ClassCastException(value+" not expected type byte[]/ByteBuffer"); } } else { Class<?> type = FileAttributeName.type(name); if (type == null || !type.isAssignableFrom(value.getClass())) { throw new ClassCastException(value+" not expected type "+type); } } } } private static void addName(String attr) { Name name = getInstance(attr); Name old = nameMap.put(name.name, name); if (old != null) { throw new IllegalArgumentException(name+" ambiguous"); } } public static class FileAttributeNameMatcher { private Set<String> views; private String[] attributes; public FileAttributeNameMatcher(String expr) { String view = BASIC_VIEW; int idx = expr.indexOf(':'); if (idx != -1) { view = expr.substring(0, idx); expr = expr.substring(idx+1); } if (expr.startsWith("*")) { if (expr.length() != 1) { throw new IllegalArgumentException(expr+" invalid"); } } else { attributes = expr.split(","); } views = impliesMap.get(view); if (views == null) { throw new UnsupportedOperationException(view+" not supported"); } } public boolean any(String name) { return any(getInstance(name)); } public boolean any(Name name) { if (!views.contains(name.view)) { return false; } if (attributes == null) { return true; } else { for (String at : attributes) { if (at.equals(name.name)) { return true; } } } return false; } } public static final Name getInstance(String attribute) { Name name = nameMap.get(attribute); if (name == null) { String view; String attr; int idx = attribute.indexOf(':'); if (idx != -1) { view = attribute.substring(0, idx); attr = attribute.substring(idx+1); name = new Name(view, attr); } else { view = BASIC_VIEW; attr = attribute; name = new Name(view, attr); nameMap.put(attr, name); } nameMap.put(attribute, name); } return name; } public static class Name { private String view; private String name; private String string; public Name(String view, String name) { this.view = view; this.name = name; this.string = view+':'+name; } public String getView() { return view; } public String getName() { return name; } @Override public String toString() { return string; } } }
tvesalainen/util
vfs/src/main/java/org/vesalainen/vfs/attributes/FileAttributeName.java
Java
gpl-3.0
13,646
/*---------------------------------------------------------------------------*\ ========= | \\ / F ield | OpenFOAM: The Open Source CFD Toolbox \\ / O peration | \\ / A nd | Copyright (C) 2011 OpenFOAM Foundation \\/ M anipulation | ------------------------------------------------------------------------------- License This file is part of OpenFOAM. OpenFOAM 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. OpenFOAM 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 OpenFOAM. If not, see <http://www.gnu.org/licenses/>. InNamespace Foam Description Bound the given scalar field if it has gone unbounded. Used extensively in RAS and LES turbulence models, but also of use within solvers. SourceFiles bound.C \*---------------------------------------------------------------------------*/ #ifndef bound_H #define bound_H #include "OpenFOAM-2.1.x/src/OpenFOAM/dimensionedTypes/dimensionedScalar/dimensionedScalar.H" #include "OpenFOAM-2.1.x/src/finiteVolume/fields/volFields/volFieldsFwd.H" // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * // namespace Foam { // * * * * * * * * * * * * * * * Global Functions * * * * * * * * * * * * * // //- Bound the given scalar field if it has gone unbounded. // Return the bounded field. // Used extensively in RAS and LES turbulence models. volScalarField& bound(volScalarField&, const dimensionedScalar& lowerBound); // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * // } // End namespace Foam // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * // #endif // ************************************************************************* //
kempj/OpenFOAM-win
src/finiteVolume/cfdTools/general/bound/bound.H
C++
gpl-3.0
2,244
package de.macbury.botlogic.core.ui.code_editor.js; import java.io.Reader; /** * A simple Java source file parser for syntax highlighting. * * @author Matthias Mann */ public class JavaScriptScanner { public enum Kind { /** End of file - this token has no text */ EOF, /** End of line - this token has no text */ NEWLINE, /** Normal text - does not include line breaks */ NORMAL, /** A keyword */ KEYWORD, /** A string or character constant */ STRING, /** A comment - multi line comments are split up and {@link NEWLINE} tokens are inserted */ COMMENT, /** A javadoc tag inside a comment */ COMMENT_TAG, NUMBER, SPECIAL_KEYWORD } private static final KeywordList KEYWORD_LIST = new KeywordList( "function", "true", "false", "var", "for", "while", "if", "else", "null", "this", "new", "switch", "case", "break", "try", "catch", "do", "instanceof", "return", "throw", "typeof", "with", "prototype"); private static final KeywordList SPECIAL_KEYWORD_LIST = new KeywordList("robot", "led", "sonar", "console"); private final CharacterIterator iterator; private boolean inMultiLineComment; public JavaScriptScanner(CharSequence cs) { this.iterator = new CharacterIterator(cs); } public JavaScriptScanner(Reader r) { this.iterator = new CharacterIterator(r); } /** * Scans for the next token. * Read errors result in EOF. * * Use {@link #getString()} to retrieve the string for the parsed token. * * @return the next token. */ public Kind scan() { iterator.clear(); if(inMultiLineComment) { return scanMultiLineComment(false); } int ch = iterator.next(); switch(ch) { case CharacterIterator.EOF: return Kind.EOF; case '\n': return Kind.NEWLINE; case '\"': case '\'': scanString(ch); return Kind.STRING; case '/': switch(iterator.peek()) { case '/': iterator.advanceToEOL(); return Kind.COMMENT; case '*': inMultiLineComment = true; iterator.next(); // skip '*' return scanMultiLineComment(true); } // fall through default: return scanNormal(ch); } } /** * Returns the string for the last token returned by {@link #scan() } * * @return the string for the last token */ public String getString() { return iterator.getString(); } public int getCurrentPosition() { return iterator.getCurrentPosition(); } private void scanString(int endMarker) { for(;;) { int ch = iterator.next(); if(ch == '\\') { iterator.next(); } else if(ch == '\n') { iterator.pushback(); return; } else if(ch == endMarker || ch == '\n' || ch == '\r' || ch < 0) { return; } } } private Kind scanMultiLineComment(boolean start) { int ch = iterator.next(); if(!start && ch == '\n') { return Kind.NEWLINE; } if(ch == '@') { iterator.advanceIdentifier(); return Kind.COMMENT_TAG; } for(;;) { if(ch < 0 || (ch == '*' && iterator.peek() == '/')) { iterator.next(); inMultiLineComment = false; return Kind.COMMENT; } if(ch == '\n') { iterator.pushback(); return Kind.COMMENT; } if(ch == '@') { iterator.pushback(); return Kind.COMMENT; } ch = iterator.next(); } } private Kind scanNormal(int ch) { for(;;) { switch(ch) { case '\n': case '\"': case '\'': case CharacterIterator.EOF: iterator.pushback(); return Kind.NORMAL; case '/': if(iterator.check("/*")) { iterator.pushback(); return Kind.NORMAL; } break; default: if(Character.isJavaIdentifierStart(ch)) { iterator.setMarker(true); iterator.advanceIdentifier(); if(iterator.isKeyword(KEYWORD_LIST)) { if(iterator.isMarkerAtStart()) { return Kind.KEYWORD; } iterator.rewindToMarker(); return Kind.NORMAL; } else if(iterator.isKeyword(SPECIAL_KEYWORD_LIST)) { if(iterator.isMarkerAtStart()) { return Kind.SPECIAL_KEYWORD; } iterator.rewindToMarker(); return Kind.NORMAL; } else if (Character.isDigit(ch)) { return Kind.NUMBER; } } break; } ch = iterator.next(); } } }
macbury/BotLogic
src/de/macbury/botlogic/core/ui/code_editor/js/JavaScriptScanner.java
Java
gpl-3.0
4,698
# vim: ft=python fileencoding=utf-8 sts=4 sw=4 et: # Copyright 2015-2021 Florian Bruhin (The Compiler) <mail@qutebrowser.org> # # This file is part of qutebrowser. # # qutebrowser 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. # # qutebrowser 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 qutebrowser. If not, see <https://www.gnu.org/licenses/>. """Tests for qutebrowser.misc.ipc.""" import os import pathlib import getpass import logging import json import hashlib import dataclasses from unittest import mock from typing import Optional, List import pytest from PyQt5.QtCore import pyqtSignal, QObject from PyQt5.QtNetwork import QLocalServer, QLocalSocket, QAbstractSocket from PyQt5.QtTest import QSignalSpy import qutebrowser from qutebrowser.misc import ipc from qutebrowser.utils import standarddir, utils from helpers import stubs, utils as testutils pytestmark = pytest.mark.usefixtures('qapp') @pytest.fixture(autouse=True) def shutdown_server(): """If ipc.send_or_listen was called, make sure to shut server down.""" yield if ipc.server is not None: ipc.server.shutdown() @pytest.fixture def ipc_server(qapp, qtbot): server = ipc.IPCServer('qute-test') yield server if (server._socket is not None and server._socket.state() != QLocalSocket.UnconnectedState): with qtbot.waitSignal(server._socket.disconnected, raising=False): server._socket.abort() try: server.shutdown() except ipc.Error: pass @pytest.fixture def qlocalserver(qapp): server = QLocalServer() yield server server.close() server.deleteLater() @pytest.fixture def qlocalsocket(qapp): socket = QLocalSocket() yield socket socket.disconnectFromServer() if socket.state() != QLocalSocket.UnconnectedState: socket.waitForDisconnected(1000) @pytest.fixture(autouse=True) def fake_runtime_dir(monkeypatch, short_tmpdir): monkeypatch.setenv('XDG_RUNTIME_DIR', str(short_tmpdir)) standarddir._init_runtime(args=None) return short_tmpdir class FakeSocket(QObject): """A stub for a QLocalSocket. Args: _can_read_line_val: The value returned for canReadLine(). _error_val: The value returned for error(). _state_val: The value returned for state(). _connect_successful: The value returned for waitForConnected(). """ readyRead = pyqtSignal() # noqa: N815 disconnected = pyqtSignal() def __init__(self, *, error=QLocalSocket.UnknownSocketError, state=None, data=None, connect_successful=True, parent=None): super().__init__(parent) self._error_val = error self._state_val = state self._data = data self._connect_successful = connect_successful self.error = stubs.FakeSignal('error', func=self._error) def _error(self): return self._error_val def state(self): return self._state_val def canReadLine(self): return bool(self._data) def readLine(self): firstline, mid, rest = self._data.partition(b'\n') self._data = rest return firstline + mid def errorString(self): return "Error string" def abort(self): self.disconnected.emit() def disconnectFromServer(self): pass def connectToServer(self, _name): pass def waitForConnected(self, _time): return self._connect_successful def writeData(self, _data): pass def waitForBytesWritten(self, _time): pass def waitForDisconnected(self, _time): pass class FakeServer: def __init__(self, socket): self._socket = socket def nextPendingConnection(self): socket = self._socket self._socket = None return socket def close(self): pass def deleteLater(self): pass def test_getpass_getuser(): """Make sure getpass.getuser() returns something sensible.""" assert getpass.getuser() def md5(inp): return hashlib.md5(inp.encode('utf-8')).hexdigest() class TestSocketName: WINDOWS_TESTS = [ (None, 'qutebrowser-testusername'), ('/x', 'qutebrowser-testusername-{}'.format(md5('/x'))), ] @pytest.fixture(autouse=True) def patch_user(self, monkeypatch): monkeypatch.setattr(ipc.getpass, 'getuser', lambda: 'testusername') @pytest.mark.parametrize('basedir, expected', WINDOWS_TESTS) @pytest.mark.windows def test_windows(self, basedir, expected): socketname = ipc._get_socketname(basedir) assert socketname == expected @pytest.mark.parametrize('basedir, expected', WINDOWS_TESTS) def test_windows_on_posix(self, basedir, expected): socketname = ipc._get_socketname_windows(basedir) assert socketname == expected def test_windows_broken_getpass(self, monkeypatch): def _fake_username(): raise ImportError monkeypatch.setattr(ipc.getpass, 'getuser', _fake_username) with pytest.raises(ipc.Error, match='USERNAME'): ipc._get_socketname_windows(basedir=None) @pytest.mark.mac @pytest.mark.parametrize('basedir, expected', [ (None, 'i-{}'.format(md5('testusername'))), ('/x', 'i-{}'.format(md5('testusername-/x'))), ]) def test_mac(self, basedir, expected): socketname = ipc._get_socketname(basedir) parts = socketname.split(os.sep) assert parts[-2] == 'qutebrowser' assert parts[-1] == expected @pytest.mark.linux @pytest.mark.parametrize('basedir, expected', [ (None, 'ipc-{}'.format(md5('testusername'))), ('/x', 'ipc-{}'.format(md5('testusername-/x'))), ]) def test_linux(self, basedir, fake_runtime_dir, expected): socketname = ipc._get_socketname(basedir) expected_path = str(fake_runtime_dir / 'qutebrowser' / expected) assert socketname == expected_path def test_other_unix(self): """Fake test for POSIX systems which aren't Linux/macOS. We probably would adjust the code first to make it work on that platform. """ if utils.is_windows: pass elif utils.is_mac: pass elif utils.is_linux: pass else: raise Exception("Unexpected platform!") class TestExceptions: def test_listen_error(self, qlocalserver): qlocalserver.listen(None) exc = ipc.ListenError(qlocalserver) assert exc.code == 2 assert exc.message == "QLocalServer::listen: Name error" msg = ("Error while listening to IPC server: QLocalServer::listen: " "Name error (error 2)") assert str(exc) == msg with pytest.raises(ipc.Error): raise exc def test_socket_error(self, qlocalserver): socket = FakeSocket(error=QLocalSocket.ConnectionRefusedError) exc = ipc.SocketError("testing", socket) assert exc.code == QLocalSocket.ConnectionRefusedError assert exc.message == "Error string" assert str(exc) == "Error while testing: Error string (error 0)" with pytest.raises(ipc.Error): raise exc class TestListen: @pytest.mark.posix def test_remove_error(self, ipc_server, monkeypatch): """Simulate an error in _remove_server.""" monkeypatch.setattr(ipc_server, '_socketname', None) with pytest.raises(ipc.Error, match="Error while removing server None!"): ipc_server.listen() def test_error(self, ipc_server, monkeypatch): """Simulate an error while listening.""" monkeypatch.setattr(ipc.QLocalServer, 'removeServer', lambda self: True) monkeypatch.setattr(ipc_server, '_socketname', None) with pytest.raises(ipc.ListenError): ipc_server.listen() @pytest.mark.posix def test_in_use(self, qlocalserver, ipc_server, monkeypatch): monkeypatch.setattr(ipc.QLocalServer, 'removeServer', lambda self: True) qlocalserver.listen('qute-test') with pytest.raises(ipc.AddressInUseError): ipc_server.listen() def test_successful(self, ipc_server): ipc_server.listen() @pytest.mark.windows def test_permissions_windows(self, ipc_server): opts = ipc_server._server.socketOptions() assert opts == QLocalServer.UserAccessOption @pytest.mark.posix def test_permissions_posix(self, ipc_server): ipc_server.listen() sockfile = ipc_server._server.fullServerName() sockdir = pathlib.Path(sockfile).parent file_stat = os.stat(sockfile) dir_stat = sockdir.stat() # pylint: disable=no-member,useless-suppression file_owner_ok = file_stat.st_uid == os.getuid() dir_owner_ok = dir_stat.st_uid == os.getuid() # pylint: enable=no-member,useless-suppression file_mode_ok = file_stat.st_mode & 0o777 == 0o700 dir_mode_ok = dir_stat.st_mode & 0o777 == 0o700 print('sockdir: {} / owner {} / mode {:o}'.format( sockdir, dir_stat.st_uid, dir_stat.st_mode)) print('sockfile: {} / owner {} / mode {:o}'.format( sockfile, file_stat.st_uid, file_stat.st_mode)) assert file_owner_ok or dir_owner_ok assert file_mode_ok or dir_mode_ok @pytest.mark.posix def test_atime_update(self, qtbot, ipc_server): ipc_server._atime_timer.setInterval(500) # We don't want to wait ipc_server.listen() old_atime = os.stat(ipc_server._server.fullServerName()).st_atime_ns with qtbot.waitSignal(ipc_server._atime_timer.timeout, timeout=2000): pass # Make sure the timer is not singleShot with qtbot.waitSignal(ipc_server._atime_timer.timeout, timeout=2000): pass new_atime = os.stat(ipc_server._server.fullServerName()).st_atime_ns assert old_atime != new_atime @pytest.mark.posix def test_atime_update_no_name(self, qtbot, caplog, ipc_server): with caplog.at_level(logging.ERROR): ipc_server.update_atime() assert caplog.messages[-1] == "In update_atime with no server path!" @pytest.mark.posix def test_atime_shutdown_typeerror(self, qtbot, ipc_server): """This should never happen, but let's handle it gracefully.""" ipc_server._atime_timer.timeout.disconnect(ipc_server.update_atime) ipc_server.shutdown() @pytest.mark.posix def test_vanished_runtime_file(self, qtbot, caplog, ipc_server): ipc_server._atime_timer.setInterval(500) # We don't want to wait ipc_server.listen() sockfile = pathlib.Path(ipc_server._server.fullServerName()) sockfile.unlink() with caplog.at_level(logging.ERROR): with qtbot.waitSignal(ipc_server._atime_timer.timeout, timeout=2000): pass msg = 'Failed to update IPC socket, trying to re-listen...' assert caplog.messages[-1] == msg assert ipc_server._server.isListening() assert sockfile.exists() class TestOnError: def test_closed(self, ipc_server): ipc_server._socket = QLocalSocket() ipc_server._timer.timeout.disconnect() ipc_server._timer.start() ipc_server.on_error(QLocalSocket.PeerClosedError) assert not ipc_server._timer.isActive() def test_other_error(self, ipc_server, monkeypatch): socket = QLocalSocket() ipc_server._socket = socket monkeypatch.setattr(socket, 'error', lambda: QLocalSocket.ConnectionRefusedError) monkeypatch.setattr(socket, 'errorString', lambda: "Connection refused") socket.setErrorString("Connection refused.") with pytest.raises(ipc.Error, match=r"Error while handling IPC " r"connection: Connection refused \(error 0\)"): ipc_server.on_error(QLocalSocket.ConnectionRefusedError) class TestHandleConnection: def test_ignored(self, ipc_server, monkeypatch): m = mock.Mock(spec=[]) monkeypatch.setattr(ipc_server._server, 'nextPendingConnection', m) ipc_server.ignored = True ipc_server.handle_connection() m.assert_not_called() def test_no_connection(self, ipc_server, caplog): ipc_server.handle_connection() assert caplog.messages[-1] == "No new connection to handle." def test_double_connection(self, qlocalsocket, ipc_server, caplog): ipc_server._socket = qlocalsocket ipc_server.handle_connection() msg = ("Got new connection but ignoring it because we're still " "handling another one") assert any(message.startswith(msg) for message in caplog.messages) def test_disconnected_immediately(self, ipc_server, caplog): socket = FakeSocket(state=QLocalSocket.UnconnectedState) ipc_server._server = FakeServer(socket) ipc_server.handle_connection() assert "Socket was disconnected immediately." in caplog.messages def test_error_immediately(self, ipc_server, caplog): socket = FakeSocket(error=QLocalSocket.ConnectionError) ipc_server._server = FakeServer(socket) with pytest.raises(ipc.Error, match=r"Error while handling IPC " r"connection: Error string \(error 7\)"): ipc_server.handle_connection() assert "We got an error immediately." in caplog.messages def test_read_line_immediately(self, qtbot, ipc_server, caplog): data = ('{{"args": ["foo"], "target_arg": "tab", ' '"protocol_version": {}}}\n'.format(ipc.PROTOCOL_VERSION)) socket = FakeSocket(data=data.encode('utf-8')) ipc_server._server = FakeServer(socket) with qtbot.waitSignal(ipc_server.got_args) as blocker: ipc_server.handle_connection() assert blocker.args == [['foo'], 'tab', ''] assert "We can read a line immediately." in caplog.messages @pytest.fixture def connected_socket(qtbot, qlocalsocket, ipc_server): if utils.is_mac: pytest.skip("Skipping connected_socket test - " "https://github.com/qutebrowser/qutebrowser/issues/1045") ipc_server.listen() with qtbot.waitSignal(ipc_server._server.newConnection): qlocalsocket.connectToServer('qute-test') yield qlocalsocket qlocalsocket.disconnectFromServer() def test_disconnected_without_data(qtbot, connected_socket, ipc_server, caplog): """Disconnect without sending data. This means self._socket will be None on on_disconnected. """ connected_socket.disconnectFromServer() def test_partial_line(connected_socket): connected_socket.write(b'foo') OLD_VERSION = str(ipc.PROTOCOL_VERSION - 1).encode('utf-8') NEW_VERSION = str(ipc.PROTOCOL_VERSION + 1).encode('utf-8') @pytest.mark.parametrize('data, msg', [ (b'\x80\n', 'invalid utf-8'), (b'\n', 'invalid json'), (b'{"is this invalid json?": true\n', 'invalid json'), (b'{"valid json without args": true}\n', 'Missing args'), (b'{"args": []}\n', 'Missing target_arg'), (b'{"args": [], "target_arg": null, "protocol_version": ' + OLD_VERSION + b'}\n', 'incompatible version'), (b'{"args": [], "target_arg": null, "protocol_version": ' + NEW_VERSION + b'}\n', 'incompatible version'), (b'{"args": [], "target_arg": null, "protocol_version": "foo"}\n', 'invalid version'), (b'{"args": [], "target_arg": null}\n', 'invalid version'), ]) def test_invalid_data(qtbot, ipc_server, connected_socket, caplog, data, msg): signals = [ipc_server.got_invalid_data, connected_socket.disconnected] with caplog.at_level(logging.ERROR): with qtbot.assertNotEmitted(ipc_server.got_args): with qtbot.waitSignals(signals, order='strict'): connected_socket.write(data) invalid_msg = 'Ignoring invalid IPC data from socket ' assert caplog.messages[-1].startswith(invalid_msg) assert caplog.messages[-2].startswith(msg) def test_multiline(qtbot, ipc_server, connected_socket): spy = QSignalSpy(ipc_server.got_args) data = ('{{"args": ["one"], "target_arg": "tab",' ' "protocol_version": {version}}}\n' '{{"args": ["two"], "target_arg": null,' ' "protocol_version": {version}}}\n'.format( version=ipc.PROTOCOL_VERSION)) with qtbot.assertNotEmitted(ipc_server.got_invalid_data): with qtbot.waitSignals([ipc_server.got_args, ipc_server.got_args], order='strict'): connected_socket.write(data.encode('utf-8')) assert len(spy) == 2 assert spy[0] == [['one'], 'tab', ''] assert spy[1] == [['two'], '', ''] class TestSendToRunningInstance: def test_no_server(self, caplog): sent = ipc.send_to_running_instance('qute-test', [], None) assert not sent assert caplog.messages[-1] == "No existing instance present (error 2)" @pytest.mark.parametrize('has_cwd', [True, False]) @pytest.mark.linux(reason="Causes random trouble on Windows and macOS") def test_normal(self, qtbot, tmp_path, ipc_server, mocker, has_cwd): ipc_server.listen() with qtbot.assertNotEmitted(ipc_server.got_invalid_data): with qtbot.waitSignal(ipc_server.got_args, timeout=5000) as blocker: with qtbot.waitSignal(ipc_server.got_raw, timeout=5000) as raw_blocker: with testutils.change_cwd(tmp_path): if not has_cwd: m = mocker.patch('qutebrowser.misc.ipc.os') m.getcwd.side_effect = OSError sent = ipc.send_to_running_instance( 'qute-test', ['foo'], None) assert sent expected_cwd = str(tmp_path) if has_cwd else '' assert blocker.args == [['foo'], '', expected_cwd] raw_expected = {'args': ['foo'], 'target_arg': None, 'version': qutebrowser.__version__, 'protocol_version': ipc.PROTOCOL_VERSION} if has_cwd: raw_expected['cwd'] = str(tmp_path) assert len(raw_blocker.args) == 1 parsed = json.loads(raw_blocker.args[0].decode('utf-8')) assert parsed == raw_expected def test_socket_error(self): socket = FakeSocket(error=QLocalSocket.ConnectionError) with pytest.raises(ipc.Error, match=r"Error while writing to running " r"instance: Error string \(error 7\)"): ipc.send_to_running_instance('qute-test', [], None, socket=socket) def test_not_disconnected_immediately(self): socket = FakeSocket() ipc.send_to_running_instance('qute-test', [], None, socket=socket) def test_socket_error_no_server(self): socket = FakeSocket(error=QLocalSocket.ConnectionError, connect_successful=False) with pytest.raises(ipc.Error, match=r"Error while connecting to " r"running instance: Error string \(error 7\)"): ipc.send_to_running_instance('qute-test', [], None, socket=socket) @pytest.mark.not_mac(reason="https://github.com/qutebrowser/qutebrowser/" "issues/975") def test_timeout(qtbot, caplog, qlocalsocket, ipc_server): ipc_server._timer.setInterval(100) ipc_server.listen() with qtbot.waitSignal(ipc_server._server.newConnection): qlocalsocket.connectToServer('qute-test') with caplog.at_level(logging.ERROR): with qtbot.waitSignal(qlocalsocket.disconnected, timeout=5000): pass assert caplog.messages[-1].startswith("IPC connection timed out") def test_ipcserver_socket_none_readyread(ipc_server, caplog): assert ipc_server._socket is None assert ipc_server._old_socket is None with caplog.at_level(logging.WARNING): ipc_server.on_ready_read() msg = "In on_ready_read with None socket and old_socket!" assert msg in caplog.messages @pytest.mark.posix def test_ipcserver_socket_none_error(ipc_server, caplog): assert ipc_server._socket is None ipc_server.on_error(0) msg = "In on_error with None socket!" assert msg in caplog.messages class TestSendOrListen: @dataclasses.dataclass class Args: no_err_windows: bool basedir: str command: List[str] target: Optional[str] @pytest.fixture def args(self): return self.Args(no_err_windows=True, basedir='/basedir/for/testing', command=['test'], target=None) @pytest.fixture def qlocalserver_mock(self, mocker): m = mocker.patch('qutebrowser.misc.ipc.QLocalServer', autospec=True) m().errorString.return_value = "Error string" m().newConnection = stubs.FakeSignal() return m @pytest.fixture def qlocalsocket_mock(self, mocker): m = mocker.patch('qutebrowser.misc.ipc.QLocalSocket', autospec=True) m().errorString.return_value = "Error string" for name in ['UnknownSocketError', 'UnconnectedState', 'ConnectionRefusedError', 'ServerNotFoundError', 'PeerClosedError']: setattr(m, name, getattr(QLocalSocket, name)) return m @pytest.mark.linux(reason="Flaky on Windows and macOS") def test_normal_connection(self, caplog, qtbot, args): ret_server = ipc.send_or_listen(args) assert isinstance(ret_server, ipc.IPCServer) assert "Starting IPC server..." in caplog.messages assert ret_server is ipc.server with qtbot.waitSignal(ret_server.got_args): ret_client = ipc.send_or_listen(args) assert ret_client is None @pytest.mark.posix(reason="Unneeded on Windows") def test_correct_socket_name(self, args): server = ipc.send_or_listen(args) expected_dir = ipc._get_socketname(args.basedir) assert '/' in expected_dir assert server._socketname == expected_dir def test_address_in_use_ok(self, qlocalserver_mock, qlocalsocket_mock, stubs, caplog, args): """Test the following scenario. - First call to send_to_running_instance: -> could not connect (server not found) - Trying to set up a server and listen -> AddressInUseError - Second call to send_to_running_instance: -> success """ qlocalserver_mock().listen.return_value = False err = QAbstractSocket.AddressInUseError qlocalserver_mock().serverError.return_value = err qlocalsocket_mock().waitForConnected.side_effect = [False, True] qlocalsocket_mock().error.side_effect = [ QLocalSocket.ServerNotFoundError, QLocalSocket.UnknownSocketError, QLocalSocket.UnknownSocketError, # error() gets called twice ] ret = ipc.send_or_listen(args) assert ret is None assert "Got AddressInUseError, trying again." in caplog.messages @pytest.mark.parametrize('has_error, exc_name, exc_msg', [ (True, 'SocketError', 'Error while writing to running instance: Error string (error 0)'), (False, 'AddressInUseError', 'Error while listening to IPC server: Error string (error 8)'), ]) def test_address_in_use_error(self, qlocalserver_mock, qlocalsocket_mock, stubs, caplog, args, has_error, exc_name, exc_msg): """Test the following scenario. - First call to send_to_running_instance: -> could not connect (server not found) - Trying to set up a server and listen -> AddressInUseError - Second call to send_to_running_instance: -> not sent / error """ qlocalserver_mock().listen.return_value = False err = QAbstractSocket.AddressInUseError qlocalserver_mock().serverError.return_value = err # If the second connection succeeds, we will have an error later. # If it fails, that's the "not sent" case above. qlocalsocket_mock().waitForConnected.side_effect = [False, has_error] qlocalsocket_mock().error.side_effect = [ QLocalSocket.ServerNotFoundError, QLocalSocket.ServerNotFoundError, QLocalSocket.ConnectionRefusedError, QLocalSocket.ConnectionRefusedError, # error() gets called twice ] with caplog.at_level(logging.ERROR): with pytest.raises(ipc.Error): ipc.send_or_listen(args) error_msgs = [ 'Handling fatal misc.ipc.{} with --no-err-windows!'.format( exc_name), '', 'title: Error while connecting to running instance!', 'pre_text: ', 'post_text: ', 'exception text: {}'.format(exc_msg), ] assert caplog.messages == ['\n'.join(error_msgs)] @pytest.mark.posix(reason="Flaky on Windows") def test_error_while_listening(self, qlocalserver_mock, caplog, args): """Test an error with the first listen call.""" qlocalserver_mock().listen.return_value = False err = QAbstractSocket.SocketResourceError qlocalserver_mock().serverError.return_value = err with caplog.at_level(logging.ERROR): with pytest.raises(ipc.Error): ipc.send_or_listen(args) error_msgs = [ 'Handling fatal misc.ipc.ListenError with --no-err-windows!', '', 'title: Error while connecting to running instance!', 'pre_text: ', 'post_text: ', ('exception text: Error while listening to IPC server: Error ' 'string (error 4)'), ] assert caplog.messages[-1] == '\n'.join(error_msgs) @pytest.mark.windows @pytest.mark.mac def test_long_username(monkeypatch): """See https://github.com/qutebrowser/qutebrowser/issues/888.""" username = 'alexandercogneau' basedir = '/this_is_a_long_basedir' monkeypatch.setattr(getpass, 'getuser', lambda: username) name = ipc._get_socketname(basedir=basedir) server = ipc.IPCServer(name) expected_md5 = md5('{}-{}'.format(username, basedir)) assert expected_md5 in server._socketname try: server.listen() finally: server.shutdown() def test_connect_inexistent(qlocalsocket): """Make sure connecting to an inexistent server fails immediately. If this test fails, our connection logic checking for the old naming scheme would not work properly. """ qlocalsocket.connectToServer('qute-test-inexistent') assert qlocalsocket.error() == QLocalSocket.ServerNotFoundError @pytest.mark.posix def test_socket_options_address_in_use_problem(qlocalserver, short_tmpdir): """Qt seems to ignore AddressInUseError when using socketOptions. With this test we verify this bug still exists. If it fails, we can probably start using setSocketOptions again. """ servername = str(short_tmpdir / 'x') s1 = QLocalServer() ok = s1.listen(servername) assert ok s2 = QLocalServer() s2.setSocketOptions(QLocalServer.UserAccessOption) ok = s2.listen(servername) print(s2.errorString()) # We actually would expect ok == False here - but we want the test to fail # when the Qt bug is fixed. assert ok
fiete201/qutebrowser
tests/unit/misc/test_ipc.py
Python
gpl-3.0
28,342
package es.udc.tfg_es.clubtriatlon.utils.dao; /* BSD License */ import java.io.Serializable; import es.udc.tfg_es.clubtriatlon.utils.exceptions.InstanceNotFoundException; public interface GenericDao <E, PK extends Serializable>{ void save(E entity); E find(PK id) throws InstanceNotFoundException; boolean exists(PK id); void remove(PK id) throws InstanceNotFoundException; }
Al-Mikitinskis/ClubTriatlon
src/main/java/es/udc/tfg_es/clubtriatlon/utils/dao/GenericDao.java
Java
gpl-3.0
388
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace ConsoleTutorial1 { class Program { static void Main(string[] args) { Console.ForegroundColor = ConsoleColor.Green; Console.WriteLine("Hello"); Console.ForegroundColor = ConsoleColor.DarkYellow; Console.WriteLine("World"); Console.Read(); } } }
Easelm/ProgrammingNomEntertainment
Tutorials/C# Console Tutorials/ConsoleTutorial1/ConsoleTutorial1/Program.cs
C#
gpl-3.0
472
// // MusicDetailCell.h // 子曰 // // Created by Martell on 15/11/28. // Copyright © 2015年 Martell. All rights reserved. // #import <UIKit/UIKit.h> #import "MImageView.h" #import "DownloadMusicNetManager.h" @protocol MusicDetailCellDelegate <NSObject> - (void)tellmeProgress:(CGFloat)progress withCellTag:(NSInteger)tag; @end @interface MusicDetailCell : UITableViewCell <DownloadMusicNetManagerDelegate> /** 音乐封面图 */ @property (nonatomic, strong) MImageView *coverIV; /** 题目标签 */ @property (nonatomic, strong) UILabel *titleLb; /** 添加时间标签 */ @property (nonatomic, strong) UILabel *timeLb; /** 音乐来源标签 */ @property (nonatomic, strong) UILabel *sourceLb; /** 播放次数标签 */ @property (nonatomic, strong) UILabel *playCountLb; /** 喜欢次数标签 */ @property (nonatomic, strong) UILabel *favorCountLb; /** 评论次数 */ @property (nonatomic, strong) UILabel *commentCountLb; /** 时长标签 */ @property (nonatomic, strong) UILabel *durationLb; /** 下载按钮 */ @property (nonatomic, strong) UIButton *downloadBtn; /** 专辑名 */ @property (nonatomic, strong) NSString *album; /** 下载某行音频 */ - (void)downLoadMusicURL:(NSURL *)url; /** 开始下载某行音频图片 */ //- (void)downLoadMusicImage:(NSURL *)url; @property (nonatomic,strong) DownloadMusicNetManager *dlmNetManager; - (void)downloadPause; - (void)downloadResume; @property (nonatomic,assign) NSInteger startOrFinish; @property (nonatomic, assign) id<MusicDetailCellDelegate> delegate; @end
Martell1994/ConfusionSaying
子曰/子曰/View/Music/MusicDetailCell.h
C
gpl-3.0
1,538
/***************************************************************************** The Dark Mod GPL Source Code This file is part of the The Dark Mod Source Code, originally based on the Doom 3 GPL Source Code as published in 2011. The Dark Mod Source Code 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. For details, see LICENSE.TXT. Project: The Dark Mod (http://www.thedarkmod.com/) $Revision: 5935 $ (Revision of last commit) $Date: 2014-02-15 19:19:00 +0000 (Sat, 15 Feb 2014) $ (Date of last commit) $Author: grayman $ (Author of last commit) ******************************************************************************/ #include "precompiled_game.h" #pragma hdrstop static bool versioned = RegisterVersionedFile("$Id: PathWaitForTriggerTask.cpp 5935 2014-02-15 19:19:00Z grayman $"); #include "../Memory.h" #include "PathWaitForTriggerTask.h" #include "../Library.h" namespace ai { PathWaitForTriggerTask::PathWaitForTriggerTask() : PathTask() {} PathWaitForTriggerTask::PathWaitForTriggerTask(idPathCorner* path) : PathTask(path) { _path = path; } // Get the name of this task const idStr& PathWaitForTriggerTask::GetName() const { static idStr _name(TASK_PATH_WAIT_FOR_TRIGGER); return _name; } void PathWaitForTriggerTask::Init(idAI* owner, Subsystem& subsystem) { PathTask::Init(owner, subsystem); owner->AI_ACTIVATED = false; } bool PathWaitForTriggerTask::Perform(Subsystem& subsystem) { DM_LOG(LC_AI, LT_INFO)LOGSTRING("Path WaitForTrigger Task performing.\r"); //idPathCorner* path = _path.GetEntity(); idAI* owner = _owner.GetEntity(); // This task may not be performed with empty entity pointers assert( owner != NULL ); if (owner->AI_ACTIVATED) { owner->AI_ACTIVATED = false; // Trigger path targets, now that the owner has been activated // grayman #3670 - this activates owner targets, not path targets owner->ActivateTargets(owner); // NextPath(); // Move is done, fall back to PatrolTask DM_LOG(LC_AI, LT_INFO)LOGSTRING("Waiting for trigger is done.\r"); return true; // finish this task } return false; } PathWaitForTriggerTaskPtr PathWaitForTriggerTask::CreateInstance() { return PathWaitForTriggerTaskPtr(new PathWaitForTriggerTask); } // Register this task with the TaskLibrary TaskLibrary::Registrar pathWaitForTriggerTaskRegistrar( TASK_PATH_WAIT_FOR_TRIGGER, // Task Name TaskLibrary::CreateInstanceFunc(&PathWaitForTriggerTask::CreateInstance) // Instance creation callback ); } // namespace ai
Extant-1/ThieVR
game/ai/Tasks/PathWaitForTriggerTask.cpp
C++
gpl-3.0
2,703
/* * Copyright (C) 2008-2009 Daniel Prevost <dprevost@photonsoftware.org> * * This file is part of Photon (photonsoftware.org). * * This file may be distributed and/or modified under the terms of the * GNU General Public License version 2 or version 3 as published by the * Free Software Foundation and appearing in the file COPYING.GPL2 and * COPYING.GPL3 included in the packaging of this software. * * Licensees holding a valid Photon Commercial license can use this file * in accordance with the terms of their license. * * This software 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. */ using System; using System.Collections.Generic; using System.Text; using System.Runtime.InteropServices; namespace Photon { public partial class Lifo { // --+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+-- // Track whether Dispose has been called. private bool disposed = false; private IntPtr handle; private IntPtr sessionHandle; // --+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+-- [DllImport("photon.dll", CallingConvention = CallingConvention.Cdecl)] private static extern int psoLifoClose(IntPtr objectHandle); [DllImport("photon.dll", CallingConvention = CallingConvention.Cdecl)] private static extern int psoLifoDefinition( IntPtr objectHandle, ref ObjectDefinition definition); [DllImport("photon.dll", CallingConvention = CallingConvention.Cdecl)] private static extern int psoLifoGetFirst( IntPtr objectHandle, byte[] buffer, UInt32 bufferLength, ref UInt32 returnedLength); [DllImport("photon.dll", CallingConvention = CallingConvention.Cdecl)] private static extern int psoLifoGetNext( IntPtr objectHandle, byte[] buffer, UInt32 bufferLength, ref UInt32 returnedLength); [DllImport("photon.dll", CallingConvention = CallingConvention.Cdecl)] private static extern int psoLifoOpen( IntPtr sessionHandle, string queueName, UInt32 nameLengthInBytes, ref IntPtr objectHandle); [DllImport("photon.dll", CallingConvention = CallingConvention.Cdecl)] private static extern int psoLifoPop( IntPtr objectHandle, byte[] buffer, UInt32 bufferLength, ref UInt32 returnedLength); [DllImport("photon.dll", CallingConvention = CallingConvention.Cdecl)] private static extern int psoLifoPush( IntPtr objectHandle, byte[] pItem, UInt32 length); [DllImport("photon.dll", CallingConvention = CallingConvention.Cdecl)] private static extern int psoLifoStatus( IntPtr objectHandle, ref ObjStatus pStatus); // --+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+-- private void Dispose(bool disposing) { // Check to see if Dispose has already been called. if (!this.disposed) { psoLifoClose(handle); } disposed = true; } // --+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+-- ~Lifo() { Dispose(false); } // --+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+-- } }
dprevost/photon
src/CS/PhotonLib/PrivateLifo.cs
C#
gpl-3.0
3,740
INSERT INTO PARAMETERS (ID,NAME,SORT,VALUE) VALUES (1,'realVehicleName',0,'RV37'); INSERT INTO PARAMETERS (ID,NAME,SORT,VALUE) VALUES (2,'masterServerURI',0,'http://localhost:8371'); INSERT INTO PARAMETERS (ID,NAME,SORT,VALUE) VALUES (3,'useInternalRosCore',0,'true'); INSERT INTO DEVICES (ID,CONFIGURATION,TOPIC_ROOT,TYPE_ID) VALUES (1,'origin=(47.822345;13.041134;0) maxVelocity=20 maxAcceleration=5 precision=10 updateCycle=100 idlePower=20 hoverPower=55 mass=2.2 takeOffHeight=10 takeOffVelocity=2 takeOffAcceleration=2 landingVelocity=1.5 landingAcceleration=2','/rv37',4); INSERT INTO MAPPING_ATTRIBUTES (CONNECTED_TO_AUTOPILOT,VV_VISIBLE,TOPIC_ID,DEVICE_ID,SENSORDEFINITION_ID) VALUES (1,1,6,1,null); INSERT INTO MAPPING_ATTRIBUTES (CONNECTED_TO_AUTOPILOT,VV_VISIBLE,TOPIC_ID,DEVICE_ID,SENSORDEFINITION_ID) VALUES (1,1,5,1,9); INSERT INTO MAPPING_ATTRIBUTES (CONNECTED_TO_AUTOPILOT,VV_VISIBLE,TOPIC_ID,DEVICE_ID,SENSORDEFINITION_ID) VALUES (1,1,7,1,1);
cksystemsgroup/cpcc
cpcc-demo/src/main/resources/setups/rect-050m-by-050m-08x08/db-setup-RV37-rv.sql
SQL
gpl-3.0
961
package io.github.davidm98.crescent.detection.checks.inventory.inventorytweaks; import org.bukkit.entity.Player; import org.bukkit.event.Event; import org.bukkit.event.inventory.InventoryClickEvent; import io.github.davidm98.crescent.detection.checks.Check; import io.github.davidm98.crescent.detection.checks.CheckVersion; public class InventoryTweaksA extends CheckVersion { public InventoryTweaksA(Check check) { super(check, "A", "Check if the player is performing impossible actions whilst moving."); } @Override public void call(Event event) { if (event instanceof InventoryClickEvent) { // The player has clicked. final Player player = profile.getPlayer(); if (player.isSprinting() || player.isSneaking() || player.isBlocking() || player.isSleeping() || player.isConversing()) { // The player has clicked in their inventory impossibly. callback(true); } } } }
awesome90/Crescent
src/io/github/davidm98/crescent/detection/checks/inventory/inventorytweaks/InventoryTweaksA.java
Java
gpl-3.0
942
/* * Copyright (c) 2007-2013 Nicira, Inc. * * This program is free software; you can redistribute it and/or * modify it under the terms of version 2 of the GNU General Public * License as published by the Free Software Foundation. * * This program is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * 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 */ #include <linux/version.h> #include <linux/module.h> #include <linux/if.h> #include <linux/if_tunnel.h> #include <linux/if_vlan.h> #include <linux/icmp.h> #include <linux/in.h> #include <linux/ip.h> #include <linux/ipv6.h> #include <linux/kernel.h> #include <linux/kmod.h> #include <linux/netdevice.h> #include <linux/skbuff.h> #include <linux/spinlock.h> #include <net/gre.h> #include <net/icmp.h> #include <net/mpls.h> #include <net/protocol.h> #include <net/route.h> #include <net/xfrm.h> #include "gso.h" #ifdef OVS_USE_COMPAT_GSO_SEGMENTATION /* Strictly this is not needed and will be optimised out * as this code is guarded by if LINUX_VERSION_CODE < KERNEL_VERSION(3,19,0). * It is here to make things explicit should the compatibility * code be extended in some way prior extending its life-span * beyond v3.19. */ static bool supports_mpls_gso(void) { /* MPLS GSO was introduced in v3.11, however it was not correctly * activated using mpls_features until v3.19. */ #ifdef OVS_USE_COMPAT_GSO_SEGMENTATION return true; #else return false; #endif } int rpl_dev_queue_xmit(struct sk_buff *skb) { #undef dev_queue_xmit int err = -ENOMEM; bool mpls; mpls = false; /* Avoid traversing any VLAN tags that are present to determine if * the ethtype is MPLS. Instead compare the mac_len (end of L2) and * skb_network_offset() (beginning of L3) whose inequality will * indicate the presence of an MPLS label stack. */ if (skb->mac_len != skb_network_offset(skb) && !supports_mpls_gso()) mpls = true; if (mpls) { int features; features = netif_skb_features(skb); /* As of v3.11 the kernel provides an mpls_features field in * struct net_device which allows devices to advertise which * features its supports for MPLS. This value defaults to * NETIF_F_SG and as of v3.19. * * This compatibility code is intended for kernels older * than v3.19 that do not support MPLS GSO and do not * use mpls_features. Thus this code uses NETIF_F_SG * directly in place of mpls_features. */ if (mpls) features &= NETIF_F_SG; if (netif_needs_gso(skb, features)) { struct sk_buff *nskb; nskb = skb_gso_segment(skb, features); if (!nskb) { if (unlikely(skb_cloned(skb) && pskb_expand_head(skb, 0, 0, GFP_ATOMIC))) goto drop; skb_shinfo(skb)->gso_type &= ~SKB_GSO_DODGY; goto xmit; } if (IS_ERR(nskb)) { err = PTR_ERR(nskb); goto drop; } consume_skb(skb); skb = nskb; do { nskb = skb->next; skb->next = NULL; err = dev_queue_xmit(skb); skb = nskb; } while (skb); return err; } } xmit: return dev_queue_xmit(skb); drop: kfree_skb(skb); return err; } EXPORT_SYMBOL_GPL(rpl_dev_queue_xmit); #endif /* OVS_USE_COMPAT_GSO_SEGMENTATION */ #ifndef USE_UPSTREAM_TUNNEL_GSO static __be16 __skb_network_protocol(struct sk_buff *skb) { __be16 type = skb->protocol; int vlan_depth = ETH_HLEN; while (type == htons(ETH_P_8021Q) || type == htons(ETH_P_8021AD)) { struct vlan_hdr *vh; if (unlikely(!pskb_may_pull(skb, vlan_depth + VLAN_HLEN))) return 0; vh = (struct vlan_hdr *)(skb->data + vlan_depth); type = vh->h_vlan_encapsulated_proto; vlan_depth += VLAN_HLEN; } if (eth_p_mpls(type)) type = ovs_skb_get_inner_protocol(skb); return type; } static struct sk_buff *tnl_skb_gso_segment(struct sk_buff *skb, netdev_features_t features, bool tx_path, sa_family_t sa_family) { void *iph = skb_network_header(skb); int pkt_hlen = skb_inner_network_offset(skb); /* inner l2 + tunnel hdr. */ int mac_offset = skb_inner_mac_offset(skb); int outer_l3_offset = skb_network_offset(skb); int outer_l4_offset = skb_transport_offset(skb); struct sk_buff *skb1 = skb; struct dst_entry *dst = skb_dst(skb); struct sk_buff *segs; __be16 proto = skb->protocol; char cb[sizeof(skb->cb)]; BUILD_BUG_ON(sizeof(struct ovs_gso_cb) > FIELD_SIZEOF(struct sk_buff, cb)); OVS_GSO_CB(skb)->ipv6 = (sa_family == AF_INET6); /* setup whole inner packet to get protocol. */ __skb_pull(skb, mac_offset); skb->protocol = __skb_network_protocol(skb); /* setup l3 packet to gso, to get around segmentation bug on older kernel.*/ __skb_pull(skb, (pkt_hlen - mac_offset)); skb_reset_mac_header(skb); skb_reset_network_header(skb); skb_reset_transport_header(skb); /* From 3.9 kernel skb->cb is used by skb gso. Therefore * make copy of it to restore it back. */ memcpy(cb, skb->cb, sizeof(cb)); /* We are handling offloads by segmenting l3 packet, so * no need to call OVS compat segmentation function. */ #ifdef HAVE___SKB_GSO_SEGMENT #undef __skb_gso_segment segs = __skb_gso_segment(skb, 0, tx_path); #else #undef skb_gso_segment segs = skb_gso_segment(skb, 0); #endif if (!segs || IS_ERR(segs)) goto free; skb = segs; while (skb) { __skb_push(skb, pkt_hlen); skb_reset_mac_header(skb); skb_set_network_header(skb, outer_l3_offset); skb_set_transport_header(skb, outer_l4_offset); skb->mac_len = 0; memcpy(skb_network_header(skb), iph, pkt_hlen); memcpy(skb->cb, cb, sizeof(cb)); skb->protocol = proto; if (skb->next) dst = dst_clone(dst); skb_dst_set(skb, dst); OVS_GSO_CB(skb)->fix_segment(skb); skb = skb->next; } free: consume_skb(skb1); return segs; } static int output_ip(struct sk_buff *skb) { memset(IPCB(skb), 0, sizeof(*IPCB(skb))); #undef ip_local_out return ip_local_out(skb); } int rpl_ip_local_out(struct net *net, struct sock *sk, struct sk_buff *skb) { if (!OVS_GSO_CB(skb)->fix_segment) return output_ip(skb); /* This bit set can confuse some drivers on old kernel. */ skb->encapsulation = 0; if (skb_is_gso(skb)) { int ret; int id; skb = tnl_skb_gso_segment(skb, 0, false, AF_INET); if (!skb || IS_ERR(skb)) return NET_XMIT_DROP; id = ntohs(ip_hdr(skb)->id); do { struct sk_buff *next_skb = skb->next; skb->next = NULL; ip_hdr(skb)->id = htons(id++); ret = output_ip(skb); skb = next_skb; } while (skb); return ret; } else if (skb->ip_summed == CHECKSUM_PARTIAL) { int err; err = skb_checksum_help(skb); if (unlikely(err)) return NET_XMIT_DROP; } return output_ip(skb); } EXPORT_SYMBOL_GPL(rpl_ip_local_out); static int output_ipv6(struct sk_buff *skb) { memset(IP6CB(skb), 0, sizeof (*IP6CB(skb))); #undef ip6_local_out return ip6_local_out(skb); } int rpl_ip6_local_out(struct net *net, struct sock *sk, struct sk_buff *skb) { if (!OVS_GSO_CB(skb)->fix_segment) return output_ipv6(skb); /* This bit set can confuse some drivers on old kernel. */ skb->encapsulation = 0; if (skb_is_gso(skb)) { int ret; skb = tnl_skb_gso_segment(skb, 0, false, AF_INET6); if (!skb || IS_ERR(skb)) return NET_XMIT_DROP; do { struct sk_buff *next_skb = skb->next; skb->next = NULL; ret = output_ipv6(skb); skb = next_skb; } while (skb); return ret; } else if (skb->ip_summed == CHECKSUM_PARTIAL) { int err; err = skb_checksum_help(skb); if (unlikely(err)) return NET_XMIT_DROP; } return output_ipv6(skb); } EXPORT_SYMBOL_GPL(rpl_ip6_local_out); #endif /* USE_UPSTREAM_TUNNEL_GSO */
ejschiller/FLEX
ovs/datapath/linux/compat/gso.c
C
gpl-3.0
7,839
//------------------------------------------------------------------------------ // // Module 08939 : Advanced Graphics // Bicubic B-Spline Assessment // Curve1D.cpp // //------------------------------------------------------------------------------ //------------------------------------------------------------------------------ // include files #include <iostream> #include <string> #include <fstream> #include <GL/glut.h> #pragma hdrstop #include "Curve1D.h" #include "Curve.h" #include "Constants.h" //------------------------------------------------------------------------------ // namespace using namespace std; using namespace ComputerGraphics; //------------------------------------------------------------------------------ // constructor Curve1D::Curve1D() : _position(0) { } //------------------------------------------------------------------------------ // render data points void Curve1D::render(bool markers, bool animation) { glDisable(GL_LIGHTING); glDisable(GL_DEPTH_TEST); const double BORDER = 0.2; int width = glutGet(GLUT_WINDOW_WIDTH); int height = glutGet(GLUT_WINDOW_HEIGHT); int point; glViewport(0, 0, width, height); glBegin(GL_LINES); glColor3d(0.5, 0.5, 0.5); glVertex2d(-1.0 + BORDER * 2.0, -1.0); glVertex2d(-1.0 + BORDER * 2.0, 1.0); glVertex2d(-1.0, -1.0 + BORDER * 2.0); glVertex2d(1.0, -1.0 + BORDER * 2.0); glEnd(); // main window glViewport(BORDER * width, BORDER * height, (1.0 - BORDER) * width, (1.0 - BORDER) * height); glColor3d(0.0, 0.0, 0.0); glRasterPos2d(-1.0, -1.0); glutBitmapCharacter(GLUT_BITMAP_8_BY_13, '('); glutBitmapCharacter(GLUT_BITMAP_8_BY_13, 'Y'); glutBitmapCharacter(GLUT_BITMAP_8_BY_13, ')'); glutBitmapCharacter(GLUT_BITMAP_8_BY_13, '('); glutBitmapCharacter(GLUT_BITMAP_8_BY_13, 'T'); glutBitmapCharacter(GLUT_BITMAP_8_BY_13, ')'); glLineWidth(LINE_WIDTH); glDisable(GL_LINE_SMOOTH); glBegin(GL_LINE_STRIP); glColor3d(0.0, 0.0, 1.0); for (point = 0; point <= RESOLUTION; point++) { double tPoint = t(0) + (double)point / (double)RESOLUTION * (t(n() - 1) - t(0)); glVertex2d(tPoint, x().vertex(tPoint)); } glEnd(); if (markers) { glPointSize(POINT_SIZE); glEnable(GL_POINT_SMOOTH); glBegin(GL_POINTS); glColor3d(0.0, 0.0, 1.0); for (point = 0; point < n(); point++) { glVertex2d(x().t(point), x().f(point)); } glColor3d(1.0, 0.0, 0.0); glVertex2d(x().t(x().i()), x().f(x().i())); glEnd(); } if (animation) { glPointSize(POINT_SIZE); glEnable(GL_POINT_SMOOTH); glBegin(GL_POINTS); glColor3d(1.0, 0.0, 1.0); double tPoint = t(0) + (double)_position / (double)RESOLUTION * (t(n() - 1) - t(0)); glVertex2d(tPoint, x().vertex(tPoint)); _position = (_position + 1) % RESOLUTION; glEnd(); } else { _position = 0; } // y window glViewport(0, BORDER * height, BORDER * width, (1.0 - BORDER) * height); glColor3d(0.0, 0.0, 0.0); glRasterPos2d(-1.0, -1.0); glutBitmapCharacter(GLUT_BITMAP_8_BY_13, 'Y'); glutBitmapCharacter(GLUT_BITMAP_8_BY_13, '('); glutBitmapCharacter(GLUT_BITMAP_8_BY_13, 'T'); glutBitmapCharacter(GLUT_BITMAP_8_BY_13, ')'); x().render(markers); } //------------------------------------------------------------------------------ // get x const Curve &Curve1D::x() const { return _x; } //------------------------------------------------------------------------------ // read data points void Curve1D::read(const string &filename) { ifstream in(filename.c_str()); if (!in.good()) { throw string("Error : Invalid file name = " + filename); } clear(); int n; in >> n; for (int i = 0; i < n; i++) { double x; in >> x; add(x); } } //------------------------------------------------------------------------------ // write data points void Curve1D::write(const string &filename) const { ofstream out(filename.c_str()); if (!out.good()) { throw string("Error : Invalid file name = " + filename); } out << n() << endl; for (int i = 0; i < n(); i++) { out << _x.f(i) << endl; } } //------------------------------------------------------------------------------ // add data point void Curve1D::add(double x) { _x.add(x); } //------------------------------------------------------------------------------ // modify data point void Curve1D::modify(double x) { _x.modify(x); } //------------------------------------------------------------------------------ // insert data point void Curve1D::insert() { _x.insert(); } //------------------------------------------------------------------------------ // remove data point void Curve1D::remove() { _x.remove(); } //------------------------------------------------------------------------------ // clear arrays void Curve1D::clear() { _x.clear(); } //------------------------------------------------------------------------------ // next data point void Curve1D::next() { _x.next(); } //------------------------------------------------------------------------------ // previous data point void Curve1D::previous() { _x.previous(); } //------------------------------------------------------------------------------ // first data point void Curve1D::first() { _x.first(); } //------------------------------------------------------------------------------ // last data point void Curve1D::last() { _x.last(); } //------------------------------------------------------------------------------ // get index of data point int Curve1D::i() const { return x().i(); } //------------------------------------------------------------------------------ // get number of data points int Curve1D::n() const { return x().n(); } //------------------------------------------------------------------------------ // get data point parameter double Curve1D::t(int m) const { return x().t(m); } //------------------------------------------------------------------------------
sihart25/BicubicBSpline
Source/Curve1D.cpp
C++
gpl-3.0
6,272
/* Copyright (C) 2013-2017 Rafael Guglielmetti, rafael.guglielmetti@unifr.ch */ /* This file is part of CoxIter and AlVin. CoxIter 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. CoxIter 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 CoxIter. If not, see <http://www.gnu.org/licenses/>. */ /*! * \file polynomials.h * \author Rafael Guglielmetti * * \brief Some mathematical functions regarding polynomials */ #ifndef __POLYNOMIALS_H__ #define __POLYNOMIALS_H__ #include <cmath> #include <iostream> #include <iterator> #include <map> #include <string> #include <vector> #ifdef _USE_LOCAL_GMP_ #include "gmpxx.h" #else #include <gmpxx.h> #endif using namespace std; namespace Polynomials { /*! \fn polynomialDisplay * \brief Display a polynomial * \param polynomial(const vector< int >& polynomial) Integer */ template <typename Type> void polynomialDisplay(const vector<Type> &polynomial) { bool isFirst(true); unsigned int iSize(polynomial.size()); for (unsigned int i(0); i < iSize; i++) { if (polynomial[i] != 0) { if (isFirst) { cout << polynomial[i] << (i ? " * x" + string(i > 1 ? "^" + to_string(i) : "") : ""); isFirst = false; } else { if ((polynomial[i] != 1 && polynomial[i] != -1) || !i) cout << (polynomial[i] > 0 ? " + " : " - ") << abs(polynomial[i]) << (i ? " * x" + string(i > 1 ? "^" + to_string(i) : "") : ""); else cout << (polynomial[i] > 0 ? " + " : " - ") << "x" + string(i > 1 ? "^" + to_string(i) : ""); } } } } /*! \fn symbolDisplay * \brief Display a symbol * \param symbol(const vector< int >& symbol) Integer */ template <typename Type> void symbolDisplay(const vector<Type> &symbol) { bool isFirst(true); unsigned int iSize(symbol.size()); cout << "["; for (unsigned int i(0); i < iSize; i++) { if (symbol[i]) { for (unsigned int j(0); j < symbol[i]; j++) { cout << (isFirst ? "" : ",") << i; isFirst = false; } } } cout << "]"; } /*! \fn polynomialDotSymbol * \brief Multiply a polynomial by a symbol * \param polynomial(const vector< Type >& polynomial) The polynomial * \param symbol(const unsigned int&) The symbol */ template <typename Type> void polynomialDotSymbol(vector<Type> &polynomial, const unsigned int &symbol) { vector<Type> polynomialBackup(polynomial); unsigned int polynomialDegree(polynomial.size() - 1); for (unsigned int i(1); i < symbol - 1; i++) polynomial.push_back(0); polynomial.push_back(polynomial[polynomialDegree]); if (polynomialDegree < symbol) { for (unsigned int i(1); i <= polynomialDegree; i++) polynomial[i] = polynomial[i - 1] + polynomialBackup[i]; fill(polynomial.begin() + polynomialDegree + 1, polynomial.end() - polynomialDegree, polynomial[polynomialDegree]); for (unsigned int i(1); i <= polynomialDegree; i++) // TODO: gérer degré plus petit que symbole polynomial[polynomialDegree + symbol - i - 1] = polynomial[polynomialDegree + symbol - i] + polynomialBackup[polynomialDegree - i]; } else { for (unsigned int i(1); i < symbol; i++) polynomial[i] = polynomial[i - 1] + polynomialBackup[i]; for (unsigned int i(symbol); i < polynomialDegree; i++) polynomial[i] = polynomial[i - 1] - polynomialBackup[i - symbol] + polynomialBackup[i]; for (unsigned int i(1); i < symbol && i <= polynomialDegree; i++) polynomial[polynomialDegree + symbol - i - 1] = polynomial[polynomialDegree + symbol - i] + polynomialBackup[polynomialDegree - i]; } } template <typename Type> bool dividePolynomialBySymbol(vector<Type> &polynomial, const unsigned int &symbol) { unsigned int polynomialDegree(polynomial.size() - 1); // Removing eventual 0 while (polynomial[polynomialDegree] == 0) polynomialDegree--; vector<Type> iWorking(polynomial.begin(), polynomial.begin() + polynomialDegree + 1); vector<Type> quotient; unsigned int i; Type temp; if (polynomialDegree < symbol - 1) return false; while (polynomialDegree >= symbol) { temp = iWorking[polynomialDegree]; quotient.insert(quotient.begin(), temp); for (i = 0; i < symbol; i++) iWorking[polynomialDegree - i] -= temp; polynomialDegree--; while (iWorking[polynomialDegree] == 0 && polynomialDegree >= 1) { quotient.insert(quotient.begin(), 0); polynomialDegree--; } } if (polynomialDegree < symbol - 1) { for (i = 0; i <= polynomialDegree; i++) { if (iWorking[i] != 0) return false; } } temp = iWorking[polynomialDegree]; quotient.insert(quotient.begin(), temp); for (i = 0; i < polynomialDegree; i++) { if (iWorking[i] != temp) return false; } polynomial = quotient; return true; } /*! \fn dividePolynomialByPolynomial * \brief Try to make a division * * \param numerator(vector< Type >&) The dividend ; updated if the * remainder is 0 \param denominator(const vector< Type >) The divisor \return * bool: True if numerator is divisible by denominator. In this case, * numerator is updated to the quotient */ template <typename Type> bool dividePolynomialByPolynomial(vector<Type> &numerator, const vector<Type> &denominator) { unsigned int numDeg(numerator.size() - 1), denomDeg(denominator.size() - 1); if (numDeg < denomDeg || (denomDeg == 0 && denominator[0] != 0)) return false; vector<Type> working(numerator), quotient; unsigned int i; Type temp; while (numDeg >= denomDeg) { if (working[numDeg] % denominator[denomDeg] != 0) return false; temp = working[numDeg] / denominator[denomDeg]; quotient.insert(quotient.begin(), temp); for (i = 0; i <= denomDeg; i++) working[numDeg - i] -= temp * denominator[denomDeg - i]; numDeg--; while (working[numDeg] == 0 && numDeg >= 1 && numDeg >= denomDeg) { quotient.insert(quotient.begin(), 0); numDeg--; } } for (i = 0; i <= numDeg; i++) { if (working[i] != 0) return false; } numerator = quotient; return true; } extern vector<vector<mpz_class>> cyclotomicPolynomials; ///< List of some cyclotomic polynomials (we want to ///< be able to multiply/divide with the growth ///< series so we use here BigInteger instead of ///< int) } // namespace Polynomials #endif
rgugliel/CoxIter
lib/polynomials.h
C
gpl-3.0
7,047
<!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_45) on Fri Jun 14 04:56:05 BST 2013 --> <TITLE> A-Index </TITLE> <META NAME="date" CONTENT="2013-06-14"> <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="A-Index"; } } </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"> <FONT CLASS="NavBarFont1">Package</FONT>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <FONT CLASS="NavBarFont1">Class</FONT>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <FONT CLASS="NavBarFont1">Use</FONT>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../overview-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="#FFFFFF" CLASS="NavBarCell1Rev"> &nbsp;<FONT CLASS="NavBarFont1Rev"><B>Index</B></FONT>&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;PREV LETTER&nbsp; &nbsp;<A HREF="index-2.html"><B>NEXT LETTER</B></A></FONT></TD> <TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2"> <A HREF="../index.html?index-filesindex-1.html" target="_top"><B>FRAMES</B></A> &nbsp; &nbsp;<A HREF="index-1.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> </TABLE> <A NAME="skip-navbar_top"></A> <!-- ========= END OF TOP NAVBAR ========= --> <A HREF="index-1.html">A</A> <A HREF="index-2.html">B</A> <A HREF="index-3.html">C</A> <A HREF="index-4.html">D</A> <A HREF="index-5.html">E</A> <A HREF="index-6.html">F</A> <A HREF="index-7.html">G</A> <A HREF="index-8.html">H</A> <A HREF="index-9.html">I</A> <A HREF="index-10.html">J</A> <A HREF="index-11.html">L</A> <A HREF="index-12.html">M</A> <A HREF="index-13.html">N</A> <A HREF="index-14.html">O</A> <A HREF="index-15.html">P</A> <A HREF="index-16.html">R</A> <A HREF="index-17.html">S</A> <A HREF="index-18.html">T</A> <A HREF="index-19.html">U</A> <A HREF="index-20.html">V</A> <A HREF="index-21.html">W</A> <HR> <A NAME="_A_"><!-- --></A><H2> <B>A</B></H2> <DL> <DT><A HREF="../net/metarelate/terminology/webedit/ViewPage.html#abandonCommand()"><B>abandonCommand()</B></A> - Method in class net.metarelate.terminology.webedit.<A HREF="../net/metarelate/terminology/webedit/ViewPage.html" title="class in net.metarelate.terminology.webedit">ViewPage</A> <DD>&nbsp; <DT><A HREF="../net/metarelate/terminology/webedit/AbstractEditPage.html" title="class in net.metarelate.terminology.webedit"><B>AbstractEditPage</B></A> - Class in <A HREF="../net/metarelate/terminology/webedit/package-summary.html">net.metarelate.terminology.webedit</A><DD>Common behaviour to edit and new operations.<DT><A HREF="../net/metarelate/terminology/webedit/AbstractEditPage.html#AbstractEditPage(org.apache.wicket.request.mapper.parameter.PageParameters)"><B>AbstractEditPage(PageParameters)</B></A> - Constructor for class net.metarelate.terminology.webedit.<A HREF="../net/metarelate/terminology/webedit/AbstractEditPage.html" title="class in net.metarelate.terminology.webedit">AbstractEditPage</A> <DD>&nbsp; <DT><A HREF="../net/metarelate/terminology/coreModel/TerminologyIndividualTDBImpl.html#accept(net.metarelate.terminology.publisher.PublisherVisitor)"><B>accept(PublisherVisitor)</B></A> - Method in class net.metarelate.terminology.coreModel.<A HREF="../net/metarelate/terminology/coreModel/TerminologyIndividualTDBImpl.html" title="class in net.metarelate.terminology.coreModel">TerminologyIndividualTDBImpl</A> <DD>&nbsp; <DT><A HREF="../net/metarelate/terminology/coreModel/TerminologySetTDBImpl.html#accept(net.metarelate.terminology.publisher.PublisherVisitor)"><B>accept(PublisherVisitor)</B></A> - Method in class net.metarelate.terminology.coreModel.<A HREF="../net/metarelate/terminology/coreModel/TerminologySetTDBImpl.html" title="class in net.metarelate.terminology.coreModel">TerminologySetTDBImpl</A> <DD>&nbsp; <DT><A HREF="../net/metarelate/terminology/coreModel/Visitee.html#accept(net.metarelate.terminology.publisher.PublisherVisitor)"><B>accept(PublisherVisitor)</B></A> - Method in interface net.metarelate.terminology.coreModel.<A HREF="../net/metarelate/terminology/coreModel/Visitee.html" title="interface in net.metarelate.terminology.coreModel">Visitee</A> <DD>&nbsp; <DT><A HREF="../net/metarelate/terminology/publisher/WebRendererStrings.html#ACTION"><B>ACTION</B></A> - Static variable in class net.metarelate.terminology.publisher.<A HREF="../net/metarelate/terminology/publisher/WebRendererStrings.html" title="class in net.metarelate.terminology.publisher">WebRendererStrings</A> <DD>&nbsp; <DT><A HREF="../net/metarelate/terminology/management/RegistryPolicyManager.html#actionAddURI"><B>actionAddURI</B></A> - Static variable in class net.metarelate.terminology.management.<A HREF="../net/metarelate/terminology/management/RegistryPolicyManager.html" title="class in net.metarelate.terminology.management">RegistryPolicyManager</A> <DD>&nbsp; <DT><A HREF="../net/metarelate/terminology/management/RegistryPolicyManager.html#actionObsoleteURI"><B>actionObsoleteURI</B></A> - Static variable in class net.metarelate.terminology.management.<A HREF="../net/metarelate/terminology/management/RegistryPolicyManager.html" title="class in net.metarelate.terminology.management">RegistryPolicyManager</A> <DD>&nbsp; <DT><A HREF="../net/metarelate/terminology/management/RegistryPolicyManager.html#actionSupersedURI"><B>actionSupersedURI</B></A> - Static variable in class net.metarelate.terminology.management.<A HREF="../net/metarelate/terminology/management/RegistryPolicyManager.html" title="class in net.metarelate.terminology.management">RegistryPolicyManager</A> <DD>&nbsp; <DT><A HREF="../net/metarelate/terminology/management/RegistryPolicyManager.html#actionUpdateURI"><B>actionUpdateURI</B></A> - Static variable in class net.metarelate.terminology.management.<A HREF="../net/metarelate/terminology/management/RegistryPolicyManager.html" title="class in net.metarelate.terminology.management">RegistryPolicyManager</A> <DD>&nbsp; <DT><A HREF="../net/metarelate/terminology/publisher/WebRendererStrings.html#ACTOR"><B>ACTOR</B></A> - Static variable in class net.metarelate.terminology.publisher.<A HREF="../net/metarelate/terminology/publisher/WebRendererStrings.html" title="class in net.metarelate.terminology.publisher">WebRendererStrings</A> <DD>&nbsp; <DT><A HREF="../net/metarelate/terminology/management/TerminologyManagerConfig.html#addActionURI"><B>addActionURI</B></A> - Static variable in class net.metarelate.terminology.management.<A HREF="../net/metarelate/terminology/management/TerminologyManagerConfig.html" title="class in net.metarelate.terminology.management">TerminologyManagerConfig</A> <DD>&nbsp; <DT><A HREF="../net/metarelate/terminology/coreModel/TerminologyEntity.html#addStatements(com.hp.hpl.jena.rdf.model.Model, java.lang.String)"><B>addStatements(Model, String)</B></A> - Method in interface net.metarelate.terminology.coreModel.<A HREF="../net/metarelate/terminology/coreModel/TerminologyEntity.html" title="interface in net.metarelate.terminology.coreModel">TerminologyEntity</A> <DD>Add statements to the statements known for a given version with a new statement block. <DT><A HREF="../net/metarelate/terminology/coreModel/TerminologyEntityTDBImpl.html#addStatements(com.hp.hpl.jena.rdf.model.Model, java.lang.String)"><B>addStatements(Model, String)</B></A> - Method in class net.metarelate.terminology.coreModel.<A HREF="../net/metarelate/terminology/coreModel/TerminologyEntityTDBImpl.html" title="class in net.metarelate.terminology.coreModel">TerminologyEntityTDBImpl</A> <DD>&nbsp; <DT><A HREF="../net/metarelate/terminology/management/TerminologyManager.html#addSubRegister(java.lang.String, java.lang.String, com.hp.hpl.jena.rdf.model.Model, java.lang.String, java.lang.String, boolean)"><B>addSubRegister(String, String, Model, String, String, boolean)</B></A> - Method in class net.metarelate.terminology.management.<A HREF="../net/metarelate/terminology/management/TerminologyManager.html" title="class in net.metarelate.terminology.management">TerminologyManager</A> <DD>Adds a new sub register to a register <DT><A HREF="../net/metarelate/terminology/management/TerminologyManager.html#addTermToRegister(java.lang.String, java.lang.String, com.hp.hpl.jena.rdf.model.Model, java.lang.String, java.lang.String, boolean)"><B>addTermToRegister(String, String, Model, String, String, boolean)</B></A> - Method in class net.metarelate.terminology.management.<A HREF="../net/metarelate/terminology/management/TerminologyManager.html" title="class in net.metarelate.terminology.management">TerminologyManager</A> <DD>Adds a new term to a register <DT><A HREF="../net/metarelate/terminology/management/TerminologyManager.html#addToEntityInformation(java.lang.String, com.hp.hpl.jena.rdf.model.Model, java.lang.String, java.lang.String)"><B>addToEntityInformation(String, Model, String, String)</B></A> - Method in class net.metarelate.terminology.management.<A HREF="../net/metarelate/terminology/management/TerminologyManager.html" title="class in net.metarelate.terminology.management">TerminologyManager</A> <DD>Adds a set of statement to an entity <DT><A HREF="../net/metarelate/terminology/utils/AdvancedClassLabelExtractor.html" title="class in net.metarelate.terminology.utils"><B>AdvancedClassLabelExtractor</B></A> - Class in <A HREF="../net/metarelate/terminology/utils/package-summary.html">net.metarelate.terminology.utils</A><DD>Implements heuristics for finding labels for entities<DT><A HREF="../net/metarelate/terminology/utils/AdvancedClassLabelExtractor.html#AdvancedClassLabelExtractor()"><B>AdvancedClassLabelExtractor()</B></A> - Constructor for class net.metarelate.terminology.utils.<A HREF="../net/metarelate/terminology/utils/AdvancedClassLabelExtractor.html" title="class in net.metarelate.terminology.utils">AdvancedClassLabelExtractor</A> <DD>&nbsp; <DT><A HREF="../net/metarelate/terminology/webedit/AjaxyTextArea.html" title="class in net.metarelate.terminology.webedit"><B>AjaxyTextArea</B></A> - Class in <A HREF="../net/metarelate/terminology/webedit/package-summary.html">net.metarelate.terminology.webedit</A><DD>&nbsp;<DT><A HREF="../net/metarelate/terminology/webedit/AjaxyTextArea.html#AjaxyTextArea(java.lang.String)"><B>AjaxyTextArea(String)</B></A> - Constructor for class net.metarelate.terminology.webedit.<A HREF="../net/metarelate/terminology/webedit/AjaxyTextArea.html" title="class in net.metarelate.terminology.webedit">AjaxyTextArea</A> <DD>&nbsp; <DT><A HREF="../net/metarelate/terminology/auth/AuthConfig.html#allActions"><B>allActions</B></A> - Static variable in class net.metarelate.terminology.auth.<A HREF="../net/metarelate/terminology/auth/AuthConfig.html" title="class in net.metarelate.terminology.auth">AuthConfig</A> <DD>Represents "all" actions <DT><A HREF="../net/metarelate/terminology/auth/AuthConfig.html#allActors"><B>allActors</B></A> - Static variable in class net.metarelate.terminology.auth.<A HREF="../net/metarelate/terminology/auth/AuthConfig.html" title="class in net.metarelate.terminology.auth">AuthConfig</A> <DD>Represents "all" agents <DT><A HREF="../net/metarelate/terminology/auth/AuthConfig.html#allEntities"><B>allEntities</B></A> - Static variable in class net.metarelate.terminology.auth.<A HREF="../net/metarelate/terminology/auth/AuthConfig.html" title="class in net.metarelate.terminology.auth">AuthConfig</A> <DD>Represents "all" entries. <DT><A HREF="../net/metarelate/terminology/management/ConstraintsManagerConfig.html#allRegisters"><B>allRegisters</B></A> - Static variable in class net.metarelate.terminology.management.<A HREF="../net/metarelate/terminology/management/ConstraintsManagerConfig.html" title="class in net.metarelate.terminology.management">ConstraintsManagerConfig</A> <DD>&nbsp; <DT><A HREF="../net/metarelate/terminology/publisher/WebRendererStrings.html#ALSO_AVAILABLE_IN_LANG"><B>ALSO_AVAILABLE_IN_LANG</B></A> - Static variable in class net.metarelate.terminology.publisher.<A HREF="../net/metarelate/terminology/publisher/WebRendererStrings.html" title="class in net.metarelate.terminology.publisher">WebRendererStrings</A> <DD>&nbsp; <DT><A HREF="../net/metarelate/terminology/management/TerminologyManager.html#amendEntityInformation(java.lang.String, com.hp.hpl.jena.rdf.model.Model, java.lang.String, java.lang.String, int)"><B>amendEntityInformation(String, Model, String, String, int)</B></A> - Method in class net.metarelate.terminology.management.<A HREF="../net/metarelate/terminology/management/TerminologyManager.html" title="class in net.metarelate.terminology.management">TerminologyManager</A> <DD>Update action <DT><A HREF="../net/metarelate/terminology/management/ConstraintsManagerConfig.html#appliesTo"><B>appliesTo</B></A> - Static variable in class net.metarelate.terminology.management.<A HREF="../net/metarelate/terminology/management/ConstraintsManagerConfig.html" title="class in net.metarelate.terminology.management">ConstraintsManagerConfig</A> <DD>&nbsp; <DT><A HREF="../net/metarelate/terminology/publisher/WebRendererStrings.html#ATTRIBUTE"><B>ATTRIBUTE</B></A> - Static variable in class net.metarelate.terminology.publisher.<A HREF="../net/metarelate/terminology/publisher/WebRendererStrings.html" title="class in net.metarelate.terminology.publisher">WebRendererStrings</A> <DD>&nbsp; <DT><A HREF="../net/metarelate/terminology/auth/AuthConfig.html" title="class in net.metarelate.terminology.auth"><B>AuthConfig</B></A> - Class in <A HREF="../net/metarelate/terminology/auth/package-summary.html">net.metarelate.terminology.auth</A><DD>A collection of static configuration fields<DT><A HREF="../net/metarelate/terminology/auth/AuthConfig.html#AuthConfig()"><B>AuthConfig()</B></A> - Constructor for class net.metarelate.terminology.auth.<A HREF="../net/metarelate/terminology/auth/AuthConfig.html" title="class in net.metarelate.terminology.auth">AuthConfig</A> <DD>&nbsp; <DT><A HREF="../net/metarelate/terminology/auth/AuthConfig.html#authConfigProperty"><B>authConfigProperty</B></A> - Static variable in class net.metarelate.terminology.auth.<A HREF="../net/metarelate/terminology/auth/AuthConfig.html" title="class in net.metarelate.terminology.auth">AuthConfig</A> <DD>Same as @see authConfigURI, but as Property class. <DT><A HREF="../net/metarelate/terminology/auth/AuthConfig.html#authConfigURI"><B>authConfigURI</B></A> - Static variable in class net.metarelate.terminology.auth.<A HREF="../net/metarelate/terminology/auth/AuthConfig.html" title="class in net.metarelate.terminology.auth">AuthConfig</A> <DD>A property specifying which Auth mode is used <DT><A HREF="../net/metarelate/terminology/config/CoreConfig.html#authDirString"><B>authDirString</B></A> - Static variable in class net.metarelate.terminology.config.<A HREF="../net/metarelate/terminology/config/CoreConfig.html" title="class in net.metarelate.terminology.config">CoreConfig</A> <DD>default auth sub-dir <DT><A HREF="../net/metarelate/terminology/exceptions/AuthException.html" title="class in net.metarelate.terminology.exceptions"><B>AuthException</B></A> - Exception in <A HREF="../net/metarelate/terminology/exceptions/package-summary.html">net.metarelate.terminology.exceptions</A><DD>An exception representing an authorization violation.<DT><A HREF="../net/metarelate/terminology/exceptions/AuthException.html#AuthException(java.lang.String, java.lang.String, java.lang.String)"><B>AuthException(String, String, String)</B></A> - Constructor for exception net.metarelate.terminology.exceptions.<A HREF="../net/metarelate/terminology/exceptions/AuthException.html" title="class in net.metarelate.terminology.exceptions">AuthException</A> <DD>&nbsp; <DT><A HREF="../net/metarelate/terminology/exceptions/AuthException.html#AuthException(java.lang.String)"><B>AuthException(String)</B></A> - Constructor for exception net.metarelate.terminology.exceptions.<A HREF="../net/metarelate/terminology/exceptions/AuthException.html" title="class in net.metarelate.terminology.exceptions">AuthException</A> <DD>&nbsp; <DT><A HREF="../net/metarelate/terminology/installer/InstallerConfig.html#authFilePrefix"><B>authFilePrefix</B></A> - Static variable in class net.metarelate.terminology.installer.<A HREF="../net/metarelate/terminology/installer/InstallerConfig.html" title="class in net.metarelate.terminology.installer">InstallerConfig</A> <DD>&nbsp; <DT><A HREF="../net/metarelate/terminology/utils/Loggers.html#authLogger"><B>authLogger</B></A> - Static variable in class net.metarelate.terminology.utils.<A HREF="../net/metarelate/terminology/utils/Loggers.html" title="class in net.metarelate.terminology.utils">Loggers</A> <DD>&nbsp; <DT><A HREF="../net/metarelate/terminology/auth/AuthRegistryManager.html" title="class in net.metarelate.terminology.auth"><B>AuthRegistryManager</B></A> - Class in <A HREF="../net/metarelate/terminology/auth/package-summary.html">net.metarelate.terminology.auth</A><DD>Manages permissions to operate on the Registry Manager.<DT><A HREF="../net/metarelate/terminology/auth/AuthRegistryManager.html#AuthRegistryManager(net.metarelate.terminology.auth.AuthServer, net.metarelate.terminology.coreModel.TerminologyFactory)"><B>AuthRegistryManager(AuthServer, TerminologyFactory)</B></A> - Constructor for class net.metarelate.terminology.auth.<A HREF="../net/metarelate/terminology/auth/AuthRegistryManager.html" title="class in net.metarelate.terminology.auth">AuthRegistryManager</A> <DD>Constructor <DT><A HREF="../net/metarelate/terminology/auth/AuthServer.html" title="class in net.metarelate.terminology.auth"><B>AuthServer</B></A> - Class in <A HREF="../net/metarelate/terminology/auth/package-summary.html">net.metarelate.terminology.auth</A><DD>Controls permissions to operate the register.<DT><A HREF="../net/metarelate/terminology/auth/AuthServer.html#AuthServer()"><B>AuthServer()</B></A> - Constructor for class net.metarelate.terminology.auth.<A HREF="../net/metarelate/terminology/auth/AuthServer.html" title="class in net.metarelate.terminology.auth">AuthServer</A> <DD>&nbsp; <DT><A HREF="../net/metarelate/terminology/auth/AuthServerFactory.html" title="class in net.metarelate.terminology.auth"><B>AuthServerFactory</B></A> - Class in <A HREF="../net/metarelate/terminology/auth/package-summary.html">net.metarelate.terminology.auth</A><DD>Creates an Authorization Server (currently from a file only).<DT><A HREF="../net/metarelate/terminology/auth/AuthServerFactory.html#AuthServerFactory()"><B>AuthServerFactory()</B></A> - Constructor for class net.metarelate.terminology.auth.<A HREF="../net/metarelate/terminology/auth/AuthServerFactory.html" title="class in net.metarelate.terminology.auth">AuthServerFactory</A> <DD>&nbsp; <DT><A HREF="../net/metarelate/terminology/auth/AuthServerFileBased.html" title="class in net.metarelate.terminology.auth"><B>AuthServerFileBased</B></A> - Class in <A HREF="../net/metarelate/terminology/auth/package-summary.html">net.metarelate.terminology.auth</A><DD>A file based authorization server.<DT><A HREF="../net/metarelate/terminology/auth/AuthServerFileBased.html#AuthServerFileBased(java.io.File[])"><B>AuthServerFileBased(File[])</B></A> - Constructor for class net.metarelate.terminology.auth.<A HREF="../net/metarelate/terminology/auth/AuthServerFileBased.html" title="class in net.metarelate.terminology.auth">AuthServerFileBased</A> <DD>Constructor </DL> <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"> <FONT CLASS="NavBarFont1">Package</FONT>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <FONT CLASS="NavBarFont1">Class</FONT>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <FONT CLASS="NavBarFont1">Use</FONT>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../overview-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="#FFFFFF" CLASS="NavBarCell1Rev"> &nbsp;<FONT CLASS="NavBarFont1Rev"><B>Index</B></FONT>&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;PREV LETTER&nbsp; &nbsp;<A HREF="index-2.html"><B>NEXT LETTER</B></A></FONT></TD> <TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2"> <A HREF="../index.html?index-filesindex-1.html" target="_top"><B>FRAMES</B></A> &nbsp; &nbsp;<A HREF="index-1.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> </TABLE> <A NAME="skip-navbar_bottom"></A> <!-- ======== END OF BOTTOM NAVBAR ======= --> <A HREF="index-1.html">A</A> <A HREF="index-2.html">B</A> <A HREF="index-3.html">C</A> <A HREF="index-4.html">D</A> <A HREF="index-5.html">E</A> <A HREF="index-6.html">F</A> <A HREF="index-7.html">G</A> <A HREF="index-8.html">H</A> <A HREF="index-9.html">I</A> <A HREF="index-10.html">J</A> <A HREF="index-11.html">L</A> <A HREF="index-12.html">M</A> <A HREF="index-13.html">N</A> <A HREF="index-14.html">O</A> <A HREF="index-15.html">P</A> <A HREF="index-16.html">R</A> <A HREF="index-17.html">S</A> <A HREF="index-18.html">T</A> <A HREF="index-19.html">U</A> <A HREF="index-20.html">V</A> <A HREF="index-21.html">W</A> <HR> </BODY> </HTML>
metarelate/terminology-server
moduleFiles/help/metarelateSiteBase/documentation/javadocs/index-files/index-1.html
HTML
gpl-3.0
23,824
var btimer; var isclosed=true; var current_show_id=1; var current_site_id; var wurl; var comment_recapcha_id; function hideVBrowser() { isclosed=true; $('#websiteviewer_background').fadeOut(); } function submitTest(view_token) { $('#websiteviewer_browserheader').html('<center>...در حال بررسی</center>'); $.ajax({ url:wurl+'/websites/api/submitpoint?website_id='+current_site_id+'&view_token='+view_token, success:function(dr) { if(dr.ok===true) { $('#websiteviewer_browserheader').html(`<center style="color:#00aa00;">`+dr.text+`<center>`); } else { $('#websiteviewer_browserheader').html(`<center style="color:#ff0000;">`+dr.text+`<center>`); } $("#pointviewer").html('امتیاز شما : '+ dr.point ); } }); } function showTester() { $('#websiteviewer_browserheader').html('<center>لطفا کمی صبر کنید</center>'); $.ajax({ url:wurl+'/websites/api/requestpoint?website_id='+current_site_id, success:function(dr) { if(dr.able==false) { alert('متاسفانه امکان ثبت امتیاز وجود ندارد!'); return; } $('#websiteviewer_browserheader').html(`<center> <img id=\"validation_image\" src=\"`+wurl+`/websites/api/current_image.png?s=`+dr.rand_session+`\"> <button onclick=\"submitTest(\'`+dr.v0.value+`\')\">`+dr.v0.name+`</button> <button onclick=\"submitTest(\'`+dr.v1.value+`\')\">`+dr.v1.name+`</button> <button onclick=\"submitTest(\'`+dr.v2.value+`\')\">`+dr.v2.name+`</button> گزینه ی صحیح را انتخاب کنید </center>`); } }); } function browserTimer(_reset=false) { if(_reset===true) browserTimer.csi=current_show_id; if(isclosed===true|| browserTimer.csi!== current_show_id) return; btimer-=1; $('#websiteviewer_browserheader').html(' <center> &nbsp;لطفا&nbsp; '+parseInt(btimer)+' &nbsp;ثانیه صبر کنید&nbsp; </center> '); if(btimer>0) setTimeout(browserTimer,1000); else showTester(); } function showwebsite(weburl,websiteid,watchonly=false) { $('#websiteviewer_background').css('visibility','visible'); $('#websiteviewer_browserheader').html('<center>...در حال بارگزاری</center>'); $('#websiteviewer_browser').html(''); $("#websiteviewer_browser").css('display','block'); $("#websiteviewer_comments").css('display','none'); $('#websiteviewer_background').fadeIn(); $('#website_detials').html(' '); current_show_id++; isclosed=false; $.ajax({ url:weburl+'/websites/api/requestvisit?website_id='+websiteid, success:function(dr) { $('#websiteviewer_browser').html('<iframe sandbox=\'\' style=\'width: 100%;height: 100%;\' src=\''+dr.weburl+'\'></iframe>'); if(watchonly) { $('#websiteviewer_browserheader').html('<center>'+dr.title+' <a href="'+weburl+'/websites/editwebsite?website_id='+websiteid+'"><button>اصلاح مشخصات</button></a> '+'</center>'); } else if(dr.selfwebsite===true) { $('#websiteviewer_browserheader').html('<center> این وبسایت توسط خود شما ثبت شده است </center>'); } else if(dr.thepoint<=0) { $('#websiteviewer_browserheader').html('<center> امتیازی جهت کسب کردن وجود ندارد</center>'); } else if(dr.able===false) { $('#websiteviewer_browserheader').html('<center>شما اخیرا از این سایت بازدید کرده اید . لطفا بعدا تلاش کنید</center>'); } else if(dr.nopoint===true) { $('#websiteviewer_browserheader').html('<center>متاسفانه مقدار امتیاز صاحب سایت برای دریافت امتیاز شما کافی نیست</center>'); } else { $('#websiteviewer_browserheader').html('<center> &nbsp;لطفا&nbsp; '+parseInt(dr.timer)+'&nbsp;ثانیه صبر کنید &nbsp;</center>'); setTimeout(function(){browserTimer(true);},1000); } btimer=dr.timer; current_site_id=websiteid; wurl=weburl; if(dr.liked) { $("#websiteviewer_likeButton").css('background-image',' url(\'/images/like_true.png\')'); $("#websiteviewer_likeButton").attr('title','حزف پسندیدن'); } else { $("#websiteviewer_likeButton").css('background-image',' url(\'/images/like_false.png\')'); $("#websiteviewer_likeButton").attr('title','پسندیدن'); } $("#website_detials").html('<span dir="rtl"> <a target="_blank" href="'+dr.weburl+'">'+dr.weburl+'</a> | &nbsp;'+dr.title+' &nbsp; <a target="_blank" href="'+weburl+'/user/'+dr.the_user_name+'">'+dr.user_name+'</a></span>'); } }); } function toggleLike() { $.ajax({ url:wurl+'/websites/api/togglelike?websiteid='+current_site_id, success:function(dr) { if(dr.website_id===current_site_id) { if(dr.liked) { $("#websiteviewer_likeButton").css('background-image',' url(\'/images/like_true.png\')'); $("#websiteviewer_likeButton").attr('title','حزف پسندیدن'); } else { $("#websiteviewer_likeButton").css('background-image',' url(\'/images/like_false.png\')'); $("#websiteviewer_likeButton").attr('title','پسندیدن'); } } } }); } function tabShowComments() { $("#websiteviewer_browser").css('display','none'); $("#websiteviewer_comments").css('display','block'); $("#websiteviewer_comments").html('<center>...در حال بارگزاری</center>'); loadComments(); } function tabShowWebsite() { $("#websiteviewer_browser").css('display','block'); $("#websiteviewer_comments").css('display','none'); } function loadComments() { $.ajax({ url:wurl+'/websites/api/comments/'+current_site_id, success:function(dr){ $('#websiteviewer_comments').html(''); $('#websiteviewer_comments').append(`<div id="your_comment_div"><form onsubmit="postComment()" action="`+wurl+`" method="post"><input type="text" placeholder="نظر شما" id="your_comment_content"></textarea><div id="__google_recaptcha"></div><input onclick="postComment(event)" type="submit" value="ارسال نظر"></form></div>`); comment_recapcha_id=grecaptcha.render('__google_recaptcha',{'sitekey':'6LfaYSgUAAAAAFxMhXqtX6NdYW0jxFv1wnIFS1VS'}); $('#websiteviewer_comments').append(`</div>`); for(var i=0;i<dr.comments.length;i++) { var str = '<span dir="rtl">'+dr.users[i].name + ' میگه : ' + dr.comments[i].content+'</span>'; if(dr.ownwebsite || dr.comments[i].user_id == dr.current_user_id ) { str+='<a href="javascript:void(0)"><button onclick="deleteComment('+dr.comments[i].id+')"> حزف </button></a>'; } $('#websiteviewer_comments').append('<div class="websiteviewer_thecommentblock" >'+str+'</div><br>' ); } } }); } function postComment(e) { e.preventDefault(); console.log(grecaptcha); if(grecaptcha==null) { alert('انجام نشد'); return false; } var rr = grecaptcha.getResponse(comment_recapcha_id); $.ajaxSetup({ headers: { 'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content') } }); $.ajax({ type: "POST", url:wurl+'/website/api/comments/add', data:{'g-recaptcha-response':rr,"website_id":current_site_id,"content":$("#your_comment_content").val()}, success:function(dr){ if(dr.done===true) { alert('نظر شما ثبت شد'); grecaptcha.reset(); loadComments(); } else { alert('متاسفانه مشکلی وجود دارد.نظر شما ثبت نشد. مطمئن شوید محتوای نظر شما خالی نیست و گزینه ی من یک ربات نیستم را تایید کرده اید'); grecaptcha.reset(); } }, error: function(data) { alert('متاسفانه مشکلی در ارتباط با سرور وجود دارد. نظر شما ثبت نشده است.'); } }); alert('... لطفا کمی صبر کنید'); return false; } function deleteComment(comment_id) { var _con = confirm('آیا برای حزف این نظر مطمئن هستید؟'); if(_con==false) return; $.ajaxSetup({ headers: { 'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content') } }); $.ajax({ url:wurl+'/website/api/comments/delete', type:"post", data:{"cid":comment_id}, success:function(dr){ if(dr.done==true) alert('حزف شد'); else alert('مشکلی در حزف وجود دارد'); loadComments(); } }); }
amir9480/Traffic-booster
public_html/js/websites.js
JavaScript
gpl-3.0
10,083
<?php namespace Modules\Acl\Http\Requests; use Illuminate\Foundation\Http\FormRequest; class PerimeterUpdateRequest extends FormRequest { /** * Determine if the user is authorized to make this request. * * @return bool */ public function authorize() { return true; } /** * Get the validation rules that apply to the request. * * @return array */ public function rules() { $id = $this->perimeter; return $rules = [ 'com' => 'required|max:5|unique:perimeters,com,'.$id, 'nom_com' => 'required|unique:perimeters,nom_com,'.$id, 'epci' => 'required|max:9,epci,'.$id, 'dep' => 'required|max:2,dep,'.$id ]; } }
diouck/laravel
Modules/Acl/Http/Requests/PerimeterUpdateRequest.php
PHP
gpl-3.0
763
// // This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, v2.2.7-b41 // See <a href="http://java.sun.com/xml/jaxb">http://java.sun.com/xml/jaxb</a> // Any modifications to this file will be lost upon recompilation of the source schema. // Generated on: 2016.09.01 at 06:27:35 PM MSK // package com.apple.itunes.importer.tv; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlAttribute; import javax.xml.bind.annotation.XmlRootElement; import javax.xml.bind.annotation.XmlSchemaType; import javax.xml.bind.annotation.XmlType; import javax.xml.bind.annotation.adapters.CollapsedStringAdapter; import javax.xml.bind.annotation.adapters.XmlJavaTypeAdapter; /** * <p>Java class for anonymous complex type. * * <p>The following schema fragment specifies the expected content contained within this class. * * <pre> * &lt;complexType> * &lt;complexContent> * &lt;restriction base="{http://www.w3.org/2001/XMLSchema}anyType"> * &lt;attGroup ref="{http://apple.com/itunes/importer}ReviewComponentItem"/> * &lt;/restriction> * &lt;/complexContent> * &lt;/complexType> * </pre> * * */ @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "") @XmlRootElement(name = "review_component_item") public class ReviewComponentItem { @XmlAttribute(name = "locale") @XmlJavaTypeAdapter(CollapsedStringAdapter.class) protected String locale; @XmlAttribute(name = "type", required = true) @XmlSchemaType(name = "anySimpleType") protected String type; /** * Gets the value of the locale property. * * @return * possible object is * {@link String } * */ public String getLocale() { return locale; } /** * Sets the value of the locale property. * * @param value * allowed object is * {@link String } * */ public void setLocale(String value) { this.locale = value; } /** * Gets the value of the type property. * * @return * possible object is * {@link String } * */ public String getType() { return type; } /** * Sets the value of the type property. * * @param value * allowed object is * {@link String } * */ public void setType(String value) { this.type = value; } }
DSRCorporation/imf-conversion
itunes-metadata-tv/src/main/java/com/apple/itunes/importer/tv/ReviewComponentItem.java
Java
gpl-3.0
2,525
<?php /* * Copyright (C) 2014 Aaron Sharp * Released under GNU GENERAL PUBLIC LICENSE Version 3, 29 June 2007 */ namespace Controllers; class IndexController extends Controller { protected $subController = NULL; public function setSubController($subController) { $this->subController = $subController; } public function getSubController() { return $this->subController; } public function parseSession() { return; } public function parseInput() { if (isset($_REQUEST['step'])) { $this->setSubController($this->workflow->getController($_REQUEST['step'])); } else { $this->setSubController(new LoginController($this->getWorkflow())); } } public function retrievePastResults() { return ""; } public function renderInstructions() { return ""; } public function renderForm() { return ""; } public function renderHelp() { return ""; } public function getSubTitle() { return ""; } public function renderSpecificStyle() { return ""; } public function renderSpecificScript() { return ""; } public function getScriptLibraries() { return array(); } public function renderOutput() { if ($this->subController) { $this->subController->run(); } else { error_log("Attempted to render output before setting subcontroller"); } } }
chnops/QIIMEIntegration
includes/Controllers/IndexController.php
PHP
gpl-3.0
1,275
// // Copyright (C) 2001,2002,2003,2004 Jorge Daza Garcia-Blanes // Copyright (C) 2010 Andreas Schroeder // // This file is part of DrQueue // // 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 // #ifndef _AQSISSG_H_ #define _AQSISSG_H_ #ifdef __LINUX #include <stdint.h> #else # ifdef __IRIX # include <sys/types.h> # else # ifdef __OSX # include <stdint.h> # else # ifdef __FREEBSD # include <stdint.h> # else # ifdef __CYGWIN # include <stdint.h> # else # error You need to define the OS, or OS defined not supported # endif # endif # endif # endif #endif #include "constants.h" #ifdef __CPLUSPLUS extern "C" { #endif #pragma pack(push,1) struct aqsissgi { /* Aqsis Script Generator Info */ char scene[BUFFERLEN]; char scriptdir[BUFFERLEN]; char file_owner[BUFFERLEN]; char custom_crop; uint32_t xmin,xmax,ymin,ymax; char custom_samples; // uint32_t xsamples,ysamples; char disp_stats; char verbose; char custom_beep; }; #pragma pack(pop) char *aqsissg_create (struct aqsissgi *info); char *aqsissg_default_script_path (void); #ifdef __CPLUSPLUS } #endif #endif /* _AQSISSG_H_ */
jasonwbarnett/drqueue-fork
libdrqueue/aqsissg.h
C
gpl-3.0
1,827
// // UnrealPaletteDataFormat.cs // // Author: // Michael Becker <alcexhim@gmail.com> // // Copyright (c) 2021 Mike Becker's Software // // 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/>. using System; using MBS.Framework.Drawing; using UniversalEditor.IO; using UniversalEditor.ObjectModels.Multimedia.Palette; namespace UniversalEditor.DataFormats.Multimedia.Palette.Unreal { public class UnrealPaletteDataFormat : DataFormat { public UnrealPaletteDataFormat() { } protected override void LoadInternal(ref ObjectModel objectModel) { PaletteObjectModel palette = (objectModel as PaletteObjectModel); if (palette == null) throw new ObjectModelNotSupportedException(); Reader reader = Accessor.Reader; ushort signature = reader.ReadUInt16(); while (!reader.EndOfStream) { byte r = reader.ReadByte(); byte g = reader.ReadByte(); byte b = reader.ReadByte(); byte a = reader.ReadByte(); palette.Entries.Add(Color.FromRGBAByte(r, g, b, a)); } } protected override void SaveInternal(ObjectModel objectModel) { PaletteObjectModel palette = (objectModel as PaletteObjectModel); if (palette == null) throw new ObjectModelNotSupportedException(); Writer writer = Accessor.Writer; writer.WriteUInt16(0x4001); for (int i = 0; i < Math.Min(palette.Entries.Count, 256); i++) { writer.WriteByte(palette.Entries[i].Color.GetRedByte()); writer.WriteByte(palette.Entries[i].Color.GetGreenByte()); writer.WriteByte(palette.Entries[i].Color.GetBlueByte()); writer.WriteByte(palette.Entries[i].Color.GetAlphaByte()); } int remaining = (256 - palette.Entries.Count); if (remaining > 0) { for (int i = 0; i < remaining; i++) { writer.WriteByte(0); writer.WriteByte(0); writer.WriteByte(0); writer.WriteByte(0); } } } } }
alcexhim/UniversalEditor
Plugins/UniversalEditor.Plugins.UnrealEngine/DataFormats/Multimedia/Palette/Unreal/UnrealPaletteDataFormat.cs
C#
gpl-3.0
2,463
/* * Copyright (C) 2014 HMPerson1 <hmperson1@gmail.com> * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package hmperson1.apps.superdoughnuts import java.awt.event.{ KeyListener, KeyEvent } class KeyListenerDelegate(var delegatee: KeyListener) extends KeyListener { def keyPressed(e: KeyEvent) = delegatee.keyPressed(e) def keyReleased(e: KeyEvent) = delegatee.keyReleased(e) def keyTyped(e: KeyEvent) = delegatee.keyTyped(e) }
HMPerson1/superdoughnuts
src/hmperson1/apps/superdoughnuts/KeyListenerDelegate.scala
Scala
gpl-3.0
1,043
/*************************************************************************** * Copyright (C) 2016 by Okkel Klaver * * info@vanhetland.nl * * * * 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. * ***************************************************************************/ #ifndef SEPARATISTA_ATTRIBUTEDLEAFELEMENT_H #define SEPARATISTA_ATTRIBUTEDLEAFELEMENT_H #include <map> #include "separatista/separatista.h" #include "separatista/xerces_types.h" #include "separatista/leafelement.h" #include "separatista/elementdescriptor.h" namespace Separatista { /** AttributedLeafElements are elements that hold a value and Attributes */ class SEPARATISTA_EXTERN AttributedLeafElement : public LeafElement { public: /** Creates the element from it's descriptor */ static Element* createElement(const ChildElementDescriptor* pChildElementDescriptor); IOErrorCode toDOMDocument(xercesc::DOMDocument *pDocument, xercesc::DOMElement *pParent, const ErrorOptions errorOptions = ThrowExceptions) const; void fromDOMDocument(xercesc::DOMElement *pDOMElement, const ErrorOptions errorOptions = ThrowExceptions); /// @see Element::getAttributeValue const wchar_t* getAttributeValue(const wchar_t *pAttributeName) const; /// @see Element::setAttributeValue void setAttributeValue(const wchar_t *pAttributeName, const wchar_t *pValue); protected: /// Protected constructor AttributedLeafElement(const ChildElementDescriptor* pChildElementDescriptor); std::map<std::wstring, std::wstring> m_Attributes; }; } #endif // SEPARATISTA_ATTRIBUTEDLEAFELEMENT_H
zwartetoorts/separatista
lib/separatista/attributedleafelement.h
C
gpl-3.0
2,674
require 'geomerative' # After an original sketch by fjenett # Declare the objects we are going to use, so that they are accesible # from setup and from draw attr_reader :shp, :x, :y, :xd, :yd def settings size(600, 400) smooth(4) end def setup sketch_title 'Blobby Trail' RG.init(self) @xd = rand(-5..5) @yd = rand(-5..5) @x = width / 2 @y = height / 2 @shp = RShape.new end def draw background(120) move elli = RG.getEllipse(x, y, rand(2..20)) @shp = RG.union(shp, elli) RG.shape(shp) end def move @x += xd @xd *= -1 unless (0..width).cover?(x) @y += yd @yd *= -1 unless (0..height).cover?(y) end
ruby-processing/JRubyArt-examples
external_library/gem/geomerative/blobby_trail.rb
Ruby
gpl-3.0
638
#!/usr/bin/env python if __name__ == '__main__': from anoisetools.scripts.dispatch import main main()
fhcrc/ampliconnoise
anoise.py
Python
gpl-3.0
111
/* * 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., 675 Mass Ave, Cambridge, MA 02139, USA. */ /* * Scoreable.java * Copyright (C) 2001 Remco Bouckaert * */ package weka.classifiers.bayes.net.search.local; /** * Interface for allowing to score a classifier * * @author Remco Bouckaert (rrb@xm.co.nz) * @version $Revision: 1.1 $ */ public interface Scoreable { /** * score types */ int BAYES = 0; int BDeu = 1; int MDL = 2; int ENTROPY = 3; int AIC = 4; /** * Returns log-score */ double logScore(int nType); } // interface Scoreable
paolopavan/cfr
src/weka/classifiers/BAYES/NET/SEARCH/LOCAL/Scoreable.java
Java
gpl-3.0
1,195
package donnees; import java.io.BufferedReader; import java.io.FileReader; import java.util.ArrayList; public class ProducteurDefaut implements IProducteur { private ArrayList<String> donnees; private IMagasin Magasin; public ProducteurDefaut() { super(); donnees = new ArrayList<String>(); Magasin = null; try { BufferedReader br = new BufferedReader(new FileReader("donnees/donnees.txt")); String ligne; while((ligne = br.readLine())!=null) { donnees.add(ligne); } br.close(); } catch (Exception e) { e.printStackTrace(); } } public ArrayList<IProduit> getProduits(IMagasin oMagasin){ Class<?> produit = null; IProduit concret = null; ArrayList<IProduit> oProduit = new ArrayList<IProduit>(); for (String s : donnees) { if(s.contains("class=donnees.Produit")) {//c'est un produit, on va maintenant verifier que c'est un produit du bon magasin. if(s.split(";")[5].split("=")[1].equals(oMagasin.getNomMag())) {//bon mag try { concret = newProduit(s); concret.setNom(s.split(";")[1].split("=")[1]); concret.setType(s.split(";")[2].split("=")[1]); concret.setPrix(Float.parseFloat(s.split(";")[3].split("=")[1])); concret.setQuantites(Integer.parseInt(s.split(";")[4].split("=")[1])); oProduit.add(concret); } catch (Exception e) { e.printStackTrace(); } } } } return oProduit; } private IProduit newProduit(String s) throws ClassNotFoundException, InstantiationException, IllegalAccessException { // Class<?> produit; IProduit concret; // produit = Class.forName(s.split(";")[0].split("=")[1]); // // concret = (IProduit) produit.newInstance(); concret = new ProduitConcret(); return concret; } public IMagasin getMagasin() { if(Magasin == null) { ArrayList<String> magPos = new ArrayList<String>(); System.out.println("liste des magasins: "); for (String s : donnees) { if(s.contains("donnees.Magasin")) { magPos.add(s.split(";")[0].split("=")[1]); System.out.println(s.split(";")[1].split("=")[1]); if(s.split(";")[2].split("=")[1].equals("now")) { System.out.println("load obligatoire, debut..."); try { Magasin = newMagasin(s); Magasin.setNomMag(s.split(";")[1].split("=")[1]); } catch (Exception e) { e.printStackTrace(); } } } } ArrayList<IProduit> stock = getProduits(Magasin); Magasin.setProduits(stock); } return Magasin; } private IMagasin newMagasin(String s) throws ClassNotFoundException, InstantiationException, IllegalAccessException { // Class<?> magasin; // magasin = Class.forName(s.split(";")[0].split("=")[1]); IMagasin magasin = new MagasinConcret(); // Magasin = (IMagasin) magasin.newInstance(); return magasin; } }
Liciax/Projet-M1ALMA-Logiciels-Extensibles
Projet_exten/src/donnees/ProducteurDefaut.java
Java
gpl-3.0
3,118
<div class="log-form"> <h2>Login to your account</h2> <form> <input type="text" title="username" placeholder="username" /> <input type="password" title="username" placeholder="password" /> <button type="submit" class="btn">Login</button> <a class="forgot" href="#">Forgot Username?</a> </form> </div><!--end log form -->
lifemapper/core
LmWebServer/public_html/login.html
HTML
gpl-3.0
342
<table id="location-arrows-table"> <tr class="location-arrows-row1"> <td class="location-arrows-col1"> </td> <td class="location-arrows-col2"> [%if location_arrows.loc_up%] <img src="[%location_arrows.img_up%]" alt="" onclick="Locations.move('[%location_arrows.loc_up%]');" class="clickable loc-tr-[%location_arrows.loc_up%]" /> [%end%] </td> <td class="location-arrows-col3"> </td> </tr> <tr class="location-arrows-row2"> <td class="location-arrows-col1"> [%if location_arrows.loc_left%] <img src="[%location_arrows.img_left%]" alt="" onclick="Locations.move('[%location_arrows.loc_left%]');" class="clickable loc-tr-[%location_arrows.loc_left%]" /> [%end%] </td> <td class="location-arrows-col2"> </td> <td class="location-arrows-col3"> [%if location_arrows.loc_right%] <img src="[%location_arrows.img_right%]" alt="" onclick="Locations.move('[%location_arrows.loc_right%]');" class="clickable loc-tr-[%location_arrows.loc_right%]" /> [%end%] </td> </tr> <tr class="location-arrows-row3"> <td class="location-arrows-col1"> </td> <td class="location-arrows-col2"> [%if location_arrows.loc_down%] <img src="[%location_arrows.img_down%]" alt="" onclick="Locations.move('[%location_arrows.loc_down%]');" class="clickable loc-tr-[%location_arrows.loc_down%]" /> [%end%] </td> <td class="location-arrows-col3"> </td> </tr> </table>
JoyTeam/metagam
mg/templates/game/location-arrows.html
HTML
gpl-3.0
1,406
/* * Synload Development Services * September 16, 2013 * Nathaniel Davidson <nathaniel.davidson@gmail.com> * http://synload.com */ package com.synload.groupvideo; import it.sauronsoftware.base64.Base64; import java.net.InetSocketAddress; import java.util.Hashtable; import org.java_websocket.WebSocket; import org.java_websocket.drafts.Draft; import org.java_websocket.handshake.ClientHandshake; import org.java_websocket.server.WebSocketServer; import com.synload.groupvideo.request.RequestGenerator; import com.synload.groupvideo.request.RequestHandler; import com.synload.groupvideo.users.User; public class Server extends WebSocketServer { public Server( InetSocketAddress address, Draft d ) { super( address ); } public Group newGroup(String name){ Group newGroup = new Group(this); newGroup.groupTitle = name; activeGroups.put(name, newGroup); return newGroup; } public Group getGroup(String name){ if(!activeGroups.containsKey(name)){ return this.newGroup(name); }else{ return activeGroups.get(name); } } @Override public void onError(WebSocket conn, Exception ex) { ex.printStackTrace(); } private RequestHandler request = new RequestHandler(); public Hashtable<String, Group> activeGroups = new Hashtable<String, Group>(); public Hashtable<WebSocket, String> clientGroup = new Hashtable<WebSocket, String>(); public Hashtable<WebSocket, String> clientName = new Hashtable<WebSocket, String>(); public RequestGenerator jsonbuilder = new RequestGenerator(); @Override public void onOpen(WebSocket conn, ClientHandshake handshake) { User user = new User(conn, this); //user.sendMessage("Welcome to GroupVideo!","System"); user.sendResponseData(this.jsonbuilder.user_nick()); System.out.println(conn+" connected"); } @Override public void onClose(WebSocket conn, int code, String reason, boolean remote) { if(clientGroup.containsKey(conn)){ Group group = getGroup(clientGroup.get(conn)); group.removeClient(conn); group.sendData(this.jsonbuilder.left(clientName.get(conn))); if(group.empty()){ group.thread.interrupt(); System.out.println(clientGroup.get(conn)+" destroyed!"); activeGroups.remove(clientGroup.get(conn)); clientGroup.remove(conn); }else{ if(group.getOwner().equals(conn)){ group.setOwner(group.clients.get(0)); System.out.println(clientName.get(group.clients.get(0))+" now owner of "+clientGroup.get(conn)); } clientGroup.remove(conn); String users = ""; for(WebSocket cl: group.clients){ if(users.equals("")){ users = clientName.get(cl); }else{ users += ","+clientName.get(cl); } } group.sendData("act=plylst&usrs="+Base64.encode(users)); } } if(clientName.containsKey(conn)){ System.out.println(clientName.get(conn)+" disconnected!"); clientName.remove(conn); } } @Override public void onMessage(WebSocket conn, String message) { request.translateRequest(conn,message, this); } }
firestar/GroupVideo
com/synload/groupvideo/Server.java
Java
gpl-3.0
3,491
FactoryBot.define do factory :status_change do status_change_to { 0 } status_change_from { 1 } entity { nil } end end
AgileVentures/MetPlus_PETS
spec/factories/status_changes.rb
Ruby
gpl-3.0
134
<?php namespace PhpOffice\Common\Adapter\Zip; use ZipArchive; class ZipArchiveAdapter implements ZipInterface { /** * @var ZipArchive */ protected $oZipArchive; /** * @var string */ protected $filename; public function open($filename) { $this->filename = $filename; $this->oZipArchive = new ZipArchive(); if ($this->oZipArchive->open($this->filename, ZipArchive::OVERWRITE) === true) { return $this; } if ($this->oZipArchive->open($this->filename, ZipArchive::CREATE) === true) { return $this; } throw new \Exception("Could not open $this->filename for writing."); } public function close() { if ($this->oZipArchive->close() === false) { throw new \Exception("Could not close zip file $this->filename."); } return $this; } public function addFromString($localname, $contents) { if ($this->oZipArchive->addFromString($localname, $contents) === false) { throw new \Exception('Error zipping files : ' . $localname); } return $this; } }
collectiveaccess/pawtucket2
vendor/phpoffice/common/src/Common/Adapter/Zip/ZipArchiveAdapter.php
PHP
gpl-3.0
1,167
#ifndef ADDCOUNTRYDIALOG_H #define ADDCOUNTRYDIALOG_H #include <QDialog> class QLineEdit; class AddCountryDialog : public QDialog { Q_OBJECT /*! * The name of the country. */ QLineEdit *m_nameText; /*! * The max length of name of country. */ int m_maxNameLength; public: /*! * Setup the dialog with widget components. * * @param maxNameLength The max length of name of country. * @param parent The parent widget. */ AddCountryDialog( int maxNameLength, QWidget *parent = 0 ); /*! * Get the given name of country. * * @return The name of country. */ QString getName(); private slots: /*! * The slot when call when click to the Ok button. */ void okSlot(); }; #endif // ADDCOUNTRYDIALOG_H
Dgzt/coindatabase
src/addcountrydialog.h
C
gpl-3.0
816
/* * Copyright (c) 2017 "Neo4j, Inc." <http://neo4j.com> * * This file is part of Neo4j Graph Algorithms <http://github.com/neo4j-contrib/neo4j-graph-algorithms>. * * Neo4j Graph Algorithms 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/>. */ package org.neo4j.graphalgo.impl.degree; import org.neo4j.graphalgo.api.Graph; import org.neo4j.graphalgo.core.utils.ParallelUtil; import org.neo4j.graphalgo.core.utils.Pools; import org.neo4j.graphalgo.impl.Algorithm; import org.neo4j.graphalgo.impl.pagerank.DegreeCentralityAlgorithm; import org.neo4j.graphalgo.impl.results.CentralityResult; import org.neo4j.graphalgo.impl.results.DoubleArrayResult; import org.neo4j.graphdb.Direction; import java.util.ArrayList; import java.util.concurrent.ExecutorService; import java.util.concurrent.atomic.AtomicInteger; import java.util.stream.IntStream; import java.util.stream.Stream; public class WeightedDegreeCentrality extends Algorithm<WeightedDegreeCentrality> implements DegreeCentralityAlgorithm { private final int nodeCount; private Direction direction; private Graph graph; private final ExecutorService executor; private final int concurrency; private volatile AtomicInteger nodeQueue = new AtomicInteger(); private double[] degrees; private double[][] weights; public WeightedDegreeCentrality( Graph graph, ExecutorService executor, int concurrency, Direction direction ) { if (concurrency <= 0) { concurrency = Pools.DEFAULT_CONCURRENCY; } this.graph = graph; this.executor = executor; this.concurrency = concurrency; nodeCount = Math.toIntExact(graph.nodeCount()); this.direction = direction; degrees = new double[nodeCount]; weights = new double[nodeCount][]; } public WeightedDegreeCentrality compute(boolean cacheWeights) { nodeQueue.set(0); int batchSize = ParallelUtil.adjustBatchSize(nodeCount, concurrency); int taskCount = ParallelUtil.threadSize(batchSize, nodeCount); final ArrayList<Runnable> tasks = new ArrayList<>(taskCount); for (int i = 0; i < taskCount; i++) { if(cacheWeights) { tasks.add(new CacheDegreeTask()); } else { tasks.add(new DegreeTask()); } } ParallelUtil.runWithConcurrency(concurrency, tasks, executor); return this; } @Override public WeightedDegreeCentrality me() { return this; } @Override public WeightedDegreeCentrality release() { graph = null; return null; } @Override public CentralityResult result() { return new DoubleArrayResult(degrees); } @Override public void compute() { compute(false); } @Override public Algorithm<?> algorithm() { return this; } private class DegreeTask implements Runnable { @Override public void run() { for (; ; ) { final int nodeId = nodeQueue.getAndIncrement(); if (nodeId >= nodeCount || !running()) { return; } double[] weightedDegree = new double[1]; graph.forEachRelationship(nodeId, direction, (sourceNodeId, targetNodeId, relationId, weight) -> { if(weight > 0) { weightedDegree[0] += weight; } return true; }); degrees[nodeId] = weightedDegree[0]; } } } private class CacheDegreeTask implements Runnable { @Override public void run() { for (; ; ) { final int nodeId = nodeQueue.getAndIncrement(); if (nodeId >= nodeCount || !running()) { return; } weights[nodeId] = new double[graph.degree(nodeId, direction)]; int[] index = {0}; double[] weightedDegree = new double[1]; graph.forEachRelationship(nodeId, direction, (sourceNodeId, targetNodeId, relationId, weight) -> { if(weight > 0) { weightedDegree[0] += weight; } weights[nodeId][index[0]] = weight; index[0]++; return true; }); degrees[nodeId] = weightedDegree[0]; } } } public double[] degrees() { return degrees; } public double[][] weights() { return weights; } public Stream<DegreeCentrality.Result> resultStream() { return IntStream.range(0, nodeCount) .mapToObj(nodeId -> new DegreeCentrality.Result(graph.toOriginalNodeId(nodeId), degrees[nodeId])); } }
neo4j-contrib/neo4j-graph-algorithms
algo/src/main/java/org/neo4j/graphalgo/impl/degree/WeightedDegreeCentrality.java
Java
gpl-3.0
5,540
package sporemodder.extras.spuieditor.components; import sporemodder.extras.spuieditor.SPUIViewer; import sporemodder.files.formats.spui.InvalidBlockException; import sporemodder.files.formats.spui.SPUIBlock; import sporemodder.files.formats.spui.SPUIBuilder; public class cSPUIBehaviorWinBoolStateEvent extends cSPUIBehaviorWinEventBase { public static final int TYPE = 0x025611ED; public cSPUIBehaviorWinBoolStateEvent(SPUIBlock block) throws InvalidBlockException { super(block); addUnassignedInt(block, 0x03339952, 0); } public cSPUIBehaviorWinBoolStateEvent(SPUIViewer viewer) { super(viewer); unassignedProperties.put(0x03339952, (int) 0); } @Override public SPUIBlock saveComponent(SPUIBuilder builder) { SPUIBlock block = (SPUIBlock) super.saveComponent(builder); saveInt(builder, block, 0x03339952); return block; } private cSPUIBehaviorWinBoolStateEvent() { super(); } @Override public cSPUIBehaviorWinBoolStateEvent copyComponent(boolean propagateIndependent) { cSPUIBehaviorWinBoolStateEvent other = new cSPUIBehaviorWinBoolStateEvent(); copyComponent(other, propagateIndependent); return other; } }
Emd4600/SporeModder
src/sporemodder/extras/spuieditor/components/cSPUIBehaviorWinBoolStateEvent.java
Java
gpl-3.0
1,174
#!/usr/bin/env python """ Seshat Web App/API framework built on top of gevent modifying decorators for HTTP method functions For more information, see: https://github.com/JoshAshby/ http://xkcd.com/353/ Josh Ashby 2014 http://joshashby.com joshuaashby@joshashby.com """ import json import seshat_addons.utils.patch_json from ..view.template import template import seshat.actions as actions def HTML(f): def wrapper(*args, **kwargs): self = args[0] data = {"title": self._title if self._title else "Untitled"} self.view = template(self._tmpl, self.request, data) res = f(*args, **kwargs) if isinstance(res, actions.BaseAction): return res if type(res) is dict: self.view.data = res res = self.view if isinstance(res, template): string = res.render() else: string = res del res self.head.add_header("Content-Type", "text/html") return string return wrapper def JSON(f): def wrapper(*args, **kwargs): self = args[0] res = f(*args, **kwargs) if isinstance(res, actions.BaseAction): return res if type(res) is not list: res = [res] self.head.add_header("Content-Type", "application/json") return json.dumps(res) return wrapper def Guess(f): def wrapper(*args, **kwargs): self = args[0] res = f(*args, **kwargs) if isinstance(res, actions.BaseAction): return res if self.request.accepts("html") or self.request.accepts("*/*"): self.head.add_header("Content-Type", "text/html") data = {"title": self._title if self._title else "Untitled"} data.update(res) view = template(self._tmpl, self.request, data).render() del res return view if self.request.accepts("json") or self.request.accepts("*/*"): self.head.add_header("Content-Type", "application/json") t_res = type(res) if t_res is dict: final_res = json.dumps([res]) elif t_res is list: final_res = json.dumps(res) del res return final_res else: return unicode(res) return wrapper
JoshAshby/seshat_addons
seshat_addons/seshat/func_mods.py
Python
gpl-3.0
2,354
import Component from './mock/component.spec'; QUnit.module( 'File: core/common/assets/js/api/extras/hash-commands.js', ( hooks ) => { hooks.before( () => { $e.components.register( new Component() ); } ); QUnit.test( 'get(): Ensure valid return format', ( assert ) => { // Act. const actual = $e.extras.hashCommands.get( '#whatever&e:run:test-command&e:route:test-route' ); // Assert. assert.deepEqual( actual, [ { command: 'test-command', method: 'e:run', }, { command: 'test-route', method: 'e:route', } ] ); } ); QUnit.test( 'get(): Ensure valid return format - Only one hash command the start with (#)', ( assert ) => { // Act. const actual = $e.extras.hashCommands.get( '#e:run:my-component/command' ); // Assert. assert.deepEqual( actual, [ { command: 'my-component/command', method: 'e:run', } ] ); } ); QUnit.test( 'run(): Ensure run performed', ( assert ) => { // Arrange. const dispatcherOrig = $e.extras.hashCommands.dispatchersList[ 'e:run' ], dispatcherRunnerOrig = dispatcherOrig.runner; let ensureCallbackPerformed = ''; dispatcherOrig.runner = ( command ) => { ensureCallbackPerformed = command; }; // Act. $e.extras.hashCommands.run( [ { command: 'test-hash-commands/safe-command', method: 'e:run', } ] ); // Assert. assert.equal( ensureCallbackPerformed, 'test-hash-commands/safe-command' ); // Cleanup. dispatcherOrig.runner = dispatcherRunnerOrig; } ); QUnit.test( 'run(): Ensure insecure command fails', ( assert ) => { assert.throws( () => { $e.extras.hashCommands.run( [ { command: 'test-hash-commands/insecure-command', method: 'e:run', } ] ); }, new Error( 'Attempting to run unsafe or non exist command: `test-hash-commands/insecure-command`.' ) ); } ); QUnit.test( 'run(): Ensure exception when no dispatcher found', ( assert ) => { assert.throws( () => { $e.extras.hashCommands.run( [ { command: 'test-hash-commands/insecure-command', method: 'e:non-exist-method', } ] ); }, new Error( 'No dispatcher found for the command: `test-hash-commands/insecure-command`.' ) ); } ); } );
ramiy/elementor
tests/qunit/tests/core/common/assets/js/api/extras/hash-commands.spec.js
JavaScript
gpl-3.0
2,172
/* Liquid War 6 is a unique multiplayer wargame. Copyright (C) 2005, 2006, 2007, 2008, 2009, 2010, 2011, 2012, 2013, 2014, 2015 Christian Mauduit <ufoot@ufoot.org> This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 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/>. Liquid War 6 homepage : http://www.gnu.org/software/liquidwar6/ Contact author : ufoot@ufoot.org */ #ifdef HAVE_CONFIG_H #include "config.h" #endif // HAVE_CONFIG_H #include <CUnit/CUnit.h> #include "net.h" int main (int argc, const char *argv[]) { int ret = 0; lw6sys_context_t *sys_context = NULL; int mode = 0; LW6SYS_MAIN_BEGIN (sys_context); LW6HLP_MAIN_BEGIN (sys_context); lw6sys_log_clear (sys_context, NULL); mode = lw6sys_arg_test_mode (sys_context, argc, argv); if (CU_initialize_registry () == CUE_SUCCESS) { if (lw6net_test_register (sys_context, mode)) { ret = lw6net_test_run (sys_context, mode); } CU_cleanup_registry (); } LW6SYS_TEST_OUTPUT; LW6HLP_MAIN_END (sys_context); LW6SYS_MAIN_END (sys_context); return (!ret); }
lijiaqigreat/liquidwar-web
reference/src/lib/net/net-testmain.c
C
gpl-3.0
1,614
#include <stdint.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <instruction.h> #include <printstream_file.h> #include "avr_instruction_set.h" /* AVRASM formats */ #define AVR_FORMAT_OP_REGISTER(fmt) "R" fmt "" /* mov R0, R2 */ #define AVR_FORMAT_OP_IO_REGISTER(fmt) "$" fmt "" /* out $39, R16 */ #define AVR_FORMAT_OP_DATA_HEX(fmt) "0x" fmt "" /* ldi R16, 0x3d */ #define AVR_FORMAT_OP_DATA_BIN(fmt) "0b" fmt "" /* ldi R16, 0b00111101 */ #define AVR_FORMAT_OP_DATA_DEC(fmt) "" fmt "" /* ldi R16, 61 */ #define AVR_FORMAT_OP_BIT(fmt) "" fmt "" /* cbi $12, 7 */ #define AVR_FORMAT_OP_ABSOLUTE_ADDRESS(fmt) "0x" fmt "" /* call 0x1234 */ #define AVR_FORMAT_OP_RELATIVE_ADDRESS(fmt) "." fmt "" /* rjmp .4 */ #define AVR_FORMAT_OP_ADDRESS_LABEL(fmt) "A_" fmt "" /* call A_0004 */ #define AVR_FORMAT_OP_DES_ROUND(fmt) "0x" fmt "" /* des 0x01 */ #define AVR_FORMAT_OP_RAW_WORD(fmt) "0x" fmt "" /* .dw 0xabcd */ #define AVR_FORMAT_OP_RAW_BYTE(fmt) "0x" fmt "" /* .db 0xab */ #define AVR_FORMAT_ADDRESS(fmt) "" fmt ":" /* 0004: */ #define AVR_FORMAT_ADDRESS_LABEL(fmt) "A_" fmt ":" /* A_0004: */ /* Address filed width, e.g. 4 -> 0x0004 */ #define AVR_ADDRESS_WIDTH 4 /* AVR Instruction Accessor Functions */ uint32_t avr_instruction_get_address(struct instruction *instr); unsigned int avr_instruction_get_width(struct instruction *instr); unsigned int avr_instruction_get_num_operands(struct instruction *instr); unsigned int avr_instruction_get_opcodes(struct instruction *instr, uint8_t *dest); int avr_instruction_get_str_address_label(struct instruction *instr, char *dest, int size, int flags); int avr_instruction_get_str_address(struct instruction *instr, char *dest, int size, int flags); int avr_instruction_get_str_opcodes(struct instruction *instr, char *dest, int size, int flags); int avr_instruction_get_str_mnemonic(struct instruction *instr, char *dest, int size, int flags); int avr_instruction_get_str_operand(struct instruction *instr, char *dest, int size, int index, int flags); int avr_instruction_get_str_comment(struct instruction *instr, char *dest, int size, int flags); void avr_instruction_free(struct instruction *instr); /* AVR Directive Accessor Functions */ unsigned int avr_directive_get_num_operands(struct instruction *instr); int avr_directive_get_str_mnemonic(struct instruction *instr, char *dest, int size, int flags); int avr_directive_get_str_operand(struct instruction *instr, char *dest, int size, int index, int flags); void avr_directive_free(struct instruction *instr); /******************************************************************************/ /* AVR Instructions */ /******************************************************************************/ uint32_t avr_instruction_get_address(struct instruction *instr) { struct avrInstructionDisasm *instructionDisasm = (struct avrInstructionDisasm *)instr->data; return instructionDisasm->address; } unsigned int avr_instruction_get_width(struct instruction *instr) { struct avrInstructionDisasm *instructionDisasm = (struct avrInstructionDisasm *)instr->data; return instructionDisasm->instructionInfo->width; } unsigned int avr_instruction_get_num_operands(struct instruction *instr) { struct avrInstructionDisasm *instructionDisasm = (struct avrInstructionDisasm *)instr->data; return instructionDisasm->instructionInfo->numOperands; } unsigned int avr_instruction_get_opcodes(struct instruction *instr, uint8_t *dest) { struct avrInstructionDisasm *instructionDisasm = (struct avrInstructionDisasm *)instr->data; int i; for (i = 0; i < instructionDisasm->instructionInfo->width; i++) *dest++ = instructionDisasm->opcode[i]; return instructionDisasm->instructionInfo->width; } int avr_instruction_get_str_address_label(struct instruction *instr, char *dest, int size, int flags) { struct avrInstructionDisasm *instructionDisasm = (struct avrInstructionDisasm *)instr->data; return snprintf(dest, size, AVR_FORMAT_ADDRESS_LABEL("%0*x"), AVR_ADDRESS_WIDTH, instructionDisasm->address); } int avr_instruction_get_str_address(struct instruction *instr, char *dest, int size, int flags) { struct avrInstructionDisasm *instructionDisasm = (struct avrInstructionDisasm *)instr->data; return snprintf(dest, size, AVR_FORMAT_ADDRESS("%*x"), AVR_ADDRESS_WIDTH, instructionDisasm->address); } int avr_instruction_get_str_opcodes(struct instruction *instr, char *dest, int size, int flags) { struct avrInstructionDisasm *instructionDisasm = (struct avrInstructionDisasm *)instr->data; if (instructionDisasm->instructionInfo->width == 1) return snprintf(dest, size, "%02x ", instructionDisasm->opcode[0]); else if (instructionDisasm->instructionInfo->width == 2) return snprintf(dest, size, "%02x %02x ", instructionDisasm->opcode[1], instructionDisasm->opcode[0]); else if (instructionDisasm->instructionInfo->width == 4) return snprintf(dest, size, "%02x %02x %02x %02x", instructionDisasm->opcode[3], instructionDisasm->opcode[2], instructionDisasm->opcode[1], instructionDisasm->opcode[0]); return 0; } int avr_instruction_get_str_mnemonic(struct instruction *instr, char *dest, int size, int flags) { struct avrInstructionDisasm *instructionDisasm = (struct avrInstructionDisasm *)instr->data; return snprintf(dest, size, "%s", instructionDisasm->instructionInfo->mnemonic); } int avr_instruction_get_str_operand(struct instruction *instr, char *dest, int size, int index, int flags) { struct avrInstructionDisasm *instructionDisasm = (struct avrInstructionDisasm *)instr->data; if (index < 0 || index > instructionDisasm->instructionInfo->numOperands - 1) return 0; switch (instructionDisasm->instructionInfo->operandTypes[index]) { case OPERAND_REGISTER: case OPERAND_REGISTER_STARTR16: case OPERAND_REGISTER_EVEN_PAIR: case OPERAND_REGISTER_EVEN_PAIR_STARTR24: return snprintf(dest, size, AVR_FORMAT_OP_REGISTER("%d"), instructionDisasm->operandDisasms[index]); case OPERAND_IO_REGISTER: return snprintf(dest, size, AVR_FORMAT_OP_IO_REGISTER("%02x"), instructionDisasm->operandDisasms[index]); case OPERAND_BIT: return snprintf(dest, size, AVR_FORMAT_OP_BIT("%d"), instructionDisasm->operandDisasms[index]); case OPERAND_DES_ROUND: return snprintf(dest, size, AVR_FORMAT_OP_DES_ROUND("%d"), instructionDisasm->operandDisasms[index]); case OPERAND_RAW_WORD: return snprintf(dest, size, AVR_FORMAT_OP_RAW_WORD("%04x"), instructionDisasm->operandDisasms[index]); case OPERAND_RAW_BYTE: return snprintf(dest, size, AVR_FORMAT_OP_RAW_BYTE("%02x"), instructionDisasm->operandDisasms[index]); case OPERAND_X: return snprintf(dest, size, "X"); case OPERAND_XP: return snprintf(dest, size, "X+"); case OPERAND_MX: return snprintf(dest, size, "-X"); case OPERAND_Y: return snprintf(dest, size, "Y"); case OPERAND_YP: return snprintf(dest, size, "Y+"); case OPERAND_MY: return snprintf(dest, size, "-Y"); case OPERAND_Z: return snprintf(dest, size, "Z"); case OPERAND_ZP: return snprintf(dest, size, "Z+"); case OPERAND_MZ: return snprintf(dest, size, "-Z"); case OPERAND_YPQ: return snprintf(dest, size, "Y+%d", instructionDisasm->operandDisasms[index]); case OPERAND_ZPQ: return snprintf(dest, size, "Z+%d", instructionDisasm->operandDisasms[index]); case OPERAND_DATA: if (flags & PRINT_FLAG_DATA_BIN) { /* Data representation binary */ char binary[9]; int i; for (i = 0; i < 8; i++) { if (instructionDisasm->operandDisasms[index] & (1 << i)) binary[7-i] = '1'; else binary[7-i] = '0'; } binary[8] = '\0'; return snprintf(dest, size, AVR_FORMAT_OP_DATA_BIN("%s"), binary); } else if (flags & PRINT_FLAG_DATA_DEC) { /* Data representation decimal */ return snprintf(dest, size, AVR_FORMAT_OP_DATA_DEC("%d"), instructionDisasm->operandDisasms[index]); } else { /* Default to data representation hex */ return snprintf(dest, size, AVR_FORMAT_OP_DATA_HEX("%02x"), instructionDisasm->operandDisasms[index]); } case OPERAND_LONG_ABSOLUTE_ADDRESS: /* If we have address labels turned on, replace the address with * the appropriate address label */ if (flags & PRINT_FLAG_ASSEMBLY) { return snprintf(dest, size, AVR_FORMAT_OP_ADDRESS_LABEL("%0*x"), AVR_ADDRESS_WIDTH, instructionDisasm->operandDisasms[index]); } else { /* Divide the address by two to render a word address */ return snprintf(dest, size, AVR_FORMAT_OP_ABSOLUTE_ADDRESS("%0*x"), AVR_ADDRESS_WIDTH, instructionDisasm->operandDisasms[index] / 2); } break; case OPERAND_BRANCH_ADDRESS: case OPERAND_RELATIVE_ADDRESS: /* If we have address labels turned on, replace the relative * address with the appropriate address label */ if (flags & PRINT_FLAG_ASSEMBLY) { return snprintf(dest, size, AVR_FORMAT_OP_ADDRESS_LABEL("%0*x"), AVR_ADDRESS_WIDTH, instructionDisasm->operandDisasms[index] + instructionDisasm->address + 2); } else { /* Print a plus sign for positive relative addresses, printf * will insert a minus sign for negative relative addresses. */ if (instructionDisasm->operandDisasms[index] >= 0) { return snprintf(dest, size, AVR_FORMAT_OP_RELATIVE_ADDRESS("+%d"), instructionDisasm->operandDisasms[index]); } else { return snprintf(dest, size, AVR_FORMAT_OP_RELATIVE_ADDRESS("%d"), instructionDisasm->operandDisasms[index]); } } default: break; } return 0; } int avr_instruction_get_str_comment(struct instruction *instr, char *dest, int size, int flags) { struct avrInstructionDisasm *instructionDisasm = (struct avrInstructionDisasm *)instr->data; int i; for (i = 0; i < instructionDisasm->instructionInfo->numOperands; i++) { if ( instructionDisasm->instructionInfo->operandTypes[i] == OPERAND_BRANCH_ADDRESS || instructionDisasm->instructionInfo->operandTypes[i] == OPERAND_RELATIVE_ADDRESS) { return snprintf(dest, size, "; " AVR_FORMAT_OP_ABSOLUTE_ADDRESS("%x"), instructionDisasm->operandDisasms[i] + instructionDisasm->address + 2); } } return 0; } void avr_instruction_free(struct instruction *instr) { free(instr->data); instr->data = NULL; } /******************************************************************************/ /* AVR Directives */ /******************************************************************************/ /* Only ORG and END implemented for now */ unsigned int avr_directive_get_num_operands(struct instruction *instr) { struct avrDirective *directive = (struct avrDirective *)instr->data; if (strcmp(directive->name, AVR_DIRECTIVE_NAME_ORIGIN) == 0) return 1; return 0; } int avr_directive_get_str_mnemonic(struct instruction *instr, char *dest, int size, int flags) { struct avrDirective *directive = (struct avrDirective *)instr->data; return snprintf(dest, size, "%s", directive->name); } int avr_directive_get_str_operand(struct instruction *instr, char *dest, int size, int index, int flags) { struct avrDirective *directive = (struct avrDirective *)instr->data; if (strcmp(directive->name, AVR_DIRECTIVE_NAME_ORIGIN) == 0 && index == 0) return snprintf(dest, size, AVR_FORMAT_OP_ABSOLUTE_ADDRESS("%0*x"), AVR_ADDRESS_WIDTH, directive->value); return 0; } void avr_directive_free(struct instruction *instr) { free(instr->data); instr->data = NULL; }
edma2/ucdisasm
avr/avr_accessors.c
C
gpl-3.0
12,492
/******************************************************************************/ /* */ /* X r d X r o o t d L o a d L i b . c c */ /* */ /* (c) 2004 by the Board of Trustees of the Leland Stanford, Jr., University */ /* Produced by Andrew Hanushevsky for Stanford University under contract */ /* DE-AC02-76-SFO0515 with the Department of Energy */ /* */ /* This file is part of the XRootD software suite. */ /* */ /* XRootD 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 3 of the License, or (at your */ /* option) any later version. */ /* */ /* XRootD 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 XRootD in a file called COPYING.LESSER (LGPL license) and file */ /* COPYING (GPL license). If not, see <http://www.gnu.org/licenses/>. */ /* */ /* The copyright holder's institutional names and contributor's names may not */ /* be used to endorse or promote products derived from this software without */ /* specific prior written permission of the institution or contributor. */ /******************************************************************************/ #include "XrdVersion.hh" #include "XrdOuc/XrdOucEnv.hh" #include "XrdSec/XrdSecInterface.hh" #include "XrdSfs/XrdSfsInterface.hh" #include "XrdSys/XrdSysError.hh" #include "XrdSys/XrdSysPlugin.hh" /******************************************************************************/ /* V e r s i o n I n f o r m a t i o n L i n k */ /******************************************************************************/ XrdVERSIONINFOREF(XrdgetProtocol); /******************************************************************************/ /* x r o o t d _ l o a d F i l e s y s t e m */ /******************************************************************************/ XrdSfsFileSystem *XrdXrootdloadFileSystem(XrdSysError *eDest, char *fslib, const char *cfn) { XrdSysPlugin ofsLib(eDest,fslib,"fslib",&XrdVERSIONINFOVAR(XrdgetProtocol)); XrdSfsFileSystem *(*ep)(XrdSfsFileSystem *, XrdSysLogger *, const char *); XrdSfsFileSystem *FS; // Record the library path in the environment // XrdOucEnv::Export("XRDOFSLIB", fslib); // Get the file system object creator // if (!(ep = (XrdSfsFileSystem *(*)(XrdSfsFileSystem *,XrdSysLogger *,const char *)) ofsLib.getPlugin("XrdSfsGetFileSystem"))) return 0; // Get the file system object // if (!(FS = (*ep)(0, eDest->logger(), cfn))) {eDest->Emsg("Config", "Unable to create file system object via",fslib); return 0; } // All done // ofsLib.Persist(); return FS; } /******************************************************************************/ /* x r o o t d _ l o a d S e c u r i t y */ /******************************************************************************/ XrdSecService *XrdXrootdloadSecurity(XrdSysError *eDest, char *seclib, char *cfn, void **secGetProt) { XrdSysPlugin secLib(eDest, seclib, "seclib", &XrdVERSIONINFOVAR(XrdgetProtocol), 1); XrdSecService *(*ep)(XrdSysLogger *, const char *cfn); XrdSecService *CIA; // Get the server object creator // if (!(ep = (XrdSecService *(*)(XrdSysLogger *, const char *cfn)) secLib.getPlugin("XrdSecgetService"))) return 0; // Get the server object // if (!(CIA = (*ep)(eDest->logger(), cfn))) {eDest->Emsg("Config", "Unable to create security service object via",seclib); return 0; } // Get the client object creator (in case we are acting as a client). We return // the function pointer as a (void *) to the caller so that it can be passed // onward via an environment object. // if (!(*secGetProt = (void *)secLib.getPlugin("XrdSecGetProtocol"))) return 0; // All done // secLib.Persist(); return CIA; }
bbockelm/xrootd_old_git
src/XrdXrootd/XrdXrootdLoadLib.cc
C++
gpl-3.0
5,139
#define PROTOCOL_KISS 0x01 #define PROTOCOL_SIMPLE_SERIAL 0x02 #define m328p 0x01 #define m1284p 0x02 #define m644p 0x03 #define REF_3V3 0x01 #define REF_5V 0x02 #define ROLE_FILLIN 0x01 #define ROLE_WIDENN 0x02
markqvist/MicroDigi
util/constants.h
C
gpl-3.0
217
/* * qt5-fsarchiver: Filesystem Archiver * * Copyright (C) 2008-2016 Dieter Baum. All rights reserved. * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public * License v2 as published by the Free Software Foundation. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * General Public License for more details. * */ #ifndef THREAD_H #define THREAD_H #include <qthread.h> class Thread : public QThread { Q_OBJECT public: Thread(); void setValues( int anzahl_, QString dummy); //int progressbar(); protected: void run(); private: int anzahl; QString qdummy; }; #endif
necrose99/qt4-fsarchiver
src/thread.h
C
gpl-3.0
831
//------------------------------------------------------------------------------ // <auto-generated> // This code was generated by a tool. // Runtime Version:4.0.30319.1022 // // Changes to this file may cause incorrect behavior and will be lost if // the code is regenerated. // </auto-generated> //------------------------------------------------------------------------------ namespace SimpleOnScreenDeathCounter.Properties { using System; /// <summary> /// A strongly-typed resource class, for looking up localized strings, etc. /// </summary> // This class was auto-generated by the StronglyTypedResourceBuilder // class via a tool like ResGen or Visual Studio. // To add or remove a member, edit your .ResX file then rerun ResGen // with the /str option, or rebuild your VS project. [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Resources.Tools.StronglyTypedResourceBuilder", "4.0.0.0")] [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] [global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()] internal class Resources { private static global::System.Resources.ResourceManager resourceMan; private static global::System.Globalization.CultureInfo resourceCulture; [global::System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")] internal Resources() { } /// <summary> /// Returns the cached ResourceManager instance used by this class. /// </summary> [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)] internal static global::System.Resources.ResourceManager ResourceManager { get { if (object.ReferenceEquals(resourceMan, null)) { global::System.Resources.ResourceManager temp = new global::System.Resources.ResourceManager("SimpleOnScreenDeathCounter.Properties.Resources", typeof(Resources).Assembly); resourceMan = temp; } return resourceMan; } } /// <summary> /// Overrides the current thread's CurrentUICulture property for all /// resource lookups using this strongly typed resource class. /// </summary> [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)] internal static global::System.Globalization.CultureInfo Culture { get { return resourceCulture; } set { resourceCulture = value; } } internal static System.Drawing.Bitmap GreenOn { get { object obj = ResourceManager.GetObject("GreenOn", resourceCulture); return ((System.Drawing.Bitmap)(obj)); } } internal static System.Drawing.Bitmap RedOFF { get { object obj = ResourceManager.GetObject("RedOFF", resourceCulture); return ((System.Drawing.Bitmap)(obj)); } } internal static System.Drawing.Icon S_O_S_DC_Icon { get { object obj = ResourceManager.GetObject("S_O_S_DC_Icon", resourceCulture); return ((System.Drawing.Icon)(obj)); } } } }
Glought/S.O.S.D.C
SimpleOnScreenDeathCounter/Properties/Resources.Designer.cs
C#
gpl-3.0
3,560
// // This file was generated by the BinaryNotes compiler. // See http://bnotes.sourceforge.net // Any modifications to this file will be lost upon recompilation of the source ASN.1. // using System; using org.bn.attributes; using org.bn.attributes.constraints; using org.bn.coders; using org.bn.types; using org.bn; namespace MMS_ASN1_Model { [ASN1PreparedElement] [ASN1Sequence ( Name = "Unit_Control_instance", IsSet = false )] public class Unit_Control_instance : IASN1PreparedElement { private Identifier name_ ; [ASN1Element ( Name = "name", IsOptional = false , HasTag = true, Tag = 0 , HasDefaultValue = false ) ] public Identifier Name { get { return name_; } set { name_ = value; } } private DefinitionChoiceType definition_ ; [ASN1PreparedElement] [ASN1Choice ( Name = "definition" )] public class DefinitionChoiceType : IASN1PreparedElement { private ObjectIdentifier reference_ ; private bool reference_selected = false ; [ASN1ObjectIdentifier( Name = "" )] [ASN1Element ( Name = "reference", IsOptional = false , HasTag = true, Tag = 1 , HasDefaultValue = false ) ] public ObjectIdentifier Reference { get { return reference_; } set { selectReference(value); } } private DetailsSequenceType details_ ; private bool details_selected = false ; [ASN1PreparedElement] [ASN1Sequence ( Name = "details", IsSet = false )] public class DetailsSequenceType : IASN1PreparedElement { private Access_Control_List_instance accessControl_ ; [ASN1Element ( Name = "accessControl", IsOptional = false , HasTag = true, Tag = 3 , HasDefaultValue = false ) ] public Access_Control_List_instance AccessControl { get { return accessControl_; } set { accessControl_ = value; } } private System.Collections.Generic.ICollection<Domain_instance> domains_ ; [ASN1SequenceOf( Name = "domains", IsSetOf = false )] [ASN1Element ( Name = "domains", IsOptional = false , HasTag = true, Tag = 4 , HasDefaultValue = false ) ] public System.Collections.Generic.ICollection<Domain_instance> Domains { get { return domains_; } set { domains_ = value; } } private System.Collections.Generic.ICollection<Program_Invocation_instance> programInvocations_ ; [ASN1SequenceOf( Name = "programInvocations", IsSetOf = false )] [ASN1Element ( Name = "programInvocations", IsOptional = false , HasTag = true, Tag = 5 , HasDefaultValue = false ) ] public System.Collections.Generic.ICollection<Program_Invocation_instance> ProgramInvocations { get { return programInvocations_; } set { programInvocations_ = value; } } public void initWithDefaults() { } private static IASN1PreparedElementData preparedData = CoderFactory.getInstance().newPreparedElementData(typeof(DetailsSequenceType)); public IASN1PreparedElementData PreparedData { get { return preparedData; } } } [ASN1Element ( Name = "details", IsOptional = false , HasTag = true, Tag = 2 , HasDefaultValue = false ) ] public DetailsSequenceType Details { get { return details_; } set { selectDetails(value); } } public bool isReferenceSelected () { return this.reference_selected ; } public void selectReference (ObjectIdentifier val) { this.reference_ = val; this.reference_selected = true; this.details_selected = false; } public bool isDetailsSelected () { return this.details_selected ; } public void selectDetails (DetailsSequenceType val) { this.details_ = val; this.details_selected = true; this.reference_selected = false; } public void initWithDefaults() { } private static IASN1PreparedElementData preparedData = CoderFactory.getInstance().newPreparedElementData(typeof(DefinitionChoiceType)); public IASN1PreparedElementData PreparedData { get { return preparedData; } } } [ASN1Element ( Name = "definition", IsOptional = false , HasTag = false , HasDefaultValue = false ) ] public DefinitionChoiceType Definition { get { return definition_; } set { definition_ = value; } } public void initWithDefaults() { } private static IASN1PreparedElementData preparedData = CoderFactory.getInstance().newPreparedElementData(typeof(Unit_Control_instance)); public IASN1PreparedElementData PreparedData { get { return preparedData; } } } }
rogerz/IEDExplorer
MMS_ASN1_Model/Unit_Control_instance.cs
C#
gpl-3.0
5,743
// VNR - Plugin for NewRelic which monitors `varnishstat` // Copyright (C) 2015 Luke Mallon // // 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/>. package process import ( "github.com/nalum/vnr/structs" "log" ) func VClient(Channel chan interface{}) { var holder interface{} var data structs.VClient for { holder = <-Channel data = holder.(structs.VClient) log.Println(data) } }
Nalum/vnr
process/vclient.go
GO
gpl-3.0
990
<?php // Heading $_['heading_title'] = 'View Transaction'; // Text $_['text_pp_express'] = 'PayPal Express Checkout'; $_['text_product_lines'] = 'Product lines'; $_['text_ebay_txn_id'] = 'eBay transaction ID'; $_['text_name'] = 'Navn'; $_['text_qty'] = 'Lager'; $_['text_price'] = 'Pris'; $_['text_number'] = 'Number'; $_['text_coupon_id'] = 'Coupon ID'; $_['text_coupon_amount'] = 'Coupon amount'; $_['text_coupon_currency'] = 'Coupon currency'; $_['text_loyalty_disc_amt'] = 'Loyalty card disc amount'; $_['text_loyalty_currency'] = 'Loyalty card currency'; $_['text_options_name'] = 'Options name'; $_['text_tax_amt'] = 'Tax amount'; $_['text_currency_code'] = 'Currency code'; $_['text_amount'] = 'Beløp'; $_['text_gift_msg'] = 'Gift message'; $_['text_gift_receipt'] = 'Gift receipt'; $_['text_gift_wrap_name'] = 'Gift wrap name'; $_['text_gift_wrap_amt'] = 'Gift wrap amount'; $_['text_buyer_email_market'] = 'Buyer marketing email'; $_['text_survey_question'] = 'Survey question'; $_['text_survey_chosen'] = 'Survey choice selected'; $_['text_receiver_business'] = 'Receiver business'; $_['text_receiver_email'] = 'Receiver email'; $_['text_receiver_id'] = 'Receiver ID'; $_['text_buyer_email'] = 'Buyer email'; $_['text_payer_id'] = 'Payer ID'; $_['text_payer_status'] = 'Payer status'; $_['text_country_code'] = 'Country code'; $_['text_payer_business'] = 'Payer business'; $_['text_payer_salute'] = 'Payer salutation'; $_['text_payer_firstname'] = 'Payer first name'; $_['text_payer_middlename'] = 'Payer middle name'; $_['text_payer_lastname'] = 'Payer last name'; $_['text_payer_suffix'] = 'Payer suffix'; $_['text_address_owner'] = 'Address owner'; $_['text_address_status'] = 'Address status'; $_['text_ship_sec_name'] = 'Ship to secondary name'; $_['text_ship_name'] = 'Ship to name'; $_['text_ship_street1'] = 'Ship to address 1'; $_['text_ship_street2'] = 'Ship to address 2'; $_['text_ship_city'] = 'Ship to city'; $_['text_ship_state'] = 'Ship to state'; $_['text_ship_zip'] = 'Ship to ZIP'; $_['text_ship_country'] = 'Ship to country code'; $_['text_ship_phone'] = 'Ship to phone number'; $_['text_ship_sec_add1'] = 'Ship to secondary address 1'; $_['text_ship_sec_add2'] = 'Ship to secondary address 2'; $_['text_ship_sec_city'] = 'Ship to secondary city'; $_['text_ship_sec_state'] = 'Ship to secondary state'; $_['text_ship_sec_zip'] = 'Ship to secondary ZIP'; $_['text_ship_sec_country'] = 'Ship to secondary country code'; $_['text_ship_sec_phone'] = 'Ship to secondary phone'; $_['text_trans_id'] = 'Transaction ID'; $_['text_receipt_id'] = 'Receipt ID'; $_['text_parent_trans_id'] = 'Parent transaction ID'; $_['text_trans_type'] = 'Transaction type'; $_['text_payment_type'] = 'Payment type'; $_['text_order_time'] = 'Order time'; $_['text_fee_amount'] = 'Fee amount'; $_['text_settle_amount'] = 'Settle amount'; $_['text_tax_amount'] = 'Tax amount'; $_['text_exchange'] = 'Exchange rate'; $_['text_payment_status'] = 'Payment status'; $_['text_pending_reason'] = 'Pending reason'; $_['text_reason_code'] = 'Reason code'; $_['text_protect_elig'] = 'Protection eligibility'; $_['text_protect_elig_type'] = 'Protection eligibility type'; $_['text_store_id'] = 'Store ID'; $_['text_terminal_id'] = 'Terminal ID'; $_['text_invoice_number'] = 'Invoice number'; $_['text_custom'] = 'Custom'; $_['text_note'] = 'Note'; $_['text_sales_tax'] = 'Sales tax'; $_['text_buyer_id'] = 'Buyer ID'; $_['text_close_date'] = 'Closing date'; $_['text_multi_item'] = 'Multi item'; $_['text_sub_amt'] = 'Subscription amount'; $_['text_sub_period'] = 'Subscription period';
opencartnorge/norwegian-opencart-translation
upload/admin/language/norwegian/payment/pp_express_view.php
PHP
gpl-3.0
3,808
# multibox This program is a frontend to the Dropbox Client for Linux that enables you to access **more than one Dropbox** at a time. It can be executed with both Python 2.x and 3.x on Unix machines (although only tested on Linux). ## Getting started ### Download Dropbox Client First of all you need to install (or simply extract) the official Dropbox Client from https://www.dropbox.com/install?os=lnx . This software contains a script called `dropboxd`. You need to make that command available by setting `$PATH` accordingly. ### Downloading and Installing multibox Simply fetch the sources via git and install them by using `setup.py`: ```bash $ cd /tmp $ git clone https://github.com/p-ho/multibox.git [...] $ cd multibox/ $ python setup.py install ``` You might need root permissions to execute the install command or you could use a virtual environment. If - for whatever reason - you don't want to install you could simply use the bare module at https://github.com/p-ho/multibox/blob/master/multibox.py . ### Using multibox Now you can issue the command `multibox`: ```bash $ multibox --version multibox 0.2.1 ``` So let's start to initialize a Dropbox location. First of all choose/create a folder preferably an empty one (_[myfolder]_). Start by issuing: ```bash $ multibox [myfolder] ``` Then, if you run a graphical environment, a window should appear asking for the credentials to access your Dropbox. Enter them and sign in (or create a new account). Afterwards you can simply close the window. Now nautilus will pop up displaying an error dialog. You can simply ignore it and close the windows. If you run a non-graphical (e.g. headless) environment you will be presented an URL you need to follow. When done with that an Dropbox icon should appear in your status bar (of course only in graphical envs) and the client starts to synchronize your files from your Dropbox to `[myfolder]/Dropbox`. You can terminate the process at any time by opening the context menu of the Dropbox icon and clicking _Quit_, by issuing `Ctrl` + `C` in command line or sending an `SIGTERM` signal to the process. The next time you execute `$ multibox [myfolder]` the synchronization will resume. You can repeat these steps for each Dropbox you might want to connect to. Of course pick different folders for each of them. ### multibox Flags The following flags can be added when executing multibox: ```bash $ multibox --nogui --force --async [myfolder] ``` - **nogui:** mimic an headless environment - **async:** fires off the Dropbox Client an returns immediately - **force:** disables various checks (NOT recommended) ## License This program is licensed under [GNU General Public License v3 (GPLv3)](https://www.gnu.org/licenses/gpl.html)
p-ho/multibox
README.md
Markdown
gpl-3.0
2,750
[//000000001]: # (valtype::iban \- Validation types) [//000000002]: # (Generated from file 'vtype\.inc' by tcllib/doctools with format 'markdown') [//000000003]: # (Copyright &copy; 2011 Andreas Kupries <andreas\_kupries@users\.sourceforge\.net>) [//000000004]: # (valtype::iban\(n\) 1\.7 tcllib "Validation types") <hr> [ <a href="../../../../toc.md">Main Table Of Contents</a> &#124; <a href="../../../toc.md">Table Of Contents</a> &#124; <a href="../../../../index.md">Keyword Index</a> &#124; <a href="../../../../toc0.md">Categories</a> &#124; <a href="../../../../toc1.md">Modules</a> &#124; <a href="../../../../toc2.md">Applications</a> ] <hr> # NAME valtype::iban \- Validation for IBAN # <a name='toc'></a>Table Of Contents - [Table Of Contents](#toc) - [Synopsis](#synopsis) - [Description](#section1) - [API](#section2) - [Error Codes](#section3) - [Bugs, Ideas, Feedback](#section4) - [Keywords](#keywords) - [Category](#category) - [Copyright](#copyright) # <a name='synopsis'></a>SYNOPSIS package require Tcl 8\.5 package require snit 2 package require valtype::common package require valtype::iban ?1\.7? [__valtype::iban__ __validate__ *value*](#1) [__valtype::iban__ __checkdigit__ *value*](#2) # <a name='description'></a>DESCRIPTION This package implements a snit validation type for an IBAN\. A validation type is an object that can be used to validate Tcl values of a particular kind\. For example, __snit::integer__, a validation type defined by the __[snit](\.\./snit/snit\.md)__ package is used to validate that a Tcl value is an integer\. Every validation type has a __validate__ method which is used to do the validation\. This method must take a single argument, the value to be validated; further, it must do nothing if the value is valid, but throw an error if the value is invalid: valtype::iban validate .... ;# Does nothing valtype::iban validate .... ;# Throws an error (bad International Bank Account Number). The __validate__ method will always return the validated value on success, and throw the __\-errorcode__ INVALID on error, possibly with additional elements which provide more details about the problem\. # <a name='section2'></a>API The API provided by this package satisfies the specification of snit validation types found in the documentation of *[Snit's Not Incr Tcl](\.\./snit/snit\.md)*\. - <a name='1'></a>__valtype::iban__ __validate__ *value* This method validates the *value* and returns it, possibly in a canonical form, if it passes\. If the value does not pass the validation an error is thrown\. - <a name='2'></a>__valtype::iban__ __checkdigit__ *value* This method computes a check digit for the *value*\. Before doing so it is validated, except for a checkdigit\. If the value does not pass the validation no check digit is calculated and an error is thrown instead\. # <a name='section3'></a>Error Codes As said in the package description, the errors thrown by the commands of this package in response to input validation failures use the __\-errorcode__ INVALID to distinguish themselves from package internal errors\. To provide more detailed information about why the validation failed the __\-errorCode__ goes actually beyond that\. First, it will contain a code detailing the type itself\. Here this is __IBAN__\. This is then followed by values detailing the reason for the failure\. The full set of __\-errorCode__s which can be thrown by this package are: - INVALID IBAN CHARACTER The input value contained one or more bad characters, i\.e\. characters which must not occur in the input for it to be an IBAN\. - INVALID IBAN CHECK\-DIGIT The check digit of the input value is wrong\. This usually signals a data\-entry error, with digits transposed, forgotten, etc\. Of course, th input may be an outright fake too\. # <a name='section4'></a>Bugs, Ideas, Feedback This document, and the package it describes, will undoubtedly contain bugs and other problems\. Please report such in the category *valtype* of the [Tcllib Trackers](http://core\.tcl\.tk/tcllib/reportlist)\. Please also report any ideas for enhancements you may have for either package and/or documentation\. When proposing code changes, please provide *unified diffs*, i\.e the output of __diff \-u__\. Note further that *attachments* are strongly preferred over inlined patches\. Attachments can be made by going to the __Edit__ form of the ticket immediately after its creation, and then using the left\-most button in the secondary navigation bar\. # <a name='keywords'></a>KEYWORDS [Checking](\.\./\.\./\.\./\.\./index\.md\#checking), [IBAN](\.\./\.\./\.\./\.\./index\.md\#iban), [International Bank Account Number](\.\./\.\./\.\./\.\./index\.md\#international\_bank\_account\_number), [Testing](\.\./\.\./\.\./\.\./index\.md\#testing), [Type checking](\.\./\.\./\.\./\.\./index\.md\#type\_checking), [Validation](\.\./\.\./\.\./\.\./index\.md\#validation), [Value checking](\.\./\.\./\.\./\.\./index\.md\#value\_checking), [bank](\.\./\.\./\.\./\.\./index\.md\#bank), [finance](\.\./\.\./\.\./\.\./index\.md\#finance), [isA](\.\./\.\./\.\./\.\./index\.md\#isa) # <a name='category'></a>CATEGORY Validation, Type checking # <a name='copyright'></a>COPYRIGHT Copyright &copy; 2011 Andreas Kupries <andreas\_kupries@users\.sourceforge\.net>
SAOImageDS9/SAOImageDS9
tcllib/embedded/md/tcllib/files/modules/valtype/iban.md
Markdown
gpl-3.0
5,415
/*********************************************************** * Programming Assignment 6 * Arrays program * Programmers: Mark Eatough and Stephen Williams * Course: CS 1600 * Created March 5, 2013 *This program takes values from a current array and a resistance, *array, and uses them to calculate a volts array. The Program *then prints the three arrays with appropriate headings. ***********************************************************/ #include<iostream> using namespace std; //create function prototype void calc_volts(double [], double [], double [], int); //main function int main() { const int capacity = 10; int k; double current[capacity] = {10.62, 14.89, 13.21, 16.55, 18.62, 9.47, 6.58, 18.32, 12.15, 3.98}; double resistance[capacity] = {4, 8.5, 6, 7.35, 9, 15.3, 3, 5.4, 2.9, 4.8}; double volts[capacity]; calc_volts(current, resistance, volts, capacity); cout << "Current \tResistence \tVolts " << endl; for(k = 0; k < capacity; k++) { cout << current[k] << "\t\t" << resistance[k] << "\t\t" << volts[k] << endl; } } //implementation of function to calculate volts void calc_volts(double res [], double cur [], double vol [], int cap) { int i; for(i = 0; i < cap; i++) { vol[i] = (cur[i] * res[i]); } }
meatough/Marks-Programs
CS 1600/Homework assignments/programming projects/Programming project 6/Programming Project 6.cpp
C++
gpl-3.0
1,313
<?php if(!defined('sugarEntry') || !sugarEntry) die('Not A Valid Entry Point'); /********************************************************************************* * SugarCRM is a customer relationship management program developed by * SugarCRM, Inc. Copyright (C) 2004 - 2009 SugarCRM Inc. * * This program is free software; you can redistribute it and/or modify it under * the terms of the GNU General Public License version 3 as published by the * Free Software Foundation with the addition of the following permission added * to Section 15 as permitted in Section 7(a): FOR ANY PART OF THE COVERED WORK * IN WHICH THE COPYRIGHT IS OWNED BY SUGARCRM, SUGARCRM DISCLAIMS THE WARRANTY * OF NON INFRINGEMENT OF THIRD PARTY RIGHTS. * * This program is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS * FOR A PARTICULAR PURPOSE. See the GNU 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 or write to the Free * Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA * 02110-1301 USA. * * You can contact SugarCRM, Inc. headquarters at 10050 North Wolfe Road, * SW2-130, Cupertino, CA 95014, USA. or at email address contact@sugarcrm.com. * * The interactive user interfaces in modified source and object code versions * of this program must display Appropriate Legal Notices, as required under * Section 5 of the GNU General Public License version 3. * * In accordance with Section 7(b) of the GNU General Public License version 3, * these Appropriate Legal Notices must retain the display of the "Powered by * SugarCRM" logo. If the display of the logo is not reasonably feasible for * technical reasons, the Appropriate Legal Notices must display the words * "Powered by SugarCRM". ********************************************************************************/ /********************************************************************************* * Description: base form for account * Portions created by SugarCRM are Copyright (C) SugarCRM, Inc. * All Rights Reserved. * Contributor(s): ______________________________________.. ********************************************************************************/ class AccountFormBase{ function checkForDuplicates($prefix){ require_once('include/formbase.php'); $focus = new Account(); $query = ''; $baseQuery = 'select id, name, website, billing_address_city from accounts where deleted!=1 and '; if(!empty($_POST[$prefix.'name'])){ $query = $baseQuery ." name like '".$_POST[$prefix.'name']."%'"; } if(!empty($_POST[$prefix.'billing_address_city']) || !empty($_POST[$prefix.'shipping_address_city'])){ $temp_query = ''; if(!empty($_POST[$prefix.'billing_address_city'])){ if(empty($temp_query)){ $temp_query = " billing_address_city like '".$_POST[$prefix.'billing_address_city']."%'"; }else { $temp_query .= "or billing_address_city like '".$_POST[$prefix.'billing_address_city']."%'"; } } if(!empty($_POST[$prefix.'shipping_address_city'])){ if(empty($temp_query)){ $temp_query = " shipping_address_city like '".$_POST[$prefix.'shipping_address_city']."%'"; }else { $temp_query .= "or shipping_address_city like '".$_POST[$prefix.'shipping_address_city']."%'"; } } if(empty($query)){ $query .= $baseQuery; }else{ $query .= ' AND '; } $query .= ' ('. $temp_query . ' ) '; } if(!empty($query)){ $rows = array(); global $db; $result = $db->query($query); $i=-1; while(($row=$db->fetchByAssoc($result)) != null) { $i++; $rows[$i] = $row; } if ($i==-1) return null; return $rows; } return null; } function buildTableForm($rows, $mod='Accounts'){ if(!ACLController::checkAccess('Accounts', 'edit', true)){ return ''; } global $action; if(!empty($mod)){ global $current_language; $mod_strings = return_module_language($current_language, $mod); }else global $mod_strings; global $app_strings; $cols = sizeof($rows[0]) * 2 + 1; if ($action != 'ShowDuplicates') { $form = "<form action='index.php' method='post' id='dupAccounts' name='dupAccounts'><input type='hidden' name='selectedAccount' value=''>"; $form .= '<table width="100%"><tr><td>'.$mod_strings['MSG_DUPLICATE']. '</td></tr><tr><td height="20"></td></tr></table>'; unset($_POST['selectedAccount']); } else { $form = '<table width="100%"><tr><td>'.$mod_strings['MSG_SHOW_DUPLICATES']. '</td></tr><tr><td height="20"></td></tr></table>'; } $form .= get_form_header($mod_strings['LBL_DUPLICATE'], "", ''); $form .= "<table width='100%' cellpadding='0' cellspacing='0'> <tr> "; if ($action != 'ShowDuplicates') { $form .= "<th> &nbsp;</th>"; } require_once('include/formbase.php'); if(isset($_POST['return_action']) && $_POST['return_action'] == 'SubPanelViewer') { $_POST['return_action'] = 'DetailView'; } if(isset($_POST['return_action']) && $_POST['return_action'] == 'DetailView' && empty($_REQUEST['return_id'])) { unset($_POST['return_action']); } $form .= getPostToForm('/emailAddress(PrimaryFlag|OptOutFlag|InvalidFlag)?[0-9]*?$/', true); if(isset($rows[0])){ foreach ($rows[0] as $key=>$value){ if($key != 'id'){ $form .= "<th>". $mod_strings[$mod_strings['db_'.$key]]. "</th>"; }} $form .= "</tr>"; } $rowColor = 'oddListRowS1'; foreach($rows as $row){ $form .= "<tr class='$rowColor'>"; if ($action != 'ShowDuplicates') { $form .= "<td width='1%' nowrap><a href='#' onclick='document.dupAccounts.selectedAccount.value=\"${row['id']}\"; document.dupAccounts.submit(); '>[${app_strings['LBL_SELECT_BUTTON_LABEL']}]</a>&nbsp;&nbsp;</td>\n"; } foreach ($row as $key=>$value){ if($key != 'id'){ if(isset($_POST['popup']) && $_POST['popup']==true){ $form .= "<td scope='row'><a href='#' onclick=\"window.opener.location='index.php?module=Accounts&action=DetailView&record=${row['id']}'\">$value</a></td>\n"; } else $form .= "<td><a target='_blank' href='index.php?module=Accounts&action=DetailView&record=${row['id']}'>$value</a></td>\n"; }} if($rowColor == 'evenListRowS1'){ $rowColor = 'oddListRowS1'; }else{ $rowColor = 'evenListRowS1'; } $form .= "</tr>"; } $form .= "<tr><td colspan='$cols' class='blackline'></td></tr>"; // handle buttons if ($action == 'ShowDuplicates') { $return_action = 'ListView'; // cn: bug 6658 - hardcoded return action break popup -> create -> duplicate -> cancel $return_action = (isset($_REQUEST['return_action']) && !empty($_REQUEST['return_action'])) ? $_REQUEST['return_action'] : $return_action; $form .= "</table><br><input type='hidden' name='selectedAccount' id='selectedAccount' value=''><input title='${app_strings['LBL_SAVE_BUTTON_TITLE']}' accessKey='${app_strings['LBL_SAVE_BUTTON_KEY']}' class='button' onclick=\"this.form.action.value='Save';\" type='submit' name='button' value=' ${app_strings['LBL_SAVE_BUTTON_LABEL']} '>"; if (!empty($_REQUEST['return_module']) && !empty($_REQUEST['return_action']) && !empty($_REQUEST['return_id'])) $form .= "<input title='${app_strings['LBL_CANCEL_BUTTON_TITLE']}' accessKey='${app_strings['LBL_CANCEL_BUTTON_KEY']}' class='button' onclick=\"location.href='index.php?module=".$_REQUEST['return_module']."&action=".$_REQUEST['return_action']."&record=".$_REQUEST['return_id']."'\" type='button' name='button' value=' ${app_strings['LBL_CANCEL_BUTTON_LABEL']} '></form>"; else if (!empty($_POST['return_module']) && !empty($_POST['return_action'])) $form .= "<input title='${app_strings['LBL_CANCEL_BUTTON_TITLE']}' accessKey='${app_strings['LBL_CANCEL_BUTTON_KEY']}' class='button' onclick=\"location.href='index.php?module=".$_POST['return_module']."&action=". $_POST['return_action']."'\" type='button' name='button' value=' ${app_strings['LBL_CANCEL_BUTTON_LABEL']} '></form>"; else $form .= "<input title='${app_strings['LBL_CANCEL_BUTTON_TITLE']}' accessKey='${app_strings['LBL_CANCEL_BUTTON_KEY']}' class='button' onclick=\"location.href='index.php?module=Accounts&action=ListView'\" type='button' name='button' value=' ${app_strings['LBL_CANCEL_BUTTON_LABEL']} '></form>"; } else { $form .= "</table><BR><input type='submit' class='button' name='ContinueAccount' value='${mod_strings['LNK_NEW_ACCOUNT']}'></form>\n"; } return $form; } function getForm($prefix, $mod='', $form=''){ if(!ACLController::checkAccess('Accounts', 'edit', true)){ return ''; } if(!empty($mod)){ global $current_language; $mod_strings = return_module_language($current_language, $mod); }else global $mod_strings; global $app_strings; $lbl_save_button_title = $app_strings['LBL_SAVE_BUTTON_TITLE']; $lbl_save_button_key = $app_strings['LBL_SAVE_BUTTON_KEY']; $lbl_save_button_label = $app_strings['LBL_SAVE_BUTTON_LABEL']; $the_form = get_left_form_header($mod_strings['LBL_NEW_FORM_TITLE']); $the_form .= <<<EOQ <form name="${prefix}AccountSave" onSubmit="return check_form('${prefix}AccountSave');" method="POST" action="index.php"> <input type="hidden" name="${prefix}module" value="Accounts"> <input type="hidden" name="${prefix}action" value="Save"> EOQ; $the_form .= $this->getFormBody($prefix, $mod, $prefix."AccountSave"); $the_form .= <<<EOQ <p><input title="$lbl_save_button_title" accessKey="$lbl_save_button_key" class="button" type="submit" name="button" value=" $lbl_save_button_label " ></p> </form> EOQ; $the_form .= get_left_form_footer(); $the_form .= get_validate_record_js(); return $the_form; } function getFormBody($prefix,$mod='', $formname=''){ if(!ACLController::checkAccess('Accounts', 'edit', true)){ return ''; } global $mod_strings; $temp_strings = $mod_strings; if(!empty($mod)){ global $current_language; $mod_strings = return_module_language($current_language, $mod); } global $app_strings; global $current_user; $lbl_required_symbol = $app_strings['LBL_REQUIRED_SYMBOL']; $lbl_account_name = $mod_strings['LBL_ACCOUNT_NAME']; $lbl_phone = $mod_strings['LBL_PHONE']; $lbl_website = $mod_strings['LBL_WEBSITE']; $lbl_save_button_title = $app_strings['LBL_SAVE_BUTTON_TITLE']; $lbl_save_button_key = $app_strings['LBL_SAVE_BUTTON_KEY']; $lbl_save_button_label = $app_strings['LBL_SAVE_BUTTON_LABEL']; $user_id = $current_user->id; $form = <<<EOQ <p><input type="hidden" name="record" value=""> <input type="hidden" name="email1" value=""> <input type="hidden" name="email2" value=""> <input type="hidden" name="assigned_user_id" value='${user_id}'> <input type="hidden" name="action" value="Save"> EOQ; $form .= "$lbl_account_name&nbsp;<span class='required'>$lbl_required_symbol</span><br><input name='name' type='text' value=''><br>"; $form .= "$lbl_phone<br><input name='phone_office' type='text' value=''><br>"; $form .= "$lbl_website<br><input name='website' type='text' value='http://'><br>"; $form .='</p>'; $javascript = new javascript(); $javascript->setFormName($formname); $javascript->setSugarBean(new Account()); $javascript->addRequiredFields($prefix); $form .=$javascript->getScript(); $mod_strings = $temp_strings; return $form; } function getWideFormBody($prefix, $mod='',$formname='', $contact=''){ if(!ACLController::checkAccess('Accounts', 'edit', true)){ return ''; } if(empty($contact)){ $contact = new Contact(); } global $mod_strings; $temp_strings = $mod_strings; if(!empty($mod)){ global $current_language; $mod_strings = return_module_language($current_language, $mod); } global $app_strings; global $current_user; $account = new Account(); $lbl_required_symbol = $app_strings['LBL_REQUIRED_SYMBOL']; $lbl_account_name = $mod_strings['LBL_ACCOUNT_NAME']; $lbl_phone = $mod_strings['LBL_PHONE']; $lbl_website = $mod_strings['LBL_WEBSITE']; if (isset($contact->assigned_user_id)) { $user_id=$contact->assigned_user_id; } else { $user_id = $current_user->id; } //Retrieve Email address and set email1, email2 $sugarEmailAddress = new SugarEmailAddress(); $sugarEmailAddress->handleLegacyRetrieve($contact); if(!isset($contact->email1)){ $contact->email1 = ''; } if(!isset($contact->email2)){ $contact->email2 = ''; } if(!isset($contact->email_opt_out)){ $contact->email_opt_out = ''; } $form=""; $default_desc=""; if (!empty($contact->description)) { $default_desc=$contact->description; } $form .= <<<EOQ <input type="hidden" name="${prefix}record" value=""> <input type="hidden" name="${prefix}phone_fax" value="{$contact->phone_fax}"> <input type="hidden" name="${prefix}phone_other" value="{$contact->phone_other}"> <input type="hidden" name="${prefix}email1" value="{$contact->email1}"> <input type="hidden" name="${prefix}email2" value="{$contact->email2}"> <input type='hidden' name='${prefix}billing_address_street' value='{$contact->primary_address_street}'><input type='hidden' name='${prefix}billing_address_city' value='{$contact->primary_address_city}'><input type='hidden' name='${prefix}billing_address_state' value='{$contact->primary_address_state}'><input type='hidden' name='${prefix}billing_address_postalcode' value='{$contact->primary_address_postalcode}'><input type='hidden' name='${prefix}billing_address_country' value='{$contact->primary_address_country}'> <input type='hidden' name='${prefix}shipping_address_street' value='{$contact->primary_address_street}'><input type='hidden' name='${prefix}shipping_address_city' value='{$contact->primary_address_city}'><input type='hidden' name='${prefix}shipping_address_state' value='{$contact->primary_address_state}'><input type='hidden' name='${prefix}shipping_address_postalcode' value='{$contact->primary_address_postalcode}'><input type='hidden' name='${prefix}shipping_address_country' value='{$contact->primary_address_country}'> <input type="hidden" name="${prefix}assigned_user_id" value='${user_id}'> <input type='hidden' name='${prefix}do_not_call' value='{$contact->do_not_call}'> <input type='hidden' name='${prefix}email_opt_out' value='{$contact->email_opt_out}'> <table width='100%' border="0" cellpadding="0" cellspacing="0"> <tr> <td width="20%" nowrap scope="row">$lbl_account_name&nbsp;<span class="required">$lbl_required_symbol</span></td> <TD width="80%" nowrap scope="row">{$mod_strings['LBL_DESCRIPTION']}</TD> </tr> <tr> <td nowrap ><input name='{$prefix}name' type="text" value="$contact->account_name"></td> <TD rowspan="5" ><textarea name='{$prefix}description' rows='6' cols='50' >$default_desc</textarea></TD> </tr> <tr> <td nowrap scope="row">$lbl_phone</td> </tr> <tr> <td nowrap ><input name='{$prefix}phone_office' type="text" value="$contact->phone_work"></td> </tr> <tr> <td nowrap scope="row">$lbl_website</td> </tr> <tr> <td nowrap ><input name='{$prefix}website' type="text" value="http://"></td> </tr> EOQ; //carry forward custom lead fields common to accounts during Lead Conversion $tempAccount = new Account(); if (method_exists($contact, 'convertCustomFieldsForm')) $contact->convertCustomFieldsForm($form, $tempAccount, $prefix); unset($tempAccount); $form .= <<<EOQ </TABLE> EOQ; $javascript = new javascript(); $javascript->setFormName($formname); $javascript->setSugarBean(new Account()); $javascript->addRequiredFields($prefix); $form .=$javascript->getScript(); $mod_strings = $temp_strings; return $form; } function handleSave($prefix,$redirect=true, $useRequired=false){ require_once('include/formbase.php'); $focus = new Account(); if($useRequired && !checkRequired($prefix, array_keys($focus->required_fields))){ return null; } $focus = populateFromPost($prefix, $focus); if (isset($GLOBALS['check_notify'])) { $check_notify = $GLOBALS['check_notify']; } else { $check_notify = FALSE; } if (empty($_POST['record']) && empty($_POST['dup_checked'])) { $duplicateAccounts = $this->checkForDuplicates($prefix); if(isset($duplicateAccounts)){ $location='module=Accounts&action=ShowDuplicates'; $get = ''; //add all of the post fields to redirect get string foreach ($focus->column_fields as $field) { if (!empty($focus->$field)) { $get .= "&Accounts$field=".urlencode($focus->$field); } } foreach ($focus->additional_column_fields as $field) { if (!empty($focus->$field)) { $get .= "&Accounts$field=".urlencode($focus->$field); } } if($focus->hasCustomFields()) { foreach($focus->field_defs as $name=>$field) { if (!empty($field['source']) && $field['source'] == 'custom_fields') { $get .= "&Accounts$name=".urlencode($focus->$name); } } } $emailAddress = new SugarEmailAddress(); $get .= $emailAddress->getFormBaseURL($focus); //create list of suspected duplicate account id's in redirect get string $i=0; foreach ($duplicateAccounts as $account) { $get .= "&duplicate[$i]=".$account['id']; $i++; } //add return_module, return_action, and return_id to redirect get string $get .= '&return_module='; if(!empty($_POST['return_module'])) $get .= $_POST['return_module']; else $get .= 'Accounts'; $get .= '&return_action='; if(!empty($_POST['return_action'])) $get .= $_POST['return_action']; //else $get .= 'DetailView'; if(!empty($_POST['return_id'])) $get .= '&return_id='.$_POST['return_id']; if(!empty($_POST['popup'])) $get .= '&popup='.$_POST['popup']; if(!empty($_POST['create'])) $get .= '&create='.$_POST['create']; //echo $get; //die; //now redirect the post to modules/Accounts/ShowDuplicates.php if (!empty($_POST['is_ajax_call']) && $_POST['is_ajax_call'] == '1') { $json = getJSONobj(); echo $json->encode(array('status' => 'dupe', 'get' => $get)); } else { if(!empty($_POST['to_pdf'])) $location .= '&to_pdf='.$_POST['to_pdf']; $_SESSION['SHOW_DUPLICATES'] = $get; header("Location: index.php?$location"); } return null; } } if(!$focus->ACLAccess('Save')){ ACLController::displayNoAccess(true); sugar_cleanup(true); } $focus->save($check_notify); $return_id = $focus->id; $GLOBALS['log']->debug("Saved record with id of ".$return_id); if (!empty($_POST['is_ajax_call']) && $_POST['is_ajax_call'] == '1') { $json = getJSONobj(); echo $json->encode(array('status' => 'success', 'get' => '')); return null; } if(isset($_POST['popup']) && $_POST['popup'] == 'true') { $get = '&module='; if(!empty($_POST['return_module'])) $get .= $_POST['return_module']; else $get .= 'Accounts'; $get .= '&action='; if(!empty($_POST['return_action'])) $get .= $_POST['return_action']; else $get .= 'Popup'; if(!empty($_POST['return_id'])) $get .= '&return_id='.$_POST['return_id']; if(!empty($_POST['popup'])) $get .= '&popup='.$_POST['popup']; if(!empty($_POST['create'])) $get .= '&create='.$_POST['create']; if(!empty($_POST['to_pdf'])) $get .= '&to_pdf='.$_POST['to_pdf']; $get .= '&name=' . $focus->name; $get .= '&query=true'; header("Location: index.php?$get"); return; } if($redirect){ handleRedirect($return_id,'Accounts'); }else{ return $focus; } } } ?>
mitani/dashlet-subpanels
modules/Accounts/AccountFormBase.php
PHP
gpl-3.0
19,722
public class Solution { public int longestSubstring(String s, int k) { if(s.length() < k) return 0; int[] count = new int[26]; Arrays.fill(count, 0); for(int i = 0;i < s.length();++i) { count[(int)(s.charAt(i) - 'a')]++; } char c = '-'; for(int i = 0;i < 26;++i) { if(count[i] < k && count[i] != 0) { c = (char) (i + 'a'); break; } } if(c == '-') return s.length(); int index = -1; for(int i = 0;i < s.length();++i) { if(s.charAt(i) == c) { index = i; break; } } String left = s.substring(0, index); String right = s.substring(index + 1, s.length()); int l = 0; int r = 0; if(index >= k) { l = longestSubstring(s.substring(0, index), k); } if(s.length() - index - 1 >= k) { r = longestSubstring(s.substring(index + 1, s.length()), k); } if(l > r) return l; return r; } }
acgtun/leetcode
algorithms/java/Longest Substring with At Least K Repeating Characters.java
Java
gpl-3.0
1,120
module OLDRETS VERSION = "2.0.6" end
mccollek/ruby-rets
lib/old_rets/version.rb
Ruby
gpl-3.0
39
# -*- coding: utf-8 -*- # XMPPVOX: XMPP client for DOSVOX. # Copyright (C) 2012 Rodolfo Henrique Carvalho # # This file is part of XMPPVOX. # # XMPPVOX 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/>. u""" XMPPVOX - módulo servidor Este módulo implementa um servidor compatível com o protocolo usado pelo Papovox e Sítiovox. """ import socket import struct import textwrap import time import sys from cStringIO import StringIO from xmppvox import commands from xmppvox.strings import safe_unicode, get_string as S import logging log = logging.getLogger(__name__) # Constantes ------------------------------------------------------------------# # Todas as strings passadas para o Papovox devem ser codificadas usando a # codificação padrão do DOSVOX, ISO-8859-1, também conhecida como Latin-1. SYSTEM_ENCODING = 'ISO-8859-1' #------------------------------------------------------------------------------# class PapovoxLikeServer(object): u"""Um servidor compatível com o Papovox.""" DEFAULT_HOST = '127.0.0.1' # Escuta apenas conexões locais PORTA_PAPOVOX = 1963 #PORTA_URGENTE = 1964 #PORTA_NOMES = 1956 DADOTECLADO = 1 # texto da mensagem (sem tab, nem lf nem cr ao final) TAMANHO_DO_BUFFER = 4096 # Ver C:\winvox\Fontes\tradutor\DVINET.PAS TAMANHO_MAXIMO_MSG = 255 def __init__(self, host=None, port=None): u"""Cria servidor compatível com o Papovox.""" # Socket do servidor self.server_socket = None # Host/interface de escuta self.host = host or self.DEFAULT_HOST # Porta do servidor self.port = port or self.PORTA_PAPOVOX # Socket do cliente self.socket = None # Endereço do cliente self.addr = None # Apelido self.nickname = u"" def connect(self): u"""Conecta ao Papovox via socket. Retorna booleano indicando se a conexão foi bem-sucedida. Bloqueia aguardando Papovox conectar. Define atributos: self.server_socket self.socket self.addr self.nickname """ try: self.server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) # Reutilizar porta já aberta #self.server_socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) self.server_socket.bind((self.host, self.port)) self.server_socket.listen(1) log.debug(u"XMPPVOX servindo em %s:%s", self.host, self.port) # Conecta ao Papovox ----------------------------------------------# try: self._accept() except socket.error: return False #------------------------------------------------------------------# return True except socket.error, e: log.error(safe_unicode(e.message) or u" ".join(map(safe_unicode, e.args))) sys.exit(1) def _accept(self): ur"""Aceita uma conexão via socket com o Papovox. Ver 'C:\winvox\Fontes\PAPOVOX\PPLIGA.PAS' e 'C:\winvox\Fontes\SITIOVOX\SVPROC.PAS'. """ log.info(u"Aguardando Papovox conectar...") self.socket, self.addr = self.server_socket.accept() self.sendline(u"+OK - %s:%s conectado" % self.addr) self.nickname = self.recvline(self.TAMANHO_DO_BUFFER) self.sendline(u"+OK") # Espera Papovox estar pronto para receber mensagens. # # A espera é necessária pois se enviar mensagens logo em seguida o Papovox # as ignora, provavelmente relacionado a alguma temporização ou espera na # leitura de algum buffer ou estado da variável global 'conversando'. # O SítioVox aguarda 100ms (arquivo SVPROC.PAS). time.sleep(0.1) log.info(u"Conectado ao Papovox.") log.debug(u"Apelido: %s", self.nickname) def disconnect(self): u"""Desliga a conexão com o Papovox.""" log.debug(u"Encerrando conexão com o Papovox...") try: self.socket.shutdown(socket.SHUT_RDWR) self.socket.close() except socket.error, e: log.debug("Client socket: %s", safe_unicode(e)) try: self.server_socket.shutdown(socket.SHUT_RDWR) self.server_socket.close() except socket.error, e: log.debug("Server socket: %s", safe_unicode(e)) # Funções de integração com o cliente XMPP --------------------------------# def process(self, xmpp): u"""Processa mensagens do Papovox para a rede XMPP. Mensagens podem conter comandos para o XMPPVOX. Nota: esta função só termina caso ocorra algum erro ou a conexão com o Papovox seja perdida. """ try: while True: data = self.recvmessage() # Tenta executar algum comando contido na mensagem. if commands.process_command(xmpp, data, self): # Caso algum comando seja executado, sai do loop e passa # para a próxima mensagem. continue else: # Caso contrário, envia a mensagem para a rede XMPP. self.send_xmpp_message(xmpp, data) except socket.error, e: log.debug(safe_unicode(e)) finally: log.info(u"Conexão com o Papovox encerrada.") def show_online_contacts(self, xmpp): u"""Envia para o Papovox informação sobre contatos disponíveis.""" online_contacts_count = len(commands.enumerate_online_roster(xmpp)) if online_contacts_count == 0: online_contacts_count = "nenhum" contacts = u"contato disponível" elif online_contacts_count == 1: contacts = u"contato disponível" else: contacts = u"contatos disponíveis" self.sendmessage(S.ONLINE_CONTACTS_INFO.format(amount=online_contacts_count, contacts=contacts)) def send_xmpp_message(self, xmpp, mbody): u"""Envia mensagem XMPP para quem está conversando comigo.""" if xmpp.talking_to is not None: mto = xmpp.talking_to # Envia mensagem XMPP. xmpp.send_message(mto=mto, mbody=mbody, mtype='chat') # Repete a mensagem que estou enviando para ser falada pelo Papovox. self.send_chat_message(u"eu", mbody) # Avisa se o contato estiver offline. bare_jid = xmpp.get_bare_jid(mto) roster = xmpp.client_roster if bare_jid in roster and not roster[bare_jid].resources: name = xmpp.get_chatty_name(mto) self.sendmessage(S.WARN_MSG_TO_OFFLINE_USER.format(name=name)) else: mto = u"ninguém" self.sendmessage(S.WARN_MSG_TO_NOBODY) log.debug(u"-> %(mto)s: %(mbody)s", locals()) # Funções de envio de dados para o Papovox --------------------------------# def sendline(self, line): u"""Codifica e envia texto via socket pelo protocolo do Papovox. Uma quebra de linha é adicionada automaticamente ao fim da mensagem. Nota: esta função *não* deve ser usada para enviar mensagens. Use apenas para transmitir dados brutos de comunicação. """ log.debug(u"> %s", line) line = line.encode(SYSTEM_ENCODING, 'replace') self.socket.sendall("%s\r\n" % (line,)) def sendmessage(self, msg): u"""Codifica e envia uma mensagem via socket pelo protocolo do Papovox.""" log.debug(u">> %s", msg) msg = msg.encode(SYSTEM_ENCODING, 'replace') # Apesar de teoricamente o protocolo do Papovox suportar mensagens com até # 65535 (2^16 - 1) caracteres, na prática apenas os 255 primeiros são # exibidos, e os restantes acabam ignorados. # Portanto, é necessário quebrar mensagens grandes em várias menores. chunks = textwrap.wrap( text=msg, width=self.TAMANHO_MAXIMO_MSG, expand_tabs=False, replace_whitespace=False, drop_whitespace=False, ) def sendmsg(msg): self.socket.sendall("%s%s" % (struct.pack('<BH', self.DADOTECLADO, len(msg)), msg)) # Envia uma ou mais mensagens pelo socket map(sendmsg, chunks) def send_chat_message(self, sender, body, _state={}): u"""Formata e envia uma mensagem de bate-papo via socket. Use esta função para enviar uma mensagem para o Papovox sintetizar. """ # Tempo máximo entre duas mensagens para considerar que fazem parte da mesma # conversa, em segundos. TIMEOUT = 90 # Recupera estado. last_sender = _state.get('last_sender') last_timestamp = _state.get('last_timestamp', 0) # em segundos timestamp = time.time() timed_out = (time.time() - last_timestamp) > TIMEOUT if sender == last_sender and not timed_out: msg = S.MSG else: msg = S.MSG_FROM self.sendmessage(msg.format(**locals())) # Guarda estado para ser usado na próxima execução. _state['last_sender'] = sender _state['last_timestamp'] = timestamp def signal_error(self, msg): u"""Sinaliza erro para o Papovox e termina a conexão.""" # Avisa Papovox sobre o erro. self.sendmessage(msg) # Encerra conexão com o Papovox. self.disconnect() # Funções de recebimento de dados do Papovox ------------------------------# def recv(self, size): u"""Recebe dados via socket. Use esta função para receber do socket `size' bytes ou menos. Levanta uma exceção caso nenhum byte seja recebido. Nota: em geral, use esta função ao invés do método 'socket.recv'. Veja também a função 'recvall'. """ data = self.socket.recv(size) if not data and size: raise socket.error(u"Nenhum dado recebido do socket, conexão perdida.") return data def recvline(self, size): u"""Recebe uma linha via socket. A string é retornada em unicode e não contém \r nem \n. """ # Assume que apenas uma linha está disponível no socket. data = self.recv(size).rstrip('\r\n') data = data.decode(SYSTEM_ENCODING) if any(c in data for c in '\r\n'): log.warning("Mais que uma linha recebida!") return data def recvall(self, size): u"""Recebe dados exaustivamente via socket. Use esta função para receber do socket exatamente `size' bytes. Levanta uma exceção caso nenhum byte seja recebido. Nota: em geral, use esta função ou 'recv' ao invés do método 'socket.recv'. """ data = StringIO() while data.tell() < size: data.write(self.recv(size - data.tell())) data_str = data.getvalue() data.close() return data_str def recvmessage(self): u"""Recebe uma mensagem via socket pelo protocolo do Papovox. A mensagem é retornada em unicode. Se uma exceção não for levantada, esta função sempre retorna uma mensagem. """ # Tenta receber mensagem até obter sucesso. while True: datatype, datalen = struct.unpack('<BH', self.recvall(3)) # Recusa dados do Papovox que não sejam do tipo DADOTECLADO if datatype != self.DADOTECLADO: log.warning(u"Tipo de dado desconhecido: (%d).", datatype) continue # Ignora mensagens vazias if datalen == 0: log.debug(u"Mensagem vazia ignorada") continue # Recebe dados/mensagem do Papovox data = self.recvall(datalen) data = data.decode(SYSTEM_ENCODING) return data # FIXME Remover referências hard-coded para comandos e o prefixo de comando.
rhcarvalho/xmppvox
xmppvox/server.py
Python
gpl-3.0
12,781
/** -*- mode: c++ ; c-basic-offset: 2 -*- * * @file SeparatorParameter.cpp * * Copyright 2017 Sebastien Fourey * * This file is part of G'MIC-Qt, a generic plug-in for raster graphics * editors, offering hundreds of filters thanks to the underlying G'MIC * image processing framework. * * gmic_qt 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. * * gmic_qt 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 gmic_qt. If not, see <http://www.gnu.org/licenses/>. * */ #include "SeparatorParameter.h" #include "Common.h" #include <QFrame> #include <QSizePolicy> #include <QGridLayout> SeparatorParameter::SeparatorParameter(QObject *parent) : AbstractParameter(parent,false), _frame(0) { } SeparatorParameter::~SeparatorParameter() { delete _frame; } void SeparatorParameter::addTo(QWidget * widget, int row) { QGridLayout * grid = dynamic_cast<QGridLayout*>(widget->layout()); if (! grid) return; delete _frame; _frame = new QFrame(widget); QSizePolicy sizePolicy(QSizePolicy::Preferred, QSizePolicy::Fixed); sizePolicy.setHorizontalStretch(0); sizePolicy.setVerticalStretch(0); sizePolicy.setHeightForWidth(_frame->sizePolicy().hasHeightForWidth()); _frame->setSizePolicy(sizePolicy); _frame->setFrameShape(QFrame::HLine); _frame->setFrameShadow(QFrame::Sunken); grid->addWidget(_frame,row,0,1,3); } QString SeparatorParameter::textValue() const { return QString::null; } void SeparatorParameter::setValue(const QString &) { } void SeparatorParameter::reset() { } void SeparatorParameter::initFromText(const char * text, int & textLength) { QStringList list = parseText("separator",text,textLength); unused(list); }
boudewijnrempt/gmic-qt
src/SeparatorParameter.cpp
C++
gpl-3.0
2,143
/*************************************************************************** * * * Copyright (C) 2017 Seamly, LLC * * * * https://github.com/fashionfreedom/seamly2d * * * *************************************************************************** ** ** Seamly2D 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. ** ** Seamly2D 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 Seamly2D. If not, see <http://www.gnu.org/licenses/>. ** ************************************************************************** ************************************************************************ ** ** @file VArcRadiusData.h ** @author Roman Telezhynskyi <dismine(at)gmail.com> ** @date 30 5, 2015 ** ** @brief ** @copyright ** This source code is part of the Valentine project, a pattern making ** program, whose allow create and modeling patterns of clothing. ** Copyright (C) 2015 Seamly2D project ** <https://github.com/fashionfreedom/seamly2d> All Rights Reserved. ** ** Seamly2D 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. ** ** Seamly2D 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 Seamly2D. If not, see <http://www.gnu.org/licenses/>. ** *************************************************************************/ #ifndef VARCRADIUSDATA_H #define VARCRADIUSDATA_H #include <QSharedData> #include "../vmisc/diagnostic.h" QT_WARNING_PUSH QT_WARNING_DISABLE_GCC("-Weffc++") QT_WARNING_DISABLE_GCC("-Wnon-virtual-dtor") class VArcRadiusData : public QSharedData { public: VArcRadiusData() :arcId(NULL_ID) {} VArcRadiusData(const quint32 &arcId) :arcId(arcId) {} VArcRadiusData(const VArcRadiusData &var) :QSharedData(var), arcId(var.arcId) {} virtual ~VArcRadiusData() Q_DECL_OVERRIDE; quint32 arcId; private: VArcRadiusData &operator=(const VArcRadiusData &) Q_DECL_EQ_DELETE; }; VArcRadiusData::~VArcRadiusData() {} QT_WARNING_POP #endif // VARCRADIUSDATA_H
FashionFreedom/Seamly2D
src/libs/vpatterndb/variables/varcradius_p.h
C
gpl-3.0
3,210
import urllib import urllib2 import json import time import hmac,hashlib def createTimeStamp(datestr, format="%Y-%m-%d %H:%M:%S"): return time.mktime(time.strptime(datestr, format)) class poloniex: def __init__(self, APIKey, Secret): self.APIKey = APIKey self.Secret = Secret def post_process(self, before): after = before # Add timestamps if there isnt one but is a datetime if('return' in after): if(isinstance(after['return'], list)): for x in xrange(0, len(after['return'])): if(isinstance(after['return'][x], dict)): if('datetime' in after['return'][x] and 'timestamp' not in after['return'][x]): after['return'][x]['timestamp'] = float(createTimeStamp(after['return'][x]['datetime'])) return after def api_query(self, command, req={}): if(command == "returnTicker" or command == "return24Volume"): ret = urllib2.urlopen(urllib2.Request('https://poloniex.com/public?command=' + command)) return json.loads(ret.read()) elif(command == "returnChartData"): ret = urllib2.urlopen(urllib2.Request('https://poloniex.com/public?command=' + command + '&currencyPair=' + str(req['currencyPair'] + '&start=' + str((int(time.time()) - req['chartDataAge'])) + '&period=' + str(300)))) return json.loads(ret.read()) elif(command == "returnOrderBook"): ret = urllib2.urlopen(urllib2.Request('https://poloniex.com/public?command=' + command + '&currencyPair=' + str(req['currencyPair']))) return json.loads(ret.read()) elif(command == "returnMarketTradeHistory"): ret = urllib2.urlopen(urllib2.Request('https://poloniex.com/public?command=' + "returnTradeHistory" + '&currencyPair=' + str(req['currencyPair']))) return json.loads(ret.read()) else: req['command'] = command req['nonce'] = int(time.time()*1000) post_data = urllib.urlencode(req) sign = hmac.new(self.Secret, post_data, hashlib.sha512).hexdigest() headers = { 'Sign': sign, 'Key': self.APIKey } ret = urllib2.urlopen(urllib2.Request('https://poloniex.com/tradingApi', post_data, headers)) jsonRet = json.loads(ret.read()) return self.post_process(jsonRet) def returnTicker(self): return self.api_query("returnTicker") def returnChartData(self, currencyPair, chartDataAge = 300): return self.api_query("returnChartData", {'currencyPair': currencyPair, 'chartDataAge' : chartDataAge}) def return24Volume(self): return self.api_query("return24Volume") def returnOrderBook (self, currencyPair): return self.api_query("returnOrderBook", {'currencyPair': currencyPair}) def returnMarketTradeHistory (self, currencyPair): return self.api_query("returnMarketTradeHistory", {'currencyPair': currencyPair}) # Returns all of your balances. # Outputs: # {"BTC":"0.59098578","LTC":"3.31117268", ... } def returnBalances(self): return self.api_query('returnBalances') # Returns your open orders for a given market, specified by the "currencyPair" POST parameter, e.g. "BTC_XCP" # Inputs: # currencyPair The currency pair e.g. "BTC_XCP" # Outputs: # orderNumber The order number # type sell or buy # rate Price the order is selling or buying at # Amount Quantity of order # total Total value of order (price * quantity) def returnOpenOrders(self,currencyPair): return self.api_query('returnOpenOrders',{"currencyPair":currencyPair}) # Returns your trade history for a given market, specified by the "currencyPair" POST parameter # Inputs: # currencyPair The currency pair e.g. "BTC_XCP" # Outputs: # date Date in the form: "2014-02-19 03:44:59" # rate Price the order is selling or buying at # amount Quantity of order # total Total value of order (price * quantity) # type sell or buy def returnTradeHistory(self,currencyPair): return self.api_query('returnTradeHistory',{"currencyPair":currencyPair}) # Places a buy order in a given market. Required POST parameters are "currencyPair", "rate", and "amount". If successful, the method will return the order number. # Inputs: # currencyPair The curreny pair # rate price the order is buying at # amount Amount of coins to buy # Outputs: # orderNumber The order number def buy(self,currencyPair,rate,amount): return self.api_query('buy',{"currencyPair":currencyPair,"rate":rate,"amount":amount}) # Places a sell order in a given market. Required POST parameters are "currencyPair", "rate", and "amount". If successful, the method will return the order number. # Inputs: # currencyPair The curreny pair # rate price the order is selling at # amount Amount of coins to sell # Outputs: # orderNumber The order number def sell(self,currencyPair,rate,amount): return self.api_query('sell',{"currencyPair":currencyPair,"rate":rate,"amount":amount}) # Cancels an order you have placed in a given market. Required POST parameters are "currencyPair" and "orderNumber". # Inputs: # currencyPair The curreny pair # orderNumber The order number to cancel # Outputs: # succes 1 or 0 def cancel(self,currencyPair,orderNumber): return self.api_query('cancelOrder',{"currencyPair":currencyPair,"orderNumber":orderNumber}) # Immediately places a withdrawal for a given currency, with no email confirmation. In order to use this method, the withdrawal privilege must be enabled for your API key. Required POST parameters are "currency", "amount", and "address". Sample output: {"response":"Withdrew 2398 NXT."} # Inputs: # currency The currency to withdraw # amount The amount of this coin to withdraw # address The withdrawal address # Outputs: # response Text containing message about the withdrawal def withdraw(self, currency, amount, address): return self.api_query('withdraw',{"currency":currency, "amount":amount, "address":address})
Vadus/eldo
src/poloniex/poloniex.py
Python
gpl-3.0
6,502
<?php if(isset($_GET['id'])) { // Allocate a new XSLT processor $xh = xslt_create(); // Process the document if (xslt_process($xh, "xml/audio/$id", "xsl/audio/audio.xsl", "gen/audio/$id.xml")) { readfile("gen/audio/$id.xml"); } else { echo "Error : " . xslt_error($xh) . " and the "; echo "error code is " . xslt_errno($xh); } xslt_free($xh); } ?>
astorije/projet-nf29-a10
export_html/p_audio.php
PHP
gpl-3.0
395
package com.androidGames.lettersoup; import java.io.IOException; import java.io.InputStream; import org.json.JSONException; import org.json.JSONObject; import android.os.Build; import android.os.Bundle; import android.annotation.SuppressLint; import android.app.Activity; import android.graphics.Canvas; import android.graphics.Color; import android.graphics.Paint; import android.graphics.Paint.Style; import android.graphics.drawable.ColorDrawable; import android.util.Log; import android.view.Menu; import android.view.View; import android.view.MenuItem; import android.view.MotionEvent; import android.view.View.OnTouchListener; import android.widget.FrameLayout; import android.widget.GridView; import android.widget.TextView; import android.widget.Toast; import android.support.v4.app.NavUtils; public class PlayGameActivity extends Activity { private char[][] boardGame; PlayGameView playgameview; private String puzzle = ""; FrameLayout layout; Paint paint; private float width; private float height; private float x; private float y; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_play_game); //Get the JSON object from the data JSONObject parent = this.parseJSONData(); paint = new Paint(); paint.setAlpha(255); paint.setColor(Color.BLUE); paint.setStyle(Style.STROKE); paint.setStrokeWidth(5); /*//THis will store all the values inside "Hydrogen" in a element string try { String element = parent.getString("Nivel1"); } catch (JSONException e) { // TODO Auto-generated catch block e.printStackTrace(); }*/ //THis will store "1" inside atomicNumber try { puzzle = parent.getJSONObject("Nivel1").getString("Puzzle"); } catch (JSONException e) { // TODO Auto-generated catch block e.printStackTrace(); } Log.d("onCreate", "oncreate"); Log.w("onCreate", "oncreate"); this.boardGame = board(4,5); this.boardGame = fillBoardGame(puzzle,this.boardGame); Log.d("onCreate", ""+this.boardGame ); final GridView gridView = (GridView) findViewById(R.id.playgamegrid); gridView.setNumColumns(4); gridView.setAdapter(new PlayGameViewAdapter(this,this.getBoard())); gridView.setOnTouchListener(new OnTouchListener() { String text=""; int pos = 0; @SuppressWarnings("unused") protected void onDraw(Canvas canvas) { canvas.drawLine(x, y, width, height, paint); } @Override public boolean onTouch(View v, MotionEvent event) { // TODO Auto-generated method stub float currentXPosition = event.getX(); float currentYPosition = event.getY(); int position = gridView.pointToPosition((int) currentXPosition, (int) currentYPosition); TextView tv = (TextView) gridView.getChildAt(position); width = tv.getWidth(); height = tv.getHeight(); switch(event.getAction()) { case MotionEvent.ACTION_DOWN: pos = position; text += tv.getText(); //tv.setBackgroundColor(Color.RED); return true; case MotionEvent.ACTION_MOVE: if(pos != position) { x=event.getX(); y=event.getY(); pos = position; text += tv.getText(); } gridView.invalidateViews(); //adapter.notifyDataChanged(); //grid.setAdapter(adapter); return true; case MotionEvent.ACTION_UP: getWordBoard(text); return true; } return false; } }); /*PlayGameView playgameview = new PlayGameView(this); setContentView(playgameview); playgameview.requestFocus();*/ //RelativeLayout game = (RelativeLayout)findViewById(R.id.layoutgame); //game.addView(playgameview); if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) { // Show the Up button in the action bar. setupActionBar(); } } /** * Set up the {@link android.app.ActionBar}. */ private void setupActionBar() { getActionBar().setDisplayHomeAsUpEnabled(true); } @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate(R.menu.play_game, menu); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()) { case android.R.id.home: // This ID represents the Home or Up button. In the case of this // activity, the Up button is shown. Use NavUtils to allow users // to navigate up one level in the application structure. For // more details, see the Navigation pattern on Android Design: // // http://developer.android.com/design/patterns/navigation.html#up-vs-back // NavUtils.navigateUpFromSameTask(this); return true; } return super.onOptionsItemSelected(item); } public char[][] board(int x, int y) { final char board[][] = new char [x][y]; return board; } public char[][] fillBoardGame(String string,char[][] board) { int indexString=0; int nCols = this.getColsBoard(); int nRows = this.getRowsBoard(); for (int i = 0; i < nRows; i++) { for(int k = 0; k<nCols;k++) { this.boardGame[i][k] = string.charAt(indexString); indexString++; } Log.d("fillBoard", ""+this.boardGame[i][0]); } return this.boardGame; } public String getcharBoard(int x, int y){ StringBuilder charBoard = new StringBuilder(); Log.d("getcharBoard", ""+this.boardGame[x][y]); charBoard.append(this.boardGame[x][y]); return charBoard.toString(); } public int getColsBoard() { Log.d("numCols",""+this.boardGame[0].length); return this.boardGame[0].length; } public int getRowsBoard(){ Log.d("numRows",""+this.boardGame.length); return this.boardGame.length; } public String[] getBoard() { final String[] texts = new String[puzzle.length()]; for(int i=0;i<puzzle.length();i++) { texts[i]=""+puzzle.charAt(i); } return texts; } public JSONObject parseJSONData() { String JSONString = null; JSONObject JSONObject = null; try { //open the inputStream to the file InputStream inputStream = getAssets().open("PuzzleStore.json"); int sizeOfJSONFile = inputStream.available(); //array that will store all the data byte[] bytes = new byte[sizeOfJSONFile]; //reading data into the array from the file inputStream.read(bytes); //close the input stream inputStream.close(); JSONString = new String(bytes, "UTF-8"); JSONObject = new JSONObject(JSONString); } catch (IOException ex) { ex.printStackTrace(); return null; } catch (JSONException x) { x.printStackTrace(); return null; } return JSONObject; } public void getWordBoard(String caracter) { String word = caracter; Log.d("Word",word); } }
papoon/sopa_letras
LetterSoup/src/com/androidGames/lettersoup/PlayGameActivity.java
Java
gpl-3.0
7,386
/*! * Ext JS Library * Copyright(c) 2006-2014 Sencha Inc. * licensing@sencha.com * http://www.sencha.com/license */ Ext.define('Ext.org.micoli.app.modules.GridWindow', { extend: 'Ext.ux.desktop.Module', requires: [ 'Ext.data.ArrayStore', 'Ext.util.Format', 'Ext.grid.Panel', 'Ext.grid.RowNumberer' ], id:'grid-win', init : function(){ this.launcher = { text: 'Grid Window', iconCls:'icon-grid' }; }, createWindow : function(){ var desktop = this.app.getDesktop(); var win = desktop.getWindow('grid-win'); if(!win){ win = desktop.createWindow({ id: 'grid-win', title:'Grid Window', width:740, height:480, iconCls: 'icon-grid', animCollapse:false, constrainHeader:true, layout: 'fit', items: [ { border: false, xtype: 'grid', store: new Ext.data.ArrayStore({ fields: [ { name: 'company' }, { name: 'price', type: 'float' }, { name: 'change', type: 'float' }, { name: 'pctChange', type: 'float' } ], data: Ext.org.micoli.app.modules.GridWindow.getDummyData() }), columns: [ new Ext.grid.RowNumberer(), { text: "Company", flex: 1, sortable: true, dataIndex: 'company' }, { text: "Price", width: 70, sortable: true, renderer: Ext.util.Format.usMoney, dataIndex: 'price' }, { text: "Change", width: 70, sortable: true, dataIndex: 'change' }, { text: "% Change", width: 70, sortable: true, dataIndex: 'pctChange' } ] } ], tbar:[{ text:'Add Something', tooltip:'Add a new row', iconCls:'add' }, '-', { text:'Options', tooltip:'Modify options', iconCls:'option' },'-',{ text:'Remove Something', tooltip:'Remove the selected item', iconCls:'remove' }] }); } return win; }, statics: { getDummyData: function () { return [ ['3m Co',71.72,0.02,0.03], ['Alcoa Inc',29.01,0.42,1.47], ['American Express Company',52.55,0.01,0.02], ['American International Group, Inc.',64.13,0.31,0.49], ['AT&T Inc.',31.61,-0.48,-1.54], ['Caterpillar Inc.',67.27,0.92,1.39], ['Citigroup, Inc.',49.37,0.02,0.04], ['Exxon Mobil Corp',68.1,-0.43,-0.64], ['General Electric Company',34.14,-0.08,-0.23], ['General Motors Corporation',30.27,1.09,3.74], ['Hewlett-Packard Co.',36.53,-0.03,-0.08], ['Honeywell Intl Inc',38.77,0.05,0.13], ['Intel Corporation',19.88,0.31,1.58], ['Johnson & Johnson',64.72,0.06,0.09], ['Merck & Co., Inc.',40.96,0.41,1.01], ['Microsoft Corporation',25.84,0.14,0.54], ['The Coca-Cola Company',45.07,0.26,0.58], ['The Procter & Gamble Company',61.91,0.01,0.02], ['Wal-Mart Stores, Inc.',45.45,0.73,1.63], ['Walt Disney Company (The) (Holding Company)',29.89,0.24,0.81] ]; } } });
micoli/reQuester
desk6/app/org/micoli/app/modules/samples/GridWindow.js
JavaScript
gpl-3.0
3,137
// Boost Includes ============================================================== #include <boost/python.hpp> #include <boost/cstdint.hpp> // Includes ==================================================================== #include <spuc/raised_cosine_imp.h> // Using ======================================================================= using namespace boost::python; // Module ====================================================================== BOOST_PYTHON_MODULE(raised_cosine_imp) { def("raised_cosine_imp", &SPUC::raised_cosine_imp); }
sav6622/spuc
pyste/raised_cosine_imp.cpp
C++
gpl-3.0
552
/* === This file is part of Tomahawk Player - <http://tomahawk-player.org> === * * Copyright 2010-2011, Leo Franchi <lfranchi@kde.org> * * Tomahawk 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. * * Tomahawk 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 Tomahawk. If not, see <http://www.gnu.org/licenses/>. */ #include "TransferStatusItem.h" #include "network/StreamConnection.h" #include "network/Servent.h" #include "utils/TomahawkUtils.h" #include "utils/TomahawkUtilsGui.h" #include "Artist.h" #include "JobStatusModel.h" #include "JobStatusView.h" #include "Result.h" #include "Source.h" #include "Track.h" TransferStatusItem::TransferStatusItem( TransferStatusManager* p, StreamConnection* sc ) : m_parent( p ) , m_stream( QPointer< StreamConnection >( sc ) ) { if ( m_stream.data()->type() == StreamConnection::RECEIVING ) m_type = "receive"; else m_type = "send"; connect( m_stream.data(), SIGNAL( updated() ), SLOT( onTransferUpdate() ) ); connect( Servent::instance(), SIGNAL( streamFinished( StreamConnection* ) ), SLOT( streamFinished( StreamConnection* ) ) ); } TransferStatusItem::~TransferStatusItem() { } QString TransferStatusItem::mainText() const { if ( m_stream.isNull() ) return QString(); if ( m_stream.data()->source().isNull() && !m_stream.data()->track().isNull() ) return QString( "%1" ).arg( QString( "%1 - %2" ).arg( m_stream.data()->track()->track()->artist() ).arg( m_stream.data()->track()->track()->track() ) ); else if ( !m_stream.data()->source().isNull() && !m_stream.data()->track().isNull() ) return QString( "%1 %2 %3" ).arg( QString( "%1 - %2" ).arg( m_stream.data()->track()->track()->artist() ).arg( m_stream.data()->track()->track()->track() ) ) .arg( m_stream.data()->type() == StreamConnection::RECEIVING ? tr( "from", "streaming artist - track from friend" ) : tr( "to", "streaming artist - track to friend" ) ) .arg( m_stream.data()->source()->friendlyName() ); else return QString(); } QString TransferStatusItem::rightColumnText() const { if ( m_stream.isNull() ) return QString(); return QString( "%1 kB/s" ).arg( m_stream.data()->transferRate() / 1000 ); } void TransferStatusItem::streamFinished( StreamConnection* sc ) { if ( m_stream.data() == sc ) emit finished(); } QPixmap TransferStatusItem::icon() const { if ( m_stream.isNull() ) return QPixmap(); if ( m_stream.data()->type() == StreamConnection::SENDING ) return m_parent->txPixmap(); else return m_parent->rxPixmap(); } void TransferStatusItem::onTransferUpdate() { emit statusChanged(); } TransferStatusManager::TransferStatusManager( QObject* parent ) : QObject( parent ) { connect( Servent::instance(), SIGNAL( streamStarted( StreamConnection* ) ), SLOT( streamRegistered( StreamConnection* ) ) ); } void TransferStatusManager::streamRegistered( StreamConnection* sc ) { JobStatusView::instance()->model()->addJob( new TransferStatusItem( this, sc ) ); } QPixmap TransferStatusManager::rxPixmap() const { return TomahawkUtils::defaultPixmap( TomahawkUtils::Downloading, TomahawkUtils::Original, QSize( 128, 128 ) ); } QPixmap TransferStatusManager::txPixmap() const { return TomahawkUtils::defaultPixmap( TomahawkUtils::Uploading, TomahawkUtils::Original, QSize( 128, 128 ) ); }
tomahawk-player/tomahawk
src/libtomahawk/jobview/TransferStatusItem.cpp
C++
gpl-3.0
3,947
/*************************************************************************** * Copyright (C) 2006 by Esteban Zeller & Daniel Sequeira * * juiraze@yahoo.com.ar - daniels@hotmail.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. * ***************************************************************************/ #include "resumenanual.h" #include "visorresumenes.h" #include <QTextCursor> #include <QLocale> #include <QDate> #include <QSqlQuery> #include <QSqlRecord> #include <QSqlError> #include <QTextTable> #include <QFile> resumenAnual::resumenAnual(QObject *parent) : QObject(parent) { } resumenAnual::~resumenAnual() { }
tranfuga25s/gestotux
plugins/digifauno/resumenanual.cpp
C++
gpl-3.0
1,754
/* * ice4j, the OpenSource Java Solution for NAT and Firewall Traversal. * Maintained by the SIP Communicator community (http://sip-communicator.org). * * Distributable under LGPL license. * See terms of license at gnu.org. */ package org.ice4j.socket; import java.net.*; import org.ice4j.*; import org.ice4j.message.*; /** * Implements a <tt>DatagramPacketFilter</tt> which accepts * <tt>DatagramPacket</tt>s which represent TURN messages defined in * RFC 5766 "Traversal Using Relays around NAT (TURN): Relay Extensions to * Session Traversal Utilities for NAT (STUN)" and which are part of the * communication with a specific TURN server. <tt>TurnDatagramPacketFilter</tt> * does not accept TURN ChannelData messages because they require knowledge of * the value of the "Channel Number" field. * * @author Lubomir Marinov */ public class TurnDatagramPacketFilter extends StunDatagramPacketFilter { /** * Initializes a new <tt>TurnDatagramPacketFilter</tt> which will accept * <tt>DatagramPacket</tt>s which represent TURN messages and which are part * of the communication with a specific TURN server. * * @param turnServer the <tt>TransportAddress</tt> of the TURN server * <tt>DatagramPacket</tt>s representing TURN messages from and to which * will be accepted by the new instance */ public TurnDatagramPacketFilter(TransportAddress turnServer) { super(turnServer); } /** * Determines whether a specific <tt>DatagramPacket</tt> represents a TURN * message which is part of the communication with the TURN server * associated with this instance. * * @param p the <tt>DatagramPacket</tt> to be checked whether it represents * a TURN message which is part of the communicator with the TURN server * associated with this instance * @return <tt>true</tt> if the specified <tt>DatagramPacket</tt> represents * a TURN message which is part of the communication with the TURN server * associated with this instance; otherwise, <tt>false</tt> */ @Override public boolean accept(DatagramPacket p) { if (super.accept(p)) { /* * The specified DatagramPacket represents a STUN message with a * TURN method. */ return true; } else { /* * The specified DatagramPacket does not come from or is not being * sent to the TURN server associated with this instance or is a * ChannelData message which is not supported by * TurnDatagramPacketFilter. */ return false; } } /** * Determines whether this <tt>DatagramPacketFilter</tt> accepts a * <tt>DatagramPacket</tt> which represents a STUN message with a specific * STUN method. <tt>TurnDatagramPacketFilter</tt> accepts TURN methods. * * @param method the STUN method of a STUN message represented by a * <tt>DatagramPacket</tt> to be checked whether it is accepted by this * <tt>DatagramPacketFilter</tt> * @return <tt>true</tt> if this <tt>DatagramPacketFilter</tt> accepts the * <tt>DatagramPacket</tt> which represents a STUN message with the * specified STUN method; otherwise, <tt>false</tt> * @see StunDatagramPacketFilter#acceptMethod(char) */ @Override protected boolean acceptMethod(char method) { if (super.acceptMethod(method)) return true; else { switch (method) { case Message.TURN_METHOD_ALLOCATE: case Message.TURN_METHOD_CHANNELBIND: case Message.TURN_METHOD_CREATEPERMISSION: case Message.TURN_METHOD_DATA: case Message.TURN_METHOD_REFRESH: case Message.TURN_METHOD_SEND: case 0x0005: /* old TURN DATA indication */ return true; default: return false; } } } }
ziah/Friends-Module
ice4j-lib/org/ice4j/socket/TurnDatagramPacketFilter.java
Java
gpl-3.0
4,068
/** * @file mt_cpufreq.c * @brief Driver for CPU DVFS * */ #define __MT_CPUFREQ_C__ /*=============================================================*/ /* Include files */ /*=============================================================*/ /* system includes */ #include <linux/kernel.h> #include <linux/module.h> #include <linux/sched.h> #include <linux/init.h> #include <linux/cpu.h> #include <linux/cpufreq.h> #include <linux/delay.h> #include <linux/slab.h> #include <linux/proc_fs.h> #include <linux/miscdevice.h> #include <linux/platform_device.h> #include <linux/earlysuspend.h> #include <linux/spinlock.h> #include <linux/kthread.h> #include <linux/hrtimer.h> #include <linux/ktime.h> #include <linux/xlog.h> #include <linux/jiffies.h> #include <linux/bitops.h> #include <linux/uaccess.h> #include <linux/aee.h> #ifdef CONFIG_OF #include <linux/of.h> #include <linux/of_address.h> #endif /* project includes */ #include "mach/mt_typedefs.h" #include "mach/irqs.h" #include "mach/mt_irq.h" #include "mach/mt_thermal.h" #include "mach/mt_spm_idle.h" #include "mach/mt_pmic_wrap.h" #include "mach/mt_clkmgr.h" #include "mt_freqhopping.h" #include "mach/mt_spm.h" #include "mach/mt_ptp.h" // TODO: disable to avoid build error (Brian) //#include "mach/mt_static_power.h" #include "mach/upmu_sw.h" #include "mach/mtk_rtc_hal.h" #include "mach/mt_rtc_hw.h" #include "mach/mt_hotplug_strategy.h" #ifndef __KERNEL__ #include "freqhop_sw.h" #include <mt_spm.h> #endif /* local includes */ #include "mach/mt_cpufreq.h" /* forward references */ extern int is_ext_buck_sw_ready(void); // TODO: ask James to provide the head file extern int ext_buck_vosel(unsigned long val); // TODO: ask James to provide the head file extern int da9210_read_byte(kal_uint8 cmd, kal_uint8 *ret_data); // TODO: ask James to provide the head file //wait for james extern u32 get_devinfo_with_index(u32 index); //extern int mtktscpu_get_Tj_temp(void); // TODO: ask Jerry to provide the head file extern void (*cpufreq_freq_check)(enum mt_cpu_dvfs_id id); // Freq Meter API #ifdef __KERNEL__ extern unsigned int mt_get_cpu_freq(void); #endif /*=============================================================*/ /* Macro definition */ /*=============================================================*/ /* * CONFIG */ #define CONFIG_CPU_DVFS_SHOWLOG 1 //#define CONFIG_CPU_DVFS_BRINGUP 1 /* for bring up */ //#define CONFIG_CPU_DVFS_FFTT_TEST 1 /* FF TT SS volt test */ //#define CONFIG_CPU_DVFS_DOWNGRADE_FREQ 1 /* downgrade freq */ #define CONFIG_CPU_DVFS_POWER_THROTTLING 1 /* power throttling features */ // #define CONFIG_CPU_DVFS_RAMP_DOWN 1 /* ramp down to slow down freq change */ #ifdef CONFIG_MTK_RAM_CONSOLE #define CONFIG_CPU_DVFS_AEE_RR_REC 1 /* AEE SRAM debugging */ #endif #define MAX(a, b) ((a) >= (b) ? (a) : (b)) #define MIN(a, b) ((a) >= (b) ? (b) : (a)) /* used @ set_cur_volt_extBuck() */ #define PMIC_SETTLE_TIME(old_mv, new_mv) ((((old_mv) > (new_mv)) ? ((old_mv) - (new_mv)) : ((new_mv) - (old_mv))) * 2 / 2500 + 25 + 1) /* us, PMIC settle time, should not be changed */ // (((((old_mv) > (new_mv)) ? ((old_mv) - (new_mv)) : ((new_mv) - (old_mv))) + 9 ) / 10) //#define MIN_DIFF_VSRAM_PROC 1000 /* 10mv * 100 */ #define NORMAL_DIFF_VRSAM_VPROC 10000 /* 100mv * 100 */ #define MAX_DIFF_VSRAM_VPROC 20000 /* 200mv * 100 */ #define MIN_VSRAM_VOLT 93000 /* 931.25mv * 100 */ #define MAX_VSRAM_VOLT 115000 /* 1150mv * 100 */ #define MAX_VPROC_VOLT 115000 /* 1150mv * 100 */ /* PMIC/PLL settle time (us), should not be changed */ #define PMIC_CMD_DELAY_TIME 5 #define MIN_PMIC_SETTLE_TIME 25 #define PMIC_VOLT_UP_SETTLE_TIME(old_volt, new_volt) (((((new_volt) - (old_volt)) + 1250 - 1) / 1250) + PMIC_CMD_DELAY_TIME) #define PMIC_VOLT_DOWN_SETTLE_TIME(old_volt, new_volt) (((((old_volt) - (new_volt)) * 2) / 625) + PMIC_CMD_DELAY_TIME) #define PLL_SETTLE_TIME (20) #define RAMP_DOWN_TIMES (2) /* RAMP DOWN TIMES to postpone frequency degrade */ #define CPUFREQ_BOUNDARY_FOR_FHCTL (CPU_DVFS_FREQ5) /* if cross 1183MHz when DFS, don't used FHCTL */ #define DEFAULT_VOLT_VSRAM (105000) #define DEFAULT_VOLT_VLTE (100000) #define DEFAULT_VOLT_VGPU (100000) #define DEFAULT_VOLT_SOC (100000) /* for DVFS OPP table */ #define CPU_DVFS_FREQ0 (1846000) /* KHz */ #define CPU_DVFS_FREQ1 (1677000) /* KHz */ #define CPU_DVFS_FREQ2 (1547000) /* KHz */ #define CPU_DVFS_FREQ3 (1417000) /* KHz */ #define CPU_DVFS_FREQ4 (1300000) /* KHz */ #define CPU_DVFS_FREQ5 (1183000) /* KHz */ #define CPU_DVFS_FREQ6 (806000) /* KHz */ #define CPU_DVFS_FREQ7 (403000) /* KHz */ #define CPUFREQ_LAST_FREQ_LEVEL (CPU_DVFS_FREQ7) #define CPU_DVFS_FREQ0_1 (1950000) /* KHz */ #define CPU_DVFS_FREQ1_1 (1781000) /* KHz */ #define CPU_DVFS_FREQ2_1 (1625000) /* KHz */ #define CPU_DVFS_FREQ3_1 (1469000) /* KHz */ #define CPU_DVFS_FREQ4_1 (1326000) /* KHz */ #define CPU_DVFS_FREQ5_1 (1183000) /* KHz */ #define CPU_DVFS_FREQ6_1 (806000) /* KHz */ #define CPU_DVFS_FREQ7_1 (403000) /* KHz */ #define CPUFREQ_LAST_FREQ1_LEVEL (CPU_DVFS_FREQ7_1) #define CPU_DVFS_FREQ0_2 (2158000) /* KHz */ #define CPU_DVFS_FREQ1_2 (1885000) /* KHz */ #define CPU_DVFS_FREQ2_2 (1664000) /* KHz */ #define CPU_DVFS_FREQ3_2 (1482000) /* KHz */ #define CPU_DVFS_FREQ4_2 (1326000) /* KHz */ #define CPU_DVFS_FREQ5_2 (1183000) /* KHz */ #define CPU_DVFS_FREQ6_2 (806000) /* KHz */ #define CPU_DVFS_FREQ7_2 (403000) /* KHz */ #define CPUFREQ_LAST_FREQ2_LEVEL (CPU_DVFS_FREQ7_2) // TODO: NEED to check power throttling settings #ifdef CONFIG_CPU_DVFS_POWER_THROTTLING #define PWR_THRO_MODE_LBAT_806MHZ BIT(0) #define PWR_THRO_MODE_BAT_OC_1183MHZ BIT(1) #define PWR_THRO_MODE_BAT_PER_806MHZ BIT(2) #define CPU_DVFS_OPPIDX_1183MHZ 5 #define CPU_DVFS_OPPIDX_806MHZ 6 #endif /* * LOG and Test */ #undef TAG #define TAG "[Power/cpufreq] " #define cpufreq_err(fmt, args...) \ pr_err(TAG KERN_CONT "[ERROR]"fmt, ##args) #define cpufreq_warn(fmt, args...) \ pr_warn(TAG KERN_CONT "[WARNING]"fmt, ##args) #define cpufreq_info(fmt, args...) \ pr_warn(TAG KERN_CONT fmt, ##args) #define cpufreq_dbg(fmt, args...) \ pr_debug(TAG KERN_CONT fmt, ##args) #define cpufreq_ver(fmt, args...) \ do { \ if (func_lv_mask) \ cpufreq_info(TAG KERN_CONT fmt, ##args); \ } while (0) #define FUNC_LV_MODULE BIT(0) /* module, platform driver interface */ #define FUNC_LV_CPUFREQ BIT(1) /* cpufreq driver interface */ #define FUNC_LV_API BIT(2) /* mt_cpufreq driver global function */ #define FUNC_LV_LOCAL BIT(3) /* mt_cpufreq driver local function */ #define FUNC_LV_HELP BIT(4) /* mt_cpufreq driver help function */ //static unsigned int func_lv_mask = (FUNC_LV_MODULE | FUNC_LV_CPUFREQ | FUNC_LV_API | FUNC_LV_LOCAL | FUNC_LV_HELP); static unsigned int func_lv_mask = 0; static unsigned int do_dvfs_stress_test = 0; #ifdef CONFIG_CPU_DVFS_SHOWLOG #define FUNC_ENTER(lv) do { if ((lv) & func_lv_mask) cpufreq_dbg(">> %s()\n", __func__); } while (0) #define FUNC_EXIT(lv) do { if ((lv) & func_lv_mask) cpufreq_dbg("<< %s():%d\n", __func__, __LINE__); } while (0) #else #define FUNC_ENTER(lv) #define FUNC_EXIT(lv) #endif /* CONFIG_CPU_DVFS_SHOWLOG */ /* * BIT Operation */ #define _BIT_(_bit_) (unsigned)(1 << (_bit_)) #define _BITS_(_bits_, _val_) ((((unsigned) -1 >> (31 - ((1) ? _bits_))) & ~((1U << ((0) ? _bits_)) - 1)) & ((_val_)<<((0) ? _bits_))) #define _BITMASK_(_bits_) (((unsigned) -1 >> (31 - ((1) ? _bits_))) & ~((1U << ((0) ? _bits_)) - 1)) #define _GET_BITS_VAL_(_bits_, _val_) (((_val_) & (_BITMASK_(_bits_))) >> ((0) ? _bits_)) /* * REG ACCESS */ #define cpufreq_read(addr) DRV_Reg32(addr) #define cpufreq_write(addr, val) mt_reg_sync_writel(val, addr) #define cpufreq_write_mask(addr, mask, val) cpufreq_write(addr, (cpufreq_read(addr) & ~(_BITMASK_(mask))) | _BITS_(mask, val)) /*=============================================================*/ /* Local type definition */ /*=============================================================*/ /*=============================================================*/ /* Local variable definition */ /*=============================================================*/ /*=============================================================*/ /* Local function definition */ /*=============================================================*/ /*=============================================================*/ /* Gobal function definition */ /*=============================================================*/ /* * LOCK */ #if 0 /* spinlock */ // TODO: FIXME, it would cause warning @ big because of i2c access with atomic operation static DEFINE_SPINLOCK(cpufreq_lock); #define cpufreq_lock(flags) spin_lock_irqsave(&cpufreq_lock, flags) #define cpufreq_unlock(flags) spin_unlock_irqrestore(&cpufreq_lock, flags) #else /* mutex */ DEFINE_MUTEX(cpufreq_mutex); bool is_in_cpufreq = 0; #define cpufreq_lock(flags) \ do { \ /* to fix compile warning */ \ flags = (unsigned long)&flags; \ mutex_lock(&cpufreq_mutex); \ is_in_cpufreq = 1;\ spm_mcdi_wakeup_all_cores();\ } while (0) #define cpufreq_unlock(flags) \ do { \ /* to fix compile warning */ \ flags = (unsigned long)&flags; \ is_in_cpufreq = 0;\ mutex_unlock(&cpufreq_mutex); \ } while (0) #endif int max_power_budget = 9999; /* * EFUSE */ #define CPUFREQ_EFUSE_INDEX (3) #define FUNC_CODE_EFUSE_INDEX (28) #define CPU_LEVEL_0 (0x0) #define CPU_LEVEL_1 (0x1) #define CPU_LEVEL_2 (0x2) #define CPU_LV_TO_OPP_IDX(lv) ((lv)) /* cpu_level to opp_idx */ unsigned int AllowTurboMode = 0; #ifdef __KERNEL__ static unsigned int _mt_cpufreq_get_cpu_level(void) { unsigned int lv = 0; /* get CPU clock-frequency from DT */ #ifdef CONFIG_OF { struct device_node *node = of_find_node_by_type(NULL, "cpu"); unsigned int cpu_speed = 0; unsigned int seg_code = get_devinfo_with_index(24); unsigned int seg2_code = get_devinfo_with_index(25);//25:23 unsigned int seg2_code_result = 0; unsigned int turbo_code = get_devinfo_with_index(5); if (!of_property_read_u32(node, "clock-frequency", &cpu_speed)) cpu_speed = cpu_speed / 1000 / 1000; // MHz else { cpufreq_err("@%s: missing clock-frequency property, use default CPU level\n", __func__); return CPU_LEVEL_1; } //cpufreq_info("CPU clock-frequency from DT = %d MHz\n", cpu_speed); switch (cpu_speed) { case 1846: lv = CPU_LEVEL_0; // 1.82G not used break; case 2000: lv = CPU_LEVEL_1; // 1.95G break; case 2200: lv = CPU_LEVEL_2; // 2.158G break; default: lv = CPU_LEVEL_1; // 1.95G M break; } switch (_GET_BITS_VAL_(31 : 24, seg_code)) { case 0x0B: case 0x0C: case 0x0E: case 0x0F: lv = CPU_LEVEL_2; // 2.158G break; case 0x10: lv = CPU_LEVEL_0; // 1.846G break; case 0x0: seg2_code_result = _GET_BITS_VAL_(25 : 23, seg2_code); if (seg2_code_result == 0x01) lv = CPU_LEVEL_2; // 2.158G break; case 0x06: case 0x01: case 0x03: default: break; } if ((turbo_code >> 29) & 0x1) AllowTurboMode = 1; } #endif return lv; } #else static unsigned int _mt_cpufreq_get_cpu_level(void) { return CPU_LEVEL_1; } #endif /* * AEE (SRAM debug) */ #ifdef CONFIG_CPU_DVFS_AEE_RR_REC enum cpu_dvfs_state { CPU_DVFS_LITTLE_IS_DOING_DVFS = 0, CPU_DVFS_LITTLE_IS_TURBO, CPU_DVFS_BIG_IS_DOING_DVFS = 0, CPU_DVFS_BIG_IS_TURBO, }; extern void aee_rr_rec_cpu_dvfs_vproc_big(u8 val); extern void aee_rr_rec_cpu_dvfs_vproc_little(u8 val); extern void aee_rr_rec_cpu_dvfs_oppidx(u8 val); extern u8 aee_rr_curr_cpu_dvfs_oppidx(void); extern void aee_rr_rec_cpu_dvfs_status(u8 val); extern u8 aee_rr_curr_cpu_dvfs_status(void); static void _mt_cpufreq_aee_init(void) { aee_rr_rec_cpu_dvfs_vproc_big(0xFF); aee_rr_rec_cpu_dvfs_vproc_little(0xFF); aee_rr_rec_cpu_dvfs_oppidx(0xFF); aee_rr_rec_cpu_dvfs_status(0xFF); } #endif /* * PMIC_WRAP */ // TODO: defined @ pmic head file??? #define VOLT_TO_PMIC_VAL(volt) (((volt) - 70000 + 625 - 1) / 625) //((((volt) - 700 * 100 + 625 - 1) / 625) #define PMIC_VAL_TO_VOLT(pmic) (((pmic) * 625) + 70000) //(((pmic) * 625) / 100 + 700) #define VOLT_TO_EXTBUCK_VAL(volt) (((((volt) - 300) + 9) / 10) & 0x7F) //no use, reg_val = ((((val*10)-300000)/1000)+9)/10; #define EXTBUCK_VAL_TO_VOLT(val) (300 + ((val) & 0x7F) * 10) /* PMIC WRAP ADDR */ // TODO: include other head file #ifdef CONFIG_OF extern void __iomem *pwrap_base; #define PWRAP_BASE_ADDR ((unsigned long)pwrap_base) #else #include "mach/mt_reg_base.h" #define PWRAP_BASE_ADDR PWRAP_BASE//0x1000D000 #endif #define PMIC_WRAP_DVFS_ADR0 (PWRAP_BASE_ADDR + 0x0E8) #define PMIC_WRAP_DVFS_WDATA0 (PWRAP_BASE_ADDR + 0x0EC) #define PMIC_WRAP_DVFS_ADR1 (PWRAP_BASE_ADDR + 0x0F0) #define PMIC_WRAP_DVFS_WDATA1 (PWRAP_BASE_ADDR + 0x0F4) #define PMIC_WRAP_DVFS_ADR2 (PWRAP_BASE_ADDR + 0x0F8) #define PMIC_WRAP_DVFS_WDATA2 (PWRAP_BASE_ADDR + 0x0FC) #define PMIC_WRAP_DVFS_ADR3 (PWRAP_BASE_ADDR + 0x100) #define PMIC_WRAP_DVFS_WDATA3 (PWRAP_BASE_ADDR + 0x104) #define PMIC_WRAP_DVFS_ADR4 (PWRAP_BASE_ADDR + 0x108) #define PMIC_WRAP_DVFS_WDATA4 (PWRAP_BASE_ADDR + 0x10C) #define PMIC_WRAP_DVFS_ADR5 (PWRAP_BASE_ADDR + 0x110) #define PMIC_WRAP_DVFS_WDATA5 (PWRAP_BASE_ADDR + 0x114) #define PMIC_WRAP_DVFS_ADR6 (PWRAP_BASE_ADDR + 0x118) #define PMIC_WRAP_DVFS_WDATA6 (PWRAP_BASE_ADDR + 0x11C) #define PMIC_WRAP_DVFS_ADR7 (PWRAP_BASE_ADDR + 0x120) #define PMIC_WRAP_DVFS_WDATA7 (PWRAP_BASE_ADDR + 0x124) /* PMIC ADDR */ // TODO: include other head file //LTE #define PMIC_ADDR_VPROC_CA7_VOSEL_ON 0x847C /* [6:0] */ #define PMIC_ADDR_VPROC_CA7_VOSEL_SLEEP 0x847E /* [6:0] */ #define PMIC_ADDR_VPROC_CA7_EN 0x8476 /* [0] (shared with others) */ //VSRAM #define PMIC_ADDR_VSRAM_CA7_FAST_TRSN_EN 0x8CB4 /* [3] */ #define PMIC_ADDR_VSRAM_CA7_EN 0x8CBC /* [10] (shared with others) */ #define PMIC_ADDR_VSRAM_VOSEL_ON 0x8492 /* [6:0] HW mode ON */ //NO USE - BIG CPU #define PMIC_ADDR_VSRAM_CA15L_VOSEL_ON 0x0264 /* [6:0] */ #define PMIC_ADDR_VSRAM_CA15L_VOSEL_SLEEP 0x0266 /* [6:0] */ #define PMIC_ADDR_VSRAM_CA15L_FAST_TRSN_EN 0x051C /* [6] */ #define PMIC_ADDR_VSRAM_CA15L_EN 0x0524 /* [10] (shared with others) */ //VGPU #define PMIC_ADDR_VGPU_VOSEL_ON 0x02B0 /* [6:0] */ #define PMIC_ADDR_VGPU_VOSEL_SLEEP 0x02B2 /* [6:0] */ //NO USE - VCORE AO #define PMIC_ADDR_VCORE_AO_VOSEL_ON 0x036C /* [6:0] */ #define PMIC_ADDR_VCORE_AO_VOSEL_SLEEP 0x036E /* [6:0] */ //VCORE PDN #define PMIC_ADDR_VCORE_PDN_VOSEL_ON 0x024E /* [6:0] */ #define PMIC_ADDR_VCORE_PDN_VOSEL_SLEEP 0x0250 /* [6:0] */ #define PMIC_ADDR_VCORE_PDN_EN_CTRL 0x0244 /* [0] (shared with others) */ #define NR_PMIC_WRAP_CMD 8 /* num of pmic wrap cmd (fixed value) */ struct pmic_wrap_cmd { unsigned long cmd_addr; unsigned long cmd_wdata; }; struct pmic_wrap_setting { enum pmic_wrap_phase_id phase; struct pmic_wrap_cmd addr[NR_PMIC_WRAP_CMD]; struct { struct { unsigned long cmd_addr; unsigned long cmd_wdata; } _[NR_PMIC_WRAP_CMD]; const int nr_idx; } set[NR_PMIC_WRAP_PHASE]; }; static struct pmic_wrap_setting pw = { .phase = NR_PMIC_WRAP_PHASE, /* invalid setting for init */ #if 0 .addr = { { PMIC_WRAP_DVFS_ADR0, PMIC_WRAP_DVFS_WDATA0, }, { PMIC_WRAP_DVFS_ADR1, PMIC_WRAP_DVFS_WDATA1, }, { PMIC_WRAP_DVFS_ADR2, PMIC_WRAP_DVFS_WDATA2, }, { PMIC_WRAP_DVFS_ADR3, PMIC_WRAP_DVFS_WDATA3, }, { PMIC_WRAP_DVFS_ADR4, PMIC_WRAP_DVFS_WDATA4, }, { PMIC_WRAP_DVFS_ADR5, PMIC_WRAP_DVFS_WDATA5, }, { PMIC_WRAP_DVFS_ADR6, PMIC_WRAP_DVFS_WDATA6, }, { PMIC_WRAP_DVFS_ADR7, PMIC_WRAP_DVFS_WDATA7, }, }, #else .addr = { {0, 0} }, #endif .set[PMIC_WRAP_PHASE_NORMAL] = { ._[IDX_NM_VSRAM_CA7] = { PMIC_ADDR_VSRAM_VOSEL_ON, VOLT_TO_PMIC_VAL(DEFAULT_VOLT_VSRAM), }, ._[IDX_NM_VPROC_CA7] = { PMIC_ADDR_VPROC_CA7_VOSEL_ON, VOLT_TO_PMIC_VAL(DEFAULT_VOLT_VLTE), }, ._[IDX_NM_VGPU] = { PMIC_ADDR_VGPU_VOSEL_ON, VOLT_TO_PMIC_VAL(DEFAULT_VOLT_VGPU), }, ._[IDX_NM_VCORE_PDN] = { PMIC_ADDR_VCORE_PDN_VOSEL_ON , VOLT_TO_PMIC_VAL(DEFAULT_VOLT_SOC), }, .nr_idx = NR_IDX_NM, }, .set[PMIC_WRAP_PHASE_SUSPEND] = { ._[IDX_SP_VSRAM_CA7_PWR_ON] = { PMIC_ADDR_VSRAM_CA7_EN, _BITS_(11 : 10, 1) | _BIT_(8), }, /* RG_VSRAM_DVFS2_ON_CTRL = 1'b0, RG_VSRAM_DVFS2_EN = 1'b1, RG_VSRAM_DVFS2_STBTD = 1'b1 */ ._[IDX_SP_VSRAM_CA7_SHUTDOWN] = { PMIC_ADDR_VSRAM_CA7_EN, _BITS_(11 : 10, 0) | _BIT_(8), }, /* RG_VSRAM_DVFS2_ON_CTRL = 1'b0, RG_VSRAM_DVFS2_EN = 1'b0, RG_VSRAM_DVFS2_STBTD = 1'b1 */ .nr_idx = NR_IDX_SP, }, .set[PMIC_WRAP_PHASE_DEEPIDLE] = { ._[IDX_DI_VSRAM_CA7_NORMAL] = { PMIC_ADDR_VSRAM_VOSEL_ON, VOLT_TO_PMIC_VAL(100000), }, ._[IDX_DI_VSRAM_CA7_SLEEP] = { PMIC_ADDR_VSRAM_VOSEL_ON, VOLT_TO_PMIC_VAL(93000), }, ._[IDX_DI_VSRAM_CA7_FAST_TRSN_EN] = { PMIC_ADDR_VSRAM_CA7_FAST_TRSN_EN, _BITS_(3 : 3, 0), }, ._[IDX_DI_VSRAM_CA7_FAST_TRSN_DIS] = { PMIC_ADDR_VSRAM_CA7_FAST_TRSN_EN, _BITS_(3 : 3, 1), }, ._[IDX_DI_VPROC_CA7_NORMAL] = { PMIC_ADDR_VPROC_CA7_VOSEL_ON, VOLT_TO_PMIC_VAL(112500), }, ._[IDX_DI_VPROC_CA7_SLEEP] = { PMIC_ADDR_VPROC_CA7_VOSEL_ON, VOLT_TO_PMIC_VAL(90000), }, ._[IDX_DI_VCORE_PDN_NORMAL] = { PMIC_ADDR_VCORE_PDN_VOSEL_ON, VOLT_TO_PMIC_VAL(112500), }, ._[IDX_DI_VCORE_PDN_SLEEP] = { PMIC_ADDR_VCORE_PDN_VOSEL_ON, VOLT_TO_PMIC_VAL(90000), }, .nr_idx = NR_IDX_DI, }, .set[PMIC_WRAP_PHASE_SODI] = { ._[IDX_SO_VSRAM_CA7_NORMAL] = { PMIC_ADDR_VSRAM_VOSEL_ON, VOLT_TO_PMIC_VAL(100000), }, ._[IDX_SO_VSRAM_CA7_SLEEP] = { PMIC_ADDR_VSRAM_VOSEL_ON, VOLT_TO_PMIC_VAL(93000), }, ._[IDX_SO_VSRAM_CA7_FAST_TRSN_EN] = { PMIC_ADDR_VSRAM_CA7_FAST_TRSN_EN, _BITS_(3 : 3, 0), }, ._[IDX_SO_VSRAM_CA7_FAST_TRSN_DIS] = { PMIC_ADDR_VSRAM_CA7_FAST_TRSN_EN, _BITS_(3 : 3, 1), }, ._[IDX_SO_VPROC_CA7_NORMAL] = { PMIC_ADDR_VPROC_CA7_VOSEL_ON, VOLT_TO_PMIC_VAL(112500), }, ._[IDX_SO_VPROC_CA7_SLEEP] = { PMIC_ADDR_VPROC_CA7_VOSEL_ON, VOLT_TO_PMIC_VAL(90000), }, ._[IDX_SO_VCORE_PDN_NORMAL] = { PMIC_ADDR_VCORE_PDN_VOSEL_ON, VOLT_TO_PMIC_VAL(112500), }, ._[IDX_SO_VCORE_PDN_SLEEP] = { PMIC_ADDR_VCORE_PDN_VOSEL_ON, VOLT_TO_PMIC_VAL(90000), }, .nr_idx = NR_IDX_SO, }, }; #if 1 /* spinlock */ static DEFINE_SPINLOCK(pmic_wrap_lock); #define pmic_wrap_lock(flags) spin_lock_irqsave(&pmic_wrap_lock, flags) #define pmic_wrap_unlock(flags) spin_unlock_irqrestore(&pmic_wrap_lock, flags) #else /* mutex */ static DEFINE_MUTEX(pmic_wrap_mutex); #define pmic_wrap_lock(flags) \ do { \ /* to fix compile warning */ \ flags = (unsigned long)&flags; \ mutex_lock(&pmic_wrap_mutex); \ } while (0) #define pmic_wrap_unlock(flags) \ do { \ /* to fix compile warning */ \ flags = (unsigned long)&flags; \ mutex_unlock(&pmic_wrap_mutex); \ } while (0) #endif static int _spm_dvfs_ctrl_volt(u32 value) { #define MAX_RETRY_COUNT (100) u32 ap_dvfs_con; int retry = 0; FUNC_ENTER(FUNC_LV_HELP); spm_write(SPM_POWERON_CONFIG_SET, (SPM_PROJECT_CODE << 16) | (1U << 0)); // TODO: FIXME ap_dvfs_con = spm_read(SPM_AP_DVFS_CON_SET); spm_write(SPM_AP_DVFS_CON_SET, (ap_dvfs_con & ~(0x7)) | value); udelay(5); while ((spm_read(SPM_AP_DVFS_CON_SET) & (0x1 << 31)) == 0) { if (retry >= MAX_RETRY_COUNT) { cpufreq_err("FAIL: no response from PMIC wrapper\n"); return -1; } retry++; //cpufreq_dbg("wait for ACK signal from PMIC wrapper, retry = %d\n", retry); udelay(5); } FUNC_EXIT(FUNC_LV_HELP); return 0; } void _mt_cpufreq_pmic_table_init(void) { struct pmic_wrap_cmd pwrap_cmd_default[NR_PMIC_WRAP_CMD] = { { PMIC_WRAP_DVFS_ADR0, PMIC_WRAP_DVFS_WDATA0, }, { PMIC_WRAP_DVFS_ADR1, PMIC_WRAP_DVFS_WDATA1, }, { PMIC_WRAP_DVFS_ADR2, PMIC_WRAP_DVFS_WDATA2, }, { PMIC_WRAP_DVFS_ADR3, PMIC_WRAP_DVFS_WDATA3, }, { PMIC_WRAP_DVFS_ADR4, PMIC_WRAP_DVFS_WDATA4, }, { PMIC_WRAP_DVFS_ADR5, PMIC_WRAP_DVFS_WDATA5, }, { PMIC_WRAP_DVFS_ADR6, PMIC_WRAP_DVFS_WDATA6, }, { PMIC_WRAP_DVFS_ADR7, PMIC_WRAP_DVFS_WDATA7, }, }; FUNC_ENTER(FUNC_LV_HELP); memcpy(pw.addr, pwrap_cmd_default, sizeof(pwrap_cmd_default)); FUNC_EXIT(FUNC_LV_HELP); } void mt_cpufreq_set_pmic_phase(enum pmic_wrap_phase_id phase) { int i; unsigned long flags; FUNC_ENTER(FUNC_LV_API); BUG_ON(phase >= NR_PMIC_WRAP_PHASE); #if 0 // TODO: FIXME, check IPO-H case if (pw.phase == phase) return; #endif if (pw.addr[0].cmd_addr == 0) { cpufreq_warn("pmic table not initialized\n"); _mt_cpufreq_pmic_table_init(); } pmic_wrap_lock(flags); pw.phase = phase; for (i = 0; i < pw.set[phase].nr_idx; i++) { cpufreq_write(pw.addr[i].cmd_addr, pw.set[phase]._[i].cmd_addr); cpufreq_write(pw.addr[i].cmd_wdata, pw.set[phase]._[i].cmd_wdata); } pmic_wrap_unlock(flags); FUNC_EXIT(FUNC_LV_API); } EXPORT_SYMBOL(mt_cpufreq_set_pmic_phase); void mt_cpufreq_set_pmic_cmd(enum pmic_wrap_phase_id phase, int idx, unsigned int cmd_wdata) /* just set wdata value */ { unsigned long flags; FUNC_ENTER(FUNC_LV_API); BUG_ON(phase >= NR_PMIC_WRAP_PHASE); BUG_ON(idx >= pw.set[phase].nr_idx); //cpufreq_dbg("@%s: phase = 0x%x, idx = %d, cmd_wdata = 0x%x\n", __func__, phase, idx, cmd_wdata); pmic_wrap_lock(flags); pw.set[phase]._[idx].cmd_wdata = cmd_wdata; if (pw.phase == phase) cpufreq_write(pw.addr[idx].cmd_wdata, cmd_wdata); pmic_wrap_unlock(flags); FUNC_EXIT(FUNC_LV_API); } EXPORT_SYMBOL(mt_cpufreq_set_pmic_cmd); void mt_cpufreq_apply_pmic_cmd(int idx) /* kick spm */ { unsigned long flags; FUNC_ENTER(FUNC_LV_API); BUG_ON(idx >= pw.set[pw.phase].nr_idx); //cpufreq_dbg("@%s: idx = %d\n", __func__, idx); pmic_wrap_lock(flags); _spm_dvfs_ctrl_volt(idx); pmic_wrap_unlock(flags); FUNC_EXIT(FUNC_LV_API); } EXPORT_SYMBOL(mt_cpufreq_apply_pmic_cmd); /* cpu voltage sampler */ static cpuVoltsampler_func g_pCpuVoltSampler = NULL; void mt_cpufreq_setvolt_registerCB(cpuVoltsampler_func pCB) { g_pCpuVoltSampler = pCB; } EXPORT_SYMBOL(mt_cpufreq_setvolt_registerCB); /* for PTP-OD */ unsigned int mt_get_cur_volt_lte(void) { unsigned int rdata; FUNC_ENTER(FUNC_LV_LOCAL); pwrap_read(PMIC_ADDR_VPROC_CA7_VOSEL_ON, &rdata); rdata = PMIC_VAL_TO_VOLT(rdata); FUNC_EXIT(FUNC_LV_LOCAL); return rdata; /* mv * 100 : CA7 vproc(LTE) */ } EXPORT_SYMBOL(mt_get_cur_volt_lte); unsigned int mt_set_cur_volt_lte(unsigned int pmic_val) { mt_cpufreq_set_pmic_cmd(PMIC_WRAP_PHASE_DEEPIDLE, IDX_DI_VPROC_CA7_NORMAL, pmic_val); mt_cpufreq_set_pmic_cmd(PMIC_WRAP_PHASE_SODI, IDX_SO_VPROC_CA7_NORMAL, pmic_val); mt_cpufreq_set_pmic_cmd(PMIC_WRAP_PHASE_NORMAL, IDX_NM_VPROC_CA7, pmic_val); mt_cpufreq_apply_pmic_cmd(IDX_NM_VPROC_CA7); return 0; } EXPORT_SYMBOL(mt_set_cur_volt_lte); unsigned int mt_set_cur_volt_vcore_pdn(unsigned int pmic_val) { mt_cpufreq_set_pmic_cmd(PMIC_WRAP_PHASE_DEEPIDLE, IDX_DI_VCORE_PDN_NORMAL, pmic_val); mt_cpufreq_set_pmic_cmd(PMIC_WRAP_PHASE_SODI, IDX_SO_VCORE_PDN_NORMAL, pmic_val); mt_cpufreq_set_pmic_cmd(PMIC_WRAP_PHASE_NORMAL, IDX_NM_VCORE_PDN, pmic_val); mt_cpufreq_apply_pmic_cmd(IDX_NM_VCORE_PDN); return 0; } EXPORT_SYMBOL(mt_set_cur_volt_vcore_pdn); unsigned int mt_get_cur_volt_vcore_pdn(void) { unsigned int rdata; FUNC_ENTER(FUNC_LV_LOCAL); pwrap_read(PMIC_ADDR_VCORE_PDN_VOSEL_ON, &rdata); rdata = PMIC_VAL_TO_VOLT(rdata); FUNC_EXIT(FUNC_LV_LOCAL); return rdata; /* mv: vproc */ } EXPORT_SYMBOL(mt_get_cur_volt_vcore_pdn); /* for Vcore DVFS - wait for Terry */ void mt_vcore_dvfs_disable_by_sdio(unsigned int type, bool disabled) { // empty function } void mt_vcore_dvfs_volt_set_by_sdio(unsigned int volt) /* unit: mv x 1000 */ { unsigned int cur_pmic_val_vcore_pdn; unsigned int target_pmic_val_vcore_pdn; int step; FUNC_ENTER(FUNC_LV_LOCAL); pwrap_read(PMIC_ADDR_VCORE_PDN_VOSEL_ON, &cur_pmic_val_vcore_pdn); target_pmic_val_vcore_pdn = VOLT_TO_PMIC_VAL(volt / 10); // mv * 100 step = (target_pmic_val_vcore_pdn > cur_pmic_val_vcore_pdn) ? 1 : -1; while (target_pmic_val_vcore_pdn != cur_pmic_val_vcore_pdn) { cur_pmic_val_vcore_pdn += step; mt_cpufreq_set_pmic_cmd(PMIC_WRAP_PHASE_NORMAL, IDX_NM_VCORE_PDN, cur_pmic_val_vcore_pdn); mt_cpufreq_apply_pmic_cmd(IDX_NM_VCORE_PDN); udelay(4); } FUNC_EXIT(FUNC_LV_LOCAL); } unsigned int mt_vcore_dvfs_volt_get_by_sdio(void) /* unit: mv x 1000 */ { return mt_get_cur_volt_vcore_pdn() * 10; } /* * mt_cpufreq driver */ #define OP(khz, volt) { \ .cpufreq_khz = khz, \ .cpufreq_volt = volt, \ .cpufreq_volt_org = volt, \ } #define for_each_cpu_dvfs(i, p) for (i = 0, p = cpu_dvfs; i < NR_MT_CPU_DVFS; i++, p = &cpu_dvfs[i]) #define cpu_dvfs_is(p, id) (p == &cpu_dvfs[id]) #define cpu_dvfs_is_availiable(p) (p->opp_tbl) #define cpu_dvfs_get_name(p) (p->name) #define cpu_dvfs_get_cur_freq(p) (p->opp_tbl[p->idx_opp_tbl].cpufreq_khz) #define cpu_dvfs_get_freq_by_idx(p, idx) (p->opp_tbl[idx].cpufreq_khz) #define cpu_dvfs_get_max_freq(p) (p->opp_tbl[0].cpufreq_khz) #define cpu_dvfs_get_normal_max_freq(p) (p->opp_tbl[p->idx_normal_max_opp].cpufreq_khz) #define cpu_dvfs_get_min_freq(p) (p->opp_tbl[p->nr_opp_tbl - 1].cpufreq_khz) #define cpu_dvfs_get_cur_volt(p) (p->opp_tbl[p->idx_opp_tbl].cpufreq_volt) #define cpu_dvfs_get_volt_by_idx(p, idx) (p->opp_tbl[idx].cpufreq_volt) //#define cpu_dvfs_is_extbuck_valid() (is_ext_buck_exist() && is_ext_buck_sw_ready()) #define cpu_dvfs_is_extbuck_valid() is_ext_buck_sw_ready() struct mt_cpu_freq_info { const unsigned int cpufreq_khz; unsigned int cpufreq_volt; // mv * 100 unsigned int cpufreq_volt_org; // mv * 100 }; struct mt_cpu_power_info { unsigned int cpufreq_khz; unsigned int cpufreq_ncpu; unsigned int cpufreq_power; }; struct mt_cpu_dvfs { const char *name; unsigned int cpu_id; /* for cpufreq */ unsigned int cpu_level; struct mt_cpu_dvfs_ops *ops; /* opp (freq) table */ struct mt_cpu_freq_info *opp_tbl; /* OPP table */ int nr_opp_tbl; /* size for OPP table */ int idx_opp_tbl; /* current OPP idx */ int idx_normal_max_opp; /* idx for normal max OPP */ int idx_opp_tbl_for_late_resume; /* keep the setting for late resume */ struct cpufreq_frequency_table *freq_tbl_for_cpufreq; /* freq table for cpufreq */ /* power table */ struct mt_cpu_power_info *power_tbl; unsigned int nr_power_tbl; /* enable/disable DVFS function */ int dvfs_disable_count; bool dvfs_disable_by_ptpod; bool dvfs_disable_by_suspend; bool dvfs_disable_by_early_suspend; bool dvfs_disable_by_procfs; /* limit for thermal */ unsigned int limited_max_ncpu; unsigned int limited_max_freq; unsigned int idx_opp_tbl_for_thermal_thro; unsigned int thermal_protect_limited_power; /* limit for HEVC (via. sysfs) */ unsigned int limited_freq_by_hevc; /* limit max freq from user */ unsigned int limited_max_freq_by_user; /* for ramp down */ int ramp_down_count; int ramp_down_count_const; /* param for micro throttling */ bool downgrade_freq_for_ptpod; int over_max_cpu; int ptpod_temperature_limit_1; int ptpod_temperature_limit_2; int ptpod_temperature_time_1; int ptpod_temperature_time_2; int pre_online_cpu; unsigned int pre_freq; unsigned int downgrade_freq; unsigned int downgrade_freq_counter; unsigned int downgrade_freq_counter_return; unsigned int downgrade_freq_counter_limit; unsigned int downgrade_freq_counter_return_limit; /* turbo mode */ unsigned int turbo_mode; /* power throttling */ #ifdef CONFIG_CPU_DVFS_POWER_THROTTLING int idx_opp_tbl_for_pwr_thro; /* keep the setting for power throttling */ int idx_pwr_thro_max_opp; /* idx for power throttle max OPP */ unsigned int pwr_thro_mode; #endif }; struct mt_cpu_dvfs_ops { /* for thermal */ void (*protect)(struct mt_cpu_dvfs *p, unsigned int limited_power); /* set power limit by thermal */ // TODO: sync with mt_cpufreq_thermal_protect() unsigned int (*get_temp)(struct mt_cpu_dvfs *p); /* return temperature */ // TODO: necessary??? int (*setup_power_table)(struct mt_cpu_dvfs *p); /* for freq change (PLL/MUX) */ unsigned int (*get_cur_phy_freq)(struct mt_cpu_dvfs *p); /* return (physical) freq (KHz) */ void (*set_cur_freq)(struct mt_cpu_dvfs *p, unsigned int cur_khz, unsigned int target_khz); /* set freq */ /* for volt change (PMICWRAP/extBuck) */ unsigned int (*get_cur_volt)(struct mt_cpu_dvfs *p); /* return volt (mV * 100) */ int (*set_cur_volt)(struct mt_cpu_dvfs *p, unsigned int volt); /* set volt (mv * 100), return 0 (success), -1 (fail) */ }; /* for thermal */ static int setup_power_table(struct mt_cpu_dvfs *p); /* for freq change (PLL/MUX) */ static unsigned int get_cur_phy_freq(struct mt_cpu_dvfs *p); static void set_cur_freq(struct mt_cpu_dvfs *p, unsigned int cur_khz, unsigned int target_khz); /* for volt change (PMICWRAP/extBuck) */ static unsigned int get_cur_volt_extbuck(struct mt_cpu_dvfs *p); static int set_cur_volt_extbuck(struct mt_cpu_dvfs *p, unsigned int volt); // volt: mv * 100 static unsigned int max_cpu_num = 8; /* for limited_max_ncpu, it will be modified at driver initialization stage if needed */ static struct mt_cpu_dvfs_ops dvfs_ops_extbuck = { .setup_power_table = setup_power_table, .get_cur_phy_freq = get_cur_phy_freq, .set_cur_freq = set_cur_freq, .get_cur_volt = get_cur_volt_extbuck, .set_cur_volt = set_cur_volt_extbuck, }; static struct mt_cpu_dvfs cpu_dvfs[] = { [MT_CPU_DVFS_LITTLE] = { .name = __stringify(MT_CPU_DVFS_LITTLE), .cpu_id = MT_CPU_DVFS_LITTLE, // TODO: FIXME .cpu_level = CPU_LEVEL_1, // 1.95GHz .ops = &dvfs_ops_extbuck, // TODO: check the following settings .over_max_cpu = 8, // 4 .ptpod_temperature_limit_1 = 110000, .ptpod_temperature_limit_2 = 120000, .ptpod_temperature_time_1 = 1, .ptpod_temperature_time_2 = 4, .pre_online_cpu = 0, .pre_freq = 0, .downgrade_freq = 0, .downgrade_freq_counter = 0, .downgrade_freq_counter_return = 0, .downgrade_freq_counter_limit = 0, .downgrade_freq_counter_return_limit = 0, .ramp_down_count_const = RAMP_DOWN_TIMES, .turbo_mode = 0, #ifdef CONFIG_CPU_DVFS_POWER_THROTTLING .idx_opp_tbl_for_pwr_thro = -1, .idx_pwr_thro_max_opp = 0, #endif }, }; static struct mt_cpu_dvfs *id_to_cpu_dvfs(enum mt_cpu_dvfs_id id) { return (id < NR_MT_CPU_DVFS) ? &cpu_dvfs[id] : NULL; } /* DVFS OPP table */ /* Notice: Each table MUST has 8 element to avoid ptpod error */ #define NR_MAX_OPP_TBL 8 #define NR_MAX_CPU 8 #if 0 /* 1.82GHz segment must Turbo*/ static struct mt_cpu_freq_info opp_tbl_e1_0[] = { OP(CPU_DVFS_FREQ0, 112500), OP(CPU_DVFS_FREQ1, 110000), OP(CPU_DVFS_FREQ2, 106875), OP(CPU_DVFS_FREQ3, 104375), OP(CPU_DVFS_FREQ4, 101875), OP(CPU_DVFS_FREQ5, 99375), OP(CPU_DVFS_FREQ6, 91250), OP(CPU_DVFS_FREQ7, 82500), }; #else static struct mt_cpu_freq_info opp_tbl_e1_0[] = { OP(CPU_DVFS_FREQ0, 115000), OP(CPU_DVFS_FREQ1, 111875), OP(CPU_DVFS_FREQ2, 108750), OP(CPU_DVFS_FREQ3, 106250), OP(CPU_DVFS_FREQ4, 103125), OP(CPU_DVFS_FREQ5, 100000), OP(CPU_DVFS_FREQ6, 91875),//91875 OP(CPU_DVFS_FREQ7, 90000),//82500 }; #endif #if 0 /* 1.95GHz segment */ static struct mt_cpu_freq_info opp_tbl_e1_1[] = { OP(CPU_DVFS_FREQ0_1, 115000), OP(CPU_DVFS_FREQ1_1, 111875), OP(CPU_DVFS_FREQ2_1, 108125), OP(CPU_DVFS_FREQ3_1, 105000), OP(CPU_DVFS_FREQ4_1, 101875), OP(CPU_DVFS_FREQ5_1, 98750), OP(CPU_DVFS_FREQ6_1, 90625), OP(CPU_DVFS_FREQ7_1, 82500), }; #else /* 1.95GHz segment */ static struct mt_cpu_freq_info opp_tbl_e1_1[] = { OP(CPU_DVFS_FREQ0_1, 115000), OP(CPU_DVFS_FREQ1_1, 111875), OP(CPU_DVFS_FREQ2_1, 108125), OP(CPU_DVFS_FREQ3_1, 105000), OP(CPU_DVFS_FREQ4_1, 101875), OP(CPU_DVFS_FREQ5_1, 98750), OP(CPU_DVFS_FREQ6_1, 90625), OP(CPU_DVFS_FREQ7_1, 90000), }; #endif #if 0 /* 2.158GHz segment */ static struct mt_cpu_freq_info opp_tbl_e1_2[] = { OP(CPU_DVFS_FREQ0_2, 115000), OP(CPU_DVFS_FREQ1_2, 110000), OP(CPU_DVFS_FREQ2_2, 106250), OP(CPU_DVFS_FREQ3_2, 102500), OP(CPU_DVFS_FREQ4_2, 99375), OP(CPU_DVFS_FREQ5_2, 96875), OP(CPU_DVFS_FREQ6_2, 89375), OP(CPU_DVFS_FREQ7_2, 81875), }; #else /* 2.158GHz segment */ static struct mt_cpu_freq_info opp_tbl_e1_2[] = { OP(CPU_DVFS_FREQ0_2, 115000), OP(CPU_DVFS_FREQ1_2, 110000), OP(CPU_DVFS_FREQ2_2, 106250), OP(CPU_DVFS_FREQ3_2, 102500), OP(CPU_DVFS_FREQ4_2, 99375), OP(CPU_DVFS_FREQ5_2, 96875), OP(CPU_DVFS_FREQ6_2, 90000),//89375 OP(CPU_DVFS_FREQ7_2, 90000),//81875 }; #endif struct opp_tbl_info { struct mt_cpu_freq_info *const opp_tbl; const int size; }; #define ARRAY_AND_SIZE(x) (x), ARRAY_SIZE(x) static struct opp_tbl_info opp_tbls[] = { [CPU_LV_TO_OPP_IDX(CPU_LEVEL_0)] = { ARRAY_AND_SIZE(opp_tbl_e1_0), }, [CPU_LV_TO_OPP_IDX(CPU_LEVEL_1)] = { ARRAY_AND_SIZE(opp_tbl_e1_1), }, [CPU_LV_TO_OPP_IDX(CPU_LEVEL_2)] = { ARRAY_AND_SIZE(opp_tbl_e1_2), }, }; /* for freq change (PLL/MUX) */ #define PLL_FREQ_STEP (13000) /* KHz */ //#define PLL_MAX_FREQ (1989000) /* KHz */ // TODO: check max freq //#define PLL_MIN_FREQ (130000) /* KHz */ #define PLL_DIV1_FREQ (1612000) /* KHz */ #define PLL_FREQ5_FREQ (1183000) /* KHz */ #define PLL_DIV2_FREQ (806000) /* KHz */ //#define PLL_DIV4_FREQ (260000) /* KHz */ //#define PLL_DIV8_FREQ (PLL_MIN_FREQ) /* KHz */ #define DDS_DIV1_FREQ (0x000F8000) /* 1612MHz */ #define DDS_FREQ5_FREQ (0x000B6000) /* 1183MHz */ #define DDS_DIV2_FREQ (0x010F8000) /* 806MHz */ //#define DDS_DIV4_FREQ (0x020A0000) /* 260MHz */ //#define DDS_DIV8_FREQ (0x030A0000) /* 130MHz */ /* for turbo mode */ #define TURBO_MODE_BOUNDARY_CPU_NUM 2 /* idx sort by temp from low to high */ enum turbo_mode { TURBO_MODE_2, TURBO_MODE_1, TURBO_MODE_NONE, NR_TURBO_MODE, }; /* idx sort by temp from low to high */ struct turbo_mode_cfg { int temp; /* degree x 1000 */ int freq_delta; /* percentage */ int volt_delta; /* mv * 100 */ } turbo_mode_cfg[] = { [TURBO_MODE_2] = { .temp = 65000, .freq_delta = 10, .volt_delta = 2500, }, [TURBO_MODE_1] = { .temp = 85000, .freq_delta = 5, .volt_delta = 1250, }, [TURBO_MODE_NONE] = { .temp = 125000, .freq_delta = 0, .volt_delta = 0, }, }; #define TURBO_MODE_FREQ(mode, freq) (((freq * (100 + turbo_mode_cfg[mode].freq_delta)) / PLL_FREQ_STEP) / 100 * PLL_FREQ_STEP) #define TURBO_MODE_VOLT(mode, volt) (volt + turbo_mode_cfg[mode].volt_delta) static unsigned int num_online_cpus_delta = 0; static enum turbo_mode get_turbo_mode(struct mt_cpu_dvfs *p, unsigned int target_khz) { enum turbo_mode mode = TURBO_MODE_NONE; int temp = tscpu_get_temp_by_bank(THERMAL_BANK0); // bank0 for CPU unsigned int online_cpus = num_online_cpus() + num_online_cpus_delta; int i; if (p->turbo_mode && target_khz == cpu_dvfs_get_freq_by_idx(p, 0) && online_cpus <= TURBO_MODE_BOUNDARY_CPU_NUM ) { for (i = 0; i < NR_TURBO_MODE; i++) { if (temp < turbo_mode_cfg[i].temp) { mode = i; break; } } } if ((_mt_cpufreq_get_cpu_level() == CPU_LEVEL_2) && (mode == TURBO_MODE_2)) mode = TURBO_MODE_1; // Make sure Vproc is lower than 1.15V if (TURBO_MODE_VOLT(mode, cpu_dvfs_get_volt_by_idx(p, 0)) >= MAX_VPROC_VOLT) mode = TURBO_MODE_NONE; #ifdef CONFIG_CPU_DVFS_AEE_RR_REC if (TURBO_MODE_NONE != mode) aee_rr_rec_cpu_dvfs_status(aee_rr_curr_cpu_dvfs_status() | (1 << CPU_DVFS_LITTLE_IS_TURBO)); else aee_rr_rec_cpu_dvfs_status(aee_rr_curr_cpu_dvfs_status() & ~(1 << CPU_DVFS_LITTLE_IS_TURBO)); #endif cpufreq_ver("%s(), mode = %d, temp = %d, target_khz = %d (%d), num_online_cpus = %d\n", __func__, mode, temp, target_khz, TURBO_MODE_FREQ(mode, target_khz), online_cpus ); // <-XXX return mode; } static int _search_available_freq_idx(struct mt_cpu_dvfs *p, unsigned int target_khz, unsigned int relation) /* return -1 (not found) */ { int new_opp_idx = -1; int i; FUNC_ENTER(FUNC_LV_HELP); if (CPUFREQ_RELATION_L == relation) { for (i = (signed)(p->nr_opp_tbl - 1); i >= 0; i--) { if (cpu_dvfs_get_freq_by_idx(p, i) >= target_khz) { new_opp_idx = i; break; } } } else { /* CPUFREQ_RELATION_H */ for (i = 0; i < (signed)p->nr_opp_tbl; i++) { if (cpu_dvfs_get_freq_by_idx(p, i) <= target_khz) { new_opp_idx = i; break; } } } FUNC_EXIT(FUNC_LV_HELP); return new_opp_idx; } /* for PTP-OD */ static int _set_cur_volt_locked(struct mt_cpu_dvfs *p, unsigned int volt) // volt: mv * 100 { int ret = -1; FUNC_ENTER(FUNC_LV_HELP); BUG_ON(NULL == p); if (!cpu_dvfs_is_availiable(p)) { FUNC_EXIT(FUNC_LV_HELP); return 0; } /* set volt */ ret = p->ops->set_cur_volt(p, volt); FUNC_EXIT(FUNC_LV_HELP); return ret; } static int _restore_default_volt(struct mt_cpu_dvfs *p) { unsigned long flags; int i; int ret = -1; unsigned int freq = 0; int idx = 0; FUNC_ENTER(FUNC_LV_HELP); BUG_ON(NULL == p); if (!cpu_dvfs_is_availiable(p)) { FUNC_EXIT(FUNC_LV_HELP); return 0; } cpufreq_lock(flags); /* restore to default volt */ for (i = 0; i < p->nr_opp_tbl; i++) p->opp_tbl[i].cpufreq_volt = p->opp_tbl[i].cpufreq_volt_org; freq = p->ops->get_cur_phy_freq(p); if (freq > cpu_dvfs_get_max_freq(p)) idx = 0; else { idx = _search_available_freq_idx(p, freq, CPUFREQ_RELATION_L); } /* set volt */ ret = _set_cur_volt_locked(p, TURBO_MODE_VOLT(get_turbo_mode(p, cpu_dvfs_get_freq_by_idx(p, idx)), cpu_dvfs_get_volt_by_idx(p, idx) ) ); cpufreq_unlock(flags); FUNC_EXIT(FUNC_LV_HELP); return ret; } unsigned int mt_cpufreq_get_freq_by_idx(enum mt_cpu_dvfs_id id, int idx) { struct mt_cpu_dvfs *p = id_to_cpu_dvfs(id); FUNC_ENTER(FUNC_LV_API); BUG_ON(NULL == p); if (!cpu_dvfs_is_availiable(p)) { FUNC_EXIT(FUNC_LV_API); return 0; } BUG_ON(idx >= p->nr_opp_tbl); FUNC_EXIT(FUNC_LV_API); return cpu_dvfs_get_freq_by_idx(p, idx); } EXPORT_SYMBOL(mt_cpufreq_get_freq_by_idx); int mt_cpufreq_update_volt(enum mt_cpu_dvfs_id id, unsigned int *volt_tbl, int nr_volt_tbl) { struct mt_cpu_dvfs *p = id_to_cpu_dvfs(id); unsigned long flags; int i; int ret = -1; unsigned int freq = 0; int idx = 0; FUNC_ENTER(FUNC_LV_API); BUG_ON(NULL == p); if (!cpu_dvfs_is_availiable(p)) { FUNC_EXIT(FUNC_LV_API); return 0; } BUG_ON(nr_volt_tbl > p->nr_opp_tbl); cpufreq_lock(flags); /* update volt table */ for (i = 0; i < nr_volt_tbl; i++) p->opp_tbl[i].cpufreq_volt = PMIC_VAL_TO_VOLT(volt_tbl[i]); freq = p->ops->get_cur_phy_freq(p); if (freq > cpu_dvfs_get_max_freq(p)) idx = 0; else { idx = _search_available_freq_idx(p, freq, CPUFREQ_RELATION_L); } /* set volt */ ret = _set_cur_volt_locked(p, TURBO_MODE_VOLT(get_turbo_mode(p, cpu_dvfs_get_freq_by_idx(p, idx)), cpu_dvfs_get_volt_by_idx(p, idx) ) ); cpufreq_unlock(flags); FUNC_EXIT(FUNC_LV_API); return ret; } EXPORT_SYMBOL(mt_cpufreq_update_volt); void mt_cpufreq_restore_default_volt(enum mt_cpu_dvfs_id id) { struct mt_cpu_dvfs *p = id_to_cpu_dvfs(id); FUNC_ENTER(FUNC_LV_API); BUG_ON(NULL == p); if (!cpu_dvfs_is_availiable(p)) { FUNC_EXIT(FUNC_LV_API); return; } // Disable turbo mode since PTPOD is disabled if (p->turbo_mode) { cpufreq_ver("@%s: Turbo mode disabled!\n", __func__); p->turbo_mode = 0; } _restore_default_volt(p); FUNC_EXIT(FUNC_LV_API); } EXPORT_SYMBOL(mt_cpufreq_restore_default_volt); static unsigned int _cpu_freq_calc(unsigned int con1, unsigned int ckdiv1) { unsigned int freq = 0; con1 &= _BITMASK_(26 : 0);//POSDIV[26:24]SDM_PCW[20:0] if (con1 >= DDS_DIV2_FREQ) { freq = DDS_DIV2_FREQ; freq = PLL_DIV2_FREQ + (((con1 - freq) / 0x2000) * PLL_FREQ_STEP / 2); } else if (con1 >= DDS_FREQ5_FREQ) { freq = DDS_FREQ5_FREQ; freq = PLL_FREQ5_FREQ + (((con1 - freq) / 0x2000) * PLL_FREQ_STEP); } else if (con1 >= DDS_DIV1_FREQ) { freq = DDS_DIV1_FREQ; freq = PLL_DIV1_FREQ + (((con1 - freq) / 0x2000) * PLL_FREQ_STEP); } else BUG(); FUNC_ENTER(FUNC_LV_HELP); switch (ckdiv1) { case 10: freq = freq * 2 / 4; break; case 8: case 16: case 24: default: break; } FUNC_EXIT(FUNC_LV_HELP); return freq; // TODO: adjust by ptp level??? } static unsigned int get_cur_phy_freq(struct mt_cpu_dvfs *p) { unsigned int con1; unsigned int ckdiv1; unsigned int cur_khz; FUNC_ENTER(FUNC_LV_LOCAL); BUG_ON(NULL == p); con1 = cpufreq_read(4 + ARMCA15PLL_CON0);//10209200+4 ckdiv1 = cpufreq_read(TOP_CKDIV1);//10001008 ckdiv1 = _GET_BITS_VAL_(4 : 0, ckdiv1);//ca15_clkdiv1_sel 9:5 cur_khz = _cpu_freq_calc(con1, ckdiv1); cpufreq_ver("@%s: cur_khz = %d, con1 = 0x%x, ckdiv1_val = 0x%x\n", __func__, cur_khz, con1, ckdiv1); FUNC_EXIT(FUNC_LV_LOCAL); return cur_khz; } static unsigned int _mt_cpufreq_get_cur_phy_freq(enum mt_cpu_dvfs_id id) { struct mt_cpu_dvfs *p = id_to_cpu_dvfs(id); FUNC_ENTER(FUNC_LV_LOCAL); BUG_ON(NULL == p); FUNC_EXIT(FUNC_LV_LOCAL); return p->ops->get_cur_phy_freq(p); } static unsigned int _cpu_dds_calc(unsigned int khz) /* XXX: NOT OK FOR 1007.5MHz */ { unsigned int dds; FUNC_ENTER(FUNC_LV_HELP); if (khz >= PLL_DIV1_FREQ) dds = DDS_DIV1_FREQ + ((khz - PLL_DIV1_FREQ) / PLL_FREQ_STEP) * 0x2000; else if (khz >= CPU_DVFS_FREQ5) dds = DDS_FREQ5_FREQ + ((khz - CPU_DVFS_FREQ5) / PLL_FREQ_STEP) * 0x2000; else if (khz >= PLL_DIV2_FREQ) dds = DDS_DIV2_FREQ + ((khz - PLL_DIV2_FREQ) * 2 / PLL_FREQ_STEP) * 0x2000; else BUG(); FUNC_EXIT(FUNC_LV_HELP); return dds; } static void _cpu_clock_switch(struct mt_cpu_dvfs *p, enum top_ckmuxsel sel) { unsigned int val = cpufreq_read(TOP_CKMUXSEL); unsigned int mask = _BITMASK_(1 : 0); FUNC_ENTER(FUNC_LV_HELP); BUG_ON(sel >= NR_TOP_CKMUXSEL); cpufreq_write(TOP_CKMUXSEL, (val & ~mask) | sel); FUNC_EXIT(FUNC_LV_HELP); } static enum top_ckmuxsel _get_cpu_clock_switch(struct mt_cpu_dvfs *p) { unsigned int val = cpufreq_read(TOP_CKMUXSEL); unsigned int mask = _BITMASK_(1 : 0); FUNC_ENTER(FUNC_LV_HELP); val &= mask; /* _BITMASK_(1 : 0) */ FUNC_EXIT(FUNC_LV_HELP); return val; } int mt_cpufreq_clock_switch(enum mt_cpu_dvfs_id id, enum top_ckmuxsel sel) { struct mt_cpu_dvfs *p = id_to_cpu_dvfs(id); if (!p) return -1; _cpu_clock_switch(p, sel); return 0; } enum top_ckmuxsel mt_cpufreq_get_clock_switch(enum mt_cpu_dvfs_id id) { struct mt_cpu_dvfs *p = id_to_cpu_dvfs(id); if (!p) return -1; return _get_cpu_clock_switch(p); } /* * CPU freq scaling * * above 1GHz: use freq hopping * below 1GHz: use ARMPLL * below 800MHz: use CLKDIV1 * if cross 1GHz, migrate to 1GHz first. * */ static void set_cur_freq(struct mt_cpu_dvfs *p, unsigned int cur_khz, unsigned int target_khz) { unsigned int dds; unsigned int is_fhctl_used; unsigned int ckdiv1_val = _GET_BITS_VAL_(4 : 0, cpufreq_read(TOP_CKDIV1));//0x0008 4:0 CA7 ARMPLL CLKDIV unsigned int ckdiv1_mask = _BITMASK_(4 : 0); unsigned int sel = 0; unsigned int cur_volt = 0; unsigned int mainpll_volt_idx = 0; #define IS_CLKDIV_USED(clkdiv) (((clkdiv < 8) || ((clkdiv % 8) == 0)) ? 0 : 1) FUNC_ENTER(FUNC_LV_LOCAL); if (cur_khz == target_khz) return; //cpufreq_ver("cur_khz = %d, ckdiv1_val = 0x%x\n", cur_khz, ckdiv1_val); if (((cur_khz < CPUFREQ_BOUNDARY_FOR_FHCTL) && (target_khz > CPUFREQ_BOUNDARY_FOR_FHCTL)) || ((target_khz < CPUFREQ_BOUNDARY_FOR_FHCTL) && (cur_khz > CPUFREQ_BOUNDARY_FOR_FHCTL))) { set_cur_freq(p, cur_khz, CPUFREQ_BOUNDARY_FOR_FHCTL); cur_khz = CPUFREQ_BOUNDARY_FOR_FHCTL; } is_fhctl_used = ((target_khz >= CPUFREQ_BOUNDARY_FOR_FHCTL) && (cur_khz >= CPUFREQ_BOUNDARY_FOR_FHCTL)) ? 1 : 0; cpufreq_ver("@%s():%d, cur_khz = %d, target_khz = %d, is_fhctl_used = %d\n", __func__, __LINE__, cur_khz, target_khz, is_fhctl_used ); if (!is_fhctl_used) { /* set ca15_clkdiv1_sel */ switch (target_khz) { case CPU_DVFS_FREQ5: dds = _cpu_dds_calc(CPU_DVFS_FREQ5); // 1183000 sel = 8; // 4/4 break; case CPU_DVFS_FREQ6: dds = _cpu_dds_calc(PLL_DIV2_FREQ); // 806 = 1612000 / 2(POSDIV) sel = 8; // 4/4 break; case CPU_DVFS_FREQ7: dds = _cpu_dds_calc(PLL_DIV2_FREQ); // 403 = 1612000 / 2(POSDIV) / 2(CLKDIV) sel = 10; // 2/4 break; default: BUG(); } // adjust Vproc since MAINPLL is 1092 MHz (~= CPU_DVFS_FREQ7) cur_volt = p->ops->get_cur_volt(p); #if 1 mainpll_volt_idx = 5; //1183000 #else switch (p->cpu_level) { case CPU_LEVEL_0: case CPU_LEVEL_1: mainpll_volt_idx = 4; break; case CPU_LEVEL_2: mainpll_volt_idx = 3; break; default: mainpll_volt_idx = 1; break; } #endif if (cur_volt < cpu_dvfs_get_volt_by_idx(p, mainpll_volt_idx)) p->ops->set_cur_volt(p, cpu_dvfs_get_volt_by_idx(p, mainpll_volt_idx)); else cur_volt = 0; // set ARMPLL and CLKDIV _cpu_clock_switch(p, TOP_CKMUXSEL_MAINPLL); cpufreq_write(ARMCA15PLL_CON1, dds | _BIT_(31)); /* CHG */ udelay(PLL_SETTLE_TIME); cpufreq_write(TOP_CKDIV1, (ckdiv1_val & ~ckdiv1_mask) | sel); _cpu_clock_switch(p, TOP_CKMUXSEL_ARMPLL); // restore Vproc if (cur_volt) p->ops->set_cur_volt(p, cur_volt); } else { dds = _cpu_dds_calc(target_khz); BUG_ON(dds & _BITMASK_(26 : 24)); /* should not use posdiv */ #if !defined(__KERNEL__) && defined(MTKDRV_FREQHOP) freqhopping_dvt_dvfs_enable(ARMCA15PLL_ID, target_khz);//ask hopping owner for dvt #else /* __KERNEL__ */ #if 1 mt_dfs_armpll(FH_ARMCA15_PLLID, dds);//wait for hopping #else _cpu_clock_switch(p, TOP_CKMUXSEL_MAINPLL); cpufreq_write(ARMCA15PLL_CON1, dds | _BIT_(31)); /* CHG */ udelay(PLL_SETTLE_TIME); _cpu_clock_switch(p, TOP_CKMUXSEL_ARMPLL); #endif #endif /* ! __KERNEL__ */ } FUNC_EXIT(FUNC_LV_LOCAL); } /* for volt change (PMICWRAP/extBuck) */ static unsigned int get_cur_vsram(struct mt_cpu_dvfs *p) { unsigned int rdata = 0; unsigned int retry_cnt = 5; FUNC_ENTER(FUNC_LV_LOCAL); pwrap_read(PMIC_ADDR_VSRAM_CA7_EN, &rdata); rdata &= _BITMASK_(10 : 10); /* enable or disable (i.e. 0mv or not) */ if (rdata) { /* enabled i.e. not 0mv */ do { pwrap_read(PMIC_ADDR_VSRAM_VOSEL_ON, &rdata); } while (rdata == _BITMASK_(10 : 10) && retry_cnt--); rdata &= 0x7F; rdata = PMIC_VAL_TO_VOLT(rdata); } FUNC_EXIT(FUNC_LV_LOCAL); return rdata; /* vproc: mv*100 */ } static unsigned int get_cur_volt_extbuck(struct mt_cpu_dvfs *p) { unsigned char ret_val; unsigned int ret_mv; unsigned int retry_cnt = 5; FUNC_ENTER(FUNC_LV_LOCAL); do { if (!da9210_read_byte(0xD8, &ret_val)) { // TODO: FIXME, it is better not to access da9210 directly cpufreq_err("%s(), fail to read ext buck volt\n", __func__); ret_mv = 0; } else ret_mv = EXTBUCK_VAL_TO_VOLT(ret_val); } while (ret_mv == EXTBUCK_VAL_TO_VOLT(0) && retry_cnt--); // XXX: EXTBUCK_VAL_TO_VOLT(0) is impossible setting and need to retry FUNC_EXIT(FUNC_LV_LOCAL); return ret_mv * 100; // mv * 100 } unsigned int mt_cpufreq_get_cur_volt(enum mt_cpu_dvfs_id id) { struct mt_cpu_dvfs *p = id_to_cpu_dvfs(id); FUNC_ENTER(FUNC_LV_API); BUG_ON(NULL == p); BUG_ON(NULL == p->ops); FUNC_EXIT(FUNC_LV_API); return p->ops->get_cur_volt(p); // mv * 100 } EXPORT_SYMBOL(mt_cpufreq_get_cur_volt); #if 0 static unsigned int _calc_pmic_settle_time(unsigned int old_vproc, unsigned int old_vsram, unsigned int new_vproc, unsigned int new_vsram) { unsigned delay = 100; if (new_vproc == old_vproc && new_vsram == old_vsram) return 0; // VPROC is UP if (new_vproc >= old_vproc) { // VSRAM is UP too, choose larger one to calculate settle time if (new_vsram >= old_vsram) delay = MAX( PMIC_VOLT_UP_SETTLE_TIME(old_vsram, new_vsram), PMIC_VOLT_UP_SETTLE_TIME(old_vproc, new_vproc) ); // VSRAM is DOWN, it may happen at bootup stage else delay = MAX( PMIC_VOLT_DOWN_SETTLE_TIME(old_vsram, new_vsram), PMIC_VOLT_UP_SETTLE_TIME(old_vproc, new_vproc) ); } // VPROC is DOWN else { // VSRAM is DOWN too, choose larger one to calculate settle time if (old_vsram >= new_vsram) delay = MAX( PMIC_VOLT_DOWN_SETTLE_TIME(old_vsram, new_vsram), PMIC_VOLT_DOWN_SETTLE_TIME(old_vproc, new_vproc) ); // VSRAM is UP, it may happen at bootup stage else delay = MAX( PMIC_VOLT_UP_SETTLE_TIME(old_vsram, new_vsram), PMIC_VOLT_DOWN_SETTLE_TIME(old_vproc, new_vproc) ); } if (delay < MIN_PMIC_SETTLE_TIME) delay = MIN_PMIC_SETTLE_TIME; return delay; } #endif static void dump_opp_table(struct mt_cpu_dvfs *p) { int i; cpufreq_err("[%s/%d]\n" "cpufreq_oppidx = %d\n", p->name, p->cpu_id, p->idx_opp_tbl ); for (i = 0; i < p->nr_opp_tbl; i++) { cpufreq_err("\tOP(%d, %d),\n", cpu_dvfs_get_freq_by_idx(p, i), cpu_dvfs_get_volt_by_idx(p, i) ); } } static int set_cur_volt_extbuck(struct mt_cpu_dvfs *p, unsigned int mv) /* volt: vproc (mv*100) */ { unsigned int cur_vsram_mv = get_cur_vsram(p); unsigned int cur_vproc_mv = get_cur_volt_extbuck(p); int ret = 0; FUNC_ENTER(FUNC_LV_LOCAL); #ifdef CONFIG_CPU_DVFS_AEE_RR_REC aee_rr_rec_cpu_dvfs_vproc_little(VOLT_TO_PMIC_VAL(mv)); #endif if (unlikely(!((cur_vsram_mv >= cur_vproc_mv) && (MAX_DIFF_VSRAM_VPROC >= (cur_vsram_mv - cur_vproc_mv))))) { unsigned char ret_val; int i; dump_opp_table(p); //cpufreq_err("@%s():%d, cur_vsram_mv = %d (%d), cur_vproc_mv = %d (%d), 0xF000D0C4 = 0x%08X, 0xF000D0C8 = 0x%08X, MAINPLL_CON0 = 0x%08X, MAINPLL_CON1 = 0x%08X, MAINPLL_PWR_CON0 = 0x%08X, CLK_CFG_0 = 0x%08X, TOP_DCMCTL = 0x%08X, PERI_PDN0_STA = 0x%08X\n", cpufreq_err("@%s():%d, cur_vsram_mv = %d (%d), cur_vproc_mv = %d (%d)\n", __func__, __LINE__, cur_vsram_mv, cpu_dvfs_get_cur_volt(p), cur_vproc_mv, cpu_dvfs_get_cur_volt(p) + NORMAL_DIFF_VRSAM_VPROC ); for (i = 0; i < 10; i++) { extern kal_uint32 da9210_config_interface(kal_uint8 RegNum, kal_uint8 val, kal_uint8 MASK, kal_uint8 SHIFT); extern kal_uint32 da9210_read_interface(kal_uint8 RegNum, kal_uint8 * val, kal_uint8 MASK, kal_uint8 SHIFT); da9210_config_interface(0x0, 0x1, 0x1, 7); // page reverts to 0 after one access da9210_config_interface(0x0, 0x2, 0xF, 0); // select to page 2,3 da9210_read_interface(0x5, &ret_val, 0xF, 4); cpufreq_err("%s(), da9210 ID = %x\n", __func__, ret_val); } for (i = 0; i < 10; i++) { extern kal_uint32 tps6128x_read_byte(kal_uint8 cmd, kal_uint8 * returnData); tps6128x_read_byte(0x3, &ret_val); // read val = 0xb cpufreq_err("%s(), tps6128x ID = %x\n", __func__, ret_val); } aee_kernel_warning(TAG, "@%s():%d, cur_vsram_mv = %d, cur_vproc_mv = %d\n", __func__, __LINE__, cur_vsram_mv, cur_vproc_mv); cur_vproc_mv = cpu_dvfs_get_cur_volt(p); cur_vsram_mv = cur_vproc_mv + NORMAL_DIFF_VRSAM_VPROC; } if (cur_vsram_mv - cur_vproc_mv > NORMAL_DIFF_VRSAM_VPROC) { cur_vsram_mv = cur_vproc_mv + NORMAL_DIFF_VRSAM_VPROC; mt_cpufreq_set_pmic_cmd(PMIC_WRAP_PHASE_DEEPIDLE, IDX_DI_VSRAM_CA7_NORMAL, VOLT_TO_PMIC_VAL(cur_vsram_mv)); mt_cpufreq_set_pmic_cmd(PMIC_WRAP_PHASE_SODI, IDX_SO_VSRAM_CA7_NORMAL, VOLT_TO_PMIC_VAL(cur_vsram_mv)); mt_cpufreq_set_pmic_cmd(PMIC_WRAP_PHASE_NORMAL, IDX_NM_VSRAM_CA7, VOLT_TO_PMIC_VAL(cur_vsram_mv)); mt_cpufreq_apply_pmic_cmd(IDX_NM_VSRAM_CA7); } /* UP */ if (mv > cur_vproc_mv) { unsigned int target_vsram_mv = mv + NORMAL_DIFF_VRSAM_VPROC; unsigned int next_vsram_mv; do { next_vsram_mv = MIN(((MAX_DIFF_VSRAM_VPROC - 2500) + cur_vproc_mv), target_vsram_mv); /* update vsram */ cur_vsram_mv = MAX(next_vsram_mv, MIN_VSRAM_VOLT); // TODO: use define for 931.25mv // <-XXX if (cur_vsram_mv > MAX_VSRAM_VOLT) { cur_vsram_mv = MAX_VSRAM_VOLT; target_vsram_mv = MAX_VSRAM_VOLT; // to end the loop } if (unlikely(!((cur_vsram_mv >= cur_vproc_mv) && (MAX_DIFF_VSRAM_VPROC >= (cur_vsram_mv - cur_vproc_mv))))) { dump_opp_table(p); cpufreq_err("@%s():%d, cur_vsram_mv = %d, cur_vproc_mv = %d\n", __func__, __LINE__, cur_vsram_mv, cur_vproc_mv); BUG(); } mt_cpufreq_set_pmic_cmd(PMIC_WRAP_PHASE_DEEPIDLE, IDX_DI_VSRAM_CA7_NORMAL, VOLT_TO_PMIC_VAL(cur_vsram_mv)); mt_cpufreq_set_pmic_cmd(PMIC_WRAP_PHASE_SODI, IDX_SO_VSRAM_CA7_NORMAL, VOLT_TO_PMIC_VAL(cur_vsram_mv)); mt_cpufreq_set_pmic_cmd(PMIC_WRAP_PHASE_NORMAL, IDX_NM_VSRAM_CA7, VOLT_TO_PMIC_VAL(cur_vsram_mv)); mt_cpufreq_apply_pmic_cmd(IDX_NM_VSRAM_CA7); /* update vproc */ if (next_vsram_mv > MAX_VSRAM_VOLT) cur_vproc_mv = mv; // Vsram was limited, set to target vproc directly else cur_vproc_mv = next_vsram_mv - NORMAL_DIFF_VRSAM_VPROC; if (unlikely(!((cur_vsram_mv >= cur_vproc_mv) && (MAX_DIFF_VSRAM_VPROC >= (cur_vsram_mv - cur_vproc_mv))))) { dump_opp_table(p); cpufreq_err("@%s():%d, cur_vsram_mv = %d, cur_vproc_mv = %d\n", __func__, __LINE__, cur_vsram_mv, cur_vproc_mv); BUG(); } if (!ext_buck_vosel(cur_vproc_mv)) { // mv * 100 cpufreq_err("%s(), fail to set ext buck volt\n", __func__); ret = -1; } mdelay(PMIC_SETTLE_TIME(cur_vproc_mv - MAX_DIFF_VSRAM_VPROC, cur_vproc_mv)); // TODO: always fix max gap <- refine it??? // cpufreq_dbg("@%s(), UP, cur_vsram_mv = %d, cur_vproc_mv = %d, delay = %d\n", __func__, cur_vsram_mv, cur_vproc_mv, PMIC_SETTLE_TIME(cur_vproc_mv - MAX_DIFF_VSRAM_VPROC, cur_vproc_mv)); } while (target_vsram_mv > cur_vsram_mv); } /* DOWN */ else if (mv < cur_vproc_mv) { unsigned int next_vproc_mv; unsigned int next_vsram_mv = cur_vproc_mv + NORMAL_DIFF_VRSAM_VPROC; do { next_vproc_mv = MAX((next_vsram_mv - (MAX_DIFF_VSRAM_VPROC - 2500)), mv); /* update vproc */ cur_vproc_mv = next_vproc_mv; if (unlikely(!((cur_vsram_mv >= cur_vproc_mv) && (MAX_DIFF_VSRAM_VPROC >= (cur_vsram_mv - cur_vproc_mv))))) { dump_opp_table(p); cpufreq_err("@%s():%d, cur_vsram_mv = %d, cur_vproc_mv = %d\n", __func__, __LINE__, cur_vsram_mv, cur_vproc_mv); BUG(); } if (!ext_buck_vosel(cur_vproc_mv)) { // mv * 100 cpufreq_err("%s(), fail to set ext buck volt\n", __func__); ret = -1; } /* update vsram */ next_vsram_mv = cur_vproc_mv + NORMAL_DIFF_VRSAM_VPROC; cur_vsram_mv = MAX(next_vsram_mv, MIN_VSRAM_VOLT); // TODO: use define for 931.25mv // <-XXX cur_vsram_mv = MIN(cur_vsram_mv, MAX_VSRAM_VOLT); // TODO: use define for 1150mv // <-XXX if (unlikely(!((cur_vsram_mv >= cur_vproc_mv) && (MAX_DIFF_VSRAM_VPROC >= (cur_vsram_mv - cur_vproc_mv))))) { dump_opp_table(p); cpufreq_err("@%s():%d, cur_vsram_mv = %d, cur_vproc_mv = %d\n", __func__, __LINE__, cur_vsram_mv, cur_vproc_mv); BUG(); } mt_cpufreq_set_pmic_cmd(PMIC_WRAP_PHASE_DEEPIDLE, IDX_DI_VSRAM_CA7_NORMAL, VOLT_TO_PMIC_VAL(cur_vsram_mv)); mt_cpufreq_set_pmic_cmd(PMIC_WRAP_PHASE_SODI, IDX_SO_VSRAM_CA7_NORMAL, VOLT_TO_PMIC_VAL(cur_vsram_mv)); mt_cpufreq_set_pmic_cmd(PMIC_WRAP_PHASE_NORMAL, IDX_NM_VSRAM_CA7, VOLT_TO_PMIC_VAL(cur_vsram_mv)); mt_cpufreq_apply_pmic_cmd(IDX_NM_VSRAM_CA7); mdelay(PMIC_SETTLE_TIME(cur_vproc_mv + MAX_DIFF_VSRAM_VPROC, cur_vproc_mv)); // TODO: always fix max gap <- refine it??? // cpufreq_dbg("@%s(), DOWN, cur_vsram_mv = %d, cur_vproc_mv = %d, delay = %d\n", __func__, cur_vsram_mv, cur_vproc_mv, PMIC_SETTLE_TIME(cur_vproc_mv + MAX_DIFF_VSRAM_VPROC, cur_vproc_mv)); } while (cur_vproc_mv > mv); } if (NULL != g_pCpuVoltSampler) g_pCpuVoltSampler(MT_CPU_DVFS_LITTLE, mv / 100); // mv cpufreq_ver("@%s():%d, cur_vsram_mv = %d, cur_vproc_mv = %d\n", __func__, __LINE__, cur_vsram_mv, cur_vproc_mv); FUNC_EXIT(FUNC_LV_LOCAL); return ret; } /* cpufreq set (freq & volt) */ static unsigned int _search_available_volt(struct mt_cpu_dvfs *p, unsigned int target_khz) { int i; FUNC_ENTER(FUNC_LV_HELP); BUG_ON(NULL == p); /* search available voltage */ for (i = p->nr_opp_tbl - 1; i >= 0; i--) { if (target_khz <= cpu_dvfs_get_freq_by_idx(p, i)) break; } BUG_ON(i < 0); /* i.e. target_khz > p->opp_tbl[0].cpufreq_khz */ FUNC_EXIT(FUNC_LV_HELP); return cpu_dvfs_get_volt_by_idx(p, i); // mv * 100 } static int _cpufreq_set_locked(struct mt_cpu_dvfs *p, unsigned int cur_khz, unsigned int target_khz, struct cpufreq_policy *policy) { unsigned int volt; // mv * 100 int ret = 0; #ifdef CONFIG_CPU_FREQ struct cpufreq_freqs freqs; unsigned int cpu; unsigned int target_khz_orig = target_khz; #endif enum turbo_mode mode = get_turbo_mode(p, target_khz); FUNC_ENTER(FUNC_LV_HELP); volt = _search_available_volt(p, target_khz); if (cur_khz != TURBO_MODE_FREQ(mode, target_khz)) cpufreq_dbg("@%s(), target_khz = %d (%d), volt = %d (%d), num_online_cpus = %d, cur_khz = %d\n", __func__, target_khz, TURBO_MODE_FREQ(mode, target_khz), volt, TURBO_MODE_VOLT(mode, volt), num_online_cpus(), cur_khz ); volt = TURBO_MODE_VOLT(mode, volt); target_khz = TURBO_MODE_FREQ(mode, target_khz); if (cur_khz == target_khz) goto out; /* set volt (UP) */ if (cur_khz < target_khz) { ret = p->ops->set_cur_volt(p, volt); if (ret) /* set volt fail */ goto out; } #ifdef CONFIG_CPU_FREQ freqs.old = p->ops->get_cur_phy_freq(p); freqs.new = target_khz_orig; if (policy) { for_each_online_cpu(cpu) { freqs.cpu = cpu; cpufreq_notify_transition(policy, &freqs, CPUFREQ_PRECHANGE); } } #endif /* set freq (UP/DOWN) */ if (cur_khz != target_khz) p->ops->set_cur_freq(p, cur_khz, target_khz); #ifdef CONFIG_CPU_FREQ if (policy) { for_each_online_cpu(cpu) { freqs.cpu = cpu; cpufreq_notify_transition(policy, &freqs, CPUFREQ_POSTCHANGE); } } #endif /* set volt (DOWN) */ if (cur_khz > target_khz) { ret = p->ops->set_cur_volt(p, volt); if (ret) /* set volt fail */ goto out; } cpufreq_ver("@%s(): Vproc = %dmv, Vsram = %dmv, freq = %d KHz\n", __func__, (p->ops->get_cur_volt(p)) / 100, (get_cur_vsram(p) / 100), p->ops->get_cur_phy_freq(p) ); // trigger exception if freq/volt not correct during stress if (do_dvfs_stress_test && (!p->dvfs_disable_by_suspend)) { BUG_ON(p->ops->get_cur_volt(p) < volt); BUG_ON(p->ops->get_cur_phy_freq(p) != target_khz); } FUNC_EXIT(FUNC_LV_HELP); out: return ret; } static unsigned int _calc_new_opp_idx(struct mt_cpu_dvfs *p, int new_opp_idx); static void _mt_cpufreq_set(enum mt_cpu_dvfs_id id, int new_opp_idx) { unsigned long flags; struct mt_cpu_dvfs *p = id_to_cpu_dvfs(id); unsigned int cur_freq; unsigned int target_freq; #ifdef CONFIG_CPU_FREQ struct cpufreq_policy *policy; #endif FUNC_ENTER(FUNC_LV_LOCAL); BUG_ON(NULL == p); BUG_ON(new_opp_idx >= p->nr_opp_tbl); #ifdef CONFIG_CPU_FREQ policy = cpufreq_cpu_get(p->cpu_id); #endif cpufreq_lock(flags); // <-XXX // get current idx here to avoid idx synchronization issue if (new_opp_idx == -1) new_opp_idx = p->idx_opp_tbl; if (do_dvfs_stress_test && (!p->dvfs_disable_by_suspend)) new_opp_idx = jiffies & 0x7; /* 0~7 */ else { #if defined(CONFIG_CPU_DVFS_BRINGUP) new_opp_idx = id_to_cpu_dvfs(id)->idx_normal_max_opp; #else new_opp_idx = _calc_new_opp_idx(id_to_cpu_dvfs(id), new_opp_idx); #endif } cur_freq = p->ops->get_cur_phy_freq(p); target_freq = cpu_dvfs_get_freq_by_idx(p, new_opp_idx); #ifdef CONFIG_CPU_FREQ _cpufreq_set_locked(p, cur_freq, target_freq, policy); #else _cpufreq_set_locked(p, cur_freq, target_freq, NULL); #endif p->idx_opp_tbl = new_opp_idx; cpufreq_unlock(flags); // <-XXX #ifdef CONFIG_CPU_FREQ if (policy) cpufreq_cpu_put(policy); #endif FUNC_EXIT(FUNC_LV_LOCAL); } static int __cpuinit turbo_mode_cpu_callback(struct notifier_block *nfb, unsigned long action, void *hcpu) { #if 1 unsigned int cpu = (unsigned long)hcpu; unsigned int online_cpus = num_online_cpus(); struct device *dev; struct mt_cpu_dvfs *p = id_to_cpu_dvfs(0); // TODO: FIXME, for E1 cpufreq_ver("@%s():%d, cpu = %d, action = %lu, oppidx = %d, num_online_cpus = %d, num_online_cpus_delta = %d\n", __func__, __LINE__, cpu, action, p->idx_opp_tbl, online_cpus, num_online_cpus_delta ); // <-XXX dev = get_cpu_device(cpu); if (dev) { if (TURBO_MODE_BOUNDARY_CPU_NUM == online_cpus) { switch (action) { case CPU_UP_PREPARE: case CPU_UP_PREPARE_FROZEN: num_online_cpus_delta = 1; case CPU_DEAD: case CPU_DEAD_FROZEN: _mt_cpufreq_set(MT_CPU_DVFS_LITTLE, -1); break; } } else { switch (action) { case CPU_ONLINE: // CPU UP done case CPU_ONLINE_FROZEN: case CPU_UP_CANCELED: // CPU UP failed case CPU_UP_CANCELED_FROZEN: num_online_cpus_delta = 0; break; } } cpufreq_ver("@%s():%d, cpu = %d, action = %lu, oppidx = %d, num_online_cpus = %d, num_online_cpus_delta = %d\n", __func__, __LINE__, cpu, action, p->idx_opp_tbl, online_cpus, num_online_cpus_delta ); // <-XXX } #else // XXX: DON'T USE cpufreq_driver_target() for the case which cur_freq == target_freq struct cpufreq_policy *policy; unsigned int cpu = (unsigned long)hcpu; struct device *dev; struct mt_cpu_dvfs *p = id_to_cpu_dvfs(0); // TODO: FIXME, for E1 cpufreq_ver("@%s():%d, cpu = %d, action = %d, oppidx = %d, num_online_cpus = %d\n", __func__, __LINE__, cpu, action, p->idx_opp_tbl, num_online_cpus()); // <-XXX dev = get_cpu_device(cpu); if (dev && 0 == p->idx_opp_tbl && TURBO_MODE_BOUNDARY_CPU_NUM == num_online_cpus() ) { switch (action) { case CPU_UP_PREPARE: case CPU_DEAD: policy = cpufreq_cpu_get(p->cpu_id); if (policy) { cpufreq_driver_target(policy, cpu_dvfs_get_cur_freq(p), CPUFREQ_RELATION_L); cpufreq_cpu_put(policy); } cpufreq_ver("@%s():%d, cpu = %d, action = %d, oppidx = %d, num_online_cpus = %d\n", __func__, __LINE__, cpu, action, p->idx_opp_tbl, num_online_cpus()); // <-XXX break; } } #endif return NOTIFY_OK; } static struct notifier_block __refdata turbo_mode_cpu_notifier = { .notifier_call = turbo_mode_cpu_callback, }; static void _set_no_limited(struct mt_cpu_dvfs *p) { FUNC_ENTER(FUNC_LV_HELP); BUG_ON(NULL == p); p->limited_max_freq = cpu_dvfs_get_max_freq(p); p->limited_max_ncpu = max_cpu_num; p->thermal_protect_limited_power = 0; FUNC_EXIT(FUNC_LV_HELP); } #ifdef CONFIG_CPU_DVFS_DOWNGRADE_FREQ static void _downgrade_freq_check(enum mt_cpu_dvfs_id id) { struct cpufreq_policy *policy; struct mt_cpu_dvfs *p = id_to_cpu_dvfs(id); int temp = 0; FUNC_ENTER(FUNC_LV_API); BUG_ON(NULL == p); /* if not CPU_LEVEL0 */ if (p->cpu_level != CPU_LEVEL_0) goto out; /* get temp */ #if 0 // TODO: FIXME if (mt_ptp_status((MT_CPU_DVFS_LITTLE == id) ? PTP_DET_LITTLE : PTP_DET_BIG) == 1) temp = (((DRV_Reg32(PTP_TEMP) & 0xff)) + 25) * 1000; // TODO: mt_ptp.c provide mt_ptp_get_temp() else temp = mtktscpu_get_Tj_temp(); // TODO: FIXME, what is the difference for big & LITTLE #else temp = tscpu_get_temp_by_bank(THERMAL_BANK0); // bank0 for CPU #endif if (temp < 0 || 125000 < temp) { // cpufreq_dbg("%d (temp) < 0 || 125000 < %d (temp)\n", temp, temp); goto out; } { static enum turbo_mode pre_mode = TURBO_MODE_NONE; enum turbo_mode cur_mode = get_turbo_mode(p, cpu_dvfs_get_cur_freq(p)); if (pre_mode != cur_mode) { _mt_cpufreq_set(MT_CPU_DVFS_LITTLE, -1); cpufreq_ver("@%s():%d, oppidx = %d, num_online_cpus = %d, pre_mode = %d, cur_mode = %d\n", __func__, __LINE__, p->idx_opp_tbl, num_online_cpus(), pre_mode, cur_mode ); // <-XXX pre_mode = cur_mode; } } if (temp <= p->ptpod_temperature_limit_1) { p->downgrade_freq_for_ptpod = false; // cpufreq_dbg("%d (temp) < %d (limit_1)\n", temp, p->ptpod_temperature_limit_1); goto out; } else if ((temp > p->ptpod_temperature_limit_1) && (temp < p->ptpod_temperature_limit_2)) { p->downgrade_freq_counter_return_limit = p->downgrade_freq_counter_limit * p->ptpod_temperature_time_1; // cpufreq_dbg("%d (temp) > %d (limit_1)\n", temp, p->ptpod_temperature_limit_1); } else { p->downgrade_freq_counter_return_limit = p->downgrade_freq_counter_limit * p->ptpod_temperature_time_2; // cpufreq_dbg("%d (temp) > %d (limit_2)\n", temp, p->ptpod_temperature_limit_2); } if (p->downgrade_freq_for_ptpod == false) { if ((num_online_cpus() == p->pre_online_cpu) && (cpu_dvfs_get_cur_freq(p) == p->pre_freq)) { if ((num_online_cpus() >= p->over_max_cpu) && (p->idx_opp_tbl == 0)) { p->downgrade_freq_counter++; // cpufreq_dbg("downgrade_freq_counter_limit = %d\n", p->downgrade_freq_counter_limit); // cpufreq_dbg("downgrade_freq_counter = %d\n", p->downgrade_freq_counter); if (p->downgrade_freq_counter >= p->downgrade_freq_counter_limit) { p->downgrade_freq = cpu_dvfs_get_freq_by_idx(p, 1); p->downgrade_freq_for_ptpod = true; p->downgrade_freq_counter = 0; cpufreq_ver("freq limit, downgrade_freq_for_ptpod = %d\n", p->downgrade_freq_for_ptpod); policy = cpufreq_cpu_get(p->cpu_id); if (!policy) goto out; cpufreq_driver_target(policy, p->downgrade_freq, CPUFREQ_RELATION_L); cpufreq_cpu_put(policy); } } else p->downgrade_freq_counter = 0; } else { p->pre_online_cpu = num_online_cpus(); p->pre_freq = cpu_dvfs_get_cur_freq(p); p->downgrade_freq_counter = 0; } } else { p->downgrade_freq_counter_return++; // cpufreq_dbg("downgrade_freq_counter_return_limit = %d\n", p->downgrade_freq_counter_return_limit); // cpufreq_dbg("downgrade_freq_counter_return = %d\n", p->downgrade_freq_counter_return); if (p->downgrade_freq_counter_return >= p->downgrade_freq_counter_return_limit) { p->downgrade_freq_for_ptpod = false; p->downgrade_freq_counter_return = 0; // cpufreq_dbg("Release freq limit, downgrade_freq_for_ptpod = %d\n", p->downgrade_freq_for_ptpod); } } out: FUNC_EXIT(FUNC_LV_API); } static void _init_downgrade(struct mt_cpu_dvfs *p, unsigned int cpu_level) { FUNC_ENTER(FUNC_LV_HELP); switch (cpu_level) { case CPU_LEVEL_0: case CPU_LEVEL_1: case CPU_LEVEL_2: default: #if 0 // TODO: check this setting (Brian) p->downgrade_freq_counter_limit = cpu_dvfs_is(p, MT_CPU_DVFS_LITTLE) ? 10 : 10; p->ptpod_temperature_time_1 = cpu_dvfs_is(p, MT_CPU_DVFS_LITTLE) ? 2 : 1; p->ptpod_temperature_time_2 = cpu_dvfs_is(p, MT_CPU_DVFS_LITTLE) ? 8 : 4; #else p->downgrade_freq_counter_limit = 10; p->ptpod_temperature_time_1 = 2; p->ptpod_temperature_time_2 = 8; #endif break; } #ifdef __KERNEL__ /* install callback */ cpufreq_freq_check = _downgrade_freq_check; #endif FUNC_EXIT(FUNC_LV_HELP); } #endif static int _sync_opp_tbl_idx(struct mt_cpu_dvfs *p) { int ret = -1; unsigned int freq; int i; FUNC_ENTER(FUNC_LV_HELP); BUG_ON(NULL == p); BUG_ON(NULL == p->opp_tbl); BUG_ON(NULL == p->ops); freq = p->ops->get_cur_phy_freq(p); for (i = p->nr_opp_tbl - 1; i >= 0; i--) { if (freq <= cpu_dvfs_get_freq_by_idx(p, i)) { p->idx_opp_tbl = i; break; } } if (i >= 0) { cpufreq_ver("%s freq = %d\n", cpu_dvfs_get_name(p), cpu_dvfs_get_cur_freq(p)); ret = 0; } else cpufreq_warn("%s can't find freq = %d\n", cpu_dvfs_get_name(p), freq); FUNC_EXIT(FUNC_LV_HELP); return ret; } static void _mt_cpufreq_sync_opp_tbl_idx(void) { struct mt_cpu_dvfs *p; int i; FUNC_ENTER(FUNC_LV_LOCAL); for_each_cpu_dvfs(i, p) { if (cpu_dvfs_is_availiable(p)) _sync_opp_tbl_idx(p); } FUNC_EXIT(FUNC_LV_LOCAL); } static enum mt_cpu_dvfs_id _get_cpu_dvfs_id(unsigned int cpu_id) { #if 1 // Little core only for ROME+ return MT_CPU_DVFS_LITTLE; #else #if 1 // TODO: FIXME, just for E1 return (enum mt_cpu_dvfs_id)((cpu_id < 4) ? 0 : 1); #else // TODO: FIXME, just for E1 struct mt_cpu_dvfs *p; int i; for_each_cpu_dvfs(i, p) { if (p->cpu_id == cpu_id) break; } BUG_ON(i >= NR_MT_CPU_DVFS); return i; #endif // TODO: FIXME, just for E1 #endif } int mt_cpufreq_state_set(int enabled) // TODO: state set by id??? keep this function??? { #if 0 bool set_normal_max_opp = false; struct mt_cpu_dvfs *p; int i; unsigned long flags; #endif int ret = 0; FUNC_ENTER(FUNC_LV_API); #if 0 for_each_cpu_dvfs(i, p) { if (!cpu_dvfs_is_availiable(p)) continue; cpufreq_lock(flags); if (enabled) { /* enable CPU DVFS */ if (p->dvfs_disable_by_suspend) { p->dvfs_disable_count--; cpufreq_dbg("enable %s DVFS: dvfs_disable_count = %d\n", p->name, p->dvfs_disable_count); if (p->dvfs_disable_count <= 0) p->dvfs_disable_by_suspend = false; else cpufreq_dbg("someone still disable %s DVFS and cant't enable it\n", p->name); } else cpufreq_dbg("%s DVFS already enabled\n", p->name); } else { /* disable DVFS */ p->dvfs_disable_count++; if (p->dvfs_disable_by_suspend) cpufreq_dbg("%s DVFS already disabled\n", p->name); else { p->dvfs_disable_by_suspend = true; set_normal_max_opp = true; } } cpufreq_unlock(flags); if (set_normal_max_opp) { struct cpufreq_policy *policy = cpufreq_cpu_get(p->cpu_id); if (policy) { cpufreq_driver_target(policy, cpu_dvfs_get_normal_max_freq(p), CPUFREQ_RELATION_L); cpufreq_cpu_put(policy); } else { cpufreq_warn("can't get cpufreq policy to disable %s DVFS\n", p->name); ret = -1; } } set_normal_max_opp = false; } #endif FUNC_EXIT(FUNC_LV_API); return ret; } EXPORT_SYMBOL(mt_cpufreq_state_set); /* Power Table */ #if 0 #define P_MCU_L (1243) /* MCU Leakage Power */ #define P_MCU_T (2900) /* MCU Total Power */ #define P_CA7_L (110) /* CA7 Leakage Power */ #define P_CA7_T (305) /* Single CA7 Core Power */ #define P_MCL99_105C_L (1243) /* MCL99 Leakage Power @ 105C */ #define P_MCL99_25C_L (93) /* MCL99 Leakage Power @ 25C */ #define P_MCL50_105C_L (587) /* MCL50 Leakage Power @ 105C */ #define P_MCL50_25C_L (35) /* MCL50 Leakage Power @ 25C */ #define T_105 (105) /* Temperature 105C */ #define T_65 (65) /* Temperature 65C */ #define T_25 (25) /* Temperature 25C */ #define P_MCU_D ((P_MCU_T - P_MCU_L) - 8 * (P_CA7_T - P_CA7_L)) /* MCU dynamic power except of CA7 cores */ #define P_TOTAL_CORE_L ((P_MCL99_105C_L * 27049) / 100000) /* Total leakage at T_65 */ #define P_EACH_CORE_L ((P_TOTAL_CORE_L * ((P_CA7_L * 1000) / P_MCU_L)) / 1000) /* 1 core leakage at T_65 */ #define P_CA7_D_1_CORE ((P_CA7_T - P_CA7_L) * 1) /* CA7 dynamic power for 1 cores turned on */ #define P_CA7_D_2_CORE ((P_CA7_T - P_CA7_L) * 2) /* CA7 dynamic power for 2 cores turned on */ #define P_CA7_D_3_CORE ((P_CA7_T - P_CA7_L) * 3) /* CA7 dynamic power for 3 cores turned on */ #define P_CA7_D_4_CORE ((P_CA7_T - P_CA7_L) * 4) /* CA7 dynamic power for 4 cores turned on */ #define A_1_CORE (P_MCU_D + P_CA7_D_1_CORE) /* MCU dynamic power for 1 cores turned on */ #define A_2_CORE (P_MCU_D + P_CA7_D_2_CORE) /* MCU dynamic power for 2 cores turned on */ #define A_3_CORE (P_MCU_D + P_CA7_D_3_CORE) /* MCU dynamic power for 3 cores turned on */ #define A_4_CORE (P_MCU_D + P_CA7_D_4_CORE) /* MCU dynamic power for 4 cores turned on */ static void _power_calculation(struct mt_cpu_dvfs *p, int idx, int ncpu) { int multi = 0, p_dynamic = 0, p_leakage = 0, freq_ratio = 0, volt_square_ratio = 0; int possible_cpu = 0; FUNC_ENTER(FUNC_LV_HELP); possible_cpu = num_possible_cpus(); // TODO: FIXME volt_square_ratio = (((p->opp_tbl[idx].cpufreq_volt * 100) / 1000) * ((p->opp_tbl[idx].cpufreq_volt * 100) / 1000)) / 100; freq_ratio = (p->opp_tbl[idx].cpufreq_khz / 1700); cpufreq_dbg("freq_ratio = %d, volt_square_ratio %d\n", freq_ratio, volt_square_ratio); multi = ((p->opp_tbl[idx].cpufreq_volt * 100) / 1000) * ((p->opp_tbl[idx].cpufreq_volt * 100) / 1000) * ((p->opp_tbl[idx].cpufreq_volt * 100) / 1000); switch (ncpu) { case 0: /* 1 core */ p_dynamic = (((A_1_CORE * freq_ratio) / 1000) * volt_square_ratio) / 100; p_leakage = ((P_TOTAL_CORE_L - 7 * P_EACH_CORE_L) * (multi)) / (100 * 100 * 100); cpufreq_dbg("p_dynamic = %d, p_leakage = %d\n", p_dynamic, p_leakage); break; case 1: /* 2 core */ p_dynamic = (((A_2_CORE * freq_ratio) / 1000) * volt_square_ratio) / 100; p_leakage = ((P_TOTAL_CORE_L - 6 * P_EACH_CORE_L) * (multi)) / (100 * 100 * 100); cpufreq_dbg("p_dynamic = %d, p_leakage = %d\n", p_dynamic, p_leakage); break; case 2: /* 3 core */ p_dynamic = (((A_3_CORE * freq_ratio) / 1000) * volt_square_ratio) / 100; p_leakage = ((P_TOTAL_CORE_L - 5 * P_EACH_CORE_L) * (multi)) / (100 * 100 * 100); cpufreq_dbg("p_dynamic = %d, p_leakage = %d\n", p_dynamic, p_leakage); break; case 3: /* 4 core */ p_dynamic = (((A_4_CORE * freq_ratio) / 1000) * volt_square_ratio) / 100; p_leakage = ((P_TOTAL_CORE_L - 4 * P_EACH_CORE_L) * (multi)) / (100 * 100 * 100); cpufreq_dbg("p_dynamic = %d, p_leakage = %d\n", p_dynamic, p_leakage); break; default: break; } p->power_tbl[idx * possible_cpu + ncpu].cpufreq_ncpu = ncpu + 1; p->power_tbl[idx * possible_cpu + ncpu].cpufreq_khz = p->opp_tbl[idx].cpufreq_khz; p->power_tbl[idx * possible_cpu + ncpu].cpufreq_power = p_dynamic + p_leakage; cpufreq_dbg("p->power_tbl[%d]: cpufreq_ncpu = %d, cpufreq_khz = %d, cpufreq_power = %d\n", (idx * possible_cpu + ncpu), p->power_tbl[idx * possible_cpu + ncpu].cpufreq_ncpu, p->power_tbl[idx * possible_cpu + ncpu].cpufreq_khz, p->power_tbl[idx * possible_cpu + ncpu].cpufreq_power ); FUNC_EXIT(FUNC_LV_HELP); } static int setup_power_table(struct mt_cpu_dvfs *p) { static const unsigned int pwr_tbl_cgf[] = { 0, 0, 1, 0, 1, 0, 1, 0, }; unsigned int pwr_eff_tbl[NR_MAX_OPP_TBL][NR_MAX_CPU]; unsigned int pwr_eff_num; int possible_cpu; int i, j; int ret = 0; FUNC_ENTER(FUNC_LV_LOCAL); BUG_ON(NULL == p); if (p->power_tbl) goto out; cpufreq_dbg("P_MCU_D = %d\n", P_MCU_D); cpufreq_dbg("P_CA7_D_1_CORE = %d, P_CA7_D_2_CORE = %d, P_CA7_D_3_CORE = %d, P_CA7_D_4_CORE = %d\n", P_CA7_D_1_CORE, P_CA7_D_2_CORE, P_CA7_D_3_CORE, P_CA7_D_4_CORE); cpufreq_dbg("P_TOTAL_CORE_L = %d, P_EACH_CORE_L = %d\n", P_TOTAL_CORE_L, P_EACH_CORE_L); cpufreq_dbg("A_1_CORE = %d, A_2_CORE = %d, A_3_CORE = %d, A_4_CORE = %d\n", A_1_CORE, A_2_CORE, A_3_CORE, A_4_CORE); possible_cpu = num_possible_cpus(); // TODO: FIXME /* allocate power table */ memset((void *)pwr_eff_tbl, 0, sizeof(pwr_eff_tbl)); p->power_tbl = kzalloc(p->nr_opp_tbl * possible_cpu * sizeof(struct mt_cpu_power_info), GFP_KERNEL); if (NULL == p->power_tbl) { ret = -ENOMEM; goto out; } /* setup power efficiency array */ for (i = 0, pwr_eff_num = 0; i < possible_cpu; i++) { if (1 == pwr_tbl_cgf[i]) pwr_eff_num++; } for (i = 0; i < p->nr_opp_tbl; i++) { for (j = 0; j < possible_cpu; j++) { if (1 == pwr_tbl_cgf[j]) pwr_eff_tbl[i][j] = 1; } } p->nr_power_tbl = p->nr_opp_tbl * (possible_cpu - pwr_eff_num); /* calc power and fill in power table */ for (i = 0; i < p->nr_opp_tbl; i++) { for (j = 0; j < possible_cpu; j++) { if (0 == pwr_eff_tbl[i][j]) _power_calculation(p, i, j); } } /* sort power table */ for (i = p->nr_opp_tbl * possible_cpu; i > 0; i--) { for (j = 1; j < i; j++) { if (p->power_tbl[j - 1].cpufreq_power < p->power_tbl[j].cpufreq_power) { struct mt_cpu_power_info tmp; tmp.cpufreq_khz = p->power_tbl[j - 1].cpufreq_khz; tmp.cpufreq_ncpu = p->power_tbl[j - 1].cpufreq_ncpu; tmp.cpufreq_power = p->power_tbl[j - 1].cpufreq_power; p->power_tbl[j - 1].cpufreq_khz = p->power_tbl[j].cpufreq_khz; p->power_tbl[j - 1].cpufreq_ncpu = p->power_tbl[j].cpufreq_ncpu; p->power_tbl[j - 1].cpufreq_power = p->power_tbl[j].cpufreq_power; p->power_tbl[j].cpufreq_khz = tmp.cpufreq_khz; p->power_tbl[j].cpufreq_ncpu = tmp.cpufreq_ncpu; p->power_tbl[j].cpufreq_power = tmp.cpufreq_power; } } } /* dump power table */ for (i = 0; i < p->nr_opp_tbl * possible_cpu; i++) { cpufreq_dbg("[%d] = { .khz = %d, .ncup = %d, .power = %d }\n", p->power_tbl[i].cpufreq_khz, p->power_tbl[i].cpufreq_ncpu, p->power_tbl[i].cpufreq_power ); } out: FUNC_EXIT(FUNC_LV_LOCAL); return ret; } #else static void _power_calculation(struct mt_cpu_dvfs *p, int oppidx, int ncpu) { #define CA53_REF_POWER 2286 /* mW */ #define CA53_REF_FREQ 1690000 /* KHz */ #define CA53_REF_VOLT 100000 /* mV * 100 */ int p_dynamic = 0, p_leakage = 0, ref_freq, ref_volt; int possible_cpu = max_cpu_num;//num_possible_cpus(); // TODO: FIXME FUNC_ENTER(FUNC_LV_HELP); p_dynamic = CA53_REF_POWER; ref_freq = CA53_REF_FREQ; ref_volt = CA53_REF_VOLT; // TODO: should not use a hardcode value for leakage power #if 0 p_leakage = mt_spower_get_leakage(MT_SPOWER_CA7, p->opp_tbl[oppidx].cpufreq_volt / 100, 65); #else p_leakage = 262; //MC50_1.0V_65oC #endif p_dynamic = p_dynamic * (p->opp_tbl[oppidx].cpufreq_khz / 1000) / (ref_freq / 1000) * p->opp_tbl[oppidx].cpufreq_volt / ref_volt * p->opp_tbl[oppidx].cpufreq_volt / ref_volt + p_leakage; p->power_tbl[NR_MAX_OPP_TBL * (possible_cpu - 1 - ncpu) + oppidx].cpufreq_ncpu = ncpu + 1; p->power_tbl[NR_MAX_OPP_TBL * (possible_cpu - 1 - ncpu) + oppidx].cpufreq_khz = p->opp_tbl[oppidx].cpufreq_khz; p->power_tbl[NR_MAX_OPP_TBL * (possible_cpu - 1 - ncpu) + oppidx].cpufreq_power = p_dynamic * (ncpu + 1) / possible_cpu; FUNC_EXIT(FUNC_LV_HELP); } static int setup_power_table(struct mt_cpu_dvfs *p) { static const unsigned int pwr_tbl_cgf[NR_MAX_CPU] = { 0, 0, 0, 0, 0, 0, 0, 0 }; unsigned int pwr_eff_tbl[NR_MAX_OPP_TBL][NR_MAX_CPU]; unsigned int pwr_eff_num; int possible_cpu = max_cpu_num;//num_possible_cpus(); // TODO: FIXME int i, j; int ret = 0; FUNC_ENTER(FUNC_LV_LOCAL); BUG_ON(NULL == p); if (p->power_tbl) goto out; /* allocate power table */ memset((void *)pwr_eff_tbl, 0, sizeof(pwr_eff_tbl)); p->power_tbl = kzalloc(p->nr_opp_tbl * possible_cpu * sizeof(struct mt_cpu_power_info), GFP_KERNEL); if (NULL == p->power_tbl) { ret = -ENOMEM; goto out; } /* setup power efficiency array */ for (i = 0, pwr_eff_num = 0; i < possible_cpu; i++) { if (1 == pwr_tbl_cgf[i]) pwr_eff_num++; } for (i = 0; i < p->nr_opp_tbl; i++) { for (j = 0; j < possible_cpu; j++) { if (1 == pwr_tbl_cgf[j]) pwr_eff_tbl[i][j] = 1; } } p->nr_power_tbl = p->nr_opp_tbl * (possible_cpu - pwr_eff_num); /* calc power and fill in power table */ for (i = 0; i < p->nr_opp_tbl; i++) { for (j = 0; j < possible_cpu; j++) { if (0 == pwr_eff_tbl[i][j]) _power_calculation(p, i, j); } } /* sort power table */ for (i = p->nr_opp_tbl * possible_cpu; i > 0; i--) { for (j = 1; j <= i; j++) { if (p->power_tbl[j - 1].cpufreq_power < p->power_tbl[j].cpufreq_power) { struct mt_cpu_power_info tmp; tmp.cpufreq_khz = p->power_tbl[j - 1].cpufreq_khz; tmp.cpufreq_ncpu = p->power_tbl[j - 1].cpufreq_ncpu; tmp.cpufreq_power = p->power_tbl[j - 1].cpufreq_power; p->power_tbl[j - 1].cpufreq_khz = p->power_tbl[j].cpufreq_khz; p->power_tbl[j - 1].cpufreq_ncpu = p->power_tbl[j].cpufreq_ncpu; p->power_tbl[j - 1].cpufreq_power = p->power_tbl[j].cpufreq_power; p->power_tbl[j].cpufreq_khz = tmp.cpufreq_khz; p->power_tbl[j].cpufreq_ncpu = tmp.cpufreq_ncpu; p->power_tbl[j].cpufreq_power = tmp.cpufreq_power; } } } max_power_budget = p->power_tbl[0].cpufreq_power; cpufreq_ver("max_power_budget = %d\n", max_power_budget); /* dump power table */ for (i = 0; i < p->nr_opp_tbl * possible_cpu; i++) { cpufreq_ver("[%d] = { .cpufreq_khz = %d,\t.cpufreq_ncpu = %d,\t.cpufreq_power = %d }\n", i, p->power_tbl[i].cpufreq_khz, p->power_tbl[i].cpufreq_ncpu, p->power_tbl[i].cpufreq_power ); } #if 0 // def CONFIG_THERMAL // TODO: FIXME mtk_cpufreq_register(p->power_tbl, p->nr_power_tbl); #endif out: FUNC_EXIT(FUNC_LV_LOCAL); return ret; } #endif static int _mt_cpufreq_setup_freqs_table(struct cpufreq_policy *policy, struct mt_cpu_freq_info *freqs, int num) { struct mt_cpu_dvfs *p; struct cpufreq_frequency_table *table; int i, ret = 0; FUNC_ENTER(FUNC_LV_LOCAL); BUG_ON(NULL == policy); BUG_ON(NULL == freqs); p = id_to_cpu_dvfs(_get_cpu_dvfs_id(policy->cpu)); if (NULL == p->freq_tbl_for_cpufreq) { table = kzalloc((num + 1) * sizeof(*table), GFP_KERNEL); if (NULL == table) { ret = -ENOMEM; goto out; } for (i = 0; i < num; i++) { table[i].index = i; table[i].frequency = freqs[i].cpufreq_khz; } table[num].index = i; // TODO: FIXME, why need this??? table[num].frequency = CPUFREQ_TABLE_END; p->opp_tbl = freqs; p->nr_opp_tbl = num; p->freq_tbl_for_cpufreq = table; } #ifdef CONFIG_CPU_FREQ ret = cpufreq_frequency_table_cpuinfo(policy, p->freq_tbl_for_cpufreq); if (!ret) cpufreq_frequency_table_get_attr(p->freq_tbl_for_cpufreq, policy->cpu); #endif if (NULL == p->power_tbl) p->ops->setup_power_table(p); out: FUNC_EXIT(FUNC_LV_LOCAL); return 0; } void mt_cpufreq_enable_by_ptpod(enum mt_cpu_dvfs_id id) { struct mt_cpu_dvfs *p = id_to_cpu_dvfs(id); FUNC_ENTER(FUNC_LV_API); BUG_ON(NULL == p); p->dvfs_disable_by_ptpod = false; /* Turbo mode is enabled when: * 1. PTPOD is enabled * 2. Turbo bit */ if (AllowTurboMode) { cpufreq_ver("@%s: Turbo mode enabled!\n", __func__); p->turbo_mode = 1; } if (!cpu_dvfs_is_availiable(p)) { FUNC_EXIT(FUNC_LV_API); return; } _mt_cpufreq_set(id, p->idx_opp_tbl_for_late_resume); FUNC_EXIT(FUNC_LV_API); } EXPORT_SYMBOL(mt_cpufreq_enable_by_ptpod); unsigned int mt_cpufreq_disable_by_ptpod(enum mt_cpu_dvfs_id id) { struct mt_cpu_dvfs *p = id_to_cpu_dvfs(id); FUNC_ENTER(FUNC_LV_API); BUG_ON(NULL == p); p->dvfs_disable_by_ptpod = true; if (!cpu_dvfs_is_availiable(p)) { FUNC_EXIT(FUNC_LV_API); return 0; } #if 0 // XXX: BUG_ON(irqs_disabled()) @ __cpufreq_notify_transition() { struct cpufreq_policy *policy; policy = cpufreq_cpu_get(p->cpu_id); if (policy) { cpufreq_driver_target(policy, cpu_dvfs_get_normal_max_freq(p), CPUFREQ_RELATION_L); cpufreq_cpu_put(policy); } else cpufreq_warn("can't get cpufreq policy to disable %s DVFS\n", p->name); } #else p->idx_opp_tbl_for_late_resume = p->idx_opp_tbl; _mt_cpufreq_set(id, p->idx_normal_max_opp); // XXX: useless, decided @ _calc_new_opp_idx() #endif FUNC_EXIT(FUNC_LV_API); return cpu_dvfs_get_cur_freq(p); } EXPORT_SYMBOL(mt_cpufreq_disable_by_ptpod); void mt_cpufreq_thermal_protect(unsigned int limited_power) { FUNC_ENTER(FUNC_LV_API); cpufreq_ver("%s(): limited_power = %d\n", __func__, limited_power); #ifdef CONFIG_CPU_FREQ { struct cpufreq_policy *policy; struct mt_cpu_dvfs *p; int possible_cpu; int ncpu; int found = 0; unsigned long flag; int i; policy = cpufreq_cpu_get(0); // TODO: FIXME if it has more than one DVFS policy if (NULL == policy) goto no_policy; p = id_to_cpu_dvfs(_get_cpu_dvfs_id(policy->cpu)); BUG_ON(NULL == p); cpufreq_lock(flag); /* <- lock */ // save current oppidx if (!p->thermal_protect_limited_power) p->idx_opp_tbl_for_thermal_thro = p->idx_opp_tbl; p->thermal_protect_limited_power = limited_power; possible_cpu = max_cpu_num;//num_possible_cpus(); // TODO: FIXME /* no limited */ if (0 == limited_power) { p->limited_max_ncpu = possible_cpu; p->limited_max_freq = cpu_dvfs_get_max_freq(p); // restore oppidx p->idx_opp_tbl = p->idx_opp_tbl_for_thermal_thro; } else { for (ncpu = possible_cpu; ncpu > 0; ncpu--) { for (i = 0; i < p->nr_opp_tbl * possible_cpu; i++) { if (p->power_tbl[i].cpufreq_power <= limited_power) { // p->power_tbl[i].cpufreq_ncpu == ncpu && p->limited_max_ncpu = p->power_tbl[i].cpufreq_ncpu; p->limited_max_freq = p->power_tbl[i].cpufreq_khz; found = 1; ncpu = 0; /* for break outer loop */ break; } } } /* not found and use lowest power limit */ if (!found) { p->limited_max_ncpu = p->power_tbl[p->nr_power_tbl - 1].cpufreq_ncpu; p->limited_max_freq = p->power_tbl[p->nr_power_tbl - 1].cpufreq_khz; } } cpufreq_ver("found = %d, limited_max_freq = %d, limited_max_ncpu = %d\n", found, p->limited_max_freq, p->limited_max_ncpu); cpufreq_unlock(flag); /* <- unlock */ hps_set_cpu_num_limit(LIMIT_THERMAL, p->limited_max_ncpu, 0); // correct opp idx will be calcualted in _thermal_limited_verify() _mt_cpufreq_set(MT_CPU_DVFS_LITTLE, -1); cpufreq_cpu_put(policy); /* <- policy put */ } no_policy: #endif FUNC_EXIT(FUNC_LV_API); } EXPORT_SYMBOL(mt_cpufreq_thermal_protect); /* for ramp down */ void mt_cpufreq_set_ramp_down_count_const(enum mt_cpu_dvfs_id id, int count) { struct mt_cpu_dvfs *p = id_to_cpu_dvfs(id); BUG_ON(NULL == p); p->ramp_down_count_const = count; } EXPORT_SYMBOL(mt_cpufreq_set_ramp_down_count_const); #ifdef CONFIG_CPU_DVFS_RAMP_DOWN static int _keep_max_freq(struct mt_cpu_dvfs *p, unsigned int freq_old, unsigned int freq_new) // TODO: inline @ mt_cpufreq_target() { int ret = 0; FUNC_ENTER(FUNC_LV_HELP); if (RAMP_DOWN_TIMES < p->ramp_down_count_const) p->ramp_down_count_const--; else p->ramp_down_count_const = RAMP_DOWN_TIMES; if (freq_new < freq_old && p->ramp_down_count < p->ramp_down_count_const) { ret = 1; p->ramp_down_count++; } else p->ramp_down_count = 0; FUNC_ENTER(FUNC_LV_HELP); return ret; } #endif static int _thermal_limited_verify(struct mt_cpu_dvfs *p, int new_opp_idx) { unsigned int target_khz = cpu_dvfs_get_freq_by_idx(p, new_opp_idx); int possible_cpu = 0; unsigned int online_cpu = 0; int found = 0; int i; FUNC_ENTER(FUNC_LV_HELP); possible_cpu = max_cpu_num; //num_possible_cpus(); // TODO: FIXME online_cpu = num_online_cpus(); // TODO: FIXME //cpufreq_dbg("%s(): begin, idx = %d, online_cpu = %d\n", __func__, new_opp_idx, online_cpu); /* no limited */ if (0 == p->thermal_protect_limited_power) return new_opp_idx; for (i = 0; i < p->nr_opp_tbl * possible_cpu; i++) { if (p->power_tbl[i].cpufreq_ncpu == p->limited_max_ncpu && p->power_tbl[i].cpufreq_khz == p->limited_max_freq ) break; } cpufreq_ver("%s(): idx = %d, limited_max_ncpu = %d, limited_max_freq = %d\n", __func__, i, p->limited_max_ncpu, p->limited_max_freq); for (; i < p->nr_opp_tbl * possible_cpu; i++) { if (p->power_tbl[i].cpufreq_ncpu == online_cpu) { if (target_khz >= p->power_tbl[i].cpufreq_khz) { found = 1; break; } } } if (found) { target_khz = p->power_tbl[i].cpufreq_khz; cpufreq_ver("%s(): freq found, idx = %d, target_khz = %d, online_cpu = %d\n", __func__, i, target_khz, online_cpu); } else { target_khz = p->limited_max_freq; cpufreq_ver("%s(): freq not found, set to limited_max_freq = %d\n", __func__, target_khz); } i = _search_available_freq_idx(p, target_khz, CPUFREQ_RELATION_H); // TODO: refine this function for idx searching FUNC_EXIT(FUNC_LV_HELP); return i; } static unsigned int _calc_new_opp_idx(struct mt_cpu_dvfs *p, int new_opp_idx) { int idx; FUNC_ENTER(FUNC_LV_HELP); BUG_ON(NULL == p); /* for ramp down */ #ifdef CONFIG_CPU_DVFS_RAMP_DOWN if (_keep_max_freq(p, cpu_dvfs_get_cur_freq(p), cpu_dvfs_get_freq_by_idx(p, new_opp_idx))) { cpufreq_ver("%s(): ramp down, idx = %d, freq_old = %d, freq_new = %d\n", __func__, new_opp_idx, cpu_dvfs_get_cur_freq(p), cpu_dvfs_get_freq_by_idx(p, new_opp_idx) ); new_opp_idx = p->idx_opp_tbl; } #endif /* HEVC */ if (p->limited_freq_by_hevc) { idx = _search_available_freq_idx(p, p->limited_freq_by_hevc, CPUFREQ_RELATION_L); if ((idx != -1) && (new_opp_idx > idx)) { new_opp_idx = idx; cpufreq_ver("%s(): hevc limited freq, idx = %d\n", __func__, new_opp_idx); } } #ifdef CONFIG_CPU_DVFS_DOWNGRADE_FREQ if (true == p->downgrade_freq_for_ptpod) { if (cpu_dvfs_get_freq_by_idx(p, new_opp_idx) > p->downgrade_freq) { idx = _search_available_freq_idx(p, p->downgrade_freq, CPUFREQ_RELATION_H); if (idx != -1) { new_opp_idx = idx; cpufreq_ver("%s(): downgrade freq, idx = %d\n", __func__, new_opp_idx); } } } #endif /* CONFIG_CPU_DVFS_DOWNGRADE_FREQ */ /* search thermal limited freq */ idx = _thermal_limited_verify(p, new_opp_idx); if (idx != -1 && idx != new_opp_idx) { new_opp_idx = idx; cpufreq_ver("%s(): thermal limited freq, idx = %d\n", __func__, new_opp_idx); } /* for early suspend */ if (p->dvfs_disable_by_early_suspend) { if (new_opp_idx > p->idx_normal_max_opp) new_opp_idx = p->idx_normal_max_opp; cpufreq_ver("%s(): for early suspend, idx = %d\n", __func__, new_opp_idx); } /* for suspend */ if (p->dvfs_disable_by_suspend) new_opp_idx = p->idx_normal_max_opp; /* for power throttling */ #ifdef CONFIG_CPU_DVFS_POWER_THROTTLING if (p->pwr_thro_mode & (PWR_THRO_MODE_BAT_OC_1183MHZ)) { if (new_opp_idx < CPU_DVFS_OPPIDX_1183MHZ) cpufreq_ver("%s(): for power throttling = %d\n", __func__, CPU_DVFS_OPPIDX_1183MHZ); new_opp_idx = (new_opp_idx < CPU_DVFS_OPPIDX_1183MHZ) ? CPU_DVFS_OPPIDX_1183MHZ : new_opp_idx; } else if (p->pwr_thro_mode & (PWR_THRO_MODE_LBAT_806MHZ | PWR_THRO_MODE_BAT_PER_806MHZ)) { if (new_opp_idx < CPU_DVFS_OPPIDX_806MHZ) cpufreq_ver("%s(): for power throttling = %d\n", __func__, CPU_DVFS_OPPIDX_806MHZ); new_opp_idx = (new_opp_idx < CPU_DVFS_OPPIDX_806MHZ) ? CPU_DVFS_OPPIDX_806MHZ : new_opp_idx; } #endif /* limit max freq by user */ if (p->limited_max_freq_by_user) { idx = _search_available_freq_idx(p, p->limited_max_freq_by_user, CPUFREQ_RELATION_H); if (idx != -1 && new_opp_idx < idx) { new_opp_idx = idx; cpufreq_ver("%s(): limited max freq by user, idx = %d\n", __func__, new_opp_idx); } } /* for ptpod init */ if (p->dvfs_disable_by_ptpod) { // at least CPU_DVFS_FREQ5 will make sure VBoot >= 1V idx = _search_available_freq_idx(p, CPU_DVFS_FREQ5, CPUFREQ_RELATION_L); if (idx != -1) { new_opp_idx = idx; cpufreq_ver("%s(): for ptpod init, idx = %d\n", __func__, new_opp_idx); } } #ifdef CONFIG_CPU_DVFS_AEE_RR_REC aee_rr_rec_cpu_dvfs_oppidx((aee_rr_curr_cpu_dvfs_oppidx() & 0xF0) | new_opp_idx); #endif FUNC_EXIT(FUNC_LV_HELP); return new_opp_idx; } #ifdef CONFIG_CPU_DVFS_POWER_THROTTLING static void bat_per_protection_powerlimit(BATTERY_PERCENT_LEVEL level) { struct mt_cpu_dvfs *p; int i; unsigned long flags; for_each_cpu_dvfs(i, p) { if (!cpu_dvfs_is_availiable(p)) continue; cpufreq_lock(flags); if (!p->pwr_thro_mode) p->idx_opp_tbl_for_pwr_thro = p->idx_opp_tbl; switch (level) { case BATTERY_PERCENT_LEVEL_1: // Trigger CPU Limit to under CA53 x 4 + 806MHz p->pwr_thro_mode |= PWR_THRO_MODE_BAT_PER_806MHZ; break; default: // unlimit cpu and gpu p->pwr_thro_mode &= ~PWR_THRO_MODE_BAT_PER_806MHZ; break; } if (!p->pwr_thro_mode) p->idx_opp_tbl = p->idx_opp_tbl_for_pwr_thro; cpufreq_unlock(flags); _mt_cpufreq_set(MT_CPU_DVFS_LITTLE, p->idx_opp_tbl); switch (level) { case BATTERY_PERCENT_LEVEL_1: // Trigger CPU Limit to under CA53 x 4 + 806MHz hps_set_cpu_num_limit(LIMIT_LOW_BATTERY, 4, 0); // TODO: FIXME break; default: // unlimit cpu and gpu hps_set_cpu_num_limit(LIMIT_LOW_BATTERY, max_cpu_num, 0); // TODO: FIXME break; } } } static void bat_oc_protection_powerlimit(BATTERY_OC_LEVEL level) { struct mt_cpu_dvfs *p; int i; unsigned long flags; for_each_cpu_dvfs(i, p) { if (!cpu_dvfs_is_availiable(p)) /* just for big */ continue; cpufreq_lock(flags); if (!p->pwr_thro_mode) p->idx_opp_tbl_for_pwr_thro = p->idx_opp_tbl; switch (level) { case BATTERY_OC_LEVEL_1: // battery OC trigger CPU Limit to under CA53 x 8 + 1.183GHz p->pwr_thro_mode |= PWR_THRO_MODE_BAT_OC_1183MHZ; break; default: // unlimit cpu and gpu p->pwr_thro_mode &= ~PWR_THRO_MODE_BAT_OC_1183MHZ; break; } if (!p->pwr_thro_mode) p->idx_opp_tbl = p->idx_opp_tbl_for_pwr_thro; cpufreq_unlock(flags); _mt_cpufreq_set(MT_CPU_DVFS_LITTLE, p->idx_opp_tbl); } } void Lbat_protection_powerlimit(LOW_BATTERY_LEVEL level) { struct mt_cpu_dvfs *p; int i; unsigned long flags; for_each_cpu_dvfs(i, p) { if (!cpu_dvfs_is_availiable(p)) continue; cpufreq_lock(flags); if (!p->pwr_thro_mode) p->idx_opp_tbl_for_pwr_thro = p->idx_opp_tbl; switch (level) { case LOW_BATTERY_LEVEL_1: //1st LV trigger CPU Limit to under CA53 x 4 + 806MHz p->pwr_thro_mode |= PWR_THRO_MODE_LBAT_806MHZ; break; case LOW_BATTERY_LEVEL_2: //2nd LV trigger CPU Limit to under CA53 x 4 + 806MHz p->pwr_thro_mode |= PWR_THRO_MODE_LBAT_806MHZ; break; default: //unlimit cpu and gpu p->pwr_thro_mode &= ~PWR_THRO_MODE_LBAT_806MHZ; break; } if (!p->pwr_thro_mode) p->idx_opp_tbl = p->idx_opp_tbl_for_pwr_thro; cpufreq_unlock(flags); _mt_cpufreq_set(MT_CPU_DVFS_LITTLE , p->idx_opp_tbl); switch (level) { case LOW_BATTERY_LEVEL_1: //1st LV trigger CPU Limit to under CA7 x 4 hps_set_cpu_num_limit(LIMIT_LOW_BATTERY, 4, 0); // TODO: FIXME break; case LOW_BATTERY_LEVEL_2: //2nd LV trigger CPU Limit to under CA7 x 4 + 1.36G hps_set_cpu_num_limit(LIMIT_LOW_BATTERY, 4, 0); // TODO: FIXME break; default: //unlimit cpu and gpu hps_set_cpu_num_limit(LIMIT_LOW_BATTERY, max_cpu_num, 0); // TODO: FIXME break; } } } #endif /* * Return value definitions * 0: 26M, * 1: 3 PLL, * 2: 1 PLL */ unsigned int mt_get_clk_mem_sel(void) { unsigned int val; //CLK_CFG_0(0x10000040)[9:8] //clk_mem_sel //2'b00:clk26m //2'b01:dmpll_ck->3PLL //2'b10:ddr_x1_ck->1PLL val = (*(volatile unsigned int *)(CLK_CFG_0)); val = (val >> 8) & 0x3; return val; } EXPORT_SYMBOL(mt_get_clk_mem_sel); /* * cpufreq driver */ static int _mt_cpufreq_verify(struct cpufreq_policy *policy) { struct mt_cpu_dvfs *p; int ret = 0; /* cpufreq_frequency_table_verify() always return 0 */ FUNC_ENTER(FUNC_LV_MODULE); p = id_to_cpu_dvfs(_get_cpu_dvfs_id(policy->cpu)); BUG_ON(NULL == p); #ifdef CONFIG_CPU_FREQ ret = cpufreq_frequency_table_verify(policy, p->freq_tbl_for_cpufreq); #endif FUNC_EXIT(FUNC_LV_MODULE); return ret; } static int _mt_cpufreq_target(struct cpufreq_policy *policy, unsigned int target_freq, unsigned int relation) { // unsigned int cpu; // XXX: move to _cpufreq_set_locked() // struct cpufreq_freqs freqs; // XXX: move to _cpufreq_set_locked() unsigned int new_opp_idx; enum mt_cpu_dvfs_id id = _get_cpu_dvfs_id(policy->cpu); // unsigned long flags; // XXX: move to _mt_cpufreq_set() int ret = 0; /* -EINVAL; */ FUNC_ENTER(FUNC_LV_MODULE); if (policy->cpu >= max_cpu_num || cpufreq_frequency_table_target(policy, id_to_cpu_dvfs(id)->freq_tbl_for_cpufreq, target_freq, relation, &new_opp_idx) || (id_to_cpu_dvfs(id) && id_to_cpu_dvfs(id)->dvfs_disable_by_procfs) ) return -EINVAL; // freqs.old = policy->cur; // XXX: move to _cpufreq_set_locked() // freqs.new = mt_cpufreq_max_frequency_by_DVS(id, new_opp_idx); // XXX: move to _cpufreq_set_locked() // freqs.cpu = policy->cpu; // XXX: move to _cpufreq_set_locked() // for_each_online_cpu(cpu) { // TODO: big LITTLE issue (id mapping) // XXX: move to _cpufreq_set_locked() // freqs.cpu = cpu; // XXX: move to _cpufreq_set_locked() // cpufreq_notify_transition(policy, &freqs, CPUFREQ_PRECHANGE); // XXX: move to _cpufreq_set_locked() // } // XXX: move to _cpufreq_set_locked() // cpufreq_lock(flags); // XXX: move to _mt_cpufreq_set() #ifdef CONFIG_CPU_DVFS_AEE_RR_REC aee_rr_rec_cpu_dvfs_status(aee_rr_curr_cpu_dvfs_status() | (1 << CPU_DVFS_LITTLE_IS_DOING_DVFS)); #endif _mt_cpufreq_set(id, new_opp_idx); #ifdef CONFIG_CPU_DVFS_AEE_RR_REC aee_rr_rec_cpu_dvfs_status(aee_rr_curr_cpu_dvfs_status() & ~(1 << CPU_DVFS_LITTLE_IS_DOING_DVFS)); #endif // cpufreq_unlock(flags); // XXX: move to _mt_cpufreq_set() // for_each_online_cpu(cpu) { // TODO: big LITTLE issue (id mapping) // XXX: move to _cpufreq_set_locked() // freqs.cpu = cpu; // XXX: move to _cpufreq_set_locked() // cpufreq_notify_transition(policy, &freqs, CPUFREQ_POSTCHANGE); // XXX: move to _cpufreq_set_locked() // } // XXX: move to _cpufreq_set_locked() FUNC_EXIT(FUNC_LV_MODULE); return ret; } static int _mt_cpufreq_init(struct cpufreq_policy *policy) { int ret = -EINVAL; FUNC_ENTER(FUNC_LV_MODULE); max_cpu_num = num_possible_cpus(); if (policy->cpu >= max_cpu_num) // TODO: FIXME return -EINVAL; cpufreq_info("@%s: max_cpu_num: %d\n", __func__, max_cpu_num); policy->shared_type = CPUFREQ_SHARED_TYPE_ANY; cpumask_setall(policy->cpus); /******************************************************* * 1 us, assumed, will be overwrited by min_sampling_rate ********************************************************/ policy->cpuinfo.transition_latency = 1000; /********************************************* * set default policy and cpuinfo, unit : Khz **********************************************/ { #define DORMANT_MODE_VOLT 80000 enum mt_cpu_dvfs_id id = _get_cpu_dvfs_id(policy->cpu); struct mt_cpu_dvfs *p = id_to_cpu_dvfs(id); unsigned int lv = _mt_cpufreq_get_cpu_level(); struct opp_tbl_info *opp_tbl_info = &opp_tbls[CPU_LV_TO_OPP_IDX(lv)]; unsigned int lock_code = get_devinfo_with_index(23); if ((lock_code & 0x1) == 0) { opp_tbl_info->opp_tbl[0].cpufreq_volt = 112500; opp_tbl_info->opp_tbl[0].cpufreq_volt_org = 112500; } BUG_ON(NULL == p); BUG_ON(!(lv == CPU_LEVEL_0 || lv == CPU_LEVEL_1 || lv == CPU_LEVEL_2)); p->cpu_level = lv; // set dpidle volt for Vsram // pmic_config_interface(PMIC_ADDR_VSRAM_VOSEL_CTRL, 0x1, 0x1, 0x1); //pmic_config_interface(PMIC_ADDR_VSRAM_VOSEL_ON, VOLT_TO_PMIC_VAL(MIN_VSRAM_VOLT), 0x7F, 0x9); // Set RG_VSRAM_VOSEL[15:9] to 0.93125v pwrap_write(0x8490, 0x1);// pwrap_write(0x8424, 0x0);//auto-track off ret = _mt_cpufreq_setup_freqs_table(policy, opp_tbl_info->opp_tbl, opp_tbl_info->size ); policy->cpuinfo.max_freq = cpu_dvfs_get_max_freq(id_to_cpu_dvfs(id)); policy->cpuinfo.min_freq = cpu_dvfs_get_min_freq(id_to_cpu_dvfs(id)); policy->cur = _mt_cpufreq_get_cur_phy_freq(id); /* use cur phy freq is better */ policy->max = cpu_dvfs_get_max_freq(id_to_cpu_dvfs(id)); policy->min = cpu_dvfs_get_min_freq(id_to_cpu_dvfs(id)); if (_sync_opp_tbl_idx(p) >= 0) /* sync p->idx_opp_tbl first before _restore_default_volt() */ p->idx_normal_max_opp = p->idx_opp_tbl; /* restore default volt, sync opp idx, set default limit */ if (cpu_dvfs_is_extbuck_valid()) _restore_default_volt(p); _set_no_limited(p); #ifdef CONFIG_CPU_DVFS_DOWNGRADE_FREQ _init_downgrade(p, _mt_cpufreq_get_cpu_level()); #endif #ifdef CONFIG_CPU_DVFS_POWER_THROTTLING register_battery_percent_notify(&bat_per_protection_powerlimit, BATTERY_PERCENT_PRIO_CPU_L); register_battery_oc_notify(&bat_oc_protection_powerlimit, BATTERY_OC_PRIO_CPU_L); register_low_battery_notify(&Lbat_protection_powerlimit, LOW_BATTERY_PRIO_CPU_L); #endif } if (ret) cpufreq_err("failed to setup frequency table\n"); FUNC_EXIT(FUNC_LV_MODULE); return ret; } static unsigned int _mt_cpufreq_get(unsigned int cpu) { struct mt_cpu_dvfs *p; FUNC_ENTER(FUNC_LV_MODULE); p = id_to_cpu_dvfs(_get_cpu_dvfs_id(cpu)); BUG_ON(NULL == p); FUNC_EXIT(FUNC_LV_MODULE); return cpu_dvfs_get_cur_freq(p); } /* * Early suspend */ static bool _allow_dpidle_ctrl_vproc = false; bool mt_cpufreq_earlysuspend_status_get(void) { return _allow_dpidle_ctrl_vproc; } EXPORT_SYMBOL(mt_cpufreq_earlysuspend_status_get); #ifdef CONFIG_HAS_EARLYSUSPEND static void _mt_cpufreq_early_suspend(struct early_suspend *h) { struct cpufreq_policy *policy; struct mt_cpu_dvfs *p; int i; FUNC_ENTER(FUNC_LV_MODULE); // mt_cpufreq_state_set(0); // TODO: it is not necessary because of dvfs_disable_by_early_suspend // mt_cpufreq_set_pmic_phase(PMIC_WRAP_PHASE_DEEPIDLE); // TODO: move to deepidle driver for_each_cpu_dvfs(i, p) { if (!cpu_dvfs_is_availiable(p)) continue; p->dvfs_disable_by_early_suspend = true; p->idx_opp_tbl_for_late_resume = p->idx_opp_tbl; #ifdef CONFIG_CPU_FREQ policy = cpufreq_cpu_get(p->cpu_id); if (policy) { cpufreq_driver_target(policy, cpu_dvfs_get_normal_max_freq(p), CPUFREQ_RELATION_L); cpufreq_cpu_put(policy); } #endif } _allow_dpidle_ctrl_vproc = true; FUNC_EXIT(FUNC_LV_MODULE); } static void _mt_cpufreq_late_resume(struct early_suspend *h) { struct cpufreq_policy *policy; struct mt_cpu_dvfs *p; int i; FUNC_ENTER(FUNC_LV_MODULE); _allow_dpidle_ctrl_vproc = false; for_each_cpu_dvfs(i, p) { if (!cpu_dvfs_is_availiable(p)) continue; p->dvfs_disable_by_early_suspend = false; #ifdef CONFIG_CPU_FREQ policy = cpufreq_cpu_get(p->cpu_id); if (policy) { cpufreq_driver_target(policy, cpu_dvfs_get_freq_by_idx(p, p->idx_opp_tbl_for_late_resume), CPUFREQ_RELATION_L); cpufreq_cpu_put(policy); } #endif } // mt_cpufreq_set_pmic_phase(PMIC_WRAP_PHASE_NORMAL); // TODO: move to deepidle driver // mt_cpufreq_state_set(1); // TODO: it is not necessary because of dvfs_disable_by_early_suspend FUNC_EXIT(FUNC_LV_MODULE); } //#ifdef CONFIG_HAS_EARLYSUSPEND static struct early_suspend _mt_cpufreq_early_suspend_handler = { .level = EARLY_SUSPEND_LEVEL_DISABLE_FB + 200, .suspend = _mt_cpufreq_early_suspend, .resume = _mt_cpufreq_late_resume, }; #endif /* CONFIG_HAS_EARLYSUSPEND */ #ifdef CONFIG_CPU_FREQ static struct freq_attr *_mt_cpufreq_attr[] = { &cpufreq_freq_attr_scaling_available_freqs, NULL, }; static struct cpufreq_driver _mt_cpufreq_driver = { .verify = _mt_cpufreq_verify, .target = _mt_cpufreq_target, .init = _mt_cpufreq_init, .get = _mt_cpufreq_get, .name = "mt-cpufreq", .attr = _mt_cpufreq_attr, }; #endif /* * Platform driver */ static int _mt_cpufreq_suspend(struct device *dev) { //struct cpufreq_policy *policy; struct mt_cpu_dvfs *p; int i; FUNC_ENTER(FUNC_LV_MODULE); // mt_cpufreq_set_pmic_phase(PMIC_WRAP_PHASE_SUSPEND); // TODO: move to suspend driver for_each_cpu_dvfs(i, p) { if (!cpu_dvfs_is_availiable(p)) continue; p->dvfs_disable_by_suspend = true; #if 0 // XXX: cpufreq_driver_target doesn't work @ suspend policy = cpufreq_cpu_get(p->cpu_id); if (policy) { cpufreq_driver_target(policy, cpu_dvfs_get_normal_max_freq(p), CPUFREQ_RELATION_L); cpufreq_cpu_put(policy); } #else _mt_cpufreq_set(MT_CPU_DVFS_LITTLE, p->idx_normal_max_opp); // XXX: useless, decided @ _calc_new_opp_idx() #endif } FUNC_EXIT(FUNC_LV_MODULE); return 0; } static int _mt_cpufreq_resume(struct device *dev) { struct mt_cpu_dvfs *p; int i; FUNC_ENTER(FUNC_LV_MODULE); // mt_cpufreq_set_pmic_phase(PMIC_WRAP_PHASE_NORMAL); // TODO: move to suspend driver for_each_cpu_dvfs(i, p) { if (!cpu_dvfs_is_availiable(p)) continue; p->dvfs_disable_by_suspend = false; } FUNC_EXIT(FUNC_LV_MODULE); return 0; } static int _mt_cpufreq_pm_restore_early(struct device *dev) /* for IPO-H HW(freq) / SW(opp_tbl_idx) */ // TODO: DON'T CARE??? { FUNC_ENTER(FUNC_LV_MODULE); _mt_cpufreq_sync_opp_tbl_idx(); FUNC_EXIT(FUNC_LV_MODULE); return 0; } static int _mt_cpufreq_pdrv_probe(struct platform_device *pdev) { FUNC_ENTER(FUNC_LV_MODULE); // TODO: check extBuck init with James if (pw.addr[0].cmd_addr == 0) _mt_cpufreq_pmic_table_init(); # if 0 // TODO: FIXME <-- disable to avoid build error (Brian) /* init static power table */ mt_spower_init(); #endif #ifdef CONFIG_CPU_DVFS_AEE_RR_REC _mt_cpufreq_aee_init(); #endif /* register early suspend */ #ifdef CONFIG_HAS_EARLYSUSPEND register_early_suspend(&_mt_cpufreq_early_suspend_handler); #endif /* init PMIC_WRAP & volt */ mt_cpufreq_set_pmic_phase(PMIC_WRAP_PHASE_NORMAL); #if 0 // TODO: FIXME /* restore default volt, sync opp idx, set default limit */ { struct mt_cpu_dvfs *p; int i; for_each_cpu_dvfs(i, p) { if (!cpu_dvfs_is_availiable(p)) continue; _restore_default_volt(p); if (_sync_opp_tbl_idx(p) >= 0) p->idx_normal_max_opp = p->idx_opp_tbl; _set_no_limited(p); #if defined(CONFIG_CPU_DVFS_DOWNGRADE_FREQ) _init_downgrade(p, read_efuse_cpu_speed()); #endif } } #endif #ifdef CONFIG_CPU_FREQ cpufreq_register_driver(&_mt_cpufreq_driver); #endif register_hotcpu_notifier(&turbo_mode_cpu_notifier); // <-XXX FUNC_EXIT(FUNC_LV_MODULE); return 0; } static int _mt_cpufreq_pdrv_remove(struct platform_device *pdev) { FUNC_ENTER(FUNC_LV_MODULE); unregister_hotcpu_notifier(&turbo_mode_cpu_notifier); // <-XXX #ifdef CONFIG_CPU_FREQ cpufreq_unregister_driver(&_mt_cpufreq_driver); #endif FUNC_EXIT(FUNC_LV_MODULE); return 0; } static const struct dev_pm_ops _mt_cpufreq_pm_ops = { .suspend = _mt_cpufreq_suspend, .resume = _mt_cpufreq_resume, .restore_early = _mt_cpufreq_pm_restore_early, .freeze = _mt_cpufreq_suspend, .thaw = _mt_cpufreq_resume, .restore = _mt_cpufreq_resume, }; struct platform_device _mt_cpufreq_pdev = { .name = "mt-cpufreq", .id = -1, }; static struct platform_driver _mt_cpufreq_pdrv = { .probe = _mt_cpufreq_pdrv_probe, .remove = _mt_cpufreq_pdrv_remove, .driver = { .name = "mt-cpufreq", .pm = &_mt_cpufreq_pm_ops, .owner = THIS_MODULE, }, }; #ifndef __KERNEL__ /* * For CTP */ int mt_cpufreq_pdrv_probe(void) { static struct cpufreq_policy policy; _mt_cpufreq_pdrv_probe(NULL); policy.cpu = cpu_dvfs[MT_CPU_DVFS_LITTLE].cpu_id; _mt_cpufreq_init(&policy); return 0; } int mt_cpufreq_set_opp_volt(enum mt_cpu_dvfs_id id, int idx)//for volt & stress test { int ret = 0; static struct opp_tbl_info *info; struct mt_cpu_dvfs *p = id_to_cpu_dvfs(id); info = &opp_tbls[CPU_LV_TO_OPP_IDX(p->cpu_level)]; if (idx >= info->size) return -1; return _set_cur_volt_locked(p, info->opp_tbl[idx].cpufreq_volt); } int mt_cpufreq_set_freq(enum mt_cpu_dvfs_id id, int idx)//for freq & stress test { unsigned int cur_freq; unsigned int target_freq; int ret; struct mt_cpu_dvfs *p = id_to_cpu_dvfs(id); cur_freq = p->ops->get_cur_phy_freq(p); target_freq = cpu_dvfs_get_freq_by_idx(p, idx); #ifdef CONFIG_CPU_FREQ ret = _cpufreq_set_locked(p, cur_freq, target_freq, policy); #else ret = _cpufreq_set_locked(p, cur_freq, target_freq, NULL); #endif if (ret < 0) return ret; return target_freq; } #include "dvfs.h" /* MCUSYS Register */ // APB Module ca15l_config #define CA15L_CONFIG_BASE (0x10200200) #define IR_ROSC_CTL (MCUCFG_BASE + 0x030) #define pminit_write(addr, val) mt65xx_reg_sync_writel((val), ((void *)addr)) static unsigned int _mt_get_cpu_freq(enum top_ckmuxsel sel) { int output = 0; unsigned int temp, clk26cali_0, clk_cfg_8, clk_misc_cfg_1, clk26cali_1; unsigned int top_ckmuxsel, top_ckdiv1, ir_rosc_ctl; unsigned int ckdiv1; clk26cali_0 = DRV_Reg32(CLK26CALI_0); pminit_write(CLK26CALI_0, clk26cali_0 | 0x80); // enable fmeter_en clk_misc_cfg_1 = DRV_Reg32(CLK_MISC_CFG_1); pminit_write(CLK_MISC_CFG_1, 0xFFFFFF00); // select divider clk_cfg_8 = DRV_Reg32(CLK_CFG_8); pminit_write(CLK_CFG_8, (46 << 8)); // select abist_cksw top_ckmuxsel = DRV_Reg32(TOP_CKMUXSEL); pminit_write(TOP_CKMUXSEL, (top_ckmuxsel & 0xFFFFFFFC) | sel); top_ckdiv1 = DRV_Reg32(TOP_CKDIV1); ckdiv1 = _GET_BITS_VAL_(4 : 0, top_ckdiv1); pminit_write(TOP_CKDIV1, (top_ckdiv1 & 0xFFFFFFE0) | 0xb); ir_rosc_ctl = DRV_Reg32(IR_ROSC_CTL); pminit_write(IR_ROSC_CTL, ir_rosc_ctl | 0x08100000); temp = DRV_Reg32(CLK26CALI_0); pminit_write(CLK26CALI_0, temp | 0x1); // start fmeter /* wait frequency meter finish */ while (DRV_Reg32(CLK26CALI_0) & 0x1) { printf("wait for frequency meter finish, CLK26CALI = 0x%x\n", DRV_Reg32(CLK26CALI_0)); //mdelay(10); } temp = DRV_Reg32(CLK26CALI_1) & 0xFFFF; output = ((temp * 26000) / 1024) * 4; // Khz output = _cpu_freq_calc(output, ckdiv1); pminit_write(CLK_CFG_8, clk_cfg_8); pminit_write(CLK_MISC_CFG_1, clk_misc_cfg_1); pminit_write(CLK26CALI_0, clk26cali_0); pminit_write(TOP_CKMUXSEL, top_ckmuxsel); pminit_write(TOP_CKDIV1, top_ckdiv1); pminit_write(IR_ROSC_CTL, ir_rosc_ctl); //print("CLK26CALI = 0x%x, cpu frequency = %d Khz\n", temp, output); return output; } unsigned int dvfs_get_cpu_freq(enum mt_cpu_dvfs_id id, enum top_ckmuxsel sel)//for freq & stress test { //return _mt_cpufreq_get_cur_phy_freq(id); return (MT_CPU_DVFS_LITTLE == id) ? _mt_get_cpu_freq(sel) : 0; } void dvfs_set_cpu_freq_FH(enum mt_cpu_dvfs_id id, int freq)//for freq & stress test { struct mt_cpu_dvfs *p = id_to_cpu_dvfs(id); int idx; if (!p) { cpufreq_err("%s(%d, %d), id is wrong\n", __func__, id, freq); return; } idx = _search_available_freq_idx(p, freq, CPUFREQ_RELATION_H); if (-1 == idx) { cpufreq_err("%s(%d, %d), freq is wrong\n", __func__, id, freq); return; } mt_cpufreq_set_freq(id, idx); } unsigned int cpu_frequency_output_slt(enum mt_cpu_dvfs_id id, enum top_ckmuxsel sel) { return (MT_CPU_DVFS_LITTLE == id) ? _mt_get_cpu_freq(sel) : 0; } void dvfs_set_cpu_volt(enum mt_cpu_dvfs_id id, int volt) // volt: mv * 100 //for REG test { struct mt_cpu_dvfs *p = id_to_cpu_dvfs(id); cpufreq_dbg("%s(%d, %d)\n", __func__, id, volt); if (!p) { cpufreq_err("%s(%d, %d), id is wrong\n", __func__, id, volt); return; } if (_set_cur_volt_locked(p, volt)) cpufreq_err("%s(%d, %d), set volt fail\n", __func__, id, volt); cpufreq_dbg("%s(%d, %d) Vproc = %d, Vsram = %d\n", __func__, id, volt, p->ops->get_cur_volt(p), get_cur_vsram(p) ); } void dvfs_set_gpu_volt(int pmic_val) { cpufreq_dbg("%s(%d)\n", __func__, pmic_val); mt_cpufreq_set_pmic_cmd(PMIC_WRAP_PHASE_NORMAL, IDX_NM_VGPU, pmic_val); mt_cpufreq_apply_pmic_cmd(IDX_NM_VGPU); } #if 0 /* NOTE: This is ONLY for PTPOD SLT. Should not adjust VCORE in other cases. */ void dvfs_set_vcore_ao_volt(int pmic_val) { cpufreq_dbg("%s(%d)\n", __func__, pmic_val); mt_cpufreq_set_pmic_cmd(PMIC_WRAP_PHASE_NORMAL, IDX_NM_VCORE, pmic_val); mt_cpufreq_apply_pmic_cmd(IDX_NM_VCORE); } #endif void dvfs_set_vcore_pdn_volt(int pmic_val) { cpufreq_dbg("%s(%d)\n", __func__, pmic_val); mt_cpufreq_set_pmic_phase(PMIC_WRAP_PHASE_DEEPIDLE); mt_cpufreq_set_pmic_cmd(PMIC_WRAP_PHASE_DEEPIDLE, IDX_DI_VCORE_PDN_NORMAL, pmic_val); mt_cpufreq_apply_pmic_cmd(IDX_DI_VCORE_PDN_NORMAL); mt_cpufreq_set_pmic_phase(PMIC_WRAP_PHASE_SODI); mt_cpufreq_set_pmic_cmd(PMIC_WRAP_PHASE_SODI, IDX_SO_VCORE_PDN_NORMAL, pmic_val); mt_cpufreq_apply_pmic_cmd(IDX_SO_VCORE_PDN_NORMAL); mt_cpufreq_set_pmic_phase(PMIC_WRAP_PHASE_NORMAL); } void dvfs_set_vlte_volt(int pmic_val) { cpufreq_dbg("%s(%d)\n", __func__, pmic_val); mt_cpufreq_set_pmic_phase(PMIC_WRAP_PHASE_DEEPIDLE); mt_cpufreq_set_pmic_cmd(PMIC_WRAP_PHASE_DEEPIDLE, IDX_DI_VPROC_CA7_NORMAL, pmic_val); mt_cpufreq_apply_pmic_cmd(IDX_DI_VPROC_CA7_NORMAL); mt_cpufreq_set_pmic_phase(PMIC_WRAP_PHASE_SODI); mt_cpufreq_set_pmic_cmd(PMIC_WRAP_PHASE_SODI, IDX_SO_VPROC_CA7_NORMAL, pmic_val); mt_cpufreq_apply_pmic_cmd(IDX_SO_VPROC_CA7_NORMAL); mt_cpufreq_set_pmic_phase(PMIC_WRAP_PHASE_NORMAL); } //static unsigned int little_freq_backup; static unsigned int vcpu_backup; static unsigned int vlte_backup; static unsigned int vgpu_backup; static unsigned int vcore_pdn_backup; typedef enum { PTP_CTRL_CPU = 0, PTP_CTRL_LTE = 1, PTP_CTRL_GPU = 2, PTP_CTRL_SOC = 3, PTP_CTRL_ALL = 4, NR_PTP_CTRL, } ptp_ctrl_id; //void dvfs_disable_by_ptpod(void) void dvfs_disable_by_ptpod(int id) { struct mt_cpu_dvfs *p = id_to_cpu_dvfs(MT_CPU_DVFS_LITTLE); cpufreq_dbg("%s()\n", __func__); // <-XXX //little_freq_backup = _mt_cpufreq_get_cur_phy_freq(MT_CPU_DVFS_LITTLE); switch (id) { case PTP_CTRL_CPU: vcpu_backup = cpu_dvfs_get_cur_volt(p); dvfs_set_cpu_volt(MT_CPU_DVFS_LITTLE, 100000); // 1V break; case PTP_CTRL_GPU: pmic_read_interface(PMIC_ADDR_VGPU_VOSEL_ON, &vgpu_backup, 0x7F, 0); dvfs_set_gpu_volt(VOLT_TO_PMIC_VAL(100000)); // 1V break; case PTP_CTRL_LTE: pmic_read_interface(PMIC_ADDR_VPROC_CA7_VOSEL_ON, &vlte_backup, 0x7F, 0); dvfs_set_vlte_volt(VOLT_TO_PMIC_VAL(100000)); // 1V break; case PTP_CTRL_SOC: //pmic_read_interface(PMIC_ADDR_VCORE_VOSEL_ON, &vcore_ao_backup, 0x7F, 0); pmic_read_interface(PMIC_ADDR_VCORE_PDN_VOSEL_ON, &vcore_pdn_backup, 0x7F, 0); //dvfs_set_vcore_ao_volt(VOLT_TO_PMIC_VAL(100000)); // 1V dvfs_set_vcore_pdn_volt(VOLT_TO_PMIC_VAL(112500)); // 1V break; case PTP_CTRL_ALL: vcpu_backup = cpu_dvfs_get_cur_volt(p); pmic_read_interface(PMIC_ADDR_VPROC_CA7_VOSEL_ON, &vlte_backup, 0x7F, 0); pmic_read_interface(PMIC_ADDR_VGPU_VOSEL_ON, &vgpu_backup, 0x7F, 0); //pmic_read_interface(PMIC_ADDR_VCORE_VOSEL_ON, &vcore_ao_backup, 0x7F, 0); pmic_read_interface(PMIC_ADDR_VCORE_PDN_VOSEL_ON, &vcore_pdn_backup, 0x7F, 0); dvfs_set_cpu_volt(MT_CPU_DVFS_LITTLE, 100000); // 1V dvfs_set_vlte_volt(VOLT_TO_PMIC_VAL(100000)); // 1V dvfs_set_gpu_volt(VOLT_TO_PMIC_VAL(100000)); // 1V //dvfs_set_vcore_ao_volt(VOLT_TO_PMIC_VAL(100000)); // 1V dvfs_set_vcore_pdn_volt(VOLT_TO_PMIC_VAL(100000)); // 1V break; default: break; } } void dvfs_enable_by_ptpod(int id) { struct mt_cpu_dvfs *p = id_to_cpu_dvfs(MT_CPU_DVFS_LITTLE); cpufreq_dbg("%s()\n", __func__); // <-XXX switch (id) { case PTP_CTRL_CPU: dvfs_set_cpu_volt(MT_CPU_DVFS_LITTLE, vcpu_backup); break; case PTP_CTRL_LTE: dvfs_set_vlte_volt(vlte_backup); break; case PTP_CTRL_GPU: dvfs_set_gpu_volt(vgpu_backup); break; case PTP_CTRL_SOC: //dvfs_set_vcore_ao_volt(vcore_ao_backup); dvfs_set_vcore_pdn_volt(vcore_pdn_backup); break; case PTP_CTRL_ALL: dvfs_set_cpu_volt(MT_CPU_DVFS_LITTLE, vcpu_backup); dvfs_set_vlte_volt(vlte_backup); dvfs_set_gpu_volt(vgpu_backup); //dvfs_set_vcore_ao_volt(vcore_ao_backup); dvfs_set_vcore_pdn_volt(vcore_pdn_backup); break; default: break; } } #endif /* ! __KERNEL__ */ #ifdef CONFIG_PROC_FS /* * PROC */ static char *_copy_from_user_for_proc(const char __user *buffer, size_t count) { char *buf = (char *)__get_free_page(GFP_USER); if (!buf) return NULL; if (count >= PAGE_SIZE) goto out; if (copy_from_user(buf, buffer, count)) goto out; buf[count] = '\0'; return buf; out: free_page((unsigned long)buf); return NULL; } /* cpufreq_debug */ static int cpufreq_debug_proc_show(struct seq_file *m, void *v) { seq_printf(m, "cpufreq debug (log level) = %d\n", func_lv_mask); return 0; } static ssize_t cpufreq_debug_proc_write(struct file *file, const char __user *buffer, size_t count, loff_t *pos) { unsigned int dbg_lv; char *buf = _copy_from_user_for_proc(buffer, count); if (!buf) return -EINVAL; if (sscanf(buf, "%d", &dbg_lv) == 1) func_lv_mask = dbg_lv; else cpufreq_err("echo dbg_lv (dec) > /proc/cpufreq/cpufreq_debug\n"); free_page((unsigned long)buf); return count; } /* cpufreq_downgrade_freq_info */ static int cpufreq_downgrade_freq_info_proc_show(struct seq_file *m, void *v) { struct mt_cpu_dvfs *p = (struct mt_cpu_dvfs *)m->private; seq_printf(m, "downgrade_freq_counter_limit = %d\n" "ptpod_temperature_limit_1 = %d\n" "ptpod_temperature_limit_2 = %d\n" "ptpod_temperature_time_1 = %d\n" "ptpod_temperature_time_2 = %d\n" "downgrade_freq_counter_return_limit 1 = %d\n" "downgrade_freq_counter_return_limit 2 = %d\n" "over_max_cpu = %d\n", p->downgrade_freq_counter_limit, p->ptpod_temperature_limit_1, p->ptpod_temperature_limit_2, p->ptpod_temperature_time_1, p->ptpod_temperature_time_2, p->ptpod_temperature_limit_1 * p->ptpod_temperature_time_1, p->ptpod_temperature_limit_2 * p->ptpod_temperature_time_2, p->over_max_cpu ); return 0; } /* cpufreq_downgrade_freq_counter_limit */ static int cpufreq_downgrade_freq_counter_limit_proc_show(struct seq_file *m, void *v) { struct mt_cpu_dvfs *p = (struct mt_cpu_dvfs *)m->private; seq_printf(m, "%d\n", p->downgrade_freq_counter_limit); return 0; } static ssize_t cpufreq_downgrade_freq_counter_limit_proc_write(struct file *file, const char __user *buffer, size_t count, loff_t *pos) { struct mt_cpu_dvfs *p = (struct mt_cpu_dvfs *)PDE_DATA(file_inode(file)); int downgrade_freq_counter_limit; char *buf = _copy_from_user_for_proc(buffer, count); if (!buf) return -EINVAL; if (sscanf(buf, "%d", &downgrade_freq_counter_limit) == 1) p->downgrade_freq_counter_limit = downgrade_freq_counter_limit; else cpufreq_err("echo downgrade_freq_counter_limit (dec) > /proc/cpufreq/cpufreq_downgrade_freq_counter_limit\n"); free_page((unsigned long)buf); return count; } /* cpufreq_downgrade_freq_counter_return_limit */ static int cpufreq_downgrade_freq_counter_return_limit_proc_show(struct seq_file *m, void *v) { struct mt_cpu_dvfs *p = (struct mt_cpu_dvfs *)m->private; seq_printf(m, "%d\n", p->downgrade_freq_counter_return_limit); return 0; } static ssize_t cpufreq_downgrade_freq_counter_return_limit_proc_write(struct file *file, const char __user *buffer, size_t count, loff_t *pos) { struct mt_cpu_dvfs *p = (struct mt_cpu_dvfs *)PDE_DATA(file_inode(file)); int downgrade_freq_counter_return_limit; char *buf = _copy_from_user_for_proc(buffer, count); if (!buf) return -EINVAL; if (sscanf(buf, "%d", &downgrade_freq_counter_return_limit) == 1) p->downgrade_freq_counter_return_limit = downgrade_freq_counter_return_limit; // TODO: p->ptpod_temperature_limit_1 * p->ptpod_temperature_time_1 or p->ptpod_temperature_limit_2 * p->ptpod_temperature_time_2 else cpufreq_err("echo downgrade_freq_counter_return_limit (dec) > /proc/cpufreq/cpufreq_downgrade_freq_counter_return_limit\n"); free_page((unsigned long)buf); return count; } /* cpufreq_fftt_test */ #include <linux/sched_clock.h> static unsigned long _delay_us; static unsigned long _delay_us_buf; static int cpufreq_fftt_test_proc_show(struct seq_file *m, void *v) { seq_printf(m, "%lu\n", _delay_us); if (_delay_us < _delay_us_buf) cpufreq_err("@%s(), %lu < %lu, loops_per_jiffy = %lu\n", __func__, _delay_us, _delay_us_buf, loops_per_jiffy); return 0; } static ssize_t cpufreq_fftt_test_proc_write(struct file *file, const char __user *buffer, size_t count, loff_t *pos) { char *buf = _copy_from_user_for_proc(buffer, count); if (!buf) return -EINVAL; if (sscanf(buf, "%lu", &_delay_us_buf) == 1) { unsigned long start; start = (unsigned long)sched_clock(); udelay(_delay_us_buf); _delay_us = ((unsigned long)sched_clock() - start) / 1000; cpufreq_ver("@%s(%lu), _delay_us = %lu, loops_per_jiffy = %lu\n", __func__, _delay_us_buf, _delay_us, loops_per_jiffy); } free_page((unsigned long)buf); return count; } static int cpufreq_stress_test_proc_show(struct seq_file *m, void *v) { seq_printf(m, "%d\n", do_dvfs_stress_test); return 0; } static ssize_t cpufreq_stress_test_proc_write(struct file *file, const char __user *buffer, size_t count, loff_t *pos) { unsigned int do_stress; char *buf = _copy_from_user_for_proc(buffer, count); if (!buf) return -EINVAL; if (sscanf(buf, "%d", &do_stress) == 1) do_dvfs_stress_test = do_stress; else cpufreq_err("echo 0/1 > /proc/cpufreq/cpufreq_stress_test\n"); free_page((unsigned long)buf); return count; } /* cpufreq_limited_by_hevc */ static int cpufreq_limited_by_hevc_proc_show(struct seq_file *m, void *v) { struct mt_cpu_dvfs *p = (struct mt_cpu_dvfs *)m->private; seq_printf(m, "%d\n", p->limited_freq_by_hevc); return 0; } static ssize_t cpufreq_limited_by_hevc_proc_write(struct file *file, const char __user *buffer, size_t count, loff_t *pos) { struct mt_cpu_dvfs *p = (struct mt_cpu_dvfs *)PDE_DATA(file_inode(file)); int limited_freq_by_hevc; char *buf = _copy_from_user_for_proc(buffer, count); if (!buf) return -EINVAL; if (sscanf(buf, "%d", &limited_freq_by_hevc) == 1) { p->limited_freq_by_hevc = limited_freq_by_hevc; if (cpu_dvfs_is_availiable(p) && (p->limited_freq_by_hevc > cpu_dvfs_get_cur_freq(p))) { struct cpufreq_policy *policy = cpufreq_cpu_get(p->cpu_id); if (policy) { cpufreq_driver_target(policy, p->limited_freq_by_hevc, CPUFREQ_RELATION_L); cpufreq_cpu_put(policy); } } } else cpufreq_err("echo limited_freq_by_hevc (dec) > /proc/cpufreq/cpufreq_limited_by_hevc\n"); free_page((unsigned long)buf); return count; } static int cpufreq_limited_max_freq_by_user_proc_show(struct seq_file *m, void *v) { struct mt_cpu_dvfs *p = (struct mt_cpu_dvfs *)m->private; seq_printf(m, "%d\n", p->limited_max_freq_by_user); return 0; } static ssize_t cpufreq_limited_max_freq_by_user_proc_write(struct file *file, const char __user *buffer, size_t count, loff_t *pos) { struct mt_cpu_dvfs *p = (struct mt_cpu_dvfs *)PDE_DATA(file_inode(file)); int limited_max_freq; char *buf = _copy_from_user_for_proc(buffer, count); if (!buf) return -EINVAL; if (sscanf(buf, "%d", &limited_max_freq) == 1) { p->limited_max_freq_by_user = limited_max_freq; if (cpu_dvfs_is_availiable(p) && (p->limited_max_freq_by_user != 0) && (p->limited_max_freq_by_user < cpu_dvfs_get_cur_freq(p))) { struct cpufreq_policy *policy = cpufreq_cpu_get(p->cpu_id); if (policy) { cpufreq_driver_target(policy, p->limited_max_freq_by_user, CPUFREQ_RELATION_H); cpufreq_cpu_put(policy); } } } else cpufreq_err("echo limited_max_freq (dec) > /proc/cpufreq/%s/cpufreq_limited_max_freq_by_user\n", p->name); free_page((unsigned long)buf); return count; } /* cpufreq_limited_power */ static int cpufreq_limited_power_proc_show(struct seq_file *m, void *v) { struct mt_cpu_dvfs *p; int i; for_each_cpu_dvfs(i, p) { seq_printf(m, "[%s/%d] %d\n" "limited_max_freq = %d\n" "limited_max_ncpu = %d\n", p->name, i, p->thermal_protect_limited_power, p->limited_max_freq, p->limited_max_ncpu ); } return 0; } static ssize_t cpufreq_limited_power_proc_write(struct file *file, const char __user *buffer, size_t count, loff_t *pos) { int limited_power; char *buf = _copy_from_user_for_proc(buffer, count); if (!buf) return -EINVAL; if (sscanf(buf, "%d", &limited_power) == 1) mt_cpufreq_thermal_protect(limited_power); // TODO: specify limited_power by id??? else cpufreq_err("echo limited_power (dec) > /proc/cpufreq/cpufreq_limited_power\n"); free_page((unsigned long)buf); return count; } /* cpufreq_over_max_cpu */ static int cpufreq_over_max_cpu_proc_show(struct seq_file *m, void *v) { struct mt_cpu_dvfs *p = (struct mt_cpu_dvfs *)m->private; seq_printf(m, "%d\n", p->over_max_cpu); return 0; } static ssize_t cpufreq_over_max_cpu_proc_write(struct file *file, const char __user *buffer, size_t count, loff_t *pos) { struct mt_cpu_dvfs *p = (struct mt_cpu_dvfs *)PDE_DATA(file_inode(file)); int over_max_cpu; char *buf = _copy_from_user_for_proc(buffer, count); if (!buf) return -EINVAL; if (sscanf(buf, "%d", &over_max_cpu) == 1) p->over_max_cpu = over_max_cpu; else cpufreq_err("echo over_max_cpu (dec) > /proc/cpufreq/cpufreq_over_max_cpu\n"); free_page((unsigned long)buf); return count; } /* cpufreq_power_dump */ static int cpufreq_power_dump_proc_show(struct seq_file *m, void *v) { struct mt_cpu_dvfs *p; int i, j; for_each_cpu_dvfs(i, p) { seq_printf(m, "[%s/%d]\n", p->name, i); for (j = 0; j < p->nr_power_tbl; j++) { seq_printf(m, "[%d] = { .cpufreq_khz = %d,\t.cpufreq_ncpu = %d,\t.cpufreq_power = %d, },\n", j, p->power_tbl[j].cpufreq_khz, p->power_tbl[j].cpufreq_ncpu, p->power_tbl[j].cpufreq_power ); } } return 0; } /* cpufreq_ptpod_freq_volt */ static int cpufreq_ptpod_freq_volt_proc_show(struct seq_file *m, void *v) { struct mt_cpu_dvfs *p = (struct mt_cpu_dvfs *)m->private; int j; for (j = 0; j < p->nr_opp_tbl; j++) { seq_printf(m, "[%d] = { .cpufreq_khz = %d,\t.cpufreq_volt = %d,\t.cpufreq_volt_org = %d, },\n", j, p->opp_tbl[j].cpufreq_khz, p->opp_tbl[j].cpufreq_volt, p->opp_tbl[j].cpufreq_volt_org ); } return 0; } /* cpufreq_ptpod_temperature_limit */ static int cpufreq_ptpod_temperature_limit_proc_show(struct seq_file *m, void *v) { struct mt_cpu_dvfs *p = (struct mt_cpu_dvfs *)m->private; seq_printf(m, "ptpod_temperature_limit_1 = %d\n" "ptpod_temperature_limit_2 = %d\n", p->ptpod_temperature_limit_1, p->ptpod_temperature_limit_2 ); return 0; } static ssize_t cpufreq_ptpod_temperature_limit_proc_write(struct file *file, const char __user *buffer, size_t count, loff_t *pos) { struct mt_cpu_dvfs *p = (struct mt_cpu_dvfs *)PDE_DATA(file_inode(file)); int ptpod_temperature_limit_1; int ptpod_temperature_limit_2; char *buf = _copy_from_user_for_proc(buffer, count); if (!buf) return -EINVAL; if (sscanf(buf, "%d %d", &ptpod_temperature_limit_1, &ptpod_temperature_limit_2) == 2) { p->ptpod_temperature_limit_1 = ptpod_temperature_limit_1; p->ptpod_temperature_limit_2 = ptpod_temperature_limit_2; } else cpufreq_err("echo ptpod_temperature_limit_1 (dec) ptpod_temperature_limit_2 (dec) > /proc/cpufreq/cpufreq_ptpod_temperature_limit\n"); free_page((unsigned long)buf); return count; } /* cpufreq_ptpod_temperature_time */ static int cpufreq_ptpod_temperature_time_proc_show(struct seq_file *m, void *v) { struct mt_cpu_dvfs *p = (struct mt_cpu_dvfs *)m->private; seq_printf(m, "ptpod_temperature_time_1 = %d\n" "ptpod_temperature_time_2 = %d\n", p->ptpod_temperature_time_1, p->ptpod_temperature_time_2 ); return 0; } static ssize_t cpufreq_ptpod_temperature_time_proc_write(struct file *file, const char __user *buffer, size_t count, loff_t *pos) { struct mt_cpu_dvfs *p = (struct mt_cpu_dvfs *)PDE_DATA(file_inode(file)); int ptpod_temperature_time_1; int ptpod_temperature_time_2; char *buf = _copy_from_user_for_proc(buffer, count); if (!buf) return -EINVAL; if (sscanf(buf, "%d %d", &ptpod_temperature_time_1, &ptpod_temperature_time_2) == 2) { p->ptpod_temperature_time_1 = ptpod_temperature_time_1; p->ptpod_temperature_time_2 = ptpod_temperature_time_2; } else cpufreq_err("echo ptpod_temperature_time_1 (dec) ptpod_temperature_time_2 (dec) > /proc/cpufreq/cpufreq_ptpod_temperature_time\n"); free_page((unsigned long)buf); return count; } /* cpufreq_ptpod_test */ static int cpufreq_ptpod_test_proc_show(struct seq_file *m, void *v) { return 0; } static ssize_t cpufreq_ptpod_test_proc_write(struct file *file, const char __user *buffer, size_t count, loff_t *pos) { return count; } /* cpufreq_state */ static int cpufreq_state_proc_show(struct seq_file *m, void *v) // TODO: keep this function??? { struct mt_cpu_dvfs *p; int i; for_each_cpu_dvfs(i, p) { seq_printf(m, "[%s/%d]\n" "dvfs_disable_by_suspend = %d\n" "dvfs_disable_by_early_suspend = %d\n" "dvfs_disable_by_ptpod = %d\n" "dvfs_disable_by_procfs = %d\n", p->name, i, p->dvfs_disable_by_suspend, p->dvfs_disable_by_early_suspend, p->dvfs_disable_by_ptpod, p->dvfs_disable_by_procfs ); } return 0; } static ssize_t cpufreq_state_proc_write(struct file *file, const char __user *buffer, size_t count, loff_t *pos) // TODO: keep this function??? { struct mt_cpu_dvfs *p = (struct mt_cpu_dvfs *)PDE_DATA(file_inode(file)); char *buf = _copy_from_user_for_proc(buffer, count); int enable; if (!buf) return -EINVAL; if (sscanf(buf, "%d", &enable) == 1) { if (enable == 0) p->dvfs_disable_by_procfs = true; else p->dvfs_disable_by_procfs = false; } else cpufreq_err("echo 1/0 > /proc/cpufreq/cpufreq_state\n"); free_page((unsigned long)buf); return count; } /* cpufreq_oppidx */ static int cpufreq_oppidx_proc_show(struct seq_file *m, void *v) // <-XXX { struct mt_cpu_dvfs *p = (struct mt_cpu_dvfs *)m->private; int j; seq_printf(m, "[%s/%d]\n" "cpufreq_oppidx = %d\n", p->name, p->cpu_id, p->idx_opp_tbl ); for (j = 0; j < p->nr_opp_tbl; j++) { seq_printf(m, "\tOP(%d, %d),\n", cpu_dvfs_get_freq_by_idx(p, j), cpu_dvfs_get_volt_by_idx(p, j) ); } return 0; } static ssize_t cpufreq_oppidx_proc_write(struct file *file, const char __user *buffer, size_t count, loff_t *pos) // <-XXX { struct mt_cpu_dvfs *p = (struct mt_cpu_dvfs *)PDE_DATA(file_inode(file)); int oppidx; char *buf = _copy_from_user_for_proc(buffer, count); if (!buf) return -EINVAL; BUG_ON(NULL == p); if (sscanf(buf, "%d", &oppidx) == 1 && 0 <= oppidx && oppidx < p->nr_opp_tbl ) { p->dvfs_disable_by_procfs = true; _mt_cpufreq_set(MT_CPU_DVFS_LITTLE, oppidx); } else { p->dvfs_disable_by_procfs = false; // TODO: FIXME cpufreq_err("echo oppidx > /proc/cpufreq/cpufreq_oppidx (0 <= %d < %d)\n", oppidx, p->nr_opp_tbl); } free_page((unsigned long)buf); return count; } /* cpufreq_freq */ static int cpufreq_freq_proc_show(struct seq_file *m, void *v) // <-XXX { struct mt_cpu_dvfs *p = (struct mt_cpu_dvfs *)m->private; seq_printf(m, "%d KHz\n", p->ops->get_cur_phy_freq(p)); return 0; } static ssize_t cpufreq_freq_proc_write(struct file *file, const char __user *buffer, size_t count, loff_t *pos) // <-XXX { unsigned long flags; struct mt_cpu_dvfs *p = (struct mt_cpu_dvfs *)PDE_DATA(file_inode(file)); unsigned int cur_freq; int freq, i, found; char *buf = _copy_from_user_for_proc(buffer, count); if (!buf) return -EINVAL; BUG_ON(NULL == p); if (sscanf(buf, "%d", &freq) == 1) { if (freq < CPUFREQ_LAST_FREQ_LEVEL) { if (freq != 0) cpufreq_err("frequency should higher than %dKHz!\n", CPUFREQ_LAST_FREQ_LEVEL); p->dvfs_disable_by_procfs = false; goto end; } else { for (i = 0; i < p->nr_opp_tbl; i++) { if (freq == p->opp_tbl[i].cpufreq_khz) { found = 1; break; } } if (found == 1) { p->dvfs_disable_by_procfs = true; // TODO: FIXME cpufreq_lock(flags); // <-XXX cur_freq = p->ops->get_cur_phy_freq(p); if (freq != cur_freq) p->ops->set_cur_freq(p, cur_freq, freq); cpufreq_unlock(flags); // <-XXX } else { p->dvfs_disable_by_procfs = false; cpufreq_err("frequency %dKHz! is not found in CPU opp table\n", freq); } } } else { p->dvfs_disable_by_procfs = false; // TODO: FIXME cpufreq_err("echo khz > /proc/cpufreq/cpufreq_freq\n"); } end: free_page((unsigned long)buf); return count; } /* cpufreq_volt */ static int cpufreq_volt_proc_show(struct seq_file *m, void *v) // <-XXX { struct mt_cpu_dvfs *p = (struct mt_cpu_dvfs *)m->private; if (cpu_dvfs_is_extbuck_valid()) { seq_printf(m, "Vproc: %d mv\n", p->ops->get_cur_volt(p) / 100); // mv seq_printf(m, "Vsram: %d mv\n", get_cur_vsram(p) / 100); // mv } else seq_printf(m, "%d mv\n", p->ops->get_cur_volt(p) / 100); // mv return 0; } static ssize_t cpufreq_volt_proc_write(struct file *file, const char __user *buffer, size_t count, loff_t *pos) // <-XXX { unsigned long flags; struct mt_cpu_dvfs *p = (struct mt_cpu_dvfs *)PDE_DATA(file_inode(file)); int mv; char *buf = _copy_from_user_for_proc(buffer, count); if (!buf) return -EINVAL; if (sscanf(buf, "%d", &mv) == 1) { p->dvfs_disable_by_procfs = true; // TODO: FIXME cpufreq_lock(flags); _set_cur_volt_locked(p, mv * 100); cpufreq_unlock(flags); } else { p->dvfs_disable_by_procfs = false; // TODO: FIXME cpufreq_err("echo mv > /proc/cpufreq/cpufreq_volt\n"); } free_page((unsigned long)buf); return count; } /* cpufreq_turbo_mode */ static int cpufreq_turbo_mode_proc_show(struct seq_file *m, void *v) // <-XXX { struct mt_cpu_dvfs *p = (struct mt_cpu_dvfs *)m->private; int i; seq_printf(m, "turbo_mode = %d\n", p->turbo_mode); for (i = 0; i < NR_TURBO_MODE; i++) { seq_printf(m, "[%d] = { .temp = %d, .freq_delta = %d, .volt_delta = %d }\n", i, turbo_mode_cfg[i].temp, turbo_mode_cfg[i].freq_delta, turbo_mode_cfg[i].volt_delta ); } return 0; } static ssize_t cpufreq_turbo_mode_proc_write(struct file *file, const char __user *buffer, size_t count, loff_t *pos) // <-XXX { struct mt_cpu_dvfs *p = (struct mt_cpu_dvfs *)PDE_DATA(file_inode(file)); unsigned int turbo_mode; int temp; int freq_delta; int volt_delta; char *buf = _copy_from_user_for_proc(buffer, count); if (!buf) return -EINVAL; if ((sscanf(buf, "%d %d %d %d", &turbo_mode, &temp, &freq_delta, &volt_delta) == 4) && turbo_mode < NR_TURBO_MODE) { turbo_mode_cfg[turbo_mode].temp = temp; turbo_mode_cfg[turbo_mode].freq_delta = freq_delta; turbo_mode_cfg[turbo_mode].volt_delta = volt_delta; } else if (sscanf(buf, "%d", &turbo_mode) == 1) p->turbo_mode = turbo_mode; // TODO: FIXME else { cpufreq_err("echo 0/1 > /proc/cpufreq/cpufreq_turbo_mode\n"); cpufreq_err("echo idx temp freq_delta volt_delta > /proc/cpufreq/cpufreq_turbo_mode\n"); } free_page((unsigned long)buf); return count; } #define PROC_FOPS_RW(name) \ static int name ## _proc_open(struct inode *inode, struct file *file) \ { \ return single_open(file, name ## _proc_show, PDE_DATA(inode)); \ } \ static const struct file_operations name ## _proc_fops = { \ .owner = THIS_MODULE, \ .open = name ## _proc_open, \ .read = seq_read, \ .llseek = seq_lseek, \ .release = single_release, \ .write = name ## _proc_write, \ } #define PROC_FOPS_RO(name) \ static int name ## _proc_open(struct inode *inode, struct file *file) \ { \ return single_open(file, name ## _proc_show, PDE_DATA(inode)); \ } \ static const struct file_operations name ## _proc_fops = { \ .owner = THIS_MODULE, \ .open = name ## _proc_open, \ .read = seq_read, \ .llseek = seq_lseek, \ .release = single_release, \ } #define PROC_ENTRY(name) {__stringify(name), &name ## _proc_fops} PROC_FOPS_RW(cpufreq_debug); PROC_FOPS_RW(cpufreq_fftt_test); PROC_FOPS_RW(cpufreq_stress_test); PROC_FOPS_RW(cpufreq_limited_power); PROC_FOPS_RO(cpufreq_power_dump); PROC_FOPS_RW(cpufreq_ptpod_test); PROC_FOPS_RW(cpufreq_state); PROC_FOPS_RO(cpufreq_downgrade_freq_info); PROC_FOPS_RW(cpufreq_downgrade_freq_counter_limit); PROC_FOPS_RW(cpufreq_downgrade_freq_counter_return_limit); PROC_FOPS_RW(cpufreq_limited_by_hevc); PROC_FOPS_RW(cpufreq_limited_max_freq_by_user); PROC_FOPS_RW(cpufreq_over_max_cpu); PROC_FOPS_RO(cpufreq_ptpod_freq_volt); PROC_FOPS_RW(cpufreq_ptpod_temperature_limit); PROC_FOPS_RW(cpufreq_ptpod_temperature_time); PROC_FOPS_RW(cpufreq_oppidx); // <-XXX PROC_FOPS_RW(cpufreq_freq); // <-XXX PROC_FOPS_RW(cpufreq_volt); // <-XXX PROC_FOPS_RW(cpufreq_turbo_mode); // <-XXX static int _create_procfs(void) { struct proc_dir_entry *dir = NULL; //struct proc_dir_entry *cpu_dir = NULL; struct mt_cpu_dvfs *p = id_to_cpu_dvfs(0); int i; //, j; struct pentry { const char *name; const struct file_operations *fops; }; const struct pentry entries[] = { PROC_ENTRY(cpufreq_debug), PROC_ENTRY(cpufreq_fftt_test), PROC_ENTRY(cpufreq_stress_test), PROC_ENTRY(cpufreq_limited_power), PROC_ENTRY(cpufreq_power_dump), PROC_ENTRY(cpufreq_ptpod_test), }; const struct pentry cpu_entries[] = { PROC_ENTRY(cpufreq_downgrade_freq_info), PROC_ENTRY(cpufreq_downgrade_freq_counter_limit), PROC_ENTRY(cpufreq_downgrade_freq_counter_return_limit), PROC_ENTRY(cpufreq_limited_by_hevc), PROC_ENTRY(cpufreq_limited_max_freq_by_user), PROC_ENTRY(cpufreq_over_max_cpu), PROC_ENTRY(cpufreq_ptpod_freq_volt), PROC_ENTRY(cpufreq_ptpod_temperature_limit), PROC_ENTRY(cpufreq_ptpod_temperature_time), PROC_ENTRY(cpufreq_state), PROC_ENTRY(cpufreq_oppidx), // <-XXX PROC_ENTRY(cpufreq_freq), // <-XXX PROC_ENTRY(cpufreq_volt), // <-XXX PROC_ENTRY(cpufreq_turbo_mode), // <-XXX }; dir = proc_mkdir("cpufreq", NULL); if (!dir) { cpufreq_err("fail to create /proc/cpufreq @ %s()\n", __func__); return -ENOMEM; } for (i = 0; i < ARRAY_SIZE(entries); i++) { if (!proc_create(entries[i].name, S_IRUGO | S_IWUSR | S_IWGRP, dir, entries[i].fops)) cpufreq_err("%s(), create /proc/cpufreq/%s failed\n", __func__, entries[i].name); } for (i = 0; i < ARRAY_SIZE(cpu_entries); i++) { if (!proc_create_data(cpu_entries[i].name, S_IRUGO | S_IWUSR | S_IWGRP, dir, cpu_entries[i].fops, p)) cpufreq_err("%s(), create /proc/cpufreq/%s failed\n", __func__, cpu_entries[i].name); } #if 0 // K2 has little core only for_each_cpu_dvfs(j, p) { cpu_dir = proc_mkdir(p->name, dir); if (!cpu_dir) { cpufreq_err("fail to create /proc/cpufreq/%s @ %s()\n", p->name, __func__); return -ENOMEM; } for (i = 0; i < ARRAY_SIZE(cpu_entries); i++) { if (!proc_create_data(cpu_entries[i].name, S_IRUGO | S_IWUSR | S_IWGRP, cpu_dir, cpu_entries[i].fops, p)) cpufreq_err("%s(), create /proc/cpufreq/%s/%s failed\n", __func__, p->name, entries[i].name); } } #endif return 0; } #endif /* CONFIG_PROC_FS */ /* * Module driver */ static int __init _mt_cpufreq_pdrv_init(void) { int ret = 0; FUNC_ENTER(FUNC_LV_MODULE); //if (CPU_LEVEL_0 != _mt_cpufreq_get_cpu_level()) cpu_dvfs[MT_CPU_DVFS_LITTLE].turbo_mode = 0; #ifdef CONFIG_PROC_FS /* init proc */ if (_create_procfs()) goto out; #endif /* CONFIG_PROC_FS */ /* register platform device/driver */ ret = platform_device_register(&_mt_cpufreq_pdev); if (ret) { cpufreq_err("fail to register cpufreq device @ %s()\n", __func__); goto out; } ret = platform_driver_register(&_mt_cpufreq_pdrv); if (ret) { cpufreq_err("fail to register cpufreq driver @ %s()\n", __func__); platform_device_unregister(&_mt_cpufreq_pdev); } out: FUNC_EXIT(FUNC_LV_MODULE); return ret; } static void __exit _mt_cpufreq_pdrv_exit(void) { FUNC_ENTER(FUNC_LV_MODULE); platform_driver_unregister(&_mt_cpufreq_pdrv); platform_device_unregister(&_mt_cpufreq_pdev); FUNC_EXIT(FUNC_LV_MODULE); } late_initcall(_mt_cpufreq_pdrv_init); module_exit(_mt_cpufreq_pdrv_exit); MODULE_DESCRIPTION("MediaTek CPU DVFS Driver v0.3"); MODULE_LICENSE("GPL");
psycho-source/Psycho-Kernel
drivers/misc/mediatek/mach/mt6795/mt_cpufreq_64.c
C
gpl-3.0
140,761