code
stringlengths
3
1.05M
repo_name
stringlengths
4
116
path
stringlengths
4
991
language
stringclasses
9 values
license
stringclasses
15 values
size
int32
3
1.05M
import { Map, Set, OrderedSet, List } from 'immutable' import * as constants from '../constants/files.js' import { ls, searchFiles, rangeSelect } from '../sagas/helpers.js' const initialState = Map({ files: List(), workingDirectoryFiles: null, searchResults: List(), uploading: List(), downloading: List(), selected: OrderedSet(), path: '', searchText: '', uploadSource: '', showAllowanceDialog: false, showUploadDialog: false, showSearchField: false, showFileTransfers: false, showDeleteDialog: false, showRenameDialog: false, settingAllowance: false, dragging: false, contractCount: 0, allowance: '0', spending: '0', showDownloadsSince: Date.now(), unreadUploads: Set(), unreadDownloads: Set(), }) export default function filesReducer(state = initialState, action) { switch (action.type) { case constants.SET_ALLOWANCE_COMPLETED: return state.set('settingAllowance', false) case constants.RECEIVE_ALLOWANCE: return state.set('allowance', action.allowance) case constants.RECEIVE_SPENDING: return state.set('spending', action.spending) case constants.DOWNLOAD_FILE: return state.set('unreadDownloads', state.get('unreadDownloads').add(action.file.siapath)) case constants.UPLOAD_FILE: return state.set('unreadUploads', state.get('unreadUploads').add(action.siapath)) case constants.RECEIVE_FILES: { const workingDirectoryFiles = ls(action.files, state.get('path')) const workingDirectorySiapaths = workingDirectoryFiles.map((file) => file.siapath) // filter out selected files that are no longer in the working directory const selected = state.get('selected').filter((file) => workingDirectorySiapaths.includes(file.siapath)) return state.set('files', action.files) .set('workingDirectoryFiles', workingDirectoryFiles) .set('selected', selected) } case constants.SET_ALLOWANCE: return state.set('allowance', action.funds) .set('settingAllowance', true) case constants.CLEAR_DOWNLOADS: return state.set('showDownloadsSince', Date.now()) case constants.SET_SEARCH_TEXT: { const results = searchFiles(state.get('workingDirectoryFiles'), action.text, state.get('path')) return state.set('searchResults', results) .set('searchText', action.text) } case constants.SET_PATH: return state.set('path', action.path) .set('selected', OrderedSet()) .set('workingDirectoryFiles', ls(state.get('files'), action.path)) .set('searchResults', searchFiles(state.get('workingDirectoryFiles'), state.get('searchText', state.get('path')))) case constants.DESELECT_FILE: return state.set('selected', state.get('selected').filter((file) => file.siapath !== action.file.siapath)) case constants.SELECT_FILE: return state.set('selected', state.get('selected').add(action.file)) case constants.DESELECT_ALL: return state.set('selected', OrderedSet()) case constants.SELECT_UP_TO: return state.set('selected', rangeSelect(action.file, state.get('workingDirectoryFiles'), state.get('selected'))) case constants.SHOW_ALLOWANCE_DIALOG: return state.set('showAllowanceDialog', true) case constants.CLOSE_ALLOWANCE_DIALOG: return state.set('showAllowanceDialog', false) case constants.TOGGLE_SEARCH_FIELD: return state.set('showSearchField', !state.get('showSearchField')) case constants.SET_DRAGGING: return state.set('dragging', true) case constants.SET_NOT_DRAGGING: return state.set('dragging', false) case constants.SHOW_DELETE_DIALOG: return state.set('showDeleteDialog', true) case constants.HIDE_DELETE_DIALOG: return state.set('showDeleteDialog', false) case constants.SHOW_UPLOAD_DIALOG: return state.set('showUploadDialog', true) .set('uploadSource', action.source) case constants.HIDE_UPLOAD_DIALOG: return state.set('showUploadDialog', false) case constants.RECEIVE_UPLOADS: return state.set('uploading', action.uploads) case constants.RECEIVE_DOWNLOADS: return state.set('downloading', action.downloads.filter((download) => Date.parse(download.starttime) > state.get('showDownloadsSince'))) case constants.SHOW_FILE_TRANSFERS: return state.set('showFileTransfers', true) case constants.HIDE_FILE_TRANSFERS: return state.set('showFileTransfers', false) case constants.TOGGLE_FILE_TRANSFERS: return state.set('showFileTransfers', !state.get('showFileTransfers')) .set('unreadDownloads', Set()) .set('unreadUploads', Set()) case constants.SET_CONTRACT_COUNT: return state.set('contractCount', action.count) case constants.SHOW_RENAME_DIALOG: return state.set('showRenameDialog', true) case constants.HIDE_RENAME_DIALOG: return state.set('showRenameDialog', false) default: return state } }
patel344/Mr.Miner
Mr.Mining/MikeTheMiner/dist/Santas_helpers/Sia_wallet/resources/app/plugins/Files/js/reducers/files.js
JavaScript
gpl-3.0
4,745
// pythonFlu - Python wrapping for OpenFOAM C++ API // Copyright (C) 2010- Alexey Petrov // Copyright (C) 2009-2010 Pebble Bed Modular Reactor (Pty) Limited (PBMR) // // 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/>. // // See http://sourceforge.net/projects/pythonflu // // Author : Alexey PETROV //--------------------------------------------------------------------------- #ifndef limitedSurfaceInterpolationScheme_hh #define limitedSurfaceInterpolationScheme_hh //--------------------------------------------------------------------------- #include "Foam/src/finiteVolume/interpolation/surfaceInterpolation/surfaceInterpolationScheme/surfaceInterpolationScheme.hh" #include <limitedSurfaceInterpolationScheme.H> //--------------------------------------------------------------------------- #endif
ivan7farre/PyFreeFOAM
Foam/src/finiteVolume/interpolation/surfaceInterpolation/limitedSchemes/limitedSurfaceInterpolationScheme/limitedSurfaceInterpolationScheme.hh
C++
gpl-3.0
1,424
/* Copyright (C) 2015 Lukasz Hryniuk This file is part of toys. toys 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. toys 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 toys. If not, see <http://www.gnu.org/licenses/>. */ #include "CellularAutomaton2d.hpp" #include "../utils/Cell2d.hpp" CellularAutomaton2d::CellularAutomaton2d(state_t number_of_states, int width, int height) : CellularAutomaton(number_of_states), width_{width}, height_{height}, states_{std::vector<std::vector<state_t>>(height, std::vector<state_t>(width, 0))} { } void CellularAutomaton2d::Reset() { states_.clear(); states_ = std::vector<std::vector<state_t>>(height_, std::vector<state_t>(width_, 0)); } std::vector<std::unique_ptr<Atom>> CellularAutomaton2d::GetInitialState() const { std::vector<std::unique_ptr<Atom>> atoms; for (auto y = 0u; y < unsigned(height_); ++y) { for (auto x = 0u; x < unsigned(width_); ++x) { if (states_[y][x] != 0) { atoms.push_back(std::make_unique<Cell2d>(x, y, states_[y][x])); } } } return atoms; } int CellularAutomaton2d::GetNumberOfAtomsWithState(state_t state) const { int nbr_of_atoms{}; for (const auto& row : states_) { for (const auto& s : row) { if (s == state) { ++nbr_of_atoms; } } } return nbr_of_atoms; } state_t CellularAutomaton2d::GetStateAt(int x, int y) { return states_[y][x]; } void CellularAutomaton2d::SetStateAt(int x, int y, state_t new_state) { states_[y][x] = new_state; } std::vector<std::unique_ptr<Atom>> CellularAutomaton2d::Step(int) { return std::vector<std::unique_ptr<Atom>>{}; } std::vector<std::unique_ptr<Atom>> CellularAutomaton2d::GetAllAtoms() const { std::vector<std::unique_ptr<Atom>> atoms; for (auto y = 0u; y < unsigned(height_); ++y) { for (auto x = 0u; x < unsigned(width_); ++x) { atoms.push_back(std::make_unique<Cell2d>(x, y, states_[y][x])); } } return atoms; }
R-Toys/toys
src/models/CellularAutomaton2d.cpp
C++
gpl-3.0
2,600
package org.esa.snap.binning.operator.metadata; import com.vividsolutions.jts.io.ParseException; import com.vividsolutions.jts.io.WKTReader; import org.esa.snap.binning.AggregatorConfig; import org.esa.snap.binning.aggregators.AggregatorAverage; import org.esa.snap.binning.aggregators.AggregatorOnMaxSet; import org.esa.snap.binning.operator.BinningConfig; import org.esa.snap.binning.operator.BinningOp; import org.esa.snap.binning.operator.VariableConfig; import org.esa.snap.framework.datamodel.MetadataAttribute; import org.esa.snap.framework.datamodel.MetadataElement; import org.esa.snap.util.io.FileUtils; import org.junit.Test; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.util.SortedMap; import java.util.logging.Logger; import static org.junit.Assert.*; import static org.mockito.Mockito.*; public class GlobalMetadataTest { private static final String TEST_DIR = "test_dir"; private static final String TEST_PROPERTIES = "param_a = aaaaa\n" + "param_b = bbbb\n" + "param_c = CCCC"; @Test public void testCreate_fromBinningOp() throws ParseException { final BinningOp binningOp = createBinningOp(); final GlobalMetadata metadata = GlobalMetadata.create(binningOp); assertNotNull(metadata); final SortedMap<String, String> metaProperties = metadata.asSortedMap(); assertNotNull(metaProperties); assertEquals("org.esa.snap.binning.operator.BinningOp", metaProperties.get("software_qualified_name")); assertEquals("Binning", metaProperties.get("software_name")); assertEquals("1.0", metaProperties.get("software_version")); assertEquals(FileUtils.getFilenameWithoutExtension("output.file"), metaProperties.get("product_name")); //assertNotNull(metaProperties.get("processing_time")); assertEquals("2013-05-01", metaProperties.get("aggregation_period_start")); assertEquals("15.56 day(s)", metaProperties.get("aggregation_period_duration")); assertEquals("POLYGON ((10 10, 15 10, 15 12, 10 12, 10 10))", metaProperties.get("region")); assertEquals("8192", metaProperties.get("num_rows")); assertEquals("2.446286592055973", metaProperties.get("pixel_size_in_km")); assertEquals("3", metaProperties.get("super_sampling")); assertEquals("a_mask_expression", metaProperties.get("mask_expression")); } @Test public void testCreate_fromConfig() { final BinningConfig config = new BinningConfig(); config.setNumRows(12); config.setSuperSampling(13); config.setMaskExpr("14"); config.setVariableConfigs(new VariableConfig("var_name", "var_expr")); config.setAggregatorConfigs(new AggregatorAverage.Config("variable", "target", 2.076, false, true)); // @todo 3 tb/** add check for PostProcessorConfig 2014-10-17 config.setMinDataHour(15.0); config.setTimeFilterMethod(BinningOp.TimeFilterMethod.SPATIOTEMPORAL_DATA_DAY); config.setMetadataAggregatorName("NAME"); config.setStartDateTime("here_we_go"); config.setPeriodDuration(15.88); final GlobalMetadata metadata = GlobalMetadata.create(config); assertNotNull(metadata); final SortedMap<String, String> metaProperties = metadata.asSortedMap(); assertNotNull(metaProperties); assertEquals("12", metaProperties.get("num_rows")); assertEquals("13", metaProperties.get("super_sampling")); assertEquals("14", metaProperties.get("mask_expression")); assertEquals("var_name", metaProperties.get("variable_config.0:name")); assertEquals("var_expr", metaProperties.get("variable_config.0:expr")); assertEquals("AVG", metaProperties.get("aggregator_config.0:type")); assertEquals("false", metaProperties.get("aggregator_config.0:outputCounts")); assertEquals("true", metaProperties.get("aggregator_config.0:outputSums")); assertEquals("target", metaProperties.get("aggregator_config.0:targetName")); assertEquals("variable", metaProperties.get("aggregator_config.0:varName")); assertEquals("2.076", metaProperties.get("aggregator_config.0:weightCoeff")); assertEquals("15.0", metaProperties.get("min_data_hour")); assertEquals("SPATIOTEMPORAL_DATA_DAY", metaProperties.get("time_filter_method")); assertEquals("NAME", metaProperties.get("metadata_aggregator_name")); assertEquals("here_we_go", metaProperties.get("aggregation_period_start")); assertEquals("15.88 day(s)", metaProperties.get("aggregation_period_duration")); } @Test public void testCreateFromConfig_noParametersSet() throws ParseException { final BinningConfig binningConfig = new BinningConfig(); final GlobalMetadata metadata = GlobalMetadata.create(binningConfig); assertNotNull(metadata); final SortedMap<String, String> metaProperties = metadata.asSortedMap(); assertNotNull(metaProperties); assertNull(metaProperties.get("product_name")); //assertNotNull(metaProperties.get("processing_time")); assertNull(metaProperties.get("aggregation_period_start")); assertNull(metaProperties.get("aggregation_period_duration")); assertNull(metaProperties.get("region")); assertNull(metaProperties.get("num_rows")); assertNull(metaProperties.get("pixel_size_in_km")); assertNull(metaProperties.get("super_sampling")); assertEquals("", metaProperties.get("mask_expression")); assertNull(metaProperties.get("variable_config.0:name")); } @Test public void testCreate_timeFilerMethod_timeRange() throws ParseException { final BinningConfig binningConfig = new BinningConfig(); binningConfig.setTimeFilterMethod(BinningOp.TimeFilterMethod.TIME_RANGE); final GlobalMetadata metadata = GlobalMetadata.create(binningConfig); assertNotNull(metadata); final SortedMap<String, String> metaProperties = metadata.asSortedMap(); assertNotNull(metaProperties); assertEquals("TIME_RANGE", metaProperties.get("time_filter_method")); assertNull(metaProperties.get("min_data_hour")); } @Test public void testCreate_timeFilterMethod_spatioTemporalDay() throws ParseException { final BinningConfig binningConfig = new BinningConfig(); binningConfig.setTimeFilterMethod(BinningOp.TimeFilterMethod.SPATIOTEMPORAL_DATA_DAY); binningConfig.setMinDataHour(0.8876); final GlobalMetadata metadata = GlobalMetadata.create(binningConfig); assertNotNull(metadata); final SortedMap<String, String> metaProperties = metadata.asSortedMap(); assertNotNull(metaProperties); assertEquals("SPATIOTEMPORAL_DATA_DAY", metaProperties.get("time_filter_method")); assertEquals("0.8876", metaProperties.get("min_data_hour")); } @Test public void testCreate_variableConfigs() { final VariableConfig[] variableConfigs = new VariableConfig[2]; variableConfigs[0] = new VariableConfig("first", "one and one"); variableConfigs[1] = new VariableConfig("second", "is two"); final BinningOp binningOp = new BinningOp(); binningOp.setVariableConfigs(variableConfigs); final GlobalMetadata metadata = GlobalMetadata.create(binningOp); assertNotNull(metadata); final SortedMap<String, String> metaProperties = metadata.asSortedMap(); assertNotNull(metaProperties); assertEquals("first", metaProperties.get("variable_config.0:name")); assertEquals("one and one", metaProperties.get("variable_config.0:expr")); assertEquals("second", metaProperties.get("variable_config.1:name")); assertEquals("is two", metaProperties.get("variable_config.1:expr")); } @Test public void testCreate_aggregatorConfigs() { final AggregatorConfig[] aggregatorConfigs = new AggregatorConfig[2]; aggregatorConfigs[0] = new AggregatorAverage.Config("variable_1", "the target", 1.087, true, false); aggregatorConfigs[1] = new AggregatorOnMaxSet.Config("variable_2", "another one", "set_1", "set_2"); final BinningOp binningOp = new BinningOp(); binningOp.setAggregatorConfigs(aggregatorConfigs); final GlobalMetadata metadata = GlobalMetadata.create(binningOp); assertNotNull(metadata); final SortedMap<String, String> metaProperties = metadata.asSortedMap(); assertNotNull(metaProperties); assertEquals("AVG", metaProperties.get("aggregator_config.0:type")); assertEquals("true", metaProperties.get("aggregator_config.0:outputCounts")); assertEquals("false", metaProperties.get("aggregator_config.0:outputSums")); assertEquals("the target", metaProperties.get("aggregator_config.0:targetName")); assertEquals("variable_1", metaProperties.get("aggregator_config.0:varName")); assertEquals("1.087", metaProperties.get("aggregator_config.0:weightCoeff")); assertEquals("ON_MAX_SET", metaProperties.get("aggregator_config.1:type")); assertEquals("another one", metaProperties.get("aggregator_config.1:onMaxVarName")); assertEquals("set_1,set_2", metaProperties.get("aggregator_config.1:setVarNames")); assertEquals("variable_2", metaProperties.get("aggregator_config.1:targetName")); } @Test public void testLoad_fileIsNull() throws IOException { final Logger logger = mock(Logger.class); final GlobalMetadata globalMetadata = new GlobalMetadata(); globalMetadata.load(null, logger); final SortedMap<String, String> metaProperties = globalMetadata.asSortedMap(); assertNotNull(metaProperties); assertEquals(0, metaProperties.size()); verifyNoMoreInteractions(logger); } @Test public void testLoad_fileDoesNotExist() throws IOException { final Logger logger = mock(Logger.class); final GlobalMetadata globalMetadata = new GlobalMetadata(); globalMetadata.load(new File("over_the_rain.bow"), logger); final SortedMap<String, String> metaProperties = globalMetadata.asSortedMap(); assertNotNull(metaProperties); assertEquals(0, metaProperties.size()); verify(logger, times(1)).warning("Metadata properties file 'over_the_rain.bow' not found"); verifyNoMoreInteractions(logger); } @Test public void testLoad() throws IOException { final Logger logger = mock(Logger.class); final GlobalMetadata globalMetadata = new GlobalMetadata(); try { final File propertiesFile = writePropertiesFile(); globalMetadata.load(propertiesFile, logger); final SortedMap<String, String> metaProperties = globalMetadata.asSortedMap(); assertEquals("aaaaa", metaProperties.get("param_a")); assertEquals("bbbb", metaProperties.get("param_b")); assertEquals("CCCC", metaProperties.get("param_c")); verify(logger, times(1)).info(contains("Reading metadata properties file")); verifyNoMoreInteractions(logger); } finally { deletePropertiesFile(); } } @Test public void testAsMetadataElement() throws ParseException { final BinningOp binningOp = createBinningOp(); final GlobalMetadata globalMetadata = GlobalMetadata.create(binningOp); final MetadataElement processingGraphElement = globalMetadata.asMetadataElement(); assertNotNull(processingGraphElement); assertEquals("Processing_Graph", processingGraphElement.getName()); final MetadataElement node_0_Element = processingGraphElement.getElement("node.0"); assertNotNull(node_0_Element); final MetadataElement parameterElement = node_0_Element.getElement("parameters"); assertEquals(11, parameterElement.getNumAttributes()); // @todo 2 tb/tb check for other meta elements 2014-10-10 final MetadataAttribute software_qualified_name = parameterElement.getAttribute("software_qualified_name"); assertNotNull(software_qualified_name); assertEquals("org.esa.snap.binning.operator.BinningOp", software_qualified_name.getData().getElemString()); } @Test public void testAsMetadataElement_noMetadataContained() { final GlobalMetadata globalMetadata = new GlobalMetadata(); final MetadataElement metadataElement = globalMetadata.asMetadataElement(); assertNotNull(metadataElement); assertEquals("Processing_Graph", metadataElement.getName()); assertEquals(0, metadataElement.getNumAttributes()); } @Test public void testIsTimeFilterMetadataRequired() { assertFalse(GlobalMetadata.isTimeFilterMetadataRequired(null)); assertFalse(GlobalMetadata.isTimeFilterMetadataRequired(BinningOp.TimeFilterMethod.NONE)); assertTrue(GlobalMetadata.isTimeFilterMetadataRequired(BinningOp.TimeFilterMethod.SPATIOTEMPORAL_DATA_DAY)); assertTrue(GlobalMetadata.isTimeFilterMetadataRequired(BinningOp.TimeFilterMethod.TIME_RANGE)); } @Test public void testToPixelSizeString() { assertEquals("1821.593952320952", GlobalMetadata.toPixelSizeString(12)); assertEquals("2.446286592055973", GlobalMetadata.toPixelSizeString(8192)); } private void deletePropertiesFile() { final File testDir = new File(TEST_DIR); if (testDir.isDirectory()) { if (!FileUtils.deleteTree(testDir)) { fail("unable to delete test directory"); } } } private File writePropertiesFile() throws IOException { final File testDir = new File(TEST_DIR); if (!testDir.mkdirs()) { fail("unable to create test directory"); } final File testPropertiesFile = new File(testDir, "test.properties"); if (!testPropertiesFile.createNewFile()) { fail("unable to create test file"); } final FileOutputStream fileOutputStream = new FileOutputStream(testPropertiesFile); fileOutputStream.write(TEST_PROPERTIES.getBytes()); fileOutputStream.close(); return testPropertiesFile; } private BinningOp createBinningOp() throws ParseException { final BinningOp binningOp = new BinningOp(); binningOp.setOutputFile("output.file"); binningOp.setStartDateTime("2013-05-01"); binningOp.setPeriodDuration(15.56); final WKTReader wktReader = new WKTReader(); binningOp.setRegion(wktReader.read("POLYGON((10 10, 15 10, 15 12, 10 12, 10 10))")); binningOp.setTimeFilterMethod(BinningOp.TimeFilterMethod.NONE); binningOp.setNumRows(8192); binningOp.setSuperSampling(3); binningOp.setMaskExpr("a_mask_expression"); return binningOp; } }
arraydev/snap-engine
snap-binning/src/test/java/org/esa/snap/binning/operator/metadata/GlobalMetadataTest.java
Java
gpl-3.0
15,038
#pragma region Copyright (c) 2014-2017 OpenRCT2 Developers /***************************************************************************** * OpenRCT2, an open source clone of Roller Coaster Tycoon 2. * * OpenRCT2 is the work of many authors, a full list can be found in contributors.md * For more information, visit https://github.com/OpenRCT2/OpenRCT2 * * OpenRCT2 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. * * A full copy of the GNU General Public License can be found in licence.txt *****************************************************************************/ #pragma endregion #ifndef DISABLE_OPENGL #include <openrct2/Context.h> #include <openrct2/core/Console.hpp> #include <openrct2/core/FileStream.hpp> #include <openrct2/core/Path.hpp> #include <openrct2/core/String.hpp> #include <openrct2/PlatformEnvironment.h> #include "OpenGLShaderProgram.h" using namespace OpenRCT2; OpenGLShader::OpenGLShader(const char * name, GLenum type) { _type = type; auto path = GetPath(name); auto sourceCode = ReadSourceCode(path); auto sourceCodeStr = sourceCode.c_str(); _id = glCreateShader(type); glShaderSource(_id, 1, (const GLchar * *)&sourceCodeStr, nullptr); glCompileShader(_id); GLint status; glGetShaderiv(_id, GL_COMPILE_STATUS, &status); if (status != GL_TRUE) { char buffer[512]; glGetShaderInfoLog(_id, sizeof(buffer), nullptr, buffer); glDeleteShader(_id); Console::Error::WriteLine("Error compiling %s", path.c_str()); Console::Error::WriteLine(buffer); throw std::runtime_error("Error compiling shader."); } } OpenGLShader::~OpenGLShader() { glDeleteShader(_id); } GLuint OpenGLShader::GetShaderId() { return _id; } std::string OpenGLShader::GetPath(const std::string &name) { auto env = GetContext()->GetPlatformEnvironment(); auto shadersPath = env->GetDirectoryPath(DIRBASE::OPENRCT2, DIRID::SHADER); auto path = Path::Combine(shadersPath, name); if (_type == GL_VERTEX_SHADER) { path += ".vert"; } else { path += ".frag"; } return path; } std::string OpenGLShader::ReadSourceCode(const std::string &path) { auto fs = FileStream(path, FILE_MODE_OPEN); uint64 fileLength = fs.GetLength(); if (fileLength > MaxSourceSize) { throw IOException("Shader source too large."); } auto fileData = std::string((size_t)fileLength + 1, '\0'); fs.Read((void *)fileData.data(), fileLength); return fileData; } OpenGLShaderProgram::OpenGLShaderProgram(const char * name) { _vertexShader = new OpenGLShader(name, GL_VERTEX_SHADER); _fragmentShader = new OpenGLShader(name, GL_FRAGMENT_SHADER); _id = glCreateProgram(); glAttachShader(_id, _vertexShader->GetShaderId()); glAttachShader(_id, _fragmentShader->GetShaderId()); glBindFragDataLocation(_id, 0, "oColour"); if (!Link()) { char buffer[512]; GLsizei length; glGetProgramInfoLog(_id, sizeof(buffer), &length, buffer); Console::Error::WriteLine("Error linking %s", name); Console::Error::WriteLine(buffer); throw std::runtime_error("Failed to link OpenGL shader."); } } OpenGLShaderProgram::~OpenGLShaderProgram() { if (_vertexShader != nullptr) { glDetachShader(_id, _vertexShader->GetShaderId()); delete _vertexShader; } if (_fragmentShader != nullptr) { glDetachShader(_id, _fragmentShader->GetShaderId()); delete _fragmentShader; } glDeleteProgram(_id); } GLuint OpenGLShaderProgram::GetAttributeLocation(const char * name) { return glGetAttribLocation(_id, name); } GLuint OpenGLShaderProgram::GetUniformLocation(const char * name) { return glGetUniformLocation(_id, name); } void OpenGLShaderProgram::Use() { if (OpenGLState::CurrentProgram != _id) { OpenGLState::CurrentProgram = _id; glUseProgram(_id); } } bool OpenGLShaderProgram::Link() { glLinkProgram(_id); GLint linkStatus; glGetProgramiv(_id, GL_LINK_STATUS, &linkStatus); return linkStatus == GL_TRUE; } #endif /* DISABLE_OPENGL */
zaxcav/OpenRCT2
src/openrct2-ui/drawing/engines/opengl/OpenGLShaderProgram.cpp
C++
gpl-3.0
4,377
package io.firesoft.service; import java.util.ArrayList; import java.util.List; import javax.persistence.EntityManager; import javax.persistence.NoResultException; import javax.persistence.PersistenceContext; import javax.persistence.TypedQuery; import javax.persistence.criteria.CriteriaBuilder; import javax.persistence.criteria.CriteriaQuery; import javax.persistence.criteria.Root; import javax.transaction.Transactional; import io.firesoft.model.Post; import io.firesoft.model.Role; import io.firesoft.model.User; import io.firesoft.repository.PostRepository; import io.firesoft.repository.RoleRepository; import io.firesoft.repository.UserRepository; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.data.domain.PageRequest; import org.springframework.data.domain.Sort.Direction; import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder; import org.springframework.stereotype.Service; @Service @Transactional public class UserService { @Autowired private UserRepository userRepository; @PersistenceContext(unitName="punit") private EntityManager em; @Autowired private PostRepository postRepository; @Autowired private RoleRepository roleRepository; public List<User> findAll() { return userRepository.findAll(); } public User findOne(int id) { return userRepository.findOne(id); } public User findUserByEmail(String email){ CriteriaBuilder builder = em.getCriteriaBuilder(); CriteriaQuery<User> query = builder.createQuery(User.class); Root<User> root = query.from(User.class); query.select(root).where(builder.equal(root.get("username").as(String.class), email)); return findUserByCriteria(query); } private User findUserByCriteria(CriteriaQuery<User> criteria) { TypedQuery<User> pQuery= em.createQuery(criteria); User result = null; try{ result = pQuery.getSingleResult(); } catch (NoResultException e) { return result; } return result; } @Transactional public User findOneWithPosts(int id) { User user = findOne(id); List<Post> posts = postRepository.findByUser(user, new PageRequest(0, 10, Direction.DESC, "title")); user.setPosts(posts); return user; } public void save(User user) { user.setEnabled(true); BCryptPasswordEncoder encoder = new BCryptPasswordEncoder(); user.setPassword(encoder.encode(user.getPassword())); List<Role> roles = new ArrayList<Role>(); roles.add(roleRepository.findByName("ROLE_USER")); user.setRoles(roles); userRepository.save(user); } public User findOneWithPosts(String name) { User user = userRepository.findByUsername(name); return findOneWithPosts(user.getId()); } public User findByName(String name) { return userRepository.findByUsername(name); } public void delete(int id) { userRepository.delete(id); } }
noskill/Firesoft
src/main/java/io/firesoft/service/UserService.java
Java
gpl-3.0
3,093
package generated.gio20.gio; import generated.glib20.glib.GList; import org.bridj.BridJ; import org.bridj.Pointer; import org.bridj.StructObject; import org.bridj.ann.Library; import org.bridj.ann.Ptr; @Library("gio-2.0") public class GIOExtensionPoint extends StructObject { static { BridJ.register(); } public GIOExtensionPoint() { super(); } public GIOExtensionPoint(Pointer pointer) { super(pointer); } @Ptr protected native long g_io_extension_point_get_extension_by_name( @Ptr long extension_point, @Ptr long name); public Pointer<GIOExtension> get_extension_by_name(Pointer name) { return Pointer.pointerToAddress(this.g_io_extension_point_get_extension_by_name(Pointer.pointerTo(this, GIOExtensionPoint.class).getPeer(), Pointer.getPeer(name)), GIOExtension.class); } @Ptr protected native long g_io_extension_point_get_extensions( @Ptr long extension_point); public Pointer<GList> get_extensions() { return Pointer.pointerToAddress(this.g_io_extension_point_get_extensions(Pointer.pointerTo(this, GIOExtensionPoint.class).getPeer()), GList.class); } protected native long g_io_extension_point_get_required_type( @Ptr long extension_point); public long get_required_type() { return this.g_io_extension_point_get_required_type(Pointer.pointerTo(this, GIOExtensionPoint.class).getPeer()); } protected native void g_io_extension_point_set_required_type( @Ptr long extension_point, long type); public void set_required_type(long type) { this.g_io_extension_point_set_required_type(Pointer.pointerTo(this, GIOExtensionPoint.class).getPeer(), type); } @Ptr protected static native long g_io_extension_point_implement( @Ptr long extension_point_name, long type, @Ptr long extension_name, int priority); public static Pointer<GIOExtension> implement(Pointer extension_point_name, long type, Pointer extension_name, int priority) { return Pointer.pointerToAddress(GIOExtensionPoint.g_io_extension_point_implement(Pointer.getPeer(extension_point_name), type, Pointer.getPeer(extension_name), priority), GIOExtension.class); } @Ptr protected static native long g_io_extension_point_lookup( @Ptr long name); public static Pointer lookup(Pointer name) { return Pointer.pointerToAddress(GIOExtensionPoint.g_io_extension_point_lookup(Pointer.getPeer(name))); } @Ptr protected static native long g_io_extension_point_register( @Ptr long name); public static Pointer register(Pointer name) { return Pointer.pointerToAddress(GIOExtensionPoint.g_io_extension_point_register(Pointer.getPeer(name))); } }
gstreamer-java/gir2java
generated-src/generated/gio20/gio/GIOExtensionPoint.java
Java
gpl-3.0
2,870
<?php require_once(dirname(__FILE__) . "/../KalturaClientBase.php"); require_once(dirname(__FILE__) . "/../KalturaEnums.php"); require_once(dirname(__FILE__) . "/../KalturaTypes.php"); class KalturaAttachmentAssetOrderBy { const SIZE_ASC = "+size"; const SIZE_DESC = "-size"; const CREATED_AT_ASC = "+createdAt"; const CREATED_AT_DESC = "-createdAt"; const UPDATED_AT_ASC = "+updatedAt"; const UPDATED_AT_DESC = "-updatedAt"; const DELETED_AT_ASC = "+deletedAt"; const DELETED_AT_DESC = "-deletedAt"; } class KalturaAttachmentAssetStatus { const ERROR = -1; const QUEUED = 0; const READY = 2; const DELETED = 3; const IMPORTING = 7; } class KalturaAttachmentType { const TEXT = "1"; const MEDIA = "2"; const DOCUMENT = "3"; } class KalturaAttachmentAsset extends KalturaAsset { /** * The filename of the attachment asset content * * @var string */ public $filename = null; /** * Attachment asset title * * @var string */ public $title = null; /** * The attachment format * * @var KalturaAttachmentType */ public $format = null; /** * The status of the asset * * * @var KalturaAttachmentAssetStatus * @readonly */ public $status = null; } class KalturaAttachmentAssetListResponse extends KalturaObjectBase { /** * * * @var array of KalturaAttachmentAsset * @readonly */ public $objects; /** * * * @var int * @readonly */ public $totalCount = null; } abstract class KalturaAttachmentAssetBaseFilter extends KalturaAssetFilter { /** * * * @var KalturaAttachmentType */ public $formatEqual = null; /** * * * @var string */ public $formatIn = null; /** * * * @var KalturaAttachmentAssetStatus */ public $statusEqual = null; /** * * * @var string */ public $statusIn = null; /** * * * @var string */ public $statusNotIn = null; } class KalturaAttachmentAssetFilter extends KalturaAttachmentAssetBaseFilter { } class KalturaAttachmentAssetService extends KalturaServiceBase { function __construct(KalturaClient $client = null) { parent::__construct($client); } function add($entryId, KalturaAttachmentAsset $attachmentAsset) { $kparams = array(); $this->client->addParam($kparams, "entryId", $entryId); $this->client->addParam($kparams, "attachmentAsset", $attachmentAsset->toParams()); $this->client->queueServiceActionCall("attachment_attachmentasset", "add", $kparams); if ($this->client->isMultiRequest()) return $this->client->getMultiRequestResult(); $resultObject = $this->client->doQueue(); $this->client->throwExceptionIfError($resultObject); $this->client->validateObjectType($resultObject, "KalturaAttachmentAsset"); return $resultObject; } function setContent($id, KalturaContentResource $contentResource) { $kparams = array(); $this->client->addParam($kparams, "id", $id); $this->client->addParam($kparams, "contentResource", $contentResource->toParams()); $this->client->queueServiceActionCall("attachment_attachmentasset", "setContent", $kparams); if ($this->client->isMultiRequest()) return $this->client->getMultiRequestResult(); $resultObject = $this->client->doQueue(); $this->client->throwExceptionIfError($resultObject); $this->client->validateObjectType($resultObject, "KalturaAttachmentAsset"); return $resultObject; } function update($id, KalturaAttachmentAsset $attachmentAsset) { $kparams = array(); $this->client->addParam($kparams, "id", $id); $this->client->addParam($kparams, "attachmentAsset", $attachmentAsset->toParams()); $this->client->queueServiceActionCall("attachment_attachmentasset", "update", $kparams); if ($this->client->isMultiRequest()) return $this->client->getMultiRequestResult(); $resultObject = $this->client->doQueue(); $this->client->throwExceptionIfError($resultObject); $this->client->validateObjectType($resultObject, "KalturaAttachmentAsset"); return $resultObject; } function getUrl($id, $storageId = null) { $kparams = array(); $this->client->addParam($kparams, "id", $id); $this->client->addParam($kparams, "storageId", $storageId); $this->client->queueServiceActionCall("attachment_attachmentasset", "getUrl", $kparams); if ($this->client->isMultiRequest()) return $this->client->getMultiRequestResult(); $resultObject = $this->client->doQueue(); $this->client->throwExceptionIfError($resultObject); $this->client->validateObjectType($resultObject, "string"); return $resultObject; } function getRemotePaths($id) { $kparams = array(); $this->client->addParam($kparams, "id", $id); $this->client->queueServiceActionCall("attachment_attachmentasset", "getRemotePaths", $kparams); if ($this->client->isMultiRequest()) return $this->client->getMultiRequestResult(); $resultObject = $this->client->doQueue(); $this->client->throwExceptionIfError($resultObject); $this->client->validateObjectType($resultObject, "KalturaRemotePathListResponse"); return $resultObject; } function serve($attachmentAssetId) { $kparams = array(); $this->client->addParam($kparams, "attachmentAssetId", $attachmentAssetId); $this->client->queueServiceActionCall('attachment_attachmentasset', 'serve', $kparams); $resultObject = $this->client->getServeUrl(); return $resultObject; } function get($attachmentAssetId) { $kparams = array(); $this->client->addParam($kparams, "attachmentAssetId", $attachmentAssetId); $this->client->queueServiceActionCall("attachment_attachmentasset", "get", $kparams); if ($this->client->isMultiRequest()) return $this->client->getMultiRequestResult(); $resultObject = $this->client->doQueue(); $this->client->throwExceptionIfError($resultObject); $this->client->validateObjectType($resultObject, "KalturaAttachmentAsset"); return $resultObject; } function listAction(KalturaAssetFilter $filter = null, KalturaFilterPager $pager = null) { $kparams = array(); if ($filter !== null) $this->client->addParam($kparams, "filter", $filter->toParams()); if ($pager !== null) $this->client->addParam($kparams, "pager", $pager->toParams()); $this->client->queueServiceActionCall("attachment_attachmentasset", "list", $kparams); if ($this->client->isMultiRequest()) return $this->client->getMultiRequestResult(); $resultObject = $this->client->doQueue(); $this->client->throwExceptionIfError($resultObject); $this->client->validateObjectType($resultObject, "KalturaAttachmentAssetListResponse"); return $resultObject; } function delete($attachmentAssetId) { $kparams = array(); $this->client->addParam($kparams, "attachmentAssetId", $attachmentAssetId); $this->client->queueServiceActionCall("attachment_attachmentasset", "delete", $kparams); if ($this->client->isMultiRequest()) return $this->client->getMultiRequestResult(); $resultObject = $this->client->doQueue(); $this->client->throwExceptionIfError($resultObject); $this->client->validateObjectType($resultObject, "null"); return $resultObject; } } class KalturaAttachmentClientPlugin extends KalturaClientPlugin { /** * @var KalturaAttachmentClientPlugin */ protected static $instance; /** * @var KalturaAttachmentAssetService */ public $attachmentAsset = null; protected function __construct(KalturaClient $client) { parent::__construct($client); $this->attachmentAsset = new KalturaAttachmentAssetService($client); } /** * @return KalturaAttachmentClientPlugin */ public static function get(KalturaClient $client) { if(!self::$instance) self::$instance = new KalturaAttachmentClientPlugin($client); return self::$instance; } /** * @return array<KalturaServiceBase> */ public function getServices() { $services = array( 'attachmentAsset' => $this->attachmentAsset, ); return $services; } /** * @return string */ public function getName() { return 'attachment'; } }
junwan6/cdhpoodll
local/kaltura/API/KalturaPlugins/KalturaAttachmentClientPlugin.php
PHP
gpl-3.0
7,925
/* Copyright 2011-2013 Pieter Pareit Copyright 2009 David Revell This file is part of SwiFTP. SwiFTP 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. SwiFTP 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 SwiFTP. If not, see <http://www.gnu.org/licenses/>. */ package be.ppareit.swiftp; import java.io.IOException; import java.net.InetAddress; import java.net.InetSocketAddress; import java.net.NetworkInterface; import java.net.ServerSocket; import java.util.ArrayList; import java.util.Enumeration; import java.util.List; import android.app.AlarmManager; import android.app.PendingIntent; import android.app.Service; import android.content.Context; import android.content.Intent; import android.net.ConnectivityManager; import android.net.NetworkInfo; import android.net.wifi.WifiManager; import android.net.wifi.WifiManager.WifiLock; import android.os.IBinder; import android.os.PowerManager; import android.os.SystemClock; import android.util.Log; import be.ppareit.swiftp.server.SessionThread; import be.ppareit.swiftp.server.TcpListener; public class FtpServerService extends Service implements Runnable { private static final String TAG = FtpServerService.class.getSimpleName(); // Service will (global) broadcast when server start/stop static public final String ACTION_STARTED = "be.ppareit.swiftp.FTPSERVER_STARTED"; static public final String ACTION_STOPPED = "be.ppareit.swiftp.FTPSERVER_STOPPED"; static public final String ACTION_FAILEDTOSTART = "be.ppareit.swiftp.FTPSERVER_FAILEDTOSTART"; // RequestStartStopReceiver listens for these actions to start/stop this server static public final String ACTION_START_FTPSERVER = "be.ppareit.swiftp.ACTION_START_FTPSERVER"; static public final String ACTION_STOP_FTPSERVER = "be.ppareit.swiftp.ACTION_STOP_FTPSERVER"; protected static Thread serverThread = null; protected boolean shouldExit = false; protected ServerSocket listenSocket; // The server thread will check this often to look for incoming // connections. We are forced to use non-blocking accept() and polling // because we cannot wait forever in accept() if we want to be able // to receive an exit signal and cleanly exit. public static final int WAKE_INTERVAL_MS = 1000; // milliseconds private TcpListener wifiListener = null; private final List<SessionThread> sessionThreads = new ArrayList<SessionThread>(); private PowerManager.WakeLock wakeLock; private WifiLock wifiLock = null; @Override public int onStartCommand(Intent intent, int flags, int startId) { shouldExit = false; int attempts = 10; // The previous server thread may still be cleaning up, wait for it to finish. while (serverThread != null) { Log.w(TAG, "Won't start, server thread exists"); if (attempts > 0) { attempts--; Util.sleepIgnoreInterupt(1000); } else { Log.w(TAG, "Server thread already exists"); return START_STICKY; } } Log.d(TAG, "Creating server thread"); serverThread = new Thread(this); serverThread.start(); return START_STICKY; } public static boolean isRunning() { // return true if and only if a server Thread is running if (serverThread == null) { Log.d(TAG, "Server is not running (null serverThread)"); return false; } if (!serverThread.isAlive()) { Log.d(TAG, "serverThread non-null but !isAlive()"); } else { Log.d(TAG, "Server is alive"); } return true; } @Override public void onDestroy() { Log.i(TAG, "onDestroy() Stopping server"); shouldExit = true; if (serverThread == null) { Log.w(TAG, "Stopping with null serverThread"); return; } serverThread.interrupt(); try { serverThread.join(10000); // wait 10 sec for server thread to finish } catch (InterruptedException e) { } if (serverThread.isAlive()) { Log.w(TAG, "Server thread failed to exit"); // it may still exit eventually if we just leave the shouldExit flag set } else { Log.d(TAG, "serverThread join()ed ok"); serverThread = null; } try { if (listenSocket != null) { Log.i(TAG, "Closing listenSocket"); listenSocket.close(); } } catch (IOException e) { } if (wifiLock != null) { Log.d(TAG, "onDestroy: Releasing wifi lock"); wifiLock.release(); wifiLock = null; } if (wakeLock != null) { Log.d(TAG, "onDestroy: Releasing wake lock"); wakeLock.release(); wakeLock = null; } Log.d(TAG, "FTPServerService.onDestroy() finished"); } // This opens a listening socket on all interfaces. void setupListener() throws IOException { listenSocket = new ServerSocket(); listenSocket.setReuseAddress(true); listenSocket.bind(new InetSocketAddress(Settings.getPortNumber())); } public void run() { Log.d(TAG, "Server thread running"); if (isConnectedToLocalNetwork() == false) { Log.w(TAG, "run: There is no local network, bailing out"); stopSelf(); sendBroadcast(new Intent(ACTION_FAILEDTOSTART)); return; } // Initialization of wifi, set up the socket try { setupListener(); } catch (IOException e) { Log.w(TAG, "run: Unable to open port, bailing out."); stopSelf(); sendBroadcast(new Intent(ACTION_FAILEDTOSTART)); return; } // @TODO: when using ethernet, is it needed to take wifi lock? takeWifiLock(); takeWakeLock(); // A socket is open now, so the FTP server is started, notify rest of world Log.i(TAG, "Ftp Server up and running, broadcasting ACTION_STARTED"); sendBroadcast(new Intent(ACTION_STARTED)); while (!shouldExit) { if (wifiListener != null) { if (!wifiListener.isAlive()) { Log.d(TAG, "Joining crashed wifiListener thread"); try { wifiListener.join(); } catch (InterruptedException e) { } wifiListener = null; } } if (wifiListener == null) { // Either our wifi listener hasn't been created yet, or has crashed, // so spawn it wifiListener = new TcpListener(listenSocket, this); wifiListener.start(); } try { // TODO: think about using ServerSocket, and just closing // the main socket to send an exit signal Thread.sleep(WAKE_INTERVAL_MS); } catch (InterruptedException e) { Log.d(TAG, "Thread interrupted"); } } terminateAllSessions(); if (wifiListener != null) { wifiListener.quit(); wifiListener = null; } shouldExit = false; // we handled the exit flag, so reset it to acknowledge Log.d(TAG, "Exiting cleanly, returning from run()"); stopSelf(); sendBroadcast(new Intent(ACTION_STOPPED)); } private void terminateAllSessions() { Log.i(TAG, "Terminating " + sessionThreads.size() + " session thread(s)"); synchronized (this) { for (SessionThread sessionThread : sessionThreads) { if (sessionThread != null) { sessionThread.closeDataSocket(); sessionThread.closeSocket(); } } } } /** * Takes the wake lock * * Many devices seem to not properly honor a PARTIAL_WAKE_LOCK, which should prevent * CPU throttling. For these devices, we have a option to force the phone into a full * wake lock. */ private void takeWakeLock() { if (wakeLock == null) { PowerManager pm = (PowerManager) getSystemService(Context.POWER_SERVICE); if (Settings.shouldTakeFullWakeLock()) { Log.d(TAG, "takeWakeLock: Taking full wake lock"); wakeLock = pm.newWakeLock(PowerManager.FULL_WAKE_LOCK, TAG); } else { Log.d(TAG, "maybeTakeWakeLock: Taking parial wake lock"); wakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, TAG); } wakeLock.setReferenceCounted(false); } wakeLock.acquire(); } private void takeWifiLock() { Log.d(TAG, "takeWifiLock: Taking wifi lock"); if (wifiLock == null) { WifiManager manager = (WifiManager) getSystemService(Context.WIFI_SERVICE); wifiLock = manager.createWifiLock(TAG); wifiLock.setReferenceCounted(false); } wifiLock.acquire(); } /** * Gets the local ip address * * @return local ip adress or null if not found */ public static InetAddress getLocalInetAddress() { if (isConnectedToLocalNetwork() == false) { Log.e(TAG, "getLocalInetAddress called and no connection"); return null; } // TODO: next if block could probably be removed if (isConnectedUsingWifi() == true) { Context context = FtpServerApp.getAppContext(); WifiManager wm = (WifiManager) context.getSystemService(Context.WIFI_SERVICE); int ipAddress = wm.getConnectionInfo().getIpAddress(); if (ipAddress == 0) return null; return Util.intToInet(ipAddress); } // This next part should be able to get the local ip address, but in some case // I'm receiving the routable address try { Enumeration<NetworkInterface> netinterfaces = NetworkInterface .getNetworkInterfaces(); while (netinterfaces.hasMoreElements()) { NetworkInterface netinterface = netinterfaces.nextElement(); Enumeration<InetAddress> adresses = netinterface.getInetAddresses(); while (adresses.hasMoreElements()) { InetAddress address = adresses.nextElement(); // this is the condition that sometimes gives problems if (address.isLoopbackAddress() == false && address.isLinkLocalAddress() == false) return address; } } } catch (Exception e) { e.printStackTrace(); } return null; } /** * Checks to see if we are connected to a local network, for instance wifi or ethernet * * @return true if connected to a local network */ public static boolean isConnectedToLocalNetwork() { Context context = FtpServerApp.getAppContext(); ConnectivityManager cm = (ConnectivityManager) context .getSystemService(Context.CONNECTIVITY_SERVICE); NetworkInfo ni = cm.getActiveNetworkInfo(); // @TODO: this is only defined starting in api level 13 final int TYPE_ETHERNET = 0x00000009; return ni != null && ni.isConnected() == true && (ni.getType() & (ConnectivityManager.TYPE_WIFI | TYPE_ETHERNET)) != 0; } /** * Checks to see if we are connected using wifi * * @return true if connected using wifi */ public static boolean isConnectedUsingWifi() { Context context = FtpServerApp.getAppContext(); ConnectivityManager cm = (ConnectivityManager) context .getSystemService(Context.CONNECTIVITY_SERVICE); NetworkInfo ni = cm.getActiveNetworkInfo(); return ni != null && ni.isConnected() == true && ni.getType() == ConnectivityManager.TYPE_WIFI; } /** * All messages server<->client are also send to this call * * @param incoming * @param s */ public static void writeMonitor(boolean incoming, String s) { } /** * The FTPServerService must know about all running session threads so they can be * terminated on exit. Called when a new session is created. */ public void registerSessionThread(SessionThread newSession) { // Before adding the new session thread, clean up any finished session // threads that are present in the list. // Since we're not allowed to modify the list while iterating over // it, we construct a list in toBeRemoved of threads to remove // later from the sessionThreads list. synchronized (this) { List<SessionThread> toBeRemoved = new ArrayList<SessionThread>(); for (SessionThread sessionThread : sessionThreads) { if (!sessionThread.isAlive()) { Log.d(TAG, "Cleaning up finished session..."); try { sessionThread.join(); Log.d(TAG, "Thread joined"); toBeRemoved.add(sessionThread); sessionThread.closeSocket(); // make sure socket closed } catch (InterruptedException e) { Log.d(TAG, "Interrupted while joining"); // We will try again in the next loop iteration } } } for (SessionThread removeThread : toBeRemoved) { sessionThreads.remove(removeThread); } // Cleanup is complete. Now actually add the new thread to the list. sessionThreads.add(newSession); } Log.d(TAG, "Registered session thread"); } @Override public IBinder onBind(Intent intent) { return null; } @Override public void onTaskRemoved(Intent rootIntent) { super.onTaskRemoved(rootIntent); Log.d(TAG, "user has removed my activity, we got killed! restarting..."); Intent restartService = new Intent(getApplicationContext(), this.getClass()); restartService.setPackage(getPackageName()); PendingIntent restartServicePI = PendingIntent.getService( getApplicationContext(), 1, restartService, PendingIntent.FLAG_ONE_SHOT); AlarmManager alarmService = (AlarmManager) getApplicationContext() .getSystemService(Context.ALARM_SERVICE); alarmService.set(AlarmManager.ELAPSED_REALTIME, SystemClock.elapsedRealtime() + 2000, restartServicePI); } }
sparkleDai/swiftp
src/be/ppareit/swiftp/FtpServerService.java
Java
gpl-3.0
15,378
<?php /** * Zend Framework * * LICENSE * * This source file is subject to the new BSD license that is bundled * with this package in the file LICENSE.txt. * It is also available through the world-wide-web at this URL: * http://framework.zend.com/license/new-bsd * If you did not receive a copy of the license and are unable to * obtain it through the world-wide-web, please send an email * to license@zend.com so we can send you a copy immediately. * * @category Zend * @package Zend_Service * @subpackage DeveloperGarden * @copyright Copyright (c) 2005-2012 Zend Technologies USA Inc. (http://www.zend.com) * @license http://framework.zend.com/license/new-bsd New BSD License * @version $Id: BaseUserService.php 24594 2012-01-05 21:27:01Z matthew $ */ /** * @see Zend_Service_DeveloperGarden_Client_ClientAbstract */ //require_once 'Zend/Service/DeveloperGarden/Client/ClientAbstract.php'; /** * @see Zend_Service_DeveloperGarden_Response_BaseUserService_GetQuotaInformationResponse */ //require_once 'Zend/Service/DeveloperGarden/Response/BaseUserService/GetQuotaInformationResponse.php'; /** * @see Zend_Service_DeveloperGarden_Response_BaseUserService_ChangeQuotaPoolResponse */ //require_once 'Zend/Service/DeveloperGarden/Response/BaseUserService/ChangeQuotaPoolResponse.php'; /** * @see Zend_Service_DeveloperGarden_Response_BaseUserService_GetAccountBalanceResponse */ //require_once 'Zend/Service/DeveloperGarden/Response/BaseUserService/GetAccountBalanceResponse.php'; /** * @see Zend_Service_DeveloperGarden_BaseUserService_AccountBalance */ //require_once 'Zend/Service/DeveloperGarden/BaseUserService/AccountBalance.php'; /** * @see Zend_Service_DeveloperGarden_Request_BaseUserService_GetQuotaInformation */ //require_once 'Zend/Service/DeveloperGarden/Request/BaseUserService/GetQuotaInformation.php'; /** * @see Zend_Service_DeveloperGarden_Request_BaseUserService_ChangeQuotaPool */ //require_once 'Zend/Service/DeveloperGarden/Request/BaseUserService/ChangeQuotaPool.php'; /** * @see Zend_Service_DeveloperGarden_Request_BaseUserService_GetAccountBalance */ //require_once 'Zend/Service/DeveloperGarden/Request/BaseUserService/GetAccountBalance.php'; /** * @category Zend * @package Zend_Service * @subpackage DeveloperGarden * @copyright Copyright (c) 2005-2012 Zend Technologies USA Inc. (http://www.zend.com) * @author Marco Kaiser * @license http://framework.zend.com/license/new-bsd New BSD License */ class Zend_Service_DeveloperGarden_BaseUserService extends Zend_Service_DeveloperGarden_Client_ClientAbstract { /** * wsdl file * * @var string */ protected $_wsdlFile = 'https://gateway.developer.telekom.com/p3gw-mod-odg-admin/services/ODGBaseUserService?wsdl'; /** * wsdl file local * * @var string */ protected $_wsdlFileLocal = 'Wsdl/ODGBaseUserService.wsdl'; /** * Response, Request Classmapping * * @var array * */ protected $_classMap = array( 'getQuotaInformationResponse' => 'Zend_Service_DeveloperGarden_Response_BaseUserService_GetQuotaInformationResponse', 'changeQuotaPoolResponse' => 'Zend_Service_DeveloperGarden_Response_BaseUserService_ChangeQuotaPoolResponse', 'getAccountBalanceResponse' => 'Zend_Service_DeveloperGarden_Response_BaseUserService_GetAccountBalanceResponse', 'AccountBalance' => 'Zend_Service_DeveloperGarden_BaseUserService_AccountBalance', ); /** * array with all QuotaModuleIds * * @var array */ protected $_moduleIds = array( 'SmsProduction' => 'SmsProduction', 'SmsSandbox' => 'SmsSandbox', 'VoiceCallProduction' => 'VoiceButlerProduction', 'VoiceCallSandbox' => 'VoiceButlerSandbox', 'ConferenceCallProduction' => 'CCSProduction', 'ConferenceCallSandbox' => 'CCSSandbox', 'LocalSearchProduction' => 'localsearchProduction', 'LocalSearchSandbox' => 'localsearchSandbox', 'IPLocationProduction' => 'IPLocationProduction', 'IPLocationSandbox' => 'IPLocationSandbox' ); /** * returns an array with all possible ModuleIDs * * @return array */ public function getModuleIds() { return $this->_moduleIds; } /** * checks the moduleId and throws exception if not valid * * @param string $moduleId * @throws Zend_Service_DeveloperGarden_Client_Exception * @return void */ protected function _checkModuleId($moduleId) { if (!in_array($moduleId, $this->_moduleIds)) { //require_once 'Zend/Service/DeveloperGarden/Client/Exception.php'; throw new Zend_Service_DeveloperGarden_Client_Exception('moduleId not valid'); } } /** * returns the correct module string * * @param string $module * @param integer $environment * @return string */ protected function _buildModuleString($module, $environment) { $moduleString = $module; switch($environment) { case self::ENV_PRODUCTION : $moduleString .= 'Production'; break; case self::ENV_SANDBOX : $moduleString .= 'Sandbox'; break; default: //require_once 'Zend/Service/DeveloperGarden/Client/Exception.php'; throw new Zend_Service_DeveloperGarden_Client_Exception( 'Not a valid environment supplied.' ); } if (!in_array($moduleString, $this->_moduleIds)) { //require_once 'Zend/Service/DeveloperGarden/Client/Exception.php'; throw new Zend_Service_DeveloperGarden_Client_Exception( 'Not a valid module name supplied.' ); } return $moduleString; } /** * returns the request object with the specific moduleId * * @param string $moduleId * @return Zend_Service_DeveloperGarden_Response_BaseUserService_GetQuotaInformationResponse */ protected function _getRequestModule($moduleId) { return new Zend_Service_DeveloperGarden_Request_BaseUserService_GetQuotaInformation( $moduleId ); } /** * returns the request object with the specific moduleId and new quotaMax value * * @param string $moduleId * @param integer $quotaMax * @return Zend_Service_DeveloperGarden_Response_BaseUserService_GetQuotaInformationResponse */ protected function _getChangeRequestModule($moduleId, $quotaMax) { return new Zend_Service_DeveloperGarden_Request_BaseUserService_ChangeQuotaPool( $moduleId, $quotaMax ); } /** * returns the Quota Information for SMS Service * * @param int $environment * @return Zend_Service_DeveloperGarden_Response_BaseUserService_GetQuotaInformationResponse */ public function getSmsQuotaInformation($environment = self::ENV_PRODUCTION) { self::checkEnvironment($environment); $moduleId = $this->_buildModuleString('Sms', $environment); $request = $this->_getRequestModule($moduleId); return $this->getQuotaInformation($request); } /** * returns the Quota Information for VoiceCall Service * * @param int $environment * @return Zend_Service_DeveloperGarden_Response_BaseUserService_GetQuotaInformationResponse */ public function getVoiceCallQuotaInformation($environment = self::ENV_PRODUCTION) { self::checkEnvironment($environment); $moduleId = $this->_buildModuleString('VoiceButler', $environment); $request = $this->_getRequestModule($moduleId); return $this->getQuotaInformation($request); } /** * returns the Quota Information for SMS ConferenceCall * * @param int $environment * @return Zend_Service_DeveloperGarden_Response_BaseUserService_GetQuotaInformationResponse */ public function getConfernceCallQuotaInformation($environment = self::ENV_PRODUCTION) { self::checkEnvironment($environment); $moduleId = $this->_buildModuleString('CCS', $environment); $request = $this->_getRequestModule($moduleId); return $this->getQuotaInformation($request); } /** * returns the Quota Information for LocaleSearch Service * * @param int $environment * @return Zend_Service_DeveloperGarden_Response_BaseUserService_GetQuotaInformationResponse */ public function getLocalSearchQuotaInformation($environment = self::ENV_PRODUCTION) { self::checkEnvironment($environment); $moduleId = $this->_buildModuleString('localsearch', $environment); $request = $this->_getRequestModule($moduleId); return $this->getQuotaInformation($request); } /** * returns the Quota Information for IPLocation Service * * @param int $environment * @return Zend_Service_DeveloperGarden_Response_BaseUserService_GetQuotaInformationResponse */ public function getIPLocationQuotaInformation($environment = self::ENV_PRODUCTION) { self::checkEnvironment($environment); $moduleId = $this->_buildModuleString('IPLocation', $environment); $request = $this->_getRequestModule($moduleId); return $this->getQuotaInformation($request); } /** * returns the quota information * * @param Zend_Service_DeveloperGarden_Request_BaseUserService $request * @return Zend_Service_DeveloperGarden_Response_BaseUserService_GetQuotaInformationResponse */ public function getQuotaInformation( Zend_Service_DeveloperGarden_Request_BaseUserService_GetQuotaInformation $request ) { $this->_checkModuleId($request->getModuleId()); return $this->getSoapClient() ->getQuotaInformation($request) ->parse(); } /** * sets new user quota for the sms service * * @param integer $quotaMax * @param integer $environment * @return Zend_Service_DeveloperGarden_Response_BaseUserService_ChangeQuotaPoolResponse */ public function changeSmsQuotaPool($quotaMax = 0, $environment = self::ENV_PRODUCTION) { self::checkEnvironment($environment); $moduleId = $this->_buildModuleString('Sms', $environment); $request = $this->_getChangeRequestModule($moduleId, $quotaMax); return $this->changeQuotaPool($request); } /** * sets new user quota for the voice call service * * @param integer $quotaMax * @param integer $environment * @return Zend_Service_DeveloperGarden_Response_BaseUserService_ChangeQuotaPoolResponse */ public function changeVoiceCallQuotaPool($quotaMax = 0, $environment = self::ENV_PRODUCTION) { self::checkEnvironment($environment); $moduleId = $this->_buildModuleString('VoiceButler', $environment); $request = $this->_getChangeRequestModule($moduleId, $quotaMax); return $this->changeQuotaPool($request); } /** * sets new user quota for the IPLocation service * * @param integer $quotaMax * @param integer $environment * @return Zend_Service_DeveloperGarden_Response_BaseUserService_ChangeQuotaPoolResponse */ public function changeIPLocationQuotaPool($quotaMax = 0, $environment = self::ENV_PRODUCTION) { self::checkEnvironment($environment); $moduleId = $this->_buildModuleString('IPLocation', $environment); $request = $this->_getChangeRequestModule($moduleId, $quotaMax); return $this->changeQuotaPool($request); } /** * sets new user quota for the Conference Call service * * @param integer $quotaMax * @param integer $environment * @return Zend_Service_DeveloperGarden_Response_BaseUserService_ChangeQuotaPoolResponse */ public function changeConferenceCallQuotaPool($quotaMax = 0, $environment = self::ENV_PRODUCTION) { self::checkEnvironment($environment); $moduleId = $this->_buildModuleString('CCS', $environment); $request = $this->_getChangeRequestModule($moduleId, $quotaMax); return $this->changeQuotaPool($request); } /** * sets new user quota for the Local Search service * * @param integer $quotaMax * @param integer $environment * @return Zend_Service_DeveloperGarden_Response_BaseUserService_ChangeQuotaPoolResponse */ public function changeLocalSearchQuotaPool($quotaMax = 0, $environment = self::ENV_PRODUCTION) { self::checkEnvironment($environment); $moduleId = $this->_buildModuleString('localsearch', $environment); $request = $this->_getChangeRequestModule($moduleId, $quotaMax); return $this->changeQuotaPool($request); } /** * set new quota values for the defined module * * @param Zend_Service_DeveloperGarden_Request_BaseUserService_ChangeQuotaPool $request * @return Zend_Service_DeveloperGarden_Response_BaseUserService_ChangeQuotaPoolResponse */ public function changeQuotaPool( Zend_Service_DeveloperGarden_Request_BaseUserService_ChangeQuotaPool $request ) { $this->_checkModuleId($request->getModuleId()); return $this->getSoapClient() ->changeQuotaPool($request) ->parse(); } /** * get the result for a list of accounts * * @param array $accounts * @return Zend_Service_DeveloperGarden_Response_BaseUserService_GetAccountBalanceResponse */ public function getAccountBalance(array $accounts = array()) { $request = new Zend_Service_DeveloperGarden_Request_BaseUserService_GetAccountBalance( $accounts ); return $this->getSoapClient() ->getAccountBalance($request) ->parse(); } }
sadiqdon/cycommerce
common/lib/Zend/Service/DeveloperGarden/BaseUserService.php
PHP
gpl-3.0
14,198
/**************************************************************************** ** ** Copyright (C) 2016 The Qt Company Ltd. ** Contact: https://www.qt.io/licensing/ ** ** This file is part of Qt Creator. ** ** Commercial License Usage ** Licensees holding valid commercial Qt licenses may use this file in ** accordance with the commercial license agreement provided with the ** Software or, alternatively, in accordance with the terms contained in ** a written agreement between you and The Qt Company. For licensing terms ** and conditions see https://www.qt.io/terms-conditions. For further ** information use the contact form at https://www.qt.io/contact-us. ** ** GNU General Public License Usage ** Alternatively, this file may be used under the terms of the GNU ** General Public License version 3 as published by the Free Software ** Foundation with exceptions as appearing in the file LICENSE.GPL3-EXCEPT ** included in the packaging of this file. Please review the following ** information to ensure the GNU General Public License requirements will ** be met: https://www.gnu.org/licenses/gpl-3.0.html. ** ****************************************************************************/ #include "registryaccess.h" #include <QApplication> #include <QDir> #include <QTextStream> namespace RegistryAccess { static QString winErrorMessage(unsigned long error) { QString rc = QString::fromLatin1("#%1: ").arg(error); ushort *lpMsgBuf; const int len = FormatMessage( FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS, NULL, error, 0, (LPTSTR)&lpMsgBuf, 0, NULL); if (len) { rc = QString::fromUtf16(lpMsgBuf, len); LocalFree(lpMsgBuf); } else { rc += QString::fromLatin1("<unknown error>"); } return rc; } QString msgFunctionFailed(const char *f, unsigned long error) { return QString::fromLatin1("\"%1\" failed: %2").arg(QLatin1String(f), winErrorMessage(error)); } static bool registryReadBinaryKey(HKEY handle, // HKEY_LOCAL_MACHINE, etc. const WCHAR *valueName, QByteArray *data, QString *errorMessage) { data->clear(); DWORD type; DWORD size; // get size and retrieve LONG rc = RegQueryValueEx(handle, valueName, 0, &type, 0, &size); if (rc != ERROR_SUCCESS) { *errorMessage = msgRegistryOperationFailed("read", valueName, msgFunctionFailed("RegQueryValueEx1", rc)); return false; } BYTE *dataC = new BYTE[size + 1]; // Will be Utf16 in case of a string rc = RegQueryValueEx(handle, valueName, 0, &type, dataC, &size); if (rc != ERROR_SUCCESS) { *errorMessage = msgRegistryOperationFailed("read", valueName, msgFunctionFailed("RegQueryValueEx2", rc)); return false; } *data = QByteArray(reinterpret_cast<const char*>(dataC), size); delete [] dataC; return true; } bool registryReadStringKey(HKEY handle, // HKEY_LOCAL_MACHINE, etc. const WCHAR *valueName, QString *s, QString *errorMessage) { QByteArray data; if (!registryReadBinaryKey(handle, valueName, &data, errorMessage)) return false; data += '\0'; data += '\0'; *s = QString::fromUtf16(reinterpret_cast<const unsigned short*>(data.data())); return true; } bool openRegistryKey(HKEY category, // HKEY_LOCAL_MACHINE, etc. const WCHAR *key, bool readWrite, HKEY *keyHandle, AccessMode mode, QString *errorMessage) { Q_UNUSED(debuggerRegistryKeyC); // avoid warning from MinGW REGSAM accessRights = KEY_READ; if (readWrite) accessRights |= KEY_SET_VALUE; switch (mode) { case RegistryAccess::DefaultAccessMode: break; case RegistryAccess::Registry32Mode: accessRights |= KEY_WOW64_32KEY; break; case RegistryAccess::Registry64Mode: accessRights |= KEY_WOW64_64KEY; break; } const LONG rc = RegOpenKeyEx(category, key, 0, accessRights, keyHandle); if (rc != ERROR_SUCCESS) { *errorMessage = msgFunctionFailed("RegOpenKeyEx", rc); if (readWrite) *errorMessage += QLatin1String("You need administrator privileges to edit the registry."); return false; } return true; } // Installation helpers: Format the debugger call with placeholders for PID and event // '"[path]\qtcdebugger" [-wow] %ld %ld'. QString debuggerCall(const QString &additionalOption) { QString rc; QTextStream str(&rc); str << '"' << QDir::toNativeSeparators(QApplication::applicationDirPath() + QLatin1Char('/') + QLatin1String(debuggerApplicationFileC) + QLatin1String(".exe")) << '"'; if (!additionalOption.isEmpty()) str << ' ' << additionalOption; str << " %ld %ld"; return rc; } bool isRegistered(HKEY handle, const QString &call, QString *errorMessage, QString *oldDebugger) { QString registeredDebugger; registryReadStringKey(handle, debuggerRegistryValueNameC, &registeredDebugger, errorMessage); if (oldDebugger) *oldDebugger = registeredDebugger; return !registeredDebugger.compare(call, Qt::CaseInsensitive); } } // namespace RegistryAccess
Philips14171/qt-creator-opensource-src-4.2.1
src/shared/registryaccess/registryaccess.cpp
C++
gpl-3.0
5,457
# coding: utf-8 from common import base class Plugin(base.BASE): __name__ = 'csdn' __title__ = 'CSDN' __url__ = 'http://www.csdn.net/' def register(self, target): self.information = { 'email': { 'url': 'http://passport.csdn.net/account/register', 'method': 'get', 'settings': { 'params': { 'action': 'validateEmail', 'email': target } }, 'result': { 'type': 'str', 'value': 'false' } } }
tonybreak/Registered
plugins/csdn.py
Python
gpl-3.0
675
<?php /* ########################################################################## # # # Version 4 / / / # # -----------__---/__---__------__----__---/---/- # # | /| / /___) / ) (_ ` / ) /___) / / # # _|/_|/__(___ _(___/_(__)___/___/_(___ _/___/___ # # Free Content / Management System # # / # # # # # # Copyright 2005-2010 by webspell.org # # # # visit webSPELL.org, webspell.info to get webSPELL for free # # - Script runs under the GNU GENERAL PUBLIC LICENSE # # - It's NOT allowed to remove this copyright-tag # # -- http://www.fsf.org/licensing/licenses/gpl.html # # # # Code based on WebSPELL Clanpackage (Michael Gruber - webspell.at), # # Far Development by Development Team - webspell.org # # # # visit webspell.org # # # ########################################################################## ########################################################################## # # # Version 4 / / / # # -----------__---/__---__------__----__---/---/- # # | /| / /___) / ) (_ ` / ) /___) / / # # _|/_|/__(___ _(___/_(__)___/___/_(___ _/___/___ # # Society / Edition # # / # # # # modified by webspell|k3rmit (Stefan Giesecke) in 2009 # # # # - Modifications are released under the GNU GENERAL PUBLIC LICENSE # # - It is NOT allowed to remove this copyright-tag # # - http://www.fsf.org/licensing/licenses/gpl.html # # # ########################################################################## */ $language_array = Array( /* do not edit above this line */ 'about'=>'About', 'active'=>'active', 'activity'=>'Activity', 'awards'=>'Awards', 'back_overview'=>'&raquo; <a href="index.php?site=members"><b>back to members overview</b></a>', 'challenge'=>'Challenge', 'contact'=>'Contact', 'go'=>'Go!', 'inactive'=>'inactive', 'member'=>'Member', 'members'=>'members', 'nickname'=>'Nickname', 'no_description'=>'no description available', 'position'=>'Position', 'results'=>'Results', 'show_details'=>'&raquo; <a href="index.php?site=members&amp;action=show&amp;squadID=%squadID%"><b>Show details</b></a>', 'show_only'=>'Show only', 'status'=>'Status', 'town'=>'Town' ); ?>
Dwarfex/Hosting-Service
languages/uk/members.php
PHP
gpl-3.0
3,697
/* * Copyright (c) 2014, 2019, Marcus Hirt, Miroslav Wengner * * Robo4J 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. * * Robo4J 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 Robo4J. If not, see <http://www.gnu.org/licenses/>. */ package com.robo4j.hw.rpi.i2c.adafruitbackpack; import java.io.IOException; /** * LedBackpackFactory create an Backpack device by defined type * * @author Marcus Hirt (@hirt) * @author Miroslav Wengner (@miragemiko) */ public final class LedBackpackFactory { public static AbstractBackpack createDevice(int bus, int address, LedBackpackType type, int brightness) throws IOException { switch (type) { case BI_COLOR_BAR_24: return new BiColor24BarDevice(bus, address, brightness); case BI_COLOR_MATRIX_8x8: return new BiColor8x8MatrixDevice(bus, address, brightness); case ALPHANUMERIC: return new AlphanumericDevice(bus, address, brightness); default: throw new IllegalStateException("not available backpack: " + type); } } }
mirage22/robo4j
robo4j-hw-rpi/src/main/java/com/robo4j/hw/rpi/i2c/adafruitbackpack/LedBackpackFactory.java
Java
gpl-3.0
1,458
using System; using Server; using Server.Items; namespace Server.Items { public class ReactiveArmorScroll : SpellScroll { [Constructable] public ReactiveArmorScroll() : this( 1 ) { } [Constructable] public ReactiveArmorScroll( int amount ) : base( 6, 0x1F2D, amount ) { } public ReactiveArmorScroll( Serial ser ) : base( ser ) { } public override void Serialize( GenericWriter writer ) { base.Serialize( writer ); writer.Write( (int) 0 ); // version } public override void Deserialize( GenericReader reader ) { base.Deserialize( reader ); /*int version = */ reader.ReadInt(); } } }
greeduomacro/xrunuo
Scripts/Distro/Items/Skill Items/Magical/Scrolls/First Circle/ReactiveArmorScroll.cs
C#
gpl-3.0
689
package com.example.springjpa; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.validation.BindingResult; import org.springframework.web.bind.annotation.ModelAttribute; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; @Controller @RequestMapping(value = "/personlist") public class PersonListController { @Autowired private PersonList list; @RequestMapping(method = RequestMethod.POST) public String add(@ModelAttribute(value = "newPerson") Person newPerson, BindingResult result, Model model) { if (result.hasErrors()) return "personlist"; list.addPerson(newPerson); return "redirect:/personlist"; } @RequestMapping(method = RequestMethod.GET) public String list(Model model) { model.addAttribute("list", list.getAll()); model.addAttribute("newPerson", new Person()); return "personlist"; } }
robertp1984/softwarecave
springjpa/src/main/java/com/example/springjpa/PersonListController.java
Java
gpl-3.0
1,116
window.nomer=sl(1,4); window.comment='Элементарные бытовые задачи.';
DrMGC/chas-ege
zdn/mat2014gia/B9/main.js
JavaScript
gpl-3.0
94
/* * * This file is part of the Hesperides distribution. * (https://github.com/voyages-sncf-technologies/hesperides) * Copyright (c) 2020 VSCT. * * Hesperides is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as * published by the Free Software Foundation, version 3. * * Hesperides 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.hesperides.core.presentation.security; import org.springframework.http.HttpHeaders; import org.springframework.http.HttpStatus; import org.springframework.security.core.AuthenticationException; import org.springframework.security.web.authentication.www.BasicAuthenticationEntryPoint; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.IOException; final class VerboseBasicAuthenticationEntryPoint extends BasicAuthenticationEntryPoint { VerboseBasicAuthenticationEntryPoint() { setRealmName("Realm"); } @Override public void commence(HttpServletRequest request, HttpServletResponse response, AuthenticationException authException) throws IOException { response.addHeader(HttpHeaders.WWW_AUTHENTICATE, "Basic realm=\"" + getRealmName() + "\""); response.setStatus(HttpStatus.UNAUTHORIZED.value()); String errorMessage = authException.getMessage(); if (authException.getCause() != null) { // LDAP error messages have been seen to contain \u0000 characters. We remove them: errorMessage += " : " + authException.getCause().getMessage().replace("\u0000", ""); } response.getOutputStream().println(errorMessage); } }
voyages-sncf-technologies/hesperides
core/presentation/src/main/java/org/hesperides/core/presentation/security/VerboseBasicAuthenticationEntryPoint.java
Java
gpl-3.0
1,954
# # Copyright (c) 2010-2011, 2015 # Nexa Center for Internet & Society, Politecnico di Torino (DAUIN), # and Simone Basso <bassosimone@gmail.com>. # # This file is part of Neubot <http://www.neubot.org/>. # # Neubot 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. # # Neubot 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 Neubot. If not, see <http://www.gnu.org/licenses/>. # ''' HTTP client ''' import logging from .stream_handler import StreamHandler from .http_client_stream import HttpClientStream from .http_message import HttpMessage from . import utils from . import utils_net class HttpClient(StreamHandler): ''' Manages one or more HTTP streams ''' def __init__(self, poller): ''' Initialize the HTTP client ''' StreamHandler.__init__(self, poller) self.host_header = "" self.rtt = 0 def connect_uri(self, uri, count=1): ''' Connects to the given URI ''' try: message = HttpMessage() message.compose(method="GET", uri=uri) if message.scheme == "https": self.conf["net.stream.secure"] = True endpoint = (message.address, int(message.port)) self.host_header = utils_net.format_epnt(endpoint) except (KeyboardInterrupt, SystemExit): raise except Exception as why: self.connection_failed(None, why) else: self.connect(endpoint, count) def connection_ready(self, stream): ''' Invoked when the connection is ready ''' def got_response_headers(self, stream, request, response): ''' Invoked when we receive response headers ''' return True def got_response(self, stream, request, response): ''' Invoked when we receive the response ''' def connection_made(self, sock, endpoint, rtt): ''' Invoked when the connection is created ''' if rtt: logging.debug("ClientHTTP: latency: %s", utils.time_formatter(rtt)) self.rtt = rtt # XXX If we didn't connect via connect_uri()... if not self.host_header: self.host_header = utils_net.format_epnt(endpoint) stream = HttpClientStream(self.poller) stream.attach(self, sock, self.conf) self.connection_ready(stream)
bassosimone/neubot-server
neubot/runtime/http_client.py
Python
gpl-3.0
2,757
<?php /* ########################################################################## # # # Version 4 / / / # # -----------__---/__---__------__----__---/---/- # # | /| / /___) / ) (_ ` / ) /___) / / # # _|/_|/__(___ _(___/_(__)___/___/_(___ _/___/___ # # Free Content / Management System # # / # # # # # # Copyright 2005-2015 by webspell.org # # # # visit webSPELL.org, webspell.info to get webSPELL for free # # - Script runs under the GNU GENERAL PUBLIC LICENSE # # - It's NOT allowed to remove this copyright-tag # # -- http://www.fsf.org/licensing/licenses/gpl.html # # # # Code based on WebSPELL Clanpackage (Michael Gruber - webspell.at), # # Far Development by Development Team - webspell.org # # # # visit webspell.org # # # ########################################################################## */ $languages = ''; if ($handle = opendir('./languages/')) { while (false !== ($file = readdir($handle))) { if (is_dir('./languages/' . $file) && $file != ".." && $file != "." && $file != ".svn") { $languages .= '<a href="index.php?lang=' . $file . '"><img src="../images/languages/' . $file . '.gif" alt="' . $file . '"></a>'; } } closedir($handle); } ?> <tr> <td id="step" align="center" colspan="2"> <span class="steps start" id="active"><?php echo $_language->module['step0']; ?></span> <span class="steps"><?php echo $_language->module['step1']; ?></span> <span class="steps"><?php echo $_language->module['step2']; ?></span> <span class="steps"><?php echo $_language->module['step3']; ?></span> <span class="steps"><?php echo $_language->module['step4']; ?></span> <span class="steps"><?php echo $_language->module['step5']; ?></span> <span class="steps end"><?php echo $_language->module['step6']; ?></span> </td> </tr> <tr id="headline"> <td id="title" colspan="2"><?php echo $_language->module['welcome']; ?></td> </tr> <tr> <td id="content" colspan="2"> <b><?php echo $_language->module['welcome_to']; ?></b><br><br> <b><?php echo $_language->module['select_a_language']; ?>:</b> <span class="padding"><?php echo $languages; ?></span><br><br> <?php echo $_language->module['welcome_text']; ?> <br><br><br> <?php echo $_language->module['webspell_team']; ?><br> - <a href="http://www.webspell.org" target="_blank">www.webspell.org</a> <div align="right"><br><a href="javascript:document.ws_install.submit()"><img src="images/next.jpg" alt=""></a> </div> </td> </tr>
nerdiabet/webSPELL
install/step0.php
PHP
gpl-3.0
3,517
/*********************************************************************************************** * File Info: $Id: ChartItem.java,v 1.1 2002/11/16 19:03:24 nathaniel_auvil Exp $ * Copyright (C) 2002 * Author: Nathaniel G. Auvil * Contributor(s): * * Copyright 2002 (C) Nathaniel G. Auvil. All Rights Reserved. * * Redistribution and use of this software and associated documentation ("Software"), with or * without modification, are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain copyright statements and notices. * Redistributions must also contain a copy of this document. * * 2. Redistributions in binary form must reproduce the above copyright notice, this list of * conditions and the following disclaimer in the documentation and/or other materials * provided with the distribution. * * 3. The name "jCharts" or "Nathaniel G. Auvil" must not be used to endorse or promote * products derived from this Software without prior written permission of Nathaniel G. * Auvil. For written permission, please contact nathaniel_auvil@users.sourceforge.net * * 4. Products derived from this Software may not be called "jCharts" nor may "jCharts" appear * in their names without prior written permission of Nathaniel G. Auvil. jCharts is a * registered trademark of Nathaniel G. Auvil. * * 5. Due credit should be given to the jCharts Project (http://jcharts.sourceforge.net/). * * THIS SOFTWARE IS PROVIDED BY Nathaniel G. Auvil AND CONTRIBUTORS ``AS IS'' AND ANY * EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL * jCharts OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN * IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE ************************************************************************************************/ package org.jCharts.properties; import java.awt.*; public abstract class ChartItem { private static final Paint DEFAULT_PAINT= Color.black; private Paint paint; public ChartItem() { this.paint= DEFAULT_PAINT; } public ChartItem( Paint paint ) { this.paint= paint; } public Paint getPaint() { return paint; } /********************************************************************************** * Sets the Paint and Stroke implementations on the Graphics2D Object * * @param graphics2D **********************************************************************************/ public void setupGraphics2D( Graphics2D graphics2D ) { graphics2D.setPaint( this.getPaint() ); } }
tectronics/ingatan
src/org/jCharts/properties/ChartItem.java
Java
gpl-3.0
3,137
<?php // =================================================================================================== // _ __ _ _ // | |/ /__ _| | |_ _ _ _ _ __ _ // | ' </ _` | | _| || | '_/ _` | // |_|\_\__,_|_|\__|\_,_|_| \__,_| // // This file is part of the Kaltura Collaborative Media Suite which allows users // to do with audio, video, and animation what Wiki platfroms allow them to do with // text. // // Copyright (C) 2006-2011 Kaltura Inc. // // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU Affero General Public License as // published by the Free Software Foundation, either version 3 of the // License, or (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU Affero General Public License for more details. // // You should have received a copy of the GNU Affero General Public License // along with this program. If not, see <http://www.gnu.org/licenses/>. // // @ignore // =================================================================================================== /** * @namespace */ namespace Kaltura\Client\Enum; /** * @package Kaltura * @subpackage Client */ class ApiParameterPermissionItemAction { const READ = "read"; const UPDATE = "update"; const INSERT = "insert"; const USAGE = "all"; }
intrallect/intraLibrary-moodle
src/repository/intralibrary/vendors/Kaltura/Client/Enum/ApiParameterPermissionItemAction.php
PHP
gpl-3.0
1,584
import unittest import random import sys import os ETEPATH = os.path.abspath(os.path.split(os.path.realpath(__file__))[0]+'/../') sys.path.insert(0, ETEPATH) from ete2 import Tree, TreeStyle, NodeStyle, PhyloTree, faces, random_color from ete2.treeview.faces import * from ete2.treeview.main import _NODE_TYPE_CHECKER, FACE_POSITIONS sys.path.insert(0, os.path.join(ETEPATH, "examples/treeview")) import face_grid, bubble_map, item_faces, node_style, node_background, face_positions, face_rotation, seq_motif_faces, barchart_and_piechart_faces sys.path.insert(0, os.path.join(ETEPATH, "examples/phylogenies")) import phylotree_visualization CONT = 0 class Test_Coretype_Treeview(unittest.TestCase): """ Tests tree basics. """ def test_renderer(self): main_tree = Tree() main_tree.dist = 0 t, ts = face_grid.get_example_tree() t_grid = TreeFace(t, ts) n = main_tree.add_child() n.add_face(t_grid, 0, "aligned") t, ts = bubble_map.get_example_tree() t_bubble = TreeFace(t, ts) n = main_tree.add_child() n.add_face(t_bubble, 0, "aligned") t, ts = item_faces.get_example_tree() t_items = TreeFace(t, ts) n = main_tree.add_child() n.add_face(t_items, 0, "aligned") t, ts = node_style.get_example_tree() t_nodest = TreeFace(t, ts) n = main_tree.add_child() n.add_face(t_nodest, 0, "aligned") t, ts = node_background.get_example_tree() t_bg = TreeFace(t, ts) n = main_tree.add_child() n.add_face(t_bg, 0, "aligned") t, ts = face_positions.get_example_tree() t_fpos = TreeFace(t, ts) n = main_tree.add_child() n.add_face(t_fpos, 0, "aligned") t, ts = phylotree_visualization.get_example_tree() t_phylo = TreeFace(t, ts) n = main_tree.add_child() n.add_face(t_phylo, 0, "aligned") t, ts = face_rotation.get_example_tree() temp_facet = TreeFace(t, ts) n = main_tree.add_child() n.add_face(temp_facet, 0, "aligned") t, ts = seq_motif_faces.get_example_tree() temp_facet = TreeFace(t, ts) n = main_tree.add_child() n.add_face(temp_facet, 0, "aligned") t, ts = barchart_and_piechart_faces.get_example_tree() temp_facet = TreeFace(t, ts) n = main_tree.add_child() n.add_face(temp_facet, 0, "aligned") #Test orphan nodes and trees with 0 branch length t, ts = Tree(), TreeStyle() t.populate(5) for n in t.traverse(): n.dist = 0 temp_tface = TreeFace(t, ts) n = main_tree.add_child() n.add_face(temp_tface, 0, "aligned") ts.optimal_scale_level = "full" temp_tface = TreeFace(t, ts) n = main_tree.add_child() n.add_face(temp_tface, 0, "aligned") ts = TreeStyle() t.populate(5) ts.mode = "c" temp_tface = TreeFace(t, ts) n = main_tree.add_child() n.add_face(temp_tface, 0, "aligned") ts.optimal_scale_level = "full" temp_tface = TreeFace(t, ts) n = main_tree.add_child() n.add_face(temp_tface, 0, "aligned") t, ts = Tree(), TreeStyle() temp_tface = TreeFace(Tree('node;'), ts) n = main_tree.add_child() n.add_face(temp_tface, 0, "aligned") t, ts = Tree(), TreeStyle() ts.mode = "c" temp_tface = TreeFace(Tree('node;'), ts) n = main_tree.add_child() n.add_face(temp_tface, 0, "aligned") t, ts = Tree(), TreeStyle() ts.mode = "c" temp_tface = TreeFace(Tree(), ts) n = main_tree.add_child() n.add_face(temp_tface, 0, "aligned") t, ts = Tree(), TreeStyle() temp_tface = TreeFace(Tree(), ts) n = main_tree.add_child() n.add_face(temp_tface, 0, "aligned") # TEST TIGHT TEST WRAPPING chars = ["." "p", "j", "jJ"] def layout(node): global CONT if CONT >= len(chars): CONT = 0 if node.is_leaf(): node.img_style["size"] = 0 F2= AttrFace("name", tight_text=True) F= TextFace(chars[CONT], tight_text=True) F.inner_border.width = 0 F2.inner_border.width = 0 #faces.add_face_to_node(F ,node, 0, position="branch-right") faces.add_face_to_node(F2 ,node, 1, position="branch-right") CONT += 1 t = Tree() t.populate(20, random_branches=True) ts = TreeStyle() ts.layout_fn = layout ts.mode = "c" ts.show_leaf_name = False temp_tface = TreeFace(t, ts) n = main_tree.add_child() n.add_face(temp_tface, 0, "aligned") # MAIN TREE ms = TreeStyle() ms.mode = "r" ms.show_leaf_name = False main_tree.render('test.png', tree_style=ms) main_tree.render('test.svg', tree_style=ms) if __name__ == '__main__': unittest.main()
fw1121/ete
test/test_treeview.py
Python
gpl-3.0
5,124
using System; using System.Collections.Generic; using System.Text; using System.Windows.Automation; using Microsoft.VisualStudio.TestTools.UnitTesting; using UiClickTestDSL.AutomationCode; using UiClickTestDSL.HelperPrograms; namespace UiClickTestDSL.DslObjects { public class GuiTextBox { public static IEnumerable<AutomationElement> GetAll(AutomationElement window) { var tbs = window.FindAllChildrenByControlType(ControlType.Edit); return tbs; } private static GuiTextBox _cachedtb = null; public static GuiTextBox GetTextBox(AutomationElement window, string automationId) { if (_cachedtb == null || _cachedtb.AutomationId != automationId) { var tb = window.FindChildByControlTypeAndAutomationId(ControlType.Edit, automationId); _cachedtb = new GuiTextBox(tb); } return _cachedtb; } public static GuiTextBox GetTextBoxByName(AutomationElement window, string name) { if (_cachedtb == null || _cachedtb.Name != name) { var tb = window.FindChildByControlTypeAndName(ControlType.Edit, name); _cachedtb = new GuiTextBox(tb); } return _cachedtb; } public static void InvalidateCache() { _cachedtb = null; } protected AutomationElement tbAutoEl; protected ValuePattern value; public string AutomationId { get; protected set; } public string Name { get; protected set; } public GuiTextBox(AutomationElement textbox) { tbAutoEl = textbox; AutomationId = textbox.Current.AutomationId; Name = textbox.Current.Name; value = tbAutoEl.GetPattern<ValuePattern>(ValuePattern.Pattern); } public string Text { get { return value.Current.Value; } } public bool IsEditable { get { return !value.Current.IsReadOnly && tbAutoEl.Current.IsKeyboardFocusable; } } public bool Visible { get { return !tbAutoEl.Current.IsOffscreen; } } public void Type(object text) { Type(text.ToString()); } public void Type(string text) { //Focus(); var completeText = Text + text; Workarounds.TryUntilElementAvailable(() => value.SetValue(completeText)); } public void SetText(object text) { SetText(text.ToString()); } public void SetText(string text) { //Focus(); Workarounds.TryUntilElementAvailable(() => value.SetValue(text)); } public void Focus() { Workarounds.TryUntilElementAvailable(() => tbAutoEl.SetFocus()); } public void ShouldRead(object expected) { ShouldRead(expected.ToString()); } public void ShouldRead(string expected) { Assert.AreEqual(expected, Text); } public void ShouldNotRead(object expected) { ShouldNotRead(expected.ToString()); } public void ShouldNotRead(string expected) { Assert.AreNotEqual(expected, Text); } public void ShouldStartWith(string startText) { Assert.IsTrue(Text.StartsWith(startText, StringComparison.CurrentCultureIgnoreCase), $"Expected TextBox to start with <{startText}>. Actual: <{Text}>."); } public void ShouldNotStartWith(string startText) { Assert.IsFalse(Text.StartsWith(startText, StringComparison.CurrentCultureIgnoreCase), $"Expected TextBox to not start with <{startText}>. Actual: <{Text}>."); } public void ShouldReadLines(params string[] expectedLines) { var expected = new StringBuilder(); foreach (var line in expectedLines) { expected.AppendLine(line); } expected.Length -= Environment.NewLine.Length; ShouldRead(expected.ToString()); } public void ShouldContain(params string[] expectedTexts) { foreach (var expectedText in expectedTexts) { Assert.IsTrue(Text.ContainsIgnoreCase(expectedText), $"TextBox did not contain <{expectedText}>. Actual: <{Text}>."); } } public void AssertIsEditable() { Assert.IsTrue(IsEditable); } public void AssertIsNotEditable() { Assert.IsFalse(IsEditable); } /* public void ShouldNotBeVisible() { Assert.IsTrue(tbAutoEl.Current.IsOffscreen, $"TextBox: {Name} ({AutomationId}) should have been offscreen"); }*/ public void ShouldBeVisible() { Assert.IsFalse(tbAutoEl.Current.IsOffscreen, $"TextBox: {Name} ({AutomationId}) should have been visible"); } } }
ThetaDev/clicktest
UiClickTestDSL/DslObjects/GuiTextBox.cs
C#
gpl-3.0
5,115
package com.linguaculturalists.phoenicia.models; import android.content.Context; import com.linguaculturalists.phoenicia.locale.Locale; import com.linguaculturalists.phoenicia.util.PhoeniciaContext; import com.orm.androrm.Filter; import com.orm.androrm.Model; import com.orm.androrm.QuerySet; import com.orm.androrm.field.BooleanField; import com.orm.androrm.field.CharField; import com.orm.androrm.field.DoubleField; import com.orm.androrm.field.IntegerField; import com.orm.androrm.migration.Migrator; import org.andengine.util.debug.Debug; import java.util.ArrayList; import java.util.Date; import java.util.List; import java.util.concurrent.TimeUnit; /** * Database model representing a single user's game session. */ public class GameSession extends Model { public CharField session_name; /**< user defined name for this session */ public CharField person_name; /**< locale person representing this player */ public CharField locale_pack; /**< path to the locale pack used by this session */ public DoubleField start_timestamp; /**< time when this session was created (in seconds from epoch) */ public DoubleField last_timestamp; /**< last time this session was used (in seconds from epoch) */ public IntegerField sessions_played; /**< incremented every time the session is used */ public IntegerField days_played; /**< number of unique days when this session was used */ public CharField current_level; /**< the name of the current level from the locale that the session has reached */ public IntegerField points; /**< accumulated points from various in-game actions */ public IntegerField account_balance; /**< current amount of in-game currency held by the player */ public IntegerField gross_income; /**< cumulative total of in-game currency earned over the course of this session */ public BooleanField is_active; /**< Whether this session is active (not deleted) and should be displayed */ public BooleanField pref_music; /**< Store user preference to play background music or not */ public Filter filter; public Filter session_filter; private List<ExperienceChangeListener> listeners; public static final QuerySet<GameSession> objects(Context context) { return objects(context, GameSession.class); } public GameSession(){ super(); this.session_name = new CharField(32); this.person_name = new CharField(32); this.locale_pack = new CharField(32); this.start_timestamp = new DoubleField(); this.last_timestamp = new DoubleField(); this.sessions_played = new IntegerField(); this.days_played = new IntegerField(); this.current_level = new CharField(); this.points = new IntegerField(); this.account_balance = new IntegerField(); this.gross_income = new IntegerField(); this.is_active = new BooleanField(); this.pref_music = new BooleanField(); this.listeners = new ArrayList<ExperienceChangeListener>(); } /** * Creates a new GameSession for the given local. * @param locale for the new session * @return a new session */ static public GameSession start(Locale locale) { GameSession session = new GameSession(); session.locale_pack.set(locale.name); Date now = new Date(); session.start_timestamp.set((double)now.getTime()); session.last_timestamp.set((double)now.getTime()); session.sessions_played.set(0); session.days_played.set(0); session.points.set(0); session.account_balance.set(0); session.gross_income.set(0); session.is_active.set(true); session.pref_music.set(true); return session; } static public GameSession start(String locale_path) { GameSession session = new GameSession(); session.locale_pack.set(locale_path); Date now = new Date(); session.start_timestamp.set((double)now.getTime()); session.last_timestamp.set((double)now.getTime()); session.sessions_played.set(0); session.days_played.set(0); session.points.set(0); session.account_balance.set(0); session.gross_income.set(0); session.is_active.set(true); session.pref_music.set(true); return session; } public void reset() { Date now = new Date(); this.start_timestamp.set((double)now.getTime()); this.last_timestamp.set((double)now.getTime()); this.sessions_played.set(0); this.days_played.set(0); this.current_level.reset(); this.points.set(0); this.account_balance.set(0); this.gross_income.set(0); this.is_active.set(true); this.pref_music.set(true); } public int addExperience(int points) { this.points.set(this.points.get()+points); this.experienceChanged(this.points.get()); return this.points.get(); } public int removeExperience(int points) { this.points.set(this.points.get()-points); this.experienceChanged(this.points.get()); return this.points.get(); } private void experienceChanged(int new_xp) { Debug.d("Experience points changed"); for (int i = 0; i < this.listeners.size(); i++) { Debug.d("Calling update listener: "+this.listeners.get(i).getClass()); this.listeners.get(i).onExperienceChanged(new_xp); } } public void addExperienceChangeListener(ExperienceChangeListener listener) { this.listeners.add(listener); } public void removeUpdateListener(ExperienceChangeListener listener) { this.listeners.remove(listener); } @Override public boolean save(Context context) { final boolean retval = super.save(context); if (retval && this.filter == null) { this.filter = new Filter(); this.filter.is("game", this); this.session_filter = new Filter(); this.session_filter.is("session", this); } return retval; } /** * Inform the session of a new instance of play * * Updates #last_timestamp, #sessions_played, and if it has been more than a day since the last * time, also updates the #days_played3 */ public void update() { Date now = new Date(); long diff = now.getTime() - this.last_timestamp.get().longValue(); if (TimeUnit.MILLISECONDS.toDays(diff) > 1) { this.days_played.set(this.days_played.get() + 1); } this.sessions_played.set(this.sessions_played.get() + 1); this.last_timestamp.set((double)now.getTime()); } @Override protected void migrate(Context context) { Migrator<GameSession> migrator = new Migrator<GameSession>(GameSession.class); // Add level field migrator.addField("current_level", new IntegerField()); // Add points field migrator.addField("points", new IntegerField()); migrator.addField("account_balance", new IntegerField()); migrator.addField("gross_income", new IntegerField()); migrator.addField("person_name", new CharField()); // Add state fields migrator.addField("is_active", new BooleanField()); migrator.addField("pref_music", new BooleanField()); // roll out all migrations migrator.migrate(context); return; } /** * Called by the GameSession class whenever the player's experience points changes */ public interface ExperienceChangeListener { public void onExperienceChanged(int new_xp); } }
mhall119/Phoenicia
app/src/main/java/com/linguaculturalists/phoenicia/models/GameSession.java
Java
gpl-3.0
7,698
package uk.ac.exeter.QuinCe.web.Instrument.newInstrument; import javax.faces.application.FacesMessage; import javax.faces.validator.ValidatorException; import uk.ac.exeter.QuinCe.data.Instrument.FileDefinition; /** * Check that the chosen separator results in more than 0 columns * * @author Steve Jones * */ public class SeparatorValidator extends NewInstrumentValidator { @Override public void doValidation(NewInstrumentBean bean, Object value) throws ValidatorException { String separator = ((String) value).trim(); if (!FileDefinition.validateSeparator(separator)) { throw new ValidatorException(new FacesMessage(FacesMessage.SEVERITY_ERROR, "Unsupported separator", "Unsupported separator")); } if (bean.getCurrentInstrumentFile().calculateColumnCount(separator) <= 1) { throw new ValidatorException(new FacesMessage(FacesMessage.SEVERITY_ERROR, "Cannot extract any columns using the specified separator", "Cannot extract any columns using the specified separator")); } } }
BjerknesClimateDataCentre/QuinCe
WebApp/src/uk/ac/exeter/QuinCe/web/Instrument/newInstrument/SeparatorValidator.java
Java
gpl-3.0
1,059
#!/usr/bin/env python # Progressive Cactus Package # Copyright (C) 2009-2012 by Glenn Hickey (hickey@soe.ucsc.edu) # and Benedict Paten (benedictpaten@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/>. # import os import sys import xml.etree.ElementTree as ET import math import time import random import copy from optparse import OptionParser from optparse import OptionGroup import imp import socket import signal import traceback import datetime from sonLib.bioio import logger from sonLib.bioio import setLoggingFromOptions from sonLib.bioio import getTempDirectory from sonLib.bioio import system from sonLib.bioio import popenCatch from jobTree.scriptTree.target import Target from jobTree.scriptTree.stack import Stack from jobTree.src.master import getJobFileDirName, getConfigFileName from jobTree.src.jobTreeStatus import parseJobFiles from cactus.progressive.multiCactusProject import MultiCactusProject from cactus.shared.experimentWrapper import ExperimentWrapper from cactus.shared.configWrapper import ConfigWrapper from seqFile import SeqFile from projectWrapper import ProjectWrapper from jobStatusMonitor import JobStatusMonitor def initParser(): usage = "usage: runProgressiveCactus.sh [options] <seqFile> <workDir> <outputHalFile>\n\n"\ "Required Arguments:\n"\ " <seqFile>\t\tFile containing newick tree and seqeunce paths"\ " paths.\n"\ "\t\t\t(see documetation or examples for format).\n"\ " <workDir>\t\tWorking directory (which can grow "\ "exteremely large)\n"\ " <outputHalFile>\tPath of output alignment in .hal format." parser = OptionParser(usage=usage) #JobTree Options (method below now adds an option group) Stack.addJobTreeOptions(parser) #Progressive Cactus will handle where the jobtree path is parser.remove_option("--jobTree") #Progressive Cactus Options parser.add_option("--optionsFile", dest="optionsFile", help="Text file containing command line options to use as"\ " defaults", default=None) parser.add_option("--database", dest="database", help="Database type: tokyo_cabinet or kyoto_tycoon" " [default: %default]", default="kyoto_tycoon") parser.add_option("--outputMaf", dest="outputMaf", help="[DEPRECATED use hal2maf on the ouput file instead] Path of output alignment in .maf format. This option should be avoided and will soon be removed. It may cause sequence names to be mangled, and use a tremendous amount of memory. ", default=None) parser.add_option("--configFile", dest="configFile", help="Specify cactus configuration file", default=None) parser.add_option("--legacy", dest="legacy", action="store_true", help= "Run cactus directly on all input sequences " "without any progressive decomposition (ie how it " "was originally published in 2011)", default=False) parser.add_option("--autoAbortOnDeadlock", dest="autoAbortOnDeadlock", action="store_true", help="Abort automatically when jobTree monitor" + " suspects a deadlock by deleting the jobTree folder." + " Will guarantee no trailing ktservers but still " + " dangerous to use until we can more robustly detect " + " deadlocks.", default=False) parser.add_option("--overwrite", dest="overwrite", action="store_true", help="Re-align nodes in the tree that have already" + " been successfully aligned.", default=False) parser.add_option("--rootOutgroupDists", dest="rootOutgroupDists", help="root outgroup distance (--rootOutgroupPaths must " + "be given as well)", default=None) parser.add_option("--rootOutgroupPaths", dest="rootOutgroupPaths", type=str, help="root outgroup path (--rootOutgroup must be given " + "as well)", default=None) parser.add_option("--root", dest="root", help="Name of ancestral node (which" " must appear in NEWICK tree in <seqfile>) to use as a " "root for the alignment. Any genomes not below this node " "in the tree may be used as outgroups but will never appear" " in the output. If no root is specifed then the root" " of the tree is used. ", default=None) #Kyoto Tycoon Options ktGroup = OptionGroup(parser, "kyoto_tycoon Options", "Kyoto tycoon provides a client/server framework " "for large in-memory hash tables and is available " "via the --database option.") ktGroup.add_option("--ktPort", dest="ktPort", help="starting port (lower bound of range) of ktservers" " [default: %default]", default=1978) ktGroup.add_option("--ktHost", dest="ktHost", help="The hostname to use for connections to the " "ktserver (this just specifies where nodes will attempt" " to find the server, *not* where the ktserver will be" " run)", default=None) ktGroup.add_option("--ktType", dest="ktType", help="Kyoto Tycoon server type " "(memory, snapshot, or disk)" " [default: %default]", default='memory') # sonlib doesn't allow for spaces in attributes in the db conf # which renders this options useless #ktGroup.add_option("--ktOpts", dest="ktOpts", # help="Command line ktserver options", # default=None) ktGroup.add_option("--ktCreateTuning", dest="ktCreateTuning", help="ktserver options when creating db "\ "(ex #bnum=30m#msiz=50g)", default=None) ktGroup.add_option("--ktOpenTuning", dest="ktOpenTuning", help="ktserver options when opening existing db "\ "(ex #opts=ls#ktopts=p)", default=None) parser.add_option_group(ktGroup) return parser # Try to weed out errors early by checking options and paths def validateInput(workDir, outputHalFile, options): try: if workDir.find(' ') >= 0: raise RuntimeError("Cactus does not support spaces in pathnames: %s" % workDir) if not os.path.isdir(workDir): os.makedirs(workDir) if not os.path.isdir(workDir) or not os.access(workDir, os.W_OK): raise except: raise RuntimeError("Can't write to workDir: %s" % workDir) try: open(outputHalFile, "w") except: raise RuntimeError("Unable to write to hal: %s" % outputHalFile) if options.database != "tokyo_cabinet" and\ options.database != "kyoto_tycoon": raise RuntimeError("Invalid database type: %s" % options.database) if options.outputMaf is not None: try: open(options.outputMaf, "w") except: raise RuntimeError("Unable to write to maf: %s" % options.outputMaf) if options.configFile is not None: try: ConfigWrapper(ET.parse(options.configFile).getroot()) except: raise RuntimeError("Unable to read config: %s" % options.configFile) if options.database == 'kyoto_tycoon': if options.ktType.lower() != 'memory' and\ options.ktType.lower() != 'snapshot' and\ options.ktType.lower() != 'disk': raise RuntimeError("Invalid ktserver type specified: %s. Must be " "memory, snapshot or disk" % options.ktType) # Convert the jobTree options taken in by the parser back # out to command line options to pass to progressive cactus def getJobTreeCommands(jtPath, parser, options): cmds = "--jobTree %s" % jtPath for optGroup in parser.option_groups: if optGroup.title.startswith("jobTree") or optGroup.title.startswith("Jobtree"): for opt in optGroup.option_list: if hasattr(options, opt.dest) and \ getattr(options, opt.dest) != optGroup.defaults[opt.dest]: cmds += " %s" % str(opt) if opt.nargs > 0: cmds += " \"%s\"" % getattr(options, opt.dest) return cmds # Go through a text file and add every word inside to an arguments list # which will be prepended to sys.argv. This way both the file and # command line are passed to the option parser, with the command line # getting priority. def parseOptionsFile(path): if not os.path.isfile(path): raise RuntimeError("Options File not found: %s" % path) args = [] optFile = open(path, "r") for l in optFile: line = l.rstrip() if line: args += shlex.split(line) # This source file should always be in progressiveCactus/src. So # we return the path to progressiveCactus/environment, which needs # to be sourced before doing anything. def getEnvFilePath(): path = os.path.dirname(sys.argv[0]) envFile = os.path.join(path, '..', 'environment') assert os.path.isfile(envFile) return envFile # If specified with the risky --autoAbortOnDeadlock option, we call this to # force an abort if the jobStatusMonitor thinks it's hopeless. # We delete the jobTreePath to get rid of kyoto tycoons. def abortFunction(jtPath, options): def afClosure(): sys.stderr.write('\nAborting due to deadlock (prevent with' + '--noAutoAbort' + ' option), and running rm -rf %s\n\n' % jtPath) system('rm -rf %s' % jtPath) sys.exit(-1) if options.autoAbortOnDeadlock: return afClosure else: return None # Run cactus progressive on the project that has been created in workDir. # Any jobtree options are passed along. Should probably look at redirecting # stdout/stderr in the future. def runCactus(workDir, jtCommands, jtPath, options): envFile = getEnvFilePath() pjPath = os.path.join(workDir, ProjectWrapper.alignmentDirName, '%s_project.xml' % ProjectWrapper.alignmentDirName) logFile = os.path.join(workDir, 'cactus.log') if options.overwrite: overwriteFlag = '--overwrite' system("rm -f %s" % logFile) else: overwriteFlag = '' logHandle = open(logFile, "a") logHandle.write("\n%s: Beginning Progressive Cactus Alignment\n\n" % str( datetime.datetime.now())) logHandle.close() cmd = '. %s && cactus_progressive.py %s %s %s >> %s 2>&1' % (envFile, jtCommands, pjPath, overwriteFlag, logFile) jtMonitor = JobStatusMonitor(jtPath, pjPath, logFile, deadlockCallbackFn=abortFunction(jtPath, options)) if options.database == "kyoto_tycoon": jtMonitor.daemon = True jtMonitor.start() system(cmd) logHandle = open(logFile, "a") logHandle.write("\n%s: Finished Progressive Cactus Alignment\n" % str( datetime.datetime.now())) logHandle.close() def checkCactus(workDir, options): pass # Call cactus2hal to extract a single hal file out of the progressive # alignmenet in the working directory. If the maf option was set, we # just move out the root maf. def extractOutput(workDir, outputHalFile, options): if options.outputMaf is not None: mcProj = MultiCactusProject() mcProj.readXML( os.path.join(workDir, ProjectWrapper.alignmentDirName, ProjectWrapper.alignmentDirName + "_project.xml")) rootName = mcProj.mcTree.getRootName() rootPath = os.path.join(workDir, ProjectWrapper.alignmentDirName, rootName, rootName + '.maf') cmd = 'mv %s %s' % (rootPath, options.outputMaf) system(cmd) envFile = getEnvFilePath() logFile = os.path.join(workDir, 'cactus.log') pjPath = os.path.join(workDir, ProjectWrapper.alignmentDirName, '%s_project.xml' % ProjectWrapper.alignmentDirName) logHandle = open(logFile, "a") logHandle.write("\n\n%s: Beginning HAL Export\n\n" % str( datetime.datetime.now())) logHandle.close() cmd = '. %s && cactus2hal.py %s %s >> %s 2>&1' % (envFile, pjPath, outputHalFile, logFile) system(cmd) logHandle = open(logFile, "a") logHandle.write("\n%s: Finished HAL Export \n" % str( datetime.datetime.now())) logHandle.close() def main(): # init as dummy function cleanKtFn = lambda x,y:x stage = -1 workDir = None try: parser = initParser() options, args = parser.parse_args() if (options.rootOutgroupDists is not None) \ ^ (options.rootOutgroupPaths is not None): parser.error("--rootOutgroupDists and --rootOutgroupPaths must be " + "provided together") if len(args) == 0: parser.print_help() return 1 if len(args) != 3: raise RuntimeError("Error parsing command line. Exactly 3 arguments are required but %d arguments were detected: %s" % (len(args), str(args))) if options.optionsFile != None: fileArgs = parseOptionsFile(options.optionsFile) options, args = parser.parse_args(fileArgs + sys.argv[1:]) if len(args) != 3: raise RuntimeError("Error parsing options file. Make sure all " "options have -- prefix") stage = 0 setLoggingFromOptions(options) seqFile = SeqFile(args[0]) workDir = args[1] outputHalFile = args[2] validateInput(workDir, outputHalFile, options) jtPath = os.path.join(workDir, "jobTree") stage = 1 print "\nBeginning Alignment" system("rm -rf %s" % jtPath) projWrapper = ProjectWrapper(options, seqFile, workDir) projWrapper.writeXml() jtCommands = getJobTreeCommands(jtPath, parser, options) runCactus(workDir, jtCommands, jtPath, options) cmd = 'jobTreeStatus --failIfNotComplete --jobTree %s > /dev/null 2>&1 ' %\ jtPath system(cmd) stage = 2 print "Beginning HAL Export" extractOutput(workDir, outputHalFile, options) print "Success.\n" "Temporary data was left in: %s\n" \ % workDir return 0 except RuntimeError, e: sys.stderr.write("Error: %s\n\n" % str(e)) if stage >= 0 and workDir is not None and os.path.isdir(workDir): sys.stderr.write("Temporary data was left in: %s\n" % workDir) if stage == 1: sys.stderr.write("More information can be found in %s\n" % os.path.join(workDir, "cactus.log")) elif stage == 2: sys.stderr.write("More information can be found in %s\n" % os.path.join(workDir, "cactus.log")) return -1 if __name__ == '__main__': sys.exit(main())
BD2KGenomics/cactus
src/progressiveCactus.py
Python
gpl-3.0
16,648
# frozen_string_literal: true require "active_support/core_ext/array" require "active_support/core_ext/hash/except" require "active_support/core_ext/kernel/singleton_class" module ActiveRecord # = Active Record \Named \Scopes module Scoping module Named extend ActiveSupport::Concern module ClassMethods # Returns an ActiveRecord::Relation scope object. # # posts = Post.all # posts.size # Fires "select count(*) from posts" and returns the count # posts.each {|p| puts p.name } # Fires "select * from posts" and loads post objects # # fruits = Fruit.all # fruits = fruits.where(color: 'red') if options[:red_only] # fruits = fruits.limit(10) if limited? # # You can define a scope that applies to all finders using # {default_scope}[rdoc-ref:Scoping::Default::ClassMethods#default_scope]. def all current_scope = self.current_scope if current_scope if self == current_scope.klass current_scope.clone else relation.merge!(current_scope) end else default_scoped end end def scope_for_association(scope = relation) # :nodoc: current_scope = self.current_scope if current_scope && current_scope.empty_scope? scope else default_scoped(scope) end end def default_scoped(scope = relation) # :nodoc: build_default_scope(scope) || scope end def default_extensions # :nodoc: if scope = current_scope || build_default_scope scope.extensions else [] end end # Adds a class method for retrieving and querying objects. # The method is intended to return an ActiveRecord::Relation # object, which is composable with other scopes. # If it returns +nil+ or +false+, an # {all}[rdoc-ref:Scoping::Named::ClassMethods#all] scope is returned instead. # # A \scope represents a narrowing of a database query, such as # <tt>where(color: :red).select('shirts.*').includes(:washing_instructions)</tt>. # # class Shirt < ActiveRecord::Base # scope :red, -> { where(color: 'red') } # scope :dry_clean_only, -> { joins(:washing_instructions).where('washing_instructions.dry_clean_only = ?', true) } # end # # The above calls to #scope define class methods <tt>Shirt.red</tt> and # <tt>Shirt.dry_clean_only</tt>. <tt>Shirt.red</tt>, in effect, # represents the query <tt>Shirt.where(color: 'red')</tt>. # # You should always pass a callable object to the scopes defined # with #scope. This ensures that the scope is re-evaluated each # time it is called. # # Note that this is simply 'syntactic sugar' for defining an actual # class method: # # class Shirt < ActiveRecord::Base # def self.red # where(color: 'red') # end # end # # Unlike <tt>Shirt.find(...)</tt>, however, the object returned by # <tt>Shirt.red</tt> is not an Array but an ActiveRecord::Relation, # which is composable with other scopes; it resembles the association object # constructed by a {has_many}[rdoc-ref:Associations::ClassMethods#has_many] # declaration. For instance, you can invoke <tt>Shirt.red.first</tt>, <tt>Shirt.red.count</tt>, # <tt>Shirt.red.where(size: 'small')</tt>. Also, just as with the # association objects, named \scopes act like an Array, implementing # Enumerable; <tt>Shirt.red.each(&block)</tt>, <tt>Shirt.red.first</tt>, # and <tt>Shirt.red.inject(memo, &block)</tt> all behave as if # <tt>Shirt.red</tt> really was an array. # # These named \scopes are composable. For instance, # <tt>Shirt.red.dry_clean_only</tt> will produce all shirts that are # both red and dry clean only. Nested finds and calculations also work # with these compositions: <tt>Shirt.red.dry_clean_only.count</tt> # returns the number of garments for which these criteria obtain. # Similarly with <tt>Shirt.red.dry_clean_only.average(:thread_count)</tt>. # # All scopes are available as class methods on the ActiveRecord::Base # descendant upon which the \scopes were defined. But they are also # available to {has_many}[rdoc-ref:Associations::ClassMethods#has_many] # associations. If, # # class Person < ActiveRecord::Base # has_many :shirts # end # # then <tt>elton.shirts.red.dry_clean_only</tt> will return all of # Elton's red, dry clean only shirts. # # \Named scopes can also have extensions, just as with # {has_many}[rdoc-ref:Associations::ClassMethods#has_many] declarations: # # class Shirt < ActiveRecord::Base # scope :red, -> { where(color: 'red') } do # def dom_id # 'red_shirts' # end # end # end # # Scopes can also be used while creating/building a record. # # class Article < ActiveRecord::Base # scope :published, -> { where(published: true) } # end # # Article.published.new.published # => true # Article.published.create.published # => true # # \Class methods on your model are automatically available # on scopes. Assuming the following setup: # # class Article < ActiveRecord::Base # scope :published, -> { where(published: true) } # scope :featured, -> { where(featured: true) } # # def self.latest_article # order('published_at desc').first # end # # def self.titles # pluck(:title) # end # end # # We are able to call the methods like this: # # Article.published.featured.latest_article # Article.featured.titles def scope(name, body, &block) unless body.respond_to?(:call) raise ArgumentError, "The scope body needs to be callable." end if dangerous_class_method?(name) raise ArgumentError, "You tried to define a scope named \"#{name}\" " \ "on the model \"#{self.name}\", but Active Record already defined " \ "a class method with the same name." end if method_defined_within?(name, Relation) raise ArgumentError, "You tried to define a scope named \"#{name}\" " \ "on the model \"#{self.name}\", but ActiveRecord::Relation already defined " \ "an instance method with the same name." end valid_scope_name?(name) extension = Module.new(&block) if block if body.respond_to?(:to_proc) singleton_class.send(:define_method, name) do |*args| scope = all scope = scope._exec_scope(*args, &body) scope = scope.extending(extension) if extension scope end else singleton_class.send(:define_method, name) do |*args| scope = all scope = scope.scoping { body.call(*args) || scope } scope = scope.extending(extension) if extension scope end end generate_relation_method(name) end private def valid_scope_name?(name) if respond_to?(name, true) && logger logger.warn "Creating scope :#{name}. " \ "Overwriting existing method #{self.name}.#{name}." end end end end end end
BeGe78/esood
vendor/bundle/ruby/3.0.0/gems/activerecord-5.2.6/lib/active_record/scoping/named.rb
Ruby
gpl-3.0
8,106
/** * Copyright (c) 2011-2014, SpaceToad and the BuildCraft Team * http://www.mod-buildcraft.com * * The BuildCraft API is distributed under the terms of the MIT License. * Please check the contents of the license, which should be located * as "LICENSE.API" in the BuildCraft source code distribution. */ package buildcraft.api.blueprints; public abstract class SchematicBlockBase extends Schematic { }
AEnterprise/Buildcraft-Additions
src/main/java/buildcraft/api/blueprints/SchematicBlockBase.java
Java
gpl-3.0
412
class AddPlanIdToDonations < ActiveRecord::Migration def change add_column :donations, :plan_id, :integer end end
nossas/bonde-server
db/migrate/20160620130706_add_plan_id_to_donations.rb
Ruby
gpl-3.0
122
var __extends = (this && this.__extends) || function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; function __() { this.constructor = d; } d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); }; (function (factory) { if (typeof module === 'object' && typeof module.exports === 'object') { var v = factory(require, exports); if (v !== undefined) module.exports = v; } else if (typeof define === 'function' && define.amd) { define(["require", "exports", '@angular/core', '@angular/forms', '../app/app', '../../util/dom', '../../config/config', '../content/content', '../../util/dom-controller', '../../util/form', '../ion', '../../util/util', '../item/item', '../../navigation/nav-controller', '../../platform/platform'], factory); } })(function (require, exports) { "use strict"; var core_1 = require('@angular/core'); var forms_1 = require('@angular/forms'); var app_1 = require('../app/app'); var dom_1 = require('../../util/dom'); var config_1 = require('../../config/config'); var content_1 = require('../content/content'); var dom_controller_1 = require('../../util/dom-controller'); var form_1 = require('../../util/form'); var ion_1 = require('../ion'); var util_1 = require('../../util/util'); var item_1 = require('../item/item'); var nav_controller_1 = require('../../navigation/nav-controller'); var platform_1 = require('../../platform/platform'); /** * @private * Hopefully someday a majority of the auto-scrolling tricks can get removed. */ var InputBase = (function (_super) { __extends(InputBase, _super); function InputBase(config, _form, _item, _app, _platform, elementRef, renderer, _content, nav, ngControl, _dom) { var _this = this; _super.call(this, config, elementRef, renderer, 'input'); this._form = _form; this._item = _item; this._app = _app; this._platform = _platform; this._content = _content; this._dom = _dom; this._disabled = false; this._type = 'text'; this._value = ''; this._nav = nav; this._useAssist = config.getBoolean('scrollAssist', false); this._usePadding = config.getBoolean('scrollPadding', this._useAssist); this._keyboardHeight = config.getNumber('keyboardHeight'); this._autoFocusAssist = config.get('autoFocusAssist', 'delay'); this._autoComplete = config.get('autocomplete', 'off'); this._autoCorrect = config.get('autocorrect', 'off'); if (ngControl) { ngControl.valueAccessor = this; this.inputControl = ngControl; } _form.register(this); // only listen to content scroll events if there is content if (_content) { this._scrollStart = _content.ionScrollStart.subscribe(function (ev) { _this.scrollHideFocus(ev, true); }); this._scrollEnd = _content.ionScrollEnd.subscribe(function (ev) { _this.scrollHideFocus(ev, false); }); } } InputBase.prototype.scrollHideFocus = function (ev, shouldHideFocus) { var _this = this; // do not continue if there's no nav, or it's transitioning if (!this._nav) return; // DOM READ: check if this input has focus if (this.hasFocus()) { // if it does have focus, then do the dom write this._dom.write(function () { _this._native.hideFocus(shouldHideFocus); }); } }; InputBase.prototype.setItemInputControlCss = function () { var item = this._item; var nativeInput = this._native; var inputControl = this.inputControl; // Set the control classes on the item if (item && inputControl) { this.setControlCss(item, inputControl); } // Set the control classes on the native input if (nativeInput && inputControl) { this.setControlCss(nativeInput, inputControl); } }; InputBase.prototype.setControlCss = function (element, control) { element.setElementClass('ng-untouched', control.untouched); element.setElementClass('ng-touched', control.touched); element.setElementClass('ng-pristine', control.pristine); element.setElementClass('ng-dirty', control.dirty); element.setElementClass('ng-valid', control.valid); element.setElementClass('ng-invalid', !control.valid); }; InputBase.prototype.setValue = function (val) { this._value = val; this.checkHasValue(val); }; InputBase.prototype.setType = function (val) { this._type = 'text'; if (val) { val = val.toLowerCase(); if (/password|email|number|search|tel|url|date|month|time|week/.test(val)) { this._type = val; } } }; InputBase.prototype.setDisabled = function (val) { this._disabled = util_1.isTrueProperty(val); this._item && this._item.setElementClass('item-input-disabled', this._disabled); this._native && this._native.isDisabled(this._disabled); }; InputBase.prototype.setClearOnEdit = function (val) { this._clearOnEdit = util_1.isTrueProperty(val); }; /** * Check if we need to clear the text input if clearOnEdit is enabled * @private */ InputBase.prototype.checkClearOnEdit = function (inputValue) { if (!this._clearOnEdit) { return; } // Did the input value change after it was blurred and edited? if (this._didBlurAfterEdit && this.hasValue()) { // Clear the input this.clearTextInput(); } // Reset the flag this._didBlurAfterEdit = false; }; /** * Overriden in child input * @private */ InputBase.prototype.clearTextInput = function () { }; /** * @private */ InputBase.prototype.setNativeInput = function (nativeInput) { var _this = this; this._native = nativeInput; if (this._item && this._item.labelId !== null) { nativeInput.labelledBy(this._item.labelId); } nativeInput.valueChange.subscribe(function (inputValue) { _this.onChange(inputValue); }); nativeInput.keydown.subscribe(function (inputValue) { _this.onKeydown(inputValue); }); this.focusChange(this.hasFocus()); nativeInput.focusChange.subscribe(function (textInputHasFocus) { _this.focusChange(textInputHasFocus); _this.checkHasValue(nativeInput.getValue()); if (!textInputHasFocus) { _this.onTouched(textInputHasFocus); } }); this.checkHasValue(nativeInput.getValue()); this.setDisabled(this._disabled); var ionInputEle = this._elementRef.nativeElement; var nativeInputEle = nativeInput.element(); // copy ion-input attributes to the native input element dom_1.copyInputAttributes(ionInputEle, nativeInputEle); if (ionInputEle.hasAttribute('autofocus')) { // the ion-input element has the autofocus attributes ionInputEle.removeAttribute('autofocus'); if (this._autoFocusAssist === 'immediate') { // config says to immediate focus on the input // works best on android devices nativeInputEle.focus(); } else if (this._autoFocusAssist === 'delay') { // config says to chill out a bit and focus on the input after transitions // works best on desktop setTimeout(function () { nativeInputEle.focus(); }, 650); } } // by default set autocomplete="off" unless specified by the input if (ionInputEle.hasAttribute('autocomplete')) { this._autoComplete = ionInputEle.getAttribute('autocomplete'); } nativeInputEle.setAttribute('autocomplete', this._autoComplete); // by default set autocorrect="off" unless specified by the input if (ionInputEle.hasAttribute('autocorrect')) { this._autoCorrect = ionInputEle.getAttribute('autocorrect'); } nativeInputEle.setAttribute('autocorrect', this._autoCorrect); }; /** * @private */ InputBase.prototype.setNextInput = function (nextInput) { var _this = this; if (nextInput) { nextInput.focused.subscribe(function () { _this._form.tabFocus(_this); }); } }; /** * @private * Angular2 Forms API method called by the model (Control) on change to update * the checked value. * https://github.com/angular/angular/blob/master/modules/angular2/src/forms/directives/shared.ts#L34 */ InputBase.prototype.writeValue = function (val) { this._value = val; this.checkHasValue(val); }; /** * @private */ InputBase.prototype.onChange = function (val) { this.checkHasValue(val); }; /** * onKeydown handler for clearOnEdit * @private */ InputBase.prototype.onKeydown = function (val) { if (this._clearOnEdit) { this.checkClearOnEdit(val); } }; /** * @private */ InputBase.prototype.onTouched = function (val) { }; /** * @private */ InputBase.prototype.hasFocus = function () { // check if an input has focus or not return this._native.hasFocus(); }; /** * @private */ InputBase.prototype.hasValue = function () { var inputValue = this._value; return (inputValue !== null && inputValue !== undefined && inputValue !== ''); }; /** * @private */ InputBase.prototype.checkHasValue = function (inputValue) { if (this._item) { var hasValue = (inputValue !== null && inputValue !== undefined && inputValue !== ''); this._item.setElementClass('input-has-value', hasValue); } }; /** * @private */ InputBase.prototype.focusChange = function (inputHasFocus) { if (this._item) { (void 0) /* console.debug */; this._item.setElementClass('input-has-focus', inputHasFocus); } // If clearOnEdit is enabled and the input blurred but has a value, set a flag if (this._clearOnEdit && !inputHasFocus && this.hasValue()) { this._didBlurAfterEdit = true; } }; InputBase.prototype.pointerStart = function (ev) { // input cover touchstart if (ev.type === 'touchstart') { this._isTouch = true; } if ((this._isTouch || (!this._isTouch && ev.type === 'mousedown')) && this._app.isEnabled()) { // remember where the touchstart/mousedown started this._coord = dom_1.pointerCoord(ev); } (void 0) /* console.debug */; }; InputBase.prototype.pointerEnd = function (ev) { // input cover touchend/mouseup (void 0) /* console.debug */; if ((this._isTouch && ev.type === 'mouseup') || !this._app.isEnabled()) { // the app is actively doing something right now // don't try to scroll in the input ev.preventDefault(); ev.stopPropagation(); } else if (this._coord) { // get where the touchend/mouseup ended var endCoord = dom_1.pointerCoord(ev); // focus this input if the pointer hasn't moved XX pixels // and the input doesn't already have focus if (!dom_1.hasPointerMoved(8, this._coord, endCoord) && !this.hasFocus()) { ev.preventDefault(); ev.stopPropagation(); // begin the input focus process this.initFocus(); } } this._coord = null; }; /** * @private */ InputBase.prototype.initFocus = function () { var _this = this; // begin the process of setting focus to the inner input element var content = this._content; (void 0) /* console.debug */; if (content) { // this input is inside of a scroll view // find out if text input should be manually scrolled into view // get container of this input, probably an ion-item a few nodes up var ele = this._elementRef.nativeElement; ele = ele.closest('ion-item,[ion-item]') || ele; var scrollData = getScrollData(ele.offsetTop, ele.offsetHeight, content.getContentDimensions(), this._keyboardHeight, this._platform.height()); if (Math.abs(scrollData.scrollAmount) < 4) { // the text input is in a safe position that doesn't // require it to be scrolled into view, just set focus now this.setFocus(); // all good, allow clicks again this._app.setEnabled(true); this._nav && this._nav.setTransitioning(false); if (this._usePadding) { content.clearScrollPaddingFocusOut(); } return; } if (this._usePadding) { // add padding to the bottom of the scroll view (if needed) content.addScrollPadding(scrollData.scrollPadding); } // manually scroll the text input to the top // do not allow any clicks while it's scrolling var scrollDuration = getScrollAssistDuration(scrollData.scrollAmount); this._app.setEnabled(false, scrollDuration); this._nav && this._nav.setTransitioning(true); // temporarily move the focus to the focus holder so the browser // doesn't freak out while it's trying to get the input in place // at this point the native text input still does not have focus this._native.beginFocus(true, scrollData.inputSafeY); // scroll the input into place content.scrollTo(0, scrollData.scrollTo, scrollDuration, function () { (void 0) /* console.debug */; // the scroll view is in the correct position now // give the native text input focus _this._native.beginFocus(false, 0); // ensure this is the focused input _this.setFocus(); // all good, allow clicks again _this._app.setEnabled(true); _this._nav && _this._nav.setTransitioning(false); if (_this._usePadding) { content.clearScrollPaddingFocusOut(); } }); } else { // not inside of a scroll view, just focus it this.setFocus(); } }; /** * @private */ InputBase.prototype.setFocus = function () { // immediately set focus this._form.setAsFocused(this); // set focus on the actual input element (void 0) /* console.debug */; this._native.setFocus(); // ensure the body hasn't scrolled down document.body.scrollTop = 0; }; /** * @private * Angular2 Forms API method called by the view (formControlName) to register the * onChange event handler that updates the model (Control). * @param {Function} fn the onChange event handler. */ InputBase.prototype.registerOnChange = function (fn) { this.onChange = fn; }; /** * @private * Angular2 Forms API method called by the view (formControlName) to register * the onTouched event handler that marks model (Control) as touched. * @param {Function} fn onTouched event handler. */ InputBase.prototype.registerOnTouched = function (fn) { this.onTouched = fn; }; InputBase.prototype.focusNext = function () { this._form.tabFocus(this); }; /** @nocollapse */ InputBase.ctorParameters = [ { type: config_1.Config, }, { type: form_1.Form, }, { type: item_1.Item, }, { type: app_1.App, }, { type: platform_1.Platform, }, { type: core_1.ElementRef, }, { type: core_1.Renderer, }, { type: content_1.Content, decorators: [{ type: core_1.Optional },] }, { type: nav_controller_1.NavController, }, { type: forms_1.NgControl, }, { type: dom_controller_1.DomController, }, ]; return InputBase; }(ion_1.Ion)); exports.InputBase = InputBase; /** * @private */ function getScrollData(inputOffsetTop, inputOffsetHeight, scrollViewDimensions, keyboardHeight, plaformHeight) { // compute input's Y values relative to the body var inputTop = (inputOffsetTop + scrollViewDimensions.contentTop - scrollViewDimensions.scrollTop); var inputBottom = (inputTop + inputOffsetHeight); // compute the safe area which is the viewable content area when the soft keyboard is up var safeAreaTop = scrollViewDimensions.contentTop; var safeAreaHeight = (plaformHeight - keyboardHeight - safeAreaTop) / 2; var safeAreaBottom = safeAreaTop + safeAreaHeight; // figure out if each edge of teh input is within the safe area var inputTopWithinSafeArea = (inputTop >= safeAreaTop && inputTop <= safeAreaBottom); var inputTopAboveSafeArea = (inputTop < safeAreaTop); var inputTopBelowSafeArea = (inputTop > safeAreaBottom); var inputBottomWithinSafeArea = (inputBottom >= safeAreaTop && inputBottom <= safeAreaBottom); var inputBottomBelowSafeArea = (inputBottom > safeAreaBottom); /* Text Input Scroll To Scenarios --------------------------------------- 1) Input top within safe area, bottom within safe area 2) Input top within safe area, bottom below safe area, room to scroll 3) Input top above safe area, bottom within safe area, room to scroll 4) Input top below safe area, no room to scroll, input smaller than safe area 5) Input top within safe area, bottom below safe area, no room to scroll, input smaller than safe area 6) Input top within safe area, bottom below safe area, no room to scroll, input larger than safe area 7) Input top below safe area, no room to scroll, input larger than safe area */ var scrollData = { scrollAmount: 0, scrollTo: 0, scrollPadding: 0, inputSafeY: 0 }; if (inputTopWithinSafeArea && inputBottomWithinSafeArea) { // Input top within safe area, bottom within safe area // no need to scroll to a position, it's good as-is return scrollData; } // looks like we'll have to do some auto-scrolling if (inputTopBelowSafeArea || inputBottomBelowSafeArea || inputTopAboveSafeArea) { // Input top or bottom below safe area // auto scroll the input up so at least the top of it shows if (safeAreaHeight > inputOffsetHeight) { // safe area height is taller than the input height, so we // can bring up the input just enough to show the input bottom scrollData.scrollAmount = Math.round(safeAreaBottom - inputBottom); } else { // safe area height is smaller than the input height, so we can // only scroll it up so the input top is at the top of the safe area // however the input bottom will be below the safe area scrollData.scrollAmount = Math.round(safeAreaTop - inputTop); } scrollData.inputSafeY = -(inputTop - safeAreaTop) + 4; if (inputTopAboveSafeArea && scrollData.scrollAmount > inputOffsetHeight) { // the input top is above the safe area and we're already scrolling it into place // don't let it scroll more than the height of the input scrollData.scrollAmount = inputOffsetHeight; } } // figure out where it should scroll to for the best position to the input scrollData.scrollTo = (scrollViewDimensions.scrollTop - scrollData.scrollAmount); // when auto-scrolling, there also needs to be enough // content padding at the bottom of the scroll view // always add scroll padding when a text input has focus // this allows for the content to scroll above of the keyboard // content behind the keyboard would be blank // some cases may not need it, but when jumping around it's best // to have the padding already rendered so there's no jank scrollData.scrollPadding = keyboardHeight; // var safeAreaEle: HTMLElement = (<any>window).safeAreaEle; // if (!safeAreaEle) { // safeAreaEle = (<any>window).safeAreaEle = document.createElement('div'); // safeAreaEle.style.cssText = 'position:absolute; padding:1px 5px; left:0; right:0; font-weight:bold; font-size:10px; font-family:Courier; text-align:right; background:rgba(0, 128, 0, 0.8); text-shadow:1px 1px white; pointer-events:none;'; // document.body.appendChild(safeAreaEle); // } // safeAreaEle.style.top = safeAreaTop + 'px'; // safeAreaEle.style.height = safeAreaHeight + 'px'; // safeAreaEle.innerHTML = ` // <div>scrollTo: ${scrollData.scrollTo}</div> // <div>scrollAmount: ${scrollData.scrollAmount}</div> // <div>scrollPadding: ${scrollData.scrollPadding}</div> // <div>inputSafeY: ${scrollData.inputSafeY}</div> // <div>scrollHeight: ${scrollViewDimensions.scrollHeight}</div> // <div>scrollTop: ${scrollViewDimensions.scrollTop}</div> // <div>contentHeight: ${scrollViewDimensions.contentHeight}</div> // <div>plaformHeight: ${plaformHeight}</div> // `; return scrollData; } exports.getScrollData = getScrollData; var SCROLL_ASSIST_SPEED = 0.3; function getScrollAssistDuration(distanceToScroll) { distanceToScroll = Math.abs(distanceToScroll); var duration = distanceToScroll / SCROLL_ASSIST_SPEED; return Math.min(400, Math.max(150, duration)); } }); //# sourceMappingURL=input-base.js.map
kfrerichs/roleplay
node_modules/ionic-angular/umd/components/input/input-base.js
JavaScript
gpl-3.0
24,204
<?php use yii\helpers\Html; use yii\grid\GridView; use yii\widgets\Pjax; /* @var $this yii\web\View */ /* @var $model izyue\admin\models\BizRule */ /* @var $dataProvider yii\data\ActiveDataProvider */ /* @var $searchModel izyue\admin\models\searchs\BizRule */ $this->title = Yii::t('rbac-admin', 'Rules'); $this->params['breadcrumbs'][] = $this->title; ?> <section class="wrapper site-min-height"> <!-- page start--> <section class="panel"> <header class="panel-heading"> <?=$this->title?> </header> <div class="panel-body"> <div class="adv-table editable-table "> <div class="space15"></div> <?= GridView::widget([ 'dataProvider' => $dataProvider, 'filterModel' => $searchModel, 'tableOptions' => [ 'class' => 'table table-striped table-hover table-bordered', 'id' => 'editable-sample', ], 'pager' => [ 'prevPageLabel' => Yii::t('rbac-admin', 'Prev'), 'nextPageLabel' => Yii::t('rbac-admin', 'Next'), ], 'layout'=> '{items} <div class="row"> <div class="col-lg-6"> <div class="dataTables_info" id="editable-sample_info">{summary}</div> </div> <div class="col-lg-6"> <div class="dataTables_paginate paging_bootstrap pagination">{pager}</div> </div> </div>', 'columns' => [ ['class' => 'yii\grid\SerialColumn'], 'route', 'url', [ 'attribute' => 'admin.username', 'filter' => Html::activeTextInput($searchModel, 'admin', [ 'class' => 'form-control', 'id' => null ]), ], 'admin_email', 'ip', [ 'class' => 'yii\grid\ActionColumn', 'template' => '{view}' ], ], ]); ?> </div> </div> </section> <!-- page end--> </section>
liulipeng/Yii2-Admin
views/log/index.php
PHP
gpl-3.0
2,636
/* * Copyright (c) 2010, * Gavriloaie Eugen-Andrei (shiretu@gmail.com) * * This file is part of crtmpserver. * crtmpserver 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. * * crtmpserver 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 crtmpserver. If not, see <http://www.gnu.org/licenses/>. */ #ifdef HAS_PROTOCOL_VAR #include "protocols/variant/basevariantprotocol.h" #include "protocols/variant/basevariantappprotocolhandler.h" #include "protocols/http/outboundhttpprotocol.h" #include "application/baseclientapplication.h" #include "protocols/protocolmanager.h" BaseVariantProtocol::BaseVariantProtocol(uint64_t type) : BaseProtocol(type) { _pProtocolHandler = NULL; } BaseVariantProtocol::~BaseVariantProtocol() { } bool BaseVariantProtocol::Initialize(Variant &parameters) { return true; } void BaseVariantProtocol::SetApplication(BaseClientApplication *pApplication) { BaseProtocol::SetApplication(pApplication); if (pApplication != NULL) { _pProtocolHandler = (BaseVariantAppProtocolHandler *) pApplication->GetProtocolHandler(this); } else { _pProtocolHandler = NULL; } } IOBuffer * BaseVariantProtocol::GetOutputBuffer() { if (GETAVAILABLEBYTESCOUNT(_outputBuffer) == 0) return NULL; return &_outputBuffer; } bool BaseVariantProtocol::AllowFarProtocol(uint64_t type) { return type == PT_TCP || type == PT_OUTBOUND_HTTP || type == PT_INBOUND_HTTP; } bool BaseVariantProtocol::AllowNearProtocol(uint64_t type) { ASSERT("This is an endpoint protocol"); return false; } bool BaseVariantProtocol::SignalInputData(int32_t recvAmount) { ASSERT("OPERATION NOT SUPPORTED"); return false; } bool BaseVariantProtocol::SignalInputData(IOBuffer &buffer) { if (_pProtocolHandler == NULL) { FATAL("This protocol is not registered to any application yet"); return false; } if (_pFarProtocol->GetType() == PT_OUTBOUND_HTTP || _pFarProtocol->GetType() == PT_INBOUND_HTTP) { #ifdef HAS_PROTOCOL_HTTP //1. This is a HTTP based transfer. We only start doing stuff //after a complete request is made. BaseHTTPProtocol *pHTTPProtocol = (BaseHTTPProtocol *) _pFarProtocol; if (!pHTTPProtocol->TransferCompleted()) return true; if (!Deserialize(GETIBPOINTER(buffer), pHTTPProtocol->GetContentLength(), _lastReceived)) { FATAL("Unable to deserialize content"); return false; } buffer.Ignore(pHTTPProtocol->GetContentLength()); _lastReceived.Compact(); return _pProtocolHandler->ProcessMessage(this, _lastSent, _lastReceived); #else FATAL("HTTP protocol not supported"); return false; #endif /* HAS_PROTOCOL_HTTP */ } else if (_pFarProtocol->GetType() == PT_TCP) { while (GETAVAILABLEBYTESCOUNT(buffer) > 4) { uint32_t size = ENTOHLP(GETIBPOINTER(buffer)); if (size > 1024 * 128) { FATAL("Size too big: %u", size); return false; } if (GETAVAILABLEBYTESCOUNT(buffer) < size + 4) { FINEST("Need more data"); return true; } if (!Deserialize(GETIBPOINTER(buffer) + 4, size, _lastReceived)) { FATAL("Unable to deserialize variant"); return false; } buffer.Ignore(size + 4); _lastReceived.Compact(); if (!_pProtocolHandler->ProcessMessage(this, _lastSent, _lastReceived)) { FATAL("Unable to process message"); return false; } } return true; } else { FATAL("Invalid protocol stack"); return false; } } bool BaseVariantProtocol::Send(Variant &variant) { //1. Do we have a protocol? if (_pFarProtocol == NULL) { FATAL("This protocol is not linked"); return false; } //2. Save the variant _lastSent = variant; //3. Depending on the far protocol, we do different stuff string rawContent = ""; switch (_pFarProtocol->GetType()) { case PT_TCP: { //5. Serialize it if (!Serialize(rawContent, variant)) { FATAL("Unable to serialize variant"); return false; } _outputBuffer.ReadFromRepeat(0, 4); uint32_t rawContentSize = rawContent.size(); EHTONLP(GETIBPOINTER(_outputBuffer), rawContentSize); _outputBuffer.ReadFromString(rawContent); //6. enqueue for outbound return EnqueueForOutbound(); } case PT_OUTBOUND_HTTP: { #ifdef HAS_PROTOCOL_HTTP //7. This is a HTTP request. So, first things first: get the http protocol OutboundHTTPProtocol *pHTTP = (OutboundHTTPProtocol *) _pFarProtocol; //8. We wish to disconnect after the transfer is complete pHTTP->SetDisconnectAfterTransfer(true); //9. This will always be a POST pHTTP->Method(HTTP_METHOD_POST); //10. Our document and the host pHTTP->Document(variant["document"]); pHTTP->Host(variant["host"]); //11. Serialize it if (!Serialize(rawContent, variant["payload"])) { FATAL("Unable to serialize variant"); return false; } _outputBuffer.ReadFromString(rawContent); //12. enqueue for outbound return EnqueueForOutbound(); #else FATAL("HTTP protocol not supported"); return false; #endif /* HAS_PROTOCOL_HTTP */ } case PT_INBOUND_HTTP: { #ifdef HAS_PROTOCOL_HTTP if (!Serialize(rawContent, variant)) { FATAL("Unable to serialize variant"); return false; } _outputBuffer.ReadFromString(rawContent); return EnqueueForOutbound(); #else FATAL("HTTP protocol not supported"); return false; #endif /* HAS_PROTOCOL_HTTP */ } default: { ASSERT("We should not be here"); return false; } } } #endif /* HAS_PROTOCOL_VAR */
a4tunado/crtmpserver
sources/thelib/src/protocols/variant/basevariantprotocol.cpp
C++
gpl-3.0
5,856
/******************************************************************************* Copyright (C) The University of Auckland OpenCOR 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. OpenCOR 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://gnu.org/licenses>. *******************************************************************************/ //============================================================================== // Data store Python wrapper //============================================================================== #include <Qt> //============================================================================== // Note: yes, these two header files must be included in this order... #include "datastorepythonwrapper.h" #include "datastorepythonnumpy.h" //============================================================================== #include "pythonqtsupport.h" //============================================================================== #include <array> //============================================================================== namespace OpenCOR { namespace DataStore { //============================================================================== static bool initNumPy() { // Initialise NumPy import_array1(false) return true; } //============================================================================== static DataStoreValue * getDataStoreValue(PyObject *pValuesDict, PyObject *pKey) { // Get and return a DataStoreValue item from a values dictionary PythonQtInstanceWrapper *wrappedObject = PythonQtSupport::getInstanceWrapper(PyDict_GetItem(pValuesDict, pKey)); if (wrappedObject != nullptr) { return static_cast<DataStoreValue *>(wrappedObject->_objPointerCopy); } return nullptr; } //============================================================================== static PyObject * DataStoreValuesDict_subscript(PyObject *pValuesDict, PyObject *pKey) { // Get and return a subscripted item from a values dictionary DataStoreValue *dataStoreValue = getDataStoreValue(pValuesDict, pKey); if (dataStoreValue != nullptr) { return PyFloat_FromDouble(dataStoreValue->value()); } #include "pythonbegin.h" Py_RETURN_NONE; #include "pythonend.h" } //============================================================================== using DataStoreValuesDictObject = struct { PyDictObject dict; SimulationSupport::SimulationDataUpdatedFunction *simulationDataUpdatedFunction; }; //============================================================================== static int DataStoreValuesDict_ass_subscript(PyObject *pValuesDict, PyObject *pKey, PyObject *pValue) { // Assign to a subscripted item in a values dictionary if (pValue == nullptr) { return PyDict_DelItem(pValuesDict, pKey); } if (PyNumber_Check(pValue) == 1) { DataStoreValue *dataStoreValue = getDataStoreValue(pValuesDict, pKey); if (dataStoreValue != nullptr) { #include "pythonbegin.h" auto newValue = PyFloat_AS_DOUBLE(PyNumber_Float(pValue)); // NOLINT(cppcoreguidelines-pro-type-cstyle-cast) #include "pythonend.h" if (!qFuzzyCompare(dataStoreValue->value(), newValue)) { dataStoreValue->setValue(newValue); // Let our SimulationData object know that simulation data values // have been updated auto simulationDataUpdatedFunction = reinterpret_cast<DataStoreValuesDictObject *>(pValuesDict)->simulationDataUpdatedFunction; if (simulationDataUpdatedFunction != nullptr) { (*simulationDataUpdatedFunction)(); } } return 0; } } PyErr_SetString(PyExc_TypeError, qPrintable(QObject::tr("invalid value."))); return -1; } //============================================================================== static PyMappingMethods DataStoreValuesDict_as_mapping = { nullptr, // mp_length static_cast<binaryfunc>(DataStoreValuesDict_subscript), // mp_subscript static_cast<objobjargproc>(DataStoreValuesDict_ass_subscript) // mp_ass_subscript }; //============================================================================== #include "pythonbegin.h" static PyObject * DataStoreValuesDict_repr(DataStoreValuesDictObject *pValuesDict) { // A string representation of a values dictionary // Note: this is a modified version of dict_repr() from dictobject.c in the // Python source code... auto mp = reinterpret_cast<PyDictObject *>(pValuesDict); Py_ssize_t i = Py_ReprEnter(reinterpret_cast<PyObject *>(mp)); PyObject *key = nullptr; PyObject *value = nullptr; bool first = true; if (i != 0) { return (i > 0)? PyUnicode_FromString("{...}"): nullptr; } if (mp->ma_used == 0) { Py_ReprLeave(reinterpret_cast<PyObject *>(mp)); return PyUnicode_FromString("{}"); } _PyUnicodeWriter writer; _PyUnicodeWriter_Init(&writer); writer.overallocate = 1; writer.min_length = 1+4+(2+4)*(mp->ma_used-1)+1; if (_PyUnicodeWriter_WriteChar(&writer, '{') < 0) { goto error; // NOLINT(cppcoreguidelines-avoid-goto, hicpp-avoid-goto) } while (PyDict_Next(reinterpret_cast<PyObject *>(mp), &i, &key, &value) != 0) { PyObject *s; int res; Py_INCREF(key); Py_INCREF(value); if (!first) { if (_PyUnicodeWriter_WriteASCIIString(&writer, ", ", 2) < 0) { goto error; // NOLINT(cppcoreguidelines-avoid-goto, hicpp-avoid-goto) } } first = false; s = PyObject_Repr(key); if (s == nullptr) { goto error; // NOLINT(cppcoreguidelines-avoid-goto, hicpp-avoid-goto) } res = _PyUnicodeWriter_WriteStr(&writer, s); Py_DECREF(s); if (res < 0) { goto error; // NOLINT(cppcoreguidelines-avoid-goto, hicpp-avoid-goto) } if (_PyUnicodeWriter_WriteASCIIString(&writer, ": ", 2) < 0) { goto error; // NOLINT(cppcoreguidelines-avoid-goto, hicpp-avoid-goto) } PythonQtInstanceWrapper *wrappedValue = PythonQtSupport::getInstanceWrapper(value); if (wrappedValue != nullptr) { auto dataStoreValue = static_cast<DataStoreValue *>(wrappedValue->_objPointerCopy); Py_CLEAR(value); value = PyFloat_FromDouble(dataStoreValue->value()); } s = PyObject_Repr(value); if (s == nullptr) { goto error; // NOLINT(cppcoreguidelines-avoid-goto, hicpp-avoid-goto) } res = _PyUnicodeWriter_WriteStr(&writer, s); Py_DECREF(s); if (res < 0) { goto error; // NOLINT(cppcoreguidelines-avoid-goto, hicpp-avoid-goto) } Py_CLEAR(key); Py_CLEAR(value); } writer.overallocate = 0; if (_PyUnicodeWriter_WriteChar(&writer, '}') < 0) { goto error; // NOLINT(cppcoreguidelines-avoid-goto, hicpp-avoid-goto) } Py_ReprLeave((PyObject *)mp); // NOLINT(cppcoreguidelines-pro-type-cstyle-cast, google-readability-casting) return _PyUnicodeWriter_Finish(&writer); error: Py_ReprLeave((PyObject *)mp); // NOLINT(cppcoreguidelines-pro-type-cstyle-cast, google-readability-casting) _PyUnicodeWriter_Dealloc(&writer); Py_XDECREF(key); Py_XDECREF(value); return nullptr; } #include "pythonend.h" //============================================================================== // Note: a DataStoreValuesDict is a dictionary sub-class for mapping between the // values of a DataStoreValues list and Python... static PyTypeObject DataStoreValuesDict_Type = { PyVarObject_HEAD_INIT(&PyType_Type, 0) "OpenCOR.DataStoreValuesDict", // tp_name sizeof(DataStoreValuesDictObject), // tp_basicsize 0, // tp_itemsize nullptr, // tp_dealloc nullptr, // tp_print nullptr, // tp_getattr nullptr, // tp_setattr nullptr, // tp_compare reinterpret_cast<reprfunc>(DataStoreValuesDict_repr), // tp_repr nullptr, // tp_as_number nullptr, // tp_as_sequence &DataStoreValuesDict_as_mapping, // tp_as_mapping nullptr, // tp_hash nullptr, // tp_call nullptr, // tp_str nullptr, // tp_getattro nullptr, // tp_setattro nullptr, // tp_as_buffer Py_TPFLAGS_DEFAULT|Py_TPFLAGS_BASETYPE, // tp_flags nullptr, // tp_doc nullptr, // tp_traverse nullptr, // tp_clear nullptr, // tp_richcompare 0, // tp_weaklistoffset nullptr, // tp_iter nullptr, // tp_iternext nullptr, // tp_methods nullptr, // tp_members nullptr, // tp_getset &PyDict_Type, // tp_base nullptr, // tp_dict nullptr, // tp_descr_get nullptr, // tp_descr_set 0, // tp_dictoffset nullptr, // tp_init nullptr, // tp_alloc nullptr, // tp_new nullptr, // tp_free nullptr, // tp_is_gc nullptr, // tp_bases nullptr, // tp_mro nullptr, // tp_cache nullptr, // tp_subclasses nullptr, // tp_weaklist nullptr, // tp_del 0, // tp_version_tag nullptr, // tp_finalize }; //============================================================================== DataStorePythonWrapper::DataStorePythonWrapper(void *pModule, QObject *pParent) : QObject(pParent) { Q_UNUSED(pModule) // Initialise NumPy if (OpenCOR_Python_Wrapper_PyArray_API == nullptr) { #ifdef QT_DEBUG bool res = #endif initNumPy(); #ifdef QT_DEBUG if (!res) { qFatal("FATAL ERROR | %s:%d: unable to initialise NumPy.", __FILE__, __LINE__); } #endif } PyType_Ready(&DataStoreValuesDict_Type); // Register some OpenCOR classes with Python and add some decorators to // ourselves PythonQtSupport::registerClass(&DataStore::staticMetaObject); PythonQtSupport::registerClass(&DataStoreValue::staticMetaObject); PythonQtSupport::registerClass(&DataStoreVariable::staticMetaObject); PythonQtSupport::addInstanceDecorators(this); } //============================================================================== PyObject * DataStorePythonWrapper::dataStoreValuesDict(const DataStoreValues *pDataStoreValues, SimulationSupport::SimulationDataUpdatedFunction *pSimulationDataUpdatedFunction) { // Create and return a Python dictionary for the given data store values and // keep track of the given simulation data updated function so that we can // let OpenCOR know when simulation data have been updated PyObject *res = PyDict_Type.tp_new(&DataStoreValuesDict_Type, nullptr, nullptr); res->ob_type = &DataStoreValuesDict_Type; reinterpret_cast<DataStoreValuesDictObject *>(res)->simulationDataUpdatedFunction = pSimulationDataUpdatedFunction; if (pDataStoreValues != nullptr) { for (int i = 0, iMax = pDataStoreValues->size(); i < iMax; ++i) { DataStoreValue *value = pDataStoreValues->at(i); PythonQtSupport::addObject(res, value->uri(), value); } } return res; } //============================================================================== PyObject * DataStorePythonWrapper::dataStoreVariablesDict(const DataStoreVariables &pDataStoreVariables) { // Create and return a Python dictionary for the given data store variables PyObject *res = PyDict_New(); for (auto dataStoreVariable : pDataStoreVariables) { PythonQtSupport::addObject(res, dataStoreVariable->uri(), dataStoreVariable); } return res; } //============================================================================== PyObject * DataStorePythonWrapper::variables(DataStore *pDataStore) { // Return the variables in the given data store as a Python dictionary return dataStoreVariablesDict(pDataStore->variables()); } //============================================================================== PyObject * DataStorePythonWrapper::voi_and_variables(DataStore *pDataStore) { // Return the VOI and variables in the given data store as a Python // dictionary return dataStoreVariablesDict(pDataStore->voiAndVariables()); } //============================================================================== double DataStorePythonWrapper::value(DataStoreVariable *pDataStoreVariable, quint64 pPosition, int pRun) const { // Return the value of the given data store variable at the given position // and for the given run if ( (pDataStoreVariable != nullptr) && (pDataStoreVariable->array() != nullptr)) { return pDataStoreVariable->value(pPosition, pRun); } throw std::runtime_error(tr("The 'NoneType' object is not subscriptable.").toStdString()); } //============================================================================== PyObject * DataStorePythonWrapper::values(DataStoreVariable *pDataStoreVariable, int pRun) const { // Create and return a NumPy array for the given data store variable and run DataStoreArray *dataStoreArray = pDataStoreVariable->array(pRun); if ((pDataStoreVariable != nullptr) && (dataStoreArray != nullptr)) { auto numPyArray = new NumPyPythonWrapper(dataStoreArray, pDataStoreVariable->size()); return numPyArray->numPyArray(); } #include "pythonbegin.h" Py_RETURN_NONE; #include "pythonend.h" } //============================================================================== NumPyPythonWrapper::NumPyPythonWrapper(DataStoreArray *pDataStoreArray, quint64 pSize) : mArray(pDataStoreArray) { // Tell our array that we are holding it mArray->hold(); // Initialise ourselves std::array<npy_intp, 1> dims = { npy_intp((pSize > 0)?pSize:pDataStoreArray->size()) }; #include "pythonbegin.h" mNumPyArray = PyArray_SimpleNewFromData(1, dims.data(), NPY_DOUBLE, static_cast<void *>(mArray->data())); // NOLINT(cppcoreguidelines-pro-type-cstyle-cast) PyArray_SetBaseObject(reinterpret_cast<PyArrayObject *>(mNumPyArray), // NOLINT(cppcoreguidelines-pro-type-cstyle-cast) PythonQtSupport::wrapQObject(this)); #include "pythonend.h" } //============================================================================== NumPyPythonWrapper::~NumPyPythonWrapper() { // Tell our array that we are releasing it mArray->release(); } //============================================================================== PyObject * NumPyPythonWrapper::numPyArray() const { // Return our NumPy array return mNumPyArray; } //============================================================================== } // namespace DataStore } // namespace OpenCOR //============================================================================== // End of file //==============================================================================
agarny/opencor
src/plugins/dataStore/DataStore/src/datastorepythonwrapper.cpp
C++
gpl-3.0
17,880
package ksp.kos.ideaplugin.reference; import com.intellij.psi.PsiFileFactory; import ksp.kos.ideaplugin.KerboScriptFile; import ksp.kos.ideaplugin.KerboScriptLanguage; import ksp.kos.ideaplugin.reference.context.FileContextResolver; import ksp.kos.ideaplugin.reference.context.FileDuality; import ksp.kos.ideaplugin.reference.context.PsiFileDuality; import org.jetbrains.annotations.NotNull; /** * Created on 08/10/16. * * @author ptasha */ public class PsiFileResolver implements FileContextResolver { private final KerboScriptFile anyFile; public PsiFileResolver(KerboScriptFile anyFile) { this.anyFile = anyFile; } @Override public @NotNull FileDuality ensureFile(String name) { KerboScriptFile file = anyFile.findFile(name); if (file == null) { file = (KerboScriptFile) PsiFileFactory.getInstance(anyFile.getProject()).createFileFromText( name + ".ks", KerboScriptLanguage.INSTANCE, "@lazyglobal off."); file = (KerboScriptFile) anyFile.getContainingDirectory().add(file); } return file; } @Override public FileDuality resolveFile(String name) { KerboScriptFile file = anyFile.resolveFile(name); if (file!=null) { return new PsiFileDuality(file); } return null; } }
valery-labuzhsky/EditorTools
IDEA/src/main/java/ksp/kos/ideaplugin/reference/PsiFileResolver.java
Java
gpl-3.0
1,343
# ***** BEGIN LICENSE BLOCK ***** # Version: MPL 1.1/GPL 2.0/LGPL 2.1 # # The contents of this file are subject to the Mozilla Public License Version # 1.1 (the "License"); you may not use this file except in compliance with # the License. You may obtain a copy of the License at # http://www.mozilla.org/MPL/ # # Software distributed under the License is distributed on an "AS IS" basis, # WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License # for the specific language governing rights and limitations under the # License. # # The Original Code is Bespin. # # The Initial Developer of the Original Code is # Mozilla. # Portions created by the Initial Developer are Copyright (C) 2009 # the Initial Developer. All Rights Reserved. # # Contributor(s): # # Alternatively, the contents of this file may be used under the terms of # either the GNU General Public License Version 2 or later (the "GPL"), or # the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), # in which case the provisions of the GPL or the LGPL are applicable instead # of those above. If you wish to allow use of your version of this file only # under the terms of either the GPL or the LGPL, and not to allow others to # use your version of this file under the terms of the MPL, indicate your # decision by deleting the provisions above and replace them with the notice # and other provisions required by the GPL or the LGPL. If you do not delete # the provisions above, a recipient may use your version of this file under # the terms of any one of the MPL, the GPL or the LGPL. # # ***** END LICENSE BLOCK ***** """ path.py - An object representing a path to a file or directory. Example: from path import path d = path('/home/guido/bin') for f in d.files('*.py'): f.chmod(0755) This module requires Python 2.5 or later. URL: http://www.jorendorff.com/articles/python/path Author: Jason Orendorff <jason.orendorff\x40gmail\x2ecom> (and others - see the url!) Date: 9 Mar 2007 Slightly modified to eliminate the deprecationwarning for the md5 module. """ # TODO # - Tree-walking functions don't avoid symlink loops. Matt Harrison # sent me a patch for this. # - Bug in write_text(). It doesn't support Universal newline mode. # - Better error message in listdir() when self isn't a # directory. (On Windows, the error message really sucks.) # - Make sure everything has a good docstring. # - Add methods for regex find and replace. # - guess_content_type() method? # - Perhaps support arguments to touch(). import sys, warnings, os, fnmatch, glob, shutil, codecs, hashlib __version__ = '2.2' __all__ = ['path'] # Platform-specific support for path.owner if os.name == 'nt': try: import win32security except ImportError: win32security = None else: try: import pwd except ImportError: pwd = None # Pre-2.3 support. Are unicode filenames supported? _base = str _getcwd = os.getcwd try: if os.path.supports_unicode_filenames: _base = unicode _getcwd = os.getcwdu except AttributeError: pass # Pre-2.3 workaround for booleans try: True, False except NameError: True, False = 1, 0 # Pre-2.3 workaround for basestring. try: basestring except NameError: basestring = (str, unicode) # Universal newline support _textmode = 'r' if hasattr(file, 'newlines'): _textmode = 'U' class TreeWalkWarning(Warning): pass class path(_base): """ Represents a filesystem path. For documentation on individual methods, consult their counterparts in os.path. """ # --- Special Python methods. def __repr__(self): return 'path(%s)' % _base.__repr__(self) # Adding a path and a string yields a path. def __add__(self, more): try: resultStr = _base.__add__(self, more) except TypeError: #Python bug resultStr = NotImplemented if resultStr is NotImplemented: return resultStr return self.__class__(resultStr) def __radd__(self, other): if isinstance(other, basestring): return self.__class__(other.__add__(self)) else: return NotImplemented # The / operator joins paths. def __div__(self, rel): """ fp.__div__(rel) == fp / rel == fp.joinpath(rel) Join two path components, adding a separator character if needed. """ return self.__class__(os.path.join(self, rel)) # Make the / operator work even when true division is enabled. __truediv__ = __div__ def getcwd(cls): """ Return the current working directory as a path object. """ return cls(_getcwd()) getcwd = classmethod(getcwd) # --- Operations on path strings. isabs = os.path.isabs def abspath(self): return self.__class__(os.path.abspath(self)) def normcase(self): return self.__class__(os.path.normcase(self)) def normpath(self): return self.__class__(os.path.normpath(self)) def realpath(self): return self.__class__(os.path.realpath(self)) def expanduser(self): return self.__class__(os.path.expanduser(self)) def expandvars(self): return self.__class__(os.path.expandvars(self)) def dirname(self): return self.__class__(os.path.dirname(self)) basename = os.path.basename def expand(self): """ Clean up a filename by calling expandvars(), expanduser(), and normpath() on it. This is commonly everything needed to clean up a filename read from a configuration file, for example. """ return self.expandvars().expanduser().normpath() def _get_namebase(self): base, ext = os.path.splitext(self.name) return base def _get_ext(self): f, ext = os.path.splitext(_base(self)) return ext def _get_drive(self): drive, r = os.path.splitdrive(self) return self.__class__(drive) parent = property( dirname, None, None, """ This path's parent directory, as a new path object. For example, path('/usr/local/lib/libpython.so').parent == path('/usr/local/lib') """) name = property( basename, None, None, """ The name of this file or directory without the full path. For example, path('/usr/local/lib/libpython.so').name == 'libpython.so' """) namebase = property( _get_namebase, None, None, """ The same as path.name, but with one file extension stripped off. For example, path('/home/guido/python.tar.gz').name == 'python.tar.gz', but path('/home/guido/python.tar.gz').namebase == 'python.tar' """) ext = property( _get_ext, None, None, """ The file extension, for example '.py'. """) drive = property( _get_drive, None, None, """ The drive specifier, for example 'C:'. This is always empty on systems that don't use drive specifiers. """) def splitpath(self): """ p.splitpath() -> Return (p.parent, p.name). """ parent, child = os.path.split(self) return self.__class__(parent), child def splitdrive(self): """ p.splitdrive() -> Return (p.drive, <the rest of p>). Split the drive specifier from this path. If there is no drive specifier, p.drive is empty, so the return value is simply (path(''), p). This is always the case on Unix. """ drive, rel = os.path.splitdrive(self) return self.__class__(drive), rel def splitext(self): """ p.splitext() -> Return (p.stripext(), p.ext). Split the filename extension from this path and return the two parts. Either part may be empty. The extension is everything from '.' to the end of the last path segment. This has the property that if (a, b) == p.splitext(), then a + b == p. """ filename, ext = os.path.splitext(self) return self.__class__(filename), ext def stripext(self): """ p.stripext() -> Remove one file extension from the path. For example, path('/home/guido/python.tar.gz').stripext() returns path('/home/guido/python.tar'). """ return self.splitext()[0] if hasattr(os.path, 'splitunc'): def splitunc(self): unc, rest = os.path.splitunc(self) return self.__class__(unc), rest def _get_uncshare(self): unc, r = os.path.splitunc(self) return self.__class__(unc) uncshare = property( _get_uncshare, None, None, """ The UNC mount point for this path. This is empty for paths on local drives. """) def joinpath(self, *args): """ Join two or more path components, adding a separator character (os.sep) if needed. Returns a new path object. """ return self.__class__(os.path.join(self, *args)) def splitall(self): r""" Return a list of the path components in this path. The first item in the list will be a path. Its value will be either os.curdir, os.pardir, empty, or the root directory of this path (for example, '/' or 'C:\\'). The other items in the list will be strings. path.path.joinpath(*result) will yield the original path. """ parts = [] loc = self while loc != os.curdir and loc != os.pardir: prev = loc loc, child = prev.splitpath() if loc == prev: break parts.append(child) parts.append(loc) parts.reverse() return parts def relpath(self): """ Return this path as a relative path, based from the current working directory. """ cwd = self.__class__(os.getcwd()) return cwd.relpathto(self) def relpathto(self, dest): """ Return a relative path from self to dest. If there is no relative path from self to dest, for example if they reside on different drives in Windows, then this returns dest.abspath(). """ origin = self.abspath() dest = self.__class__(dest).abspath() orig_list = origin.normcase().splitall() # Don't normcase dest! We want to preserve the case. dest_list = dest.splitall() if orig_list[0] != os.path.normcase(dest_list[0]): # Can't get here from there. return dest # Find the location where the two paths start to differ. i = 0 for start_seg, dest_seg in zip(orig_list, dest_list): if start_seg != os.path.normcase(dest_seg): break i += 1 # Now i is the point where the two paths diverge. # Need a certain number of "os.pardir"s to work up # from the origin to the point of divergence. segments = [os.pardir] * (len(orig_list) - i) # Need to add the diverging part of dest_list. segments += dest_list[i:] if len(segments) == 0: # If they happen to be identical, use os.curdir. relpath = os.curdir else: relpath = os.path.join(*segments) return self.__class__(relpath) # --- Listing, searching, walking, and matching def listdir(self, pattern=None): """ D.listdir() -> List of items in this directory. Use D.files() or D.dirs() instead if you want a listing of just files or just subdirectories. The elements of the list are path objects. With the optional 'pattern' argument, this only lists items whose names match the given pattern. """ names = os.listdir(self) if pattern is not None: names = fnmatch.filter(names, pattern) return [self / child for child in names] def dirs(self, pattern=None): """ D.dirs() -> List of this directory's subdirectories. The elements of the list are path objects. This does not walk recursively into subdirectories (but see path.walkdirs). With the optional 'pattern' argument, this only lists directories whose names match the given pattern. For example, d.dirs('build-*'). """ return [p for p in self.listdir(pattern) if p.isdir()] def files(self, pattern=None): """ D.files() -> List of the files in this directory. The elements of the list are path objects. This does not walk into subdirectories (see path.walkfiles). With the optional 'pattern' argument, this only lists files whose names match the given pattern. For example, d.files('*.pyc'). """ return [p for p in self.listdir(pattern) if p.isfile()] def walk(self, pattern=None, errors='strict'): """ D.walk() -> iterator over files and subdirs, recursively. The iterator yields path objects naming each child item of this directory and its descendants. This requires that D.isdir(). This performs a depth-first traversal of the directory tree. Each directory is returned just before all its children. The errors= keyword argument controls behavior when an error occurs. The default is 'strict', which causes an exception. The other allowed values are 'warn', which reports the error via warnings.warn(), and 'ignore'. """ if errors not in ('strict', 'warn', 'ignore'): raise ValueError("invalid errors parameter") try: childList = self.listdir() except Exception: if errors == 'ignore': return elif errors == 'warn': warnings.warn( "Unable to list directory '%s': %s" % (self, sys.exc_info()[1]), TreeWalkWarning) return else: raise for child in childList: if pattern is None or child.fnmatch(pattern): yield child try: isdir = child.isdir() except Exception: if errors == 'ignore': isdir = False elif errors == 'warn': warnings.warn( "Unable to access '%s': %s" % (child, sys.exc_info()[1]), TreeWalkWarning) isdir = False else: raise if isdir: for item in child.walk(pattern, errors): yield item def walkdirs(self, pattern=None, errors='strict'): """ D.walkdirs() -> iterator over subdirs, recursively. With the optional 'pattern' argument, this yields only directories whose names match the given pattern. For example, mydir.walkdirs('*test') yields only directories with names ending in 'test'. The errors= keyword argument controls behavior when an error occurs. The default is 'strict', which causes an exception. The other allowed values are 'warn', which reports the error via warnings.warn(), and 'ignore'. """ if errors not in ('strict', 'warn', 'ignore'): raise ValueError("invalid errors parameter") try: dirs = self.dirs() except Exception: if errors == 'ignore': return elif errors == 'warn': warnings.warn( "Unable to list directory '%s': %s" % (self, sys.exc_info()[1]), TreeWalkWarning) return else: raise for child in dirs: if pattern is None or child.fnmatch(pattern): yield child for subsubdir in child.walkdirs(pattern, errors): yield subsubdir def walkfiles(self, pattern=None, errors='strict'): """ D.walkfiles() -> iterator over files in D, recursively. The optional argument, pattern, limits the results to files with names that match the pattern. For example, mydir.walkfiles('*.tmp') yields only files with the .tmp extension. """ if errors not in ('strict', 'warn', 'ignore'): raise ValueError("invalid errors parameter") try: childList = self.listdir() except Exception: if errors == 'ignore': return elif errors == 'warn': warnings.warn( "Unable to list directory '%s': %s" % (self, sys.exc_info()[1]), TreeWalkWarning) return else: raise for child in childList: try: isfile = child.isfile() isdir = not isfile and child.isdir() except: if errors == 'ignore': continue elif errors == 'warn': warnings.warn( "Unable to access '%s': %s" % (self, sys.exc_info()[1]), TreeWalkWarning) continue else: raise if isfile: if pattern is None or child.fnmatch(pattern): yield child elif isdir: for f in child.walkfiles(pattern, errors): yield f def fnmatch(self, pattern): """ Return True if self.name matches the given pattern. pattern - A filename pattern with wildcards, for example '*.py'. """ return fnmatch.fnmatch(self.name, pattern) def glob(self, pattern): """ Return a list of path objects that match the pattern. pattern - a path relative to this directory, with wildcards. For example, path('/users').glob('*/bin/*') returns a list of all the files users have in their bin directories. """ cls = self.__class__ return [cls(s) for s in glob.glob(_base(self / pattern))] # --- Reading or writing an entire file at once. def open(self, mode='r'): """ Open this file. Return a file object. """ return file(self, mode) def bytes(self): """ Open this file, read all bytes, return them as a string. """ f = self.open('rb') try: return f.read() finally: f.close() def write_bytes(self, bytes, append=False): """ Open this file and write the given bytes to it. Default behavior is to overwrite any existing file. Call p.write_bytes(bytes, append=True) to append instead. """ if append: mode = 'ab' else: mode = 'wb' f = self.open(mode) try: f.write(bytes) finally: f.close() def text(self, encoding=None, errors='strict'): r""" Open this file, read it in, return the content as a string. This uses 'U' mode in Python 2.3 and later, so '\r\n' and '\r' are automatically translated to '\n'. Optional arguments: encoding - The Unicode encoding (or character set) of the file. If present, the content of the file is decoded and returned as a unicode object; otherwise it is returned as an 8-bit str. errors - How to handle Unicode errors; see help(str.decode) for the options. Default is 'strict'. """ if encoding is None: # 8-bit f = self.open(_textmode) try: return f.read() finally: f.close() else: # Unicode f = codecs.open(self, 'r', encoding, errors) # (Note - Can't use 'U' mode here, since codecs.open # doesn't support 'U' mode, even in Python 2.3.) try: t = f.read() finally: f.close() return (t.replace(u'\r\n', u'\n') .replace(u'\r\x85', u'\n') .replace(u'\r', u'\n') .replace(u'\x85', u'\n') .replace(u'\u2028', u'\n')) def write_text(self, text, encoding=None, errors='strict', linesep=os.linesep, append=False): r""" Write the given text to this file. The default behavior is to overwrite any existing file; to append instead, use the 'append=True' keyword argument. There are two differences between path.write_text() and path.write_bytes(): newline handling and Unicode handling. See below. Parameters: - text - str/unicode - The text to be written. - encoding - str - The Unicode encoding that will be used. This is ignored if 'text' isn't a Unicode string. - errors - str - How to handle Unicode encoding errors. Default is 'strict'. See help(unicode.encode) for the options. This is ignored if 'text' isn't a Unicode string. - linesep - keyword argument - str/unicode - The sequence of characters to be used to mark end-of-line. The default is os.linesep. You can also specify None; this means to leave all newlines as they are in 'text'. - append - keyword argument - bool - Specifies what to do if the file already exists (True: append to the end of it; False: overwrite it.) The default is False. --- Newline handling. write_text() converts all standard end-of-line sequences ('\n', '\r', and '\r\n') to your platform's default end-of-line sequence (see os.linesep; on Windows, for example, the end-of-line marker is '\r\n'). If you don't like your platform's default, you can override it using the 'linesep=' keyword argument. If you specifically want write_text() to preserve the newlines as-is, use 'linesep=None'. This applies to Unicode text the same as to 8-bit text, except there are three additional standard Unicode end-of-line sequences: u'\x85', u'\r\x85', and u'\u2028'. (This is slightly different from when you open a file for writing with fopen(filename, "w") in C or file(filename, 'w') in Python.) --- Unicode If 'text' isn't Unicode, then apart from newline handling, the bytes are written verbatim to the file. The 'encoding' and 'errors' arguments are not used and must be omitted. If 'text' is Unicode, it is first converted to bytes using the specified 'encoding' (or the default encoding if 'encoding' isn't specified). The 'errors' argument applies only to this conversion. """ if isinstance(text, unicode): if linesep is not None: # Convert all standard end-of-line sequences to # ordinary newline characters. text = (text.replace(u'\r\n', u'\n') .replace(u'\r\x85', u'\n') .replace(u'\r', u'\n') .replace(u'\x85', u'\n') .replace(u'\u2028', u'\n')) text = text.replace(u'\n', linesep) if encoding is None: encoding = sys.getdefaultencoding() bytes = text.encode(encoding, errors) else: # It is an error to specify an encoding if 'text' is # an 8-bit string. assert encoding is None if linesep is not None: text = (text.replace('\r\n', '\n') .replace('\r', '\n')) bytes = text.replace('\n', linesep) self.write_bytes(bytes, append) def lines(self, encoding=None, errors='strict', retain=True): r""" Open this file, read all lines, return them in a list. Optional arguments: encoding - The Unicode encoding (or character set) of the file. The default is None, meaning the content of the file is read as 8-bit characters and returned as a list of (non-Unicode) str objects. errors - How to handle Unicode errors; see help(str.decode) for the options. Default is 'strict' retain - If true, retain newline characters; but all newline character combinations ('\r', '\n', '\r\n') are translated to '\n'. If false, newline characters are stripped off. Default is True. This uses 'U' mode in Python 2.3 and later. """ if encoding is None and retain: f = self.open(_textmode) try: return f.readlines() finally: f.close() else: return self.text(encoding, errors).splitlines(retain) def write_lines(self, lines, encoding=None, errors='strict', linesep=os.linesep, append=False): r""" Write the given lines of text to this file. By default this overwrites any existing file at this path. This puts a platform-specific newline sequence on every line. See 'linesep' below. lines - A list of strings. encoding - A Unicode encoding to use. This applies only if 'lines' contains any Unicode strings. errors - How to handle errors in Unicode encoding. This also applies only to Unicode strings. linesep - The desired line-ending. This line-ending is applied to every line. If a line already has any standard line ending ('\r', '\n', '\r\n', u'\x85', u'\r\x85', u'\u2028'), that will be stripped off and this will be used instead. The default is os.linesep, which is platform-dependent ('\r\n' on Windows, '\n' on Unix, etc.) Specify None to write the lines as-is, like file.writelines(). Use the keyword argument append=True to append lines to the file. The default is to overwrite the file. Warning: When you use this with Unicode data, if the encoding of the existing data in the file is different from the encoding you specify with the encoding= parameter, the result is mixed-encoding data, which can really confuse someone trying to read the file later. """ if append: mode = 'ab' else: mode = 'wb' f = self.open(mode) try: for line in lines: isUnicode = isinstance(line, unicode) if linesep is not None: # Strip off any existing line-end and add the # specified linesep string. if isUnicode: if line[-2:] in (u'\r\n', u'\x0d\x85'): line = line[:-2] elif line[-1:] in (u'\r', u'\n', u'\x85', u'\u2028'): line = line[:-1] else: if line[-2:] == '\r\n': line = line[:-2] elif line[-1:] in ('\r', '\n'): line = line[:-1] line += linesep if isUnicode: if encoding is None: encoding = sys.getdefaultencoding() line = line.encode(encoding, errors) f.write(line) finally: f.close() def read_md5(self): """ Calculate the md5 hash for this file. This reads through the entire file. """ f = self.open('rb') try: m = hashlib.new("md5") while True: d = f.read(8192) if not d: break m.update(d) finally: f.close() return m.digest() # --- Methods for querying the filesystem. exists = os.path.exists isdir = os.path.isdir isfile = os.path.isfile islink = os.path.islink ismount = os.path.ismount if hasattr(os.path, 'samefile'): samefile = os.path.samefile getatime = os.path.getatime atime = property( getatime, None, None, """ Last access time of the file. """) getmtime = os.path.getmtime mtime = property( getmtime, None, None, """ Last-modified time of the file. """) if hasattr(os.path, 'getctime'): getctime = os.path.getctime ctime = property( getctime, None, None, """ Creation time of the file. """) getsize = os.path.getsize size = property( getsize, None, None, """ Size of the file, in bytes. """) if hasattr(os, 'access'): def access(self, mode): """ Return true if current user has access to this path. mode - One of the constants os.F_OK, os.R_OK, os.W_OK, os.X_OK """ return os.access(self, mode) def stat(self): """ Perform a stat() system call on this path. """ return os.stat(self) def lstat(self): """ Like path.stat(), but do not follow symbolic links. """ return os.lstat(self) def get_owner(self): r""" Return the name of the owner of this file or directory. This follows symbolic links. On Windows, this returns a name of the form ur'DOMAIN\User Name'. On Windows, a group can own a file or directory. """ if os.name == 'nt': if win32security is None: raise Exception("path.owner requires win32all to be installed") desc = win32security.GetFileSecurity( self, win32security.OWNER_SECURITY_INFORMATION) sid = desc.GetSecurityDescriptorOwner() account, domain, typecode = win32security.LookupAccountSid(None, sid) return domain + u'\\' + account else: if pwd is None: raise NotImplementedError("path.owner is not implemented on this platform.") st = self.stat() return pwd.getpwuid(st.st_uid).pw_name owner = property( get_owner, None, None, """ Name of the owner of this file or directory. """) if hasattr(os, 'statvfs'): def statvfs(self): """ Perform a statvfs() system call on this path. """ return os.statvfs(self) if hasattr(os, 'pathconf'): def pathconf(self, name): return os.pathconf(self, name) # --- Modifying operations on files and directories def utime(self, times): """ Set the access and modified times of this file. """ os.utime(self, times) def chmod(self, mode): os.chmod(self, mode) if hasattr(os, 'chown'): def chown(self, uid, gid): os.chown(self, uid, gid) def rename(self, new): os.rename(self, new) def renames(self, new): os.renames(self, new) # --- Create/delete operations on directories def mkdir(self, mode=0777): os.mkdir(self, mode) def makedirs(self, mode=0777): os.makedirs(self, mode) def rmdir(self): os.rmdir(self) def removedirs(self): os.removedirs(self) # --- Modifying operations on files def touch(self): """ Set the access/modified times of this file to the current time. Create the file if it does not exist. """ fd = os.open(self, os.O_WRONLY | os.O_CREAT, 0666) os.close(fd) os.utime(self, None) def remove(self): os.remove(self) def unlink(self): os.unlink(self) # --- Links if hasattr(os, 'link'): def link(self, newpath): """ Create a hard link at 'newpath', pointing to this file. """ os.link(self, newpath) if hasattr(os, 'symlink'): def symlink(self, newlink): """ Create a symbolic link at 'newlink', pointing here. """ os.symlink(self, newlink) if hasattr(os, 'readlink'): def readlink(self): """ Return the path to which this symbolic link points. The result may be an absolute or a relative path. """ return self.__class__(os.readlink(self)) def readlinkabs(self): """ Return the path to which this symbolic link points. The result is always an absolute path. """ p = self.readlink() if p.isabs(): return p else: return (self.parent / p).abspath() # --- High-level functions from shutil copyfile = shutil.copyfile copymode = shutil.copymode copystat = shutil.copystat copy = shutil.copy copy2 = shutil.copy2 copytree = shutil.copytree if hasattr(shutil, 'move'): move = shutil.move rmtree = shutil.rmtree # --- Special stuff from os if hasattr(os, 'chroot'): def chroot(self): os.chroot(self) if hasattr(os, 'startfile'): def startfile(self): os.startfile(self)
samn/spectral-workbench
webserver/public/lib/bespin-0.9a2/lib/dryice/path.py
Python
gpl-3.0
33,721
/*************************************************************************** * * * 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. * * * ***************************************************************************/ //function for use fsusage #ifdef WIN32 #include <io.h> #include <dcpp/stdinc.h> #include <dcpp/Text.h> #else //WIN32 extern "C" { #include "fsusage.h" } #endif //WIN32 #include "freespace.h" bool FreeSpace::FreeDiscSpace ( std::string path, unsigned long long * res, unsigned long long * res2) { if ( !res ) { return false; } #ifdef WIN32 ULARGE_INTEGER lpFreeBytesAvailableToCaller; // receives the number of bytes on // disk available to the caller ULARGE_INTEGER lpTotalNumberOfBytes; // receives the number of bytes on disk ULARGE_INTEGER lpTotalNumberOfFreeBytes; // receives the free bytes on disk if ( GetDiskFreeSpaceExW( (const WCHAR*)dcpp::Text::utf8ToWide(path).c_str(), &lpFreeBytesAvailableToCaller, &lpTotalNumberOfBytes, &lpTotalNumberOfFreeBytes ) == true ) { *res = lpTotalNumberOfFreeBytes.QuadPart; *res2 = lpTotalNumberOfBytes.QuadPart; return true; } else { return false; } #else //WIN32 struct fs_usage fsp; if ( get_fs_usage(path.c_str(),path.c_str(),&fsp) == 0 ) { *res = fsp.fsu_bavail*fsp.fsu_blocksize; *res2 =fsp.fsu_blocks*fsp.fsu_blocksize; return true; } else { return false; } #endif //WIN32 }
skylitedcpp/skylitedcpp
extra/freespace.cpp
C++
gpl-3.0
2,112
/*---------------------------------------------------------------------------*\ ========= | \\ / F ield | OpenFOAM: The Open Source CFD Toolbox \\ / O peration | \\ / A nd | Copyright (C) 1991-2010 OpenCFD Ltd. \\/ 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/>. Class Foam::OFstream Description Output to file stream. SourceFiles OFstream.C \*---------------------------------------------------------------------------*/ #ifndef OFstream_H #define OFstream_H #include "OSstream.H" #include "fileName.H" #include "className.H" #include <fstream> using std::ofstream; // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * // namespace Foam { class OFstream; /*---------------------------------------------------------------------------*\ Class OFstreamAllocator Declaration \*---------------------------------------------------------------------------*/ //- A std::ostream with ability to handle compressed files class OFstreamAllocator { friend class OFstream; ostream* ofPtr_; // Constructors //- Construct from pathname OFstreamAllocator ( const fileName& pathname, IOstream::compressionType compression=IOstream::UNCOMPRESSED ); // Destructor ~OFstreamAllocator(); public: // Member functions //- Access to underlying std::ostream ostream& stdStream(); }; /*---------------------------------------------------------------------------*\ Class OFstream Declaration \*---------------------------------------------------------------------------*/ class OFstream : private OFstreamAllocator, public OSstream { // Private data fileName pathname_; public: // Declare name of the class and its debug switch ClassName("OFstream"); // Constructors //- Construct from pathname OFstream ( const fileName& pathname, streamFormat format=ASCII, versionNumber version=currentVersion, compressionType compression=UNCOMPRESSED ); // Destructor ~OFstream(); // Member functions // Access //- Return the name of the stream const fileName& name() const { return pathname_; } //- Return non-const access to the name of the stream fileName& name() { return pathname_; } // Print //- Print description of IOstream to Ostream void print(Ostream&) const; }; // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * // // Global predefined null output stream extern OFstream Snull; // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * // } // End namespace Foam // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * // #endif // ************************************************************************* //
OpenCFD/OpenFOAM-1.7.x
src/OpenFOAM/db/IOstreams/Fstreams/OFstream.H
C++
gpl-3.0
3,886
package org.demoiselle.artigoJM.persistence; import br.gov.frameworkdemoiselle.stereotype.PersistenceController; import br.gov.frameworkdemoiselle.template.JPACrud; import org.demoiselle.artigoJM.domain.Bookmark; @PersistenceController public class BookmarkDAO extends JPACrud<Bookmark, Long> { private static final long serialVersionUID = 1L; }
luiz158/ExemplosDemoiselle
artigoJM/src/main/java/org/demoiselle/artigoJM/persistence/BookmarkDAO.java
Java
gpl-3.0
354
# -*- coding: utf-8 -*- class Charset(object): common_name = 'NotoSansHebrew-Regular' native_name = '' def glyphs(self): chars = [] chars.append(0x0000) #null ???? chars.append(0x200C) #uni200C ZERO WIDTH NON-JOINER chars.append(0x000D) #nonmarkingreturn ???? chars.append(0x200E) #uni200E LEFT-TO-RIGHT MARK chars.append(0x200F) #uni200F RIGHT-TO-LEFT MARK chars.append(0x0020) #space SPACE chars.append(0x200D) #uni200D ZERO WIDTH JOINER chars.append(0x00A0) #space NO-BREAK SPACE chars.append(0x20AA) #sheqel NEW SHEQEL SIGN chars.append(0xFEFF) #null ZERO WIDTH NO-BREAK SPACE chars.append(0xFB1D) #uniFB1D HEBREW LETTER YOD WITH HIRIQ chars.append(0xFB1E) #uniFB1E HEBREW POINT JUDEO-SPANISH VARIKA chars.append(0xFB1F) #yodyod_patah HEBREW LIGATURE YIDDISH YOD YOD PATAH chars.append(0xFB20) #alternativeayin HEBREW LETTER ALTERNATIVE AYIN chars.append(0xFB21) #alefwide HEBREW LETTER WIDE ALEF chars.append(0xFB22) #daletwide HEBREW LETTER WIDE DALET chars.append(0xFB23) #hewide HEBREW LETTER WIDE HE chars.append(0xFB24) #kafwide HEBREW LETTER WIDE KAF chars.append(0xFB25) #lamedwide HEBREW LETTER WIDE LAMED chars.append(0xFB26) #finalmemwide HEBREW LETTER WIDE FINAL MEM chars.append(0xFB27) #reshwide HEBREW LETTER WIDE RESH chars.append(0xFB28) #tavwide HEBREW LETTER WIDE TAV chars.append(0xFB29) #alt_plussign HEBREW LETTER ALTERNATIVE PLUS SIGN chars.append(0xFB2A) #shinshindot HEBREW LETTER SHIN WITH SHIN DOT chars.append(0xFB2B) #shinsindot HEBREW LETTER SHIN WITH SIN DOT chars.append(0xFB2C) #shindageshshindot HEBREW LETTER SHIN WITH DAGESH AND SHIN DOT chars.append(0xFB2D) #shindageshsindot HEBREW LETTER SHIN WITH DAGESH AND SIN DOT chars.append(0xFB2E) #alefpatah HEBREW LETTER ALEF WITH PATAH chars.append(0xFB2F) #alefqamats HEBREW LETTER ALEF WITH QAMATS chars.append(0xFB30) #alefmapiq HEBREW LETTER ALEF WITH MAPIQ chars.append(0xFB31) #betdagesh HEBREW LETTER BET WITH DAGESH chars.append(0xFB32) #gimeldagesh HEBREW LETTER GIMEL WITH DAGESH chars.append(0xFB33) #daletdagesh HEBREW LETTER DALET WITH DAGESH chars.append(0xFB34) #hedagesh HEBREW LETTER HE WITH MAPIQ chars.append(0xFB35) #vavdagesh HEBREW LETTER VAV WITH DAGESH chars.append(0xFB36) #zayindagesh HEBREW LETTER ZAYIN WITH DAGESH chars.append(0xFB38) #tetdagesh HEBREW LETTER TET WITH DAGESH chars.append(0xFB39) #yoddagesh HEBREW LETTER YOD WITH DAGESH chars.append(0xFB3A) #finalkafdagesh HEBREW LETTER FINAL KAF WITH DAGESH chars.append(0xFB3B) #kafdagesh HEBREW LETTER KAF WITH DAGESH chars.append(0xFB3C) #lameddagesh HEBREW LETTER LAMED WITH DAGESH chars.append(0xFB3E) #memdagesh HEBREW LETTER MEM WITH DAGESH chars.append(0xFB40) #nundagesh HEBREW LETTER NUN WITH DAGESH chars.append(0xFB41) #samekhdagesh HEBREW LETTER SAMEKH WITH DAGESH chars.append(0xFB43) #finalpedagesh HEBREW LETTER FINAL PE WITH DAGESH chars.append(0xFB44) #pedagesh HEBREW LETTER PE WITH DAGESH chars.append(0xFB46) #tsadidagesh HEBREW LETTER TSADI WITH DAGESH chars.append(0xFB47) #qofdagesh HEBREW LETTER QOF WITH DAGESH chars.append(0xFB48) #reshdagesh HEBREW LETTER RESH WITH DAGESH chars.append(0xFB49) #shindagesh HEBREW LETTER SHIN WITH DAGESH chars.append(0xFB4A) #tavdagesh HEBREW LETTER TAV WITH DAGESH chars.append(0xFB4B) #vavholam HEBREW LETTER VAV WITH HOLAM chars.append(0xFB4C) #betrafe HEBREW LETTER BET WITH RAFE chars.append(0xFB4D) #kafrafe HEBREW LETTER KAF WITH RAFE chars.append(0xFB4E) #perafe HEBREW LETTER PE WITH RAFE chars.append(0xFB4F) #aleflamed HEBREW LIGATURE ALEF LAMED chars.append(0x0591) #uni0591 HEBREW ACCENT ETNAHTA chars.append(0x0592) #uni0592 HEBREW ACCENT SEGOL chars.append(0x0593) #uni0593 HEBREW ACCENT SHALSHELET chars.append(0x0594) #uni0594 HEBREW ACCENT ZAQEF QATAN chars.append(0x0595) #uni0595 HEBREW ACCENT ZAQEF GADOL chars.append(0x0596) #uni0596 HEBREW ACCENT TIPEHA chars.append(0x0597) #uni0597 HEBREW ACCENT REVIA chars.append(0x0598) #uni0598 HEBREW ACCENT ZARQA chars.append(0x0599) #uni0599 HEBREW ACCENT PASHTA chars.append(0x059A) #uni059A HEBREW ACCENT YETIV chars.append(0x059B) #uni059B HEBREW ACCENT TEVIR chars.append(0x059C) #uni059C HEBREW ACCENT GERESH chars.append(0x059D) #uni059D HEBREW ACCENT GERESH MUQDAM chars.append(0x059E) #uni059E HEBREW ACCENT GERSHAYIM chars.append(0x059F) #uni059F HEBREW ACCENT QARNEY PARA chars.append(0x05A0) #uni05A0 HEBREW ACCENT TELISHA GEDOLA chars.append(0x05A1) #uni05A1 HEBREW ACCENT PAZER chars.append(0x05A2) #uni05A2 HEBREW ACCENT ATNAH HAFUKH chars.append(0x05A3) #uni05A3 HEBREW ACCENT MUNAH chars.append(0x05A4) #uni05A4 HEBREW ACCENT MAHAPAKH chars.append(0x05A5) #uni05A5 HEBREW ACCENT MERKHA chars.append(0x05A6) #uni05A6 HEBREW ACCENT MERKHA KEFULA chars.append(0x05A7) #uni05A7 HEBREW ACCENT DARGA chars.append(0x05A8) #uni05A8 HEBREW ACCENT QADMA chars.append(0x05A9) #uni05A9 HEBREW ACCENT TELISHA QETANA chars.append(0x05AA) #uni05AA HEBREW ACCENT YERAH BEN YOMO chars.append(0x05AB) #uni05AB HEBREW ACCENT OLE chars.append(0x05AC) #uni05AC HEBREW ACCENT ILUY chars.append(0x05AD) #uni05AD HEBREW ACCENT DEHI chars.append(0x05AE) #uni05AE HEBREW ACCENT ZINOR chars.append(0x05AF) #uni05AF HEBREW MARK MASORA CIRCLE chars.append(0x05B0) #sheva HEBREW POINT SHEVA chars.append(0x05B1) #hatafsegol HEBREW POINT HATAF SEGOL chars.append(0x05B2) #hatafpatah HEBREW POINT HATAF PATAH chars.append(0x05B3) #hatafqamats HEBREW POINT HATAF QAMATS chars.append(0x05B4) #hiriq HEBREW POINT HIRIQ chars.append(0x05B5) #tsere HEBREW POINT TSERE chars.append(0x05B6) #segol HEBREW POINT SEGOL chars.append(0x05B7) #patah HEBREW POINT PATAH chars.append(0x05B8) #qamats HEBREW POINT QAMATS chars.append(0x05B9) #holam HEBREW POINT HOLAM chars.append(0x05BA) #uni05BA HEBREW POINT HOLAM HASER FOR VAV chars.append(0x05BB) #qubuts HEBREW POINT QUBUTS chars.append(0x05BC) #dagesh HEBREW POINT DAGESH OR MAPIQ chars.append(0x05BD) #meteg HEBREW POINT METEG chars.append(0x05BE) #maqaf HEBREW PUNCTUATION MAQAF chars.append(0x05BF) #rafe HEBREW POINT RAFE chars.append(0x05C0) #paseq HEBREW PUNCTUATION PASEQ chars.append(0x05C1) #shindot HEBREW POINT SHIN DOT chars.append(0x05C2) #sindot HEBREW POINT SIN DOT chars.append(0x05C3) #sofpasuq HEBREW PUNCTUATION SOF PASUQ chars.append(0x05C4) #upper_dot HEBREW MARK UPPER DOT chars.append(0x05C5) #lowerdot HEBREW MARK LOWER DOT chars.append(0x05C6) #uni05C6 HEBREW PUNCTUATION NUN HAFUKHA chars.append(0x05C7) #qamatsqatan HEBREW POINT QAMATS QATAN chars.append(0x25CC) #uni25CC DOTTED CIRCLE chars.append(0x05D0) #alef HEBREW LETTER ALEF chars.append(0x05D1) #bet HEBREW LETTER BET chars.append(0x05D2) #gimel HEBREW LETTER GIMEL chars.append(0x05D3) #dalet HEBREW LETTER DALET chars.append(0x05D4) #he HEBREW LETTER HE chars.append(0x05D5) #vav HEBREW LETTER VAV chars.append(0x05D6) #zayin HEBREW LETTER ZAYIN chars.append(0x05D7) #het HEBREW LETTER HET chars.append(0x05D8) #tet HEBREW LETTER TET chars.append(0x05D9) #yod HEBREW LETTER YOD chars.append(0x05DA) #finalkaf HEBREW LETTER FINAL KAF chars.append(0x05DB) #kaf HEBREW LETTER KAF chars.append(0x05DC) #lamed HEBREW LETTER LAMED chars.append(0x05DD) #finalmem HEBREW LETTER FINAL MEM chars.append(0x05DE) #mem HEBREW LETTER MEM chars.append(0x05DF) #finalnun HEBREW LETTER FINAL NUN chars.append(0x05E0) #nun HEBREW LETTER NUN chars.append(0x05E1) #samekh HEBREW LETTER SAMEKH chars.append(0x05E2) #ayin HEBREW LETTER AYIN chars.append(0x05E3) #finalpe HEBREW LETTER FINAL PE chars.append(0x05E4) #pe HEBREW LETTER PE chars.append(0x05E5) #finaltsadi HEBREW LETTER FINAL TSADI chars.append(0x05E6) #tsadi HEBREW LETTER TSADI chars.append(0x05E7) #qof HEBREW LETTER QOF chars.append(0x05E8) #resh HEBREW LETTER RESH chars.append(0x05E9) #shin HEBREW LETTER SHIN chars.append(0x05EA) #tav HEBREW LETTER TAV chars.append(0x05F0) #vavvav HEBREW LIGATURE YIDDISH DOUBLE VAV chars.append(0x05F1) #vavyod HEBREW LIGATURE YIDDISH VAV YOD chars.append(0x05F2) #yodyod HEBREW LIGATURE YIDDISH DOUBLE YOD chars.append(0x05F3) #geresh HEBREW PUNCTUATION GERESH chars.append(0x05F4) #gershayim HEBREW PUNCTUATION GERSHAYIM return chars
davelab6/pyfontaine
fontaine/charsets/noto_chars/notosanshebrew_regular.py
Python
gpl-3.0
9,355
/* * ============================================================================ * GNU General Public License * ============================================================================ * * Copyright (C) 2006-2011 Serotonin Software Technologies Inc. http://serotoninsoftware.com * @author Matthew Lohbihler * * 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/>. * * When signing a commercial license with Serotonin Software Technologies Inc., * the following extension to GPL is made. A special exception to the GPL is * included to allow you to distribute a combined work that includes BAcnet4J * without being obliged to provide the source code for any proprietary components. */ package com.serotonin.bacnet4j.type.notificationParameters; import com.serotonin.bacnet4j.exception.BACnetException; import com.serotonin.bacnet4j.type.AmbiguousValue; import com.serotonin.bacnet4j.type.Encodable; import com.serotonin.bacnet4j.type.constructed.StatusFlags; import org.free.bacnet4j.util.ByteQueue; public class CommandFailure extends NotificationParameters { private static final long serialVersionUID = 5727410398456093753L; public static final byte TYPE_ID = 3; private final Encodable commandValue; private final StatusFlags statusFlags; private final Encodable feedbackValue; public CommandFailure(Encodable commandValue, StatusFlags statusFlags, Encodable feedbackValue) { this.commandValue = commandValue; this.statusFlags = statusFlags; this.feedbackValue = feedbackValue; } @Override protected void writeImpl(ByteQueue queue) { writeEncodable(queue, commandValue, 0); write(queue, statusFlags, 1); writeEncodable(queue, feedbackValue, 2); } public CommandFailure(ByteQueue queue) throws BACnetException { commandValue = new AmbiguousValue(queue, 0); statusFlags = read(queue, StatusFlags.class, 1); feedbackValue = new AmbiguousValue(queue, 2); } @Override protected int getTypeId() { return TYPE_ID; } public Encodable getCommandValue() { return commandValue; } public StatusFlags getStatusFlags() { return statusFlags; } public Encodable getFeedbackValue() { return feedbackValue; } @Override public int hashCode() { final int PRIME = 31; int result = 1; result = PRIME * result + ((commandValue == null) ? 0 : commandValue.hashCode()); result = PRIME * result + ((feedbackValue == null) ? 0 : feedbackValue.hashCode()); result = PRIME * result + ((statusFlags == null) ? 0 : statusFlags.hashCode()); return result; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; final CommandFailure other = (CommandFailure) obj; if (commandValue == null) { if (other.commandValue != null) return false; } else if (!commandValue.equals(other.commandValue)) return false; if (feedbackValue == null) { if (other.feedbackValue != null) return false; } else if (!feedbackValue.equals(other.feedbackValue)) return false; if (statusFlags == null) { if (other.statusFlags != null) return false; } else if (!statusFlags.equals(other.statusFlags)) return false; return true; } }
empeeoh/BACnet4J
src/com/serotonin/bacnet4j/type/notificationParameters/CommandFailure.java
Java
gpl-3.0
4,226
<?php /** * Copyright © 2016 Magento. All rights reserved. * See COPYING.txt for license details. */ // @codingStandardsIgnoreFile namespace Magento\Widget\Model\ResourceModel\Layout; /** * Layout update resource model */ class Update extends \Magento\Framework\Model\ResourceModel\Db\AbstractDb { /** * @var \Magento\Framework\Cache\FrontendInterface */ private $_cache; /** * @var array */ private $layoutUpdateCache; /** * @param \Magento\Framework\Model\ResourceModel\Db\Context $context * @param \Magento\Framework\Cache\FrontendInterface $cache * @param string $connectionName */ public function __construct( \Magento\Framework\Model\ResourceModel\Db\Context $context, \Magento\Framework\Cache\FrontendInterface $cache, $connectionName = null ) { parent::__construct($context, $connectionName); $this->_cache = $cache; } /** * Define main table * * @return void */ protected function _construct() { $this->_init('layout_update', 'layout_update_id'); } /** * Retrieve layout updates by handle * * @param string $handle * @param \Magento\Framework\View\Design\ThemeInterface $theme * @param \Magento\Framework\App\ScopeInterface $store * @return string */ public function fetchUpdatesByHandle( $handle, \Magento\Framework\View\Design\ThemeInterface $theme, \Magento\Framework\App\ScopeInterface $store ) { $bind = ['theme_id' => $theme->getId(), 'store_id' => $store->getId()]; $cacheKey = implode('-', $bind); if (!isset($this->layoutUpdateCache[$cacheKey])) { $this->layoutUpdateCache[$cacheKey] = []; foreach ($this->getConnection()->fetchAll($this->_getFetchUpdatesByHandleSelect(), $bind) as $layout) { if (!isset($this->layoutUpdateCache[$cacheKey][$layout['handle']])) { $this->layoutUpdateCache[$cacheKey][$layout['handle']] = ''; } $this->layoutUpdateCache[$cacheKey][$layout['handle']] .= $layout['xml']; } } return isset($this->layoutUpdateCache[$cacheKey][$handle]) ? $this->layoutUpdateCache[$cacheKey][$handle] : ''; } /** * Get select to fetch updates by handle * * @param bool $loadAllUpdates * @return \Magento\Framework\DB\Select */ protected function _getFetchUpdatesByHandleSelect($loadAllUpdates = false) { //@todo Why it also loads layout updates for store_id=0, isn't it Admin Store View? //If 0 means 'all stores' why it then refers by foreign key to Admin in `store` and not to something named // 'All Stores'? $select = $this->getConnection()->select()->from( ['layout_update' => $this->getMainTable()], ['xml', 'handle'] )->join( ['link' => $this->getTable('layout_link')], 'link.layout_update_id=layout_update.layout_update_id', '' )->where( 'link.store_id IN (0, :store_id)' )->where( 'link.theme_id = :theme_id' )->order( 'layout_update.sort_order ' . \Magento\Framework\DB\Select::SQL_ASC ); if (!$loadAllUpdates) { $select->where('link.is_temporary = 0'); } return $select; } /** * Update a "layout update link" if relevant data is provided * * @param \Magento\Widget\Model\Layout\Update|\Magento\Framework\Model\AbstractModel $object * @return $this */ protected function _afterSave(\Magento\Framework\Model\AbstractModel $object) { $data = $object->getData(); if (isset($data['store_id']) && isset($data['theme_id'])) { $this->getConnection()->insertOnDuplicate( $this->getTable('layout_link'), [ 'store_id' => $data['store_id'], 'theme_id' => $data['theme_id'], 'layout_update_id' => $object->getId(), 'is_temporary' => (int)$object->getIsTemporary() ] ); } $this->_cache->clean(); return parent::_afterSave($object); } }
rajmahesh/magento2-master
vendor/magento/module-widget/Model/ResourceModel/Layout/Update.php
PHP
gpl-3.0
4,332
<?php use Illuminate\Database\Schema\Blueprint; use Illuminate\Database\Migrations\Migration; class CreateCategoryTable extends Migration { /** * Run the migrations. * * @return void */ public function up() { Schema::create('category', function($table) { $table->increments('id', 11); $table->INTEGER('pid')->unsigned()->default(0); $table->INTEGER('tid')->unsigned()->default(1); $table->string('title', 64); $table->string('description', 256)->nullable(); $table->INTEGER('weight')->unsigned()->default(0); }); //添加数据 DB::table('category')->insert(array( 'id' => '1', 'pid' => '0', 'tid' => '1', 'title' => '未分类', 'description' => '未分类栏目,所有未分类的文章都放在这里', 'weight' => '0', )); } /** * Reverse the migrations. * * @return void */ public function down() { Schema::drop('category'); } }
y80x86ol/simpla-cms
v1.0/database/migrations/2014_10_18_120757_create_category_table.php
PHP
gpl-3.0
1,097
// -*- coding: utf-8 -*- // Copyright (C) 2016 Laboratoire de Recherche et Developpement de // l'Epita (LRDE). // // This file is part of Spot, a model checking library. // // Spot 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. // // Spot 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/>. #undef NDEBUG #include <spot/misc/trival.hh> #include <cassert> int main() { spot::trival v1; spot::trival v2(false); spot::trival v3(true); spot::trival v4 = spot::trival::maybe(); assert(v1 != v2); assert(v1 != v3); assert(v2 != v3); assert(v4 != v2); assert(v4 != v3); assert(v2 == false); assert(true == v3); assert(v4 == spot::trival::maybe()); assert((bool)v3); assert(!(bool)v2); assert(!(bool)!v1); assert(!(bool)v1); assert(!(bool)!v3); for (auto u : {v2, v1, v3}) for (auto v : {v2, v1, v3}) std::cout << u << " && " << v << " == " << (u && v) << '\n'; for (auto u : {v2, v1, v3}) for (auto v : {v2, v1, v3}) std::cout << u << " || " << v << " == " << (u || v) << '\n'; }
hich28/mytesttxx
tests/core/trival.cc
C++
gpl-3.0
1,546
# Authors: # Jason Gerard DeRose <jderose@redhat.com> # # Copyright (C) 2008 Red Hat # see file 'COPYING' for use and warranty information # # 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/>. """ Foundational classes and functions. """ import re from constants import NAME_REGEX, NAME_ERROR from constants import TYPE_ERROR, SET_ERROR, DEL_ERROR, OVERRIDE_ERROR class ReadOnly(object): """ Base class for classes that can be locked into a read-only state. Be forewarned that Python does not offer true read-only attributes for user-defined classes. Do *not* rely upon the read-only-ness of this class for security purposes! The point of this class is not to make it impossible to set or to delete attributes after an instance is locked, but to make it impossible to do so *accidentally*. Rather than constantly reminding our programmers of things like, for example, "Don't set any attributes on this ``FooBar`` instance because doing so wont be thread-safe", this class offers a real way to enforce read-only attribute usage. For example, before a `ReadOnly` instance is locked, you can set and delete its attributes as normal: >>> class Person(ReadOnly): ... pass ... >>> p = Person() >>> p.name = 'John Doe' >>> p.phone = '123-456-7890' >>> del p.phone But after an instance is locked, you cannot set its attributes: >>> p.__islocked__() # Is this instance locked? False >>> p.__lock__() # This will lock the instance >>> p.__islocked__() True >>> p.department = 'Engineering' Traceback (most recent call last): ... AttributeError: locked: cannot set Person.department to 'Engineering' Nor can you deleted its attributes: >>> del p.name Traceback (most recent call last): ... AttributeError: locked: cannot delete Person.name However, as noted at the start, there are still obscure ways in which attributes can be set or deleted on a locked `ReadOnly` instance. For example: >>> object.__setattr__(p, 'department', 'Engineering') >>> p.department 'Engineering' >>> object.__delattr__(p, 'name') >>> hasattr(p, 'name') False But again, the point is that a programmer would never employ the above techniques *accidentally*. Lastly, this example aside, you should use the `lock()` function rather than the `ReadOnly.__lock__()` method. And likewise, you should use the `islocked()` function rather than the `ReadOnly.__islocked__()` method. For example: >>> readonly = ReadOnly() >>> islocked(readonly) False >>> lock(readonly) is readonly # lock() returns the instance True >>> islocked(readonly) True """ __locked = False def __lock__(self): """ Put this instance into a read-only state. After the instance has been locked, attempting to set or delete an attribute will raise an AttributeError. """ assert self.__locked is False, '__lock__() can only be called once' self.__locked = True def __islocked__(self): """ Return True if instance is locked, otherwise False. """ return self.__locked def __setattr__(self, name, value): """ If unlocked, set attribute named ``name`` to ``value``. If this instance is locked, an AttributeError will be raised. :param name: Name of attribute to set. :param value: Value to assign to attribute. """ if self.__locked: raise AttributeError( SET_ERROR % (self.__class__.__name__, name, value) ) return object.__setattr__(self, name, value) def __delattr__(self, name): """ If unlocked, delete attribute named ``name``. If this instance is locked, an AttributeError will be raised. :param name: Name of attribute to delete. """ if self.__locked: raise AttributeError( DEL_ERROR % (self.__class__.__name__, name) ) return object.__delattr__(self, name) def lock(instance): """ Lock an instance of the `ReadOnly` class or similar. This function can be used to lock instances of any class that implements the same locking API as the `ReadOnly` class. For example, this function can lock instances of the `config.Env` class. So that this function can be easily used within an assignment, ``instance`` is returned after it is locked. For example: >>> readonly = ReadOnly() >>> readonly is lock(readonly) True >>> readonly.attr = 'This wont work' Traceback (most recent call last): ... AttributeError: locked: cannot set ReadOnly.attr to 'This wont work' Also see the `islocked()` function. :param instance: The instance of `ReadOnly` (or similar) to lock. """ assert instance.__islocked__() is False, 'already locked: %r' % instance instance.__lock__() assert instance.__islocked__() is True, 'failed to lock: %r' % instance return instance def islocked(instance): """ Return ``True`` if ``instance`` is locked. This function can be used on an instance of the `ReadOnly` class or an instance of any other class implemented the same locking API. For example: >>> readonly = ReadOnly() >>> islocked(readonly) False >>> readonly.__lock__() >>> islocked(readonly) True Also see the `lock()` function. :param instance: The instance of `ReadOnly` (or similar) to interrogate. """ assert ( hasattr(instance, '__lock__') and callable(instance.__lock__) ), 'no __lock__() method: %r' % instance return instance.__islocked__() def check_name(name): """ Verify that ``name`` is suitable for a `NameSpace` member name. In short, ``name`` must be a valid lower-case Python identifier that neither starts nor ends with an underscore. Otherwise an exception is raised. This function will raise a ``ValueError`` if ``name`` does not match the `constants.NAME_REGEX` regular expression. For example: >>> check_name('MyName') Traceback (most recent call last): ... ValueError: name must match '^[a-z][_a-z0-9]*[a-z0-9]$|^[a-z]$'; got 'MyName' Also, this function will raise a ``TypeError`` if ``name`` is not an ``str`` instance. For example: >>> check_name(u'my_name') Traceback (most recent call last): ... TypeError: name: need a <type 'str'>; got u'my_name' (a <type 'unicode'>) So that `check_name()` can be easily used within an assignment, ``name`` is returned unchanged if it passes the check. For example: >>> n = check_name('my_name') >>> n 'my_name' :param name: Identifier to test. """ if type(name) is not str: raise TypeError( TYPE_ERROR % ('name', str, name, type(name)) ) if re.match(NAME_REGEX, name) is None: raise ValueError( NAME_ERROR % (NAME_REGEX, name) ) return name class NameSpace(ReadOnly): """ A read-only name-space with handy container behaviours. A `NameSpace` instance is an ordered, immutable mapping object whose values can also be accessed as attributes. A `NameSpace` instance is constructed from an iterable providing its *members*, which are simply arbitrary objects with a ``name`` attribute whose value: 1. Is unique among the members 2. Passes the `check_name()` function Beyond that, no restrictions are placed on the members: they can be classes or instances, and of any type. The members can be accessed as attributes on the `NameSpace` instance or through a dictionary interface. For example, say we create a `NameSpace` instance from a list containing a single member, like this: >>> class my_member(object): ... name = 'my_name' ... >>> namespace = NameSpace([my_member]) >>> namespace NameSpace(<1 member>, sort=True) We can then access ``my_member`` both as an attribute and as a dictionary item: >>> my_member is namespace.my_name # As an attribute True >>> my_member is namespace['my_name'] # As dictionary item True For a more detailed example, say we create a `NameSpace` instance from a generator like this: >>> class Member(object): ... def __init__(self, i): ... self.i = i ... self.name = 'member%d' % i ... def __repr__(self): ... return 'Member(%d)' % self.i ... >>> ns = NameSpace(Member(i) for i in xrange(3)) >>> ns NameSpace(<3 members>, sort=True) As above, the members can be accessed as attributes and as dictionary items: >>> ns.member0 is ns['member0'] True >>> ns.member1 is ns['member1'] True >>> ns.member2 is ns['member2'] True Members can also be accessed by index and by slice. For example: >>> ns[0] Member(0) >>> ns[-1] Member(2) >>> ns[1:] (Member(1), Member(2)) (Note that slicing a `NameSpace` returns a ``tuple``.) `NameSpace` instances provide standard container emulation for membership testing, counting, and iteration. For example: >>> 'member3' in ns # Is there a member named 'member3'? False >>> 'member2' in ns # But there is a member named 'member2' True >>> len(ns) # The number of members 3 >>> list(ns) # Iterate through the member names ['member0', 'member1', 'member2'] Although not a standard container feature, the `NameSpace.__call__()` method provides a convenient (and efficient) way to iterate through the *members* (as opposed to the member names). Think of it like an ordered version of the ``dict.itervalues()`` method. For example: >>> list(ns[name] for name in ns) # One way to do it [Member(0), Member(1), Member(2)] >>> list(ns()) # A more efficient, simpler way to do it [Member(0), Member(1), Member(2)] Another convenience method is `NameSpace.__todict__()`, which will return a copy of the ``dict`` mapping the member names to the members. For example: >>> ns.__todict__() {'member1': Member(1), 'member0': Member(0), 'member2': Member(2)} As `NameSpace.__init__()` locks the instance, `NameSpace` instances are read-only from the get-go. An ``AttributeError`` is raised if you try to set *any* attribute on a `NameSpace` instance. For example: >>> ns.member3 = Member(3) # Lets add that missing 'member3' Traceback (most recent call last): ... AttributeError: locked: cannot set NameSpace.member3 to Member(3) (For information on the locking protocol, see the `ReadOnly` class, of which `NameSpace` is a subclass.) By default the members will be sorted alphabetically by the member name. For example: >>> sorted_ns = NameSpace([Member(7), Member(3), Member(5)]) >>> sorted_ns NameSpace(<3 members>, sort=True) >>> list(sorted_ns) ['member3', 'member5', 'member7'] >>> sorted_ns[0] Member(3) But if the instance is created with the ``sort=False`` keyword argument, the original order of the members is preserved. For example: >>> unsorted_ns = NameSpace([Member(7), Member(3), Member(5)], sort=False) >>> unsorted_ns NameSpace(<3 members>, sort=False) >>> list(unsorted_ns) ['member7', 'member3', 'member5'] >>> unsorted_ns[0] Member(7) The `NameSpace` class is used in many places throughout freeIPA. For a few examples, see the `plugable.API` and the `frontend.Command` classes. """ def __init__(self, members, sort=True, name_attr='name'): """ :param members: An iterable providing the members. :param sort: Whether to sort the members by member name. """ if type(sort) is not bool: raise TypeError( TYPE_ERROR % ('sort', bool, sort, type(sort)) ) self.__sort = sort if sort: self.__members = tuple( sorted(members, key=lambda m: getattr(m, name_attr)) ) else: self.__members = tuple(members) self.__names = tuple(getattr(m, name_attr) for m in self.__members) self.__map = dict() for member in self.__members: name = check_name(getattr(member, name_attr)) if name in self.__map: raise AttributeError(OVERRIDE_ERROR % (self.__class__.__name__, name, self.__map[name], member) ) assert not hasattr(self, name), 'Ouch! Has attribute %r' % name self.__map[name] = member setattr(self, name, member) lock(self) def __len__(self): """ Return the number of members. """ return len(self.__members) def __iter__(self): """ Iterate through the member names. If this instance was created with ``sort=False``, the names will be in the same order as the members were passed to the constructor; otherwise the names will be in alphabetical order (which is the default). This method is like an ordered version of ``dict.iterkeys()``. """ for name in self.__names: yield name def __call__(self): """ Iterate through the members. If this instance was created with ``sort=False``, the members will be in the same order as they were passed to the constructor; otherwise the members will be in alphabetical order by name (which is the default). This method is like an ordered version of ``dict.itervalues()``. """ for member in self.__members: yield member def __contains__(self, name): """ Return ``True`` if namespace has a member named ``name``. """ return name in self.__map def __getitem__(self, key): """ Return a member by name or index, or return a slice of members. :param key: The name or index of a member, or a slice object. """ if isinstance(key, basestring): return self.__map[key] if type(key) in (int, slice): return self.__members[key] raise TypeError( TYPE_ERROR % ('key', (str, int, slice), key, type(key)) ) def __repr__(self): """ Return a pseudo-valid expression that could create this instance. """ cnt = len(self) if cnt == 1: m = 'member' else: m = 'members' return '%s(<%d %s>, sort=%r)' % ( self.__class__.__name__, cnt, m, self.__sort, ) def __todict__(self): """ Return a copy of the private dict mapping member name to member. """ return dict(self.__map)
hatchetation/freeipa
ipalib/base.py
Python
gpl-3.0
15,669
/* Copyright (C) 2008 Bradley Arsenault 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, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ #include "YOGClientGameListManager.h" #include "NetMessage.h" #include "YOGClientGameListListener.h" YOGClientGameListManager::YOGClientGameListManager(YOGClient* client) : client(client) { } void YOGClientGameListManager::recieveMessage(boost::shared_ptr<NetMessage> message) { Uint8 type = message->getMessageType(); ///This recieves a game list update message if(type==MNetUpdateGameList) { shared_ptr<NetUpdateGameList> info = static_pointer_cast<NetUpdateGameList>(message); info->applyDifferences(games); sendToListeners(); } } const std::list<YOGGameInfo>& YOGClientGameListManager::getGameList() const { return games; } std::list<YOGGameInfo>& YOGClientGameListManager::getGameList() { return games; } YOGGameInfo YOGClientGameListManager::getGameInfo(Uint16 gameID) { for(std::list<YOGGameInfo>::iterator i=games.begin(); i!=games.end(); ++i) { if(i->getGameID() == gameID) { return *i; } } return YOGGameInfo(); } void YOGClientGameListManager::addListener(YOGClientGameListListener* listener) { listeners.push_back(listener); } void YOGClientGameListManager::removeListener(YOGClientGameListListener* listener) { listeners.remove(listener); } void YOGClientGameListManager::sendToListeners() { for(std::list<YOGClientGameListListener*>::iterator i = listeners.begin(); i!=listeners.end(); ++i) { (*i)->gameListUpdated(); } }
krichter722/glob2-git-hg
src/YOGClientGameListManager.cpp
C++
gpl-3.0
2,140
/* * (c) 2009-2016 Jens Mueller * * Kleincomputer-Emulator * * Fenster zum manuellen Erzeugen einer Diskettenabbilddatei */ package jkcemu.disk; import java.awt.Color; import java.awt.Dimension; import java.awt.EventQueue; import java.awt.FlowLayout; import java.awt.Font; import java.awt.Frame; import java.awt.GridBagConstraints; import java.awt.GridBagLayout; import java.awt.Insets; import java.awt.Toolkit; import java.awt.datatransfer.Clipboard; import java.awt.datatransfer.DataFlavor; import java.awt.datatransfer.FlavorEvent; import java.awt.datatransfer.FlavorListener; import java.awt.datatransfer.Transferable; import java.awt.datatransfer.UnsupportedFlavorException; import java.awt.dnd.DnDConstants; import java.awt.dnd.DropTarget; import java.awt.dnd.DropTargetDragEvent; import java.awt.dnd.DropTargetDropEvent; import java.awt.dnd.DropTargetEvent; import java.awt.dnd.DropTargetListener; import java.awt.event.KeyEvent; import java.io.File; import java.io.IOException; import java.io.OutputStream; import java.lang.*; import java.util.Collection; import java.util.EventObject; import java.util.Arrays; import javax.swing.JButton; import javax.swing.JLabel; import javax.swing.JMenu; import javax.swing.JMenuBar; import javax.swing.JMenuItem; import javax.swing.JOptionPane; import javax.swing.JPanel; import javax.swing.JScrollPane; import javax.swing.JSpinner; import javax.swing.JTabbedPane; import javax.swing.JTable; import javax.swing.JTextField; import javax.swing.JToolBar; import javax.swing.JViewport; import javax.swing.KeyStroke; import javax.swing.ListSelectionModel; import javax.swing.SpinnerNumberModel; import javax.swing.event.ChangeEvent; import javax.swing.event.ChangeListener; import javax.swing.event.ListSelectionEvent; import javax.swing.event.ListSelectionListener; import jkcemu.Main; import jkcemu.base.BaseDlg; import jkcemu.base.BaseFrm; import jkcemu.base.EmuUtil; import jkcemu.base.FileEntry; import jkcemu.base.FileNameFld; import jkcemu.base.FileTableModel; import jkcemu.base.HelpFrm; import jkcemu.base.NIOFileTimesViewFactory; import jkcemu.base.ReplyTextDlg; import jkcemu.text.TextUtil; public class DiskImgCreateFrm extends BaseFrm implements ChangeListener, DropTargetListener, FlavorListener, ListSelectionListener { private static final String HELP_PAGE = "/help/disk/creatediskimg.htm"; private static DiskImgCreateFrm instance = null; private Clipboard clipboard; private File lastOutFile; private boolean dataChanged; private JMenuItem mnuClose; private JMenuItem mnuNew; private JMenuItem mnuFileAdd; private JMenuItem mnuFileRemove; private JMenuItem mnuSort; private JMenuItem mnuSave; private JMenuItem mnuChangeAttrs; private JMenuItem mnuChangeUser; private JMenuItem mnuPaste; private JMenuItem mnuSelectAll; private JMenuItem mnuHelpContent; private JButton btnFileAdd; private JButton btnFileRemove; private JButton btnSave; private JButton btnFileUp; private JButton btnFileDown; private JButton btnSysTrackFileSelect; private JButton btnSysTrackFileRemove; private JTabbedPane tabbedPane; private FileTableModel tableModel; private JTable table; private JScrollPane scrollPane; private FloppyDiskFormatSelectFld fmtSelectFld; private JLabel labelSysTrackFile; private FileNameFld fldSysTrackFileName; private JTextField fldRemark; private JLabel labelStatus; private DropTarget dropTargetFile1; private DropTarget dropTargetFile2; private DropTarget dropTargetSysTrackFile; public static void open() { if( instance != null ) { if( instance.getExtendedState() == Frame.ICONIFIED ) { instance.setExtendedState( Frame.NORMAL ); } } else { instance = new DiskImgCreateFrm(); } instance.toFront(); instance.setVisible( true ); } /* --- ChangeListener --- */ @Override public void stateChanged( ChangeEvent e ) { Object src = e.getSource(); if( src != null ) { if( src == this.tabbedPane ) { updActionButtons(); updStatusText(); } else if( src == this.fmtSelectFld ) { updSysTrackFileFieldsEnabled(); updStatusText(); } } } /* --- DropTargetListener --- */ @Override public void dragEnter( DropTargetDragEvent e ) { if( !EmuUtil.isFileDrop( e ) ) e.rejectDrag(); } @Override public void dragExit( DropTargetEvent e ) { // leer } @Override public void dragOver( DropTargetDragEvent e ) { // leer } @Override public void drop( DropTargetDropEvent e ) { Object src = e.getSource(); if( (src == this.dropTargetFile1) || (src == this.dropTargetFile2) ) { if( EmuUtil.isFileDrop( e ) ) { e.acceptDrop( DnDConstants.ACTION_COPY ); // Quelle nicht loeschen pasteFiles( e.getTransferable() ); } } else if( src == this.dropTargetSysTrackFile ) { File file = EmuUtil.fileDrop( this, e ); if( file != null ) { addSysTrackFile( file ); } } } @Override public void dropActionChanged( DropTargetDragEvent e ) { if( !EmuUtil.isFileDrop( e ) ) e.rejectDrag(); } /* --- FlavorListener --- */ @Override public void flavorsChanged( FlavorEvent e ) { updPasteButton(); } /* --- ListSelectionListener --- */ @Override public void valueChanged( ListSelectionEvent e ) { updActionButtons(); } /* --- ueberschriebene Methoden --- */ @Override protected boolean doAction( EventObject e ) { updStatusText(); boolean rv = false; Object src = e.getSource(); if( src == this.mnuClose ) { rv = true; doClose(); } else if( (src == this.mnuFileAdd) || (src == this.btnFileAdd) ) { rv = true; doFileAdd(); } else if( (src == this.mnuFileRemove) || (src == this.btnFileRemove) ) { rv = true; doFileRemove(); } else if( src == this.mnuNew ) { rv = true; doNew(); } else if( src == this.mnuSort ) { rv = true; this.tableModel.sortAscending( 0 ); } else if( (src == this.mnuSave) || (src == this.btnSave) ) { rv = true; doSave(); } else if( src == this.btnFileDown ) { rv = true; doFileDown(); } else if( src == this.btnFileUp ) { rv = true; doFileUp(); } else if( src == this.btnSysTrackFileSelect ) { rv = true; doSysTrackFileSelect(); } else if( src == this.mnuChangeAttrs ) { rv = true; doChangeAttrs(); } else if( src == this.mnuChangeUser ) { rv = true; doChangeUser(); } else if( src == this.mnuPaste ) { rv = true; doPaste(); } else if( src == this.mnuSelectAll ) { rv = true; doSelectAll(); } else if( src == this.btnSysTrackFileRemove ) { rv = true; doSysTrackFileRemove(); } else if( src == this.mnuHelpContent ) { rv = true; HelpFrm.open( HELP_PAGE ); } return rv; } @Override public boolean doClose() { boolean rv = true; if( this.dataChanged ) { setState( Frame.NORMAL ); toFront(); if( !BaseDlg.showYesNoDlg( this, "Daten ge\u00E4ndert!\n" + "Trotzdem schlie\u00DFen?" ) ) { rv = false; } } if( rv ) { this.tableModel.clear( true ); updStatusText(); rv = super.doClose(); } if( rv ) { this.dataChanged = false; Main.checkQuit( this ); } return rv; } /* --- Aktionen --- */ private void doChangeAttrs() { int[] rowNums = this.table.getSelectedRows(); if( rowNums != null ) { if( rowNums.length > 0 ) { ChangeFileAttrsDlg dlg = new ChangeFileAttrsDlg( this ); dlg.setVisible( true ); Boolean readOnly = dlg.getReadOnlyValue(); Boolean sysFile = dlg.getSystemFileValue(); Boolean archive = dlg.getArchiveValue(); if( (readOnly != null) || (sysFile != null) || (archive != null) ) { for( int i = 0; i< rowNums.length; i++ ) { int rowNum = rowNums[ i ]; FileEntry entry = this.tableModel.getRow( rowNums[ i ] ); if( entry != null ) { if( readOnly != null ) { entry.setReadOnly( readOnly.booleanValue() ); } if( sysFile != null ) { entry.setSystemFile( sysFile.booleanValue() ); } if( archive != null ) { entry.setArchive( archive.booleanValue() ); } this.tableModel.fireTableRowsUpdated( rowNum, rowNum ); } } } } } } private void doChangeUser() { int[] rowNums = this.table.getSelectedRows(); if( rowNums != null ) { if( rowNums.length > 0 ) { // voreingestellten User-Bereich ermitteln int value = -1; for( int i = 0; i< rowNums.length; i++ ) { FileEntry entry = this.tableModel.getRow( rowNums[ i ] ); if( entry != null ) { Integer userNum = entry.getUserNum(); if( userNum != null ) { if( value >= 0 ) { if( userNum.intValue() != value ) { value = -1; break; } } else { value = userNum.intValue(); } } } } if( (value < 0) || (value > 15) ) { value = 0; } // Dialog anzeigen JPanel panel = new JPanel( new FlowLayout( FlowLayout.CENTER, 5, 5 ) ); panel.add( new JLabel( "User-Bereich:" ) ); JSpinner spinner = new JSpinner( new SpinnerNumberModel( value, 0, 15, 1 ) ); panel.add( spinner ); int option = JOptionPane.showConfirmDialog( this, panel, "User-Bereich \u00E4ndern", JOptionPane.OK_CANCEL_OPTION, JOptionPane.PLAIN_MESSAGE ); if( option == JOptionPane.OK_OPTION ) { Object o = spinner.getValue(); if( o != null ) { if( o instanceof Number ) { value = ((Number) o).intValue(); if( (value >= 0) && (value <= 15) ) { Integer userNum = value; for( int i = 0; i< rowNums.length; i++ ) { int rowNum = rowNums[ i ]; FileEntry entry = this.tableModel.getRow( rowNum ); if( entry != null ) { entry.setUserNum( userNum ); this.tableModel.fireTableRowsUpdated( rowNum, rowNum ); } } } } } } } } } public void doNew() { boolean status = true; StringBuilder buf = new StringBuilder( 256 ); if( this.dataChanged ) { buf.append( "Die letzten \u00C3nderungen wurden nicht gespeichert!" ); } if( (this.tableModel.getRowCount() > 0) || (this.fldSysTrackFileName.getFile() != null) ) { if( buf.length() > 0 ) { buf.append( (char) '\n' ); } buf.append( "Die hinzugef\u00FCgten Dateien werden entfernt." ); } if( buf.length() > 0 ) { status = BaseDlg.showConfirmDlg( this, buf.toString() ); } if( status ) { this.tableModel.clear( true ); this.fldSysTrackFileName.setFile( null ); this.dataChanged = false; this.lastOutFile = null; updTitle(); } } private void doPaste() { if( this.clipboard != null ) { try { pasteFiles( this.clipboard.getContents( this ) ); } catch( IllegalStateException ex ) {} } } private void doSelectAll() { int nRows = this.table.getRowCount(); if( nRows > 0 ) { this.table.setRowSelectionInterval( 0, nRows - 1 ); } } private void doSave() { boolean status = true; if( this.tableModel.getRowCount() == 0 ) { status = BaseDlg.showYesNoDlg( this, "Es wurden keine Dateien hinzugef\u00FCgt.\n" + "M\u00F6chten Sie eine leere Diskettenabbilddatei" + " erstellen?" ); } int sysTracks = this.fmtSelectFld.getSysTracks(); File sysTrackFile = this.fldSysTrackFileName.getFile(); if( (sysTrackFile != null) && (sysTracks == 0) ) { if( JOptionPane.showConfirmDialog( this, "Sie haben ein Format ohne Systemspuren ausgew\u00E4hlt,\n" + "aber eine Datei f\u00FCr die Systemspuren" + " angegeben.\n" + "Diese Datei wird ignoriert.", "Warnung", JOptionPane.OK_CANCEL_OPTION, JOptionPane.WARNING_MESSAGE ) != JOptionPane.OK_OPTION ) { status = false; } } if( status ) { File file = EmuUtil.showFileSaveDlg( this, "Diskettenabbilddatei speichern", this.lastOutFile != null ? this.lastOutFile : Main.getLastDirFile( Main.FILE_GROUP_DISK ), EmuUtil.getPlainDiskFileFilter(), EmuUtil.getAnaDiskFileFilter(), EmuUtil.getCopyQMFileFilter(), EmuUtil.getDskFileFilter(), EmuUtil.getImageDiskFileFilter(), EmuUtil.getTeleDiskFileFilter() ); if( file != null ) { boolean plainDisk = false; boolean anaDisk = false; boolean cpcDisk = false; boolean copyQMDisk = false; boolean imageDisk = false; boolean teleDisk = false; String fileName = file.getName(); if( fileName != null ) { String lowerName = fileName.toLowerCase(); if( lowerName.endsWith( ".gz" ) ) { lowerName = lowerName.substring( 0, lowerName.length() - 3 ); } plainDisk = TextUtil.endsWith( lowerName, DiskUtil.plainDiskFileExt ); anaDisk = TextUtil.endsWith( lowerName, DiskUtil.anaDiskFileExt ); copyQMDisk = TextUtil.endsWith( lowerName, DiskUtil.copyQMFileExt ); cpcDisk = TextUtil.endsWith( lowerName, DiskUtil.dskFileExt ); imageDisk = TextUtil.endsWith( lowerName, DiskUtil.imageDiskFileExt ); teleDisk = TextUtil.endsWith( lowerName, DiskUtil.teleDiskFileExt ); } if( plainDisk || anaDisk || copyQMDisk || cpcDisk || imageDisk || teleDisk ) { boolean cancelled = false; OutputStream out = null; try { int sides = this.fmtSelectFld.getSides(); int cyls = this.fmtSelectFld.getCylinders(); int sectPerCyl = this.fmtSelectFld.getSectorsPerCylinder(); int sectorSize = this.fmtSelectFld.getSectorSize(); DiskImgCreator diskImgCreator = new DiskImgCreator( new NIOFileTimesViewFactory(), sides, cyls, sysTracks, sectPerCyl, sectorSize, this.fmtSelectFld.isBlockNum16Bit(), this.fmtSelectFld.getBlockSize(), this.fmtSelectFld.getDirBlocks(), this.fmtSelectFld.isDateStamperEnabled() ); if( (sysTrackFile != null) && (sysTracks > 0) ) { diskImgCreator.fillSysTracks( sysTrackFile ); } int nRows = this.tableModel.getRowCount(); for( int i = 0; i < nRows; i++ ) { FileEntry entry = this.tableModel.getRow( i ); if( entry != null ) { try { diskImgCreator.addFile( entry.getUserNum(), entry.getName(), entry.getFile(), entry.isReadOnly(), entry.isSystemFile(), entry.isArchive() ); } catch( IOException ex ) { fireSelectRowInterval( i, i ); String msg = ex.getMessage(); if( msg != null ) { if( msg.isEmpty() ) { msg = null; } } if( msg != null ) { msg = entry.getName() + ":\n" + msg; } else { msg = entry.getName() + " kann nicht hinzugef\u00FCgt werden."; } if( JOptionPane.showConfirmDialog( this, msg, "Fehler", JOptionPane.OK_CANCEL_OPTION, JOptionPane.ERROR_MESSAGE ) != JOptionPane.OK_OPTION ) { cancelled = true; break; } } } } if( !cancelled ) { byte[] diskBuf = diskImgCreator.getPlainDiskByteBuffer(); if( plainDisk ) { out = EmuUtil.createOptionalGZipOutputStream( file ); out.write( diskBuf ); out.close(); out = null; } else { PlainDisk disk = PlainDisk.createForByteArray( this, file.getPath(), diskBuf, new FloppyDiskFormat( sides, cyls, sectPerCyl, sectorSize ), this.fmtSelectFld.getInterleave() ); if( disk != null ) { if( anaDisk ) { AnaDisk.export( disk, file ); } else if( copyQMDisk ) { CopyQMDisk.export( disk, file, this.fldRemark.getText() ); } else if( cpcDisk ) { CPCDisk.export( disk, file ); } else if( imageDisk ) { ImageDisk.export( disk, file, this.fldRemark.getText() ); } else if( teleDisk ) { TeleDisk.export( disk, file, this.fldRemark.getText() ); } } } this.dataChanged = false; this.lastOutFile = file; updTitle(); Main.setLastFile( file, Main.FILE_GROUP_DISK ); this.labelStatus.setText( "Diskettenabbilddatei gespeichert" ); } } catch( Exception ex ) { BaseDlg.showErrorDlg( this, ex ); } finally { EmuUtil.closeSilent( out ); } } else { BaseDlg.showErrorDlg( this, "Aus der Dateiendung der ausgew\u00E4hlten Datei\n" + "kann JKCEMU das Dateiformat nicht erkennen.\n" + "W\u00E4hlen Sie bitte einen Dateinamen" + " mit einer f\u00FCr\n" + "das gew\u00FCnschte Format \u00FCblichen" + " Dateiendung aus." ); } } } } private void doFileAdd() { java.util.List<File> files = EmuUtil.showMultiFileOpenDlg( this, "Dateien hinzuf\u00FCgen", Main.getLastDirFile( Main.FILE_GROUP_SOFTWARE ) ); if( files != null ) { int firstRowToSelect = this.table.getRowCount(); for( File file : files ) { if( addFile( file ) ) { Main.setLastFile( file, Main.FILE_GROUP_SOFTWARE ); } } updSelectAllEnabled(); fireSelectRowInterval( firstRowToSelect, this.table.getRowCount() - 1 ); } } private void doFileRemove() { int[] rowNums = this.table.getSelectedRows(); if( rowNums != null ) { if( rowNums.length > 0 ) { Arrays.sort( rowNums ); for( int i = rowNums.length - 1; i >= 0; --i ) { this.tableModel.removeRow( rowNums[ i ], true ); this.mnuSort.setEnabled( this.tableModel.getRowCount() > 1 ); this.dataChanged = true; } updSelectAllEnabled(); updStatusText(); } } } private void doFileDown() { final int[] rowNums = this.table.getSelectedRows(); if( rowNums != null ) { if( rowNums.length > 0) { Arrays.sort( rowNums ); if( (rowNums[ rowNums.length - 1 ] + 1) < this.tableModel.getRowCount() ) { for( int i = rowNums.length - 1 ; i >= 0; --i ) { int row = rowNums[ i ]; FileEntry e1 = this.tableModel.getRow( row ); FileEntry e2 = this.tableModel.getRow( row + 1 ); if( (e1 != null) && (e2 != null) ) { this.tableModel.setRow( row, e2 ); this.tableModel.setRow( row + 1, e1 ); this.tableModel.fireTableDataChanged(); this.dataChanged = true; } rowNums[ i ]++; } } fireSelectRows( rowNums ); } } } private void doFileUp() { final int[] rowNums = this.table.getSelectedRows(); if( rowNums != null ) { if( rowNums.length > 0) { Arrays.sort( rowNums ); if( rowNums[ 0 ] > 0 ) { for( int i = 0; i < rowNums.length; i++ ) { int row = rowNums[ i ]; FileEntry e1 = this.tableModel.getRow( row ); FileEntry e2 = this.tableModel.getRow( row - 1 ); if( (e1 != null) && (e2 != null) ) { this.tableModel.setRow( row, e2 ); this.tableModel.setRow( row - 1, e1 ); this.tableModel.fireTableDataChanged(); this.dataChanged = true; } --rowNums[ i ]; } } fireSelectRows( rowNums ); } } } private void doSysTrackFileSelect() { File file = EmuUtil.showFileOpenDlg( this, "Datei \u00FCffnen", Main.getLastDirFile( Main.FILE_GROUP_SOFTWARE ) ); if( file != null ) { addSysTrackFile( file ); } } private void doSysTrackFileRemove() { this.fldSysTrackFileName.setFile( null ); this.btnSysTrackFileRemove.setEnabled( false ); } /* --- Konstruktor --- */ private DiskImgCreateFrm() { this.clipboard = null; this.dataChanged = false; this.lastOutFile = null; updTitle(); Main.updIcon( this ); Toolkit tk = getToolkit(); if( tk != null ) { this.clipboard = tk.getSystemClipboard(); } // Menu JMenuBar mnuBar = new JMenuBar(); setJMenuBar( mnuBar ); // Menu Datei JMenu mnuFile = new JMenu( "Datei" ); mnuFile.setMnemonic( KeyEvent.VK_D ); mnuBar.add( mnuFile ); this.mnuNew = createJMenuItem( "Neue Diskettenabbilddatei" ); mnuFile.add( this.mnuNew ); mnuFile.addSeparator(); this.mnuFileAdd = createJMenuItem( "Hinzuf\u00FCgen..." ); mnuFile.add( this.mnuFileAdd ); this.mnuFileRemove = createJMenuItem( "Entfernen", KeyStroke.getKeyStroke( KeyEvent.VK_DELETE, 0 ) ); mnuFile.add( this.mnuFileRemove ); mnuFile.addSeparator(); this.mnuSort = createJMenuItem( "Sortieren" ); this.mnuSort.setEnabled( false ); mnuFile.add( this.mnuSort ); mnuFile.addSeparator(); this.mnuSave = createJMenuItem( "Diskettenabbilddatei speichern..." ); mnuFile.add( this.mnuSave ); mnuFile.addSeparator(); this.mnuClose = createJMenuItem( "Schlie\u00DFen" ); mnuFile.add( this.mnuClose ); // Menu Bearbeiten JMenu mnuEdit = new JMenu( "Bearbeiten" ); mnuEdit.setMnemonic( KeyEvent.VK_B ); mnuBar.add( mnuEdit ); this.mnuPaste = createJMenuItem( "Einf\u00FCgen" ); mnuEdit.add( this.mnuPaste ); mnuEdit.addSeparator(); this.mnuChangeAttrs = createJMenuItem( "Dateiattribute \u00E4ndern..." ); mnuEdit.add( this.mnuChangeAttrs ); this.mnuChangeUser = createJMenuItem( "User-Bereich \u00E4ndern..." ); mnuEdit.add( this.mnuChangeUser ); mnuEdit.addSeparator(); this.mnuSelectAll = createJMenuItem( "Alles ausw\u00E4hlem" ); this.mnuSelectAll.setEnabled( false ); mnuEdit.add( this.mnuSelectAll ); // Menu Hilfe JMenu mnuHelp = new JMenu( "?" ); mnuBar.add( mnuHelp ); this.mnuHelpContent = createJMenuItem( "Hilfe..." ); mnuHelp.add( this.mnuHelpContent ); // Fensterinhalt setLayout( new GridBagLayout() ); GridBagConstraints gbc = new GridBagConstraints( 0, 0, 1, 1, 1.0, 0.0, GridBagConstraints.WEST, GridBagConstraints.HORIZONTAL, new Insets( 5, 5, 5, 5 ), 0, 0 ); // Werkzeugleiste JToolBar toolBar = new JToolBar(); toolBar.setFloatable( false ); toolBar.setBorderPainted( false ); toolBar.setOrientation( JToolBar.HORIZONTAL ); toolBar.setRollover( true ); add( toolBar, gbc ); this.btnFileAdd = createImageButton( "/images/file/open.png", "Hinzuf\u00FCgen" ); toolBar.add( this.btnFileAdd ); this.btnFileRemove = createImageButton( "/images/file/delete.png", "Entfernen" ); toolBar.add( this.btnFileRemove ); toolBar.addSeparator(); this.btnSave = createImageButton( "/images/file/save_as.png", "Diskettenabbilddatei speichern" ); toolBar.add( this.btnSave ); toolBar.addSeparator(); this.btnFileDown = createImageButton( "/images/nav/down.png", "Nach unten" ); toolBar.add( this.btnFileDown ); this.btnFileUp = createImageButton( "/images/nav/up.png", "Nach oben" ); toolBar.add( this.btnFileUp ); // TabbedPane this.tabbedPane = new JTabbedPane(); gbc.fill = GridBagConstraints.BOTH; gbc.weighty = 1.0; gbc.gridy++; add( this.tabbedPane, gbc ); // Tabellenfeld this.tableModel = new FileTableModel( FileTableModel.Column.NAME, FileTableModel.Column.FILE, FileTableModel.Column.SIZE, FileTableModel.Column.LAST_MODIFIED, FileTableModel.Column.USER_NUM, FileTableModel.Column.READ_ONLY, FileTableModel.Column.SYSTEM_FILE, FileTableModel.Column.ARCHIVE ); this.table = new JTable( this.tableModel ); this.table.setAutoResizeMode( JTable.AUTO_RESIZE_OFF ); this.table.setColumnSelectionAllowed( false ); this.table.setPreferredScrollableViewportSize( new Dimension( 700, 300 ) ); this.table.setRowSelectionAllowed( true ); this.table.setRowSorter( null ); this.table.setShowGrid( false ); this.table.setShowHorizontalLines( false ); this.table.setShowVerticalLines( false ); this.table.setSelectionMode( ListSelectionModel.MULTIPLE_INTERVAL_SELECTION ); this.table.addMouseListener( this ); EmuUtil.setTableColWidths( this.table, 100, 280, 70, 130, 40, 40, 40, 40 ); ListSelectionModel selectionModel = this.table.getSelectionModel(); if( selectionModel != null ) { selectionModel.addListSelectionListener( this ); updActionButtons(); } this.scrollPane = new JScrollPane( this.table ); this.tabbedPane.addTab( "Dateien", this.scrollPane ); // Format JPanel panelFmt = new JPanel( new GridBagLayout() ); this.tabbedPane.addTab( "Format", new JScrollPane( panelFmt ) ); GridBagConstraints gbcFmt = new GridBagConstraints( 0, 0, GridBagConstraints.REMAINDER, 1, 0.0, 0.0, GridBagConstraints.WEST, GridBagConstraints.NONE, new Insets( 5, 5, 0, 5 ), 0, 0 ); this.fmtSelectFld = new FloppyDiskFormatSelectFld( true ); panelFmt.add( this.fmtSelectFld, gbcFmt ); this.labelSysTrackFile = new JLabel( "Datei f\u00FCr Systemspuren:" ); gbcFmt.insets.top = 5; gbcFmt.insets.left = 5; gbcFmt.insets.bottom = 5; gbcFmt.gridwidth = 1; gbcFmt.gridx = 0; gbcFmt.gridy++; panelFmt.add( this.labelSysTrackFile, gbcFmt ); this.fldSysTrackFileName = new FileNameFld(); this.fldSysTrackFileName.setEditable( false ); gbcFmt.fill = GridBagConstraints.HORIZONTAL; gbcFmt.weightx = 1.0; gbcFmt.gridwidth = 5; gbcFmt.gridx++; panelFmt.add( this.fldSysTrackFileName, gbcFmt ); this.btnSysTrackFileSelect = createImageButton( "/images/file/open.png", "\u00D6ffnen" ); gbcFmt.fill = GridBagConstraints.NONE; gbcFmt.weightx = 0.0; gbcFmt.gridwidth = 1; gbcFmt.gridx += 5; panelFmt.add( this.btnSysTrackFileSelect, gbcFmt ); this.btnSysTrackFileRemove = createImageButton( "/images/file/delete.png", "\u00D6ffnen" ); this.btnSysTrackFileRemove.setEnabled( false ); gbcFmt.gridx++; panelFmt.add( this.btnSysTrackFileRemove, gbcFmt ); // Kommentar JPanel panelRemark = new JPanel( new GridBagLayout() ); this.tabbedPane.addTab( "Kommentar", new JScrollPane( panelRemark ) ); GridBagConstraints gbcRemark = new GridBagConstraints( 0, 0, GridBagConstraints.REMAINDER, 1, 0.0, 0.0, GridBagConstraints.WEST, GridBagConstraints.NONE, new Insets( 5, 5, 0, 5 ), 0, 0 ); panelRemark.add( new JLabel( "Kommentar zur Diskettenabbilddatei:" ), gbcRemark ); this.fldRemark = new JTextField( "Erzeugt mit JKCEMU" ); gbcRemark.fill = GridBagConstraints.HORIZONTAL; gbcRemark.weightx = 1.0; gbcRemark.insets.top = 0; gbcRemark.insets.bottom = 5; gbcRemark.gridy++; panelRemark.add( this.fldRemark, gbcRemark ); JLabel label = new JLabel( "Achtung!" ); Font font = label.getFont(); if( font != null ) { label.setFont( font.deriveFont( Font.BOLD ) ); } gbcRemark.fill = GridBagConstraints.NONE; gbcRemark.weightx = 0.0; gbcRemark.insets.top = 10; gbcRemark.insets.bottom = 0; gbcRemark.gridy++; panelRemark.add( label, gbcRemark ); gbcRemark.fill = GridBagConstraints.NONE; gbcRemark.weightx = 0.0; gbcRemark.insets.top = 0; gbcRemark.insets.bottom = 5; gbcRemark.gridy++; panelRemark.add( new JLabel( "Ein Kommentar wird nur bei CopyQM-, ImageDisk-" + " und TeleDisk-Dateien unterst\u00FCtzt." ), gbcRemark ); // Statuszeile this.labelStatus = new JLabel(); gbc.fill = GridBagConstraints.HORIZONTAL; gbc.weighty = 0.0; gbc.insets.top = 0; gbc.gridy++; add( this.labelStatus, gbc ); updStatusText(); // Fenstergroesse if( !applySettings( Main.getProperties(), true ) ) { pack(); setScreenCentered(); } setResizable( true ); // Listener this.tabbedPane.addChangeListener( this ); this.fmtSelectFld.addChangeListener( this ); if( this.clipboard != null ) { this.clipboard.addFlavorListener( this ); } // Drop-Ziele this.dropTargetFile1 = new DropTarget( this.table, this ); this.dropTargetFile2 = new DropTarget( this.scrollPane, this ); this.dropTargetSysTrackFile = new DropTarget( this.fldSysTrackFileName, this ); this.dropTargetFile1.setActive( true ); this.dropTargetFile1.setActive( true ); this.dropTargetSysTrackFile.setActive( true ); // sonstiges updActionButtons(); updBgColor(); updPasteButton(); } /* --- private Methoden --- */ private boolean addFile( File file ) { boolean rv = false; boolean done = false; if( file.isDirectory() ) { String s = file.getName(); if( s != null ) { try { int userNum = Integer.parseInt( s ); if( (userNum >= 1) && (userNum <= 15) ) { done = true; if( BaseDlg.showYesNoDlg( this, "Sollen die Dateien im Verzeichnis " + s + "\nin der Benutzerebene " + s + " hinzugef\u00FCgt werden?" ) ) { File[] files = file.listFiles(); if( files != null ) { for( File f : files ) { if( f.isFile() ) { rv = addFileInternal( userNum, f ); if( !rv ) { break; } } } } } } } catch( NumberFormatException ex ) {} } } if( !done ) { rv = addFileInternal( 0, file ); } return rv; } private boolean addFileInternal( int userNum, File file ) { boolean rv = false; long size = -1L; if( file.isFile() ) { size = file.length(); if( size < 1 ) { String fName = file.getName(); if( fName != null ) { if( fName.isEmpty() ) { fName = null; } } if( fName == null ) { fName = file.getPath(); } if( !BaseDlg.showYesNoDlg( this, "Datei " + fName + ":\nDie Datei ist leer!\n" + "Trotzdem hinzuf\u00FCgen?" ) ) { file = null; } } else if( size > (1024 * 16 * 32) ) { BaseDlg.showErrorDlg( this, "Datei ist zu gro\u00DF!" ); file = null; } else { String fileName = file.getName(); if( fileName != null ) { if( fileName.equalsIgnoreCase( DirectoryFloppyDisk.SYS_FILE_NAME ) ) { if( BaseDlg.showYesNoDlg( this, DirectoryFloppyDisk.SYS_FILE_NAME + ":\n" + "JKCEMU verwendet Dateien mit diesem Namen" + " f\u00FCr den Inhalt der Systemspuren.\n" + "M\u00F6chten Sie deshalb nun diese Datei" + " f\u00FCr die Systemspuren verwenden,\n" + "anstelle Sie als gew\u00F6hnliche Datei" + " im Directory einzubinden?" ) ) { this.fldSysTrackFileName.setFile( file ); this.btnSysTrackFileRemove.setEnabled( true ); file = null; rv = true; } } } } } else { BaseDlg.showErrorDlg( this, "Es k\u00F6nnen nur regul\u00E4re Dateien" + " hinzugef\u00FCgt werden." ); file = null; } if( file != null ) { String entryName = null; String fileName = file.getName(); if( fileName != null ) { entryName = createEntryName( fileName ); } if( entryName == null ) { String title = "Dateiname"; String defaultReply = null; if( fileName != null ) { if( !fileName.isEmpty() ) { title = "Datei: " + fileName; } StringBuilder buf = new StringBuilder( 12 ); int len = fileName.length(); int n = 0; for( int i = 0; (n < 8) && (i < len); i++ ) { char ch = Character.toUpperCase( fileName.charAt( i ) ); if( DiskUtil.isValidCPMFileNameChar( ch ) ) { buf.append( ch ); n++; } else if( ch == '.' ) { break; } } if( n > 0 ) { int pos = fileName.lastIndexOf( '.' ); if( pos > 0 ) { boolean p = true; n = 0; for( int i = pos + 1; (n < 3) && (i < len); i++ ) { char ch = Character.toUpperCase( fileName.charAt( i ) ); if( DiskUtil.isValidCPMFileNameChar( ch ) ) { if( p ) { buf.append( (char) '.' ); p = false; } buf.append( ch ); n++; } } } } defaultReply = buf.toString(); } String reply = null; do { reply = ReplyTextDlg.showReplyTextDlg( this, "Dateiname im 8.3-Format:", title, defaultReply ); if( reply != null ) { entryName = createEntryName( reply ); if( entryName == null ) { BaseDlg.showErrorDlg( this, "Der eingegebene Name ist ung\u00FCltig." ); } } } while( (reply != null) && (entryName == null) ); } if( entryName != null ) { boolean exists = false; int nRows = this.tableModel.getRowCount(); for( int i = 0; i < nRows; i++ ) { FileEntry entry = this.tableModel.getRow( i ); if( entry != null ) { if( entry.getName().equals( entryName ) ) { this.table.setRowSelectionInterval( i, i ); exists = true; break; } } } if( exists ) { BaseDlg.showErrorDlg( this, "Es existiert bereits ein Eintrag mit diesem Namen." ); } else { FileEntry entry = new FileEntry( entryName ); entry.setUserNum( userNum ); if( size >= 0 ) { entry.setSize( size ); } long lastModified = file.lastModified(); if( lastModified != 0 ) { entry.setLastModified( lastModified ); } entry.setFile( file ); entry.setReadOnly( !file.canWrite() ); entry.setSystemFile( false ); entry.setArchive( false ); this.tableModel.addRow( entry, true ); updStatusText(); this.mnuSort.setEnabled( this.tableModel.getRowCount() > 1 ); this.dataChanged = true; rv = true; } } } return rv; } private void addSysTrackFile( File file ) { String errMsg = null; if( !file.exists() ) { errMsg = "Datei nicht gefunden"; } else if( !file.isFile() ) { errMsg = "Datei ist keine regul\u00E4re Datei"; } if( errMsg != null ) { BaseDlg.showErrorDlg( this, errMsg ); } else { this.fldSysTrackFileName.setFile( file ); this.btnSysTrackFileRemove.setEnabled( true ); } } private static String createEntryName( String fileName ) { StringBuilder buf = new StringBuilder( 12 ); boolean failed = false; boolean point = false; int nPre = 0; int nPost = 0; int len = fileName.length(); for( int i = 0; !failed && (i < len); i++ ) { char ch = Character.toUpperCase( fileName.charAt( i ) ); if( DiskUtil.isValidCPMFileNameChar( ch ) ) { if( !point && (nPre < 8) ) { buf.append( ch ); nPre++; } else if( point && (nPost < 3) ) { buf.append( ch ); nPost++; } else { failed = true; } } else if( ch == '.' ) { if( !point && (nPre >= 1) && (nPre <= 8) ) { buf.append( ch ); point = true; } else { failed = true; } } else { failed = true; } } return failed ? null : buf.toString(); } private void fireSelectRows( final int[] rowNums ) { final JTable table = this.table; EventQueue.invokeLater( new Runnable() { @Override public void run() { table.clearSelection(); for( int row : rowNums ) { table.addRowSelectionInterval( row, row ); } } } ); } private void fireSelectRowInterval( final int begRow, final int endRow ) { final JTable table = this.table; EventQueue.invokeLater( new Runnable() { @Override public void run() { try { int nRows = table.getRowCount(); if( (begRow >= 0) && (begRow < nRows) && (begRow <= endRow) ) { table.setRowSelectionInterval( begRow, Math.min( endRow, nRows -1 ) ); } } catch( IllegalArgumentException ex ) {} } } ); } private void pasteFiles( Transferable t ) { try { if( t != null ) { Object o = t.getTransferData( DataFlavor.javaFileListFlavor ); if( o != null ) { if( o instanceof Collection ) { int firstRowToSelect = this.table.getRowCount(); for( Object item : (Collection) o ) { if( item != null ) { File file = null; if( item instanceof File ) { file = (File) item; } else if( item instanceof String ) { file= new File( (String) item ); } if( file != null ) { if( !addFile( file ) ) { break; } } } } fireSelectRowInterval( firstRowToSelect, this.table.getRowCount() - 1 ); } } } } catch( IOException ex ) {} catch( UnsupportedFlavorException ex ) {} finally { updSelectAllEnabled(); } } private void updActionButtons() { boolean stateSelected = false; boolean stateDown = false; boolean stateUp = false; boolean fileTab = (this.tabbedPane.getSelectedIndex() == 0); if( fileTab ) { int[] rowNums = this.table.getSelectedRows(); if( rowNums != null ) { if( rowNums.length > 0 ) { stateSelected = true; Arrays.sort( rowNums ); if( (rowNums[ rowNums.length - 1 ] + 1) < this.tableModel.getRowCount() ) { stateDown = true; } if( rowNums[ 0 ] > 0 ) { stateUp = true; } } } } this.btnFileAdd.setEnabled( fileTab ); this.mnuFileRemove.setEnabled( stateSelected ); this.btnFileRemove.setEnabled( stateSelected ); this.btnFileDown.setEnabled( stateDown ); this.btnFileUp.setEnabled( stateUp ); this.mnuChangeAttrs.setEnabled( stateSelected ); this.mnuChangeUser.setEnabled( stateSelected ); } private void updBgColor() { Color color = this.table.getBackground(); JViewport vp = this.scrollPane.getViewport(); if( (color != null) && (vp != null) ) { vp.setBackground( color ); } } private void updPasteButton() { boolean state = false; if( this.clipboard != null ) { try { state = this.clipboard.isDataFlavorAvailable( DataFlavor.javaFileListFlavor ); } catch( IllegalStateException ex ) {} } this.mnuPaste.setEnabled( state ); } private void updSelectAllEnabled() { this.mnuSelectAll.setEnabled( this.table.getRowCount() > 0 ); } private void updStatusText() { String text = "Bereit"; int idx = this.tabbedPane.getSelectedIndex(); if( idx == 0 ) { long kbytes = 0; int nRows = this.tableModel.getRowCount(); for( int i = 0; i < nRows; i++ ) { FileEntry entry = this.tableModel.getRow( i ); if( entry != null ) { Long size = entry.getSize(); if( size != null ) { if( size.longValue() > 0 ) { long kb = size.longValue() / 1024L; if( (kb * 1024L) < size.longValue() ) { kb++; } kbytes += kb; } } } } StringBuilder buf = new StringBuilder( 64 ); if( nRows == 1 ) { buf.append( "1 Datei" ); } else { buf.append( nRows ); buf.append( " Dateien" ); } buf.append( " mit " ); buf.append( kbytes ); buf.append( " KByte hinzugef\u00FCgt" ); text = buf.toString(); } else if( idx == 1 ) { int sides = this.fmtSelectFld.getSides(); int cyls = this.fmtSelectFld.getCylinders(); int sysTracks = this.fmtSelectFld.getSysTracks(); int sectPerCyl = this.fmtSelectFld.getSectorsPerCylinder(); int sectorSize = this.fmtSelectFld.getSectorSize(); int kbytes = sides * cyls * sectPerCyl * sectorSize / 1024; if( sysTracks > 0 ) { text = String.format( "%d/%dK Diskettenformat eingestellt", sides * (cyls - sysTracks) * sectPerCyl * sectorSize / 1024, kbytes ); } else { text = String.format( "%dK Diskettenformat eingestellt", kbytes ); } } this.labelStatus.setText( text ); } private void updSysTrackFileFieldsEnabled() { boolean state = (this.fmtSelectFld.getSysTracks() > 0); this.labelSysTrackFile.setEnabled( state ); this.fldSysTrackFileName.setEnabled( state ); this.btnSysTrackFileSelect.setEnabled( state ); this.btnSysTrackFileRemove.setEnabled( state && (this.fldSysTrackFileName.getFile() != null) ); } private void updTitle() { String text = "JKCEMU CP/M-Diskettenabbilddatei erstellen"; if( this.lastOutFile != null ) { StringBuilder buf = new StringBuilder( 256 ); buf.append( text ); buf.append( ": " ); String fName = this.lastOutFile.getName(); if( fName != null ) { buf.append( fName ); } text = buf.toString(); } setTitle( text ); } }
lipro/jkcemu
src/jkcemu/disk/DiskImgCreateFrm.java
Java
gpl-3.0
40,900
/* * (c) 2009-2010 Jens Mueller * * Kleincomputer-Emulator * * Scanner zum Extrahieren der Zeilen und Seitenumbrueche * aus den Druckdaten */ package jkcemu.print; import java.lang.*; public class PrintDataScanner { private byte[] dataBytes; private int pos; public PrintDataScanner( byte[] dataBytes ) { this.dataBytes = dataBytes; this.pos = 0; } public boolean endReached() { return this.pos >= this.dataBytes.length; } public String readLine() { StringBuilder buf = null; while( this.pos < this.dataBytes.length ) { int b = ((int) this.dataBytes[ this.pos ]) & 0xFF; // Seitenumbruch if( b == 0x0C ) { break; } // Zeile vorhanden this.pos++; if( buf == null ) { buf = new StringBuilder(); } // Zeilenende? if( (b == 0x0A) || (b == 0x0D) || (b == 0x1E) ) { if( b == 0x0D ) { if( this.pos < this.dataBytes.length ) { if( this.dataBytes[ this.pos ] == 0x0A ) { this.pos++; } } } break; } if( (b != 0) && (b != 3) ) { buf.append( (char) b ); } } return buf != null ? buf.toString() : null; } public boolean skipFormFeed() { if( this.pos < this.dataBytes.length ) { if( this.dataBytes[ this.pos ] == 0x0C ) { this.pos++; return true; } } return false; } public boolean skipLine() { boolean rv = false; while( this.pos < this.dataBytes.length ) { int b = ((int) this.dataBytes[ this.pos ]) & 0xFF; if( b == 0x0C ) { break; } // Zeile vorhanden this.pos++; rv = true; // Zeilenende? if( (b == 0x0A) || (b == 0x0D) || (b == 0x1E) ) { if( b == 0x0D ) { if( this.pos < this.dataBytes.length ) { if( this.dataBytes[ this.pos ] == 0x0A ) { this.pos++; } } } break; } } return rv; } }
lipro/jkcemu
src/jkcemu/print/PrintDataScanner.java
Java
gpl-3.0
1,904
<?php $config->extension->apiRoot = 'http://www.zentao.net/extension-'; $config->extension->extPathes = array('module', 'bin', 'www', 'library', 'config');
isleon/zentao
module/extension/config.php
PHP
gpl-3.0
158
require 'rails_helper' RSpec.describe RankingsController, :type => :controller do before(:each) do create(:theme, id: 1, description: "Segurança") for i in 1..10 do create(:proposition, id: i) Proposition.find(i).themes << Theme.find_by(description: "Segurança") end create(:theme, id: 2, description: "Educação") for i in 11..30 do create(:proposition, id: i) Proposition.find(i).themes << Theme.find_by(description: "Educação") end create(:theme, id: 3, description: "Saúde") for i in 31..34 do create(:proposition, id: i) Proposition.find(i).themes << Theme.find_by(description: "Saúde") end create(:theme, id: 4, description: "Indústria, Comércio(até 1953)") for i in 35..40 create(:proposition, id: i) Proposition.find(i).themes << Theme.find_by(description: "Indústria, Comércio(até 1953)") end for i in 1..10 create(:theme, id: 4+i) create(:proposition, id: 40+i) Proposition.find(40+i).themes << Theme.find(4+i) end end describe "GET index" do it "render the index correctly" do get :index expect(response).to render_template("index") end it "returns @themes correctly" do expect(assigns(:themes)).not_to eq([]) end it "@selected_theme_id its null" do expect(@selected_theme_id).to be_nil end end describe "#order_themes" do it "return the themes ordered by propositions number" do theme = controller.order_themes(Theme.all) expect(theme[0].description).to eq("Educação") expect(theme[1].description).to eq("Segurança") expect(theme[2].description).to eq("Indústria, Comércio(até 1953)") expect(theme[3].description).to eq("Saúde") end end describe "#find_theme_id_by_params" do it "returns nil when the params is nil" do params = { nil: nil} id = controller.find_theme_id_by_params(params) expect(id).to be_nil end it "return the correct theme id when the params is passed" do params = { theme_id: "Indústria, Comércio(até 1953) (10)" } id = controller.find_theme_id_by_params(params) expect(id).to eq(4) end end describe "POST index" do it "return @theme_id correctly" do params = { theme_id: "Indústria, Comércio(até 1953) (10)" } post :index, params expect(response).to render_template("index") expect(assigns(:selected_theme_id)).not_to be_nil end end describe "#count_other_themes" do it "return the quantity of propositions of other themes" do controller.instance_variable_set(:@themes, controller.order_themes(Theme.all)) expect(controller.count_other_themes).to eq(4) end end end
vital-edu/espelho-politico
spec/controllers/rankings_controller_spec.rb
Ruby
gpl-3.0
2,805
/************************************************************************** This file is part of JahshakaVR, VR Authoring Toolkit http://www.jahshaka.com Copyright (c) 2016 GPLv3 Jahshaka LLC <coders@jahshaka.com> This is free software: you may copy, redistribute and/or modify it under the terms of the GPLv3 License For more information see the LICENSE file *************************************************************************/ #include "viewermaterial.h" #include "irisgl/src/graphics/texture2d.h" #include "irisgl/src/graphics/material.h" #include "irisgl/src/graphics/graphicsdevice.h" ViewerMaterial::ViewerMaterial() { createProgramFromShaderSource(":assets/shaders/viewer.vert", ":assets/shaders/viewer.frag"); this->setRenderLayer((int)iris::RenderLayer::Opaque); renderStates.rasterState = iris::RasterizerState::createCullNone(); } void ViewerMaterial::setTexture(iris::Texture2DPtr tex) { texture = tex; if(!!tex) this->addTexture("tex",tex); else this->removeTexture("tex"); } iris::Texture2DPtr ViewerMaterial::getTexture() { return texture; } void ViewerMaterial::begin(iris::GraphicsDevicePtr device, iris::ScenePtr scene) { Material::begin(device, scene); } void ViewerMaterial::end(iris::GraphicsDevicePtr device, iris::ScenePtr scene) { Material::end(device, scene); } ViewerMaterialPtr ViewerMaterial::create() { return ViewerMaterialPtr(new ViewerMaterial()); }
jahshaka/VR
src/editor/viewermaterial.cpp
C++
gpl-3.0
1,485
#ifndef STAN_MATH_PRIM_SCAL_PROB_NEG_BINOMIAL_LOG_HPP #define STAN_MATH_PRIM_SCAL_PROB_NEG_BINOMIAL_LOG_HPP #include <stan/math/prim/scal/meta/return_type.hpp> #include <stan/math/prim/scal/prob/neg_binomial_lpmf.hpp> namespace stan { namespace math { /** * @deprecated use <code>neg_binomial_lpmf</code> */ template <bool propto, typename T_n, typename T_shape, typename T_inv_scale> typename return_type<T_shape, T_inv_scale>::type neg_binomial_log(const T_n& n, const T_shape& alpha, const T_inv_scale& beta) { return neg_binomial_lpmf<propto, T_n, T_shape, T_inv_scale>(n, alpha, beta); } /** * @deprecated use <code>neg_binomial_lpmf</code> */ template <typename T_n, typename T_shape, typename T_inv_scale> inline typename return_type<T_shape, T_inv_scale>::type neg_binomial_log(const T_n& n, const T_shape& alpha, const T_inv_scale& beta) { return neg_binomial_lpmf<T_n, T_shape, T_inv_scale>(n, alpha, beta); } } } #endif
TomasVaskevicius/bouncy-particle-sampler
third_party/stan_math/stan/math/prim/scal/prob/neg_binomial_log.hpp
C++
gpl-3.0
1,173
'use strict'; // Users service used for communicating with the users REST endpoint angular.module('users').factory('Users', [ '$resource', function ($resource) { return $resource('users', {}, { update: { method: 'PUT' } }); } ]);
ogarling/targets-io
public/modules/users/services/users.client.service.js
JavaScript
gpl-3.0
239
# This file is dual licensed under the terms of the Apache License, Version # 2.0, and the BSD License. See the LICENSE file in the root of this repository # for complete details. from __future__ import absolute_import, division, print_function from cryptography import utils from cryptography.exceptions import ( AlreadyFinalized, UnsupportedAlgorithm, _Reasons ) from cryptography.hazmat.backends.interfaces import HashBackend from cryptography.hazmat.primitives import interfaces @utils.register_interface(interfaces.HashContext) class Hash(object): def __init__(self, algorithm, backend, ctx=None): if not isinstance(backend, HashBackend): raise UnsupportedAlgorithm( "Backend object does not implement HashBackend.", _Reasons.BACKEND_MISSING_INTERFACE ) if not isinstance(algorithm, interfaces.HashAlgorithm): raise TypeError("Expected instance of interfaces.HashAlgorithm.") self._algorithm = algorithm self._backend = backend if ctx is None: self._ctx = self._backend.create_hash_ctx(self.algorithm) else: self._ctx = ctx algorithm = utils.read_only_property("_algorithm") def update(self, data): if self._ctx is None: raise AlreadyFinalized("Context was already finalized.") if not isinstance(data, bytes): raise TypeError("data must be bytes.") self._ctx.update(data) def copy(self): if self._ctx is None: raise AlreadyFinalized("Context was already finalized.") return Hash( self.algorithm, backend=self._backend, ctx=self._ctx.copy() ) def finalize(self): if self._ctx is None: raise AlreadyFinalized("Context was already finalized.") digest = self._ctx.finalize() self._ctx = None return digest @utils.register_interface(interfaces.HashAlgorithm) class SHA1(object): name = "sha1" digest_size = 20 block_size = 64 @utils.register_interface(interfaces.HashAlgorithm) class SHA224(object): name = "sha224" digest_size = 28 block_size = 64 @utils.register_interface(interfaces.HashAlgorithm) class SHA256(object): name = "sha256" digest_size = 32 block_size = 64 @utils.register_interface(interfaces.HashAlgorithm) class SHA384(object): name = "sha384" digest_size = 48 block_size = 128 @utils.register_interface(interfaces.HashAlgorithm) class SHA512(object): name = "sha512" digest_size = 64 block_size = 128 @utils.register_interface(interfaces.HashAlgorithm) class RIPEMD160(object): name = "ripemd160" digest_size = 20 block_size = 64 @utils.register_interface(interfaces.HashAlgorithm) class Whirlpool(object): name = "whirlpool" digest_size = 64 block_size = 64 @utils.register_interface(interfaces.HashAlgorithm) class MD5(object): name = "md5" digest_size = 16 block_size = 64
CoderBotOrg/coderbotsrv
server/lib/cryptography/hazmat/primitives/hashes.py
Python
gpl-3.0
3,022
public class Circle extends Point { public double r; public Circle(double x, double y, double r) { super(x, y); this.r = r; } public double calArea() { return r * r * Math.PI; } public String getName() { return "Circle"; } }
McSinyx/hsg
usth/ICT2.2/labwork/5/Java/interface/Circle.java
Java
gpl-3.0
247
<?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/>. /** * Language file for 'badges' component * * @package core * @subpackage badges * @copyright 2012 onwards Totara Learning Solutions Ltd {@link http://www.totaralms.com/} * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later * @author Yuliya Bozhko <yuliya.bozhko@totaralms.com> */ $string['actions'] = 'Actions'; $string['activate'] = 'Enable access'; $string['activatesuccess'] = 'Access to the badges was successfully enabled.'; $string['addbadgecriteria'] = 'Add badge criteria'; $string['addcriteria'] = 'Add criteria'; $string['addcriteriatext'] = 'To start adding criteria, please select one of the options from the drop-down menu.'; $string['addcourse'] = 'Add courses'; $string['addcourse_help'] = 'Select all courses that should be added to this badge requirement. Hold CTRL key to select multiple items.'; $string['addtobackpack'] = 'Add to backpack'; $string['adminonly'] = 'This page is restricted to site administrators only.'; $string['after'] = 'after the date of issue.'; $string['aggregationmethod'] = 'Aggregation method'; $string['all'] = 'All'; $string['allmethod'] = 'All of the selected conditions are met'; $string['allmethodactivity'] = 'All of the selected activities are complete'; $string['allmethodcourseset'] = 'All of the selected courses are complete'; $string['allmethodmanual'] = 'All of the selected roles award the badge'; $string['allmethodprofile'] = 'All of the selected profile fields have been completed'; $string['allowcoursebadges'] = 'Enable course badges'; $string['allowcoursebadges_desc'] = 'Allow badges to be created and awarded in the course context.'; $string['allowexternalbackpack'] = 'Enable connection to external backpacks'; $string['allowexternalbackpack_desc'] = 'Allow users to set up connections and display badges from their external backpack providers. Note: It is recommended to leave this option disabled if the website cannot be accessed from the Internet (e.g. because of the firewall).'; $string['any'] = 'Any'; $string['anymethod'] = 'Any of the selected conditions is met'; $string['anymethodactivity'] = 'Any of the selected activities is complete'; $string['anymethodcourseset'] = 'Any of the selected courses is complete'; $string['anymethodmanual'] = 'Any of the selected roles awards the badge'; $string['anymethodprofile'] = 'Any of the selected profile fields has been completed'; $string['archivebadge'] = 'Would you like to delete badge \'{$a}\', but keep existing issued badges?'; $string['archiveconfirm'] = 'Delete and keep existing issued badges'; $string['archivehelp'] = '<p>This option means that the badge will be marked as "retired" and will no longer appear in the list of badges. Users will no longer be able to earn this badge, however existing badge recipients will still be able to display this badge on their profile page and push it to their external backpacks.</p> <p>If you would like your users to retain access to the earned badges it is important to select this option instead of fully deleting badges.</p>'; $string['attachment'] = 'Attach badge to message'; $string['attachment_help'] = 'If enabled, an issued badge file will be attached to the recipient\'s email for download. (Attachments must be enabled in Site administration > Plugins > Message outputs > Email to use this option.)'; $string['award'] = 'Award badge'; $string['awardedtoyou'] = 'Issued to me'; $string['awardoncron'] = 'Access to the badges was successfully enabled. Too many users can instantly earn this badge. To ensure site performance, this action will take some time to process.'; $string['awards'] = 'Recipients'; $string['backpackavailability'] = 'External badge verification'; $string['backpackavailability_help'] = 'For badge recipients to be able to prove they earned their badges from you, an external backpack service should be able to access your site and verify badges issued from it. Your site does not currently appear to be accessible, which means that badges you have already issued or will issue in the future cannot be verified. **Why am I seeing this message?** It may be that your firewall prevents access from users outside your network, your site is password protected, or you are running the site on a computer that is not available from the Internet (such as a local development machine). **Is this a problem?** You should fix this issue on any production site where you are planning to issue badges, otherwise the recipients will not be able to prove they earned their badges from you. If your site is not yet live you can create and issue test badges, as long as the site is accessible before you go live. **What if I can\'t make my whole site publicly accessible?** The only URL required for verification is [your-site-url]/badges/assertion.php so if you are able to modify your firewall to allow external access to that file, badge verification will still work.'; $string['backpackbadges'] = 'You have {$a->totalbadges} badge(s) displayed from {$a->totalcollections} collection(s). <a href="mybackpack.php">Change backpack settings</a>.'; $string['backpackconnection'] = 'Backpack connection'; $string['backpackconnection_help'] = 'This page allows you to set up connection to an external backpack provider. Connecting to a backpack lets you display external badges within this site and push badges earned here to your backpack. Currently, only <a href="http://backpack.openbadges.org">Mozilla OpenBadges Backpack</a> is supported. You need to sign up for a backpack service before trying to set up backpack connection on this page.'; $string['backpackdetails'] = 'Backpack settings'; $string['backpackemail'] = 'Email address'; $string['backpackemail_help'] = 'The email address associated with your backpack. While you are connected, any badges earned on this site will be associated with this email address.'; $string['personaconnection'] = 'Sign in with your email'; $string['personaconnection_help'] = 'Persona is a system for identifying yourself across the web, using an email address that you own. The Open Badges backpack uses Persona as a login system, so to be able to connect to a backpack you with need a Persona account. For more information about Persona visit <a href="https://login.persona.org/about">https://login.persona.org/about</a>.'; $string['backpackimport'] = 'Badge import settings'; $string['backpackimport_help'] = 'After backpack connection is successfully established, badges from your backpack can be displayed on your "My Badges" page and your profile page. In this area, you can select collections of badges from your backpack that you would like to display in your profile.'; $string['badgedetails'] = 'Badge details'; $string['badgeimage'] = 'Image'; $string['badgeimage_help'] = 'This is an image that will be used when this badge is issued. To add a new image, browse and select an image (in JPG or PNG format) then click "Save changes". The image will be cropped to a square and resized to match badge image requirements. '; $string['badgeprivacysetting'] = 'Badge privacy settings'; $string['badgeprivacysetting_help'] = 'Badges you earn can be displayed on your account profile page. This setting allows you to automatically set the visibility of the newly earned badges. You can still control individual badge privacy settings on your "My badges" page.'; $string['badgeprivacysetting_str'] = 'Automatically show badges I earn on my profile page'; $string['badgesalt'] = 'Salt for hashing the recipient\'s email address'; $string['badgesalt_desc'] = 'Using a hash allows backpack services to confirm the badge earner without having to expose their email address. This setting should only use numbers and letters. Note: For recipient verification purposes, please avoid changing this setting once you start issuing badges.'; $string['badgesdisabled'] = 'Badges are not enabled on this site.'; $string['badgesearned'] = 'Number of badges earned: {$a}'; $string['badgesettings'] = 'Badges settings'; $string['badgestatus_0'] = 'Not available to users'; $string['badgestatus_1'] = 'Available to users'; $string['badgestatus_2'] = 'Not available to users'; $string['badgestatus_3'] = 'Available to users'; $string['badgestatus_4'] = 'Archived'; $string['badgestoearn'] = 'Number of badges available: {$a}'; $string['badgesview'] = 'Course badges'; $string['badgeurl'] = 'Issued badge link'; $string['bawards'] = 'Recipients ({$a})'; $string['bcriteria'] = 'Criteria'; $string['bdetails'] = 'Edit details'; $string['bmessage'] = 'Message'; $string['boverview'] = 'Overview'; $string['bydate'] = ' complete by'; $string['clearsettings'] = 'Clear settings'; $string['completionnotenabled'] = 'Course completion is not enabled for this course, so it cannot be included in badge criteria. Course completion may be enabled in the course settings.'; $string['completioninfo'] = 'This badge was issued for completing: '; $string['configenablebadges'] = 'When enabled, this feature lets you create badges and award them to site users.'; $string['configuremessage'] = 'Badge message'; $string['connect'] = 'Connect'; $string['connected'] = 'Connected'; $string['connecting'] = 'Connecting...'; $string['contact'] = 'Contact'; $string['contact_help'] = 'An email address associated with the badge issuer.'; $string['copyof'] = 'Copy of {$a}'; $string['coursebadgesdisabled'] = 'Course badges are not enabled on this site.'; $string['coursecompletion'] = 'Users must complete this course.'; $string['coursebadges'] = 'Badges'; $string['create'] = 'New badge'; $string['createbutton'] = 'Create badge'; $string['creatorbody'] = '<p>{$a->user} has completed all badge requirements and has been awarded the badge. View issued badge at {$a->link} </p>'; $string['creatorsubject'] = '\'{$a}\' has been awarded!'; $string['criteriasummary'] = 'Criteria summary'; $string['criteriacreated'] = 'Badge criteria successfully created'; $string['criteriadeleted'] = 'Badge criteria successfully deleted'; $string['criteriaupdated'] = 'Badge criteria successfully updated'; $string['criteria_descr'] = 'Users are awarded this badge when they complete the following requirement:'; $string['criteria_descr_bydate'] = ' by <em>{$a}</em> '; $string['criteria_descr_grade'] = ' with minimum grade of <em>{$a}</em> '; $string['criteria_descr_short0'] = 'Complete <strong>{$a}</strong> of: '; $string['criteria_descr_short1'] = 'Complete <strong>{$a}</strong> of: '; $string['criteria_descr_short2'] = 'Awarded by <strong>{$a}</strong> of: '; $string['criteria_descr_short4'] = 'Complete the course '; $string['criteria_descr_short5'] = 'Complete <strong>{$a}</strong> of: '; $string['criteria_descr_short6'] = 'Complete <strong>{$a}</strong> of: '; $string['criteria_descr_single_short1'] = 'Complete: '; $string['criteria_descr_single_short2'] = 'Awarded by: '; $string['criteria_descr_single_short4'] = 'Complete the course '; $string['criteria_descr_single_short5'] = 'Complete: '; $string['criteria_descr_single_short6'] = 'Complete: '; $string['criteria_descr_single_1'] = 'The following activity has to be completed:'; $string['criteria_descr_single_2'] = 'This badge has to be awarded by a user with the following role:'; $string['criteria_descr_single_4'] = 'Users must complete the course'; $string['criteria_descr_single_5'] = 'The following course has to be completed:'; $string['criteria_descr_single_6'] = 'The following user profile field has to be completed:'; $string['criteria_descr_0'] = 'Users are awarded this badge when they complete <strong>{$a}</strong> of the listed requirements.'; $string['criteria_descr_1'] = '<strong>{$a}</strong> of the following activities are completed:'; $string['criteria_descr_2'] = 'This badge has to be awarded by the users with <strong>{$a}</strong> of the following roles:'; $string['criteria_descr_4'] = 'Users must complete the course'; $string['criteria_descr_5'] = '<strong>{$a}</strong> of the following courses have to be completed:'; $string['criteria_descr_6'] = '<strong>{$a}</strong> of the following user profile fields have to be completed:'; $string['criteria_0'] = 'This badge is awarded when...'; $string['criteria_1'] = 'Activity completion'; $string['criteria_1_help'] = 'Allows a badge to be awarded to users based on the completion of a set of activities within a course.'; $string['criteria_2'] = 'Manual issue by role'; $string['criteria_2_help'] = 'Allows a badge to be awarded manually by users who have a particular role within the site or course.'; $string['criteria_3'] = 'Social participation'; $string['criteria_3_help'] = 'Social'; $string['criteria_4'] = 'Course completion'; $string['criteria_4_help'] = 'Allows a badge to be awarded to users who have completed the course. This criterion can have additional parameters such as minimum grade and date of course completion.'; $string['criteria_5'] = 'Completing a set of courses'; $string['criteria_5_help'] = 'Allows a badge to be awarded to users who have completed a set of courses. Each course can have additional parameters such as minimum grade and date of course completion. '; $string['criteria_6'] = 'Profile completion'; $string['criteria_6_help'] = 'Allows a badge to be awarded to users for completing certain fields in their profile. You can select from default and custom profile fields that are available to users. '; $string['criterror'] = 'Current parameters issues'; $string['criterror_help'] = 'This fieldset shows all parameters that were initially added to this badge requirement but are no longer available. It is recommended that you un-check such parameters to make sure that users can earn this badge in the future.'; $string['currentimage'] = 'Current image'; $string['currentstatus'] = 'Current status: '; $string['dateawarded'] = 'Date issued'; $string['dateearned'] = 'Date: {$a}'; $string['day'] = 'Day(s)'; $string['deactivate'] = 'Disable access'; $string['deactivatesuccess'] = 'Access to the badges was successfully disabled.'; $string['defaultissuercontact'] = 'Default badge issuer contact details'; $string['defaultissuercontact_desc'] = 'An email address associated with the badge issuer.'; $string['defaultissuername'] = 'Default badge issuer name'; $string['defaultissuername_desc'] = 'Name of the issuing agent or authority.'; $string['delbadge'] = 'Would you like to delete badge \'{$a}\' and remove all existing issued badges?'; $string['delconfirm'] = 'Delete and remove existing issued badges'; $string['deletehelp'] = '<p>Fully deleting a badge means that all its information and criteria records will be permanently removed. Users who have earned this badge will no longer be able to access it and display it on their profile pages.</p> <p>Note: Users who have earned this badge and have already pushed it to their external backpack, will still have this badge in their external backpack. However, they will not be able to access criteria and evidence pages linking back to this web site.</p>'; $string['delcritconfirm'] = 'Are you sure that you want to delete this criterion?'; $string['delparamconfirm'] = 'Are you sure that you want to delete this parameter?'; $string['description'] = 'Description'; $string['disconnect'] = 'Disconnect'; $string['donotaward'] = 'Currently, this badge is not active, so it cannot be awarded to users. If you would like to award this badge, please set its status to active.'; $string['editsettings'] = 'Edit settings'; $string['enablebadges'] = 'Enable badges'; $string['error:backpackdatainvalid'] = 'The data return from the backpack was invalid.'; $string['error:backpackemailnotfound'] = 'The email \'{$a}\' is not associated with a backpack. You need to <a href="http://backpack.openbadges.org">create a backpack</a> for that account or sign in with another email address.'; $string['error:backpacknotavailable'] = 'Your site is not accessible from the Internet, so any badges issued from this site cannot be verified by external backpack services.'; $string['error:backpackloginfailed'] = 'You could not be connected to an external backpack for the following reason: {$a}'; $string['error:backpackproblem'] = 'There was a problem connecting to your backpack service provider. Please try again later.'; $string['error:badjson'] = 'The connection attempt returned invalid data.'; $string['error:cannotact'] = 'Cannot activate the badge. '; $string['error:cannotawardbadge'] = 'Cannot award badge to a user.'; $string['error:connectionunknownreason'] = 'The connection was unsuccessful but no reason was given.'; $string['error:clone'] = 'Cannot clone the badge.'; $string['error:duplicatename'] = 'Badge with such name already exists in the system.'; $string['error:externalbadgedoesntexist'] = 'Badge not found'; $string['error:guestuseraccess'] = 'You are currently using guest access. To see badges you need to log in with your user account.'; $string['error:invalidbadgeurl'] = 'Invalid badge issuer URL format.'; $string['error:invalidcriteriatype'] = 'Invalid criteria type.'; $string['error:invalidexpiredate'] = 'Expiry date has to be in the future.'; $string['error:invalidexpireperiod'] = 'Expiry period cannot be negative or equal 0.'; $string['error:noactivities'] = 'There are no activities with completion criteria enabled in this course.'; $string['error:noassertion'] = 'No assertion was returned by Persona. You may have closed the dialog before completing the login process.'; $string['error:nocourses'] = 'Course completion is not enabled for any of the courses in this site, so none can be displayed. Course completion may be enabled in the course settings.'; $string['error:nogroups'] = '<p>There are no public collections of badges available in your backpack. </p> <p>Only public collections are shown, <a href="http://backpack.openbadges.org">visit your backpack</a> to create some public collections.</p>'; $string['error:nopermissiontoview'] = 'You have no permissions to view badge recipients'; $string['error:nosuchbadge'] = 'Badge with id {$a} does not exist.'; $string['error:nosuchcourse'] = 'Warning: This course is no longer available.'; $string['error:nosuchfield'] = 'Warning: This user profile field is no longer available.'; $string['error:nosuchmod'] = 'Warning: This activity is no longer available.'; $string['error:nosuchrole'] = 'Warning: This role is no longer available.'; $string['error:nosuchuser'] = 'User with this email address does not have an account with the current backpack provider.'; $string['error:notifycoursedate'] = 'Warning: Badges associated with course and activity completions will not be issued until the course start date.'; $string['error:parameter'] = 'Warning: At least one parameter should be selected to ensure correct badge issuing workflow.'; $string['error:personaneedsjs'] = 'Currently, Javascript is required to connect to your backpack. If you can, enable Javascript and reload the page.'; $string['error:requesttimeout'] = 'The connection request timed out before it could complete.'; $string['error:requesterror'] = 'The connection request failed (error code {$a}).'; $string['error:save'] = 'Cannot save the badge.'; $string['error:userdeleted'] = '{$a->user} (This user no longer exists in {$a->site})'; $string['evidence'] = 'Evidence'; $string['existingrecipients'] = 'Existing badge recipients'; $string['expired'] = 'Expired'; $string['expiredate'] = 'This badge expires on {$a}.'; $string['expireddate'] = 'This badge expired on {$a}.'; $string['expireperiod'] = 'This badge expires {$a} day(s) after being issued.'; $string['expireperiodh'] = 'This badge expires {$a} hour(s) after being issued.'; $string['expireperiodm'] = 'This badge expires {$a} minute(s) after being issued.'; $string['expireperiods'] = 'This badge expires {$a} second(s) after being issued.'; $string['expirydate'] = 'Expiry date'; $string['expirydate_help'] = 'Optionally, badges can expire on a specific date, or the date can be calculated based on the date when the badge was issued to a user. '; $string['externalconnectto'] = 'To display external badges you need to <a href="{$a}">connect to a backpack</a>.'; $string['externalbadges'] = 'My badges from other web sites'; $string['externalbadgesp'] = 'Badges from other web sites:'; $string['externalbadges_help'] = 'This area displays badges from your external backpack.'; $string['fixed'] = 'Fixed date'; $string['hiddenbadge'] = 'Unfortunately, the badge owner has not made this information available.'; $string['issuedbadge'] = 'Issued badge information'; $string['issuancedetails'] = 'Badge expiry'; $string['issuerdetails'] = 'Issuer details'; $string['issuername'] = 'Issuer name'; $string['issuername_help'] = 'Name of the issuing agent or authority.'; $string['issuerurl'] = 'Issuer URL'; $string['localconnectto'] = 'To share these badges outside this web site you need to <a href="{$a}">connect to a backpack</a>.'; $string['localbadges'] = 'My badges from {$a} web site'; $string['localbadgesh'] = 'My badges from this web site'; $string['localbadgesh_help'] = 'All badges earned within this web site by completing courses, course activities, and other requirements. You can manage your badges here by making them public or private for your profile page. You can download all of your badges or each badge separately and save them on your computer. Downloaded badges can be added to your external backpack service.'; $string['localbadgesp'] = 'Badges from {$a}:'; $string['makeprivate'] = 'Make private'; $string['makepublic'] = 'Make public'; $string['managebadges'] = 'Manage badges'; $string['message'] = 'Message body'; $string['messagebody'] = '<p>You have been awarded the badge "%badgename%"!</p> <p>More information about this badge can be found at %badgelink%.</p> <p>You can manage and download the badge from {$a}.</p>'; $string['messagesubject'] = 'Congratulations! You just earned a badge!'; $string['method'] = 'This criterion is complete when...'; $string['mingrade'] = 'Minimum grade required'; $string['month'] = 'Month(s)'; $string['mybadges'] = 'My badges'; $string['mybackpack'] = 'My backpack settings'; $string['never'] = 'Never'; $string['newbadge'] = 'Add a new badge'; $string['newimage'] = 'New image'; $string['noawards'] = 'This badge has not been earned yet.'; $string['nobackpack'] = 'There is no backpack service connected to this account.<br/>'; $string['nobackpackbadges'] = 'There are no badges in the collections you have selected. <a href="mybackpack.php">Add more collections</a>.'; $string['nobackpackcollections'] = 'No badge collections have been selected. <a href="mybackpack.php">Add collections</a>.'; $string['nobadges'] = 'There are no badges available.'; $string['nocriteria'] = 'Criteria for this badge have not been set up yet.'; $string['noexpiry'] = 'This badge does not have an expiry date.'; $string['noparamstoadd'] = 'There are no additional parameters available to add to this badge requirement.'; $string['notacceptedrole'] = 'Your current role assignment is not among the roles that can manually issue this badge.<br/> If you would like to see users who have already earned this badge, you can visit {$a} page. '; $string['notconnected'] = 'Not connected'; $string['nothingtoadd'] = 'There are no available criteria to add.'; $string['notification'] = 'Notify badge creator'; $string['notification_help'] = 'This setting manages notifications sent to a badge creator to let them know that the badge has been issued. The following options are available: * **NEVER** – Do not send notifications. * **EVERY TIME** – Send a notification every time this badge is awarded. * **DAILY** – Send notifications once a day. * **WEEKLY** – Send notifications once a week. * **MONTHLY** – Send notifications once a month.'; $string['notifydaily'] = 'Daily'; $string['notifyevery'] = 'Every time'; $string['notifymonthly'] = 'Monthly'; $string['notifyweekly'] = 'Weekly'; $string['numawards'] = 'This badge has been issued to <a href="{$a->link}">{$a->count}</a> user(s).'; $string['numawardstat'] = 'This badge has been issued {$a} user(s).'; $string['overallcrit'] = 'of the selected criteria are complete.'; $string['potentialrecipients'] = 'Potential badge recipients'; $string['recipients'] = 'Badge recipients'; $string['recipientdetails'] = 'Recipient details'; $string['recipientidentificationproblem'] = 'Cannot find a recipient of this badge among the existing users.'; $string['recipientvalidationproblem'] = 'Current user cannot be verified as a recipient of this badge.'; $string['relative'] = 'Relative date'; $string['requiredcourse'] = 'At least one course should be added to the courseset criterion.'; $string['reviewbadge'] = 'Changes in badge access'; $string['reviewconfirm'] = '<p>This will make your badge visible to users and allow them to start earning it.</p> <p>It is possible that some users already meet this badge\'s criteria and will be issued this badge immediately after you enable it.</p> <p>Once a badge has been issued it will be <strong>locked</strong> - certain settings including the criteria and expiry settings can no longer be changed.</p> <p>Are you sure you want to enable access to the badge \'{$a}\'?</p>'; $string['save'] = 'Save'; $string['searchname'] = 'Search by name'; $string['selectaward'] = 'Please select the role you would like to use to award this badge: '; $string['selectgroup_end'] = 'Only public collections are shown, <a href="http://backpack.openbadges.org">visit your backpack</a> to create more public collections.'; $string['selectgroup_start'] = 'Select collections from your backpack to display on this site:'; $string['selecting'] = 'With selected badges...'; $string['setup'] = 'Set up connection'; $string['signinwithyouremail'] = 'Sign in with your email'; $string['sitebadges'] = 'Site badges'; $string['sitebadges_help'] = 'Site badges can only be awarded to users for site-related activities. These include completing a set of courses or parts of user profiles. Site badges can also be issued manually by one user to another. Badges for course-related activities must be created at the course level. Course badges can be found under Course Administration > Badges.'; $string['statusmessage_0'] = 'This badge is currently not available to users. Enable access if you want users to earn this badge. '; $string['statusmessage_1'] = 'This badge is currently available to users. Disable access to make any changes. '; $string['statusmessage_2'] = 'This badge is currently not available to users, and its criteria are locked. Enable access if you want users to earn this badge. '; $string['statusmessage_3'] = 'This badge is currently available to users, and its criteria are locked. '; $string['statusmessage_4'] = 'This badge is currently archived.'; $string['status'] = 'Badge status'; $string['status_help'] = 'Status of a badge determines its behaviour in the system: * **AVAILABLE** – Means that this badge can be earned by users. While a badge is available to users, its criteria cannot be modified. * **NOT AVAILABLE** – Means that this badge is not available to users and cannot be earned or manually issued. If such badge has never been issued before, its criteria can be changed. Once a badge has been issued to at least one user, it automatically becomes **LOCKED**. Locked badges can still be earned by users, but their criteria can no longer be changed. If you need to modify details or criteria of a locked badge, you can duplicate this badge and make all the required changes. *Why do we lock badges?* We want to make sure that all users complete the same requirements to earn a badge. Currently, it is not possible to revoke badges. If we allowed badges requirements to be modified all the time, we would most likely end up with users having the same badge for meeting completely different requirements.'; $string['subject'] = 'Message subject'; $string['variablesubstitution'] = 'Variable substitution in messages.'; $string['variablesubstitution_help'] = 'In a badge message, certain variables can be inserted into the subject and/or body of a message so that they will be replaced with real values when the message is sent. The variables should be inserted into the text exactly as they are shown below. The following variables can be used: %badgename% : This will be replaced by the badge\'s full name. %username% : This will be replaced by the recipient\'s full name. %badgelink% : This will be replaced by the public URL with information about the issued badge.'; $string['viewbadge'] = 'View issued badge'; $string['visible'] = 'Visible'; $string['warnexpired'] = ' (This badge has expired!)'; $string['year'] = 'Year(s)'; // Deprecated since Moodle 2.8. $string['hidden'] = 'Hidden';
tiennm3333/moodle_course_generation
lang/en/badges.php
PHP
gpl-3.0
29,351
package hello; import org.springframework.messaging.handler.annotation.MessageMapping; import org.springframework.messaging.handler.annotation.SendTo; import org.springframework.stereotype.Controller; @Controller public class GreetingController { @MessageMapping("/hello") @SendTo("/topic/greetings") public Greeting greeting(HelloMessage message) throws Exception { Thread.sleep(3000); // simulated delay return new Greeting("Hello, " + message.getName() + "!"); } }
dbolshak/websocket
src/main/java/hello/GreetingController.java
Java
gpl-3.0
505
package io.swagger.wes.api; import com.fasterxml.jackson.databind.util.ISO8601DateFormat; import com.fasterxml.jackson.databind.util.ISO8601Utils; import java.text.FieldPosition; import java.util.Date; public class RFC3339DateFormat extends ISO8601DateFormat { // Same as ISO8601DateFormat but serializing milliseconds. @Override public StringBuffer format(Date date, StringBuffer toAppendTo, FieldPosition fieldPosition) { String value = ISO8601Utils.format(date, true); toAppendTo.append(value); return toAppendTo; } }
Consonance/consonance
consonance-webservice/src/main/java/io/swagger/wes/api/RFC3339DateFormat.java
Java
gpl-3.0
565
using FluentMigrator; using NzbDrone.Core.Datastore.Migration.Framework; namespace NzbDrone.Core.Datastore.Migration { [Migration(63)] public class add_remotepathmappings : NzbDroneMigrationBase { protected override void MainDbUpgrade() { Create.TableForModel("RemotePathMappings") .WithColumn("Host").AsString() .WithColumn("RemotePath").AsString() .WithColumn("LocalPath").AsString(); } } }
jamesmacwhite/Radarr
src/NzbDrone.Core/Datastore/Migration/063_add_remotepathmappings.cs
C#
gpl-3.0
503
namespace FalloutSnip.UI.Forms { using System; using System.Collections.Generic; using System.ComponentModel; using System.Globalization; using System.Linq; using System.Windows.Forms; using FalloutSnip.Domain.Data.Strings; using FalloutSnip.Domain.Model; using FalloutSnip.Framework.Collections; using FalloutSnip.Properties; using Settings = FalloutSnip.Domain.Services.Folders; public partial class StringsEditor : Form { private readonly List<StringHolder> addStrings = new List<StringHolder>(); private readonly List<StringHolder> remStrings = new List<StringHolder>(); private readonly AdvancedList<StringHolder> strings = new AdvancedList<StringHolder>(); private readonly List<StringHolder> updateStrings = new List<StringHolder>(); public StringsEditor() { this.InitializeComponent(); Icon = Resources.fosnip; this.cboType.DataSource = Enum.GetNames(typeof(LocalizedStringFormat)); this.cboType.SelectedItem = LocalizedStringFormat.Base.ToString(); this.listStrings.DataSource = this.strings; this.listStrings.AddBindingColumn("ID", "ID", 80, new Func<StringHolder, string>(a => a.ID.ToString("X8"))); this.listStrings.AddBindingColumn("Plugin", "Source", 80, new Func<StringHolder, string>(a => a.Plugin.Name)); this.listStrings.AddBindingColumn("Format", "Format", 50, HorizontalAlignment.Center); this.listStrings.AddBindingColumn("Value", "Value", 500); } public Plugin[] Plugins { get; set; } public void Reload(Plugin[] plugins) { this.Plugins = plugins; this.listStrings.DataSource = null; this.strings.Clear(); this.addStrings.Clear(); this.remStrings.Clear(); this.updateStrings.Clear(); var strPlugins = new List<string>(); foreach (var plugin in this.Plugins) { strPlugins.Add(plugin.Name); } this.cboPlugins.DataSource = strPlugins; this.cboPlugins.SelectedIndex = 0; this.PopulateStrings(); this.listStrings.DataSource = this.strings; this.FitColumns(); this.UpdateStatusBar(); } private void ApplyChanges() { foreach (var change in this.remStrings) { LocalizedStringDict dict = this.GetStringDict(change.Plugin, change.Format); if (dict != null) { dict.Remove(change.ID); change.Plugin.StringsDirty = true; } } foreach (var change in this.addStrings) { LocalizedStringDict dict = this.GetStringDict(change.Plugin, change.Format); if (dict != null) { dict[change.ID] = change.Value; change.Plugin.StringsDirty = true; } } foreach (var change in this.updateStrings) { LocalizedStringDict dict = this.GetStringDict(change.Plugin, change.Format); if (dict != null) { dict[change.ID] = change.Value; change.Plugin.StringsDirty = true; } } this.UpdateStatusBar(); } private void FitColumns() { Application.DoEvents(); // handle outstanding events then do column sizing this.listStrings.AutoFitColumnHeaders(); } private LocalizedStringDict GetStringDict(Plugin plugin, LocalizedStringFormat format) { LocalizedStringDict strings = null; switch (format) { case LocalizedStringFormat.Base: strings = plugin.Strings; break; case LocalizedStringFormat.DL: strings = plugin.DLStrings; break; case LocalizedStringFormat.IL: strings = plugin.ILStrings; break; } return strings; } private void PopulateStrings() { if (this.Plugins == null) { return; } foreach (var plugin in this.Plugins) { foreach (var kvp in plugin.Strings) { this.strings.Add(new StringHolder { ID = kvp.Key, Plugin = plugin, Value = kvp.Value, Format = LocalizedStringFormat.Base }); } foreach (var kvp in plugin.ILStrings) { this.strings.Add(new StringHolder { ID = kvp.Key, Plugin = plugin, Value = kvp.Value, Format = LocalizedStringFormat.IL }); } foreach (var kvp in plugin.DLStrings) { this.strings.Add(new StringHolder { ID = kvp.Key, Plugin = plugin, Value = kvp.Value, Format = LocalizedStringFormat.DL }); } } } private void ResetEntry() { Plugin plugin; if (!this.TryGetCurrentPlugin(out plugin)) { this.txtID.Text = string.Empty; this.txtString.Text = string.Empty; } else { LocalizedStringFormat format; if (!this.TryGetCurrentFormat(out format)) { this.txtID.Text = string.Empty; this.txtString.Text = string.Empty; } else { LocalizedStringDict strings = this.GetStringDict(plugin, format); if (strings != null) { if (strings.Count == 0) { this.txtID.Text = 1.ToString("X8"); this.txtString.Text = string.Empty; } else { uint max = strings.Max(a => a.Key); this.txtID.Text = (max + 1).ToString("X8"); this.txtString.Text = string.Empty; } } } } } private void SetSelectedItem(StringHolder str) { str.ID = str.ID; this.txtID.Text = str.ID.ToString("X8"); this.txtString.Text = str.Value; this.cboPlugins.SelectedItem = str.Plugin.Name; this.cboType.SelectedItem = str.Format.ToString(); } private void StringsEditor_FormClosing(object sender, FormClosingEventArgs e) { Services.Settings.SetWindowPosition("StringEditor", this); } private void StringsEditor_Load(object sender, EventArgs e) { Services.Settings.GetWindowPosition("StringEditor", this); this.Reload(this.Plugins); } private void StringsEditor_ResizeEnd(object sender, EventArgs e) { this.listStrings.AutoFitColumnHeaders(); } private bool TryGetCurrentFormat(out LocalizedStringFormat format) { format = (LocalizedStringFormat)Enum.Parse(typeof(LocalizedStringFormat), this.cboType.SelectedItem.ToString(), true); return true; } private bool TryGetCurrentID(out uint uiID) { uiID = 0; string strID = this.txtID.Text; if (string.IsNullOrEmpty(strID)) { return false; } return uint.TryParse(strID, NumberStyles.HexNumber, null, out uiID); } private bool TryGetCurrentPlugin(out Plugin plugin) { string pluginName = this.cboPlugins.SelectedItem.ToString(); plugin = this.Plugins.FirstOrDefault(a => a.Name == pluginName); return plugin != null; } private void UpdateStatusBar() { } private void btnAddString_Click(object sender, EventArgs e) { uint uiID; LocalizedStringFormat format; Plugin plugin; string text = this.txtString.Text; if (!this.TryGetCurrentID(out uiID)) { MessageBox.Show(this, "ID Field is invalid", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error); return; } if (!this.TryGetCurrentFormat(out format)) { MessageBox.Show(this, "Format is invalid", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error); return; } if (!this.TryGetCurrentPlugin(out plugin)) { MessageBox.Show(this, "Plugin is invalid", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error); return; } bool doResize = this.strings.Count == 0; StringHolder str = this.strings.FirstOrDefault(a => (a.ID == uiID && a.Plugin.Equals(plugin) && a.Format == format)); if (str == null) { str = new StringHolder { ID = uiID, Plugin = plugin, Value = text, Format = format }; this.strings.Add(str); } StringHolder addStr = this.addStrings.FirstOrDefault(a => (a.ID == uiID && a.Plugin.Equals(plugin) && a.Format == format)); if (addStr == null) { this.addStrings.Add(str); } if (doResize) { this.FitColumns(); } this.UpdateStatusBar(); } private void btnApply_Click(object sender, EventArgs e) { this.ApplyChanges(); } private void btnDeleteString_Click(object sender, EventArgs e) { uint uiID; LocalizedStringFormat format; Plugin plugin; string text = this.txtString.Text; if (!this.TryGetCurrentID(out uiID)) { MessageBox.Show(this, "ID Field is invalid", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error); return; } if (!this.TryGetCurrentFormat(out format)) { MessageBox.Show(this, "Format is invalid", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error); return; } if (!this.TryGetCurrentPlugin(out plugin)) { MessageBox.Show(this, "Plugin is invalid", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error); return; } bool doResize = this.strings.Count == 0; StringHolder str = this.strings.FirstOrDefault(a => (a.ID == uiID && a.Plugin.Equals(plugin) && a.Format == format)); if (str != null) { this.strings.Remove(str); } StringHolder remStr = this.remStrings.FirstOrDefault(a => (a.ID == uiID && a.Plugin.Equals(plugin) && a.Format == format)); if (remStr == null) { this.remStrings.Add(str); } if (doResize) { this.FitColumns(); } this.UpdateStatusBar(); } private void btnEditString_Click(object sender, EventArgs e) { using (var editor = new MultilineStringEditor()) { editor.Text = this.txtString.Text; DialogResult result = editor.ShowDialog(this); if (result == DialogResult.OK) { this.txtString.Text = editor.Text; } } } private void btnLookup_Click(object sender, EventArgs e) { string strID = this.txtID.Text; if (string.IsNullOrEmpty(strID)) { MessageBox.Show(this, "ID Field is empty. Please specify a string ID to find.", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error); return; } uint uiID; if (!uint.TryParse(strID, NumberStyles.HexNumber, null, out uiID)) { MessageBox.Show(this, "Unable to parse string id", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error); } else { StringHolder holder = this.strings.FirstOrDefault(a => a.ID == uiID); if (holder != null) { this.SetSelectedItem(holder); } } } private void btnNewItem_Click(object sender, EventArgs e) { this.ResetEntry(); } private void button1_Click(object sender, EventArgs e) { DialogResult = DialogResult.OK; Close(); } private void listStrings_Click(object sender, EventArgs e) { var indices = this.listStrings.SelectedIndices; if (indices.Count > 0) { int idx = indices[0]; var str = this.strings[idx]; this.SetSelectedItem(str); } } private void listStrings_DoubleClick(object sender, EventArgs e) { } private void txtID_TextChanged(object sender, EventArgs e) { } private void txtID_Validating(object sender, CancelEventArgs e) { string strID = this.txtID.Text; if (string.IsNullOrEmpty(strID)) { return; } uint uiID; if (!uint.TryParse(strID, NumberStyles.HexNumber, null, out uiID)) { this.error.SetError(this.txtID, "Invalid String ID"); this.txtString.Enabled = false; this.btnEditString.Enabled = false; this.btnAddString.Enabled = false; this.btnDeleteString.Enabled = false; } else { this.error.SetError(this.txtID, null); this.txtString.Enabled = true; this.btnEditString.Enabled = true; this.btnAddString.Enabled = true; this.btnDeleteString.Enabled = true; } } private class StringHolder { public LocalizedStringFormat Format { get; set; } public uint ID { get; set; } public Plugin Plugin { get; set; } public string Value { get; set; } } } }
Emilgardis/falloutsnip
Application/UI/Forms/StringsEditor.cs
C#
gpl-3.0
14,903
package me.mrCookieSlime.Slimefun.api.energy; import org.bukkit.block.Block; @FunctionalInterface public interface EnergyFlowListener { void onPulse(Block b); }
NathanAdhitya/Slimefun4
src/me/mrCookieSlime/Slimefun/api/energy/EnergyFlowListener.java
Java
gpl-3.0
167
/* * Copyright 2015-2017 Atomist Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ import { GraphNode } from "@atomist/rug/tree/PathExpression"; import * as api from "../Email"; import { Person } from "./Person"; export { Email }; /* * Type Email * * Generated class exposing Atomist Cortex. * Fluent builder style class for use in testing and query by example. */ class Email implements api.Email { private _address: string; private _of: Person; nodeName(): string { return "Email"; } nodeTags(): string[] { return [ "Email", "-dynamic" ]; } /** * String * * @returns {string} */ address(): string { return this._address; } withAddress(address: string): Email { this._address = address; return this; } /** * of - Email -> Person * * @returns {Person} */ of(): Person { return this._of; } withOf(of: Person): Email { this._of = of; return this; } }
atomist/rug-cli
src/test/resources/handlers/.atomist/node_modules/@atomist/cortex/stub/Email.ts
TypeScript
gpl-3.0
1,564
// Copyright (C) 2013 Andrea Esuli // http://www.esuli.it // // 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/>. namespace Esuli.Base.IO { using System.IO; /// <summary> /// Sequential serialization of integers. Uses delta coding and variable byte coding to save space. /// </summary> public class SequentialIntSerialization : ISequentialObjectSerialization<int> { public SequentialIntSerialization() { } public void WriteFirst(int obj, Stream stream) { if (obj < 0) { VariableByteCoding.Write(0, stream); VariableByteCoding.Write(-obj, stream); } else { VariableByteCoding.Write(1, stream); VariableByteCoding.Write(obj, stream); } } public void Write(int obj, int previousObj, Stream stream) { int delta = obj - previousObj; VariableByteCoding.Write(delta, stream); } public int ReadFirst(Stream stream) { long sign = VariableByteCoding.Read(stream); if (sign == 0) { sign = -1; } return (int)(VariableByteCoding.Read(stream)*sign); } public int Read(int previousObj, Stream stream) { return (int)(VariableByteCoding.Read(stream)) + previousObj; } public int ReadFirst(byte[] buffer, ref long position) { long sign = VariableByteCoding.Read(buffer, ref position); if (sign == 0) { sign = -1; } return (int)(VariableByteCoding.Read(buffer, ref position) * sign); } public int Read(int previous, byte[] buffer, ref long position) { return (int)(previous + VariableByteCoding.Read(buffer, ref position)); } } }
aesuli/dotnet-base
Base/src/Esuli/Base/IO/SequentialIntSerialization.cs
C#
gpl-3.0
2,555
namespace crash { partial class FormAskZeroPolynomial { /// <summary> /// Required designer variable. /// </summary> private System.ComponentModel.IContainer components = null; /// <summary> /// Clean up any resources being used. /// </summary> /// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param> protected override void Dispose(bool disposing) { if (disposing && (components != null)) { components.Dispose(); } base.Dispose(disposing); } #region Windows Form Designer generated code /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// </summary> private void InitializeComponent() { System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(FormAskZeroPolynomial)); this.panel1 = new System.Windows.Forms.Panel(); this.btnCancel = new System.Windows.Forms.Button(); this.cbSaveSettings = new System.Windows.Forms.CheckBox(); this.btnOk = new System.Windows.Forms.Button(); this.lblInfo = new System.Windows.Forms.Label(); this.lblEnergyInfo = new System.Windows.Forms.Label(); this.lblEnergy = new System.Windows.Forms.Label(); this.lblZeroPolynomialInfo = new System.Windows.Forms.Label(); this.tbZeroPolynomial = new System.Windows.Forms.TextBox(); this.lblChannelInfo = new System.Windows.Forms.Label(); this.lblChannel = new System.Windows.Forms.Label(); this.panel1.SuspendLayout(); this.SuspendLayout(); // // panel1 // this.panel1.Controls.Add(this.btnCancel); this.panel1.Controls.Add(this.cbSaveSettings); this.panel1.Controls.Add(this.btnOk); this.panel1.Dock = System.Windows.Forms.DockStyle.Bottom; this.panel1.Location = new System.Drawing.Point(0, 164); this.panel1.Name = "panel1"; this.panel1.Size = new System.Drawing.Size(440, 32); this.panel1.TabIndex = 0; // // btnCancel // this.btnCancel.Dock = System.Windows.Forms.DockStyle.Right; this.btnCancel.Location = new System.Drawing.Point(260, 0); this.btnCancel.Name = "btnCancel"; this.btnCancel.Size = new System.Drawing.Size(90, 32); this.btnCancel.TabIndex = 2; this.btnCancel.Text = "Cancel"; this.btnCancel.UseVisualStyleBackColor = true; this.btnCancel.Click += new System.EventHandler(this.btnCancel_Click); // // cbSaveSettings // this.cbSaveSettings.AutoSize = true; this.cbSaveSettings.CheckAlign = System.Drawing.ContentAlignment.MiddleRight; this.cbSaveSettings.Location = new System.Drawing.Point(13, 2); this.cbSaveSettings.Name = "cbSaveSettings"; this.cbSaveSettings.Padding = new System.Windows.Forms.Padding(0, 3, 0, 0); this.cbSaveSettings.Size = new System.Drawing.Size(154, 22); this.cbSaveSettings.TabIndex = 1; this.cbSaveSettings.Text = "Adjust settings detector"; this.cbSaveSettings.UseVisualStyleBackColor = true; // // btnOk // this.btnOk.Dock = System.Windows.Forms.DockStyle.Right; this.btnOk.Location = new System.Drawing.Point(350, 0); this.btnOk.Name = "btnOk"; this.btnOk.Size = new System.Drawing.Size(90, 32); this.btnOk.TabIndex = 0; this.btnOk.Text = "Ok"; this.btnOk.UseVisualStyleBackColor = true; this.btnOk.Click += new System.EventHandler(this.btnOk_Click); // // lblInfo // this.lblInfo.AutoSize = true; this.lblInfo.Font = new System.Drawing.Font("Arial", 9F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.lblInfo.Location = new System.Drawing.Point(15, 23); this.lblInfo.Name = "lblInfo"; this.lblInfo.Size = new System.Drawing.Size(253, 15); this.lblInfo.TabIndex = 1; this.lblInfo.Text = "Adjust zero polynomial for session detector"; // // lblEnergyInfo // this.lblEnergyInfo.AutoSize = true; this.lblEnergyInfo.Location = new System.Drawing.Point(15, 88); this.lblEnergyInfo.Name = "lblEnergyInfo"; this.lblEnergyInfo.Size = new System.Drawing.Size(48, 15); this.lblEnergyInfo.TabIndex = 2; this.lblEnergyInfo.Text = "Energy:"; // // lblEnergy // this.lblEnergy.AutoSize = true; this.lblEnergy.Location = new System.Drawing.Point(116, 88); this.lblEnergy.Name = "lblEnergy"; this.lblEnergy.Size = new System.Drawing.Size(59, 15); this.lblEnergy.TabIndex = 3; this.lblEnergy.Text = "<Energy>"; // // lblZeroPolynomialInfo // this.lblZeroPolynomialInfo.AutoSize = true; this.lblZeroPolynomialInfo.Location = new System.Drawing.Point(15, 120); this.lblZeroPolynomialInfo.Name = "lblZeroPolynomialInfo"; this.lblZeroPolynomialInfo.Size = new System.Drawing.Size(98, 15); this.lblZeroPolynomialInfo.TabIndex = 4; this.lblZeroPolynomialInfo.Text = "Zero polynomial:"; // // tbZeroPolynomial // this.tbZeroPolynomial.Location = new System.Drawing.Point(119, 114); this.tbZeroPolynomial.Name = "tbZeroPolynomial"; this.tbZeroPolynomial.Size = new System.Drawing.Size(293, 21); this.tbZeroPolynomial.TabIndex = 5; this.tbZeroPolynomial.TextChanged += new System.EventHandler(this.tbZeroPolynomial_TextChanged); // // lblChannelInfo // this.lblChannelInfo.AutoSize = true; this.lblChannelInfo.Location = new System.Drawing.Point(15, 60); this.lblChannelInfo.Name = "lblChannelInfo"; this.lblChannelInfo.Size = new System.Drawing.Size(57, 15); this.lblChannelInfo.TabIndex = 6; this.lblChannelInfo.Text = "Channel:"; // // lblChannel // this.lblChannel.AutoSize = true; this.lblChannel.Location = new System.Drawing.Point(116, 60); this.lblChannel.Name = "lblChannel"; this.lblChannel.Size = new System.Drawing.Size(68, 15); this.lblChannel.TabIndex = 7; this.lblChannel.Text = "<Channel>"; // // FormAskZeroPolynomial // this.AutoScaleDimensions = new System.Drawing.SizeF(7F, 15F); this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; this.ClientSize = new System.Drawing.Size(440, 196); this.Controls.Add(this.lblChannel); this.Controls.Add(this.lblChannelInfo); this.Controls.Add(this.tbZeroPolynomial); this.Controls.Add(this.lblZeroPolynomialInfo); this.Controls.Add(this.lblEnergy); this.Controls.Add(this.lblEnergyInfo); this.Controls.Add(this.lblInfo); this.Controls.Add(this.panel1); this.Font = new System.Drawing.Font("Arial", 9F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedDialog; this.Icon = ((System.Drawing.Icon)(resources.GetObject("$this.Icon"))); this.MaximizeBox = false; this.MinimizeBox = false; this.Name = "FormAskZeroPolynomial"; this.StartPosition = System.Windows.Forms.FormStartPosition.CenterParent; this.Text = "Gamma Analyzer - Zero polynomial"; this.Load += new System.EventHandler(this.FormAskZeroPolynomial_Load); this.panel1.ResumeLayout(false); this.panel1.PerformLayout(); this.ResumeLayout(false); this.PerformLayout(); } #endregion private System.Windows.Forms.Panel panel1; private System.Windows.Forms.Label lblInfo; private System.Windows.Forms.Label lblEnergyInfo; private System.Windows.Forms.Label lblEnergy; private System.Windows.Forms.Label lblZeroPolynomialInfo; private System.Windows.Forms.TextBox tbZeroPolynomial; private System.Windows.Forms.Button btnOk; private System.Windows.Forms.CheckBox cbSaveSettings; private System.Windows.Forms.Label lblChannelInfo; private System.Windows.Forms.Label lblChannel; private System.Windows.Forms.Button btnCancel; } }
corebob/crash
FormAskZeroPolynomial.Designer.cs
C#
gpl-3.0
9,303
/** * \file * Copyright 2014-2015 Benjamin Worpitz * * This file is part of alpaka. * * alpaka 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. * * alpaka 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 alpaka. * If not, see <http://www.gnu.org/licenses/>. */ #pragma once #include <alpaka/idx/Traits.hpp> // idx::GetIdx #include <alpaka/core/OpenMp.hpp> #include <alpaka/core/MapIdx.hpp> // core::mapIdx #include <boost/core/ignore_unused.hpp> // boost::ignore_unused namespace alpaka { namespace idx { namespace bt { //############################################################################# //! The OpenMP accelerator index provider. //############################################################################# template< typename TDim, typename TSize> class IdxBtOmp { public: using IdxBtBase = IdxBtOmp; //----------------------------------------------------------------------------- //! Constructor. //----------------------------------------------------------------------------- ALPAKA_FN_ACC_NO_CUDA IdxBtOmp() = default; //----------------------------------------------------------------------------- //! Copy constructor. //----------------------------------------------------------------------------- ALPAKA_FN_ACC_NO_CUDA IdxBtOmp(IdxBtOmp const &) = delete; //----------------------------------------------------------------------------- //! Move constructor. //----------------------------------------------------------------------------- ALPAKA_FN_ACC_NO_CUDA IdxBtOmp(IdxBtOmp &&) = delete; //----------------------------------------------------------------------------- //! Copy assignment operator. //----------------------------------------------------------------------------- ALPAKA_FN_ACC_NO_CUDA auto operator=(IdxBtOmp const &) -> IdxBtOmp & = delete; //----------------------------------------------------------------------------- //! Move assignment operator. //----------------------------------------------------------------------------- ALPAKA_FN_ACC_NO_CUDA auto operator=(IdxBtOmp &&) -> IdxBtOmp & = delete; //----------------------------------------------------------------------------- //! Destructor. //----------------------------------------------------------------------------- ALPAKA_FN_ACC_NO_CUDA /*virtual*/ ~IdxBtOmp() = default; }; } } namespace dim { namespace traits { //############################################################################# //! The OpenMP accelerator index dimension get trait specialization. //############################################################################# template< typename TDim, typename TSize> struct DimType< idx::bt::IdxBtOmp<TDim, TSize>> { using type = TDim; }; } } namespace idx { namespace traits { //############################################################################# //! The OpenMP accelerator block thread index get trait specialization. //############################################################################# template< typename TDim, typename TSize> struct GetIdx< idx::bt::IdxBtOmp<TDim, TSize>, origin::Block, unit::Threads> { //----------------------------------------------------------------------------- //! \return The index of the current thread in the block. //----------------------------------------------------------------------------- template< typename TWorkDiv> ALPAKA_FN_ACC_NO_CUDA static auto getIdx( idx::bt::IdxBtOmp<TDim, TSize> const & idx, TWorkDiv const & workDiv) -> Vec<TDim, TSize> { boost::ignore_unused(idx); // We assume that the thread id is positive. assert(::omp_get_thread_num()>=0); // \TODO: Would it be faster to precompute the index and cache it inside an array? return core::mapIdx<TDim::value>( Vec1<TSize>(static_cast<TSize>(::omp_get_thread_num())), workdiv::getWorkDiv<Block, Threads>(workDiv)); } }; } } namespace size { namespace traits { //############################################################################# //! The OpenMP accelerator block thread index size type trait specialization. //############################################################################# template< typename TDim, typename TSize> struct SizeType< idx::bt::IdxBtOmp<TDim, TSize>> { using type = TSize; }; } } }
erikzenker/alpaka
include/alpaka/idx/bt/IdxBtOmp.hpp
C++
gpl-3.0
6,134
"use strict"; tutao.provide('tutao.entity.sys.ChangePasswordData'); /** * @constructor * @param {Object=} data The json data to store in this entity. */ tutao.entity.sys.ChangePasswordData = function(data) { if (data) { this.updateData(data); } else { this.__format = "0"; this._code = null; this._pwEncUserGroupKey = null; this._salt = null; this._verifier = null; } this._entityHelper = new tutao.entity.EntityHelper(this); this.prototype = tutao.entity.sys.ChangePasswordData.prototype; }; /** * Updates the data of this entity. * @param {Object=} data The json data to store in this entity. */ tutao.entity.sys.ChangePasswordData.prototype.updateData = function(data) { this.__format = data._format; this._code = data.code; this._pwEncUserGroupKey = data.pwEncUserGroupKey; this._salt = data.salt; this._verifier = data.verifier; }; /** * The version of the model this type belongs to. * @const */ tutao.entity.sys.ChangePasswordData.MODEL_VERSION = '10'; /** * The url path to the resource. * @const */ tutao.entity.sys.ChangePasswordData.PATH = '/rest/sys/changepasswordservice'; /** * The encrypted flag. * @const */ tutao.entity.sys.ChangePasswordData.prototype.ENCRYPTED = false; /** * Provides the data of this instances as an object that can be converted to json. * @return {Object} The json object. */ tutao.entity.sys.ChangePasswordData.prototype.toJsonData = function() { return { _format: this.__format, code: this._code, pwEncUserGroupKey: this._pwEncUserGroupKey, salt: this._salt, verifier: this._verifier }; }; /** * The id of the ChangePasswordData type. */ tutao.entity.sys.ChangePasswordData.prototype.TYPE_ID = 534; /** * The id of the code attribute. */ tutao.entity.sys.ChangePasswordData.prototype.CODE_ATTRIBUTE_ID = 539; /** * The id of the pwEncUserGroupKey attribute. */ tutao.entity.sys.ChangePasswordData.prototype.PWENCUSERGROUPKEY_ATTRIBUTE_ID = 538; /** * The id of the salt attribute. */ tutao.entity.sys.ChangePasswordData.prototype.SALT_ATTRIBUTE_ID = 537; /** * The id of the verifier attribute. */ tutao.entity.sys.ChangePasswordData.prototype.VERIFIER_ATTRIBUTE_ID = 536; /** * Sets the format of this ChangePasswordData. * @param {string} format The format of this ChangePasswordData. */ tutao.entity.sys.ChangePasswordData.prototype.setFormat = function(format) { this.__format = format; return this; }; /** * Provides the format of this ChangePasswordData. * @return {string} The format of this ChangePasswordData. */ tutao.entity.sys.ChangePasswordData.prototype.getFormat = function() { return this.__format; }; /** * Sets the code of this ChangePasswordData. * @param {string} code The code of this ChangePasswordData. */ tutao.entity.sys.ChangePasswordData.prototype.setCode = function(code) { this._code = code; return this; }; /** * Provides the code of this ChangePasswordData. * @return {string} The code of this ChangePasswordData. */ tutao.entity.sys.ChangePasswordData.prototype.getCode = function() { return this._code; }; /** * Sets the pwEncUserGroupKey of this ChangePasswordData. * @param {string} pwEncUserGroupKey The pwEncUserGroupKey of this ChangePasswordData. */ tutao.entity.sys.ChangePasswordData.prototype.setPwEncUserGroupKey = function(pwEncUserGroupKey) { this._pwEncUserGroupKey = pwEncUserGroupKey; return this; }; /** * Provides the pwEncUserGroupKey of this ChangePasswordData. * @return {string} The pwEncUserGroupKey of this ChangePasswordData. */ tutao.entity.sys.ChangePasswordData.prototype.getPwEncUserGroupKey = function() { return this._pwEncUserGroupKey; }; /** * Sets the salt of this ChangePasswordData. * @param {string} salt The salt of this ChangePasswordData. */ tutao.entity.sys.ChangePasswordData.prototype.setSalt = function(salt) { this._salt = salt; return this; }; /** * Provides the salt of this ChangePasswordData. * @return {string} The salt of this ChangePasswordData. */ tutao.entity.sys.ChangePasswordData.prototype.getSalt = function() { return this._salt; }; /** * Sets the verifier of this ChangePasswordData. * @param {string} verifier The verifier of this ChangePasswordData. */ tutao.entity.sys.ChangePasswordData.prototype.setVerifier = function(verifier) { this._verifier = verifier; return this; }; /** * Provides the verifier of this ChangePasswordData. * @return {string} The verifier of this ChangePasswordData. */ tutao.entity.sys.ChangePasswordData.prototype.getVerifier = function() { return this._verifier; }; /** * Posts to a service. * @param {Object.<string, string>} parameters The parameters to send to the service. * @param {?Object.<string, string>} headers The headers to send to the service. If null, the default authentication data is used. * @return {Promise.<null=>} Resolves to the string result of the server or rejects with an exception if the post failed. */ tutao.entity.sys.ChangePasswordData.prototype.setup = function(parameters, headers) { if (!headers) { headers = tutao.entity.EntityHelper.createAuthHeaders(); } parameters["v"] = 10; this._entityHelper.notifyObservers(false); return tutao.locator.entityRestClient.postService(tutao.entity.sys.ChangePasswordData.PATH, this, parameters, headers, null); }; /** * Provides the entity helper of this entity. * @return {tutao.entity.EntityHelper} The entity helper. */ tutao.entity.sys.ChangePasswordData.prototype.getEntityHelper = function() { return this._entityHelper; };
bartuspan/tutanota
web/js/generated/entity/sys/ChangePasswordData.js
JavaScript
gpl-3.0
5,572
module SDGUtils module Random extend self def integer_salt(salt_digits=4) ::Random.rand((10**(salt_digits-1))..(10**salt_digits - 1)) end def salted_timestamp(fmt="%s_%s", time_fmt="%s_%L", salt_digits=4) time = Time.now.utc.strftime(time_fmt) salt = integer_salt(salt_digits) fmt % [time, salt] end end end
sdg-mit/arby
lib/sdg_utils/random.rb
Ruby
gpl-3.0
359
// Copyright (c) 2020 The Open-Transactions developers // This Source Code Form is subject to the terms of the Mozilla Public // License, v. 2.0. If a copy of the MPL was not distributed with this // file, You can obtain one at http://mozilla.org/MPL/2.0/. #ifndef OPENTXS_PROTO_LISTENADDRESS_HPP #define OPENTXS_PROTO_LISTENADDRESS_HPP #include "VerifyContracts.hpp" namespace opentxs { namespace proto { OPENTXS_PROTO_EXPORT bool CheckProto_1( const ListenAddress& address, const bool silent); OPENTXS_PROTO_EXPORT bool CheckProto_2(const ListenAddress&, const bool); OPENTXS_PROTO_EXPORT bool CheckProto_3(const ListenAddress&, const bool); OPENTXS_PROTO_EXPORT bool CheckProto_4(const ListenAddress&, const bool); OPENTXS_PROTO_EXPORT bool CheckProto_5(const ListenAddress&, const bool); OPENTXS_PROTO_EXPORT bool CheckProto_6(const ListenAddress&, const bool); OPENTXS_PROTO_EXPORT bool CheckProto_7(const ListenAddress&, const bool); OPENTXS_PROTO_EXPORT bool CheckProto_8(const ListenAddress&, const bool); OPENTXS_PROTO_EXPORT bool CheckProto_9(const ListenAddress&, const bool); OPENTXS_PROTO_EXPORT bool CheckProto_10(const ListenAddress&, const bool); OPENTXS_PROTO_EXPORT bool CheckProto_11(const ListenAddress&, const bool); OPENTXS_PROTO_EXPORT bool CheckProto_12(const ListenAddress&, const bool); OPENTXS_PROTO_EXPORT bool CheckProto_13(const ListenAddress&, const bool); OPENTXS_PROTO_EXPORT bool CheckProto_14(const ListenAddress&, const bool); OPENTXS_PROTO_EXPORT bool CheckProto_15(const ListenAddress&, const bool); OPENTXS_PROTO_EXPORT bool CheckProto_16(const ListenAddress&, const bool); OPENTXS_PROTO_EXPORT bool CheckProto_17(const ListenAddress&, const bool); OPENTXS_PROTO_EXPORT bool CheckProto_18(const ListenAddress&, const bool); OPENTXS_PROTO_EXPORT bool CheckProto_19(const ListenAddress&, const bool); OPENTXS_PROTO_EXPORT bool CheckProto_20(const ListenAddress&, const bool); } // namespace proto } // namespace opentxs #endif // OPENTXS_PROTO_LISTENADDRESS_HPP
Open-Transactions/opentxs-proto
include/opentxs-proto/verify/ListenAddress.hpp
C++
mpl-2.0
2,014
// Copyright (C) 2019 The Syncthing Authors. // // This Source Code Form is subject to the terms of the Mozilla Public // License, v. 2.0. If a copy of the MPL was not distributed with this file, // You can obtain one at https://mozilla.org/MPL/2.0/. package testutils import ( "errors" "sync" ) var ErrClosed = errors.New("closed") // BlockingRW implements io.Reader, Writer and Closer, but only returns when closed type BlockingRW struct { c chan struct{} closeOnce sync.Once } func NewBlockingRW() *BlockingRW { return &BlockingRW{ c: make(chan struct{}), closeOnce: sync.Once{}, } } func (rw *BlockingRW) Read(p []byte) (int, error) { <-rw.c return 0, ErrClosed } func (rw *BlockingRW) Write(p []byte) (int, error) { <-rw.c return 0, ErrClosed } func (rw *BlockingRW) Close() error { rw.closeOnce.Do(func() { close(rw.c) }) return nil } // NoopRW implements io.Reader and Writer but never returns when called type NoopRW struct{} func (rw *NoopRW) Read(p []byte) (n int, err error) { return len(p), nil } func (rw *NoopRW) Write(p []byte) (n int, err error) { return len(p), nil } type NoopCloser struct{} func (NoopCloser) Close() error { return nil }
syncthing/syncthing
lib/testutils/testutils.go
GO
mpl-2.0
1,207
package command import ( "fmt" "strings" "github.com/mitchellh/cli" "github.com/posener/complete" ) var _ cli.Command = (*NamespaceLookupCommand)(nil) var _ cli.CommandAutocomplete = (*NamespaceLookupCommand)(nil) type NamespaceLookupCommand struct { *BaseCommand } func (c *NamespaceLookupCommand) Synopsis() string { return "Look up an existing namespace" } func (c *NamespaceLookupCommand) Help() string { helpText := ` Usage: vault namespace lookup [options] PATH Get information about the namespace of the locally authenticated token: $ vault namespace lookup Get information about the namespace of a particular child token (e.g. ns1/ns2/): $ vault namespace lookup -namespace=ns1 ns2 ` + c.Flags().Help() return strings.TrimSpace(helpText) } func (c *NamespaceLookupCommand) Flags() *FlagSets { return c.flagSet(FlagSetHTTP | FlagSetOutputFormat) } func (c *NamespaceLookupCommand) AutocompleteArgs() complete.Predictor { return c.PredictVaultNamespaces() } func (c *NamespaceLookupCommand) AutocompleteFlags() complete.Flags { return c.Flags().Completions() } func (c *NamespaceLookupCommand) Run(args []string) int { f := c.Flags() if err := f.Parse(args); err != nil { c.UI.Error(err.Error()) return 1 } args = f.Args() switch { case len(args) < 1: c.UI.Error(fmt.Sprintf("Not enough arguments (expected 1, got %d)", len(args))) return 1 case len(args) > 1: c.UI.Error(fmt.Sprintf("Too many arguments (expected 1, got %d)", len(args))) return 1 } namespacePath := strings.TrimSpace(args[0]) client, err := c.Client() if err != nil { c.UI.Error(err.Error()) return 2 } secret, err := client.Logical().Read("sys/namespaces/" + namespacePath) if err != nil { c.UI.Error(fmt.Sprintf("Error looking up namespace: %s", err)) return 2 } if secret == nil { c.UI.Error("Namespace not found") return 2 } return OutputSecret(c.UI, secret) }
quixoten/vault
command/namespace_lookup.go
GO
mpl-2.0
1,930
import emotion from 'preact-emotion'; import remcalc from 'remcalc'; import { Category } from './service'; export const Place = emotion(Category)` margin-bottom: ${remcalc(10)}; `; export const Region = emotion('h6')` margin: ${remcalc(6)} 0; font-size: ${remcalc(13)}; line-height: ${remcalc(18)}; font-weight: ${props => props.theme.font.weight.normal}; color: #494949; `; export { Name as default } from './service';
geek/joyent-portal
packages/my-joy-navigation/src/components/datacenter.js
JavaScript
mpl-2.0
437
/* ***** BEGIN LICENSE BLOCK ***** * Version: MPL 1.1/GPL 2.0/LGPL 2.1 * * The contents of this file are subject to the Mozilla Public License * Version 1.1 (the "License"); you may not use this file except in * compliance with the License. You may obtain a copy of the License at * http://www.mozilla.org/MPL/ * * Software distributed under the License is distributed on an "AS IS"basis, * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License * for the specific language governing rights and limitations under the * License. * * The CPR Broker concept was initally developed by * Gentofte Kommune / Municipality of Gentofte, Denmark. * Contributor(s): * Steen Deth * * * The Initial Code for CPR Broker and related components is made in * cooperation between Magenta, Gentofte Kommune and IT- og Telestyrelsen / * Danish National IT and Telecom Agency * * Contributor(s): * Beemen Beshara * * The code is currently governed by IT- og Telestyrelsen / Danish National * IT and Telecom Agency * * Alternatively, the contents of this file may be used under the terms of * either the GNU General Public License Version 2 or later (the "GPL"), or * the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), * in which case the provisions of the GPL or the LGPL are applicable instead * of those above. If you wish to allow use of your version of this file only * under the terms of either the GPL or the LGPL, and not to allow others to * use your version of this file under the terms of the MPL, indicate your * decision by deleting the provisions above and replace them with the notice * and other provisions required by the GPL or the LGPL. If you do not delete * the provisions above, a recipient may use your version of this file under * the terms of any one of the MPL, the GPL or the LGPL. * * ***** END LICENSE BLOCK ***** */ using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using CprBroker.PartInterface; using CprBroker.Providers.CPRDirect; using CprBroker.Engine.Local; using System.IO; namespace CprBroker.EventBroker.Notifications { public class CprDirectCleaner : CPRDirectIOExecuter { protected override void ExecuteCPRDirectTask(IExtractDataProvider prov) { ExtractManager.CleanProcessedFolder(prov, this.LogChecks); } } }
magenta-aps/cprbroker
PART/Source/EventBroker/EventBroker/Notifications/CprDirectCleaner.cs
C#
mpl-2.0
2,431
/* * Project Maudio * Copyright (C) 2015 Martin Schwarz * See LICENSE.txt for the full license */ #include "core/audiosource/SinusGenerator.hpp" #include "core/util/AudioException.hpp" #include "core/util/Util.hpp" #include <cmath> namespace maudio{ SinusGenerator::SinusGenerator(){ mAudioInfo.mFileInfo.Title = "Sinus Test Generator from Maudio"; mFreq.reset(new KeyableFloatProperty("Frequency", 1000)); mProperties.add(mFreq); mSamplerate.reset(new UIntProperty("Samplerate", 44100)); mProperties.add(mSamplerate); mChannels.reset(new UIntProperty("Channels", 1)); mProperties.add(mChannels); mAudioInfo.Channels = mChannels->get(); mAudioInfo.Offset = 0; mAudioInfo.Samplerate = mSamplerate->get(); mAudioInfo.Samples = -1; } SinusGenerator::~SinusGenerator(){ } AudioBuffer SinusGenerator::get(unsigned long pos, unsigned int length) noexcept{ mAudioInfo.Channels = mChannels->get(); mAudioInfo.Samplerate = mSamplerate->get(); AudioBuffer ret(mAudioInfo.Channels, length, pos, mAudioInfo.Samplerate); for(unsigned int i = 0; i < length; i++){ Sample tmp(mAudioInfo.Channels); float index = pos + i; for(unsigned int j = 0; j < mAudioInfo.Channels; j++){ tmp.set(sin(mFreq->get(PositionToSeconds((pos + i), mAudioInfo.Samplerate)) * index * (2 * M_PI) / mAudioInfo.Samplerate), j); } ret.set(tmp, i); } return ret; } AudioInfo SinusGenerator::getInfo() noexcept{ mAudioInfo.Channels = mChannels->get(); mAudioInfo.Samplerate = mSamplerate->get(); return mAudioInfo; } bool SinusGenerator::checkIfCompatible(std::shared_ptr<Node> node, int slot){ return true; } void SinusGenerator::readConfig(const Config &conf){ return; } void SinusGenerator::setFrequency(float freq){ mFreq->setKey(freq, 0); } void SinusGenerator::setSamplerate(unsigned int samplerate){ mSamplerate->set(samplerate); } void SinusGenerator::setChannels(unsigned int channels){ mChannels->set(channels); } } // maudio
emperorofmars/maudio
deprecated/src/core/audiosource/SinusGenerator.cpp
C++
mpl-2.0
1,970
package terraform import ( "fmt" "log" "runtime/debug" "strings" "sync" "github.com/hashicorp/terraform/dag" ) // RootModuleName is the name given to the root module implicitly. const RootModuleName = "root" // RootModulePath is the path for the root module. var RootModulePath = []string{RootModuleName} // Graph represents the graph that Terraform uses to represent resources // and their dependencies. Each graph represents only one module, but it // can contain further modules, which themselves have their own graph. type Graph struct { // Graph is the actual DAG. This is embedded so you can call the DAG // methods directly. dag.AcyclicGraph // Path is the path in the module tree that this Graph represents. // The root is represented by a single element list containing // RootModuleName Path []string // annotations are the annotations that are added to vertices. Annotations // are arbitrary metadata taht is used for various logic. Annotations // should have unique keys that are referenced via constants. annotations map[dag.Vertex]map[string]interface{} // dependableMap is a lookaside table for fast lookups for connecting // dependencies by their GraphNodeDependable value to avoid O(n^3)-like // situations and turn them into O(1) with respect to the number of new // edges. dependableMap map[string]dag.Vertex // debugName is a name for reference in the debug output. This is usually // to indicate what topmost builder was, and if this graph is a shadow or // not. debugName string once sync.Once } func (g *Graph) DirectedGraph() dag.Grapher { return &g.AcyclicGraph } // Annotations returns the annotations that are configured for the // given vertex. The map is guaranteed to be non-nil but may be empty. // // The returned map may be modified to modify the annotations of the // vertex. func (g *Graph) Annotations(v dag.Vertex) map[string]interface{} { g.once.Do(g.init) // If this vertex isn't in the graph, then just return an empty map if !g.HasVertex(v) { return map[string]interface{}{} } // Get the map, if it doesn't exist yet then initialize it m, ok := g.annotations[v] if !ok { m = make(map[string]interface{}) g.annotations[v] = m } return m } // Add is the same as dag.Graph.Add. func (g *Graph) Add(v dag.Vertex) dag.Vertex { g.once.Do(g.init) // Call upwards to add it to the actual graph g.Graph.Add(v) // If this is a depend-able node, then store the lookaside info if dv, ok := v.(GraphNodeDependable); ok { for _, n := range dv.DependableName() { g.dependableMap[n] = v } } // If this initializes annotations, then do that if av, ok := v.(GraphNodeAnnotationInit); ok { as := g.Annotations(v) for k, v := range av.AnnotationInit() { as[k] = v } } return v } // Remove is the same as dag.Graph.Remove func (g *Graph) Remove(v dag.Vertex) dag.Vertex { g.once.Do(g.init) // If this is a depend-able node, then remove the lookaside info if dv, ok := v.(GraphNodeDependable); ok { for _, n := range dv.DependableName() { delete(g.dependableMap, n) } } // Remove the annotations delete(g.annotations, v) // Call upwards to remove it from the actual graph return g.Graph.Remove(v) } // Replace is the same as dag.Graph.Replace func (g *Graph) Replace(o, n dag.Vertex) bool { g.once.Do(g.init) // Go through and update our lookaside to point to the new vertex for k, v := range g.dependableMap { if v == o { if _, ok := n.(GraphNodeDependable); ok { g.dependableMap[k] = n } else { delete(g.dependableMap, k) } } } // Move the annotation if it exists if m, ok := g.annotations[o]; ok { g.annotations[n] = m delete(g.annotations, o) } return g.Graph.Replace(o, n) } // ConnectDependent connects a GraphNodeDependent to all of its // GraphNodeDependables. It returns the list of dependents it was // unable to connect to. func (g *Graph) ConnectDependent(raw dag.Vertex) []string { v, ok := raw.(GraphNodeDependent) if !ok { return nil } return g.ConnectTo(v, v.DependentOn()) } // ConnectDependents goes through the graph, connecting all the // GraphNodeDependents to GraphNodeDependables. This is safe to call // multiple times. // // To get details on whether dependencies could be found/made, the more // specific ConnectDependent should be used. func (g *Graph) ConnectDependents() { for _, v := range g.Vertices() { if dv, ok := v.(GraphNodeDependent); ok { g.ConnectDependent(dv) } } } // ConnectFrom creates an edge by finding the source from a DependableName // and connecting it to the specific vertex. func (g *Graph) ConnectFrom(source string, target dag.Vertex) { g.once.Do(g.init) if source := g.dependableMap[source]; source != nil { g.Connect(dag.BasicEdge(source, target)) } } // ConnectTo connects a vertex to a raw string of targets that are the // result of DependableName, and returns the list of targets that are missing. func (g *Graph) ConnectTo(v dag.Vertex, targets []string) []string { g.once.Do(g.init) var missing []string for _, t := range targets { if dest := g.dependableMap[t]; dest != nil { g.Connect(dag.BasicEdge(v, dest)) } else { missing = append(missing, t) } } return missing } // Dependable finds the vertices in the graph that have the given dependable // names and returns them. func (g *Graph) Dependable(n string) dag.Vertex { // TODO: do we need this? return nil } // Walk walks the graph with the given walker for callbacks. The graph // will be walked with full parallelism, so the walker should expect // to be called in concurrently. func (g *Graph) Walk(walker GraphWalker) error { return g.walk(walker) } func (g *Graph) init() { if g.annotations == nil { g.annotations = make(map[dag.Vertex]map[string]interface{}) } if g.dependableMap == nil { g.dependableMap = make(map[string]dag.Vertex) } } func (g *Graph) walk(walker GraphWalker) error { // The callbacks for enter/exiting a graph ctx := walker.EnterPath(g.Path) defer walker.ExitPath(g.Path) // Get the path for logs path := strings.Join(ctx.Path(), ".") // Determine if our walker is a panic wrapper panicwrap, ok := walker.(GraphWalkerPanicwrapper) if !ok { panicwrap = nil // just to be sure } debugName := "walk-graph.json" if g.debugName != "" { debugName = g.debugName + "-" + debugName } debugBuf := dbug.NewFileWriter(debugName) g.SetDebugWriter(debugBuf) defer debugBuf.Close() // Walk the graph. var walkFn dag.WalkFunc walkFn = func(v dag.Vertex) (rerr error) { log.Printf("[DEBUG] vertex '%s.%s': walking", path, dag.VertexName(v)) // If we have a panic wrap GraphWalker and a panic occurs, recover // and call that. We ensure the return value is an error, however, // so that future nodes are not called. defer func() { // If no panicwrap, do nothing if panicwrap == nil { return } // If no panic, do nothing err := recover() if err == nil { return } // Modify the return value to show the error rerr = fmt.Errorf("vertex %q captured panic: %s\n\n%s", dag.VertexName(v), err, debug.Stack()) // Call the panic wrapper panicwrap.Panic(v, err) }() walker.EnterVertex(v) defer walker.ExitVertex(v, rerr) // vertexCtx is the context that we use when evaluating. This // is normally the context of our graph but can be overridden // with a GraphNodeSubPath impl. vertexCtx := ctx if pn, ok := v.(GraphNodeSubPath); ok && len(pn.Path()) > 0 { vertexCtx = walker.EnterPath(normalizeModulePath(pn.Path())) defer walker.ExitPath(pn.Path()) } // If the node is eval-able, then evaluate it. if ev, ok := v.(GraphNodeEvalable); ok { tree := ev.EvalTree() if tree == nil { panic(fmt.Sprintf( "%s.%s (%T): nil eval tree", path, dag.VertexName(v), v)) } // Allow the walker to change our tree if needed. Eval, // then callback with the output. log.Printf("[DEBUG] vertex '%s.%s': evaluating", path, dag.VertexName(v)) g.DebugVertexInfo(v, fmt.Sprintf("evaluating %T(%s)", v, path)) tree = walker.EnterEvalTree(v, tree) output, err := Eval(tree, vertexCtx) if rerr = walker.ExitEvalTree(v, output, err); rerr != nil { return } } // If the node is dynamically expanded, then expand it if ev, ok := v.(GraphNodeDynamicExpandable); ok { log.Printf( "[DEBUG] vertex '%s.%s': expanding/walking dynamic subgraph", path, dag.VertexName(v)) g.DebugVertexInfo(v, fmt.Sprintf("expanding %T(%s)", v, path)) g, err := ev.DynamicExpand(vertexCtx) if err != nil { rerr = err return } if g != nil { // Walk the subgraph if rerr = g.walk(walker); rerr != nil { return } } } // If the node has a subgraph, then walk the subgraph if sn, ok := v.(GraphNodeSubgraph); ok { log.Printf( "[DEBUG] vertex '%s.%s': walking subgraph", path, dag.VertexName(v)) g.DebugVertexInfo(v, fmt.Sprintf("subgraph: %T(%s)", v, path)) if rerr = sn.Subgraph().(*Graph).walk(walker); rerr != nil { return } } return nil } return g.AcyclicGraph.Walk(walkFn) } // GraphNodeAnnotationInit is an interface that allows a node to // initialize it's annotations. // // AnnotationInit will be called _once_ when the node is added to a // graph for the first time and is expected to return it's initial // annotations. type GraphNodeAnnotationInit interface { AnnotationInit() map[string]interface{} } // GraphNodeDependable is an interface which says that a node can be // depended on (an edge can be placed between this node and another) according // to the well-known name returned by DependableName. // // DependableName can return multiple names it is known by. type GraphNodeDependable interface { DependableName() []string } // GraphNodeDependent is an interface which says that a node depends // on another GraphNodeDependable by some name. By implementing this // interface, Graph.ConnectDependents() can be called multiple times // safely and efficiently. type GraphNodeDependent interface { DependentOn() []string }
mkuzmin/terraform
terraform/graph.go
GO
mpl-2.0
10,106
package compute // Copyright (c) Microsoft and contributors. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // // See the License for the specific language governing permissions and // limitations under the License. // // Code generated by Microsoft (R) AutoRest Code Generator. // Changes may cause incorrect behavior and will be lost if the code is regenerated. import ( "context" "github.com/Azure/go-autorest/autorest" "github.com/Azure/go-autorest/autorest/azure" "github.com/Azure/go-autorest/autorest/validation" "github.com/Azure/go-autorest/tracing" "net/http" ) // VirtualMachineScaleSetVMsClient is the compute Client type VirtualMachineScaleSetVMsClient struct { BaseClient } // NewVirtualMachineScaleSetVMsClient creates an instance of the VirtualMachineScaleSetVMsClient client. func NewVirtualMachineScaleSetVMsClient(subscriptionID string) VirtualMachineScaleSetVMsClient { return NewVirtualMachineScaleSetVMsClientWithBaseURI(DefaultBaseURI, subscriptionID) } // NewVirtualMachineScaleSetVMsClientWithBaseURI creates an instance of the VirtualMachineScaleSetVMsClient client // using a custom endpoint. Use this when interacting with an Azure cloud that uses a non-standard base URI (sovereign // clouds, Azure stack). func NewVirtualMachineScaleSetVMsClientWithBaseURI(baseURI string, subscriptionID string) VirtualMachineScaleSetVMsClient { return VirtualMachineScaleSetVMsClient{NewWithBaseURI(baseURI, subscriptionID)} } // Deallocate deallocates a specific virtual machine in a VM scale set. Shuts down the virtual machine and releases the // compute resources it uses. You are not billed for the compute resources of this virtual machine once it is // deallocated. // Parameters: // resourceGroupName - the name of the resource group. // VMScaleSetName - the name of the VM scale set. // instanceID - the instance ID of the virtual machine. func (client VirtualMachineScaleSetVMsClient) Deallocate(ctx context.Context, resourceGroupName string, VMScaleSetName string, instanceID string) (result VirtualMachineScaleSetVMsDeallocateFuture, err error) { if tracing.IsEnabled() { ctx = tracing.StartSpan(ctx, fqdn+"/VirtualMachineScaleSetVMsClient.Deallocate") defer func() { sc := -1 if result.Response() != nil { sc = result.Response().StatusCode } tracing.EndSpan(ctx, sc, err) }() } req, err := client.DeallocatePreparer(ctx, resourceGroupName, VMScaleSetName, instanceID) if err != nil { err = autorest.NewErrorWithError(err, "compute.VirtualMachineScaleSetVMsClient", "Deallocate", nil, "Failure preparing request") return } result, err = client.DeallocateSender(req) if err != nil { err = autorest.NewErrorWithError(err, "compute.VirtualMachineScaleSetVMsClient", "Deallocate", nil, "Failure sending request") return } return } // DeallocatePreparer prepares the Deallocate request. func (client VirtualMachineScaleSetVMsClient) DeallocatePreparer(ctx context.Context, resourceGroupName string, VMScaleSetName string, instanceID string) (*http.Request, error) { pathParameters := map[string]interface{}{ "instanceId": autorest.Encode("path", instanceID), "resourceGroupName": autorest.Encode("path", resourceGroupName), "subscriptionId": autorest.Encode("path", client.SubscriptionID), "vmScaleSetName": autorest.Encode("path", VMScaleSetName), } const APIVersion = "2019-07-01" queryParameters := map[string]interface{}{ "api-version": APIVersion, } preparer := autorest.CreatePreparer( autorest.AsPost(), autorest.WithBaseURL(client.BaseURI), autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Compute/virtualMachineScaleSets/{vmScaleSetName}/virtualmachines/{instanceId}/deallocate", pathParameters), autorest.WithQueryParameters(queryParameters)) return preparer.Prepare((&http.Request{}).WithContext(ctx)) } // DeallocateSender sends the Deallocate request. The method will close the // http.Response Body if it receives an error. func (client VirtualMachineScaleSetVMsClient) DeallocateSender(req *http.Request) (future VirtualMachineScaleSetVMsDeallocateFuture, err error) { var resp *http.Response resp, err = client.Send(req, azure.DoRetryWithRegistration(client.Client)) if err != nil { return } var azf azure.Future azf, err = azure.NewFutureFromResponse(resp) future.FutureAPI = &azf future.Result = func(client VirtualMachineScaleSetVMsClient) (ar autorest.Response, err error) { var done bool done, err = future.DoneWithContext(context.Background(), client) if err != nil { err = autorest.NewErrorWithError(err, "compute.VirtualMachineScaleSetVMsDeallocateFuture", "Result", future.Response(), "Polling failure") return } if !done { err = azure.NewAsyncOpIncompleteError("compute.VirtualMachineScaleSetVMsDeallocateFuture") return } ar.Response = future.Response() return } return } // DeallocateResponder handles the response to the Deallocate request. The method always // closes the http.Response Body. func (client VirtualMachineScaleSetVMsClient) DeallocateResponder(resp *http.Response) (result autorest.Response, err error) { err = autorest.Respond( resp, azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusAccepted), autorest.ByClosing()) result.Response = resp return } // Delete deletes a virtual machine from a VM scale set. // Parameters: // resourceGroupName - the name of the resource group. // VMScaleSetName - the name of the VM scale set. // instanceID - the instance ID of the virtual machine. func (client VirtualMachineScaleSetVMsClient) Delete(ctx context.Context, resourceGroupName string, VMScaleSetName string, instanceID string) (result VirtualMachineScaleSetVMsDeleteFuture, err error) { if tracing.IsEnabled() { ctx = tracing.StartSpan(ctx, fqdn+"/VirtualMachineScaleSetVMsClient.Delete") defer func() { sc := -1 if result.Response() != nil { sc = result.Response().StatusCode } tracing.EndSpan(ctx, sc, err) }() } req, err := client.DeletePreparer(ctx, resourceGroupName, VMScaleSetName, instanceID) if err != nil { err = autorest.NewErrorWithError(err, "compute.VirtualMachineScaleSetVMsClient", "Delete", nil, "Failure preparing request") return } result, err = client.DeleteSender(req) if err != nil { err = autorest.NewErrorWithError(err, "compute.VirtualMachineScaleSetVMsClient", "Delete", nil, "Failure sending request") return } return } // DeletePreparer prepares the Delete request. func (client VirtualMachineScaleSetVMsClient) DeletePreparer(ctx context.Context, resourceGroupName string, VMScaleSetName string, instanceID string) (*http.Request, error) { pathParameters := map[string]interface{}{ "instanceId": autorest.Encode("path", instanceID), "resourceGroupName": autorest.Encode("path", resourceGroupName), "subscriptionId": autorest.Encode("path", client.SubscriptionID), "vmScaleSetName": autorest.Encode("path", VMScaleSetName), } const APIVersion = "2019-07-01" queryParameters := map[string]interface{}{ "api-version": APIVersion, } preparer := autorest.CreatePreparer( autorest.AsDelete(), autorest.WithBaseURL(client.BaseURI), autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Compute/virtualMachineScaleSets/{vmScaleSetName}/virtualmachines/{instanceId}", pathParameters), autorest.WithQueryParameters(queryParameters)) return preparer.Prepare((&http.Request{}).WithContext(ctx)) } // DeleteSender sends the Delete request. The method will close the // http.Response Body if it receives an error. func (client VirtualMachineScaleSetVMsClient) DeleteSender(req *http.Request) (future VirtualMachineScaleSetVMsDeleteFuture, err error) { var resp *http.Response resp, err = client.Send(req, azure.DoRetryWithRegistration(client.Client)) if err != nil { return } var azf azure.Future azf, err = azure.NewFutureFromResponse(resp) future.FutureAPI = &azf future.Result = func(client VirtualMachineScaleSetVMsClient) (ar autorest.Response, err error) { var done bool done, err = future.DoneWithContext(context.Background(), client) if err != nil { err = autorest.NewErrorWithError(err, "compute.VirtualMachineScaleSetVMsDeleteFuture", "Result", future.Response(), "Polling failure") return } if !done { err = azure.NewAsyncOpIncompleteError("compute.VirtualMachineScaleSetVMsDeleteFuture") return } ar.Response = future.Response() return } return } // DeleteResponder handles the response to the Delete request. The method always // closes the http.Response Body. func (client VirtualMachineScaleSetVMsClient) DeleteResponder(resp *http.Response) (result autorest.Response, err error) { err = autorest.Respond( resp, azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusAccepted, http.StatusNoContent), autorest.ByClosing()) result.Response = resp return } // Get gets a virtual machine from a VM scale set. // Parameters: // resourceGroupName - the name of the resource group. // VMScaleSetName - the name of the VM scale set. // instanceID - the instance ID of the virtual machine. // expand - the expand expression to apply on the operation. func (client VirtualMachineScaleSetVMsClient) Get(ctx context.Context, resourceGroupName string, VMScaleSetName string, instanceID string, expand InstanceViewTypes) (result VirtualMachineScaleSetVM, err error) { if tracing.IsEnabled() { ctx = tracing.StartSpan(ctx, fqdn+"/VirtualMachineScaleSetVMsClient.Get") defer func() { sc := -1 if result.Response.Response != nil { sc = result.Response.Response.StatusCode } tracing.EndSpan(ctx, sc, err) }() } req, err := client.GetPreparer(ctx, resourceGroupName, VMScaleSetName, instanceID, expand) if err != nil { err = autorest.NewErrorWithError(err, "compute.VirtualMachineScaleSetVMsClient", "Get", nil, "Failure preparing request") return } resp, err := client.GetSender(req) if err != nil { result.Response = autorest.Response{Response: resp} err = autorest.NewErrorWithError(err, "compute.VirtualMachineScaleSetVMsClient", "Get", resp, "Failure sending request") return } result, err = client.GetResponder(resp) if err != nil { err = autorest.NewErrorWithError(err, "compute.VirtualMachineScaleSetVMsClient", "Get", resp, "Failure responding to request") return } return } // GetPreparer prepares the Get request. func (client VirtualMachineScaleSetVMsClient) GetPreparer(ctx context.Context, resourceGroupName string, VMScaleSetName string, instanceID string, expand InstanceViewTypes) (*http.Request, error) { pathParameters := map[string]interface{}{ "instanceId": autorest.Encode("path", instanceID), "resourceGroupName": autorest.Encode("path", resourceGroupName), "subscriptionId": autorest.Encode("path", client.SubscriptionID), "vmScaleSetName": autorest.Encode("path", VMScaleSetName), } const APIVersion = "2019-07-01" queryParameters := map[string]interface{}{ "api-version": APIVersion, } if len(string(expand)) > 0 { queryParameters["$expand"] = autorest.Encode("query", expand) } preparer := autorest.CreatePreparer( autorest.AsGet(), autorest.WithBaseURL(client.BaseURI), autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Compute/virtualMachineScaleSets/{vmScaleSetName}/virtualmachines/{instanceId}", pathParameters), autorest.WithQueryParameters(queryParameters)) return preparer.Prepare((&http.Request{}).WithContext(ctx)) } // GetSender sends the Get request. The method will close the // http.Response Body if it receives an error. func (client VirtualMachineScaleSetVMsClient) GetSender(req *http.Request) (*http.Response, error) { return client.Send(req, azure.DoRetryWithRegistration(client.Client)) } // GetResponder handles the response to the Get request. The method always // closes the http.Response Body. func (client VirtualMachineScaleSetVMsClient) GetResponder(resp *http.Response) (result VirtualMachineScaleSetVM, err error) { err = autorest.Respond( resp, azure.WithErrorUnlessStatusCode(http.StatusOK), autorest.ByUnmarshallingJSON(&result), autorest.ByClosing()) result.Response = autorest.Response{Response: resp} return } // GetInstanceView gets the status of a virtual machine from a VM scale set. // Parameters: // resourceGroupName - the name of the resource group. // VMScaleSetName - the name of the VM scale set. // instanceID - the instance ID of the virtual machine. func (client VirtualMachineScaleSetVMsClient) GetInstanceView(ctx context.Context, resourceGroupName string, VMScaleSetName string, instanceID string) (result VirtualMachineScaleSetVMInstanceView, err error) { if tracing.IsEnabled() { ctx = tracing.StartSpan(ctx, fqdn+"/VirtualMachineScaleSetVMsClient.GetInstanceView") defer func() { sc := -1 if result.Response.Response != nil { sc = result.Response.Response.StatusCode } tracing.EndSpan(ctx, sc, err) }() } req, err := client.GetInstanceViewPreparer(ctx, resourceGroupName, VMScaleSetName, instanceID) if err != nil { err = autorest.NewErrorWithError(err, "compute.VirtualMachineScaleSetVMsClient", "GetInstanceView", nil, "Failure preparing request") return } resp, err := client.GetInstanceViewSender(req) if err != nil { result.Response = autorest.Response{Response: resp} err = autorest.NewErrorWithError(err, "compute.VirtualMachineScaleSetVMsClient", "GetInstanceView", resp, "Failure sending request") return } result, err = client.GetInstanceViewResponder(resp) if err != nil { err = autorest.NewErrorWithError(err, "compute.VirtualMachineScaleSetVMsClient", "GetInstanceView", resp, "Failure responding to request") return } return } // GetInstanceViewPreparer prepares the GetInstanceView request. func (client VirtualMachineScaleSetVMsClient) GetInstanceViewPreparer(ctx context.Context, resourceGroupName string, VMScaleSetName string, instanceID string) (*http.Request, error) { pathParameters := map[string]interface{}{ "instanceId": autorest.Encode("path", instanceID), "resourceGroupName": autorest.Encode("path", resourceGroupName), "subscriptionId": autorest.Encode("path", client.SubscriptionID), "vmScaleSetName": autorest.Encode("path", VMScaleSetName), } const APIVersion = "2019-07-01" queryParameters := map[string]interface{}{ "api-version": APIVersion, } preparer := autorest.CreatePreparer( autorest.AsGet(), autorest.WithBaseURL(client.BaseURI), autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Compute/virtualMachineScaleSets/{vmScaleSetName}/virtualmachines/{instanceId}/instanceView", pathParameters), autorest.WithQueryParameters(queryParameters)) return preparer.Prepare((&http.Request{}).WithContext(ctx)) } // GetInstanceViewSender sends the GetInstanceView request. The method will close the // http.Response Body if it receives an error. func (client VirtualMachineScaleSetVMsClient) GetInstanceViewSender(req *http.Request) (*http.Response, error) { return client.Send(req, azure.DoRetryWithRegistration(client.Client)) } // GetInstanceViewResponder handles the response to the GetInstanceView request. The method always // closes the http.Response Body. func (client VirtualMachineScaleSetVMsClient) GetInstanceViewResponder(resp *http.Response) (result VirtualMachineScaleSetVMInstanceView, err error) { err = autorest.Respond( resp, azure.WithErrorUnlessStatusCode(http.StatusOK), autorest.ByUnmarshallingJSON(&result), autorest.ByClosing()) result.Response = autorest.Response{Response: resp} return } // List gets a list of all virtual machines in a VM scale sets. // Parameters: // resourceGroupName - the name of the resource group. // virtualMachineScaleSetName - the name of the VM scale set. // filter - the filter to apply to the operation. Allowed values are 'startswith(instanceView/statuses/code, // 'PowerState') eq true', 'properties/latestModelApplied eq true', 'properties/latestModelApplied eq false'. // selectParameter - the list parameters. Allowed values are 'instanceView', 'instanceView/statuses'. // expand - the expand expression to apply to the operation. Allowed values are 'instanceView'. func (client VirtualMachineScaleSetVMsClient) List(ctx context.Context, resourceGroupName string, virtualMachineScaleSetName string, filter string, selectParameter string, expand string) (result VirtualMachineScaleSetVMListResultPage, err error) { if tracing.IsEnabled() { ctx = tracing.StartSpan(ctx, fqdn+"/VirtualMachineScaleSetVMsClient.List") defer func() { sc := -1 if result.vmssvlr.Response.Response != nil { sc = result.vmssvlr.Response.Response.StatusCode } tracing.EndSpan(ctx, sc, err) }() } result.fn = client.listNextResults req, err := client.ListPreparer(ctx, resourceGroupName, virtualMachineScaleSetName, filter, selectParameter, expand) if err != nil { err = autorest.NewErrorWithError(err, "compute.VirtualMachineScaleSetVMsClient", "List", nil, "Failure preparing request") return } resp, err := client.ListSender(req) if err != nil { result.vmssvlr.Response = autorest.Response{Response: resp} err = autorest.NewErrorWithError(err, "compute.VirtualMachineScaleSetVMsClient", "List", resp, "Failure sending request") return } result.vmssvlr, err = client.ListResponder(resp) if err != nil { err = autorest.NewErrorWithError(err, "compute.VirtualMachineScaleSetVMsClient", "List", resp, "Failure responding to request") return } if result.vmssvlr.hasNextLink() && result.vmssvlr.IsEmpty() { err = result.NextWithContext(ctx) return } return } // ListPreparer prepares the List request. func (client VirtualMachineScaleSetVMsClient) ListPreparer(ctx context.Context, resourceGroupName string, virtualMachineScaleSetName string, filter string, selectParameter string, expand string) (*http.Request, error) { pathParameters := map[string]interface{}{ "resourceGroupName": autorest.Encode("path", resourceGroupName), "subscriptionId": autorest.Encode("path", client.SubscriptionID), "virtualMachineScaleSetName": autorest.Encode("path", virtualMachineScaleSetName), } const APIVersion = "2019-07-01" queryParameters := map[string]interface{}{ "api-version": APIVersion, } if len(filter) > 0 { queryParameters["$filter"] = autorest.Encode("query", filter) } if len(selectParameter) > 0 { queryParameters["$select"] = autorest.Encode("query", selectParameter) } if len(expand) > 0 { queryParameters["$expand"] = autorest.Encode("query", expand) } preparer := autorest.CreatePreparer( autorest.AsGet(), autorest.WithBaseURL(client.BaseURI), autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Compute/virtualMachineScaleSets/{virtualMachineScaleSetName}/virtualMachines", pathParameters), autorest.WithQueryParameters(queryParameters)) return preparer.Prepare((&http.Request{}).WithContext(ctx)) } // ListSender sends the List request. The method will close the // http.Response Body if it receives an error. func (client VirtualMachineScaleSetVMsClient) ListSender(req *http.Request) (*http.Response, error) { return client.Send(req, azure.DoRetryWithRegistration(client.Client)) } // ListResponder handles the response to the List request. The method always // closes the http.Response Body. func (client VirtualMachineScaleSetVMsClient) ListResponder(resp *http.Response) (result VirtualMachineScaleSetVMListResult, err error) { err = autorest.Respond( resp, azure.WithErrorUnlessStatusCode(http.StatusOK), autorest.ByUnmarshallingJSON(&result), autorest.ByClosing()) result.Response = autorest.Response{Response: resp} return } // listNextResults retrieves the next set of results, if any. func (client VirtualMachineScaleSetVMsClient) listNextResults(ctx context.Context, lastResults VirtualMachineScaleSetVMListResult) (result VirtualMachineScaleSetVMListResult, err error) { req, err := lastResults.virtualMachineScaleSetVMListResultPreparer(ctx) if err != nil { return result, autorest.NewErrorWithError(err, "compute.VirtualMachineScaleSetVMsClient", "listNextResults", nil, "Failure preparing next results request") } if req == nil { return } resp, err := client.ListSender(req) if err != nil { result.Response = autorest.Response{Response: resp} return result, autorest.NewErrorWithError(err, "compute.VirtualMachineScaleSetVMsClient", "listNextResults", resp, "Failure sending next results request") } result, err = client.ListResponder(resp) if err != nil { err = autorest.NewErrorWithError(err, "compute.VirtualMachineScaleSetVMsClient", "listNextResults", resp, "Failure responding to next results request") } return } // ListComplete enumerates all values, automatically crossing page boundaries as required. func (client VirtualMachineScaleSetVMsClient) ListComplete(ctx context.Context, resourceGroupName string, virtualMachineScaleSetName string, filter string, selectParameter string, expand string) (result VirtualMachineScaleSetVMListResultIterator, err error) { if tracing.IsEnabled() { ctx = tracing.StartSpan(ctx, fqdn+"/VirtualMachineScaleSetVMsClient.List") defer func() { sc := -1 if result.Response().Response.Response != nil { sc = result.page.Response().Response.Response.StatusCode } tracing.EndSpan(ctx, sc, err) }() } result.page, err = client.List(ctx, resourceGroupName, virtualMachineScaleSetName, filter, selectParameter, expand) return } // PerformMaintenance shuts down the virtual machine in a VMScaleSet, moves it to an already updated node, and powers // it back on during the self-service phase of planned maintenance. // Parameters: // resourceGroupName - the name of the resource group. // VMScaleSetName - the name of the VM scale set. // instanceID - the instance ID of the virtual machine. func (client VirtualMachineScaleSetVMsClient) PerformMaintenance(ctx context.Context, resourceGroupName string, VMScaleSetName string, instanceID string) (result VirtualMachineScaleSetVMsPerformMaintenanceFuture, err error) { if tracing.IsEnabled() { ctx = tracing.StartSpan(ctx, fqdn+"/VirtualMachineScaleSetVMsClient.PerformMaintenance") defer func() { sc := -1 if result.Response() != nil { sc = result.Response().StatusCode } tracing.EndSpan(ctx, sc, err) }() } req, err := client.PerformMaintenancePreparer(ctx, resourceGroupName, VMScaleSetName, instanceID) if err != nil { err = autorest.NewErrorWithError(err, "compute.VirtualMachineScaleSetVMsClient", "PerformMaintenance", nil, "Failure preparing request") return } result, err = client.PerformMaintenanceSender(req) if err != nil { err = autorest.NewErrorWithError(err, "compute.VirtualMachineScaleSetVMsClient", "PerformMaintenance", nil, "Failure sending request") return } return } // PerformMaintenancePreparer prepares the PerformMaintenance request. func (client VirtualMachineScaleSetVMsClient) PerformMaintenancePreparer(ctx context.Context, resourceGroupName string, VMScaleSetName string, instanceID string) (*http.Request, error) { pathParameters := map[string]interface{}{ "instanceId": autorest.Encode("path", instanceID), "resourceGroupName": autorest.Encode("path", resourceGroupName), "subscriptionId": autorest.Encode("path", client.SubscriptionID), "vmScaleSetName": autorest.Encode("path", VMScaleSetName), } const APIVersion = "2019-07-01" queryParameters := map[string]interface{}{ "api-version": APIVersion, } preparer := autorest.CreatePreparer( autorest.AsPost(), autorest.WithBaseURL(client.BaseURI), autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Compute/virtualMachineScaleSets/{vmScaleSetName}/virtualmachines/{instanceId}/performMaintenance", pathParameters), autorest.WithQueryParameters(queryParameters)) return preparer.Prepare((&http.Request{}).WithContext(ctx)) } // PerformMaintenanceSender sends the PerformMaintenance request. The method will close the // http.Response Body if it receives an error. func (client VirtualMachineScaleSetVMsClient) PerformMaintenanceSender(req *http.Request) (future VirtualMachineScaleSetVMsPerformMaintenanceFuture, err error) { var resp *http.Response resp, err = client.Send(req, azure.DoRetryWithRegistration(client.Client)) if err != nil { return } var azf azure.Future azf, err = azure.NewFutureFromResponse(resp) future.FutureAPI = &azf future.Result = func(client VirtualMachineScaleSetVMsClient) (ar autorest.Response, err error) { var done bool done, err = future.DoneWithContext(context.Background(), client) if err != nil { err = autorest.NewErrorWithError(err, "compute.VirtualMachineScaleSetVMsPerformMaintenanceFuture", "Result", future.Response(), "Polling failure") return } if !done { err = azure.NewAsyncOpIncompleteError("compute.VirtualMachineScaleSetVMsPerformMaintenanceFuture") return } ar.Response = future.Response() return } return } // PerformMaintenanceResponder handles the response to the PerformMaintenance request. The method always // closes the http.Response Body. func (client VirtualMachineScaleSetVMsClient) PerformMaintenanceResponder(resp *http.Response) (result autorest.Response, err error) { err = autorest.Respond( resp, azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusAccepted), autorest.ByClosing()) result.Response = resp return } // PowerOff power off (stop) a virtual machine in a VM scale set. Note that resources are still attached and you are // getting charged for the resources. Instead, use deallocate to release resources and avoid charges. // Parameters: // resourceGroupName - the name of the resource group. // VMScaleSetName - the name of the VM scale set. // instanceID - the instance ID of the virtual machine. // skipShutdown - the parameter to request non-graceful VM shutdown. True value for this flag indicates // non-graceful shutdown whereas false indicates otherwise. Default value for this flag is false if not // specified func (client VirtualMachineScaleSetVMsClient) PowerOff(ctx context.Context, resourceGroupName string, VMScaleSetName string, instanceID string, skipShutdown *bool) (result VirtualMachineScaleSetVMsPowerOffFuture, err error) { if tracing.IsEnabled() { ctx = tracing.StartSpan(ctx, fqdn+"/VirtualMachineScaleSetVMsClient.PowerOff") defer func() { sc := -1 if result.Response() != nil { sc = result.Response().StatusCode } tracing.EndSpan(ctx, sc, err) }() } req, err := client.PowerOffPreparer(ctx, resourceGroupName, VMScaleSetName, instanceID, skipShutdown) if err != nil { err = autorest.NewErrorWithError(err, "compute.VirtualMachineScaleSetVMsClient", "PowerOff", nil, "Failure preparing request") return } result, err = client.PowerOffSender(req) if err != nil { err = autorest.NewErrorWithError(err, "compute.VirtualMachineScaleSetVMsClient", "PowerOff", nil, "Failure sending request") return } return } // PowerOffPreparer prepares the PowerOff request. func (client VirtualMachineScaleSetVMsClient) PowerOffPreparer(ctx context.Context, resourceGroupName string, VMScaleSetName string, instanceID string, skipShutdown *bool) (*http.Request, error) { pathParameters := map[string]interface{}{ "instanceId": autorest.Encode("path", instanceID), "resourceGroupName": autorest.Encode("path", resourceGroupName), "subscriptionId": autorest.Encode("path", client.SubscriptionID), "vmScaleSetName": autorest.Encode("path", VMScaleSetName), } const APIVersion = "2019-07-01" queryParameters := map[string]interface{}{ "api-version": APIVersion, } if skipShutdown != nil { queryParameters["skipShutdown"] = autorest.Encode("query", *skipShutdown) } else { queryParameters["skipShutdown"] = autorest.Encode("query", false) } preparer := autorest.CreatePreparer( autorest.AsPost(), autorest.WithBaseURL(client.BaseURI), autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Compute/virtualMachineScaleSets/{vmScaleSetName}/virtualmachines/{instanceId}/poweroff", pathParameters), autorest.WithQueryParameters(queryParameters)) return preparer.Prepare((&http.Request{}).WithContext(ctx)) } // PowerOffSender sends the PowerOff request. The method will close the // http.Response Body if it receives an error. func (client VirtualMachineScaleSetVMsClient) PowerOffSender(req *http.Request) (future VirtualMachineScaleSetVMsPowerOffFuture, err error) { var resp *http.Response resp, err = client.Send(req, azure.DoRetryWithRegistration(client.Client)) if err != nil { return } var azf azure.Future azf, err = azure.NewFutureFromResponse(resp) future.FutureAPI = &azf future.Result = func(client VirtualMachineScaleSetVMsClient) (ar autorest.Response, err error) { var done bool done, err = future.DoneWithContext(context.Background(), client) if err != nil { err = autorest.NewErrorWithError(err, "compute.VirtualMachineScaleSetVMsPowerOffFuture", "Result", future.Response(), "Polling failure") return } if !done { err = azure.NewAsyncOpIncompleteError("compute.VirtualMachineScaleSetVMsPowerOffFuture") return } ar.Response = future.Response() return } return } // PowerOffResponder handles the response to the PowerOff request. The method always // closes the http.Response Body. func (client VirtualMachineScaleSetVMsClient) PowerOffResponder(resp *http.Response) (result autorest.Response, err error) { err = autorest.Respond( resp, azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusAccepted), autorest.ByClosing()) result.Response = resp return } // Redeploy shuts down the virtual machine in the virtual machine scale set, moves it to a new node, and powers it back // on. // Parameters: // resourceGroupName - the name of the resource group. // VMScaleSetName - the name of the VM scale set. // instanceID - the instance ID of the virtual machine. func (client VirtualMachineScaleSetVMsClient) Redeploy(ctx context.Context, resourceGroupName string, VMScaleSetName string, instanceID string) (result VirtualMachineScaleSetVMsRedeployFuture, err error) { if tracing.IsEnabled() { ctx = tracing.StartSpan(ctx, fqdn+"/VirtualMachineScaleSetVMsClient.Redeploy") defer func() { sc := -1 if result.Response() != nil { sc = result.Response().StatusCode } tracing.EndSpan(ctx, sc, err) }() } req, err := client.RedeployPreparer(ctx, resourceGroupName, VMScaleSetName, instanceID) if err != nil { err = autorest.NewErrorWithError(err, "compute.VirtualMachineScaleSetVMsClient", "Redeploy", nil, "Failure preparing request") return } result, err = client.RedeploySender(req) if err != nil { err = autorest.NewErrorWithError(err, "compute.VirtualMachineScaleSetVMsClient", "Redeploy", nil, "Failure sending request") return } return } // RedeployPreparer prepares the Redeploy request. func (client VirtualMachineScaleSetVMsClient) RedeployPreparer(ctx context.Context, resourceGroupName string, VMScaleSetName string, instanceID string) (*http.Request, error) { pathParameters := map[string]interface{}{ "instanceId": autorest.Encode("path", instanceID), "resourceGroupName": autorest.Encode("path", resourceGroupName), "subscriptionId": autorest.Encode("path", client.SubscriptionID), "vmScaleSetName": autorest.Encode("path", VMScaleSetName), } const APIVersion = "2019-07-01" queryParameters := map[string]interface{}{ "api-version": APIVersion, } preparer := autorest.CreatePreparer( autorest.AsPost(), autorest.WithBaseURL(client.BaseURI), autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Compute/virtualMachineScaleSets/{vmScaleSetName}/virtualmachines/{instanceId}/redeploy", pathParameters), autorest.WithQueryParameters(queryParameters)) return preparer.Prepare((&http.Request{}).WithContext(ctx)) } // RedeploySender sends the Redeploy request. The method will close the // http.Response Body if it receives an error. func (client VirtualMachineScaleSetVMsClient) RedeploySender(req *http.Request) (future VirtualMachineScaleSetVMsRedeployFuture, err error) { var resp *http.Response resp, err = client.Send(req, azure.DoRetryWithRegistration(client.Client)) if err != nil { return } var azf azure.Future azf, err = azure.NewFutureFromResponse(resp) future.FutureAPI = &azf future.Result = func(client VirtualMachineScaleSetVMsClient) (ar autorest.Response, err error) { var done bool done, err = future.DoneWithContext(context.Background(), client) if err != nil { err = autorest.NewErrorWithError(err, "compute.VirtualMachineScaleSetVMsRedeployFuture", "Result", future.Response(), "Polling failure") return } if !done { err = azure.NewAsyncOpIncompleteError("compute.VirtualMachineScaleSetVMsRedeployFuture") return } ar.Response = future.Response() return } return } // RedeployResponder handles the response to the Redeploy request. The method always // closes the http.Response Body. func (client VirtualMachineScaleSetVMsClient) RedeployResponder(resp *http.Response) (result autorest.Response, err error) { err = autorest.Respond( resp, azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusAccepted), autorest.ByClosing()) result.Response = resp return } // Reimage reimages (upgrade the operating system) a specific virtual machine in a VM scale set. // Parameters: // resourceGroupName - the name of the resource group. // VMScaleSetName - the name of the VM scale set. // instanceID - the instance ID of the virtual machine. // VMScaleSetVMReimageInput - parameters for the Reimaging Virtual machine in ScaleSet. func (client VirtualMachineScaleSetVMsClient) Reimage(ctx context.Context, resourceGroupName string, VMScaleSetName string, instanceID string, VMScaleSetVMReimageInput *VirtualMachineScaleSetVMReimageParameters) (result VirtualMachineScaleSetVMsReimageFuture, err error) { if tracing.IsEnabled() { ctx = tracing.StartSpan(ctx, fqdn+"/VirtualMachineScaleSetVMsClient.Reimage") defer func() { sc := -1 if result.Response() != nil { sc = result.Response().StatusCode } tracing.EndSpan(ctx, sc, err) }() } req, err := client.ReimagePreparer(ctx, resourceGroupName, VMScaleSetName, instanceID, VMScaleSetVMReimageInput) if err != nil { err = autorest.NewErrorWithError(err, "compute.VirtualMachineScaleSetVMsClient", "Reimage", nil, "Failure preparing request") return } result, err = client.ReimageSender(req) if err != nil { err = autorest.NewErrorWithError(err, "compute.VirtualMachineScaleSetVMsClient", "Reimage", nil, "Failure sending request") return } return } // ReimagePreparer prepares the Reimage request. func (client VirtualMachineScaleSetVMsClient) ReimagePreparer(ctx context.Context, resourceGroupName string, VMScaleSetName string, instanceID string, VMScaleSetVMReimageInput *VirtualMachineScaleSetVMReimageParameters) (*http.Request, error) { pathParameters := map[string]interface{}{ "instanceId": autorest.Encode("path", instanceID), "resourceGroupName": autorest.Encode("path", resourceGroupName), "subscriptionId": autorest.Encode("path", client.SubscriptionID), "vmScaleSetName": autorest.Encode("path", VMScaleSetName), } const APIVersion = "2019-07-01" queryParameters := map[string]interface{}{ "api-version": APIVersion, } preparer := autorest.CreatePreparer( autorest.AsContentType("application/json; charset=utf-8"), autorest.AsPost(), autorest.WithBaseURL(client.BaseURI), autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Compute/virtualMachineScaleSets/{vmScaleSetName}/virtualmachines/{instanceId}/reimage", pathParameters), autorest.WithQueryParameters(queryParameters)) if VMScaleSetVMReimageInput != nil { preparer = autorest.DecoratePreparer(preparer, autorest.WithJSON(VMScaleSetVMReimageInput)) } return preparer.Prepare((&http.Request{}).WithContext(ctx)) } // ReimageSender sends the Reimage request. The method will close the // http.Response Body if it receives an error. func (client VirtualMachineScaleSetVMsClient) ReimageSender(req *http.Request) (future VirtualMachineScaleSetVMsReimageFuture, err error) { var resp *http.Response resp, err = client.Send(req, azure.DoRetryWithRegistration(client.Client)) if err != nil { return } var azf azure.Future azf, err = azure.NewFutureFromResponse(resp) future.FutureAPI = &azf future.Result = func(client VirtualMachineScaleSetVMsClient) (ar autorest.Response, err error) { var done bool done, err = future.DoneWithContext(context.Background(), client) if err != nil { err = autorest.NewErrorWithError(err, "compute.VirtualMachineScaleSetVMsReimageFuture", "Result", future.Response(), "Polling failure") return } if !done { err = azure.NewAsyncOpIncompleteError("compute.VirtualMachineScaleSetVMsReimageFuture") return } ar.Response = future.Response() return } return } // ReimageResponder handles the response to the Reimage request. The method always // closes the http.Response Body. func (client VirtualMachineScaleSetVMsClient) ReimageResponder(resp *http.Response) (result autorest.Response, err error) { err = autorest.Respond( resp, azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusAccepted), autorest.ByClosing()) result.Response = resp return } // ReimageAll allows you to re-image all the disks ( including data disks ) in the a VM scale set instance. This // operation is only supported for managed disks. // Parameters: // resourceGroupName - the name of the resource group. // VMScaleSetName - the name of the VM scale set. // instanceID - the instance ID of the virtual machine. func (client VirtualMachineScaleSetVMsClient) ReimageAll(ctx context.Context, resourceGroupName string, VMScaleSetName string, instanceID string) (result VirtualMachineScaleSetVMsReimageAllFuture, err error) { if tracing.IsEnabled() { ctx = tracing.StartSpan(ctx, fqdn+"/VirtualMachineScaleSetVMsClient.ReimageAll") defer func() { sc := -1 if result.Response() != nil { sc = result.Response().StatusCode } tracing.EndSpan(ctx, sc, err) }() } req, err := client.ReimageAllPreparer(ctx, resourceGroupName, VMScaleSetName, instanceID) if err != nil { err = autorest.NewErrorWithError(err, "compute.VirtualMachineScaleSetVMsClient", "ReimageAll", nil, "Failure preparing request") return } result, err = client.ReimageAllSender(req) if err != nil { err = autorest.NewErrorWithError(err, "compute.VirtualMachineScaleSetVMsClient", "ReimageAll", nil, "Failure sending request") return } return } // ReimageAllPreparer prepares the ReimageAll request. func (client VirtualMachineScaleSetVMsClient) ReimageAllPreparer(ctx context.Context, resourceGroupName string, VMScaleSetName string, instanceID string) (*http.Request, error) { pathParameters := map[string]interface{}{ "instanceId": autorest.Encode("path", instanceID), "resourceGroupName": autorest.Encode("path", resourceGroupName), "subscriptionId": autorest.Encode("path", client.SubscriptionID), "vmScaleSetName": autorest.Encode("path", VMScaleSetName), } const APIVersion = "2019-07-01" queryParameters := map[string]interface{}{ "api-version": APIVersion, } preparer := autorest.CreatePreparer( autorest.AsPost(), autorest.WithBaseURL(client.BaseURI), autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Compute/virtualMachineScaleSets/{vmScaleSetName}/virtualmachines/{instanceId}/reimageall", pathParameters), autorest.WithQueryParameters(queryParameters)) return preparer.Prepare((&http.Request{}).WithContext(ctx)) } // ReimageAllSender sends the ReimageAll request. The method will close the // http.Response Body if it receives an error. func (client VirtualMachineScaleSetVMsClient) ReimageAllSender(req *http.Request) (future VirtualMachineScaleSetVMsReimageAllFuture, err error) { var resp *http.Response resp, err = client.Send(req, azure.DoRetryWithRegistration(client.Client)) if err != nil { return } var azf azure.Future azf, err = azure.NewFutureFromResponse(resp) future.FutureAPI = &azf future.Result = func(client VirtualMachineScaleSetVMsClient) (ar autorest.Response, err error) { var done bool done, err = future.DoneWithContext(context.Background(), client) if err != nil { err = autorest.NewErrorWithError(err, "compute.VirtualMachineScaleSetVMsReimageAllFuture", "Result", future.Response(), "Polling failure") return } if !done { err = azure.NewAsyncOpIncompleteError("compute.VirtualMachineScaleSetVMsReimageAllFuture") return } ar.Response = future.Response() return } return } // ReimageAllResponder handles the response to the ReimageAll request. The method always // closes the http.Response Body. func (client VirtualMachineScaleSetVMsClient) ReimageAllResponder(resp *http.Response) (result autorest.Response, err error) { err = autorest.Respond( resp, azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusAccepted), autorest.ByClosing()) result.Response = resp return } // Restart restarts a virtual machine in a VM scale set. // Parameters: // resourceGroupName - the name of the resource group. // VMScaleSetName - the name of the VM scale set. // instanceID - the instance ID of the virtual machine. func (client VirtualMachineScaleSetVMsClient) Restart(ctx context.Context, resourceGroupName string, VMScaleSetName string, instanceID string) (result VirtualMachineScaleSetVMsRestartFuture, err error) { if tracing.IsEnabled() { ctx = tracing.StartSpan(ctx, fqdn+"/VirtualMachineScaleSetVMsClient.Restart") defer func() { sc := -1 if result.Response() != nil { sc = result.Response().StatusCode } tracing.EndSpan(ctx, sc, err) }() } req, err := client.RestartPreparer(ctx, resourceGroupName, VMScaleSetName, instanceID) if err != nil { err = autorest.NewErrorWithError(err, "compute.VirtualMachineScaleSetVMsClient", "Restart", nil, "Failure preparing request") return } result, err = client.RestartSender(req) if err != nil { err = autorest.NewErrorWithError(err, "compute.VirtualMachineScaleSetVMsClient", "Restart", nil, "Failure sending request") return } return } // RestartPreparer prepares the Restart request. func (client VirtualMachineScaleSetVMsClient) RestartPreparer(ctx context.Context, resourceGroupName string, VMScaleSetName string, instanceID string) (*http.Request, error) { pathParameters := map[string]interface{}{ "instanceId": autorest.Encode("path", instanceID), "resourceGroupName": autorest.Encode("path", resourceGroupName), "subscriptionId": autorest.Encode("path", client.SubscriptionID), "vmScaleSetName": autorest.Encode("path", VMScaleSetName), } const APIVersion = "2019-07-01" queryParameters := map[string]interface{}{ "api-version": APIVersion, } preparer := autorest.CreatePreparer( autorest.AsPost(), autorest.WithBaseURL(client.BaseURI), autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Compute/virtualMachineScaleSets/{vmScaleSetName}/virtualmachines/{instanceId}/restart", pathParameters), autorest.WithQueryParameters(queryParameters)) return preparer.Prepare((&http.Request{}).WithContext(ctx)) } // RestartSender sends the Restart request. The method will close the // http.Response Body if it receives an error. func (client VirtualMachineScaleSetVMsClient) RestartSender(req *http.Request) (future VirtualMachineScaleSetVMsRestartFuture, err error) { var resp *http.Response resp, err = client.Send(req, azure.DoRetryWithRegistration(client.Client)) if err != nil { return } var azf azure.Future azf, err = azure.NewFutureFromResponse(resp) future.FutureAPI = &azf future.Result = func(client VirtualMachineScaleSetVMsClient) (ar autorest.Response, err error) { var done bool done, err = future.DoneWithContext(context.Background(), client) if err != nil { err = autorest.NewErrorWithError(err, "compute.VirtualMachineScaleSetVMsRestartFuture", "Result", future.Response(), "Polling failure") return } if !done { err = azure.NewAsyncOpIncompleteError("compute.VirtualMachineScaleSetVMsRestartFuture") return } ar.Response = future.Response() return } return } // RestartResponder handles the response to the Restart request. The method always // closes the http.Response Body. func (client VirtualMachineScaleSetVMsClient) RestartResponder(resp *http.Response) (result autorest.Response, err error) { err = autorest.Respond( resp, azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusAccepted), autorest.ByClosing()) result.Response = resp return } // RunCommand run command on a virtual machine in a VM scale set. // Parameters: // resourceGroupName - the name of the resource group. // VMScaleSetName - the name of the VM scale set. // instanceID - the instance ID of the virtual machine. // parameters - parameters supplied to the Run command operation. func (client VirtualMachineScaleSetVMsClient) RunCommand(ctx context.Context, resourceGroupName string, VMScaleSetName string, instanceID string, parameters RunCommandInput) (result VirtualMachineScaleSetVMsRunCommandFuture, err error) { if tracing.IsEnabled() { ctx = tracing.StartSpan(ctx, fqdn+"/VirtualMachineScaleSetVMsClient.RunCommand") defer func() { sc := -1 if result.Response() != nil { sc = result.Response().StatusCode } tracing.EndSpan(ctx, sc, err) }() } if err := validation.Validate([]validation.Validation{ {TargetValue: parameters, Constraints: []validation.Constraint{{Target: "parameters.CommandID", Name: validation.Null, Rule: true, Chain: nil}}}}); err != nil { return result, validation.NewError("compute.VirtualMachineScaleSetVMsClient", "RunCommand", err.Error()) } req, err := client.RunCommandPreparer(ctx, resourceGroupName, VMScaleSetName, instanceID, parameters) if err != nil { err = autorest.NewErrorWithError(err, "compute.VirtualMachineScaleSetVMsClient", "RunCommand", nil, "Failure preparing request") return } result, err = client.RunCommandSender(req) if err != nil { err = autorest.NewErrorWithError(err, "compute.VirtualMachineScaleSetVMsClient", "RunCommand", nil, "Failure sending request") return } return } // RunCommandPreparer prepares the RunCommand request. func (client VirtualMachineScaleSetVMsClient) RunCommandPreparer(ctx context.Context, resourceGroupName string, VMScaleSetName string, instanceID string, parameters RunCommandInput) (*http.Request, error) { pathParameters := map[string]interface{}{ "instanceId": autorest.Encode("path", instanceID), "resourceGroupName": autorest.Encode("path", resourceGroupName), "subscriptionId": autorest.Encode("path", client.SubscriptionID), "vmScaleSetName": autorest.Encode("path", VMScaleSetName), } const APIVersion = "2019-07-01" queryParameters := map[string]interface{}{ "api-version": APIVersion, } preparer := autorest.CreatePreparer( autorest.AsContentType("application/json; charset=utf-8"), autorest.AsPost(), autorest.WithBaseURL(client.BaseURI), autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Compute/virtualMachineScaleSets/{vmScaleSetName}/virtualmachines/{instanceId}/runCommand", pathParameters), autorest.WithJSON(parameters), autorest.WithQueryParameters(queryParameters)) return preparer.Prepare((&http.Request{}).WithContext(ctx)) } // RunCommandSender sends the RunCommand request. The method will close the // http.Response Body if it receives an error. func (client VirtualMachineScaleSetVMsClient) RunCommandSender(req *http.Request) (future VirtualMachineScaleSetVMsRunCommandFuture, err error) { var resp *http.Response resp, err = client.Send(req, azure.DoRetryWithRegistration(client.Client)) if err != nil { return } var azf azure.Future azf, err = azure.NewFutureFromResponse(resp) future.FutureAPI = &azf future.Result = func(client VirtualMachineScaleSetVMsClient) (rcr RunCommandResult, err error) { var done bool done, err = future.DoneWithContext(context.Background(), client) if err != nil { err = autorest.NewErrorWithError(err, "compute.VirtualMachineScaleSetVMsRunCommandFuture", "Result", future.Response(), "Polling failure") return } if !done { err = azure.NewAsyncOpIncompleteError("compute.VirtualMachineScaleSetVMsRunCommandFuture") return } sender := autorest.DecorateSender(client, autorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...)) if rcr.Response.Response, err = future.GetResult(sender); err == nil && rcr.Response.Response.StatusCode != http.StatusNoContent { rcr, err = client.RunCommandResponder(rcr.Response.Response) if err != nil { err = autorest.NewErrorWithError(err, "compute.VirtualMachineScaleSetVMsRunCommandFuture", "Result", rcr.Response.Response, "Failure responding to request") } } return } return } // RunCommandResponder handles the response to the RunCommand request. The method always // closes the http.Response Body. func (client VirtualMachineScaleSetVMsClient) RunCommandResponder(resp *http.Response) (result RunCommandResult, err error) { err = autorest.Respond( resp, azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusAccepted), autorest.ByUnmarshallingJSON(&result), autorest.ByClosing()) result.Response = autorest.Response{Response: resp} return } // Start starts a virtual machine in a VM scale set. // Parameters: // resourceGroupName - the name of the resource group. // VMScaleSetName - the name of the VM scale set. // instanceID - the instance ID of the virtual machine. func (client VirtualMachineScaleSetVMsClient) Start(ctx context.Context, resourceGroupName string, VMScaleSetName string, instanceID string) (result VirtualMachineScaleSetVMsStartFuture, err error) { if tracing.IsEnabled() { ctx = tracing.StartSpan(ctx, fqdn+"/VirtualMachineScaleSetVMsClient.Start") defer func() { sc := -1 if result.Response() != nil { sc = result.Response().StatusCode } tracing.EndSpan(ctx, sc, err) }() } req, err := client.StartPreparer(ctx, resourceGroupName, VMScaleSetName, instanceID) if err != nil { err = autorest.NewErrorWithError(err, "compute.VirtualMachineScaleSetVMsClient", "Start", nil, "Failure preparing request") return } result, err = client.StartSender(req) if err != nil { err = autorest.NewErrorWithError(err, "compute.VirtualMachineScaleSetVMsClient", "Start", nil, "Failure sending request") return } return } // StartPreparer prepares the Start request. func (client VirtualMachineScaleSetVMsClient) StartPreparer(ctx context.Context, resourceGroupName string, VMScaleSetName string, instanceID string) (*http.Request, error) { pathParameters := map[string]interface{}{ "instanceId": autorest.Encode("path", instanceID), "resourceGroupName": autorest.Encode("path", resourceGroupName), "subscriptionId": autorest.Encode("path", client.SubscriptionID), "vmScaleSetName": autorest.Encode("path", VMScaleSetName), } const APIVersion = "2019-07-01" queryParameters := map[string]interface{}{ "api-version": APIVersion, } preparer := autorest.CreatePreparer( autorest.AsPost(), autorest.WithBaseURL(client.BaseURI), autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Compute/virtualMachineScaleSets/{vmScaleSetName}/virtualmachines/{instanceId}/start", pathParameters), autorest.WithQueryParameters(queryParameters)) return preparer.Prepare((&http.Request{}).WithContext(ctx)) } // StartSender sends the Start request. The method will close the // http.Response Body if it receives an error. func (client VirtualMachineScaleSetVMsClient) StartSender(req *http.Request) (future VirtualMachineScaleSetVMsStartFuture, err error) { var resp *http.Response resp, err = client.Send(req, azure.DoRetryWithRegistration(client.Client)) if err != nil { return } var azf azure.Future azf, err = azure.NewFutureFromResponse(resp) future.FutureAPI = &azf future.Result = func(client VirtualMachineScaleSetVMsClient) (ar autorest.Response, err error) { var done bool done, err = future.DoneWithContext(context.Background(), client) if err != nil { err = autorest.NewErrorWithError(err, "compute.VirtualMachineScaleSetVMsStartFuture", "Result", future.Response(), "Polling failure") return } if !done { err = azure.NewAsyncOpIncompleteError("compute.VirtualMachineScaleSetVMsStartFuture") return } ar.Response = future.Response() return } return } // StartResponder handles the response to the Start request. The method always // closes the http.Response Body. func (client VirtualMachineScaleSetVMsClient) StartResponder(resp *http.Response) (result autorest.Response, err error) { err = autorest.Respond( resp, azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusAccepted), autorest.ByClosing()) result.Response = resp return } // Update updates a virtual machine of a VM scale set. // Parameters: // resourceGroupName - the name of the resource group. // VMScaleSetName - the name of the VM scale set where the extension should be create or updated. // instanceID - the instance ID of the virtual machine. // parameters - parameters supplied to the Update Virtual Machine Scale Sets VM operation. func (client VirtualMachineScaleSetVMsClient) Update(ctx context.Context, resourceGroupName string, VMScaleSetName string, instanceID string, parameters VirtualMachineScaleSetVM) (result VirtualMachineScaleSetVMsUpdateFuture, err error) { if tracing.IsEnabled() { ctx = tracing.StartSpan(ctx, fqdn+"/VirtualMachineScaleSetVMsClient.Update") defer func() { sc := -1 if result.Response() != nil { sc = result.Response().StatusCode } tracing.EndSpan(ctx, sc, err) }() } if err := validation.Validate([]validation.Validation{ {TargetValue: parameters, Constraints: []validation.Constraint{{Target: "parameters.VirtualMachineScaleSetVMProperties", Name: validation.Null, Rule: false, Chain: []validation.Constraint{{Target: "parameters.VirtualMachineScaleSetVMProperties.StorageProfile", Name: validation.Null, Rule: false, Chain: []validation.Constraint{{Target: "parameters.VirtualMachineScaleSetVMProperties.StorageProfile.OsDisk", Name: validation.Null, Rule: false, Chain: []validation.Constraint{{Target: "parameters.VirtualMachineScaleSetVMProperties.StorageProfile.OsDisk.EncryptionSettings", Name: validation.Null, Rule: false, Chain: []validation.Constraint{{Target: "parameters.VirtualMachineScaleSetVMProperties.StorageProfile.OsDisk.EncryptionSettings.DiskEncryptionKey", Name: validation.Null, Rule: false, Chain: []validation.Constraint{{Target: "parameters.VirtualMachineScaleSetVMProperties.StorageProfile.OsDisk.EncryptionSettings.DiskEncryptionKey.SecretURL", Name: validation.Null, Rule: true, Chain: nil}, {Target: "parameters.VirtualMachineScaleSetVMProperties.StorageProfile.OsDisk.EncryptionSettings.DiskEncryptionKey.SourceVault", Name: validation.Null, Rule: true, Chain: nil}, }}, {Target: "parameters.VirtualMachineScaleSetVMProperties.StorageProfile.OsDisk.EncryptionSettings.KeyEncryptionKey", Name: validation.Null, Rule: false, Chain: []validation.Constraint{{Target: "parameters.VirtualMachineScaleSetVMProperties.StorageProfile.OsDisk.EncryptionSettings.KeyEncryptionKey.KeyURL", Name: validation.Null, Rule: true, Chain: nil}, {Target: "parameters.VirtualMachineScaleSetVMProperties.StorageProfile.OsDisk.EncryptionSettings.KeyEncryptionKey.SourceVault", Name: validation.Null, Rule: true, Chain: nil}, }}, }}, }}, }}, }}}}}); err != nil { return result, validation.NewError("compute.VirtualMachineScaleSetVMsClient", "Update", err.Error()) } req, err := client.UpdatePreparer(ctx, resourceGroupName, VMScaleSetName, instanceID, parameters) if err != nil { err = autorest.NewErrorWithError(err, "compute.VirtualMachineScaleSetVMsClient", "Update", nil, "Failure preparing request") return } result, err = client.UpdateSender(req) if err != nil { err = autorest.NewErrorWithError(err, "compute.VirtualMachineScaleSetVMsClient", "Update", nil, "Failure sending request") return } return } // UpdatePreparer prepares the Update request. func (client VirtualMachineScaleSetVMsClient) UpdatePreparer(ctx context.Context, resourceGroupName string, VMScaleSetName string, instanceID string, parameters VirtualMachineScaleSetVM) (*http.Request, error) { pathParameters := map[string]interface{}{ "instanceId": autorest.Encode("path", instanceID), "resourceGroupName": autorest.Encode("path", resourceGroupName), "subscriptionId": autorest.Encode("path", client.SubscriptionID), "vmScaleSetName": autorest.Encode("path", VMScaleSetName), } const APIVersion = "2019-07-01" queryParameters := map[string]interface{}{ "api-version": APIVersion, } parameters.InstanceID = nil parameters.Sku = nil parameters.Resources = nil parameters.Zones = nil preparer := autorest.CreatePreparer( autorest.AsContentType("application/json; charset=utf-8"), autorest.AsPut(), autorest.WithBaseURL(client.BaseURI), autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Compute/virtualMachineScaleSets/{vmScaleSetName}/virtualmachines/{instanceId}", pathParameters), autorest.WithJSON(parameters), autorest.WithQueryParameters(queryParameters)) return preparer.Prepare((&http.Request{}).WithContext(ctx)) } // UpdateSender sends the Update request. The method will close the // http.Response Body if it receives an error. func (client VirtualMachineScaleSetVMsClient) UpdateSender(req *http.Request) (future VirtualMachineScaleSetVMsUpdateFuture, err error) { var resp *http.Response resp, err = client.Send(req, azure.DoRetryWithRegistration(client.Client)) if err != nil { return } var azf azure.Future azf, err = azure.NewFutureFromResponse(resp) future.FutureAPI = &azf future.Result = func(client VirtualMachineScaleSetVMsClient) (vmssv VirtualMachineScaleSetVM, err error) { var done bool done, err = future.DoneWithContext(context.Background(), client) if err != nil { err = autorest.NewErrorWithError(err, "compute.VirtualMachineScaleSetVMsUpdateFuture", "Result", future.Response(), "Polling failure") return } if !done { err = azure.NewAsyncOpIncompleteError("compute.VirtualMachineScaleSetVMsUpdateFuture") return } sender := autorest.DecorateSender(client, autorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...)) if vmssv.Response.Response, err = future.GetResult(sender); err == nil && vmssv.Response.Response.StatusCode != http.StatusNoContent { vmssv, err = client.UpdateResponder(vmssv.Response.Response) if err != nil { err = autorest.NewErrorWithError(err, "compute.VirtualMachineScaleSetVMsUpdateFuture", "Result", vmssv.Response.Response, "Failure responding to request") } } return } return } // UpdateResponder handles the response to the Update request. The method always // closes the http.Response Body. func (client VirtualMachineScaleSetVMsClient) UpdateResponder(resp *http.Response) (result VirtualMachineScaleSetVM, err error) { err = autorest.Respond( resp, azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusAccepted), autorest.ByUnmarshallingJSON(&result), autorest.ByClosing()) result.Response = autorest.Response{Response: resp} return }
hartsock/vault
vendor/github.com/Azure/azure-sdk-for-go/services/compute/mgmt/2019-07-01/compute/virtualmachinescalesetvms.go
GO
mpl-2.0
60,751
// Chemfiles, a modern library for chemistry file reading and writing // Copyright (C) Guillaume Fraux and contributors -- BSD license #include <cstdint> #include <string> #include "chemfiles/capi/types.h" #include "chemfiles/capi/misc.h" #include "chemfiles/capi/utils.hpp" #include "chemfiles/capi/shared_allocator.hpp" #include "chemfiles/capi/frame.h" #include "chemfiles/Frame.hpp" #include "chemfiles/error_fmt.hpp" #include "chemfiles/Property.hpp" #include "chemfiles/Connectivity.hpp" #include "chemfiles/types.hpp" #include "chemfiles/external/optional.hpp" #include "chemfiles/external/span.hpp" using namespace chemfiles; extern "C" CHFL_FRAME* chfl_frame(void) { CHFL_FRAME* frame = nullptr; CHFL_ERROR_GOTO( frame = shared_allocator::make_shared<Frame>(); ) return frame; error: chfl_free(frame); return nullptr; } extern "C" CHFL_FRAME* chfl_frame_copy(const CHFL_FRAME* const frame) { CHFL_FRAME* new_frame = nullptr; CHFL_ERROR_GOTO( new_frame = shared_allocator::make_shared<Frame>(frame->clone()); ) return new_frame; error: chfl_free(new_frame); return nullptr; } extern "C" chfl_status chfl_frame_atoms_count(const CHFL_FRAME* const frame, uint64_t* const count) { CHECK_POINTER(frame); CHECK_POINTER(count); CHFL_ERROR_CATCH( *count = static_cast<uint64_t>(frame->size()); ) } extern "C" chfl_status chfl_frame_positions(CHFL_FRAME* const frame, chfl_vector3d** positions, uint64_t* size) { CHECK_POINTER(frame); CHECK_POINTER(positions); CHECK_POINTER(size); static_assert( sizeof(chfl_vector3d) == sizeof(Vector3D), "Wrong size for chfl_vector3d. It should match Vector3D." ); CHFL_ERROR_CATCH( auto cpp_positions = frame->positions(); *size = cpp_positions.size(); *positions = reinterpret_cast<chfl_vector3d*>(cpp_positions.data()); ) } extern "C" chfl_status chfl_frame_velocities(CHFL_FRAME* const frame, chfl_vector3d** velocities, uint64_t* size) { CHECK_POINTER(frame); CHECK_POINTER(velocities); CHECK_POINTER(size); static_assert( sizeof(chfl_vector3d) == sizeof(Vector3D), "Wrong size for chfl_vector3d. It should match Vector3D." ); if (!frame->velocities()) { set_last_error("velocity data is not defined in this frame"); return CHFL_MEMORY_ERROR; } CHFL_ERROR_CATCH( auto cpp_velocities = frame->velocities(); *size = cpp_velocities->size(); *velocities = reinterpret_cast<chfl_vector3d*>(cpp_velocities->data()); ) } extern "C" chfl_status chfl_frame_add_atom( CHFL_FRAME* const frame, const CHFL_ATOM* const atom, const chfl_vector3d position, const chfl_vector3d velocity ) { CHECK_POINTER(frame); CHECK_POINTER(atom); CHECK_POINTER(position); CHFL_ERROR_CATCH( if (velocity != nullptr) { frame->add_atom(*atom, vector3d(position), vector3d(velocity)); } else { frame->add_atom(*atom, vector3d(position)); } ) } extern "C" chfl_status chfl_frame_remove(CHFL_FRAME* const frame, uint64_t i) { CHECK_POINTER(frame); CHFL_ERROR_CATCH( frame->remove(checked_cast(i)); ) } extern "C" chfl_status chfl_frame_resize(CHFL_FRAME* const frame, uint64_t size) { CHECK_POINTER(frame); CHFL_ERROR_CATCH( frame->resize(checked_cast(size)); ) } extern "C" chfl_status chfl_frame_add_velocities(CHFL_FRAME* const frame) { CHECK_POINTER(frame); CHFL_ERROR_CATCH( frame->add_velocities(); ) } extern "C" chfl_status chfl_frame_has_velocities(const CHFL_FRAME* const frame, bool* has_velocities) { CHECK_POINTER(frame); CHECK_POINTER(has_velocities); CHFL_ERROR_CATCH( *has_velocities = bool(frame->velocities()); ) } extern "C" chfl_status chfl_frame_set_cell(CHFL_FRAME* const frame, const CHFL_CELL* const cell) { CHECK_POINTER(frame); CHECK_POINTER(cell); CHFL_ERROR_CATCH( frame->set_cell(*cell); ) } extern "C" chfl_status chfl_frame_set_topology(CHFL_FRAME* const frame, const CHFL_TOPOLOGY* const topology) { CHECK_POINTER(frame); CHECK_POINTER(topology); CHFL_ERROR_CATCH( frame->set_topology(*topology); ) } extern "C" chfl_status chfl_frame_step(const CHFL_FRAME* const frame, uint64_t* step) { CHECK_POINTER(frame); CHECK_POINTER(step); CHFL_ERROR_CATCH( *step = frame->step(); ) } extern "C" chfl_status chfl_frame_set_step(CHFL_FRAME* const frame, uint64_t step) { CHECK_POINTER(frame); CHFL_ERROR_CATCH( frame->set_step(checked_cast(step)); ) } extern "C" chfl_status chfl_frame_guess_bonds(CHFL_FRAME* const frame) { CHECK_POINTER(frame); CHFL_ERROR_CATCH( frame->guess_bonds(); ) } extern "C" chfl_status chfl_frame_distance(const CHFL_FRAME* const frame, uint64_t i, uint64_t j, double* distance) { CHECK_POINTER(frame); CHECK_POINTER(distance); CHFL_ERROR_CATCH( *distance = frame->distance(checked_cast(i), checked_cast(j)); ) } extern "C" chfl_status chfl_frame_angle(const CHFL_FRAME* const frame, uint64_t i, uint64_t j, uint64_t k, double* angle) { CHECK_POINTER(frame); CHECK_POINTER(angle); CHFL_ERROR_CATCH( *angle = frame->angle(checked_cast(i), checked_cast(j), checked_cast(k)); ) } extern "C" chfl_status chfl_frame_dihedral(const CHFL_FRAME* const frame, uint64_t i, uint64_t j, uint64_t k, uint64_t m, double* dihedral) { CHECK_POINTER(frame); CHECK_POINTER(dihedral); CHFL_ERROR_CATCH( *dihedral = frame->dihedral( checked_cast(i), checked_cast(j), checked_cast(k), checked_cast(m) ); ) } extern "C" chfl_status chfl_frame_out_of_plane(const CHFL_FRAME* const frame, uint64_t i, uint64_t j, uint64_t k, uint64_t m, double* distance) { CHECK_POINTER(frame); CHECK_POINTER(distance); CHFL_ERROR_CATCH( *distance = frame->out_of_plane( checked_cast(i), checked_cast(j), checked_cast(k), checked_cast(m) ); ) } extern "C" chfl_status chfl_frame_properties_count(const CHFL_FRAME* const frame, uint64_t* const count) { CHECK_POINTER(frame); CHECK_POINTER(count); CHFL_ERROR_CATCH( *count = static_cast<uint64_t>(frame->properties().size()); ) } extern "C" chfl_status chfl_frame_list_properties(const CHFL_FRAME* const frame, const char* names[], uint64_t count) { CHECK_POINTER(frame); CHECK_POINTER(names); CHFL_ERROR_CATCH( auto& properties = frame->properties(); if (checked_cast(count) != properties.size()) { set_last_error("wrong data size in function 'chfl_frame_list_properties'."); return CHFL_MEMORY_ERROR; } size_t i = 0; for (auto& it: properties) { names[i] = it.first.c_str(); i++; } ) } extern "C" chfl_status chfl_frame_set_property(CHFL_FRAME* const frame, const char* name, const CHFL_PROPERTY* const property) { CHECK_POINTER(frame); CHECK_POINTER(name); CHECK_POINTER(property); CHFL_ERROR_CATCH( frame->set(name, *property); ) } extern "C" CHFL_PROPERTY* chfl_frame_get_property(const CHFL_FRAME* const frame, const char* name) { CHFL_PROPERTY* property = nullptr; CHECK_POINTER_GOTO(frame); CHECK_POINTER_GOTO(name); CHFL_ERROR_GOTO( auto atom_property = frame->get(name); if (atom_property) { property = shared_allocator::make_shared<Property>(*atom_property); } else { throw property_error("can not find a property named '{}' in this frame", name); } ) return property; error: chfl_free(property); return nullptr; } extern "C" chfl_status chfl_frame_add_bond(CHFL_FRAME* const frame, uint64_t i, uint64_t j) { CHECK_POINTER(frame); CHFL_ERROR_CATCH( frame->add_bond(checked_cast(i), checked_cast(j)); ) } extern "C" chfl_status chfl_frame_bond_with_order(CHFL_FRAME* const frame, uint64_t i, uint64_t j, chfl_bond_order bond_order) { CHECK_POINTER(frame); CHFL_ERROR_CATCH( frame->add_bond(checked_cast(i), checked_cast(j), static_cast<Bond::BondOrder>(bond_order)); ) } extern "C" chfl_status chfl_frame_remove_bond(CHFL_FRAME* const frame, uint64_t i, uint64_t j) { CHECK_POINTER(frame); CHFL_ERROR_CATCH( frame->remove_bond(checked_cast(i), checked_cast(j)); ) } extern "C" chfl_status chfl_frame_clear_bonds(CHFL_FRAME* const frame) { CHECK_POINTER(frame); CHFL_ERROR_CATCH( frame->clear_bonds(); ) } extern "C" chfl_status chfl_frame_add_residue(CHFL_FRAME* const frame, const CHFL_RESIDUE* const residue) { CHECK_POINTER(frame); CHECK_POINTER(residue); CHFL_ERROR_CATCH( frame->add_residue(*residue); ) }
Luthaf/Chemharp
src/capi/frame.cpp
C++
mpl-2.0
8,929
package com.servinglynk.hmis.warehouse.enums; import java.util.HashMap; import java.util.Map; public enum DataCollectionStageEnum { /** Enum Constant. */ ONE("1"), /** Enum Constant. */ TWO("2"), /** Enum Constant. */ THREE("3"), /** Enum Constant. */ FIVE("5"); /** * Internal storage of status field value, see the Enum spec for * clarification. */ private final String status; /** * Enum constructor for ActiveState. * @param state Value. */ DataCollectionStageEnum(final String state) { this.status = state; } /** Construct a map for reverse lookup. */ private static Map<String, DataCollectionStageEnum> valueMap = new HashMap<String, DataCollectionStageEnum>(); static { // construct hashmap for later possible use. for (DataCollectionStageEnum unit : values()) { valueMap.put(unit.getValue(), unit); } } /** * Current string value stored in the enum. * * @return string value. */ public String getValue() { return this.status; } /** * Perform a reverse lookup (given a value, obtain the enum). * * @param value to search * @return Enum object. */ public static DataCollectionStageEnum lookupEnum(String value) { return DataCollectionStageEnum.valueMap.get(value); } }
servinglynk/hmis-lynk-open-source
hmis-base-model/src/main/java/com/servinglynk/hmis/warehouse/enums/DataCollectionStageEnum.java
Java
mpl-2.0
1,318
/** * This file is part of veraPDF Library core, a module of the veraPDF project. * Copyright (c) 2015, veraPDF Consortium <info@verapdf.org> * All rights reserved. * * veraPDF Library core is free software: you can redistribute it and/or modify * it under the terms of either: * * The GNU General public license GPLv3+. * You should have received a copy of the GNU General Public License * along with veraPDF Library core as the LICENSE.GPL file in the root of the source * tree. If not, see http://www.gnu.org/licenses/ or * https://www.gnu.org/licenses/gpl-3.0.en.html. * * The Mozilla Public License MPLv2+. * You should have received a copy of the Mozilla Public License along with * veraPDF Library core as the LICENSE.MPL file in the root of the source tree. * If a copy of the MPL was not distributed with this file, you can obtain one at * http://mozilla.org/MPL/2.0/. */ package org.verapdf.features.tools; import java.util.logging.Level; import java.util.logging.Logger; import org.verapdf.core.FeatureParsingException; import org.verapdf.features.FeatureExtractionResult; import org.verapdf.features.FeatureObjectType; /** * Static class with constants for feature error ids and messages * * @author Maksim Bezrukov */ public final class ErrorsHelper { private static final FeatureObjectType TYPE = FeatureObjectType.ERROR; private static final Logger LOGGER = Logger.getLogger(ErrorsHelper.class.getName()); public static final String ERRORID = "errorId"; public static final String ID = "id"; private ErrorsHelper() { // Disable default public constructor } /** * Adds an error to a {@link FeaturesCollection} * * @param collection * the {@link FeaturesCollection} to add the error to * @param element * element which contains error * @param errorMessageArg * the error message * @return id of the generated error node as String */ public static String addErrorIntoCollection(FeatureExtractionResult collection, FeatureTreeNode element, String errorMessageArg) { if (collection == null) { throw new IllegalArgumentException("Collection can not be null"); } String errorMessage = errorMessageArg; if (errorMessage == null) { errorMessage = "Exception with null message."; } try { String id = null; for (FeatureTreeNode errNode : collection.getFeatureTreesForType(TYPE)) { if (errorMessage.equals(errNode.getValue())) { id = errNode.getAttributes().get(ID); break; } } if (id == null) { id = TYPE.getNodeName() + collection.getFeatureTreesForType(TYPE).size(); FeatureTreeNode error = FeatureTreeNode.createRootNode(TYPE.getNodeName()); error.setValue(errorMessage); error.setAttribute(ErrorsHelper.ID, id); collection.addNewFeatureTree(TYPE, error); } if (element != null) { String elementErrorID = id; if (element.getAttributes().get(ERRORID) != null) { elementErrorID = element.getAttributes().get(ERRORID) + ", " + elementErrorID; } element.setAttribute(ERRORID, elementErrorID); } return id; } catch (FeatureParsingException ignore) { // This exception occurs when wrong node creates for feature tree. // The logic of the method guarantees this doesn't occur. String message = "FeatureTreeNode root instance logic failure"; LOGGER.log(Level.SEVERE, message, ignore); throw new IllegalStateException(message, ignore); } } }
carlwilson/veraPDF-library
core/src/main/java/org/verapdf/features/tools/ErrorsHelper.java
Java
mpl-2.0
3,457
/* * Copyright 2004-2013 H2 Group. Multiple-Licensed under the H2 License, * Version 1.0, and under the Eclipse Public License, Version 1.0 * (http://h2database.com/html/license.html). * Initial Developer: H2 Group */ package org.h2.command.dml; import java.sql.ResultSet; import org.h2.command.CommandInterface; import org.h2.command.Prepared; import org.h2.engine.Session; import org.h2.expression.Expression; import org.h2.expression.ExpressionVisitor; import org.h2.result.LocalResult; import org.h2.result.ResultInterface; import org.h2.value.Value; /** * This class represents the statement * CALL. */ public class Call extends Prepared { private boolean isResultSet; private Expression expression; private Expression[] expressions; public Call(Session session) { super(session); } @Override public ResultInterface queryMeta() { LocalResult result; if (isResultSet) { Expression[] expr = expression.getExpressionColumns(session); result = new LocalResult(session, expr, expr.length); } else { result = new LocalResult(session, expressions, 1); } result.done(); return result; } @Override public int update() { Value v = expression.getValue(session); int type = v.getType(); switch(type) { case Value.RESULT_SET: // this will throw an exception // methods returning a result set may not be called like this. return super.update(); case Value.UNKNOWN: case Value.NULL: return 0; default: return v.getInt(); } } @Override public ResultInterface query(int maxrows) { setCurrentRowNumber(1); Value v = expression.getValue(session); if (isResultSet) { v = v.convertTo(Value.RESULT_SET); ResultSet rs = v.getResultSet(); return LocalResult.read(session, rs, maxrows); } LocalResult result = new LocalResult(session, expressions, 1); Value[] row = { v }; result.addRow(row); result.done(); return result; } @Override public void prepare() { expression = expression.optimize(session); expressions = new Expression[] { expression }; isResultSet = expression.getType() == Value.RESULT_SET; if (isResultSet) { prepareAlways = true; } } public void setExpression(Expression expression) { this.expression = expression; } @Override public boolean isQuery() { return true; } @Override public boolean isTransactional() { return true; } @Override public boolean isReadOnly() { return expression.isEverything(ExpressionVisitor.READONLY_VISITOR); } @Override public int getType() { return CommandInterface.CALL; } @Override public boolean isCacheable() { return !isResultSet; } }
miloszpiglas/h2mod
src/main/org/h2/command/dml/Call.java
Java
mpl-2.0
3,050
<?php /****************************************************************************** * Copyright (C) 2006 Jonas Genannt <jonas.genannt@brachium-system.net> * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. ******************************************************************************/ if (isset($_POST['autores_submit'])) { if (empty($_POST['autores_subject']) && $_POST['autores_active'] == 'y') { $smarty->assign('error_msg','y'); $smarty->assign('if_error_autores_subject_empty', 'y'); $error=true; } else if (empty($_POST['autores_msg']) && $_POST['autores_active'] == 'y') { $smarty->assign('error_msg','y'); $smarty->assign('if_error_autores_msg_empty', 'y'); $error=true; } else if(strlen($_POST['autores_subject']) > 50 && $_POST['autores_active'] == 'y') { $smarty->assign('error_msg','y'); $smarty->assign('if_error_autores_subject_to_long', 'y'); $error=true; } else if ( $_POST['autores_sendback_times'] != "n" && ($_POST['autores_sendback_times'] < 1 && $_POST['autores_sendback_times'] > 5 )) { $smarty->assign('error_msg','y'); $smarty->assign('if_error_autores_send_times', 'y'); $error=true; } else { save_autoresponder($_SESSION['uid'], $_POST['autores_active'], $_POST['autores_subject'], $_POST['autores_msg'], $_POST['autores_sendback_times']); // activate System-Script run_systemscripts(); } } if (isset($_POST['val_tos_active'])&& is_numeric($_POST['val_tos_active'])) { update_email_options($_SESSION['uid'],"auto_val_tos_active",$_POST['val_tos_active'], 0); } if(isset($_POST['val_tos_del'])) { val_tos_del($_SESSION['uid'],$_POST['val_tos']); } if(isset($_POST['val_tos_add'])) { if (val_tos_add($_SESSION['uid'], $_POST['val_tos_da'])== 1) { $smarty->assign('error_msg','y'); $smarty->assign('if_submit_email_wrong', 'y'); } } //xheader disable feature if ($_SESSION['p_autores_xheader'] == 1) { if (isset($_GET['xheader']) && is_numeric($_GET['xheader']) && isset($_GET['do']) && $_GET['do']=='del') { $sql=sprintf("DELETE FROM autoresponder_xheader WHERE email='%d' AND id='%d'", $db->escapeSimple($_SESSION['uid']), $db->escapeSimple($_GET['xheader'])); $db->query($sql); } if (isset($_POST['xheader_submit'])) { if (!empty($_POST['xheader_name']) && !empty($_POST['xheader_value'])) { $sql=sprintf("INSERT INTO autoresponder_xheader SET email='%d',xheader='%s',value='%s'", $db->escapeSimple($_SESSION['uid']), $db->escapeSimple($_POST['xheader_name']), $db->escapeSimple($_POST['xheader_value'])); $db->query($sql); } else { $smarty->assign('error_msg','y'); $smarty->assign('if_xheader_empty', 'y'); } } } //save automatic autoresponder disable feaure if (isset($_POST['autores_datedisable_submit'])) { if ($_POST['autores_datedisable_active'] == 0) { $sql=sprintf("UPDATE autoresponder_disable SET active='0' WHERE email='%d'", $db->escapeSimple($_SESSION['uid'])); $result=&$db->query($sql); } elseif (! preg_match('/^([0-9]{2}).([0-9]{2}).([0-9]{4})$/', $_POST['autores_datedisable_date'])) { $smarty->assign('error_msg','y'); $smarty->assign('if_error_autores_date_wrong', 'y'); } elseif (! preg_match('/^([0-9]{2}):([0-9]{2}):([0-9]{2})$/', $_POST['autores_datedisable_time'])) { $smarty->assign('error_msg','y'); $smarty->assign('if_error_autores_time_wrong', 'y'); } elseif (! check_autores_date_disable($_POST['autores_datedisable_date'],$_POST['autores_datedisable_time'])) { $smarty->assign('error_msg','y'); $smarty->assign('if_error_autores_disable_in_past', 'y'); } else { $unix_time=autores_date_format($_POST['autores_datedisable_date'],$_POST['autores_datedisable_time']); $sql=sprintf("SELECT id FROM autoresponder_disable WHERE email='%d'", $db->escapeSimple($_SESSION['uid'])); $result=&$db->query($sql); if ($result->numRows() == 1) { $data=$result->fetchrow(DB_FETCHMODE_ASSOC); $sql=sprintf("UPDATE autoresponder_disable SET a_date=FROM_UNIXTIME('%s'), active='1' WHERE email='%d'", $db->escapeSimple($unix_time), $db->escapeSimple($_SESSION['uid'])); } else { $sql=sprintf("INSERT INTO autoresponder_disable SET a_date=FROM_UNIXTIME('%s'),email='%d',active='1'", $db->escapeSimple($unix_time), $db->escapeSimple($_SESSION['uid'])); } $result=&$db->query($sql); } } $sql=sprintf("SELECT id,email,active,msg,esubject,times FROM autoresponder WHERE email='%d'", $db->escapeSimple($_SESSION['uid'])); $result=&$db->query($sql); if ($result->numRows()==1) { $data=$result->fetchrow(DB_FETCHMODE_ASSOC); $active=$data['active']; $msg=$data['msg']; $esubject=$data['esubject']; $id=$data['id']; $times=$data['times']; } elseif(isset($error)) { $active=$_POST['autores_active']; $msg=$_POST['autores_msg']; $esubject=$_POST['autores_subject']; $times=$_POST['autores_sendback_times']; } else { $active='n'; } // outout val_tos $sql=sprintf("SELECT recip,id FROM autoresponder_recipient WHERE email='%d'", $db->escapeSimple($_SESSION['uid'])); $result=&$db->query($sql); $table_val_tos = array(); while($data=$result->fetchrow(DB_FETCHMODE_ASSOC)) { array_push($table_val_tos,array( 'recip' => $data['recip'], 'id' => $data['id'])); } //output val_tos_active $val_tos_active = get_email_options($_SESSION['uid'],"auto_val_tos_active", 0); $smarty->assign('val_tos_active', $val_tos_active); //output autoresponder disabled feature $autores_disable=get_autores_disable($_SESSION['uid']); //output xheader feature if ($_SESSION['p_autores_xheader'] == 1) { $sql=sprintf("SELECT * FROM autoresponder_xheader WHERE email='%d' ORDER BY xheader", $db->escapeSimple($_SESSION['uid'])); $result=&$db->query($sql); $table_xheader=array(); while($data=$result->fetchrow(DB_FETCHMODE_ASSOC)) { array_push($table_xheader,array( 'id' => $data['id'], 'xheader' => $data['xheader'], 'value' => $data['value'])); } $smarty->assign('table_xheader',$table_xheader); } if(isset($autores_disable)) $smarty->assign('autores_disable', $autores_disable); else $smarty->assign('autores_disable', false); if(isset($table_val_tos)) $smarty->assign('table_val_tos', $table_val_tos); else $smarty->assign('table_val_tos', false); if(isset($esubject)) $smarty->assign('autores_subject', $esubject); else $smarty->assign('autores_subject', false); if(isset($active)) $smarty->assign('autores_active', $active); else $smarty->assign('autores_active', $active); if(isset($times)) $smarty->assign('autores_sendback_times_value', $times); else $smarty->assign('autores_sendback_times_value', false); if(isset($id)) $smarty->assign('id', $id); else $smarty->assign('id', false); if(isset($msg)) $smarty->assign('autores_msg', $msg); else $smarty->assign('autores_msg', false); if(isset($_SESSION['email'])) $smarty->assign('email', $_SESSION['email']); else $smarty->assign('email', false);
hggh/cpves
includes/sites/user_autores.php
PHP
agpl-3.0
7,545
#!/usr/bin/env python #coding:utf-8 import cyclone.auth import cyclone.escape import cyclone.web import datetime import time import os from beaker.cache import cache_managers from toughradius.manage.base import BaseHandler from toughlib.permit import permit from toughradius.manage import models from toughradius.manage.settings import * from toughradius.common import tools import psutil @permit.route(r"/admin") class HomeHandler(BaseHandler): @cyclone.web.authenticated def get(self): # cpuuse = psutil.cpu_percent(interval=None, percpu=True) # memuse = psutil.virtual_memory() # online_count = self.db.query(models.TrOnline.id).count() # user_total = self.db.query(models.TrAccount.account_number).filter_by(status=1).count() # self.render("index.html",config=self.settings.config, # cpuuse=cpuuse,memuse=memuse,online_count=online_count,user_total=user_total) self.redirect("/admin/dashboard") @permit.route(r"/") class HomeHandler(BaseHandler): @cyclone.web.authenticated def get(self): self.redirect("/admin/dashboard") @permit.route(r"/about") class HomeHandler(BaseHandler): @cyclone.web.authenticated def get(self): self.render("about.html") @permit.route(r"/toughcloud/service/register") class ToughcloudRegisterHandler(BaseHandler): def get_toughcloud_url(self): if os.environ.get("TR_DEV"): return 'http://127.0.0.1:9079/customer/license/request?sid=%s'%tools.get_sys_uuid() else: return 'https://www.toughcloud.net/customer/license/request?sid=%s'%tools.get_sys_uuid() @cyclone.web.authenticated def get(self): self.redirect(self.get_toughcloud_url())
sumonchai/tough
toughradius/manage/system/index.py
Python
agpl-3.0
1,739
# Copyright (C) 2007, 2008, 2009, 2010, 2011, 2012, 2013 The Collaborative Software Foundation # # This file is part of TriSano. # # TriSano is free software: you can redistribute it and/or modify it under the # terms of the GNU Affero General Public License as published by the # Free Software Foundation, either version 3 of the License, # or (at your option) any later version. # # TriSano is distributed in the hope that it will be useful, but # WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Affero General Public License for more details. # # You should have received a copy of the GNU Affero General Public License # along with TriSano. If not, see http://www.gnu.org/licenses/agpl-3.0.txt. def log_in_as(user) visit home_path unless current_url begin select user, :from => "user_id" submit_form "switch_user" rescue Exception => e case e.message when 'Could not find field: "user_id"' raise "Please check your site_config.yml and make sure the test enviornment includes auth_src_env: TRISANO_UID, auth_allow_user_switch: true" else raise e.message end end @current_user = User.find_by_user_name(user) end def create_basic_event(event_type, last_name=nil, disease=nil, jurisdiction=nil) # notes need a user, so set to default if current user is nil User.current_user ||= User.find_by_uid('default') returning Kernel.const_get(event_type.capitalize + "Event").new do |event| event.first_reported_PH_date = Date.yesterday.to_s(:db) if event.respond_to?(:first_reported_PH_date) if event_type.to_s.downcase=="encounter" or event_type.to_s.downcase == "contact" or event_type.to_s.downcase == "place" event.parent_event = create_basic_event("assessment", get_random_word, disease, jurisdiction) end if event_type.to_s.downcase=="encounter" event.build_participations_encounter(:user => User.current_user, :encounter_date => event.first_reported_PH_date, :encounter_location_type => ParticipationsEncounter.valid_location_types.first) end if event_type.to_s.downcase == "outbreak" event.event_name = get_random_word end if event.respond_to?(:interested_party) if last_name.nil? event.interested_party = InterestedParty.create(:primary_entity_id => @person.id) else event.attributes = { :interested_party_attributes => { :person_entity_attributes => { :person_attributes => { :last_name => last_name } } } } end end if event.respond_to?(:interested_place) event.attributes = {"interested_place_attributes"=>{ "place_entity_attributes"=>{ "place_attributes"=>{ "name"=> get_random_word } } }, "participations_place_attributes"=>{ "date_of_exposure"=>"" } } end event.build_disease_event(:disease => Disease.find_or_create_by_disease_name(:active => true, :disease_name => disease)) if disease event.build_jurisdiction(:secondary_entity_id => Place.all_by_name_and_types(jurisdiction || "Unassigned", 'J', true).first.entity_id) event.add_note("Dummy Note") event.save! end end def unassigned_jurisdiction Place.all_by_name_and_types("Unassigned", 'J', true).first end def create_event_with_attributes(event_type, last_name, attrs, disease=nil, jurisdiction=nil) e = create_basic_event(event_type, last_name, disease, jurisdiction) e.attributes = attrs e.save! e end def add_encounter_to_event(event, options={}) returning event.encounter_child_events.build do |child| child.attributes = { :participations_encounter_attributes => { :encounter_date => options[:encounter_date] || Date.today, :user_id => options[:user_id] || 1, :encounter_location_type => options[:location_id] || "clinic" } } event.save! child.save end end def jurisdiction_id_by_name(name) Place.all_by_name_and_types(name || "Unassigned", 'J', true).first.entity_id end # Core field keys do not have the _attributes in them that Rails throws # in for nested forms. This method takes a core field key and converts it # to a key that can be used to identify form elements in the browser. def railsify_core_field_key(key) key.chop.gsub("]", "_attributes]") << "]" end # Debt: Replace these with factory-based setup def place_child_events_attributes(values) { "5"=>{ "interested_place_attributes"=>{ "place_entity_attributes"=>{ "place_attributes"=>{ "name"=>"#{values[:name]}" } } }, "participations_place_attributes"=>{ "date_of_exposure"=>"" } } } end def lab_attributes(values) { "3"=>{ "place_entity_attributes"=>{ "place_attributes"=>{ "name"=>"#{values[:name] if values[:name]}" } }, "lab_results_attributes"=>{ "0"=>{ "test_type_id"=>"#{values[:test_type_id] if values[:test_type_id]}", "reference_range"=>"", "specimen_source_id"=>"", "collection_date"=>"", "lab_test_date"=>"", "specimen_sent_to_state_id"=>"" } } } } end def add_path_to(page_name, path_str=nil, &path_proc) Cucumber::Rails::World.class_eval do @@extension_path_names << { :page_name => page_name, :path => path_str || path_proc } end end def invalidate_date_diagnosed(event) DiseaseEvent.update_all("disease_onset_date = '#{Date.today + 1.month}', date_diagnosed = '#{Date.today}'", ['event_id = ?', event.id]) end def invalidate_disease_onset_date(event) invalid_date = event.first_reported_PH_date + 1.month DiseaseEvent.update_all("disease_onset_date = '#{invalid_date}'", ['event_id = ?', event.id]) end # A dirty, filthy hack because succ! seems to be broken in JRuby on 64 # bit Java String.class_eval do def loinc_succ (self.gsub('-', '').to_i + 1).to_s.insert(-2, '-') end end
csinitiative/trisano
webapp/features/support/trisano.rb
Ruby
agpl-3.0
6,238
class Server module ResourcePacks extend ActiveSupport::Concern included do belongs_to :resource_pack # true -> send new respack to players immediately # false -> send new respack to players only on map cycle field :resource_pack_fast_update, type: Boolean, default: false attr_cloneable :resource_pack, :resource_pack_fast_update api_property :resource_pack_fast_update api_synthetic :resource_pack_url do resource_pack.url if resource_pack? end api_synthetic :resource_pack_sha1 do resource_pack.sha1 if resource_pack? end end # included end # ResourcePacks end
OvercastNetwork/OCN
app/models/server/resource_packs.rb
Ruby
agpl-3.0
754
/* * Tanaguru - Automated webpage assessment * Copyright (C) 2008-2015 Tanaguru.org * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as * published by the Free Software Foundation, either version 3 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * * Contact us by mail: tanaguru AT tanaguru DOT org */ package org.tanaguru.rules.accessiweb21; import org.tanaguru.entity.audit.ProcessResult; import org.tanaguru.entity.audit.TestSolution; import org.tanaguru.entity.reference.Nomenclature; import org.tanaguru.processor.SSPHandler; import org.tanaguru.ruleimplementation.AbstractPageRuleImplementation; import org.w3c.dom.Node; /** * This rule tests if forbidden representation tags are used in the source * code. * We use the specific nomenclature "DeprecatedRepresentationTags" to determine * the presence of these * @author jkowalczyk */ public class Aw21Rule10011 extends AbstractPageRuleImplementation { private static final String XPATH_EXPR = "//*"; private static final String MESSAGE_CODE = "DeprecatedRepresentationTagFound"; private static final String DEPREC_TAG_NOM = "DeprecatedRepresentationTags"; public Aw21Rule10011() { super(); } /** * * @param sspHandler * @return */ @Override protected ProcessResult processImpl(SSPHandler sspHandler) { Nomenclature deprecatedHtmlTags = nomenclatureLoaderService. loadByCode(DEPREC_TAG_NOM); sspHandler.beginSelection(). selectDocumentNodes(deprecatedHtmlTags.getValueList()); TestSolution testSolution = TestSolution.PASSED; for (Node node : sspHandler.getSelectedElementList()) { testSolution = TestSolution.FAILED; sspHandler.getProcessRemarkService().addSourceCodeRemark( testSolution, node, MESSAGE_CODE, node.getNodeName()); } ProcessResult processResult = definiteResultFactory.create( test, sspHandler.getPage(), testSolution, sspHandler.getRemarkList()); processResult.setElementCounter( sspHandler.beginSelection().domXPathSelectNodeSet(XPATH_EXPR). getSelectedElementList().size()); return processResult; } }
Tanaguru/Tanaguru
rules/accessiweb2.1/src/main/java/org/tanaguru/rules/accessiweb21/Aw21Rule10011.java
Java
agpl-3.0
2,892
//############################################################################# //# # //# Copyright (C) <2015> <IMS MAXIMS> # //# # //# This program is free software: you can redistribute it and/or modify # //# it under the terms of the GNU Affero General Public License as # //# published by the Free Software Foundation, either version 3 of the # //# License, or (at your option) any later version. # //# # //# This program is distributed in the hope that it will be useful, # //# but WITHOUT ANY WARRANTY; without even the implied warranty of # //# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # //# GNU Affero General Public License for more details. # //# # //# You should have received a copy of the GNU Affero General Public License # //# along with this program. If not, see <http://www.gnu.org/licenses/>. # //# # //# IMS MAXIMS provides absolutely NO GUARANTEE OF THE CLINICAL SAFTEY of # //# this program. Users of this software do so entirely at their own risk. # //# IMS MAXIMS only ensures the Clinical Safety of unaltered run-time # //# software that it builds, deploys and maintains. # //# # //############################################################################# //#EOH /* * This code was generated * Copyright (C) 1995-2004 IMS MAXIMS plc. All rights reserved. * IMS Development Environment (version 1.80 build 5589.25814) * WARNING: DO NOT MODIFY the content of this file * Generated on 12/10/2015, 13:24 * */ package ims.chooseandbook.vo.domain; import ims.vo.domain.DomainObjectMap; import java.util.HashMap; import org.hibernate.proxy.HibernateProxy; /** * @author Barbara Worwood */ public class ConvPointVoAssembler { /** * Copy one ValueObject to another * @param valueObjectDest to be updated * @param valueObjectSrc to copy values from */ public static ims.chooseandbook.vo.ConvPointVo copy(ims.chooseandbook.vo.ConvPointVo valueObjectDest, ims.chooseandbook.vo.ConvPointVo valueObjectSrc) { if (null == valueObjectSrc) { return valueObjectSrc; } valueObjectDest.setID_ConvPoint(valueObjectSrc.getID_ConvPoint()); valueObjectDest.setIsRIE(valueObjectSrc.getIsRIE()); // convId valueObjectDest.setConvId(valueObjectSrc.getConvId()); // msgDetails valueObjectDest.setMsgDetails(valueObjectSrc.getMsgDetails()); // creationDate valueObjectDest.setCreationDate(valueObjectSrc.getCreationDate()); return valueObjectDest; } /** * Create the ValueObject collection to hold the set of DomainObjects. * This is a convenience method only. * It is intended to be used when one called to an Assembler is made. * If more than one call to an Assembler is made then #createConvPointVoCollectionFromConvPoint(DomainObjectMap, Set) should be used. * @param domainObjectSet - Set of ims.choose_book.domain.objects.ConvPoint objects. */ public static ims.chooseandbook.vo.ConvPointVoCollection createConvPointVoCollectionFromConvPoint(java.util.Set domainObjectSet) { return createConvPointVoCollectionFromConvPoint(new DomainObjectMap(), domainObjectSet); } /** * Create the ValueObject collection to hold the set of DomainObjects. * @param map - maps DomainObjects to created ValueObjects * @param domainObjectSet - Set of ims.choose_book.domain.objects.ConvPoint objects. */ public static ims.chooseandbook.vo.ConvPointVoCollection createConvPointVoCollectionFromConvPoint(DomainObjectMap map, java.util.Set domainObjectSet) { ims.chooseandbook.vo.ConvPointVoCollection voList = new ims.chooseandbook.vo.ConvPointVoCollection(); if ( null == domainObjectSet ) { return voList; } int rieCount=0; int activeCount=0; java.util.Iterator iterator = domainObjectSet.iterator(); while( iterator.hasNext() ) { ims.choose_book.domain.objects.ConvPoint domainObject = (ims.choose_book.domain.objects.ConvPoint) iterator.next(); ims.chooseandbook.vo.ConvPointVo vo = create(map, domainObject); if (vo != null) voList.add(vo); if (domainObject != null) { if (domainObject.getIsRIE() != null && domainObject.getIsRIE().booleanValue() == true) rieCount++; else activeCount++; } } voList.setRieCount(rieCount); voList.setActiveCount(activeCount); return voList; } /** * Create the ValueObject collection to hold the list of DomainObjects. * @param domainObjectList - List of ims.choose_book.domain.objects.ConvPoint objects. */ public static ims.chooseandbook.vo.ConvPointVoCollection createConvPointVoCollectionFromConvPoint(java.util.List domainObjectList) { return createConvPointVoCollectionFromConvPoint(new DomainObjectMap(), domainObjectList); } /** * Create the ValueObject collection to hold the list of DomainObjects. * @param map - maps DomainObjects to created ValueObjects * @param domainObjectList - List of ims.choose_book.domain.objects.ConvPoint objects. */ public static ims.chooseandbook.vo.ConvPointVoCollection createConvPointVoCollectionFromConvPoint(DomainObjectMap map, java.util.List domainObjectList) { ims.chooseandbook.vo.ConvPointVoCollection voList = new ims.chooseandbook.vo.ConvPointVoCollection(); if ( null == domainObjectList ) { return voList; } int rieCount=0; int activeCount=0; for (int i = 0; i < domainObjectList.size(); i++) { ims.choose_book.domain.objects.ConvPoint domainObject = (ims.choose_book.domain.objects.ConvPoint) domainObjectList.get(i); ims.chooseandbook.vo.ConvPointVo vo = create(map, domainObject); if (vo != null) voList.add(vo); if (domainObject != null) { if (domainObject.getIsRIE() != null && domainObject.getIsRIE().booleanValue() == true) rieCount++; else activeCount++; } } voList.setRieCount(rieCount); voList.setActiveCount(activeCount); return voList; } /** * Create the ims.choose_book.domain.objects.ConvPoint set from the value object collection. * @param domainFactory - used to create existing (persistent) domain objects. * @param voCollection - the collection of value objects */ public static java.util.Set extractConvPointSet(ims.domain.ILightweightDomainFactory domainFactory, ims.chooseandbook.vo.ConvPointVoCollection voCollection) { return extractConvPointSet(domainFactory, voCollection, null, new HashMap()); } public static java.util.Set extractConvPointSet(ims.domain.ILightweightDomainFactory domainFactory, ims.chooseandbook.vo.ConvPointVoCollection voCollection, java.util.Set domainObjectSet, HashMap domMap) { int size = (null == voCollection) ? 0 : voCollection.size(); if (domainObjectSet == null) { domainObjectSet = new java.util.HashSet(); } java.util.Set newSet = new java.util.HashSet(); for(int i=0; i<size; i++) { ims.chooseandbook.vo.ConvPointVo vo = voCollection.get(i); ims.choose_book.domain.objects.ConvPoint domainObject = ConvPointVoAssembler.extractConvPoint(domainFactory, vo, domMap); //TODO: This can only occur in the situation of a stale object exception. For now leave it to the Interceptor to handle it. if (domainObject == null) { continue; } //Trying to avoid the hibernate collection being marked as dirty via its public interface methods. (like add) if (!domainObjectSet.contains(domainObject)) domainObjectSet.add(domainObject); newSet.add(domainObject); } java.util.Set removedSet = new java.util.HashSet(); java.util.Iterator iter = domainObjectSet.iterator(); //Find out which objects need to be removed while (iter.hasNext()) { ims.domain.DomainObject o = (ims.domain.DomainObject)iter.next(); if ((o == null || o.getIsRIE() == null || !o.getIsRIE().booleanValue()) && !newSet.contains(o)) { removedSet.add(o); } } iter = removedSet.iterator(); //Remove the unwanted objects while (iter.hasNext()) { domainObjectSet.remove(iter.next()); } return domainObjectSet; } /** * Create the ims.choose_book.domain.objects.ConvPoint list from the value object collection. * @param domainFactory - used to create existing (persistent) domain objects. * @param voCollection - the collection of value objects */ public static java.util.List extractConvPointList(ims.domain.ILightweightDomainFactory domainFactory, ims.chooseandbook.vo.ConvPointVoCollection voCollection) { return extractConvPointList(domainFactory, voCollection, null, new HashMap()); } public static java.util.List extractConvPointList(ims.domain.ILightweightDomainFactory domainFactory, ims.chooseandbook.vo.ConvPointVoCollection voCollection, java.util.List domainObjectList, HashMap domMap) { int size = (null == voCollection) ? 0 : voCollection.size(); if (domainObjectList == null) { domainObjectList = new java.util.ArrayList(); } for(int i=0; i<size; i++) { ims.chooseandbook.vo.ConvPointVo vo = voCollection.get(i); ims.choose_book.domain.objects.ConvPoint domainObject = ConvPointVoAssembler.extractConvPoint(domainFactory, vo, domMap); //TODO: This can only occur in the situation of a stale object exception. For now leave it to the Interceptor to handle it. if (domainObject == null) { continue; } int domIdx = domainObjectList.indexOf(domainObject); if (domIdx == -1) { domainObjectList.add(i, domainObject); } else if (i != domIdx && i < domainObjectList.size()) { Object tmp = domainObjectList.get(i); domainObjectList.set(i, domainObjectList.get(domIdx)); domainObjectList.set(domIdx, tmp); } } //Remove all ones in domList where index > voCollection.size() as these should //now represent the ones removed from the VO collection. No longer referenced. int i1=domainObjectList.size(); while (i1 > size) { domainObjectList.remove(i1-1); i1=domainObjectList.size(); } return domainObjectList; } /** * Create the ValueObject from the ims.choose_book.domain.objects.ConvPoint object. * @param domainObject ims.choose_book.domain.objects.ConvPoint */ public static ims.chooseandbook.vo.ConvPointVo create(ims.choose_book.domain.objects.ConvPoint domainObject) { if (null == domainObject) { return null; } DomainObjectMap map = new DomainObjectMap(); return create(map, domainObject); } /** * Create the ValueObject from the ims.choose_book.domain.objects.ConvPoint object. * @param map DomainObjectMap of DomainObjects to already created ValueObjects. * @param domainObject */ public static ims.chooseandbook.vo.ConvPointVo create(DomainObjectMap map, ims.choose_book.domain.objects.ConvPoint domainObject) { if (null == domainObject) { return null; } // check if the domainObject already has a valueObject created for it ims.chooseandbook.vo.ConvPointVo valueObject = (ims.chooseandbook.vo.ConvPointVo) map.getValueObject(domainObject, ims.chooseandbook.vo.ConvPointVo.class); if ( null == valueObject ) { valueObject = new ims.chooseandbook.vo.ConvPointVo(domainObject.getId(), domainObject.getVersion()); map.addValueObject(domainObject, valueObject); valueObject = insert(map, valueObject, domainObject); } return valueObject; } /** * Update the ValueObject with the Domain Object. * @param valueObject to be updated * @param domainObject ims.choose_book.domain.objects.ConvPoint */ public static ims.chooseandbook.vo.ConvPointVo insert(ims.chooseandbook.vo.ConvPointVo valueObject, ims.choose_book.domain.objects.ConvPoint domainObject) { if (null == domainObject) { return valueObject; } DomainObjectMap map = new DomainObjectMap(); return insert(map, valueObject, domainObject); } /** * Update the ValueObject with the Domain Object. * @param map DomainObjectMap of DomainObjects to already created ValueObjects. * @param valueObject to be updated * @param domainObject ims.choose_book.domain.objects.ConvPoint */ public static ims.chooseandbook.vo.ConvPointVo insert(DomainObjectMap map, ims.chooseandbook.vo.ConvPointVo valueObject, ims.choose_book.domain.objects.ConvPoint domainObject) { if (null == domainObject) { return valueObject; } if (null == map) { map = new DomainObjectMap(); } valueObject.setID_ConvPoint(domainObject.getId()); valueObject.setIsRIE(domainObject.getIsRIE()); // If this is a recordedInError record, and the domainObject // value isIncludeRecord has not been set, then we return null and // not the value object if (valueObject.getIsRIE() != null && valueObject.getIsRIE().booleanValue() == true && !domainObject.isIncludeRecord()) return null; // If this is not a recordedInError record, and the domainObject // value isIncludeRecord has been set, then we return null and // not the value object if ((valueObject.getIsRIE() == null || valueObject.getIsRIE().booleanValue() == false) && domainObject.isIncludeRecord()) return null; // convId valueObject.setConvId(ims.chooseandbook.vo.domain.ConvIdVoAssembler.create(map, domainObject.getConvId()) ); // msgDetails valueObject.setMsgDetails(domainObject.getMsgDetails()); // creationDate java.util.Date creationDate = domainObject.getCreationDate(); if ( null != creationDate ) { valueObject.setCreationDate(new ims.framework.utils.Date(creationDate) ); } return valueObject; } /** * Create the domain object from the value object. * @param domainFactory - used to create existing (persistent) domain objects. * @param valueObject - extract the domain object fields from this. */ public static ims.choose_book.domain.objects.ConvPoint extractConvPoint(ims.domain.ILightweightDomainFactory domainFactory, ims.chooseandbook.vo.ConvPointVo valueObject) { return extractConvPoint(domainFactory, valueObject, new HashMap()); } public static ims.choose_book.domain.objects.ConvPoint extractConvPoint(ims.domain.ILightweightDomainFactory domainFactory, ims.chooseandbook.vo.ConvPointVo valueObject, HashMap domMap) { if (null == valueObject) { return null; } Integer id = valueObject.getID_ConvPoint(); ims.choose_book.domain.objects.ConvPoint domainObject = null; if ( null == id) { if (domMap.get(valueObject) != null) { return (ims.choose_book.domain.objects.ConvPoint)domMap.get(valueObject); } // ims.chooseandbook.vo.ConvPointVo ID_ConvPoint field is unknown domainObject = new ims.choose_book.domain.objects.ConvPoint(); domMap.put(valueObject, domainObject); } else { String key = (valueObject.getClass().getName() + "__" + valueObject.getID_ConvPoint()); if (domMap.get(key) != null) { return (ims.choose_book.domain.objects.ConvPoint)domMap.get(key); } domainObject = (ims.choose_book.domain.objects.ConvPoint) domainFactory.getDomainObject(ims.choose_book.domain.objects.ConvPoint.class, id ); //TODO: Not sure how this should be handled. Effectively it must be a staleobject exception, but maybe should be handled as that further up. if (domainObject == null) return null; domMap.put(key, domainObject); } domainObject.setVersion(valueObject.getVersion_ConvPoint()); domainObject.setConvId(ims.chooseandbook.vo.domain.ConvIdVoAssembler.extractConvId(domainFactory, valueObject.getConvId(), domMap)); //This is to overcome a bug in both Sybase and Oracle which prevents them from storing an empty string correctly //Sybase stores it as a single space, Oracle stores it as NULL. This fix will make them consistent at least. if (valueObject.getMsgDetails() != null && valueObject.getMsgDetails().equals("")) { valueObject.setMsgDetails(null); } domainObject.setMsgDetails(valueObject.getMsgDetails()); java.util.Date value3 = null; ims.framework.utils.Date date3 = valueObject.getCreationDate(); if ( date3 != null ) { value3 = date3.getDate(); } domainObject.setCreationDate(value3); return domainObject; } }
IMS-MAXIMS/openMAXIMS
Source Library/openmaxims_workspace/ValueObjects/src/ims/chooseandbook/vo/domain/ConvPointVoAssembler.java
Java
agpl-3.0
17,066
/* * RapidMiner * * Copyright (C) 2001-2014 by RapidMiner and the contributors * * Complete list of developers available at our web site: * * http://rapidminer.com * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see http://www.gnu.org/licenses/. */ package com.rapidminer.gui; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.util.logging.Level; import com.rapidminer.tools.FileSystemService; import com.rapidminer.tools.I18N; import com.rapidminer.tools.LogService; import com.vlsolutions.swing.docking.DockingContext; import com.vlsolutions.swing.docking.ws.Workspace; import com.vlsolutions.swing.docking.ws.WorkspaceException; /** * * @author Simon Fischer * */ public class Perspective { private final String name; private final Workspace workspace = new Workspace(); private boolean userDefined = false;; private final ApplicationPerspectives owner; public Perspective(ApplicationPerspectives owner, String name) { this.name = name; this.owner = owner; } public String getName() { return name; } public Workspace getWorkspace() { return workspace; } public void store(DockingContext dockingContext) { try { workspace.loadFrom(dockingContext); } catch (WorkspaceException e) { //LogService.getRoot().log(Level.WARNING, "Cannot save workspace: "+e, e); LogService.getRoot().log(Level.WARNING, I18N.getMessage(LogService.getRoot().getResourceBundle(), "com.rapidminer.gui.Perspective.saving_workspace_error", e), e); } } protected void apply(DockingContext dockingContext) { try { workspace.apply(dockingContext); } catch (WorkspaceException e) { //LogService.getRoot().log(Level.WARNING, "Cannot apply workspace: "+e, e); LogService.getRoot().log(Level.WARNING, I18N.getMessage(LogService.getRoot().getResourceBundle(), "com.rapidminer.gui.Perspective.applying_workspace_error", e), e); } } File getFile() { return FileSystemService.getUserConfigFile("vlperspective-"+(isUserDefined()?"user-":"predefined-")+name+".xml"); } public void save() { File file = getFile(); OutputStream out = null; try { out = new FileOutputStream(file); workspace.writeXML(out); } catch (Exception e) { //LogService.getRoot().log(Level.WARNING, "Cannot save perspective to "+file+": "+e, e); LogService.getRoot().log(Level.WARNING, I18N.getMessage(LogService.getRoot().getResourceBundle(), "com.rapidminer.gui.Perspective.saving_perspective_error", file, e), e); } finally { try { if (out != null) { out.close(); } } catch (IOException e) { } } } public void load() { //LogService.getRoot().fine("Loading perspective: "+getName()); LogService.getRoot().log(Level.FINE, "com.rapidminer.gui.Perspective.loading_perspective", getName()); File file = getFile(); if (!file.exists()) { return; } InputStream in = null; try { in = new FileInputStream(file); workspace.readXML(in); } catch (Exception e) { if (!userDefined) { //LogService.getRoot().log(Level.WARNING, "Cannot read perspective from "+file+": "+e+". Restoring default.", e); LogService.getRoot().log(Level.WARNING, I18N.getMessage(LogService.getRoot().getResourceBundle(), "com.rapidminer.gui.Perspective.reading_perspective_error_restoring", file, e), e); owner.restoreDefault(getName()); } else { //LogService.getRoot().log(Level.WARNING, "Cannot read perspective from "+file+": "+e+". Clearing perspective.", e); LogService.getRoot().log(Level.WARNING, I18N.getMessage(LogService.getRoot().getResourceBundle(), "com.rapidminer.gui.Perspective.reading_perspective_error_clearing", file, e), e); workspace.clear(); } } finally { try { if (in != null) { in.close(); } } catch (IOException e) { } } } public void setUserDefined(boolean b) { this.userDefined = b; } public boolean isUserDefined() { return this.userDefined; } public void delete() { File file = getFile(); if (file.exists()) { file.delete(); } } }
rapidminer/rapidminer-5
src/com/rapidminer/gui/Perspective.java
Java
agpl-3.0
5,452
//############################################################################# //# # //# Copyright (C) <2015> <IMS MAXIMS> # //# # //# This program is free software: you can redistribute it and/or modify # //# it under the terms of the GNU Affero General Public License as # //# published by the Free Software Foundation, either version 3 of the # //# License, or (at your option) any later version. # //# # //# This program is distributed in the hope that it will be useful, # //# but WITHOUT ANY WARRANTY; without even the implied warranty of # //# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # //# GNU Affero General Public License for more details. # //# # //# You should have received a copy of the GNU Affero General Public License # //# along with this program. If not, see <http://www.gnu.org/licenses/>. # //# # //# IMS MAXIMS provides absolutely NO GUARANTEE OF THE CLINICAL SAFTEY of # //# this program. Users of this software do so entirely at their own risk. # //# IMS MAXIMS only ensures the Clinical Safety of unaltered run-time # //# software that it builds, deploys and maintains. # //# # //############################################################################# //#EOH // This code was generated by Barbara Worwood using IMS Development Environment (version 1.80 build 5589.25814) // Copyright (C) 1995-2015 IMS MAXIMS. All rights reserved. // WARNING: DO NOT MODIFY the content of this file package ims.nursing.forms.careplanreviewdialog; public abstract class BaseLogic extends Handlers { public final Class getDomainInterface() throws ClassNotFoundException { return ims.nursing.domain.CarePlanReviewDialog.class; } public final void setContext(ims.framework.UIEngine engine, GenForm form, ims.nursing.domain.CarePlanReviewDialog domain) { setContext(engine, form); this.domain = domain; } public final void free() { super.free(); domain = null; } protected ims.nursing.domain.CarePlanReviewDialog domain; }
FreudianNM/openMAXIMS
Source Library/openmaxims_workspace/Nursing/src/ims/nursing/forms/careplanreviewdialog/BaseLogic.java
Java
agpl-3.0
2,663
require 'rails_helper' RSpec.describe MailsController, type: :controller do let(:user) { create(:user) } let(:mail) { create(:priv_message, recipient: user, owner: user) } before(:each) do mail # fu laziness sign_in user end describe 'GET #index' do it 'assigns all messages to @mails' do get :index expect(assigns(:mails)).to eq([mail]) end it 'assigns only user messages to @mails' do create(:priv_message, recipient: user, owner: user) get :index, params: { user: mail.sender_name } expect(assigns(:mails)).to eq([mail]) end end describe 'GET #show' do it 'assigns the message as @mail' do get :show, params: { id: mail.to_param, user: mail.sender_name } expect(assigns(:mail)).to eq(mail) end it 'deletes the notification' do Notification.create!(subject: 'foo', path: '/foo/bar/baz', recipient_id: user.user_id, oid: mail.to_param, otype: 'mails:create') expect do get :show, params: { id: mail.to_param, user: mail.sender_name } end.to change(Notification, :count).by(-1) end it 'marks the notification as read when configured' do n = Notification.create!(subject: 'foo', path: '/foo/bar/baz', recipient_id: user.user_id, oid: mail.to_param, otype: 'mails:create') Setting.create!(user_id: user.user_id, options: { 'delete_read_notifications_on_new_mail' => 'no' }) get :show, params: { id: mail.to_param, user: mail.sender_name } n.reload expect(n.is_read).to be true end end describe 'GET #new' do it 'assigns the new mail as @mail' do get :new expect(assigns(:mail)).to be_a_new(PrivMessage) end it 'creates an answer when giving a message id' do get :new, params: { priv_message_id: mail.priv_message_id } expect(assigns(:mail).recipient_id).to eq mail.sender_id end end describe 'POST #create' do let(:valid_attributes) do { subject: 'foo', body: 'foo bar foo bar' } end let(:invalid_attributes) do { subject: '', body: 'foo bar foo bar' } end context 'with valid params' do it 'creates a new mail' do expect do post :create, params: { priv_message: valid_attributes.merge(recipient_id: user.user_id) } end.to change(PrivMessage, :count).by(2) end it 'assigns a newly created mail as @mail' do post :create, params: { priv_message: valid_attributes.merge(recipient_id: user.user_id) } expect(assigns(:mail)).to be_a(PrivMessage) expect(assigns(:mail)).to be_persisted end it 'redirects to the new mail' do post :create, params: { priv_message: valid_attributes.merge(recipient_id: user.user_id) } expect(response).to redirect_to(mail_url(user.username, assigns(:mail).to_param)) end end context 'with invalid params' do it 'assigns a newly created but unsaved mail as @mail' do post :create, params: { priv_message: invalid_attributes } expect(assigns(:mail)).to be_a_new(PrivMessage) end it "re-renders the 'new' template" do post :create, params: { priv_message: invalid_attributes } expect(response).to render_template('new') end it 'renders the new template when only recipient is missing' do post :create, params: { priv_message: valid_attributes } expect(response).to render_template('new') end end end describe 'DELETE #destroy' do it 'deletes a mail' do expect do delete :destroy, params: { user: mail.sender_name, id: mail.to_param } end.to change(PrivMessage, :count).by(-1) end it 'redirects to index' do delete :destroy, params: { user: mail.sender_name, id: mail.to_param } expect(response).to redirect_to(mails_url) end end describe 'DELETE #batch_destroy' do it 'deletes one mail' do expect do delete :batch_destroy, params: { ids: [mail.to_param] } end.to change(PrivMessage, :count).by(-1) end it 'deletes more than one mail' do m1 = create(:priv_message, recipient: user, owner: user) expect do delete :batch_destroy, params: { ids: [mail.to_param, m1.to_param] } end.to change(PrivMessage, :count).by(-2) end it 'redirects to index' do delete :batch_destroy, params: { ids: [mail.to_param] } expect(response).to redirect_to(mails_url) end it "doesn't fail with empty IDs" do delete :batch_destroy, params: { ids: [] } expect(response).to redirect_to(mails_url) end end describe 'POST #mark_read_unread' do it 'marks a read message as unread' do post :mark_read_unread, params: { user: mail.sender_name, id: mail.to_param } mail.reload expect(mail.is_read).to be true end it 'marks a unread message as read' do mail.is_read = true mail.save! post :mark_read_unread, params: { user: mail.sender_name, id: mail.to_param } mail.reload expect(mail.is_read).to be false end it 'redirects to index' do post :mark_read_unread, params: { user: mail.sender_name, id: mail.to_param } expect(response).to redirect_to(mails_url) end end end # eof
MatthiasApsel/cforum
spec/controllers/mails_controller_spec.rb
Ruby
agpl-3.0
5,454
import React from 'react'; import Analyzer from 'parser/core/Analyzer'; import EnemyInstances from 'parser/shared/modules/EnemyInstances'; import SPELLS from 'common/SPELLS'; import SpellIcon from 'common/SpellIcon'; import SpellLink from 'common/SpellLink'; import { formatPercentage } from 'common/format'; import Statistic from 'interface/statistics/Statistic'; import BoringSpellValueText from 'interface/statistics/components/BoringSpellValueText'; import STATISTIC_ORDER from 'interface/others/STATISTIC_ORDER'; const debug = false; const HARDCAST_HITS = [ SPELLS.FROSTBOLT_DAMAGE.id, SPELLS.EBONBOLT_DAMAGE.id, SPELLS.GLACIAL_SPIKE_DAMAGE.id, ]; class WintersChill extends Analyzer { static dependencies = { enemies: EnemyInstances, }; hasGlacialSpike; totalProcs = 0; hardcastHits = 0; missedHardcasts = 0; singleHardcasts = 0; iceLanceHits = 0; missedIceLanceCasts = 0; singleIceLanceCasts = 0; doubleIceLanceCasts = 0; on_byPlayer_damage(event) { const spellId = event.ability.guid; const enemy = this.enemies.getEntity(event); if (!enemy || !enemy.hasBuff(SPELLS.WINTERS_CHILL.id)) { return; } if (spellId === SPELLS.ICE_LANCE_DAMAGE.id) { this.iceLanceHits += 1; debug && console.log("Ice Lance into Winter's Chill"); } else if(HARDCAST_HITS.includes(spellId)) { this.hardcastHits += 1; debug && console.log(`${event.ability.name} into Winter's Chill`); } } on_byPlayer_applydebuff(event) { const spellId = event.ability.guid; if(spellId !== SPELLS.WINTERS_CHILL.id) { return; } this.iceLanceHits = 0; this.hardcastHits = 0; } on_byPlayer_removedebuff(event) { const spellId = event.ability.guid; if(spellId !== SPELLS.WINTERS_CHILL.id) { return; } this.totalProcs += 1; if (this.iceLanceHits === 0) { this.missedIceLanceCasts += 1; } else if (this.iceLanceHits === 1) { this.singleIceLanceCasts += 1; } else if (this.iceLanceHits === 2) { this.doubleIceLanceCasts += 1; } else { this.error(`Unexpected number of Ice Lances inside Winter's Chill -> ${this.iceLanceHits}`); } if (this.hardcastHits === 0) { this.missedHardcasts += 1; } else if (this.hardcastHits === 1) { this.singleHardcasts += 1; } else { this.error(`Unexpected number of Frostbolt hits inside Winter's Chill -> ${this.hardcastHits}`); } } get iceLanceMissedPercent() { return (this.missedIceLanceCasts / this.totalProcs) || 0; } get iceLanceUtil() { return 1 - this.iceLanceMissedPercent; } get iceLanceUtilSuggestionThresholds() { return { actual: this.iceLanceUtil, isLessThan: { minor: 0.95, average: 0.85, major: 0.75, }, style: 'percentage', }; } get hardcastMissedPercent() { return (this.missedHardcasts / this.totalProcs) || 0; } get hardcastUtil() { return 1 - this.hardcastMissedPercent; } // less strict than the ice lance suggestion both because it's less important, // and also because using a Brain Freeze after being forced to move is a good excuse for missing the hardcast. get hardcastUtilSuggestionThresholds() { return { actual: this.hardcastUtil, isLessThan: { minor: 0.90, average: 0.80, major: 0.60, }, style: 'percentage', }; } get doubleIceLancePercentage() { return this.doubleIceLanceCasts / this.totalProcs || 0; } suggestions(when) { when(this.iceLanceUtilSuggestionThresholds) .addSuggestion((suggest, actual, recommended) => { return suggest(<>You failed to Ice Lance into <SpellLink id={SPELLS.WINTERS_CHILL.id} /> {this.missedIceLanceCasts} times ({formatPercentage(this.iceLanceMissedPercent)}%). Make sure you cast <SpellLink id={SPELLS.ICE_LANCE.id} /> after each <SpellLink id={SPELLS.FLURRY.id} /> to benefit from <SpellLink id={SPELLS.SHATTER.id} />.</>) .icon(SPELLS.ICE_LANCE.icon) .actual(`${formatPercentage(this.iceLanceMissedPercent)}% Winter's Chill not shattered with Ice Lance`) .recommended(`<${formatPercentage(1 - this.iceLanceUtilSuggestionThresholds.isLessThan.minor)}% is recommended`); }); when(this.hardcastUtilSuggestionThresholds) .addSuggestion((suggest, actual, recommended) => { return suggest(<>You failed to <SpellLink id={SPELLS.FROSTBOLT.id} />, <SpellLink id={SPELLS.GLACIAL_SPIKE_TALENT.id} /> or <SpellLink id={SPELLS.EBONBOLT_TALENT.id} /> into <SpellLink id={SPELLS.WINTERS_CHILL.id} /> {this.missedHardcasts} times ({formatPercentage(this.hardcastMissedPercent)}%). Make sure you hard cast just before each instant <SpellLink id={SPELLS.FLURRY.id} /> to benefit from <SpellLink id={SPELLS.SHATTER.id} />.</>) .icon(SPELLS.FROSTBOLT.icon) .actual(`${formatPercentage(this.hardcastMissedPercent)}% Winter's Chill not shattered with Frostbolt, Glacial Spike, or Ebonbolt`) .recommended(`${formatPercentage(1 - recommended)}% is recommended`); }); } statistic() { return ( <Statistic position={STATISTIC_ORDER.CORE(30)} size="flexible" tooltip={( <> Every Brain Freeze Flurry should be preceded by a Frostbolt, Glacial Spike, or Ebonbolt and followed by an Ice Lance, so that both the preceding and following spells benefit from Shatter. <br /><br /> You double Ice Lance'd into Winter's Chill {this.doubleIceLanceCasts} times ({formatPercentage(this.doubleIceLancePercentage, 1)}%). Note this is usually impossible, it can only be done with strong Haste buffs active and by moving towards the target while casting. It should mostly be considered 'extra credit' </> )} > <BoringSpellValueText spell={SPELLS.WINTERS_CHILL}> <SpellIcon id={SPELLS.ICE_LANCE.id} /> {formatPercentage(this.iceLanceUtil, 0)}% <small>Ice Lances shattered</small><br /> <SpellIcon id={SPELLS.FROSTBOLT.id} /> {formatPercentage(this.hardcastUtil, 0)}% <small>Pre-casts shattered</small> </BoringSpellValueText> </Statistic> ); } } export default WintersChill;
fyruna/WoWAnalyzer
src/parser/mage/frost/modules/features/WintersChill.js
JavaScript
agpl-3.0
6,255
<?php // ------------------------------------------------------------------------------- // | net2ftp: a web based FTP client | // | Copyright (c) 2003-2013 by David Gartner | // | | // | 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. | // | | // ------------------------------------------------------------------------------- // ************************************************************************************** // ************************************************************************************** // ** ** // ** ** function getActivePlugins() { // -------------- // This function modifies the global variable $net2ftp_globals["activePlugins"], which contains an array // with all active plugin names // // Which plugin is active depends on 2 things: // 1 - if the plugin is enabled or disabled (see the ["use"] field in getPluginProperties()) // 2 - the $net2ftp_globals["state"] and $net2ftp_globals["state2"] variables, as well as other specific variables (see this function) // -------------- // ------------------------------------------------------------------------- // Global variables // ------------------------------------------------------------------------- global $net2ftp_globals; $pluginProperties = getPluginProperties("ALL"); $plugincounter = 0; $activePlugins = array(); if (isset($_POST["textareaType"]) == true) { $textareaType = $_POST["textareaType"]; } // ------------------------------------------------------------------------- // Plugins to always activate // ------------------------------------------------------------------------- // ------------------------------------------------------------------------- // Plugins to activate depending on the $state and $state2 variables // ------------------------------------------------------------------------- if ($net2ftp_globals["state"] == "logout" || $net2ftp_globals["state"] == "admin") { if ($pluginProperties["versioncheck"]["use"] == "yes") { $activePlugins[$plugincounter] = "versioncheck"; $plugincounter++; } } elseif ($net2ftp_globals["state"] == "findstring") { if ($pluginProperties["jscalendar"]["use"] == "yes") { $activePlugins[$plugincounter] = "jscalendar"; $plugincounter++; } } elseif ($net2ftp_globals["state"] == "view") { if ($pluginProperties["luminous"]["use"] == "yes") { $activePlugins[$plugincounter] = "luminous"; $plugincounter++; } } // ------------------------------------------------------------------------- // Plugins to activate depending on other variables // ------------------------------------------------------------------------- if ($net2ftp_globals["state"] == "edit" && isset($textareaType) == true && $textareaType != "" && array_key_exists($textareaType, $pluginProperties) == true) { if ($pluginProperties[$textareaType]["use"] == "yes") { $activePlugins[$plugincounter] = $textareaType; $plugincounter++; } } return $activePlugins; } // end function getActivePlugins // ** ** // ** ** // ************************************************************************************** // ************************************************************************************** // ************************************************************************************** // ************************************************************************************** // ** ** // ** ** function isActivePlugin($plugin) { // -------------- // This function checks if a plugin is active or not // -------------- global $net2ftp_globals; return in_array($plugin, $net2ftp_globals["activePlugins"]); } // end function isActivePlugin // ** ** // ** ** // ************************************************************************************** // ************************************************************************************** // ************************************************************************************** // ************************************************************************************** // ** ** // ** ** function getPluginProperties() { // -------------- // This function returns an array with all plugin properties // -------------- // ------------------------------------------------------------------------- // Global variables // ------------------------------------------------------------------------- global $net2ftp_globals, $net2ftp_settings; // ------------------------------------------------------------------------- // CKEditor (formerly FCKEditor) - http://www.fckeditor.net/ // An HTML editor // ------------------------------------------------------------------------- // Language code (see /plugins/ckeditor/lang) if ($net2ftp_globals["language"] == "ar") { $ckeditor_language = "ar"; } elseif ($net2ftp_globals["language"] == "ar-utf") { $ckeditor_language = "ar"; } elseif ($net2ftp_globals["language"] == "cs") { $ckeditor_language = "cs"; } elseif ($net2ftp_globals["language"] == "da") { $ckeditor_language = "da"; } elseif ($net2ftp_globals["language"] == "de") { $ckeditor_language = "de"; } elseif ($net2ftp_globals["language"] == "es") { $ckeditor_language = "es"; } elseif ($net2ftp_globals["language"] == "fi") { $ckeditor_language = "fi"; } elseif ($net2ftp_globals["language"] == "fr") { $ckeditor_language = "fr"; } elseif ($net2ftp_globals["language"] == "he") { $ckeditor_language = "he"; } elseif ($net2ftp_globals["language"] == "hu") { $ckeditor_language = "hu"; } elseif ($net2ftp_globals["language"] == "hu-utf") { $ckeditor_language = "hu"; } elseif ($net2ftp_globals["language"] == "it") { $ckeditor_language = "it"; } elseif ($net2ftp_globals["language"] == "ja") { $ckeditor_language = "ja"; } elseif ($net2ftp_globals["language"] == "nl") { $ckeditor_language = "nl"; } elseif ($net2ftp_globals["language"] == "pl") { $ckeditor_language = "pl"; } elseif ($net2ftp_globals["language"] == "pt") { $ckeditor_language = "pt"; } elseif ($net2ftp_globals["language"] == "ru") { $ckeditor_language = "ru"; } elseif ($net2ftp_globals["language"] == "sv") { $ckeditor_language = "sv"; } elseif ($net2ftp_globals["language"] == "tc") { $ckeditor_language = "zh"; } elseif ($net2ftp_globals["language"] == "tr") { $ckeditor_language = "tr"; } elseif ($net2ftp_globals["language"] == "ua") { $ckeditor_language = "ru"; } elseif ($net2ftp_globals["language"] == "vi") { $ckeditor_language = "vi"; } elseif ($net2ftp_globals["language"] == "zh") { $ckeditor_language = "zh-cn"; } else { $ckeditor_language = "en"; } $pluginProperties["ckeditor"]["use"] = "yes"; $pluginProperties["ckeditor"]["label"] = "CKEditor (WYSIWYG)"; $pluginProperties["ckeditor"]["directory"] = "ckeditor"; $pluginProperties["ckeditor"]["type"] = "textarea"; $pluginProperties["ckeditor"]["browsers"][1] = "IE"; $pluginProperties["ckeditor"]["browsers"][2] = "Chrome"; $pluginProperties["ckeditor"]["browsers"][3] = "Safari"; $pluginProperties["ckeditor"]["browsers"][4] = "Opera"; $pluginProperties["ckeditor"]["browsers"][5] = "Mozilla"; $pluginProperties["ckeditor"]["browsers"][6] = "Other"; $pluginProperties["ckeditor"]["filename_extensions"][1] = "html"; $pluginProperties["ckeditor"]["includePhpFiles"][1] = ""; $pluginProperties["ckeditor"]["printJavascript"] = "<script type=\"text/javascript\" src=\"" . $net2ftp_globals["application_rootdir_url"] . "/plugins/ckeditor/ckeditor.js\"></script>\n"; $pluginProperties["ckeditor"]["printCss"] = ""; $pluginProperties["ckeditor"]["printBodyOnload"] = ""; $pluginProperties["ckeditor"]["printBodyOnload"] .= " CKEDITOR.replace( 'text_splitted[middle]' );\n"; $pluginProperties["ckeditor"]["printBodyOnload"] .= " CKEDITOR.config.language = '" . $ckeditor_language . "';\n"; $pluginProperties["ckeditor"]["printBodyOnload"] .= " CKEDITOR.config.contentsLangDirection = '" . __("ltr") . "';\n"; $pluginProperties["ckeditor"]["printBodyOnload"] .= " CKEDITOR.config.height = 400;\n"; // ------------------------------------------------------------------------- // TinyMCE - http://tinymce.moxiecode.com/ // An HTML editor // ------------------------------------------------------------------------- // Language code (see /plugins/tinymce/lang) if ($net2ftp_globals["language"] == "ar") { $tinymce_language = "ar"; } if ($net2ftp_globals["language"] == "ar-utf") { $tinymce_language = "ar"; } elseif ($net2ftp_globals["language"] == "cs") { $tinymce_language = "cs"; } elseif ($net2ftp_globals["language"] == "da") { $tinymce_language = "da"; } elseif ($net2ftp_globals["language"] == "de") { $tinymce_language = "de"; } elseif ($net2ftp_globals["language"] == "es") { $tinymce_language = "es"; } elseif ($net2ftp_globals["language"] == "fi") { $tinymce_language = "fi"; } elseif ($net2ftp_globals["language"] == "fr") { $tinymce_language = "fr"; } elseif ($net2ftp_globals["language"] == "he") { $tinymce_language = "he"; } elseif ($net2ftp_globals["language"] == "hu") { $tinymce_language = "hu"; } elseif ($net2ftp_globals["language"] == "hu-utf") { $tinymce_language = "hu"; } elseif ($net2ftp_globals["language"] == "it") { $tinymce_language = "it"; } elseif ($net2ftp_globals["language"] == "ja") { $tinymce_language = "ja"; } elseif ($net2ftp_globals["language"] == "nl") { $tinymce_language = "nl"; } elseif ($net2ftp_globals["language"] == "pl") { $tinymce_language = "pl"; } elseif ($net2ftp_globals["language"] == "pt") { $tinymce_language = "pt"; } elseif ($net2ftp_globals["language"] == "ru") { $tinymce_language = "ru"; } elseif ($net2ftp_globals["language"] == "sv") { $tinymce_language = "sv"; } elseif ($net2ftp_globals["language"] == "tc") { $tinymce_language = "zh-tw"; } elseif ($net2ftp_globals["language"] == "tr") { $tinymce_language = "tr"; } elseif ($net2ftp_globals["language"] == "ua") { $tinymce_language = "ru"; } elseif ($net2ftp_globals["language"] == "vi") { $tinymce_language = "vi"; } elseif ($net2ftp_globals["language"] == "zh") { $tinymce_language = "zh-cn"; } else { $tinymce_language = "en"; } $pluginProperties["tinymce"]["use"] = "yes"; $pluginProperties["tinymce"]["label"] = "TinyMCE (WYSIWYG)"; $pluginProperties["tinymce"]["directory"] = "tinymce"; $pluginProperties["tinymce"]["type"] = "textarea"; $pluginProperties["tinymce"]["browsers"][1] = "IE"; $pluginProperties["tinymce"]["browsers"][2] = "Chrome"; $pluginProperties["tinymce"]["browsers"][3] = "Safari"; $pluginProperties["tinymce"]["browsers"][4] = "Opera"; $pluginProperties["tinymce"]["browsers"][5] = "Mozilla"; $pluginProperties["tinymce"]["browsers"][6] = "Other"; $pluginProperties["tinymce"]["filename_extensions"][1] = "html"; $pluginProperties["tinymce"]["includePhpFiles"][1] = ""; $pluginProperties["tinymce"]["printJavascript"] = "<script type=\"text/javascript\" src=\"" . $net2ftp_globals["application_rootdir_url"] . "/plugins/tinymce/tiny_mce.js\"></script>\n"; $pluginProperties["tinymce"]["printJavascript"] .= "<script type=\"text/javascript\">\n"; $pluginProperties["tinymce"]["printJavascript"] .= " tinyMCE.init({\n"; $pluginProperties["tinymce"]["printJavascript"] .= " // General options\n"; $pluginProperties["tinymce"]["printJavascript"] .= " mode : \"exact\",\n"; $pluginProperties["tinymce"]["printJavascript"] .= " language : \"" . $tinymce_language . "\",\n"; $pluginProperties["tinymce"]["printJavascript"] .= " elements : \"text_splitted[middle]\",\n"; $pluginProperties["tinymce"]["printJavascript"] .= " theme : \"advanced\",\n"; $pluginProperties["tinymce"]["printJavascript"] .= " plugins : \"pagebreak,style,layer,table,save,advhr,advimage,advlink,emotions,iespell,inlinepopups,insertdatetime,preview,media,searchreplace,print,contextmenu,paste,directionality,fullscreen,noneditable,visualchars,nonbreaking,xhtmlxtras,template,wordcount,advlist,autosave\",\n"; $pluginProperties["tinymce"]["printJavascript"] .= " // Theme options\n"; $pluginProperties["tinymce"]["printJavascript"] .= " theme_advanced_buttons1 : \"save,newdocument,|,bold,italic,underline,strikethrough,|,justifyleft,justifycenter,justifyright,justifyfull,styleselect,formatselect,fontselect,fontsizeselect\",\n"; $pluginProperties["tinymce"]["printJavascript"] .= " theme_advanced_buttons2 : \"cut,copy,paste,pastetext,pasteword,|,search,replace,|,bullist,numlist,|,outdent,indent,blockquote,|,undo,redo,|,link,unlink,anchor,image,cleanup,help,code,|,insertdate,inserttime,preview,|,forecolor,backcolor\",\n"; $pluginProperties["tinymce"]["printJavascript"] .= " theme_advanced_buttons3 : \"tablecontrols,|,hr,removeformat,visualaid,|,sub,sup,|,charmap,emotions,iespell,media,advhr,|,print,|,ltr,rtl,|,fullscreen\",\n"; $pluginProperties["tinymce"]["printJavascript"] .= " theme_advanced_buttons4 : \"insertlayer,moveforward,movebackward,absolute,|,styleprops,|,cite,abbr,acronym,del,ins,attribs,|,visualchars,nonbreaking,template,pagebreak,restoredraft\",\n"; $pluginProperties["tinymce"]["printJavascript"] .= " theme_advanced_toolbar_location : \"top\",\n"; $pluginProperties["tinymce"]["printJavascript"] .= " theme_advanced_toolbar_align : \"left\",\n"; $pluginProperties["tinymce"]["printJavascript"] .= " theme_advanced_statusbar_location : \"bottom\",\n"; $pluginProperties["tinymce"]["printJavascript"] .= " theme_advanced_resizing : true,\n"; $pluginProperties["tinymce"]["printJavascript"] .= " // Example content CSS (should be your site CSS)\n"; $pluginProperties["tinymce"]["printJavascript"] .= " content_css : \"css/content.css\",\n"; $pluginProperties["tinymce"]["printJavascript"] .= " // Drop lists for link/image/media/template dialogs\n"; $pluginProperties["tinymce"]["printJavascript"] .= " template_external_list_url : \"lists/template_list.js\",\n"; $pluginProperties["tinymce"]["printJavascript"] .= " external_link_list_url : \"lists/link_list.js\",\n"; $pluginProperties["tinymce"]["printJavascript"] .= " external_image_list_url : \"lists/image_list.js\",\n"; $pluginProperties["tinymce"]["printJavascript"] .= " media_external_list_url : \"lists/media_list.js\",\n"; $pluginProperties["tinymce"]["printJavascript"] .= " // Style formats\n"; $pluginProperties["tinymce"]["printJavascript"] .= " style_formats : [\n"; $pluginProperties["tinymce"]["printJavascript"] .= " {title : 'Bold text', inline : 'b'},\n"; $pluginProperties["tinymce"]["printJavascript"] .= " {title : 'Red text', inline : 'span', styles : {color : '#ff0000'}},\n"; $pluginProperties["tinymce"]["printJavascript"] .= " {title : 'Red header', block : 'h1', styles : {color : '#ff0000'}},\n"; $pluginProperties["tinymce"]["printJavascript"] .= " {title : 'Example 1', inline : 'span', classes : 'example1'},\n"; $pluginProperties["tinymce"]["printJavascript"] .= " {title : 'Example 2', inline : 'span', classes : 'example2'},\n"; $pluginProperties["tinymce"]["printJavascript"] .= " {title : 'Table styles'},\n"; $pluginProperties["tinymce"]["printJavascript"] .= " {title : 'Table row 1', selector : 'tr', classes : 'tablerow1'}\n"; $pluginProperties["tinymce"]["printJavascript"] .= " ],\n"; $pluginProperties["tinymce"]["printJavascript"] .= " // Replace values for the template plugin\n"; $pluginProperties["tinymce"]["printJavascript"] .= " template_replace_values : {\n"; $pluginProperties["tinymce"]["printJavascript"] .= " username : \"Some User\",\n"; $pluginProperties["tinymce"]["printJavascript"] .= " staffid : \"991234\"\n"; $pluginProperties["tinymce"]["printJavascript"] .= " }\n"; $pluginProperties["tinymce"]["printJavascript"] .= " });\n"; $pluginProperties["tinymce"]["printJavascript"] .= "</script>\n"; $pluginProperties["tinymce"]["printCss"] = ""; $pluginProperties["tinymce"]["printBodyOnload"] = ""; // ------------------------------------------------------------------------- // Ace // A syntax highlighting text editor in javascript // ------------------------------------------------------------------------- $pluginProperties["ace"]["use"] = "yes"; $pluginProperties["ace"]["label"] = "Ace (code editor)"; $pluginProperties["ace"]["directory"] = "ace"; $pluginProperties["ace"]["type"] = "textarea"; $pluginProperties["ace"]["browsers"][1] = "IE"; $pluginProperties["ace"]["browsers"][2] = "Chrome"; $pluginProperties["ace"]["browsers"][3] = "Safari"; $pluginProperties["ace"]["browsers"][4] = "Opera"; $pluginProperties["ace"]["browsers"][5] = "Mozilla"; $pluginProperties["ace"]["browsers"][6] = "Other"; $pluginProperties["ace"]["filename_extensions"][1] = "asp"; $pluginProperties["ace"]["filename_extensions"][2] = "css"; $pluginProperties["ace"]["filename_extensions"][3] = "cgi"; $pluginProperties["ace"]["filename_extensions"][4] = "htm"; $pluginProperties["ace"]["filename_extensions"][5] = "html"; $pluginProperties["ace"]["filename_extensions"][6] = "java"; $pluginProperties["ace"]["filename_extensions"][7] = "javascript"; $pluginProperties["ace"]["filename_extensions"][8] = "js"; $pluginProperties["ace"]["filename_extensions"][9] = "pl"; $pluginProperties["ace"]["filename_extensions"][10] = "perl"; $pluginProperties["ace"]["filename_extensions"][11] = "php"; $pluginProperties["ace"]["filename_extensions"][12] = "phps"; $pluginProperties["ace"]["filename_extensions"][13] = "phtml"; $pluginProperties["ace"]["filename_extensions"][14] = "ruby"; $pluginProperties["ace"]["filename_extensions"][15] = "sql"; $pluginProperties["ace"]["filename_extensions"][16] = "txt"; $pluginProperties["ace"]["includePhpFiles"][1] = ""; $pluginProperties["ace"]["printJavascript"] = "<script type=\"text/javascript\" src=\"" . $net2ftp_globals["application_rootdir_url"] . "/plugins/ace/ace.js\"></script>\n"; $pluginProperties["ace"]["printCss"] = "<style type=\"text/css\" media=\"screen\">#editor { position: absolute; top: 50px; right: 0; bottom: 0; left: 0; }</style>"; $pluginProperties["ace"]["printBodyOnload"] = ""; // ------------------------------------------------------------------------- // Version Checker - written by Slynderdale for net2ftp. // This small Javascript function will check if a new version of net2ftp is available // and display a message if there is. // ------------------------------------------------------------------------- $pluginProperties["versioncheck"]["use"] = "yes"; $pluginProperties["versioncheck"]["label"] = "Javascript Version Checker"; $pluginProperties["versioncheck"]["directory"] = "versioncheck"; $pluginProperties["versioncheck"]["type"] = "versioncheck"; $pluginProperties["versioncheck"]["browsers"][1] = "IE"; $pluginProperties["versioncheck"]["browsers"][2] = "Chrome"; $pluginProperties["versioncheck"]["browsers"][3] = "Safari"; $pluginProperties["versioncheck"]["browsers"][4] = "Opera"; $pluginProperties["versioncheck"]["browsers"][5] = "Mozilla"; $pluginProperties["versioncheck"]["browsers"][6] = "Other"; $pluginProperties["versioncheck"]["filename_extensions"][1] = ""; $pluginProperties["versioncheck"]["includePhpFiles"][1] = ""; $pluginProperties["versioncheck"]["printJavascript"] = "<script type=\"text/javascript\" src=\"http://www.net2ftp.com/version.js\"></script>\n"; $pluginProperties["versioncheck"]["printCss"] = ""; $pluginProperties["versioncheck"]["printBodyOnload"] = ""; // ------------------------------------------------------------------------- // The JS Calendar code is written by Mishoo (who also wrote the HTMLArea v3). // http://dynarch.com/mishoo/calendar.epl // ------------------------------------------------------------------------- // Language code (see /plugins/jscalendar/lang) if ($net2ftp_globals["language"] == "cs") { $jscalendar_language = "calendar-cs-win"; } elseif ($net2ftp_globals["language"] == "da") { $jscalendar_language = "calendar-da"; } elseif ($net2ftp_globals["language"] == "de") { $jscalendar_language = "calendar-de"; } elseif ($net2ftp_globals["language"] == "es") { $jscalendar_language = "calendar-es"; } elseif ($net2ftp_globals["language"] == "fi") { $jscalendar_language = "calendar-fi"; } elseif ($net2ftp_globals["language"] == "fr") { $jscalendar_language = "calendar-fr"; } elseif ($net2ftp_globals["language"] == "he") { $jscalendar_language = "calendar-he-utf8.js"; } elseif ($net2ftp_globals["language"] == "it") { $jscalendar_language = "calendar-it"; } elseif ($net2ftp_globals["language"] == "ja") { $jscalendar_language = "calendar-jp"; } elseif ($net2ftp_globals["language"] == "nl") { $jscalendar_language = "calendar-nl"; } elseif ($net2ftp_globals["language"] == "pl") { $jscalendar_language = "calendar-pl"; } elseif ($net2ftp_globals["language"] == "pt") { $jscalendar_language = "calendar-pt"; } elseif ($net2ftp_globals["language"] == "ru") { $jscalendar_language = "calendar-ru"; } elseif ($net2ftp_globals["language"] == "sv") { $jscalendar_language = "calendar-sv"; } elseif ($net2ftp_globals["language"] == "tr") { $jscalendar_language = "calendar-tr"; } elseif ($net2ftp_globals["language"] == "tc") { $jscalendar_language = "calendar-big5.js"; } elseif ($net2ftp_globals["language"] == "zh") { $jscalendar_language = "calendar-zh"; } else { $jscalendar_language = "calendar-en"; } $pluginProperties["jscalendar"]["use"] = "yes"; $pluginProperties["jscalendar"]["label"] = "JS Calendar"; $pluginProperties["jscalendar"]["directory"] = "jscalendar"; $pluginProperties["jscalendar"]["type"] = "calendar"; $pluginProperties["jscalendar"]["browsers"][1] = "IE"; $pluginProperties["jscalendar"]["browsers"][2] = "Chrome"; $pluginProperties["jscalendar"]["browsers"][3] = "Safari"; $pluginProperties["jscalendar"]["browsers"][4] = "Opera"; $pluginProperties["jscalendar"]["browsers"][5] = "Mozilla"; $pluginProperties["jscalendar"]["browsers"][6] = "Other"; $pluginProperties["jscalendar"]["filename_extensions"][1] = ""; $pluginProperties["jscalendar"]["includePhpFiles"][1] = "jscalendar/calendar.php"; $pluginProperties["jscalendar"]["printJavascript"] = "<script type=\"text/javascript\" src=\"" . $net2ftp_globals["application_rootdir_url"] . "/plugins/jscalendar/calendar.js\"></script>\n"; $pluginProperties["jscalendar"]["printJavascript"] .= "<script type=\"text/javascript\" src=\"" . $net2ftp_globals["application_rootdir_url"] . "/plugins/jscalendar/lang/" . $jscalendar_language . ".js\"></script>\n"; $pluginProperties["jscalendar"]["printJavascript"] .= "<script type=\"text/javascript\" src=\"" . $net2ftp_globals["application_rootdir_url"] . "/plugins/jscalendar/calendar-setup.js\"></script>\n"; $pluginProperties["jscalendar"]["printCss"] = "<link rel=\"stylesheet\" type=\"text/css\" media=\"all\" href=\"" . $net2ftp_globals["application_rootdir_url"] . "/plugins/jscalendar/skins/aqua/theme.css\" title=\"Aqua\" />\n"; $pluginProperties["jscalendar"]["printCss"] .= "<link rel=\"alternate stylesheet\" type=\"text/css\" media=\"all\" href=\"" . $net2ftp_globals["application_rootdir_url"] . "/plugins/jscalendar/calendar-win2k-cold-1.css\" title=\"win2k-cold-1\" />\n"; $pluginProperties["jscalendar"]["printBodyOnload"] = ""; // ------------------------------------------------------------------------- // JUpload // A Java applet to upload directories and files // ------------------------------------------------------------------------- $pluginProperties["jupload"]["use"] = "yes"; $pluginProperties["jupload"]["label"] = "JUpload"; $pluginProperties["jupload"]["directory"] = "jupload"; $pluginProperties["jupload"]["type"] = "applet"; $pluginProperties["jupload"]["browsers"][1] = "IE"; $pluginProperties["jupload"]["browsers"][2] = "Chrome"; $pluginProperties["jupload"]["browsers"][3] = "Safari"; $pluginProperties["jupload"]["browsers"][4] = "Opera"; $pluginProperties["jupload"]["browsers"][5] = "Mozilla"; $pluginProperties["jupload"]["browsers"][6] = "Other"; $pluginProperties["jupload"]["filename_extensions"][1] = ""; $pluginProperties["jupload"]["includePhpFiles"][1] = ""; $pluginProperties["jupload"]["printCss"] = ""; $pluginProperties["jupload"]["printJavascript"] = ""; $pluginProperties["jupload"]["printBodyOnload"] = ""; // ------------------------------------------------------------------------- // Luminous // Syntax highlighter // ------------------------------------------------------------------------- $pluginProperties["luminous"]["use"] = "yes"; $pluginProperties["luminous"]["label"] = "Luminous"; $pluginProperties["luminous"]["directory"] = "luminous"; $pluginProperties["luminous"]["type"] = "highlighter"; $pluginProperties["luminous"]["browsers"][1] = "IE"; $pluginProperties["luminous"]["browsers"][2] = "Chrome"; $pluginProperties["luminous"]["browsers"][3] = "Safari"; $pluginProperties["luminous"]["browsers"][4] = "Opera"; $pluginProperties["luminous"]["browsers"][5] = "Mozilla"; $pluginProperties["luminous"]["browsers"][6] = "Other"; $pluginProperties["luminous"]["filename_extensions"][1] = ""; $pluginProperties["luminous"]["includePhpFiles"][1] = "luminous/luminous.php"; $pluginProperties["luminous"]["printCss"] = ""; $pluginProperties["luminous"]["printJavascript"] = ""; $pluginProperties["luminous"]["printBodyOnload"] = ""; return $pluginProperties; } // end function getPluginProperties // ** ** // ** ** // ************************************************************************************** // ************************************************************************************** // ************************************************************************************** // ************************************************************************************** // ** ** // ** ** function net2ftp_plugin_includePhpFiles() { // -------------- // This function includes PHP files which are required by the active plugins // The list of current active plugins is stored in $net2ftp_globals["activePlugins"] // -------------- // ------------------------------------------------------------------------- // Global variables and settings // ------------------------------------------------------------------------- global $net2ftp_globals; $pluginProperties = getPluginProperties(); // ------------------------------------------------------------------------- // Initial checks and initialization // ------------------------------------------------------------------------- if ($net2ftp_globals["activePlugins"] == "") { return ""; } // ------------------------------------------------------------------------- // For all plugins... // ------------------------------------------------------------------------- for ($pluginnr=0; $pluginnr<sizeof($net2ftp_globals["activePlugins"]); $pluginnr++) { // Get the plugin related data $currentPlugin = $pluginProperties[$net2ftp_globals["activePlugins"][$pluginnr]]; // Check if the plugin should be used if ($currentPlugin["use"] != "yes" || $currentPlugin["includePhpFiles"][1] == "") { continue; } // ------------------------------------------------------------------------- // Include PHP files // ------------------------------------------------------------------------- for ($i=1; $i<=sizeof($currentPlugin["includePhpFiles"]); $i++) { require_once($net2ftp_globals["application_pluginsdir"] . "/" . $currentPlugin["includePhpFiles"][$i]); } // end for } // end for } // End function net2ftp_plugin_includePhpFiles // ** ** // ** ** // ************************************************************************************** // ************************************************************************************** // ************************************************************************************** // ************************************************************************************** // ** ** // ** ** function net2ftp_plugin_printJavascript() { // -------------- // This function includes PHP files which are required by the active plugins // The list of current active plugins is stored in $net2ftp_globals["activePlugins"] // -------------- // ------------------------------------------------------------------------- // Global variables and settings // ------------------------------------------------------------------------- global $net2ftp_globals; $pluginProperties = getPluginProperties(); // ------------------------------------------------------------------------- // Initial checks and initialization // ------------------------------------------------------------------------- if ($net2ftp_globals["activePlugins"] == "") { return ""; } // ------------------------------------------------------------------------- // For all plugins... // ------------------------------------------------------------------------- for ($pluginnr=0; $pluginnr<sizeof($net2ftp_globals["activePlugins"]); $pluginnr++) { // Get the plugin related data $currentPlugin = $pluginProperties[$net2ftp_globals["activePlugins"][$pluginnr]]; // Check if the plugin should be used if ($currentPlugin["use"] != "yes") { continue; } // ------------------------------------------------------------------------- // Print Javascript code // ------------------------------------------------------------------------- echo $currentPlugin["printJavascript"]; } // end for } // End function net2ftp_plugin_printJavascript // ** ** // ** ** // ************************************************************************************** // ************************************************************************************** // ************************************************************************************** // ************************************************************************************** // ** ** // ** ** function net2ftp_plugin_printCss() { // -------------- // This function includes PHP files which are required by the active plugins // The list of current active plugins is stored in $net2ftp_globals["activePlugins"] // -------------- // ------------------------------------------------------------------------- // Global variables and settings // ------------------------------------------------------------------------- global $net2ftp_globals; $pluginProperties = getPluginProperties(); // ------------------------------------------------------------------------- // Initial checks and initialization // ------------------------------------------------------------------------- if ($net2ftp_globals["activePlugins"] == "") { return ""; } // ------------------------------------------------------------------------- // For all plugins... // ------------------------------------------------------------------------- for ($pluginnr=0; $pluginnr<sizeof($net2ftp_globals["activePlugins"]); $pluginnr++) { // Get the plugin related data $currentPlugin = $pluginProperties[$net2ftp_globals["activePlugins"][$pluginnr]]; // Check if the plugin should be used if ($currentPlugin["use"] != "yes") { continue; } // ------------------------------------------------------------------------- // Print CSS code // ------------------------------------------------------------------------- echo $currentPlugin["printCss"]; } // end for } // End function net2ftp_plugin_printCss // ** ** // ** ** // ************************************************************************************** // ************************************************************************************** // ************************************************************************************** // ************************************************************************************** // ** ** // ** ** function net2ftp_plugin_printBodyOnload() { // -------------- // This function includes PHP files which are required by the active plugins // The list of current active plugins is stored in $net2ftp_globals["activePlugins"] // -------------- // ------------------------------------------------------------------------- // Global variables and settings // ------------------------------------------------------------------------- global $net2ftp_globals; $pluginProperties = getPluginProperties(); // ------------------------------------------------------------------------- // Initial checks and initialization // ------------------------------------------------------------------------- if ($net2ftp_globals["activePlugins"] == "") { return ""; } // ------------------------------------------------------------------------- // For all plugins... // ------------------------------------------------------------------------- for ($pluginnr=0; $pluginnr<sizeof($net2ftp_globals["activePlugins"]); $pluginnr++) { // Get the plugin related data $currentPlugin = $pluginProperties[$net2ftp_globals["activePlugins"][$pluginnr]]; // Check if the plugin should be used if ($currentPlugin["use"] != "yes") { continue; } // ------------------------------------------------------------------------- // Print <body onload=""> code // ------------------------------------------------------------------------- echo $currentPlugin["printBodyOnload"]; } // end for } // End function net2ftp_plugin_printBodyOnload // ** ** // ** ** // ************************************************************************************** // ************************************************************************************** ?>
ERP2/Business-Software
apps/ftp/plugins/plugins.inc.php
PHP
agpl-3.0
38,303
# -*- coding: utf-8 -*- # Copyright 2016 Acsone SA/NV # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl). { 'name': 'Account Invoice Check Total', 'summary': """ Check if the verification total is equal to the bill's total""", 'version': '10.0.1.0.0', 'license': 'AGPL-3', 'author': 'Acsone SA/NV,Odoo Community Association (OCA)', 'website': 'https://acsone.eu/', 'depends': [ 'account', ], 'data': [ 'views/account_config_settings.xml', 'security/account_invoice_security.xml', 'views/account_invoice.xml', ], }
sysadminmatmoz/account-invoicing
account_invoice_check_total/__manifest__.py
Python
agpl-3.0
607
#!/usr/bin/env node 'use strict'; /** * Documents RPC Prototype * * - TIU CREATE RECORD (MAKE^TIUSRVP) * - TIU UPDATE RECORD (UPDATE^TIUSRVP) * - TIU DELETE RECORD (DELETE^TIUSRVP) * - TIU SIGN RECORD * ... and locks * ... key file, TIUSRVP * * REM: HMP set * "TIU AUTHORIZATION", * "TIU CREATE ADDENDUM RECORD", * "TIU CREATE RECORD", * "TIU DELETE RECORD", * "TIU DOCUMENTS BY CONTEXT", * "TIU GET DOCUMENT TITLE", * "TIU GET RECORD TEXT", * "TIU GET REQUEST", * "TIU IS THIS A CONSULT?", # manually added ? * "TIU IS THIS A SURGERY?", # manually added ? * "TIU ISPRF", * "TIU LOCK RECORD", * "TIU LONG LIST OF TITLES", * "TIU REQUIRES COSIGNATURE", * "TIU SET DOCUMENT TEXT", * "TIU SIGN RECORD", * "TIU UNLOCK RECORD", * "TIU UPDATE RECORD", * * but CPRS has more: http://vistadataproject.info/artifacts/cprsRPCs * * NOTE: year 1 (2016) has NO locking for TIU RPCs so this wasn't coded for dual pass (facade) * * Scope: initially for Allergy (Progress notes) generated automatically * from Allergy code ... * GMRAGUI1 -> EN1^GMRAPET0 (for S and E cases) -> NEW^TIUPNAPI (turns text in TMP into pass by ref) -> MAKE^TIUSRVP (same as RPC) * and note SPNJRPPN and other VISTA note makers. * * (c) 2016 VISTA Data Project */ /* * Basic setup */ const util = require('util'); const fs = require('fs'); const nodem = require('nodem'); const os = require('os'); const _ = require('lodash'); const fileman = require('../fileman'); const RPCRunner = require('../rpcRunner').RPCRunner; const vdmUtils = require('../vdmUtils'); const VDM = require('../vdm'); // using VDM read to test results const vdmModel = require('./vdmDocumentsModel').vdmModel; // for initial dump of required properties const testUtils = require('../testUtils'); // Convenience function to form the text function formatTextLines(lines) { const tlines = []; lines.forEach((line) => { tlines.push({ 0: line }); }); return tlines; } describe('testDocumentRPCs', () => { let db; // for afterAll let DUZ; // play with 55 to 56 ie/ different DUZ to see what defaults ... let DUZSIG; // AUTHORSIG ie/ signature used for signing let patientIEN; let rpcRunner; // "id": "8925_1-17", "label": "ADVERSE REACTION_ALLERGY" const araDocTypeIEN = '17'; beforeAll(() => { db = new nodem.Gtm(); db.open(); const userId = testUtils.lookupUserIdByName(db, 'ALEXANDER,ROBERT'); DUZ = parseInt(userId.split('-')[1], 10); DUZSIG = 'ROBA123'; // Robert's e sig patientIEN = testUtils.lookupPatientIdByName(db, 'CARTER,DAVID').split('-')[1]; VDM.setDBAndModel(db, vdmModel); // empty both TIU docs (8925) and VISITs (created by side effect) ['8925', '9000010'].forEach((value) => { fileman.emptyFile(db, value); }); rpcRunner = new RPCRunner(db); rpcRunner.initializeUser(DUZ); }); // Leads to error (exception) if don't define patient properly // NEW^TIUPNAPI used by Allergy Doc creation does stop bad Patient properly but MAKE, which is called directly by RPC, doesn't it('Error - patient-less/bad Create S Progress Note', () => { const rpcDefn = { name: 'TIU CREATE RECORD', args: [ '', araDocTypeIEN, '', '', '', { 1202: DUZ, TEXT: formatTextLines(['This patient has had the following reactions ', 'signed-off on Mar 05, 2016@01:16:21.', '', 'CHOCOLATE', '', "Author's comments:", '', 'unfortunate fellow ', '']), }, ], }; // errorMessage: 'EVENT+2^TIUSRVP1,%GTM-E-NULSUBSC, Null subscripts are not allowed for region: DEFAULT,%GTM-I-GVIS, \t\tGlobal variable: ^DPT("",.105)' expect(() => { rpcRunner.run(rpcDefn.name, rpcDefn.args); }).toThrowError(/EVENT\+2\^TIUSRVP1,%GTM-E-NULSUBSC, Null subscripts/); rpcDefn.args[0] = '111111111'; // errorMessage: 'PATVADPT+4^TIULV,%GTM-E-UNDEF, Undefined local variable: VA(BID)' expect(() => { rpcRunner.run(rpcDefn.name, rpcDefn.args); }).toThrowError('PATVADPT+4^TIULV,%GTM-E-UNDEF, Undefined local variable: VA(BID)'); }); // Leads to error (0/msg) if don't define document_type properly // NEW^TIUPNAPI used by Allergy doc creation stops this before the MAKE even sees it but RPC uses MAKE directly so MAKE check is needed it('Error - document type-less/bad Create S Progress Note', () => { // lot's missing const rpcDefn = { name: 'TIU CREATE RECORD', args: [ patientIEN, '', '', '', '', { 1202: DUZ, TEXT: formatTextLines(['This patient has had the following reactions ', 'signed-off on Mar 05, 2016@01:16:21.', '', 'CHOCOLATE', '', "Author's comments:", '', 'unfortunate fellow ', '']), }, ], }; let res = rpcRunner.run(rpcDefn.name, rpcDefn.args); // '0^Invalid TITLE Selected.', expect(res.result).toMatch(/0\^Invalid TITLE Selected./); rpcDefn.args[1] = '111111111'; // nonsense document type res = rpcRunner.run(rpcDefn.name, rpcDefn.args); // '0^Invalid TITLE Selected.' - expect same error expect(res.result).toMatch(/0\^Invalid TITLE Selected./); }); // Correct full note - that largely matches the input VDM // ... only three explicit values needed // - note doesn't show in VPR (as unsigned?) // - does show (so does report_text-less note) in CPRS it('Create S Progress Note', () => { // explicitly removing division and (reference) date and even author (defaults to duz) // SO ONLY THREE VALUES: patient, document title, report_text ... dates and duz defaulted elsewhere. const rpcDefn = { name: 'TIU CREATE RECORD', args: [ patientIEN, araDocTypeIEN, '', '', '', { 1202: DUZ, TEXT: formatTextLines(['This patient has had the following reactions ', 'signed-off on Mar 05, 2016@01:16:21.', '', 'CHOCOLATE', '', "Author's comments:", '', 'unfortunate fellow ', '']), }, ], }; const res = rpcRunner.run(rpcDefn.name, rpcDefn.args); expect(res.result).not.toEqual(0); // get result const tiuIEN = res.result; const descr = VDM.describe(`8925-${tiuIEN}`); descr.type = 'Tiu_Document-8925'; // TMP Fix til FMQL fills JLD type 'properly' expect(descr.report_text).toBeDefined(); }); // Allowed a text-less note! Another short coming - shows in CPRS too. // // Note: path of create allergy note through NEW^TIUNAPI does stop text-less (I $D(^TMP("TIUP",$J))'>9 Q ; If no text, quit) // but RPC goes straight to MAKE which has no check (ditto for author which is explicit and not just DUZ!) it('Not error but - text-less Create S Progress Note', () => { const rpcDefn = { name: 'TIU CREATE RECORD', args: [ patientIEN, araDocTypeIEN, '', '', '', '', ], }; const res = rpcRunner.run(rpcDefn.name, rpcDefn.args); expect(res.result[0]).not.toEqual(0); // get result const tiuIEN = res.result; const descr = VDM.describe(`8925-${tiuIEN}`); expect(descr.report_text).toBeUndefined(); expect(parseInt(descr.line_count, 10)).toEqual(0); }); // create bad explicit author (ie/ leave in but make bad) - leave invalid ref in Doc it('Not error but - bad explicit author (not DUZ) Create S Progress Note', () => { const bad200 = '200-111111'; const rpcDefn = { name: 'TIU CREATE RECORD', args: [ patientIEN, araDocTypeIEN, '', '', '', { 1202: bad200.split('-')[1], // bad author_dictator TEXT: formatTextLines(['This patient has had the following reactions ', 'signed-off on Mar 05, 2016@01:16:21.', '', 'CHOCOLATE', '', "Author's comments:", '', 'unfortunate fellow ', '']), }, ], }; const res = rpcRunner.run(rpcDefn.name, rpcDefn.args); expect(res.result).not.toMatch(/0/); // get result const tiuIEN = res.result; const descr = VDM.describe(`8925-${tiuIEN}`); expect(descr.author_dictator.id).toEqual(bad200); }); // RPC TIU SIGN RECORD (SIGN^TIUSRVP) it('Sign/complete proper Progress Note', () => { // must encrypt the sig! const encryptedSig = db.function({ function: 'ENCRYP^XUSRB1', arguments: [DUZSIG] }).result; const goodNoteIEN = '1'; // not the one with the bad Author but Robert so should work const rpcArgs = [goodNoteIEN, encryptedSig]; // tried in clear too but also fails // if fails: '89250005^You have entered an incorrect Electronic Signature Code...Try again!' const res = rpcRunner.run('TIU SIGN RECORD', rpcArgs); // but want 0! expect(parseInt(res.result, 10)).toEqual(89250005); // TODO: try TIU WHICH SIGNATURE ACTION // TODO: try AUTHSIGN^TIUSRVA (TIU HAS AUTHOR SIGNED) // TODO: ? need LOCK^TIUSRVP (TIU LOCK RECORD) }); /* * Automatic Visit Creation - note: it happens to be queued. Logic is ... */ it('Create E Progress Note', () => { // ..D EN1^GMRAPET0(GMRADFN,.GMRAIEN,"S",.GMRAOUT) ;21 File progress note ... update }); // TIU UPDATE RECORD - UPDATE^TIUSRVP // - updates the record named in the TIUDA parameter, with theinformation contained in the TIUX(Field #) array // ... if can edit in place ... // - err passed by reference /* NOTE: the ability to merge text ... { "id": "8994_02-2_92", "type": "vs:Input_Parameter-8994_02", "input_parameter-8994_02": "TIUDA", "parameter_type-8994_02": "LITERAL", "required-8994_02": true, "description-8994_02": "This is the record # (IEN) of the TIU Document in file #8925." }, { "id": "8994_02-3_92", "type": "vs:Input_Parameter-8994_02", "input_parameter-8994_02": "TIUX", "parameter_type-8994_02": "LIST", "required-8994_02": true, "description-8994_02": "This is the input array which contains the data to be filed in themodified document. It should look something like this: TIUX(.02)=45678TIUX(1301)=2960703.104556TIUX(1302)=293764TIUX(\"TEXT\",1,0)=\"The patient is a 70 year old WHITE MALE, who presentedto the ONCOLOGY CLINIC\"TIUX(\"TEXT\",2,0)=\"On JULY 3, 1996@10:00 AM, with the chief complaint ofNECK PAIN...\"" }, and This API updates the record named in the TIUDA parameter, with theinformation contained in the TIUX(Field #) array. The body of themodified TIU document should be passed in the TIUX(\"TEXT\",i,0) subscript,where i is the line number (i.e., the \"TEXT\" node should be ready to MERGEwith a word processing field). Any filing errors which may occur will bereturned in the single valued ERR parameter (which is passed byreference). */ // Circumstances of DELETE RECORD (see CPRS) ... if EIE Allergy before signing? - really need clones. afterAll(() => { db.close(); }); });
vistadataproject/VDM
prototypes/tiuDocuments/rpcDocuments-spec.js
JavaScript
agpl-3.0
11,813
//############################################################################# //# # //# Copyright (C) <2014> <IMS MAXIMS> # //# # //# This program is free software: you can redistribute it and/or modify # //# it under the terms of the GNU Affero General Public License as # //# published by the Free Software Foundation, either version 3 of the # //# License, or (at your option) any later version. # //# # //# This program is distributed in the hope that it will be useful, # //# but WITHOUT ANY WARRANTY; without even the implied warranty of # //# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # //# GNU Affero General Public License for more details. # //# # //# You should have received a copy of the GNU Affero General Public License # //# along with this program. If not, see <http://www.gnu.org/licenses/>. # //# # //############################################################################# //#EOH /* * This code was generated * Copyright (C) 1995-2004 IMS MAXIMS plc. All rights reserved. * IMS Development Environment (version 1.80 build 5007.25751) * WARNING: DO NOT MODIFY the content of this file * Generated on 16/04/2014, 12:31 * */ package ims.core.vo.domain; import ims.vo.domain.DomainObjectMap; import java.util.HashMap; import org.hibernate.proxy.HibernateProxy; /** * @author Ander Telleria */ public class PatientProcedureProcsComponentLiteVoAssembler { /** * Copy one ValueObject to another * @param valueObjectDest to be updated * @param valueObjectSrc to copy values from */ public static ims.core.vo.PatientProcedureProcsComponentLiteVo copy(ims.core.vo.PatientProcedureProcsComponentLiteVo valueObjectDest, ims.core.vo.PatientProcedureProcsComponentLiteVo valueObjectSrc) { if (null == valueObjectSrc) { return valueObjectSrc; } valueObjectDest.setID_PatientProcedure(valueObjectSrc.getID_PatientProcedure()); valueObjectDest.setIsRIE(valueObjectSrc.getIsRIE()); // ProcedureDescription valueObjectDest.setProcedureDescription(valueObjectSrc.getProcedureDescription()); // AuthoringInformation valueObjectDest.setAuthoringInformation(valueObjectSrc.getAuthoringInformation()); // includeInDischargeLetter valueObjectDest.setIncludeInDischargeLetter(valueObjectSrc.getIncludeInDischargeLetter()); // ProcDate valueObjectDest.setProcDate(valueObjectSrc.getProcDate()); return valueObjectDest; } /** * Create the ValueObject collection to hold the set of DomainObjects. * This is a convenience method only. * It is intended to be used when one called to an Assembler is made. * If more than one call to an Assembler is made then #createPatientProcedureProcsComponentLiteVoCollectionFromPatientProcedure(DomainObjectMap, Set) should be used. * @param domainObjectSet - Set of ims.core.clinical.domain.objects.PatientProcedure objects. */ public static ims.core.vo.PatientProcedureProcsComponentLiteVoCollection createPatientProcedureProcsComponentLiteVoCollectionFromPatientProcedure(java.util.Set domainObjectSet) { return createPatientProcedureProcsComponentLiteVoCollectionFromPatientProcedure(new DomainObjectMap(), domainObjectSet); } /** * Create the ValueObject collection to hold the set of DomainObjects. * @param map - maps DomainObjects to created ValueObjects * @param domainObjectSet - Set of ims.core.clinical.domain.objects.PatientProcedure objects. */ public static ims.core.vo.PatientProcedureProcsComponentLiteVoCollection createPatientProcedureProcsComponentLiteVoCollectionFromPatientProcedure(DomainObjectMap map, java.util.Set domainObjectSet) { ims.core.vo.PatientProcedureProcsComponentLiteVoCollection voList = new ims.core.vo.PatientProcedureProcsComponentLiteVoCollection(); if ( null == domainObjectSet ) { return voList; } int rieCount=0; int activeCount=0; java.util.Iterator iterator = domainObjectSet.iterator(); while( iterator.hasNext() ) { ims.core.clinical.domain.objects.PatientProcedure domainObject = (ims.core.clinical.domain.objects.PatientProcedure) iterator.next(); ims.core.vo.PatientProcedureProcsComponentLiteVo vo = create(map, domainObject); if (vo != null) voList.add(vo); if (domainObject != null) { if (domainObject.getIsRIE() != null && domainObject.getIsRIE().booleanValue() == true) rieCount++; else activeCount++; } } voList.setRieCount(rieCount); voList.setActiveCount(activeCount); return voList; } /** * Create the ValueObject collection to hold the list of DomainObjects. * @param domainObjectList - List of ims.core.clinical.domain.objects.PatientProcedure objects. */ public static ims.core.vo.PatientProcedureProcsComponentLiteVoCollection createPatientProcedureProcsComponentLiteVoCollectionFromPatientProcedure(java.util.List domainObjectList) { return createPatientProcedureProcsComponentLiteVoCollectionFromPatientProcedure(new DomainObjectMap(), domainObjectList); } /** * Create the ValueObject collection to hold the list of DomainObjects. * @param map - maps DomainObjects to created ValueObjects * @param domainObjectList - List of ims.core.clinical.domain.objects.PatientProcedure objects. */ public static ims.core.vo.PatientProcedureProcsComponentLiteVoCollection createPatientProcedureProcsComponentLiteVoCollectionFromPatientProcedure(DomainObjectMap map, java.util.List domainObjectList) { ims.core.vo.PatientProcedureProcsComponentLiteVoCollection voList = new ims.core.vo.PatientProcedureProcsComponentLiteVoCollection(); if ( null == domainObjectList ) { return voList; } int rieCount=0; int activeCount=0; for (int i = 0; i < domainObjectList.size(); i++) { ims.core.clinical.domain.objects.PatientProcedure domainObject = (ims.core.clinical.domain.objects.PatientProcedure) domainObjectList.get(i); ims.core.vo.PatientProcedureProcsComponentLiteVo vo = create(map, domainObject); if (vo != null) voList.add(vo); if (domainObject != null) { if (domainObject.getIsRIE() != null && domainObject.getIsRIE().booleanValue() == true) rieCount++; else activeCount++; } } voList.setRieCount(rieCount); voList.setActiveCount(activeCount); return voList; } /** * Create the ims.core.clinical.domain.objects.PatientProcedure set from the value object collection. * @param domainFactory - used to create existing (persistent) domain objects. * @param voCollection - the collection of value objects */ public static java.util.Set extractPatientProcedureSet(ims.domain.ILightweightDomainFactory domainFactory, ims.core.vo.PatientProcedureProcsComponentLiteVoCollection voCollection) { return extractPatientProcedureSet(domainFactory, voCollection, null, new HashMap()); } public static java.util.Set extractPatientProcedureSet(ims.domain.ILightweightDomainFactory domainFactory, ims.core.vo.PatientProcedureProcsComponentLiteVoCollection voCollection, java.util.Set domainObjectSet, HashMap domMap) { int size = (null == voCollection) ? 0 : voCollection.size(); if (domainObjectSet == null) { domainObjectSet = new java.util.HashSet(); } java.util.Set newSet = new java.util.HashSet(); for(int i=0; i<size; i++) { ims.core.vo.PatientProcedureProcsComponentLiteVo vo = voCollection.get(i); ims.core.clinical.domain.objects.PatientProcedure domainObject = PatientProcedureProcsComponentLiteVoAssembler.extractPatientProcedure(domainFactory, vo, domMap); //TODO: This can only occur in the situation of a stale object exception. For now leave it to the Interceptor to handle it. if (domainObject == null) { continue; } //Trying to avoid the hibernate collection being marked as dirty via its public interface methods. (like add) if (!domainObjectSet.contains(domainObject)) domainObjectSet.add(domainObject); newSet.add(domainObject); } java.util.Set removedSet = new java.util.HashSet(); java.util.Iterator iter = domainObjectSet.iterator(); //Find out which objects need to be removed while (iter.hasNext()) { ims.domain.DomainObject o = (ims.domain.DomainObject)iter.next(); if ((o == null || o.getIsRIE() == null || !o.getIsRIE().booleanValue()) && !newSet.contains(o)) { removedSet.add(o); } } iter = removedSet.iterator(); //Remove the unwanted objects while (iter.hasNext()) { domainObjectSet.remove(iter.next()); } return domainObjectSet; } /** * Create the ims.core.clinical.domain.objects.PatientProcedure list from the value object collection. * @param domainFactory - used to create existing (persistent) domain objects. * @param voCollection - the collection of value objects */ public static java.util.List extractPatientProcedureList(ims.domain.ILightweightDomainFactory domainFactory, ims.core.vo.PatientProcedureProcsComponentLiteVoCollection voCollection) { return extractPatientProcedureList(domainFactory, voCollection, null, new HashMap()); } public static java.util.List extractPatientProcedureList(ims.domain.ILightweightDomainFactory domainFactory, ims.core.vo.PatientProcedureProcsComponentLiteVoCollection voCollection, java.util.List domainObjectList, HashMap domMap) { int size = (null == voCollection) ? 0 : voCollection.size(); if (domainObjectList == null) { domainObjectList = new java.util.ArrayList(); } for(int i=0; i<size; i++) { ims.core.vo.PatientProcedureProcsComponentLiteVo vo = voCollection.get(i); ims.core.clinical.domain.objects.PatientProcedure domainObject = PatientProcedureProcsComponentLiteVoAssembler.extractPatientProcedure(domainFactory, vo, domMap); //TODO: This can only occur in the situation of a stale object exception. For now leave it to the Interceptor to handle it. if (domainObject == null) { continue; } int domIdx = domainObjectList.indexOf(domainObject); if (domIdx == -1) { domainObjectList.add(i, domainObject); } else if (i != domIdx && i < domainObjectList.size()) { Object tmp = domainObjectList.get(i); domainObjectList.set(i, domainObjectList.get(domIdx)); domainObjectList.set(domIdx, tmp); } } //Remove all ones in domList where index > voCollection.size() as these should //now represent the ones removed from the VO collection. No longer referenced. int i1=domainObjectList.size(); while (i1 > size) { domainObjectList.remove(i1-1); i1=domainObjectList.size(); } return domainObjectList; } /** * Create the ValueObject from the ims.core.clinical.domain.objects.PatientProcedure object. * @param domainObject ims.core.clinical.domain.objects.PatientProcedure */ public static ims.core.vo.PatientProcedureProcsComponentLiteVo create(ims.core.clinical.domain.objects.PatientProcedure domainObject) { if (null == domainObject) { return null; } DomainObjectMap map = new DomainObjectMap(); return create(map, domainObject); } /** * Create the ValueObject from the ims.core.clinical.domain.objects.PatientProcedure object. * @param map DomainObjectMap of DomainObjects to already created ValueObjects. * @param domainObject */ public static ims.core.vo.PatientProcedureProcsComponentLiteVo create(DomainObjectMap map, ims.core.clinical.domain.objects.PatientProcedure domainObject) { if (null == domainObject) { return null; } // check if the domainObject already has a valueObject created for it ims.core.vo.PatientProcedureProcsComponentLiteVo valueObject = (ims.core.vo.PatientProcedureProcsComponentLiteVo) map.getValueObject(domainObject, ims.core.vo.PatientProcedureProcsComponentLiteVo.class); if ( null == valueObject ) { valueObject = new ims.core.vo.PatientProcedureProcsComponentLiteVo(domainObject.getId(), domainObject.getVersion()); map.addValueObject(domainObject, valueObject); valueObject = insert(map, valueObject, domainObject); } return valueObject; } /** * Update the ValueObject with the Domain Object. * @param valueObject to be updated * @param domainObject ims.core.clinical.domain.objects.PatientProcedure */ public static ims.core.vo.PatientProcedureProcsComponentLiteVo insert(ims.core.vo.PatientProcedureProcsComponentLiteVo valueObject, ims.core.clinical.domain.objects.PatientProcedure domainObject) { if (null == domainObject) { return valueObject; } DomainObjectMap map = new DomainObjectMap(); return insert(map, valueObject, domainObject); } /** * Update the ValueObject with the Domain Object. * @param map DomainObjectMap of DomainObjects to already created ValueObjects. * @param valueObject to be updated * @param domainObject ims.core.clinical.domain.objects.PatientProcedure */ public static ims.core.vo.PatientProcedureProcsComponentLiteVo insert(DomainObjectMap map, ims.core.vo.PatientProcedureProcsComponentLiteVo valueObject, ims.core.clinical.domain.objects.PatientProcedure domainObject) { if (null == domainObject) { return valueObject; } if (null == map) { map = new DomainObjectMap(); } valueObject.setID_PatientProcedure(domainObject.getId()); valueObject.setIsRIE(domainObject.getIsRIE()); // If this is a recordedInError record, and the domainObject // value isIncludeRecord has not been set, then we return null and // not the value object if (valueObject.getIsRIE() != null && valueObject.getIsRIE().booleanValue() == true && !domainObject.isIncludeRecord()) return null; // If this is not a recordedInError record, and the domainObject // value isIncludeRecord has been set, then we return null and // not the value object if ((valueObject.getIsRIE() == null || valueObject.getIsRIE().booleanValue() == false) && domainObject.isIncludeRecord()) return null; // ProcedureDescription valueObject.setProcedureDescription(domainObject.getProcedureDescription()); // AuthoringInformation valueObject.setAuthoringInformation(ims.core.vo.domain.AuthoringInformationVoAssembler.create(map, domainObject.getAuthoringInformation()) ); // includeInDischargeLetter valueObject.setIncludeInDischargeLetter( domainObject.isIncludeInDischargeLetter() ); // ProcDate Integer ProcDate = domainObject.getProcDate(); if ( null != ProcDate ) { valueObject.setProcDate(new ims.framework.utils.PartialDate(ProcDate) ); } return valueObject; } /** * Create the domain object from the value object. * @param domainFactory - used to create existing (persistent) domain objects. * @param valueObject - extract the domain object fields from this. */ public static ims.core.clinical.domain.objects.PatientProcedure extractPatientProcedure(ims.domain.ILightweightDomainFactory domainFactory, ims.core.vo.PatientProcedureProcsComponentLiteVo valueObject) { return extractPatientProcedure(domainFactory, valueObject, new HashMap()); } public static ims.core.clinical.domain.objects.PatientProcedure extractPatientProcedure(ims.domain.ILightweightDomainFactory domainFactory, ims.core.vo.PatientProcedureProcsComponentLiteVo valueObject, HashMap domMap) { if (null == valueObject) { return null; } Integer id = valueObject.getID_PatientProcedure(); ims.core.clinical.domain.objects.PatientProcedure domainObject = null; if ( null == id) { if (domMap.get(valueObject) != null) { return (ims.core.clinical.domain.objects.PatientProcedure)domMap.get(valueObject); } // ims.core.vo.PatientProcedureProcsComponentLiteVo ID_PatientProcedure field is unknown domainObject = new ims.core.clinical.domain.objects.PatientProcedure(); domMap.put(valueObject, domainObject); } else { String key = (valueObject.getClass().getName() + "__" + valueObject.getID_PatientProcedure()); if (domMap.get(key) != null) { return (ims.core.clinical.domain.objects.PatientProcedure)domMap.get(key); } domainObject = (ims.core.clinical.domain.objects.PatientProcedure) domainFactory.getDomainObject(ims.core.clinical.domain.objects.PatientProcedure.class, id ); //TODO: Not sure how this should be handled. Effectively it must be a staleobject exception, but maybe should be handled as that further up. if (domainObject == null) return null; domMap.put(key, domainObject); } domainObject.setVersion(valueObject.getVersion_PatientProcedure()); //This is to overcome a bug in both Sybase and Oracle which prevents them from storing an empty string correctly //Sybase stores it as a single space, Oracle stores it as NULL. This fix will make them consistent at least. if (valueObject.getProcedureDescription() != null && valueObject.getProcedureDescription().equals("")) { valueObject.setProcedureDescription(null); } domainObject.setProcedureDescription(valueObject.getProcedureDescription()); domainObject.setAuthoringInformation(ims.core.vo.domain.AuthoringInformationVoAssembler.extractAuthoringInformation(domainFactory, valueObject.getAuthoringInformation(), domMap)); domainObject.setIncludeInDischargeLetter(valueObject.getIncludeInDischargeLetter()); ims.framework.utils.PartialDate ProcDate = valueObject.getProcDate(); Integer value4 = null; if ( null != ProcDate ) { value4 = ProcDate.toInteger(); } domainObject.setProcDate(value4); return domainObject; } }
open-health-hub/openmaxims-linux
openmaxims_workspace/ValueObjects/src/ims/core/vo/domain/PatientProcedureProcsComponentLiteVoAssembler.java
Java
agpl-3.0
18,393
//############################################################################# //# # //# Copyright (C) <2014> <IMS MAXIMS> # //# # //# This program is free software: you can redistribute it and/or modify # //# it under the terms of the GNU Affero General Public License as # //# published by the Free Software Foundation, either version 3 of the # //# License, or (at your option) any later version. # //# # //# This program is distributed in the hope that it will be useful, # //# but WITHOUT ANY WARRANTY; without even the implied warranty of # //# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # //# GNU Affero General Public License for more details. # //# # //# You should have received a copy of the GNU Affero General Public License # //# along with this program. If not, see <http://www.gnu.org/licenses/>. # //# # //############################################################################# //#EOH // This code was generated by Barbara Worwood using IMS Development Environment (version 1.80 build 5007.25751) // Copyright (C) 1995-2014 IMS MAXIMS. All rights reserved. // WARNING: DO NOT MODIFY the content of this file package ims.ocs_if.vo; /** * Linked to Hl7ADTOut.DemographicsMessageQueue business object (ID: 1103100000). */ public class DemographicsMessageQueueVo extends ims.hl7adtout.vo.DemographicsMessageQueueRefVo implements ims.vo.ImsCloneable, Comparable { private static final long serialVersionUID = 1L; public DemographicsMessageQueueVo() { } public DemographicsMessageQueueVo(Integer id, int version) { super(id, version); } public DemographicsMessageQueueVo(ims.ocs_if.vo.beans.DemographicsMessageQueueVoBean bean) { this.id = bean.getId(); this.version = bean.getVersion(); this.patient = bean.getPatient() == null ? null : new ims.core.patient.vo.PatientRefVo(new Integer(bean.getPatient().getId()), bean.getPatient().getVersion()); this.providersystem = bean.getProviderSystem() == null ? null : new ims.core.admin.vo.ProviderSystemRefVo(new Integer(bean.getProviderSystem().getId()), bean.getProviderSystem().getVersion()); this.wasprocessed = bean.getWasProcessed(); this.wasdiscarded = bean.getWasDiscarded(); this.msgtext = bean.getMsgText(); this.acktext = bean.getAckText(); this.failuremsg = bean.getFailureMsg(); this.messagestatus = bean.getMessageStatus() == null ? null : ims.ocrr.vo.lookups.OrderMessageStatus.buildLookup(bean.getMessageStatus()); this.msgtype = bean.getMsgType() == null ? null : ims.core.vo.lookups.MsgEventType.buildLookup(bean.getMsgType()); this.queuetype = bean.getQueueType() == null ? null : ims.core.vo.lookups.QueueType.buildLookup(bean.getQueueType()); this.priorpatient = bean.getPriorPatient() == null ? null : new ims.core.patient.vo.PatientRefVo(new Integer(bean.getPriorPatient().getId()), bean.getPriorPatient().getVersion()); this.mergehistory = bean.getMergeHistory() == null ? null : new ims.core.patient.vo.PatientMergeHistoryRefVo(new Integer(bean.getMergeHistory().getId()), bean.getMergeHistory().getVersion()); } public void populate(ims.vo.ValueObjectBeanMap map, ims.ocs_if.vo.beans.DemographicsMessageQueueVoBean bean) { this.id = bean.getId(); this.version = bean.getVersion(); this.patient = bean.getPatient() == null ? null : new ims.core.patient.vo.PatientRefVo(new Integer(bean.getPatient().getId()), bean.getPatient().getVersion()); this.providersystem = bean.getProviderSystem() == null ? null : new ims.core.admin.vo.ProviderSystemRefVo(new Integer(bean.getProviderSystem().getId()), bean.getProviderSystem().getVersion()); this.wasprocessed = bean.getWasProcessed(); this.wasdiscarded = bean.getWasDiscarded(); this.msgtext = bean.getMsgText(); this.acktext = bean.getAckText(); this.failuremsg = bean.getFailureMsg(); this.messagestatus = bean.getMessageStatus() == null ? null : ims.ocrr.vo.lookups.OrderMessageStatus.buildLookup(bean.getMessageStatus()); this.msgtype = bean.getMsgType() == null ? null : ims.core.vo.lookups.MsgEventType.buildLookup(bean.getMsgType()); this.queuetype = bean.getQueueType() == null ? null : ims.core.vo.lookups.QueueType.buildLookup(bean.getQueueType()); this.priorpatient = bean.getPriorPatient() == null ? null : new ims.core.patient.vo.PatientRefVo(new Integer(bean.getPriorPatient().getId()), bean.getPriorPatient().getVersion()); this.mergehistory = bean.getMergeHistory() == null ? null : new ims.core.patient.vo.PatientMergeHistoryRefVo(new Integer(bean.getMergeHistory().getId()), bean.getMergeHistory().getVersion()); } public ims.vo.ValueObjectBean getBean() { return this.getBean(new ims.vo.ValueObjectBeanMap()); } public ims.vo.ValueObjectBean getBean(ims.vo.ValueObjectBeanMap map) { ims.ocs_if.vo.beans.DemographicsMessageQueueVoBean bean = null; if(map != null) bean = (ims.ocs_if.vo.beans.DemographicsMessageQueueVoBean)map.getValueObjectBean(this); if (bean == null) { bean = new ims.ocs_if.vo.beans.DemographicsMessageQueueVoBean(); map.addValueObjectBean(this, bean); bean.populate(map, this); } return bean; } public Object getFieldValueByFieldName(String fieldName) { if(fieldName == null) throw new ims.framework.exceptions.CodingRuntimeException("Invalid field name"); fieldName = fieldName.toUpperCase(); if(fieldName.equals("PATIENT")) return getPatient(); if(fieldName.equals("PROVIDERSYSTEM")) return getProviderSystem(); if(fieldName.equals("WASPROCESSED")) return getWasProcessed(); if(fieldName.equals("WASDISCARDED")) return getWasDiscarded(); if(fieldName.equals("MSGTEXT")) return getMsgText(); if(fieldName.equals("ACKTEXT")) return getAckText(); if(fieldName.equals("FAILUREMSG")) return getFailureMsg(); if(fieldName.equals("MESSAGESTATUS")) return getMessageStatus(); if(fieldName.equals("MSGTYPE")) return getMsgType(); if(fieldName.equals("QUEUETYPE")) return getQueueType(); if(fieldName.equals("PRIORPATIENT")) return getPriorPatient(); if(fieldName.equals("MERGEHISTORY")) return getMergeHistory(); return super.getFieldValueByFieldName(fieldName); } public boolean getPatientIsNotNull() { return this.patient != null; } public ims.core.patient.vo.PatientRefVo getPatient() { return this.patient; } public void setPatient(ims.core.patient.vo.PatientRefVo value) { this.isValidated = false; this.patient = value; } public boolean getProviderSystemIsNotNull() { return this.providersystem != null; } public ims.core.admin.vo.ProviderSystemRefVo getProviderSystem() { return this.providersystem; } public void setProviderSystem(ims.core.admin.vo.ProviderSystemRefVo value) { this.isValidated = false; this.providersystem = value; } public boolean getWasProcessedIsNotNull() { return this.wasprocessed != null; } public Boolean getWasProcessed() { return this.wasprocessed; } public void setWasProcessed(Boolean value) { this.isValidated = false; this.wasprocessed = value; } public boolean getWasDiscardedIsNotNull() { return this.wasdiscarded != null; } public Boolean getWasDiscarded() { return this.wasdiscarded; } public void setWasDiscarded(Boolean value) { this.isValidated = false; this.wasdiscarded = value; } public boolean getMsgTextIsNotNull() { return this.msgtext != null; } public String getMsgText() { return this.msgtext; } public static int getMsgTextMaxLength() { return 4000; } public void setMsgText(String value) { this.isValidated = false; this.msgtext = value; } public boolean getAckTextIsNotNull() { return this.acktext != null; } public String getAckText() { return this.acktext; } public static int getAckTextMaxLength() { return 1000; } public void setAckText(String value) { this.isValidated = false; this.acktext = value; } public boolean getFailureMsgIsNotNull() { return this.failuremsg != null; } public String getFailureMsg() { return this.failuremsg; } public static int getFailureMsgMaxLength() { return 1000; } public void setFailureMsg(String value) { this.isValidated = false; this.failuremsg = value; } public boolean getMessageStatusIsNotNull() { return this.messagestatus != null; } public ims.ocrr.vo.lookups.OrderMessageStatus getMessageStatus() { return this.messagestatus; } public void setMessageStatus(ims.ocrr.vo.lookups.OrderMessageStatus value) { this.isValidated = false; this.messagestatus = value; } public boolean getMsgTypeIsNotNull() { return this.msgtype != null; } public ims.core.vo.lookups.MsgEventType getMsgType() { return this.msgtype; } public void setMsgType(ims.core.vo.lookups.MsgEventType value) { this.isValidated = false; this.msgtype = value; } public boolean getQueueTypeIsNotNull() { return this.queuetype != null; } public ims.core.vo.lookups.QueueType getQueueType() { return this.queuetype; } public void setQueueType(ims.core.vo.lookups.QueueType value) { this.isValidated = false; this.queuetype = value; } public boolean getPriorPatientIsNotNull() { return this.priorpatient != null; } public ims.core.patient.vo.PatientRefVo getPriorPatient() { return this.priorpatient; } public void setPriorPatient(ims.core.patient.vo.PatientRefVo value) { this.isValidated = false; this.priorpatient = value; } public boolean getMergeHistoryIsNotNull() { return this.mergehistory != null; } public ims.core.patient.vo.PatientMergeHistoryRefVo getMergeHistory() { return this.mergehistory; } public void setMergeHistory(ims.core.patient.vo.PatientMergeHistoryRefVo value) { this.isValidated = false; this.mergehistory = value; } public boolean isValidated() { if(this.isBusy) return true; this.isBusy = true; if(!this.isValidated) { this.isBusy = false; return false; } this.isBusy = false; return true; } public String[] validate() { return validate(null); } public String[] validate(String[] existingErrors) { if(this.isBusy) return null; this.isBusy = true; java.util.ArrayList<String> listOfErrors = new java.util.ArrayList<String>(); if(existingErrors != null) { for(int x = 0; x < existingErrors.length; x++) { listOfErrors.add(existingErrors[x]); } } if(this.patient == null) listOfErrors.add("Patient is mandatory"); if(this.acktext != null) if(this.acktext.length() > 1000) listOfErrors.add("The length of the field [acktext] in the value object [ims.ocs_if.vo.DemographicsMessageQueueVo] is too big. It should be less or equal to 1000"); if(this.failuremsg != null) if(this.failuremsg.length() > 1000) listOfErrors.add("The length of the field [failuremsg] in the value object [ims.ocs_if.vo.DemographicsMessageQueueVo] is too big. It should be less or equal to 1000"); if(this.msgtype == null) listOfErrors.add("msgType is mandatory"); int errorCount = listOfErrors.size(); if(errorCount == 0) { this.isBusy = false; this.isValidated = true; return null; } String[] result = new String[errorCount]; for(int x = 0; x < errorCount; x++) result[x] = (String)listOfErrors.get(x); this.isBusy = false; this.isValidated = false; return result; } public void clearIDAndVersion() { this.id = null; this.version = 0; } public Object clone() { if(this.isBusy) return this; this.isBusy = true; DemographicsMessageQueueVo clone = new DemographicsMessageQueueVo(this.id, this.version); clone.patient = this.patient; clone.providersystem = this.providersystem; clone.wasprocessed = this.wasprocessed; clone.wasdiscarded = this.wasdiscarded; clone.msgtext = this.msgtext; clone.acktext = this.acktext; clone.failuremsg = this.failuremsg; if(this.messagestatus == null) clone.messagestatus = null; else clone.messagestatus = (ims.ocrr.vo.lookups.OrderMessageStatus)this.messagestatus.clone(); if(this.msgtype == null) clone.msgtype = null; else clone.msgtype = (ims.core.vo.lookups.MsgEventType)this.msgtype.clone(); if(this.queuetype == null) clone.queuetype = null; else clone.queuetype = (ims.core.vo.lookups.QueueType)this.queuetype.clone(); clone.priorpatient = this.priorpatient; clone.mergehistory = this.mergehistory; clone.isValidated = this.isValidated; this.isBusy = false; return clone; } public int compareTo(Object obj) { return compareTo(obj, true); } public int compareTo(Object obj, boolean caseInsensitive) { if (obj == null) { return -1; } if(caseInsensitive); // this is to avoid eclipse warning only. if (!(DemographicsMessageQueueVo.class.isAssignableFrom(obj.getClass()))) { throw new ClassCastException("A DemographicsMessageQueueVo object cannot be compared an Object of type " + obj.getClass().getName()); } if (this.id == null) return 1; if (((DemographicsMessageQueueVo)obj).getBoId() == null) return -1; return this.id.compareTo(((DemographicsMessageQueueVo)obj).getBoId()); } public synchronized static int generateValueObjectUniqueID() { return ims.vo.ValueObject.generateUniqueID(); } public int countFieldsWithValue() { int count = 0; if(this.patient != null) count++; if(this.providersystem != null) count++; if(this.wasprocessed != null) count++; if(this.wasdiscarded != null) count++; if(this.msgtext != null) count++; if(this.acktext != null) count++; if(this.failuremsg != null) count++; if(this.messagestatus != null) count++; if(this.msgtype != null) count++; if(this.queuetype != null) count++; if(this.priorpatient != null) count++; if(this.mergehistory != null) count++; return count; } public int countValueObjectFields() { return 12; } protected ims.core.patient.vo.PatientRefVo patient; protected ims.core.admin.vo.ProviderSystemRefVo providersystem; protected Boolean wasprocessed; protected Boolean wasdiscarded; protected String msgtext; protected String acktext; protected String failuremsg; protected ims.ocrr.vo.lookups.OrderMessageStatus messagestatus; protected ims.core.vo.lookups.MsgEventType msgtype; protected ims.core.vo.lookups.QueueType queuetype; protected ims.core.patient.vo.PatientRefVo priorpatient; protected ims.core.patient.vo.PatientMergeHistoryRefVo mergehistory; private boolean isValidated = false; private boolean isBusy = false; }
open-health-hub/openmaxims-linux
openmaxims_workspace/ValueObjects/src/ims/ocs_if/vo/DemographicsMessageQueueVo.java
Java
agpl-3.0
15,375
<table class="catalogue_table"> <thead class="workflow"> <tr><th colspan=4><?php echo __("Latest Statuses") ; ?> :</th></tr> <tr> <th><?php echo __('Date');?></th> <th><?php echo __('Status');?></th> <th><?php echo __('Comments');?></th> <th><?php echo __('By');?></th> </tr> </thead> <tbody> <?php foreach($loanstatus as $info) : ?> <tr> <td><?php $date = new DateTime($info->getModificationDateTime()); echo $date->format('d/m/Y H:i:s'); ?></td> <td><?php echo $info->getFormattedStatus();?></td> <td><?php echo $info->getComment();?></td> <td><?php echo $info->Users->__toString() ;?></td> </tr> <?php endforeach ; ?> <?php if ($loanstatus->count() == 5 ) : ?> <tr> <td colspan="3">&nbsp;</td> <td> <a class="link_catalogue" information="true" title="<?php echo __('view all workflows');?>" href="<?php echo url_for('loan/viewAll?table='.$table.'&id='.$eid); ?>"> <?php echo __('History');?></a> </td> </tr> <?php endif ; ?> </tbody> </table>
naturalsciences/Darwin
apps/backend/modules/loanwidgetview/templates/_loanStatus.php
PHP
agpl-3.0
1,100
#include <iostream> #include <boost/algorithm/string.hpp> #include <bitcoin/bitcoin.hpp> #include <wallet/wallet.hpp> using namespace bc; using namespace libwallet; int display_help() { puts("Usage:"); puts(""); puts(" mnemonic <<< \"[WORD1] [WORD2] ...\""); puts(" mnemonic <<< SEED"); puts(""); puts("Please email suggestions and questions to <genjix@riseup.net>."); return -1; } int main(int argc, char** argv) { std::istreambuf_iterator<char> it(std::cin); std::istreambuf_iterator<char> end; std::string data(it, end); boost::algorithm::trim(data); string_list words; boost::split(words, data, boost::is_any_of("\n\t ")); if (words.empty()) return display_help(); else if (words.size() == 1 && words[0].size() == libwallet::deterministic_wallet::seed_size) { const std::string seed = words[0]; string_list words = encode_mnemonic(seed); bool first = true; for (const std::string& word: words) { if (!first) std::cout << " "; std::cout << word; first = false; } std::cout << std::endl; return 0; } else { std::cout << decode_mnemonic(words) << std::endl; return 0; } // Should never happen! return 0; }
kaostao/sx
src/mnemonic.cpp
C++
agpl-3.0
1,349
package javax.media.pim; import java.util.HashMap; import java.util.Iterator; import java.util.Vector; import java.util.logging.Level; import java.util.logging.Logger; import javax.media.Codec; import javax.media.Demultiplexer; import javax.media.Effect; import javax.media.Format; import javax.media.Multiplexer; import javax.media.Renderer; import net.sf.fmj.media.RegistryDefaults; import net.sf.fmj.utility.Registry; import net.sf.fmj.utility.LoggerSingleton; /** * In progress. * @author Ken Larson * */ public class PlugInManager extends javax.media.PlugInManager { private static final Logger logger = LoggerSingleton.logger; private static boolean TRACE = false; // TODO: what exactly is stored in the properties? just the class names, or the formats as well? // the properties files appears to be binary, an appears to be created using java serialization. // seems like it contains the formats. // TODO: implement efficiently using maps /** * Vectors of classname Strings. This is sorted in the order that plugins must be searched. */ private static final Vector[] classLists = new Vector[] { new Vector(), new Vector(), new Vector(), new Vector(), new Vector() }; /** * Maps of classnames to PluginInfo */ private static final HashMap[] pluginMaps = new HashMap[] { new HashMap(), new HashMap(), new HashMap(), new HashMap(), new HashMap(), }; /** * The registry that persists the data. */ private static Registry registry = Registry.getInstance(); static { try { if (TRACE) logger.info("initializing..."); // populate vectors with info from the persisted registry for (int i=0; i<5; i++) { Vector classList = classLists[i]; HashMap pluginMap = pluginMaps[i]; Iterator pluginIter = registry.getPluginList(i+1).iterator(); while (pluginIter.hasNext()) { // PlugInInfo info = (PlugInInfo) pluginIter.next(); // classList.add(info.className); // pluginMap.put(info.className, info); // registry only contains classnames, not in and out formats String classname = (String) pluginIter.next(); classList.add(classname); PlugInInfo info = getPluginInfo(classname); if (info != null) { pluginMap.put(info.className, info); } } } boolean jmfDefaults = false; try { jmfDefaults = System.getProperty("net.sf.fmj.utility.JmfRegistry.JMFDefaults", "false").equals("true"); } catch (SecurityException e) { // we must be an applet. } final int flags = jmfDefaults ? RegistryDefaults.JMF : RegistryDefaults.ALL; RegistryDefaults.registerPlugins(flags); } catch (Throwable t) { logger.log(Level.SEVERE, "Unable to initialize javax.media.pim.PlugInManager (static): " + t, t); throw new RuntimeException(t); } } /** * Private constructor so that is can not be constructed. * In JMF it is public, but this is an implementation detail that is * not important for FMJ compatibility. */ private PlugInManager() { } /** * Get a list of plugins that match the given input and output formats. * * @param input * @param output * @param type * @return A Vector of classnames */ public static synchronized Vector<String> getPlugInList(Format input, Format output, int type) { if (TRACE) logger.info("getting plugin list..."); if (!isValid(type)) { return new Vector<String>(); } final Vector<String> result = new Vector<String>(); final Vector<String> classList = getVector(type); final HashMap pluginMap = pluginMaps[type-1]; for (int i = 0; i < classList.size(); ++i) { final Object classname = classList.get(i); final PlugInInfo plugInInfo = (PlugInInfo) pluginMap.get(classname); if (plugInInfo == null) continue; if (input != null) { if (plugInInfo.inputFormats == null) { continue; } boolean match = false; for (int j = 0; j < plugInInfo.inputFormats.length; ++j) { if (input.matches(plugInInfo.inputFormats[j])) { match = true; break; } } if (!match) { continue; } } if (output != null) { if (plugInInfo.outputFormats == null) { continue; } boolean match = false; for (int j = 0; j < plugInInfo.outputFormats.length; ++j) { if (output.matches(plugInInfo.outputFormats[j])) { match = true; break; } } if (!match) { continue; } } // matched both input and output formats result.add(plugInInfo.className); } return result; } /** * according to the docs, sets the search order. does not appear to add new plugins. * * @param plugins * @param type */ public static synchronized void setPlugInList(Vector plugins, int type) { // the vector to affect Vector vector = classLists[type - 1]; // The following code does not appear to be consistent with JMF. More testing needed: // if ( vector.size() != plugins.size() || !vector.containsAll(plugins) ) { // // extra or missing classname(s) given // logger.warning("setPlugInList: extra or missing classname(s) given"); // return; // } // reorder vector vector.clear(); vector.addAll(plugins); registry.setPluginList(type, plugins); } public static synchronized void commit() throws java.io.IOException { registry.commit(); } public static synchronized boolean addPlugIn(String classname, Format[] in, Format[] out, int type) { try { Class.forName(classname); } catch (ClassNotFoundException e) { logger.finer("addPlugIn failed for nonexistant class: " + classname); return false; // class does not exist. } catch (Throwable t) { logger.log(Level.WARNING, "Unable to addPlugIn for " + classname + " due to inability to get its class: " + t, t); return false; } if (find(classname, type) != null) { return false; // already there. } final PlugInInfo plugInInfo = new PlugInInfo(classname, in, out); Vector classList = classLists[type - 1]; HashMap pluginMap = pluginMaps[type-1]; // add to end of ordered list classList.add(classname); // add to PluginInfo map pluginMap.put(classname, plugInInfo); registry.setPluginList(type, classList); return true; } public static synchronized boolean removePlugIn(String classname, int type) { Vector classList = classLists[type-1]; HashMap pluginMap = pluginMaps[type-1]; boolean result = classList.remove(classname) || (pluginMap.remove(classname) != null); registry.setPluginList(type, classList); return result; } public static synchronized Format[] getSupportedInputFormats(String className, int type) { final PlugInInfo pi = find(className, type); if (pi == null) { return null; } return pi.inputFormats; } public static synchronized Format[] getSupportedOutputFormats(String className, int type) { final PlugInInfo pi = find(className, type); if (pi == null) return null; return pi.outputFormats; } private static boolean isValid(int type) { return type >= 1 && type <= 5; } private static Vector<String> getVector(int type) { if (!isValid(type)) { return null; } return (Vector<String>) classLists[type - 1]; } private static synchronized PlugInInfo find(String classname, int type) { PlugInInfo info = (PlugInInfo) pluginMaps[type-1].get(classname); return info; } private static final PlugInInfo getPluginInfo(String pluginName) { Object pluginObject; try { Class cls = Class.forName(pluginName); pluginObject = cls.newInstance(); } catch (ClassNotFoundException e) { logger.warning("Problem loading plugin " + pluginName + ": " + e.getMessage()); return null; } catch (InstantiationException e) { logger.warning("Problem loading plugin " + pluginName + ": " + e.getMessage()); return null; } catch (IllegalAccessException e) { logger.warning("Problem loading plugin " + pluginName + ": " + e.getMessage()); return null; } Format[] in = null; Format[] out = null; if (pluginObject instanceof Demultiplexer) { Demultiplexer demux = (Demultiplexer) pluginObject; in = demux.getSupportedInputContentDescriptors(); } else if (pluginObject instanceof Codec) { Codec codec = (Codec) pluginObject; in = codec.getSupportedInputFormats(); out = codec.getSupportedOutputFormats(null); } else if (pluginObject instanceof Multiplexer) { Multiplexer mux = (Multiplexer) pluginObject; in = mux.getSupportedInputFormats(); out = mux.getSupportedOutputContentDescriptors(null); } else if (pluginObject instanceof Renderer) { Renderer renderer = (Renderer) pluginObject; in = renderer.getSupportedInputFormats(); out = null; } else if (pluginObject instanceof Effect) { Effect effect = (Effect) pluginObject; in = effect.getSupportedInputFormats(); out = effect.getSupportedOutputFormats(null); } return new PlugInInfo(pluginName, in, out); } }
AlienQueen/alienlabs-skeleton-for-wicket-spring-hibernate
lib/fmj/src/javax/media/pim/PlugInManager.java
Java
agpl-3.0
8,977
/* * Spreed WebRTC. * Copyright (C) 2013-2015 struktur AG * * This file is part of Spreed WebRTC. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * */ package main import ( "log" "sort" "sync" ) type User struct { Id string sessionTable map[string]*Session mutex sync.RWMutex } func NewUser(id string) *User { user := &User{ Id: id, sessionTable: make(map[string]*Session), } return user } // AddSession adds a session to the session table and returns true if // s is the first session. func (u *User) AddSession(s *Session) bool { first := false u.mutex.Lock() u.sessionTable[s.Id] = s if len(u.sessionTable) == 1 { log.Println("First session registered for user", u.Id) first = true } u.mutex.Unlock() return first } // RemoveSession removes a session from the session table abd returns // true if no session is left left. func (u *User) RemoveSession(sessionID string) bool { last := false u.mutex.Lock() delete(u.sessionTable, sessionID) if len(u.sessionTable) == 0 { log.Println("Last session unregistered for user", u.Id) last = true } u.mutex.Unlock() return last } func (u *User) Data() *DataUser { u.mutex.RLock() defer u.mutex.RUnlock() return &DataUser{ Id: u.Id, Sessions: len(u.sessionTable), } } func (u *User) SubscribeSessions(from *Session) []*DataSession { sessions := make([]*DataSession, 0, len(u.sessionTable)) u.mutex.RLock() defer u.mutex.RUnlock() for _, session := range u.sessionTable { // TODO(longsleep): This does lots of locks - check if these can be streamlined. from.Subscribe(session) sessions = append(sessions, session.Data()) } sort.Sort(ByPrioAndStamp(sessions)) return sessions } type ByPrioAndStamp []*DataSession func (a ByPrioAndStamp) Len() int { return len(a) } func (a ByPrioAndStamp) Swap(i, j int) { a[i], a[j] = a[j], a[i] } func (a ByPrioAndStamp) Less(i, j int) bool { if a[i].Prio < a[j].Prio { return true } if a[i].Prio == a[j].Prio { return a[i].stamp < a[j].stamp } return false }
shelsonjava/spreed-webrtc
src/app/spreed-webrtc-server/user.go
GO
agpl-3.0
2,679
//############################################################################# //# # //# Copyright (C) <2015> <IMS MAXIMS> # //# # //# This program is free software: you can redistribute it and/or modify # //# it under the terms of the GNU Affero General Public License as # //# published by the Free Software Foundation, either version 3 of the # //# License, or (at your option) any later version. # //# # //# This program is distributed in the hope that it will be useful, # //# but WITHOUT ANY WARRANTY; without even the implied warranty of # //# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # //# GNU Affero General Public License for more details. # //# # //# You should have received a copy of the GNU Affero General Public License # //# along with this program. If not, see <http://www.gnu.org/licenses/>. # //# # //# IMS MAXIMS provides absolutely NO GUARANTEE OF THE CLINICAL SAFTEY of # //# this program. Users of this software do so entirely at their own risk. # //# IMS MAXIMS only ensures the Clinical Safety of unaltered run-time # //# software that it builds, deploys and maintains. # //# # //############################################################################# //#EOH // This code was generated by Barbara Worwood using IMS Development Environment (version 1.80 build 5589.25814) // Copyright (C) 1995-2015 IMS MAXIMS. All rights reserved. // WARNING: DO NOT MODIFY the content of this file package ims.oncology.vo.beans; public class CancerCarePlanVoBean extends ims.vo.ValueObjectBean { public CancerCarePlanVoBean() { } public CancerCarePlanVoBean(ims.oncology.vo.CancerCarePlanVo vo) { this.id = vo.getBoId(); this.version = vo.getBoVersion(); this.clinicalcontact = vo.getClinicalContact() == null ? null : (ims.core.vo.beans.ClinicalContactShortVoBean)vo.getClinicalContact().getBean(); this.carecontext = vo.getCareContext() == null ? null : (ims.core.vo.beans.CareContextShortVoBean)vo.getCareContext().getBean(); this.careplandate = vo.getCarePlanDate() == null ? null : (ims.framework.utils.beans.DateBean)vo.getCarePlanDate().getBean(); this.consultantincharge = vo.getConsultantInCharge() == null ? null : (ims.core.vo.beans.HcpLiteVoBean)vo.getConsultantInCharge().getBean(); this.careplanintent = vo.getCarePlanIntent() == null ? null : (ims.vo.LookupInstanceBean)vo.getCarePlanIntent().getBean(); this.recurrenceindicator = vo.getRecurrenceIndicator() == null ? null : (ims.vo.LookupInstanceBean)vo.getRecurrenceIndicator().getBean(); this.iscurrent = vo.getIsCurrent(); this.mdtmeeting = vo.getMdtMeeting() == null ? null : (ims.oncology.vo.beans.CancerMDTMeetingVoBean)vo.getMdtMeeting().getBean(); this.episodeofcare = vo.getEpisodeOfCare() == null ? null : new ims.vo.RefVoBean(vo.getEpisodeOfCare().getBoId(), vo.getEpisodeOfCare().getBoVersion()); this.careplannotes = vo.getCarePlanNotes(); this.treatmentmodalities = vo.getTreatmentModalities() == null ? null : vo.getTreatmentModalities().getBeanCollection(); this.currentstatus = vo.getCurrentStatus() == null ? null : (ims.vo.LookupInstanceBean)vo.getCurrentStatus().getBean(); this.agreeddate = vo.getAgreedDate() == null ? null : (ims.framework.utils.beans.DateBean)vo.getAgreedDate().getBean(); this.reasonpatientplandiffmdt = vo.getReasonPatientPlanDiffMDT(); this.noanticancertxreason = vo.getNoAntiCancerTxReason() == null ? null : vo.getNoAntiCancerTxReason().getBeanCollection(); this.hasassociatedmdtmeeting = vo.getHasAssociatedMDTMeeting(); this.reasonforrevision = vo.getReasonForRevision(); } public void populate(ims.vo.ValueObjectBeanMap map, ims.oncology.vo.CancerCarePlanVo vo) { this.id = vo.getBoId(); this.version = vo.getBoVersion(); this.clinicalcontact = vo.getClinicalContact() == null ? null : (ims.core.vo.beans.ClinicalContactShortVoBean)vo.getClinicalContact().getBean(map); this.carecontext = vo.getCareContext() == null ? null : (ims.core.vo.beans.CareContextShortVoBean)vo.getCareContext().getBean(map); this.careplandate = vo.getCarePlanDate() == null ? null : (ims.framework.utils.beans.DateBean)vo.getCarePlanDate().getBean(); this.consultantincharge = vo.getConsultantInCharge() == null ? null : (ims.core.vo.beans.HcpLiteVoBean)vo.getConsultantInCharge().getBean(map); this.careplanintent = vo.getCarePlanIntent() == null ? null : (ims.vo.LookupInstanceBean)vo.getCarePlanIntent().getBean(); this.recurrenceindicator = vo.getRecurrenceIndicator() == null ? null : (ims.vo.LookupInstanceBean)vo.getRecurrenceIndicator().getBean(); this.iscurrent = vo.getIsCurrent(); this.mdtmeeting = vo.getMdtMeeting() == null ? null : (ims.oncology.vo.beans.CancerMDTMeetingVoBean)vo.getMdtMeeting().getBean(map); this.episodeofcare = vo.getEpisodeOfCare() == null ? null : new ims.vo.RefVoBean(vo.getEpisodeOfCare().getBoId(), vo.getEpisodeOfCare().getBoVersion()); this.careplannotes = vo.getCarePlanNotes(); this.treatmentmodalities = vo.getTreatmentModalities() == null ? null : vo.getTreatmentModalities().getBeanCollection(); this.currentstatus = vo.getCurrentStatus() == null ? null : (ims.vo.LookupInstanceBean)vo.getCurrentStatus().getBean(); this.agreeddate = vo.getAgreedDate() == null ? null : (ims.framework.utils.beans.DateBean)vo.getAgreedDate().getBean(); this.reasonpatientplandiffmdt = vo.getReasonPatientPlanDiffMDT(); this.noanticancertxreason = vo.getNoAntiCancerTxReason() == null ? null : vo.getNoAntiCancerTxReason().getBeanCollection(); this.hasassociatedmdtmeeting = vo.getHasAssociatedMDTMeeting(); this.reasonforrevision = vo.getReasonForRevision(); } public ims.oncology.vo.CancerCarePlanVo buildVo() { return this.buildVo(new ims.vo.ValueObjectBeanMap()); } public ims.oncology.vo.CancerCarePlanVo buildVo(ims.vo.ValueObjectBeanMap map) { ims.oncology.vo.CancerCarePlanVo vo = null; if(map != null) vo = (ims.oncology.vo.CancerCarePlanVo)map.getValueObject(this); if(vo == null) { vo = new ims.oncology.vo.CancerCarePlanVo(); map.addValueObject(this, vo); vo.populate(map, this); } return vo; } public Integer getId() { return this.id; } public void setId(Integer value) { this.id = value; } public int getVersion() { return this.version; } public void setVersion(int value) { this.version = value; } public ims.core.vo.beans.ClinicalContactShortVoBean getClinicalContact() { return this.clinicalcontact; } public void setClinicalContact(ims.core.vo.beans.ClinicalContactShortVoBean value) { this.clinicalcontact = value; } public ims.core.vo.beans.CareContextShortVoBean getCareContext() { return this.carecontext; } public void setCareContext(ims.core.vo.beans.CareContextShortVoBean value) { this.carecontext = value; } public ims.framework.utils.beans.DateBean getCarePlanDate() { return this.careplandate; } public void setCarePlanDate(ims.framework.utils.beans.DateBean value) { this.careplandate = value; } public ims.core.vo.beans.HcpLiteVoBean getConsultantInCharge() { return this.consultantincharge; } public void setConsultantInCharge(ims.core.vo.beans.HcpLiteVoBean value) { this.consultantincharge = value; } public ims.vo.LookupInstanceBean getCarePlanIntent() { return this.careplanintent; } public void setCarePlanIntent(ims.vo.LookupInstanceBean value) { this.careplanintent = value; } public ims.vo.LookupInstanceBean getRecurrenceIndicator() { return this.recurrenceindicator; } public void setRecurrenceIndicator(ims.vo.LookupInstanceBean value) { this.recurrenceindicator = value; } public Boolean getIsCurrent() { return this.iscurrent; } public void setIsCurrent(Boolean value) { this.iscurrent = value; } public ims.oncology.vo.beans.CancerMDTMeetingVoBean getMdtMeeting() { return this.mdtmeeting; } public void setMdtMeeting(ims.oncology.vo.beans.CancerMDTMeetingVoBean value) { this.mdtmeeting = value; } public ims.vo.RefVoBean getEpisodeOfCare() { return this.episodeofcare; } public void setEpisodeOfCare(ims.vo.RefVoBean value) { this.episodeofcare = value; } public String getCarePlanNotes() { return this.careplannotes; } public void setCarePlanNotes(String value) { this.careplannotes = value; } public ims.oncology.vo.beans.TreatmentModalitiesVoBean[] getTreatmentModalities() { return this.treatmentmodalities; } public void setTreatmentModalities(ims.oncology.vo.beans.TreatmentModalitiesVoBean[] value) { this.treatmentmodalities = value; } public ims.vo.LookupInstanceBean getCurrentStatus() { return this.currentstatus; } public void setCurrentStatus(ims.vo.LookupInstanceBean value) { this.currentstatus = value; } public ims.framework.utils.beans.DateBean getAgreedDate() { return this.agreeddate; } public void setAgreedDate(ims.framework.utils.beans.DateBean value) { this.agreeddate = value; } public String getReasonPatientPlanDiffMDT() { return this.reasonpatientplandiffmdt; } public void setReasonPatientPlanDiffMDT(String value) { this.reasonpatientplandiffmdt = value; } public java.util.Collection getNoAntiCancerTxReason() { return this.noanticancertxreason; } public void setNoAntiCancerTxReason(java.util.Collection value) { this.noanticancertxreason = value; } public void addNoAntiCancerTxReason(java.util.Collection value) { if(this.noanticancertxreason == null) this.noanticancertxreason = new java.util.ArrayList(); this.noanticancertxreason.add(value); } public Boolean getHasAssociatedMDTMeeting() { return this.hasassociatedmdtmeeting; } public void setHasAssociatedMDTMeeting(Boolean value) { this.hasassociatedmdtmeeting = value; } public String getReasonForRevision() { return this.reasonforrevision; } public void setReasonForRevision(String value) { this.reasonforrevision = value; } private Integer id; private int version; private ims.core.vo.beans.ClinicalContactShortVoBean clinicalcontact; private ims.core.vo.beans.CareContextShortVoBean carecontext; private ims.framework.utils.beans.DateBean careplandate; private ims.core.vo.beans.HcpLiteVoBean consultantincharge; private ims.vo.LookupInstanceBean careplanintent; private ims.vo.LookupInstanceBean recurrenceindicator; private Boolean iscurrent; private ims.oncology.vo.beans.CancerMDTMeetingVoBean mdtmeeting; private ims.vo.RefVoBean episodeofcare; private String careplannotes; private ims.oncology.vo.beans.TreatmentModalitiesVoBean[] treatmentmodalities; private ims.vo.LookupInstanceBean currentstatus; private ims.framework.utils.beans.DateBean agreeddate; private String reasonpatientplandiffmdt; private java.util.Collection noanticancertxreason; private Boolean hasassociatedmdtmeeting; private String reasonforrevision; }
FreudianNM/openMAXIMS
Source Library/openmaxims_workspace/ValueObjects/src/ims/oncology/vo/beans/CancerCarePlanVoBean.java
Java
agpl-3.0
11,691
/* * This file is part of Bisq. * * Bisq is free software: you can redistribute it and/or modify it * under the terms of the GNU Affero General Public License as published by * the Free Software Foundation, either version 3 of the License, or (at * your option) any later version. * * Bisq is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public * License for more details. * * You should have received a copy of the GNU Affero General Public License * along with Bisq. If not, see <http://www.gnu.org/licenses/>. */ package io.bisq.common.proto.network; import io.bisq.common.proto.ProtoResolver; import io.bisq.generated.protobuffer.PB; public interface NetworkProtoResolver extends ProtoResolver { NetworkEnvelope fromProto(PB.NetworkEnvelope proto); NetworkPayload fromProto(PB.StoragePayload proto); NetworkPayload fromProto(PB.StorageEntryWrapper proto); }
ManfredKarrer/exchange
common/src/main/java/io/bisq/common/proto/network/NetworkProtoResolver.java
Java
agpl-3.0
1,044